diff --git a/.idea/.gitignore b/.idea/.gitignore
new file mode 100644
index 0000000..26d3352
--- /dev/null
+++ b/.idea/.gitignore
@@ -0,0 +1,3 @@
+# Default ignored files
+/shelf/
+/workspace.xml
diff --git a/.idea/AndroidProjectSystem.xml b/.idea/AndroidProjectSystem.xml
new file mode 100644
index 0000000..4a53bee
--- /dev/null
+++ b/.idea/AndroidProjectSystem.xml
@@ -0,0 +1,6 @@
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/caches/deviceStreaming.xml b/.idea/caches/deviceStreaming.xml
new file mode 100644
index 0000000..871d8b9
--- /dev/null
+++ b/.idea/caches/deviceStreaming.xml
@@ -0,0 +1,873 @@
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/compiler.xml b/.idea/compiler.xml
new file mode 100644
index 0000000..b86273d
--- /dev/null
+++ b/.idea/compiler.xml
@@ -0,0 +1,6 @@
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/deploymentTargetSelector.xml b/.idea/deploymentTargetSelector.xml
new file mode 100644
index 0000000..98c5dc0
--- /dev/null
+++ b/.idea/deploymentTargetSelector.xml
@@ -0,0 +1,18 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/deviceManager.xml b/.idea/deviceManager.xml
new file mode 100644
index 0000000..91f9558
--- /dev/null
+++ b/.idea/deviceManager.xml
@@ -0,0 +1,13 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/gradle.xml b/.idea/gradle.xml
new file mode 100644
index 0000000..0ee14b5
--- /dev/null
+++ b/.idea/gradle.xml
@@ -0,0 +1,21 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/migrations.xml b/.idea/migrations.xml
new file mode 100644
index 0000000..f8051a6
--- /dev/null
+++ b/.idea/migrations.xml
@@ -0,0 +1,10 @@
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/misc.xml b/.idea/misc.xml
new file mode 100644
index 0000000..74dd639
--- /dev/null
+++ b/.idea/misc.xml
@@ -0,0 +1,10 @@
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/runConfigurations.xml b/.idea/runConfigurations.xml
new file mode 100644
index 0000000..16660f1
--- /dev/null
+++ b/.idea/runConfigurations.xml
@@ -0,0 +1,17 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/vcs.xml b/.idea/vcs.xml
new file mode 100644
index 0000000..35eb1dd
--- /dev/null
+++ b/.idea/vcs.xml
@@ -0,0 +1,6 @@
+
+
+
+
+
+
\ No newline at end of file
diff --git a/CS710S-Java-ENTIRE-CONTEXT.txt b/CS710S-Java-ENTIRE-CONTEXT.txt
new file mode 100644
index 0000000..0e833ad
--- /dev/null
+++ b/CS710S-Java-ENTIRE-CONTEXT.txt
@@ -0,0 +1,66263 @@
+This file is a merged representation of the entire codebase, combining all repository files into a single document.
+Generated by Repomix on: 2025-10-03T22:28:08.666Z
+
+
+This section contains a summary of this file.
+
+
+This file contains a packed representation of the entire repository's contents.
+It is designed to be easily consumable by AI systems for analysis, code review,
+or other automated processes.
+
+
+
+The content is organized as follows:
+1. This summary section
+2. Repository information
+3. Repository structure
+4. Repository files, each consisting of:
+ - File path as an attribute
+ - Full contents of the file
+
+
+
+- This file should be treated as read-only. Any changes should be made to the
+ original repository files, not this packed version.
+- When processing this file, use the file path to distinguish
+ between different files in the repository.
+- Be aware that this file may contain sensitive information. Handle it with
+ the same level of security as you would the original repository.
+- Pay special attention to the Repository Description. These contain important context and guidelines specific to this project.
+- Pay special attention to the Repository Instruction. These contain important context and guidelines specific to this project.
+
+
+
+- Some files may have been excluded based on .gitignore rules and Repomix's
+ configuration.
+- Binary files are not included in this packed representation. Please refer to
+ the Repository Structure section for a complete list of file paths, including
+ binary files.
+
+
+
+
+Packed CS710S Android codebase for AI analysis of BLE/RFID flows, including Java source, projects, and docs.
+
+
+For more information about Repomix, visit: https://github.com/yamadashy/repomix
+
+
+
+
+
+app/src/main/AndroidManifest.xml
+app/src/main/java/com/csl/cs710ademoapp/AccessTask.java
+app/src/main/java/com/csl/cs710ademoapp/AccessTask1.java
+app/src/main/java/com/csl/cs710ademoapp/adapters/DrawerListAdapter.java
+app/src/main/java/com/csl/cs710ademoapp/adapters/ReaderListAdapter.java
+app/src/main/java/com/csl/cs710ademoapp/CustomAlertDialog.java
+app/src/main/java/com/csl/cs710ademoapp/CustomIME.java
+app/src/main/java/com/csl/cs710ademoapp/CustomMediaPlayer.java
+app/src/main/java/com/csl/cs710ademoapp/CustomPopupWindow.java
+app/src/main/java/com/csl/cs710ademoapp/CustomProgressDialog.java
+app/src/main/java/com/csl/cs710ademoapp/DrawerListContent.java
+app/src/main/java/com/csl/cs710ademoapp/fragments/AboutFragment.java
+app/src/main/java/com/csl/cs710ademoapp/fragments/AccessAuraSenseFragment.java
+app/src/main/java/com/csl/cs710ademoapp/fragments/AccessColdChainFragment.java
+app/src/main/java/com/csl/cs710ademoapp/fragments/AccessConfigFragment.java
+app/src/main/java/com/csl/cs710ademoapp/fragments/AccessEm4325PassiveFragment.java
+app/src/main/java/com/csl/cs710ademoapp/fragments/AccessFdmicroFragment.java
+app/src/main/java/com/csl/cs710ademoapp/fragments/AccessImpinjFragment.java
+app/src/main/java/com/csl/cs710ademoapp/fragments/AccessKilowayFragment.java
+app/src/main/java/com/csl/cs710ademoapp/fragments/AccessMicronFragment.java
+app/src/main/java/com/csl/cs710ademoapp/fragments/AccessReadWriteFragment.java
+app/src/main/java/com/csl/cs710ademoapp/fragments/AccessReadWriteUserFragment.java
+app/src/main/java/com/csl/cs710ademoapp/fragments/AccessRegisterFragment.java
+app/src/main/java/com/csl/cs710ademoapp/fragments/AccessSecurityFragment.java
+app/src/main/java/com/csl/cs710ademoapp/fragments/AccessSecurityKillFragment.java
+app/src/main/java/com/csl/cs710ademoapp/fragments/AccessSecurityLockFragment.java
+app/src/main/java/com/csl/cs710ademoapp/fragments/AccessUcode8Fragment.java
+app/src/main/java/com/csl/cs710ademoapp/fragments/AccessUcodeFragment.java
+app/src/main/java/com/csl/cs710ademoapp/fragments/AccessXerxesLoggerFragment.java
+app/src/main/java/com/csl/cs710ademoapp/fragments/AuraSenseFragment.java
+app/src/main/java/com/csl/cs710ademoapp/fragments/AxzonFragment.java
+app/src/main/java/com/csl/cs710ademoapp/fragments/AxzonSelectorFragment.java
+app/src/main/java/com/csl/cs710ademoapp/fragments/ColdChainFragment.java
+app/src/main/java/com/csl/cs710ademoapp/fragments/CommonFragment.java
+app/src/main/java/com/csl/cs710ademoapp/fragments/ConnectionFragment.java
+app/src/main/java/com/csl/cs710ademoapp/fragments/DirectWedgeFragment.java
+app/src/main/java/com/csl/cs710ademoapp/fragments/FdmicroFragment.java
+app/src/main/java/com/csl/cs710ademoapp/fragments/ForegroundFragment.java
+app/src/main/java/com/csl/cs710ademoapp/fragments/HomeFragment.java
+app/src/main/java/com/csl/cs710ademoapp/fragments/HomeSpecialFragment.java
+app/src/main/java/com/csl/cs710ademoapp/fragments/HomeWFragment.java
+app/src/main/java/com/csl/cs710ademoapp/fragments/ImpinjFragment.java
+app/src/main/java/com/csl/cs710ademoapp/fragments/ImpinjM775Fragment.java
+app/src/main/java/com/csl/cs710ademoapp/fragments/InventoryBarcodeFragment.java
+app/src/main/java/com/csl/cs710ademoapp/fragments/InventoryFragment.java
+app/src/main/java/com/csl/cs710ademoapp/fragments/InventoryRfidiMultiFragment.java
+app/src/main/java/com/csl/cs710ademoapp/fragments/InventoryRfidSearchFragment.java
+app/src/main/java/com/csl/cs710ademoapp/fragments/InventoryRfidSimpleFragment.java
+app/src/main/java/com/csl/cs710ademoapp/fragments/KilowayFragment.java
+app/src/main/java/com/csl/cs710ademoapp/fragments/LongjingFragment.java
+app/src/main/java/com/csl/cs710ademoapp/fragments/MicronFragment.java
+app/src/main/java/com/csl/cs710ademoapp/fragments/SettingAdminFragment.java
+app/src/main/java/com/csl/cs710ademoapp/fragments/SettingFilterFragment.java
+app/src/main/java/com/csl/cs710ademoapp/fragments/SettingFilterPostFragment.java
+app/src/main/java/com/csl/cs710ademoapp/fragments/SettingFilterPreFragment.java
+app/src/main/java/com/csl/cs710ademoapp/fragments/SettingFilterRssiFragment.java
+app/src/main/java/com/csl/cs710ademoapp/fragments/SettingFragment.java
+app/src/main/java/com/csl/cs710ademoapp/fragments/SettingOperateFragment.java
+app/src/main/java/com/csl/cs710ademoapp/fragments/SettingWedgeFragment.java
+app/src/main/java/com/csl/cs710ademoapp/fragments/Test1Fragment.java
+app/src/main/java/com/csl/cs710ademoapp/fragments/TestFragment.java
+app/src/main/java/com/csl/cs710ademoapp/fragments/Ucode8Fragment.java
+app/src/main/java/com/csl/cs710ademoapp/fragments/UcodeFragment.java
+app/src/main/java/com/csl/cs710ademoapp/fragments/UtraceFragment.java
+app/src/main/java/com/csl/cs710ademoapp/GenericTextWatcher.java
+app/src/main/java/com/csl/cs710ademoapp/InventoryBarcodeTask.java
+app/src/main/java/com/csl/cs710ademoapp/InventoryRfidTask.java
+app/src/main/java/com/csl/cs710ademoapp/MainActivity.java
+app/src/main/java/com/csl/cs710ademoapp/MyForegroundService.java
+app/src/main/java/com/csl/cs710ademoapp/MyMqttClient.java
+app/src/main/java/com/csl/cs710ademoapp/SaveList2ExternalTask.java
+app/src/main/java/com/csl/cs710ademoapp/SelectTag.java
+app/src/main/java/com/csl/cs710ademoapp/SensorConnector.java
+app/src/main/java/com/csl/cs710ademoapp/SettingTask.java
+app/src/main/java/com/csl/cs710ademoapp/SharedObjects.java
+app/src/main/res/drawable/border.xml
+app/src/main/res/drawable/ic_launcher_background.xml
+app/src/main/res/drawable/my_edittext_background.xml
+app/src/main/res/layout/actionbar_indeterminate_progress.xml
+app/src/main/res/layout/activity_main.xml
+app/src/main/res/layout/activity_main1.xml
+app/src/main/res/layout/custom_edittext_password.xml
+app/src/main/res/layout/custom_edittext.xml
+app/src/main/res/layout/custom_notification.xml
+app/src/main/res/layout/custom_readwrite.xml
+app/src/main/res/layout/custom_select.xml
+app/src/main/res/layout/custom_select1.xml
+app/src/main/res/layout/custom_select2.xml
+app/src/main/res/layout/custom_spinner_layout.xml
+app/src/main/res/layout/custom_tabbed_layout.xml
+app/src/main/res/layout/drawer_list_item.xml
+app/src/main/res/layout/fragment_about.xml
+app/src/main/res/layout/fragment_access_aurasense.xml
+app/src/main/res/layout/fragment_access_coldchain.xml
+app/src/main/res/layout/fragment_access_config.xml
+app/src/main/res/layout/fragment_access_em4325passive.xml
+app/src/main/res/layout/fragment_access_fdmicro.xml
+app/src/main/res/layout/fragment_access_impinj.xml
+app/src/main/res/layout/fragment_access_kill.xml
+app/src/main/res/layout/fragment_access_kiloway.xml
+app/src/main/res/layout/fragment_access_lock.xml
+app/src/main/res/layout/fragment_access_micron.xml
+app/src/main/res/layout/fragment_access_readwrite.xml
+app/src/main/res/layout/fragment_access_register.xml
+app/src/main/res/layout/fragment_access_ucode.xml
+app/src/main/res/layout/fragment_access_ucode8.xml
+app/src/main/res/layout/fragment_access_xerxes.xml
+app/src/main/res/layout/fragment_connection.xml
+app/src/main/res/layout/fragment_directwedge_settings.xml
+app/src/main/res/layout/fragment_directwedge.xml
+app/src/main/res/layout/fragment_filterpost_content.xml
+app/src/main/res/layout/fragment_filterpre_content.xml
+app/src/main/res/layout/fragment_filterrssi_content.xml
+app/src/main/res/layout/fragment_geiger_search.xml
+app/src/main/res/layout/fragment_inventory_barcode.xml
+app/src/main/res/layout/fragment_inventory_rfid_multi.xml
+app/src/main/res/layout/fragment_inventory_rfid_simple.xml
+app/src/main/res/layout/fragment_select_axzon.xml
+app/src/main/res/layout/fragment_settings_admin.xml
+app/src/main/res/layout/fragment_settings_operate.xml
+app/src/main/res/layout/fragment_specials.xml
+app/src/main/res/layout/fragment_test.xml
+app/src/main/res/layout/fragment_test1.xml
+app/src/main/res/layout/fragment_utrace.xml
+app/src/main/res/layout/home_layout108.xml
+app/src/main/res/layout/home_layout710.xml
+app/src/main/res/layout/home_special_layout.xml
+app/src/main/res/layout/keyboard_preview.xml
+app/src/main/res/layout/keyboard_view.xml
+app/src/main/res/layout/list_item.xml
+app/src/main/res/layout/popup.xml
+app/src/main/res/layout/readers_list_item.xml
+app/src/main/res/layout/title_divider.xml
+app/src/main/res/menu/menu_connection.xml
+app/src/main/res/menu/menu_home.xml
+app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml
+app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml
+app/src/main/res/values/colors.xml
+app/src/main/res/values/dimens.xml
+app/src/main/res/values/strings.xml
+app/src/main/res/values/styles.xml
+app/src/main/res/xml/device_filter.xml
+app/src/main/res/xml/method.xml
+app/src/main/res/xml/nfc_tech_filter.xml
+app/src/main/res/xml/number_pad.xml
+app/src/main/res/xml/number_pad1.xml
+cslibrary4a/src/main/AndroidManifest.xml
+cslibrary4a/src/main/java/com/csl/cslibrary4a/AdapterTab.java
+cslibrary4a/src/main/java/com/csl/cslibrary4a/AesCmac.java
+cslibrary4a/src/main/java/com/csl/cslibrary4a/BarcodeConnector.java
+cslibrary4a/src/main/java/com/csl/cslibrary4a/BarcodeNewland.java
+cslibrary4a/src/main/java/com/csl/cslibrary4a/BluetoothConnector.java
+cslibrary4a/src/main/java/com/csl/cslibrary4a/BluetoothGatt.java
+cslibrary4a/src/main/java/com/csl/cslibrary4a/ConnectorData.java
+cslibrary4a/src/main/java/com/csl/cslibrary4a/ControllerConnector.java
+cslibrary4a/src/main/java/com/csl/cslibrary4a/Cs108Library4A.java
+cslibrary4a/src/main/java/com/csl/cslibrary4a/Cs710Library4A.java
+cslibrary4a/src/main/java/com/csl/cslibrary4a/CsLibrary4A.java
+cslibrary4a/src/main/java/com/csl/cslibrary4a/CsReaderConnector.java
+cslibrary4a/src/main/java/com/csl/cslibrary4a/DeviceFinder.java
+cslibrary4a/src/main/java/com/csl/cslibrary4a/NotificationConnector.java
+cslibrary4a/src/main/java/com/csl/cslibrary4a/ReaderDevice.java
+cslibrary4a/src/main/java/com/csl/cslibrary4a/RfidConnector.java
+cslibrary4a/src/main/java/com/csl/cslibrary4a/RfidReader.java
+cslibrary4a/src/main/java/com/csl/cslibrary4a/RfidReaderChipData.java
+cslibrary4a/src/main/java/com/csl/cslibrary4a/RfidReaderChipE710.java
+cslibrary4a/src/main/java/com/csl/cslibrary4a/RfidReaderChipR2000.java
+cslibrary4a/src/main/java/com/csl/cslibrary4a/SettingData.java
+cslibrary4a/src/main/java/com/csl/cslibrary4a/UsbConnector.java
+cslibrary4a/src/main/java/com/csl/cslibrary4a/Utility.java
+cslibrary4a/src/main/res/drawable/ic_launcher_background.xml
+cslibrary4a/src/main/res/drawable/ic_launcher_foreground.xml
+cslibrary4a/src/main/res/layout/popup.xml
+cslibrary4a/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml
+cslibrary4a/src/main/res/mipmap-anydpi-v26/ic_launcher.xml
+cslibrary4a/src/main/res/values-night/themes.xml
+cslibrary4a/src/main/res/values/colors.xml
+cslibrary4a/src/main/res/values/strings.xml
+cslibrary4a/src/main/res/values/themes.xml
+epctagcoder/src/main/AndroidManifest.xml
+epctagcoder/src/main/java/org/epctagcoder/exception/EPCParseException.java
+epctagcoder/src/main/java/org/epctagcoder/option/CPI/CPIFilterValue.java
+epctagcoder/src/main/java/org/epctagcoder/option/CPI/CPIHeader.java
+epctagcoder/src/main/java/org/epctagcoder/option/CPI/CPITagSize.java
+epctagcoder/src/main/java/org/epctagcoder/option/CPI/partitionTable/CPIPartitionTableList.java
+epctagcoder/src/main/java/org/epctagcoder/option/GDTI/GDTIFilterValue.java
+epctagcoder/src/main/java/org/epctagcoder/option/GDTI/GDTIHeader.java
+epctagcoder/src/main/java/org/epctagcoder/option/GDTI/GDTITagSize.java
+epctagcoder/src/main/java/org/epctagcoder/option/GDTI/partitionTable/GDTIPartitionTableList.java
+epctagcoder/src/main/java/org/epctagcoder/option/GIAI/GIAIFilterValue.java
+epctagcoder/src/main/java/org/epctagcoder/option/GIAI/GIAIHeader.java
+epctagcoder/src/main/java/org/epctagcoder/option/GIAI/GIAITagSize.java
+epctagcoder/src/main/java/org/epctagcoder/option/GIAI/partitionTable/GIAIPartitionTableList.java
+epctagcoder/src/main/java/org/epctagcoder/option/GRAI/GRAIFilterValue.java
+epctagcoder/src/main/java/org/epctagcoder/option/GRAI/GRAIHeader.java
+epctagcoder/src/main/java/org/epctagcoder/option/GRAI/GRAITagSize.java
+epctagcoder/src/main/java/org/epctagcoder/option/GRAI/partitionTable/GRAIPartitionTableList.java
+epctagcoder/src/main/java/org/epctagcoder/option/GSRN/GSRNFilterValue.java
+epctagcoder/src/main/java/org/epctagcoder/option/GSRN/GSRNHeader.java
+epctagcoder/src/main/java/org/epctagcoder/option/GSRN/GSRNTagSize.java
+epctagcoder/src/main/java/org/epctagcoder/option/GSRN/partitionTable/GSRNPartitionTableList.java
+epctagcoder/src/main/java/org/epctagcoder/option/GSRNP/GSRNPFilterValue.java
+epctagcoder/src/main/java/org/epctagcoder/option/GSRNP/GSRNPHeader.java
+epctagcoder/src/main/java/org/epctagcoder/option/GSRNP/GSRNPTagSize.java
+epctagcoder/src/main/java/org/epctagcoder/option/GSRNP/partitionTable/GSRNPPartitionTableList.java
+epctagcoder/src/main/java/org/epctagcoder/option/PrefixLength.java
+epctagcoder/src/main/java/org/epctagcoder/option/SGLN/partitionTable/SGLNPartitionTableList.java
+epctagcoder/src/main/java/org/epctagcoder/option/SGLN/SGLNFilterValue.java
+epctagcoder/src/main/java/org/epctagcoder/option/SGLN/SGLNHeader.java
+epctagcoder/src/main/java/org/epctagcoder/option/SGLN/SGLNTagSize.java
+epctagcoder/src/main/java/org/epctagcoder/option/SGTIN/partitionTable/SGTINPartitionTableList.java
+epctagcoder/src/main/java/org/epctagcoder/option/SGTIN/SGTINExtensionDigit.java
+epctagcoder/src/main/java/org/epctagcoder/option/SGTIN/SGTINFilterValue.java
+epctagcoder/src/main/java/org/epctagcoder/option/SGTIN/SGTINHeader.java
+epctagcoder/src/main/java/org/epctagcoder/option/SGTIN/SGTINTagSize.java
+epctagcoder/src/main/java/org/epctagcoder/option/SSCC/partitionTable/SSCCPartitionTableList.java
+epctagcoder/src/main/java/org/epctagcoder/option/SSCC/SSCCExtensionDigit.java
+epctagcoder/src/main/java/org/epctagcoder/option/SSCC/SSCCFilterValue.java
+epctagcoder/src/main/java/org/epctagcoder/option/SSCC/SSCCHeader.java
+epctagcoder/src/main/java/org/epctagcoder/option/SSCC/SSCCTagSize.java
+epctagcoder/src/main/java/org/epctagcoder/option/TableItem.java
+epctagcoder/src/main/java/org/epctagcoder/parse/CPI/ParseCPI.java
+epctagcoder/src/main/java/org/epctagcoder/parse/GDTI/ParseGDTI.java
+epctagcoder/src/main/java/org/epctagcoder/parse/GIAI/ParseGIAI.java
+epctagcoder/src/main/java/org/epctagcoder/parse/GRAI/ParseGRAI.java
+epctagcoder/src/main/java/org/epctagcoder/parse/GSRN/ParseGSRN.java
+epctagcoder/src/main/java/org/epctagcoder/parse/GSRNP/ParseGSRNP.java
+epctagcoder/src/main/java/org/epctagcoder/parse/SGLN/ParseSGLN.java
+epctagcoder/src/main/java/org/epctagcoder/parse/SGTIN/ParseSGTIN.java
+epctagcoder/src/main/java/org/epctagcoder/parse/SSCC/ParseSSCC.java
+epctagcoder/src/main/java/org/epctagcoder/result/Base.java
+epctagcoder/src/main/java/org/epctagcoder/result/CPI.java
+epctagcoder/src/main/java/org/epctagcoder/result/GDTI.java
+epctagcoder/src/main/java/org/epctagcoder/result/GIAI.java
+epctagcoder/src/main/java/org/epctagcoder/result/GRAI.java
+epctagcoder/src/main/java/org/epctagcoder/result/GSRN.java
+epctagcoder/src/main/java/org/epctagcoder/result/GSRNP.java
+epctagcoder/src/main/java/org/epctagcoder/result/SGLN.java
+epctagcoder/src/main/java/org/epctagcoder/result/SGTIN.java
+epctagcoder/src/main/java/org/epctagcoder/result/SSCC.java
+epctagcoder/src/main/java/org/epctagcoder/util/Converter.java
+gradle/wrapper/gradle-wrapper.properties
+README.md
+repomix-instruction.md
+repomix.config.json
+
+
+
+This section contains the contents of the repository's files.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+package com.csl.cs710ademoapp;
+
+import android.os.AsyncTask;
+import android.os.Handler;
+import android.widget.Button;
+import android.widget.TextView;
+import android.widget.Toast;
+
+import com.csl.cslibrary4a.RfidReaderChipData;
+
+import java.util.ArrayList;
+
+public class AccessTask extends AsyncTask {
+ final boolean DEBUG = true;
+ final boolean skipSelect = false;
+ public enum TaskCancelRReason {
+ NULL, INVALD_REQUEST, DESTORY, STOP, BUTTON_RELEASE, ERROR, TIMEOUT
+ }
+ public TaskCancelRReason taskCancelReason;
+ public String accessResult;
+ public String accessTagEpc;
+ Handler mHandler = new Handler();
+ Runnable updateRunnable = null;
+
+ Button button; String buttonText;
+ TextView registerRunTime, registerTagGot, registerVoltageLevel;
+ TextView registerYield, registerTotal;
+ boolean invalidRequest, selectOne = false;
+ String selectMask; int selectBank, selectOffset;
+ String strPassword; int powerLevel;
+ RfidReaderChipData.HostCommands hostCommand;
+
+ CustomMediaPlayer playerO, playerN;
+
+ long timeMillis, startTimeMillis, runTimeMillis;
+ int accessError, backscatterError;
+ boolean timeoutError, crcError;
+ public String resultError = "";
+ boolean success;
+ boolean done = false;
+ boolean ending = false;
+ private String endingMessaage;
+
+ int qValue=0;
+ int repeat=0;
+ boolean bEnableErrorPopWindow=true;
+
+ boolean gotInventory;
+ int batteryCountInventory_old;
+ boolean bSkipClearFilter = false;
+
+ public AccessTask(Button button, boolean invalidRequest, boolean selectOne,
+ String selectMask, int selectBank, int selectOffset,
+ String strPassword, int powerLevel, RfidReaderChipData.HostCommands hostCommand,
+ boolean bEnableErrorPopWindow, Runnable updateRunnable) {
+ this.button = button;
+ this.registerTagGot = registerTagGot;
+ this.registerVoltageLevel = registerVoltageLevel;
+
+ this.invalidRequest = invalidRequest; MainActivity.csLibrary4A.appendToLog("invalidRequest = " + invalidRequest);
+ this.selectOne = selectOne;
+ this.selectMask = selectMask;
+ this.selectBank = selectBank;
+ this.selectOffset = selectOffset;
+ this.strPassword = strPassword;
+ this.powerLevel = powerLevel;
+ this.hostCommand = hostCommand;
+ this.bEnableErrorPopWindow = bEnableErrorPopWindow;
+ this.updateRunnable = updateRunnable;
+ if (true) {
+ total = 0;
+ tagList.clear();
+ }
+ preExecute();
+ }
+ public AccessTask(Button button, TextView textViewWriteCount, boolean invalidRequest, boolean selectOne,
+ String selectMask, int selectBank, int selectOffset,
+ String strPassword, int powerLevel, RfidReaderChipData.HostCommands hostCommand,
+ int qValue, int repeat, boolean resetCount, boolean bSkipClearFilter,
+ TextView registerRunTime, TextView registerTagGot, TextView registerVoltageLevel, TextView registerYieldView, TextView registerTotalView) {
+ this.button = button;
+ this.registerTotal = textViewWriteCount;
+ this.registerRunTime = registerRunTime;
+ this.registerTagGot = registerTagGot;
+ this.registerVoltageLevel = registerVoltageLevel;
+ this.registerYield = registerYieldView;
+ this.registerTotal = registerTotalView;
+
+ this.invalidRequest = invalidRequest; MainActivity.csLibrary4A.appendToLog("invalidRequest = " + invalidRequest);
+ this.selectOne = selectOne;
+ this.selectMask = selectMask;
+ this.selectBank = selectBank;
+ this.selectOffset = selectOffset;
+ this.strPassword = strPassword;
+ this.powerLevel = powerLevel;
+ this.hostCommand = hostCommand;
+ this.qValue = qValue;
+ if (repeat > 255) repeat = 255;
+ this.repeat = repeat;
+ this.bSkipClearFilter = bSkipClearFilter;
+ if (bSkipClearFilter) this.selectOne = false;
+ if (resetCount) {
+ total = 0;
+ tagList.clear();
+ }
+ preExecute();
+ }
+ public void setRunnable(Runnable updateRunnable) {
+ this.updateRunnable = updateRunnable;
+ }
+
+ void preExecute() {
+ accessResult = null; MainActivity.csLibrary4A.appendToLog("accessResult is set null");
+ playerO = MainActivity.sharedObjects.playerO;
+ playerN = MainActivity.sharedObjects.playerN;
+ //playerN.start();
+
+ buttonText = button.getText().toString().trim();
+ String buttonText1 = ""; String strLastChar = "";
+ if (buttonText.length() != 0) {
+ strLastChar = buttonText.substring(buttonText.length() - 1);
+ if (strLastChar.toUpperCase().matches("E")) {
+ buttonText1 = buttonText.substring(0, buttonText.length() - 1);
+ } else if (buttonText.toUpperCase().matches("STOP")) {
+ buttonText1 = buttonText;
+ buttonText1 += buttonText1.substring(buttonText.length() - 1);
+ } else buttonText1 = buttonText;
+ }
+ if (repeat > 1 || buttonText.length() == 0) button.setText("Stop");
+ else {
+ if (Character.isUpperCase(strLastChar.charAt(0))) button.setText(buttonText1 + "ING");
+ else button.setText(buttonText1 + "ing");
+ }
+ if (registerYield != null && tagList.size()==0) registerYield.setText("");
+ if (registerTotal != null && total == 0) registerTotal.setText("");
+
+ timeMillis = System.currentTimeMillis(); startTimeMillis = timeMillis; runTimeMillis = startTimeMillis;
+ accessError = 0; backscatterError = 0; timeoutError = false; crcError = false;
+ success = false;
+
+ if (invalidRequest == false) {
+ if (strPassword.length() != 8) { invalidRequest = true; MainActivity.csLibrary4A.appendToLog("strPassword.length = " + strPassword.length() + " (not 8)."); }
+ else if (hostCommand == RfidReaderChipData.HostCommands.CMD_18K6CKILL) {
+ if (MainActivity.csLibrary4A.setRx000KillPassword(strPassword) == false) {
+ invalidRequest = true; MainActivity.csLibrary4A.appendToLog("setRx000KillPassword is failed");
+ }
+ } else if (MainActivity.csLibrary4A.setRx000AccessPassword(strPassword) == false) {
+ invalidRequest = true;
+ MainActivity.csLibrary4A.appendToLog("setRx000AccessPassword is failed");
+ }
+ }
+ if (invalidRequest == false) {
+ if (MainActivity.csLibrary4A.setAccessRetry(true, 7) == false) {
+ invalidRequest = true; MainActivity.csLibrary4A.appendToLog("setAccessRetry is failed");
+ }
+ }
+ if (invalidRequest == false) {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("AccessTask(): powerLevel = " + powerLevel);
+ int matchRep = 1;
+ if (repeat > 1) matchRep = repeat;
+ if (false && bSkipClearFilter == false) {
+ MainActivity.csLibrary4A.appendToLog("Going to setSelectCriteria disable");
+ MainActivity.csLibrary4A.setSelectCriteriaDisable(-1);
+ }
+ if (powerLevel < 0 || powerLevel > MainActivity.powerLevelMax) invalidRequest = true;
+ else if (skipSelect == false) {
+ MainActivity.csLibrary4A.appendToLog("AccessTask.preExecute goes to setSelectTag");
+ if (MainActivity.csLibrary4A.setSelectedTag(selectOne, selectMask, selectBank, selectOffset, powerLevel, qValue, matchRep) == false) {
+ invalidRequest = true; MainActivity.csLibrary4A.appendToLog("setSelectedTag is failed with selectMask = " + selectMask + ", selectBank = " + selectBank + ", selectOffset = " + selectOffset + ", powerLevel = " + powerLevel);
+ }
+ }
+ }
+ gotInventory = false;
+ taskCancelReason = TaskCancelRReason.NULL;
+ if (invalidRequest) {
+ cancel(true);
+ taskCancelReason = TaskCancelRReason.INVALD_REQUEST;
+ MainActivity.csLibrary4A.appendToLog("invalidRequest A= " + invalidRequest);
+ } else {
+ //MainActivity.csLibrary4A.setTagRead(0);
+ MainActivity.csLibrary4A.sendHostRegRequestHST_CMD(hostCommand);
+ }
+ }
+
+ boolean accessCompleteReceived = false;
+
+ @Override
+ protected String doInBackground(Void... a) {
+ boolean ending = false;
+ int iTimeOut = 5000;
+ accessCompleteReceived = false;
+
+ while (MainActivity.csLibrary4A.isBleConnected() && isCancelled() == false && ending == false) {
+ int batteryCount = MainActivity.csLibrary4A.getBatteryCount();
+ if (batteryCountInventory_old != batteryCount) {
+ batteryCountInventory_old = batteryCount;
+ publishProgress("VV");
+ }
+ if (System.currentTimeMillis() > runTimeMillis + 1000) {
+ runTimeMillis = System.currentTimeMillis();
+ publishProgress("WW");
+ }
+ byte[] notificationData = MainActivity.csLibrary4A.onNotificationEvent();
+ RfidReaderChipData.Rx000pkgData rx000pkgData = MainActivity.csLibrary4A.onRFIDEvent();
+ if (MainActivity.csLibrary4A.mrfidToWriteSize() != 0) timeMillis = System.currentTimeMillis();
+ else if (rx000pkgData != null) {
+ if (rx000pkgData.responseType == null) {
+ publishProgress("null response");
+ } else if (rx000pkgData.responseType == RfidReaderChipData.HostCmdResponseTypes.TYPE_18K6C_TAG_ACCESS) {
+ accessCompleteReceived = true;
+ MainActivity.csLibrary4A.appendToLog("rx000pkgData.dataValues = " + MainActivity.csLibrary4A.byteArrayToString(rx000pkgData.dataValues));
+ if (rx000pkgData.decodedError == null) {
+ if (done == false) {
+ accessResult = rx000pkgData.decodedResult;
+ MainActivity.csLibrary4A.appendToLog("responseType = " + rx000pkgData.responseType.toString() + ", accessResult = " + accessResult);
+ if (repeat > 0) repeat--;
+ if (updateRunnable != null) mHandler.post(updateRunnable);
+ publishProgress(null, rx000pkgData.decodedResult);
+ }
+ done = true;
+ } else publishProgress(rx000pkgData.decodedError);
+ iTimeOut = 1000;
+ } else if (rx000pkgData.responseType == RfidReaderChipData.HostCmdResponseTypes.TYPE_COMMAND_END) {
+ if (hostCommand == RfidReaderChipData.HostCommands.CMD_18K6CKILL && accessCompleteReceived == false) accessResult = "";
+ MainActivity.csLibrary4A.appendToLog("BtData: repeat = " + repeat + ", decodedError = " + rx000pkgData.decodedError + ", resultError = " + resultError);
+ if (rx000pkgData.decodedError != null) { endingMessaage = rx000pkgData.decodedError; ending = true; }
+ else if (repeat > 0 && resultError.length() == 0) {
+ resultError = "";
+ if (true) MainActivity.csLibrary4A.appendToLog("Debug_InvCfg: AccessTask.doInBackground goes to setMatchRep with repeat = " + repeat);
+ MainActivity.csLibrary4A.setMatchRep(repeat);
+ MainActivity.csLibrary4A.sendHostRegRequestHST_CMD(hostCommand);
+ } else {
+ endingMessaage = "";
+ ending = true;
+ }
+ } else if (rx000pkgData.responseType == RfidReaderChipData.HostCmdResponseTypes.TYPE_18K6C_INVENTORY) {
+ accessTagEpc = MainActivity.csLibrary4A.byteArrayToString(rx000pkgData.decodedEpc);
+ done = false;
+ publishProgress("TT", MainActivity.csLibrary4A.byteArrayToString(rx000pkgData.decodedEpc));
+ } else {
+ publishProgress("Unhandled Response: " + rx000pkgData.responseType.toString());
+ }
+ timeMillis = System.currentTimeMillis();
+ }
+ else if (notificationData != null) {
+ //MainActivity.csLibrary4A.appendToLog("resultError=" + MainActivity.csLibrary4A.byteArrayToString(notificationData));
+ publishProgress("Received notification uplink event 0xA101 with error code=" + MainActivity.csLibrary4A.byteArrayToString(notificationData));
+ taskCancelReason = TaskCancelRReason.ERROR;
+ }
+ if (System.currentTimeMillis() - timeMillis > iTimeOut) {
+ //MainActivity.csLibrary4A.appendToLog("endingMessage: iTimeout = " + iTimeOut);
+ taskCancelReason = TaskCancelRReason.TIMEOUT;
+ }
+ if (taskCancelReason != TaskCancelRReason.NULL) {
+ //MainActivity.csLibrary4A.appendToLog("taskCancelReason=" + TaskCancelRReason.values());
+ cancel(true);
+ }
+ }
+ return "End of Asynctask():" + ending;
+ }
+
+ static int total = 0;
+ static ArrayList tagList = new ArrayList();
+ String tagInventoried = null;
+ @Override
+ protected void onProgressUpdate(String... output) {
+ if (output[0] != null) {
+ MainActivity.csLibrary4A.appendToLog("onProgressUpdate output[0] = " + output[0]);
+ if (output[0].length() == 2) {
+ if (output[0].contains("TT")) {
+ gotInventory = true;
+ boolean matched = false;
+ for (int i = 0; i < tagList.size(); i++) {
+ if (output[1].matches(tagList.get(i))) {
+ matched = true;
+ break;
+ }
+ }
+ if (registerTagGot != null) registerTagGot.setText(output[1]);
+ if (matched == false) tagInventoried = output[1];
+ } else if (output[0].contains("WW")) {
+ long timePeriod = (System.currentTimeMillis() - startTimeMillis) / 1000;
+ if (timePeriod > 0) {
+ if (registerRunTime != null) registerRunTime.setText(String.format("Run time: %d sec", timePeriod));
+ }
+ } else if (taskCancelReason == TaskCancelRReason.NULL) {
+ if (registerVoltageLevel != null) registerVoltageLevel.setText(MainActivity.csLibrary4A.getBatteryDisplay(true));
+ }
+ } else {
+ resultError += output[0];
+ if (true)
+ MainActivity.csLibrary4A.appendToLog("output[0]: " + output[0] + ", resultError = " + resultError);
+ }
+ } else {
+ MainActivity.csLibrary4A.appendToLog("onProgressUpdate output[1] = " + output[1]);
+ if (registerYield != null) {
+ if (tagInventoried != null) {
+ tagList.add(tagInventoried);
+ tagInventoried = null;
+ }
+ registerYield.setText("Unique:" + Integer.toString(tagList.size()));
+ }
+ if (registerTotal != null) registerTotal.setText("Total:" + Integer.toString(++total));
+ }
+ }
+
+ @Override
+ protected void onCancelled() {
+ super.onCancelled();
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("endingMesssage: taskCancelReason = " + taskCancelReason);
+ MainActivity.csLibrary4A.abortOperation();
+ if (taskCancelReason == TaskCancelRReason.NULL) taskCancelReason = TaskCancelRReason.DESTORY;
+ DeviceConnectTask4RegisterEnding();
+ }
+
+ @Override
+ protected void onPostExecute(String result) {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("AccessSecurityLockFragment.InventoryRfidTask.onPostExecute(): " + result);
+ DeviceConnectTask4RegisterEnding();
+ }
+
+ void DeviceConnectTask4RegisterEnding() {
+ //MainActivity.csLibrary4A.setAccessCount(0);
+ String strErrorMessage = "";
+ if (false) {
+ boolean success = false;
+ MainActivity.csLibrary4A.appendToLog("repeat = " + repeat + ", taskCancelReason = " + taskCancelReason.toString()
+ + ", backscatterError = " + backscatterError + ", accessError =" + accessError + ", accessResult = " + accessResult + ", resultError = " + resultError);
+ if ((repeat <= 1 && taskCancelReason != TaskCancelRReason.NULL) || backscatterError != 0 || accessError != 0 || accessResult == null || resultError.length() != 0) {
+ MainActivity.csLibrary4A.appendToLog("FAILURE"); Toast.makeText(MainActivity.mContext, R.string.toast_abort_by_FAILURE, Toast.LENGTH_SHORT).show();
+ playerO.start();
+ } else {
+ MainActivity.csLibrary4A.appendToLog("SUCCESS"); Toast.makeText(MainActivity.mContext, R.string.toast_abort_by_SUCCESS, Toast.LENGTH_SHORT).show();
+ playerN.start();
+ }
+ } else {
+ strErrorMessage = "";
+ switch (taskCancelReason) {
+ case NULL:
+ if (accessResult == null) MainActivity.csLibrary4A.appendToLog("taskCancelReason: NULL accessResult");
+ if (resultError != null) MainActivity.csLibrary4A.appendToLog("taskCancelReason: resultError = " + resultError);
+ if (endingMessaage != null) MainActivity.csLibrary4A.appendToLog("taskCancelReason: endingMessaage = " + endingMessaage);
+ if (accessResult == null || (resultError != null && resultError.length() != 0) || (endingMessaage != null && endingMessaage.length() != 0)) strErrorMessage += ("Finish as COMMAND END is received " + (gotInventory ? "WITH" : "WITHOUT") + " tag response");
+ //else Toast.makeText(MainActivity.mContext, R.string.toast_abort_by_SUCCESS, Toast.LENGTH_SHORT).show();
+ break;
+ case STOP:
+ strErrorMessage += "Finish as STOP is pressed. ";
+ break;
+ case BUTTON_RELEASE:
+ strErrorMessage += "Finish as BUTTON is released. ";
+ break;
+ case ERROR:
+ strErrorMessage += "Finish due to error received.";
+ break;
+ case TIMEOUT:
+ strErrorMessage += "TIMEOUT without COMMAND_END. ";
+ break;
+ case INVALD_REQUEST:
+ strErrorMessage += "Invalid request. Operation is cancelled. ";
+ break;
+ }
+ MainActivity.csLibrary4A.appendToLog("taskCancelReason = " + taskCancelReason.toString() + ", accessResult = " + (accessResult == null ? "NULL": accessResult) + ", endingMessaage = " + (endingMessaage == null ? "NULL" : endingMessaage) + ", resultError = " + (resultError == null ? "NULL" : resultError));
+ if (resultError.length() != 0) {
+ if (strErrorMessage.trim().length() == 0) strErrorMessage = resultError;
+ else strErrorMessage += (". " + resultError);
+ }
+ if (strErrorMessage.length() != 0) strErrorMessage += ". ";
+ }
+ if (endingMessaage != null) if (endingMessaage.length() != 0) strErrorMessage += "Received CommandEND Error = " + endingMessaage;
+ if (strErrorMessage.length() != 0) endingMessaage = strErrorMessage;
+ button.setText(buttonText);
+ if (endingMessaage != null) {
+ if (endingMessaage.length() != 0) {
+ MainActivity.csLibrary4A.appendToLog("endingMessage=" + endingMessaage);
+ if (bEnableErrorPopWindow) {
+ CustomPopupWindow customPopupWindow = new CustomPopupWindow(MainActivity.mContext);
+ customPopupWindow.popupStart(endingMessaage, false);
+ }
+ }
+ }
+ }
+}
+
+
+
+package com.csl.cs710ademoapp;
+
+import android.os.AsyncTask;
+import android.widget.Button;
+import android.widget.Toast;
+
+import com.csl.cslibrary4a.RfidReaderChipData;
+
+public class AccessTask1 {
+ Button button;
+ boolean invalidRequest;
+ int accBank, accOffset, accSize, accSizeNow, accBlockCount = 90; String accWriteData, accWriteDataNow;
+ String selectMask;
+ int selectBank, selectOffset;
+ String strPassword;
+ int powerLevel;
+ RfidReaderChipData.HostCommands hostCommand;
+ Runnable updateRunnable = null;
+
+ AccessTask accessTask;
+ public AccessTask1(Button button, boolean invalidRequest,
+ int accBank, int accOffset, int accSize, int accBlockCount, String accWriteData,
+ String selectMask, int selectBank, int selectOffset,
+ String strPassword, int powerLevel, RfidReaderChipData.HostCommands hostCommand, Runnable updateRunnable) {
+ this.button = button;
+ this.invalidRequest = invalidRequest;
+ MainActivity.csLibrary4A.appendToLog("HelloK: invalidRequest=" + invalidRequest);
+ this.accBank = accBank;
+ this.accOffset = accOffset;
+ if (hostCommand == RfidReaderChipData.HostCommands.CMD_18K6CWRITE) { if (accBlockCount > 16) accBlockCount = 16; }
+ else if (accBlockCount > 255) accBlockCount = 255;
+ this.accBlockCount = accBlockCount;
+ if (accWriteData == null) accWriteData = "";
+ if (hostCommand == RfidReaderChipData.HostCommands.CMD_18K6CWRITE) {
+ MainActivity.csLibrary4A.appendToLog("strOut: accWriteData=" + accWriteData);
+ accWriteData = deformatWriteAccessData(accWriteData);
+ if (accWriteData.length() < accSize * 4) {
+ accSize = accWriteData.length()/4;
+ if (accSize*4 != accWriteData.length()) accSize++;
+ }
+ }
+ this.accSize = accSize;
+ if (accSize == 0) {
+ isResultReady = true;
+ accessResult = "";
+ }
+ this.accWriteData = accWriteData;
+ this.selectMask = selectMask;
+ this.selectBank = selectBank;
+ this.selectOffset = selectOffset;
+ this.strPassword = strPassword;
+ this.powerLevel = powerLevel;
+ this.hostCommand = hostCommand;
+ this.updateRunnable = updateRunnable;
+ MainActivity.csLibrary4A.appendToLog("HelloA, AccessTask1");
+ CustomMediaPlayer playerN = MainActivity.sharedObjects.playerN;
+ playerN.start();
+ setup();
+ }
+
+ public void execute() {
+ if (accessTask != null) accessTask.execute();
+ }
+
+ public boolean cancel(boolean bCancel) {
+ if (accessTask == null) return true;
+ return accessTask.cancel(bCancel);
+ }
+
+ public AsyncTask.Status getStatus() {
+ if (accessTask == null) return AsyncTask.Status.FINISHED;
+ return accessTask.getStatus();
+ }
+
+ public String deformatWriteAccessData(String strIn) {
+ MainActivity.csLibrary4A.appendToLog("strOut: strIn=" + strIn);
+ String strOut = strIn.replaceAll("\\P{Print}", "");
+ MainActivity.csLibrary4A.appendToLog("strOut=" + strOut);
+ while (strOut.indexOf(":") > 0) {
+ int index = strOut.indexOf(":");
+ String writeDataTemp = "";
+ if (index > 4) writeDataTemp = strOut.substring(0, index - 3);
+ writeDataTemp += strOut.substring(index + 1);
+ strOut = writeDataTemp;
+ MainActivity.csLibrary4A.appendToLog("strOut=" + strOut);
+ }
+ MainActivity.csLibrary4A.appendToLog("strOut=" + strOut);
+ return strOut;
+ }
+
+ boolean isResultReady = false; int tryCount = 0, tryCountMax = 8;
+ public boolean isResultReady() {
+ boolean bValue = false;
+ if (accessTask == null) { }
+ else if (accessTask.getStatus() != AsyncTask.Status.FINISHED) { }
+ else if (button.getText().toString().indexOf("ING") > 0) { }
+ else if (isResultReady == false) {
+ String strAccessResult = "";
+ if (hostCommand != RfidReaderChipData.HostCommands.CMD_18K6CREAD || accBank != 3) strAccessResult = accessTask.accessResult;
+ else {
+ int word4line = 7;
+ for (int i = 0; i < accSizeNow; i=i+word4line) {
+ if (tryCount < tryCountMax && accessTask.accessResult == null) break;
+ strAccessResult += String.format("%03d:", accOffset + i);
+ if (accessTask.accessResult != null) {
+ if ((i + word4line) * 4 >= accessTask.accessResult.length()) {
+ int iLastWordIndex = accessTask.accessResult.substring(i * 4).length() / 4;
+ if (iLastWordIndex * 4 != accessTask.accessResult.substring(i * 4).length())
+ iLastWordIndex++;
+ strAccessResult += String.format("%03d:", accOffset + i + iLastWordIndex - 1) + accessTask.accessResult.substring(i * 4);
+ } else
+ strAccessResult += accessTask.accessResult.substring(i * 4, (i + word4line) * 4);
+ }
+ strAccessResult += "\n";
+ MainActivity.csLibrary4A.appendToLog("i=" + i + ", formatted accessTask.accessResult=" + strAccessResult);
+ }
+ }
+ if (accessResult == null) accessResult = strAccessResult;
+ else accessResult += strAccessResult;
+
+ MainActivity.csLibrary4A.appendToLog("HelloA: accessResult=" + accessTask.accessResult);
+ if (accessTask.accessResult != null && accSizeNow >= accSize) {
+ bValue = true;
+ Toast.makeText(MainActivity.mContext, R.string.toast_abort_by_SUCCESS, Toast.LENGTH_SHORT).show();
+ }
+ else {
+ if (accessTask.accessResult != null) {
+ accOffset += accSizeNow;
+ accSize -= accSizeNow;
+ if (accWriteData != null) { if (accWriteData.length() >= accSizeNow*4) accWriteData = accWriteData.substring(accSizeNow*4); }
+ tryCount = 0;
+ }
+ MainActivity.csLibrary4A.appendToLog("HelloA: Going to retry with TryCount=" + tryCount + ", resultError = " + accessTask.resultError);
+ if (tryCount < tryCountMax) {
+ MainActivity.csLibrary4A.appendToLog("HelloA: re-setup");
+ setup();
+ execute();
+ } else bValue = true;
+ }
+ } else bValue = true;
+ //MainActivity.csLibrary4A.appendToLog("HelloA: bValue=" + bValue);
+ isResultReady = bValue;
+ return bValue;
+ }
+ public String accessResult;
+ public String getResult() {
+ MainActivity.csLibrary4A.appendToLog("HelloA: accessResult = " + accessResult);
+ if (accessTask == null) {
+ MainActivity.csLibrary4A.appendToLog("accessTask is null");
+ return null;
+ }
+ if (accessTask.getStatus() != AsyncTask.Status.FINISHED) {
+ MainActivity.csLibrary4A.appendToLog("accessTask.getStatus is not finished");
+ return null;
+ }
+ if (button.getText().toString().indexOf("ING") > 0) {
+ MainActivity.csLibrary4A.appendToLog("button is still ing");
+ return null;
+ }
+ return accessResult;
+ }
+
+ void setup() {
+ tryCount++;
+ if (invalidRequest == false) {
+ if (MainActivity.csLibrary4A.setAccessBank(accBank) == false) {
+ MainActivity.csLibrary4A.appendToLog("HelloK: accBank, invalidRequest=" + invalidRequest);
+ invalidRequest = true;
+ }
+ }
+ if (invalidRequest == false) {
+ if (MainActivity.csLibrary4A.setAccessOffset(accOffset) == false) {
+ MainActivity.csLibrary4A.appendToLog("HelloK: accOffset, invalidRequest=" + invalidRequest);
+ invalidRequest = true;
+ }
+ }
+ if (invalidRequest == false) {
+ if (accSize == 0) {
+ MainActivity.csLibrary4A.appendToLog("HelloK: accSize0, invalidRequest=" + invalidRequest);
+ invalidRequest = true;
+ } else {
+ if (accSize > accBlockCount) accSizeNow = accBlockCount;
+ else accSizeNow = accSize;
+ MainActivity.csLibrary4A.appendToLog("HelloA: accSize=" + accSize + ", accSizeNow=" + accSizeNow);
+ if (MainActivity.csLibrary4A.setAccessCount(accSizeNow) == false) {
+ invalidRequest = true;
+ }
+ }
+ }
+ if (invalidRequest == false && hostCommand == RfidReaderChipData.HostCommands.CMD_18K6CWRITE) {
+ if (accWriteData.length() > accSizeNow * 4) accWriteDataNow = accWriteData.substring(0, accSizeNow*4);
+ else accWriteDataNow = accWriteData;
+ if (MainActivity.csLibrary4A.setAccessWriteData(accWriteDataNow) == false) {
+ invalidRequest = true;
+ }
+ }
+ MainActivity.csLibrary4A.appendToLog("HelloA: accOffset=" + accOffset + ", accSizeNow=" + accSizeNow + ", accSize=" + accSize);
+ MainActivity.csLibrary4A.appendToLog("HelloK: invalidRequest=" + invalidRequest);
+ accessTask = new AccessTask(button, invalidRequest, true,
+ selectMask, selectBank, selectOffset,
+ strPassword, powerLevel, hostCommand, tryCount==tryCountMax, updateRunnable);
+ }
+}
+
+
+
+package com.csl.cs710ademoapp.adapters;
+
+import android.content.Context;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.ArrayAdapter;
+import android.widget.TextView;
+
+import com.csl.cs710ademoapp.DrawerListContent;
+import com.csl.cs710ademoapp.R;
+
+import java.util.List;
+
+/**
+ * Class to handle the data for NavigationDrawer.
+ */
+public class DrawerListAdapter extends ArrayAdapter {
+ Context mContext;
+ List mData = null;
+
+ /**
+ * Construtor. Handles the initialization.
+ *
+ * @param context - context to be used
+ * @param resource - layout to be inflated
+ * @param objects - navidation drawer items
+ */
+ public DrawerListAdapter(Context context, int resource, List objects) {
+ super(context, resource, objects);
+ this.mContext = context;
+ this.mData = objects;
+ }
+
+ @Override
+ public View getView(int position, View convertView, ViewGroup parent) {
+ if (convertView == null) {
+ LayoutInflater inflater = (LayoutInflater) mContext
+ .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
+ convertView = inflater.inflate(R.layout.drawer_list_item, parent, false);
+ }
+
+ DrawerListContent.DrawerItem item = mData.get(position);
+ //Set the label
+ TextView label1 = (TextView) convertView.findViewById(R.id.drawerItemName);
+ label1.setText(item.content);
+ return convertView;
+ }
+}
+
+
+
+package com.csl.cs710ademoapp.adapters;
+
+import android.content.Context;
+import android.text.Html;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.ArrayAdapter;
+import android.widget.CheckedTextView;
+import android.widget.TextView;
+
+import com.csl.cs710ademoapp.MainActivity;
+import com.csl.cs710ademoapp.R;
+import com.csl.cslibrary4a.ReaderDevice;
+
+import java.util.ArrayList;
+
+public class ReaderListAdapter extends ArrayAdapter {
+ final boolean DEBUG = false;
+ private final Context context;
+ private final int resourceId;
+ private final ArrayList readersList;
+ private boolean select4detail, select4Rssi, selectDupElim, select4Extra1, select4Extra2;
+
+ public ReaderListAdapter(Context context, int resourceId, ArrayList readersList, boolean select4detail, boolean select4Rssi) {
+ super(context, resourceId, readersList);
+ this.context = context;
+ this.resourceId = resourceId;
+ this.readersList = readersList;
+ this.select4detail = select4detail;
+ this.select4Rssi = select4Rssi;
+ select4Extra1 = false;
+ select4Extra2 = false;
+ }
+
+ public ReaderListAdapter(Context context, int resourceId, ArrayList readersList, boolean select4detail, boolean select4Rssi, boolean selectDupElim, boolean select4Extra1, boolean select4Extra2) {
+ super(context, resourceId, readersList);
+ this.context = context;
+ this.resourceId = resourceId;
+ this.readersList = readersList;
+ this.select4detail = select4detail;
+ this.select4Rssi = select4Rssi;
+ this.selectDupElim = selectDupElim;
+ this.select4Extra1 = select4Extra1;
+ this.select4Extra2 = select4Extra2;
+ MainActivity.csLibrary4A.appendToLog("select4Extra1 = " + select4Extra1 + ", select4Extra2 = " + select4Extra2);
+ }
+
+ @Override
+ public View getView(int position, View convertView, ViewGroup parent) {
+ ReaderDevice reader = readersList.get(position);
+ if (convertView == null) {
+ LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
+ convertView = layoutInflater.inflate(resourceId, null);
+ }
+
+ CheckedTextView checkedTextView = (CheckedTextView) convertView.findViewById(R.id.reader_checkedtextview);
+ String text1 = "";
+ if (reader.getName() != null) {
+ if (reader.getName().length() != 0) {
+ text1 += reader.getName();
+ }
+ }
+ if (reader.getAddress() != null) {
+ if (reader.getAddress().length() != 0) {
+ if (text1.length() != 0) text1 += "\n";
+ text1 += reader.getAddress();
+ }
+ }
+ if (reader.getUpcSerial() != null) {
+ if (reader.getUpcSerial().length() != 0) {
+ if (text1.length() != 0) text1 += "\n";
+ text1 += reader.getUpcSerial();
+ }
+ }
+ if (MainActivity.csLibrary4A.isBleScanning()) {
+ if (reader.getServiceUUID2p1() == 0 || reader.getServiceUUID2p1() == 1) text1 += "\nCS108 Reader";
+ else if (reader.getServiceUUID2p1() == 2 || reader.getServiceUUID2p1() == 3) text1 += "\nCS710S Reader";
+ else if (reader.getServiceUUID2p1() == 4) text1 += "\nCS463 Reader";
+ else if (reader.getServiceUUID2p1() == 5) text1 += "\nCS203XL Reader";
+ else if (reader.getServiceUUID2p1() == 6) text1 += "\nConnected paired devices";
+ }
+ checkedTextView.setText(text1);
+ if (reader.getSelected()) {
+ checkedTextView.setChecked(true);
+ } else {
+ checkedTextView.setChecked(false);
+ }
+
+ TextView countTextView = (TextView) convertView.findViewById(R.id.reader_count);
+ if (reader.getCount() != 0) {
+ countTextView.setText(String.valueOf(reader.getCount()));
+ } else {
+ countTextView.setVisibility(View.GONE);
+ }
+
+ if (select4Rssi) {
+ TextView rssiTextView = (TextView) convertView.findViewById(R.id.reader_rssi);
+ rssiTextView.setVisibility(View.VISIBLE);
+ double rssiValue = reader.getRssi();
+ if (MainActivity.csLibrary4A.getRssiDisplaySetting() != 0 && rssiValue > 0)
+ rssiValue -= MainActivity.csLibrary4A.dBuV_dBm_constant;
+ rssiTextView.setText(String.format("%.1f", rssiValue));
+ }
+
+ if (select4Extra1) {
+ TextView portTextView = (TextView) convertView.findViewById(R.id.reader_extra1);
+ portTextView.setVisibility(View.VISIBLE);
+ int portValue = reader.getPort() + 1;
+ portTextView.setText(String.valueOf(portValue));
+ }
+
+ if (select4Extra2) {
+ TextView portTextView = (TextView) convertView.findViewById(R.id.reader_extra2);
+ portTextView.setVisibility(View.VISIBLE);
+ int codeStatus = reader.getStatus();
+ int codeSensor = reader.getCodeSensor(); int codeRssi = reader.getCodeRssi(); float codeTempC = reader.getCodeTempC();
+ String brand = reader.getBrand();
+ String strExtra = "";
+ if (codeStatus > reader.INVALID_STATUS) { //for Bap tags
+ int portstatus = reader.getStatus(); if (portstatus > reader.INVALID_STATUS) {
+ if ((portstatus & 2) == 0) strExtra += "Bat OK";
+ else strExtra += "Bat NG";
+ if ((portstatus & 4) != 0) strExtra += "\nTemper NG";
+ }
+ } else if (codeSensor > reader.INVALID_CODESENSOR && codeRssi > reader.INVALID_CODERSSI) { //for Axzon/Magnus tags
+ strExtra = "SC=" + String.format("%d", codeSensor);
+ int iHumidityThreshold = Integer.parseInt(MainActivity.config.config3);
+ if (false && reader.getCodeSensorMax() > 0) {
+ float fValue = (float) codeSensor;
+ fValue /= (float) reader.getCodeSensorMax();
+ fValue *= 100;
+ strExtra += "\nSC=" + String.format("%.1f", fValue) + "%";
+ } else if (iHumidityThreshold > 0) {
+ strExtra += "\nSC=" + (codeSensor >= iHumidityThreshold ? "Dry" : "Wet");
+ }
+ int ocrssiMin = -1; int ocrssiMax = -1; boolean bValidOcrssi = false;
+ ocrssiMax = Integer.parseInt(MainActivity.config.config1);
+ ocrssiMin = Integer.parseInt(MainActivity.config.config2);
+ if (ocrssiMax > 0 && ocrssiMin > 0 && (codeRssi > ocrssiMax || codeRssi < ocrssiMin)) strExtra += ("\nOCRSSI=" + String.format("%d", codeRssi) + "");
+ else {
+ bValidOcrssi = true; strExtra += ("\nOCRSSI=" + String.format("%d", codeRssi));
+ }
+ if (codeTempC > reader.INVALID_CODETEMPC) {
+ if (bValidOcrssi || portTextView.getText().toString().indexOf("T=") >= 0)
+ strExtra += ("\nT=" + String.format("%.1f", codeTempC) + (char) 0x00B0 + "C");
+ }
+ int backport = reader.getBackport1(); if (backport > reader.INVALID_BACKPORT) strExtra += String.format("\nBP1=%d", backport);
+ backport = reader.getBackport2(); if (backport > reader.INVALID_BACKPORT) strExtra += String.format("\nBP2=%d", backport);
+ } else if (codeTempC > reader.INVALID_CODETEMPC) { //for Ctesius tags
+ strExtra = ("T=" + String.format("%.1f", codeTempC) + (char) 0x00B0 + "C");
+ } else if (brand != null) { //reader.getDetails().contains("E2806894")) { //for code8 tags
+ strExtra = ((brand != null) ? ("Brand=" + brand) : "");
+ } else if (reader.getSensorData() < reader.INVALID_SENSORDATA) {
+ strExtra = "SD=" + String.valueOf(reader.getSensorData());
+ }
+ portTextView.setText(Html.fromHtml(strExtra));
+ }
+
+ TextView readerDetailA = (TextView) convertView.findViewById(R.id.reader_detailA);
+ TextView readerDetailB = (TextView) convertView.findViewById(R.id.reader_detailB);
+ if (reader.isConnected() || checkedTextView.isChecked() || select4detail == false) {
+ readerDetailA.setText(reader.getDetails());
+ readerDetailB.setText("");
+ if (reader.isConnected()) {
+ readerDetailB.setText("Connected");
+ } else {
+ int channel = reader.getChannel();
+ int phase = reader.getPhase();
+ String stringDetailB = null;
+ if (channel != 0 || phase != 0) {
+ double dChannel = MainActivity.csLibrary4A.getLogicalChannel2PhysicalFreq(reader.getChannel());
+ stringDetailB = "Phase=" + phase + "\n" + dChannel + "MHz";
+ }
+ if (stringDetailB != null) readerDetailB.setText(stringDetailB);
+ }
+ if (readerDetailA.getText().toString().length() != 0 || readerDetailB.getText().toString().length() != 0) {
+ readerDetailA.setVisibility(View.VISIBLE);
+ readerDetailB.setVisibility(View.VISIBLE);
+ } else {
+ readerDetailA.setVisibility(View.GONE);
+ readerDetailB.setVisibility(View.GONE);
+ }
+ } else {
+ readerDetailA.setVisibility(View.GONE);
+ readerDetailB.setVisibility(View.GONE);
+ }
+ return convertView;
+ }
+
+ public boolean getSelectDupElim() { return selectDupElim; }
+ public void setSelectDupElim(boolean selectDupElim) { this.selectDupElim = selectDupElim; }
+}
+
+
+
+package com.csl.cs710ademoapp;
+
+import android.app.Activity;
+import android.app.AlertDialog;
+import android.content.DialogInterface;
+
+public class CustomAlertDialog {
+ Runnable ans_true = null;
+ Runnable ans_false = null;
+ AlertDialog dialog = null;
+ public boolean Confirm(Activity act, String Title, String ConfirmText,
+ String CancelBtn, String OkBtn, Runnable aProcedure, Runnable bProcedure) {
+ ans_true = aProcedure;
+ ans_false= bProcedure;
+ dialog = new AlertDialog.Builder(act).create();
+ dialog.setTitle(Title);
+ dialog.setMessage(ConfirmText);
+ dialog.setCancelable(false);
+ dialog.setButton(DialogInterface.BUTTON_POSITIVE, OkBtn,
+ new DialogInterface.OnClickListener() {
+ public void onClick(DialogInterface dialog, int buttonId) {
+ ans_true.run();
+ }
+ });
+ dialog.setButton(DialogInterface.BUTTON_NEGATIVE, CancelBtn,
+ new DialogInterface.OnClickListener() {
+ public void onClick(DialogInterface dialog, int buttonId) {
+ ans_false.run();
+ }
+ });
+ dialog.setIcon(R.drawable.alert);
+ dialog.show();
+ return true;
+ }
+
+ public boolean isShowing() {
+ if (dialog != null) return dialog.isShowing();
+ else return false;
+ }
+}
+
+
+
+package com.csl.cs710ademoapp;
+
+import android.inputmethodservice.InputMethodService;
+import android.inputmethodservice.Keyboard;
+import android.inputmethodservice.KeyboardView;
+import android.os.AsyncTask;
+import android.os.Handler;
+import android.provider.Settings;
+import android.util.Log;
+import android.view.View;
+import android.view.inputmethod.InputConnection;
+
+import com.csl.cslibrary4a.RfidReaderChipData;
+
+import java.io.IOException;
+import java.net.DatagramPacket;
+import java.net.DatagramSocket;
+import java.net.InetAddress;
+import java.net.SocketException;
+import java.util.ArrayList;
+
+import static android.content.ContentValues.TAG;
+
+public class CustomIME extends InputMethodService { //implements KeyboardView.OnKeyboardActionListener {
+ Handler mHandler = new Handler();
+ InputConnection ic;
+ DatagramSocket datagramSocket;
+ InetAddress hostAddress = null;
+
+ @Override
+ public void onCreate() {
+ super.onCreate();
+ try {
+ hostAddress = hostAddress = InetAddress.getByName("127.0.0.1");
+ Log.i("Hello", "udpSocket hostAddress is valid");
+ datagramSocket = new DatagramSocket(9394, hostAddress);
+ if (datagramSocket == null) Log.i("Hello", "udpSocket is null");
+ else Log.i("Hello", "udpSocket is valid");
+ //byte[] buffer = new byte[16];
+ //DatagramPacket packet = new DatagramPacket(buffer, buffer.length, InetAddress.getByName("localhost"), 14552);
+ //udpsocket.send(packet);
+ } catch (SocketException e) {
+ Log.e("UDP: ", "udpSocket Socket Error: ", e);
+ } catch (IOException e) {
+ Log.e("UDP Send: ", "udpSocket IO Error", e);
+ } catch (Exception ex) {
+ Log.i("Hello", "udpSocket Exception Error: " + ex.getMessage());
+ }
+ appendToLog("CustomIME.onCreate()");
+ }
+ @Override
+ public View onCreateInputView() {
+ super.onCreateInputView();;
+ mHandler.post(serviceRunnable);
+ KeyboardView keyboardView = null;
+ if (true) {
+ keyboardView = (KeyboardView) getLayoutInflater().inflate(R.layout.keyboard_view, null);
+ Keyboard keyboard = new Keyboard(this, R.xml.number_pad1);
+ keyboardView.setKeyboard(keyboard);
+ //keyboardView.setOnKeyboardActionListener(this);
+ }
+ ic = getCurrentInputConnection();
+ Log.i("Hello", "udpSocket inputConnection is " + (ic == null ? "null" : "valid"));
+ return keyboardView;
+ }
+ @Override
+ public void onDestroy() {
+ appendToLog("CustomIME.onDestroy()");
+ mHandler.removeCallbacks(serviceRunnable);
+ datagramSocket.close();
+ super.onDestroy();
+ }
+
+ Runnable yourRunnable = new Runnable() {
+ @Override
+ public void run() {
+ byte[] buffer = new byte[250];
+ Log.i("Hello", "udpSocket yourRunnable starts");
+ DatagramPacket datagramPacket = new DatagramPacket(buffer, buffer.length);
+ ic = getCurrentInputConnection();
+ try {
+ Log.i("Hello", "udpSocket try starts");
+// String outString = "Client say: bye bye";
+// buffer = outString.getBytes();
+// DatagramPacket outDatagramPackat = new DatagramPacket(buffer, buffer.length, hostAddress, 9394);
+// datagramSocket.send(outDatagramPackat);
+// Log.i("Hello", "udpSocket sent data");
+
+ String strDataReceived;
+ do {
+ strDataReceived = null;
+ datagramSocket.receive(datagramPacket);
+ strDataReceived = new String(datagramPacket.getData(), 0, datagramPacket.getLength());
+ Log.i("Hello", "udpSocket received data: " + strDataReceived);
+ ic.commitText(strDataReceived, 1);
+ } while (strDataReceived != null && strDataReceived.length() != 0);
+ } catch (IOException ex) {
+ Log.i("Hello", "udpSocket receive IOException Error: " + ex.toString());
+ }
+ }
+ };
+
+ ArrayList epcArrayList = new ArrayList();
+ InventoryRfidTask inventoryRfidTask;
+ InventoryBarcodeTask inventoryBarcodeTask;
+ boolean inventoring = false;
+ private Runnable serviceRunnable = new Runnable() {
+ @Override
+ public void run() {
+ String strCurrentIME = Settings.Secure.getString(getContentResolver(), Settings.Secure.DEFAULT_INPUT_METHOD);
+ String strCompare = getPackageName();
+ appendToLog("CustomIME Debug 0 with strCurrentIME = " + strCurrentIME + ", strCompare = " + strCompare);
+ if (strCurrentIME.contains(strCompare) == false) { }
+ else if (MainActivity.sharedObjects == null || MainActivity.csLibrary4A == null) {
+ if (false) { new Thread(yourRunnable).start(); }
+ }
+ else if (MainActivity.mContext == null) return;
+ else {
+ if (inventoring == false) {
+ MainActivity.sharedObjects.serviceArrayList.clear();
+ epcArrayList.clear();
+ }
+ appendToLog("CustomIME Debug 1 with activityActive = " + MainActivity.activityActive + ", wedged = " + MainActivity.wedged + ", isBleConnected = " + MainActivity.csLibrary4A.isBleConnected());
+ if (MainActivity.activityActive == false /*&& MainActivity.wedged*/ && MainActivity.csLibrary4A.isBleConnected()) {
+ if (MainActivity.csLibrary4A.getTriggerButtonStatus() == false) {
+ appendToLog("CustomIME Debug 2 with runningInventoryRfidTask = " + MainActivity.sharedObjects.runningInventoryRfidTask);
+ appendToLog("CustomIME Debug 2 with runningInventoryBarcodeTask = " + MainActivity.sharedObjects.runningInventoryBarcodeTask);
+ startStopHandler();
+ inventoring = false;
+ } else if (inventoring == false) {
+ appendToLog("CustomIME Debug 3 with runningInventoryRfidTask = " + MainActivity.sharedObjects.runningInventoryRfidTask + ", and mrfidToWriteSize = " + MainActivity.csLibrary4A.mrfidToWriteSize());
+ appendToLog("CustomIME Debug 3 with runningInventoryBarcodeTask = " + MainActivity.sharedObjects.runningInventoryBarcodeTask);
+ if (MainActivity.sharedObjects.runningInventoryRfidTask == false && MainActivity.sharedObjects.runningInventoryBarcodeTask == false && MainActivity.csLibrary4A.mrfidToWriteSize() == 0) {
+ startStopHandler();
+ inventoring = true;
+ }
+ } else {
+ appendToLog("CustomIME Debug 4");
+ while (MainActivity.sharedObjects.serviceArrayList.size() != 0) {
+ String strEpc = MainActivity.sharedObjects.serviceArrayList.get(0);
+ MainActivity.sharedObjects.serviceArrayList.remove(0);
+ appendToLog("CustomIME Debug 4A with strEpc = " + strEpc);
+ String strSgtin = null;
+ if (MainActivity.csLibrary4A.getWedgeOutput() == 1) {
+ strSgtin = MainActivity.csLibrary4A.getUpcSerial(strEpc);
+ appendToLog("strSgtin = " + (strSgtin == null ? "null" : strSgtin));
+ if (strSgtin == null) strEpc = null;
+ }
+ boolean matched = false;
+ if (epcArrayList != null && strEpc != null) {
+ for (int i = 0; i < epcArrayList.size(); i++) {
+ if (epcArrayList.get(i).matches(strEpc)) {
+ matched = true;
+ break;
+ }
+ }
+ }
+ if (matched == false && strEpc != null) {
+ epcArrayList.add(strEpc);
+ InputConnection ic = getCurrentInputConnection();
+ String strValue = strEpc;
+ if (strSgtin != null) strValue = strSgtin;
+ if (MainActivity.csLibrary4A.getWedgePrefix() != null)
+ strValue = MainActivity.csLibrary4A.getWedgePrefix() + strValue;
+ if (MainActivity.csLibrary4A.getWedgeSuffix() != null)
+ strValue += MainActivity.csLibrary4A.getWedgeSuffix();
+ appendToLog("CustomIME, serviceRunnable: wedgeDelimiter = " + MainActivity.csLibrary4A.getWedgeDelimiter());
+ switch (MainActivity.csLibrary4A.getWedgeDelimiter()) {
+ default:
+ strValue += "\n";
+ break;
+ case 0x09:
+ strValue += "\t";
+ break;
+ case 0x2C:
+ strValue += ",";
+ break;
+ case 0x20:
+ strValue += " ";
+ break;
+ case -1:
+ break;
+ }
+ appendToLog("CustomIME BtData to Keyboard: " + strValue);
+ ic.commitText(strValue, 1);
+ }
+ }
+ }
+ }
+ }
+ int iDelayms = 500;
+ if (inventoring) iDelayms = 100;
+ appendToLog("CustomIME BtData set next time as " + iDelayms);
+ mHandler.postDelayed(serviceRunnable, iDelayms);
+ }
+ };
+
+ public void appendToLog(String s) {
+ Log.i(TAG + ".Hello", s);
+ }
+ void startStopHandler() {
+ boolean started = false;
+ if (inventoryRfidTask != null) {
+ if (inventoryRfidTask.getStatus() == AsyncTask.Status.RUNNING) started = true;
+ }
+ if (inventoryBarcodeTask != null) {
+ if (inventoryBarcodeTask.getStatus() == AsyncTask.Status.RUNNING) started = true;
+ }
+ appendToLog("CustomIME Debug 10");
+ if ((started && MainActivity.csLibrary4A.getTriggerButtonStatus()) || (started == false && MainActivity.csLibrary4A.getTriggerButtonStatus() == false)) return;
+ if (started == false) {
+ appendToLog("CustomIME Debug 11 with BtData wedgeOutput = " + MainActivity.csLibrary4A.getWedgeOutput());
+ if (MainActivity.csLibrary4A.getWedgeOutput() == 2) {
+ inventoryBarcodeTask = new InventoryBarcodeTask();
+ inventoryBarcodeTask.execute();
+ } else {
+ MainActivity.csLibrary4A.setPowerLevel(MainActivity.csLibrary4A.getWedgePower());
+ MainActivity.csLibrary4A.appendToLog("Debug_Compact: CustomIME.startStopHandler");
+ MainActivity.csLibrary4A.startOperation(RfidReaderChipData.OperationTypes.TAG_INVENTORY_COMPACT);
+ inventoryRfidTask = new InventoryRfidTask();
+ inventoryRfidTask.execute();
+ }
+ } else {
+ appendToLog("CustomIME Debug 11");
+ if (inventoryRfidTask != null) inventoryRfidTask.taskCancelReason = InventoryRfidTask.TaskCancelRReason.BUTTON_RELEASE;
+ if (inventoryBarcodeTask != null) inventoryBarcodeTask.taskCancelReason = InventoryBarcodeTask.TaskCancelRReason.BUTTON_RELEASE;
+ }
+ }
+}
+
+
+
+package com.csl.cs710ademoapp;
+
+import android.content.Context;
+import android.content.res.AssetFileDescriptor;
+import android.media.AudioManager;
+import android.media.MediaPlayer;
+
+import java.io.IOException;
+
+public class CustomMediaPlayer {
+ final boolean DEBUG = false;
+ Context context;
+ MediaPlayer player; boolean starting = false;
+
+ public CustomMediaPlayer(Context context, String file) {
+ this.context = context;
+ player = null;
+ try {
+ AssetFileDescriptor afd = context.getAssets().openFd(file);
+ player = new MediaPlayer();
+ player.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
+ player.prepare();
+ player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
+ @Override
+ public void onCompletion(MediaPlayer mp) {
+ starting = false;
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("MediaPlayer is completed.");
+ }
+ });
+ } catch (IOException e) {
+ MainActivity.csLibrary4A.appendToLog("mp3 setup FAIL");
+ }
+ }
+
+ public void start() {
+ player.start();
+ if (false) starting = true;
+ }
+ public boolean isPlaying() {
+ return (player.isPlaying() | starting) ;
+ }
+ public void pause() {
+ player.pause();
+ }
+ void setVolume(int volume1, int volume2) {
+ if (false) player.setVolume(volume1, volume2);
+ else {
+ AudioManager audioManager = ((AudioManager) context.getSystemService(Context.AUDIO_SERVICE));
+ int iVolumeMax = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
+ int currentVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
+ MainActivity.csLibrary4A.appendToLog("Hello8: currentVolume = " + currentVolume);
+ if (currentVolume > 0) {
+ int volume12 = volume1 + volume2;
+ volume12 = ( volume12 * iVolumeMax ) / 600;
+ audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, iVolumeMax, 0);
+ }
+ }
+ }
+}
+
+
+
+package com.csl.cs710ademoapp;
+
+import android.content.Context;
+import android.view.Gravity;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.Button;
+import android.widget.PopupWindow;
+import android.widget.TextView;
+
+import static android.content.Context.LAYOUT_INFLATER_SERVICE;
+import static com.csl.cs710ademoapp.MainActivity.csLibrary4A;
+
+public class CustomPopupWindow {
+ Context context;
+ public CustomPopupWindow(Context context) {
+ this.context = context;
+ }
+
+ public PopupWindow popupWindow;
+ public void popupStart(String message, boolean wait) {
+ LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(LAYOUT_INFLATER_SERVICE);
+ View popupView = layoutInflater.inflate(R.layout.popup, null);
+ popupWindow = new PopupWindow(popupView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
+ popupWindow.showAtLocation(popupView, Gravity.CENTER, 0, 0);
+ TextView textViewDismiss = (TextView)popupView.findViewById(R.id.dismissMessage);
+ //int iLenghtMax = 300;
+ //if (message.length() > iLenghtMax) message = message.substring(0, iLenghtMax) + " .....";
+ csLibrary4A.appendToLog("SaveList2ExternalTask: popupStart message = " + message);
+ textViewDismiss.setText(message);
+ Button btnDismiss = (Button)popupView.findViewById(R.id.dismiss);
+ if (wait) btnDismiss.setVisibility(View.GONE);
+ else {
+ btnDismiss.setOnClickListener(new Button.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ popupWindow.dismiss();
+ }
+ });
+ }
+ }
+}
+
+
+
+package com.csl.cs710ademoapp;
+
+import android.app.ProgressDialog;
+import android.content.Context;
+
+public class CustomProgressDialog extends ProgressDialog {
+ public CustomProgressDialog(Context context, String message) {
+ super(context, ProgressDialog.STYLE_SPINNER);
+ if (message == null) message = "Progressing. Please wait.";
+ setTitle(null);
+ setMessage(message);
+ setCancelable(false);
+ }
+}
+
+
+
+package com.csl.cs710ademoapp;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Class to hold the data for Navigation Drawer Items
+ */
+public class DrawerListContent {
+ //An array of sample (Settings) items.
+ public static List ITEMS = new ArrayList<>();
+
+ //A map of sample (Settings) items, by ID.
+ public static Map ITEM_MAP = new HashMap<>();
+
+ public enum DrawerPositions {
+ MAIN, SPECIAL,
+ ABOUT, CONNECT,
+ INVENTORY, SEARCH, MULTIBANK,
+ SETTING, FILTER, READWRITE, SECURITY,
+
+ IMPINVENTORY, IMP775, IMPAUTOTUNE,
+ ALIEN,
+ UCODE8, UCODEDNA,
+ BAPCARD, COLDCHAIN, AURASENSE,
+ KILOWAY,
+ LONGJING,
+ AXZON, RFMICRON,
+ FDMICRO,
+ CTESIUS,
+ ASYGNTAG,
+
+ REGISTER, READWRITEUSER, WEDGE, DIRECTWEDGE, SIMINVENTORY,
+ BLANK;
+
+ public static DrawerPositions toDrawerPosition(int x) {
+ switch(x) {
+ case 0: return ABOUT;
+ case 1: return CONNECT;
+ case 2: return INVENTORY;
+ case 3: return SEARCH;
+ case 4: return MULTIBANK;
+ case 5: return SIMINVENTORY;
+ case 6: return SETTING;
+ case 7: return FILTER;
+ case 8: return READWRITE;
+ case 9: return SECURITY;
+
+ case 10: return IMPINVENTORY;
+ case 11: return ALIEN;
+ case 12: return UCODE8;
+ case 13: return UCODEDNA;
+ case 14: return BAPCARD;
+ case 15: return COLDCHAIN;
+ case 16: return AURASENSE;
+ case 17: return KILOWAY;
+ case 18: return LONGJING;
+ case 19: return AXZON;
+ //case 18: return RFMICRON;
+ case 20: return FDMICRO;
+ case 21: return CTESIUS;
+ case 22: return ASYGNTAG;
+
+ case 23: return REGISTER;
+ case 24: return READWRITEUSER;
+ case 25: return WEDGE;
+ case 26: return DIRECTWEDGE;
+ }
+ return null;
+ }
+ }
+
+ static {
+ // Add items.
+ addItem(new DrawerItem("0", "About", R.drawable.dl_about));
+ addItem(new DrawerItem("1", "Connect", R.drawable.dl_rdl));
+ addItem(new DrawerItem("2", "Inventory", R.drawable.dl_inv));
+ addItem(new DrawerItem("3", "Geiger Search", R.drawable.dl_loc));
+ addItem(new DrawerItem("4", "Multi-bank Inventory", R.drawable.dl_inv));
+ addItem(new DrawerItem("5", "Simple Inventory", R.drawable.dl_rr));
+ addItem(new DrawerItem("6", "Settings", R.drawable.dl_sett));
+ addItem(new DrawerItem("7", "Filters", R.drawable.dl_filters));
+ addItem(new DrawerItem("8", "Read/Write", R.drawable.dl_access));
+ addItem(new DrawerItem("9", "Security", R.drawable.dl_access));
+
+ addItem(new DrawerItem("10", "Impinj Special Features", R.drawable.dl_loc));
+ addItem(new DrawerItem("11", "Alien", R.drawable.dl_loc));
+ addItem(new DrawerItem("12", "NXP UCODE 8", R.drawable.dl_loc));
+ addItem(new DrawerItem("13", "NXP UCODE DNA", R.drawable.dl_loc));
+ addItem(new DrawerItem("14", "uEm CS9010 BAP ID Card", R.drawable.dl_loc));
+ addItem(new DrawerItem("15", "uEm Cold Chain CS8300", R.drawable.dl_loc));
+ addItem(new DrawerItem("16", "uEm Aura-sense", R.drawable.dl_loc));
+ addItem(new DrawerItem("17", "Kiloway KX2005X-BL", R.drawable.dl_rr));
+ addItem(new DrawerItem("18", "EL-N2ESL CS6861", R.drawable.dl_rr));
+ addItem(new DrawerItem("19", "Axzon", R.drawable.dl_loc));
+ addItem(new DrawerItem("20", "FM13DT160", R.drawable.dl_loc));
+ addItem(new DrawerItem("21", "Landa CTESIUS", R.drawable.dl_loc));
+ addItem(new DrawerItem("22", "Asygn AS321x", R.drawable.dl_loc));
+
+ addItem(new DrawerItem("23", "Register Tag", R.drawable.dl_rr));
+ addItem(new DrawerItem("24", "Large sized memory read/write", R.drawable.dl_rr));
+ addItem(new DrawerItem("25", "Wedge", R.drawable.dl_rr));
+ addItem(new DrawerItem("26", "Direct Wedge", R.drawable.dl_rr));
+ }
+
+ private static void addItem(DrawerItem item) {
+
+ ITEMS.add(item);
+ ITEM_MAP.put(item.id, item);
+ }
+
+ public static class DrawerItem {
+ public String id;
+ public String content;
+ public int icon;
+
+ public DrawerItem(String id, String content, int icon_id) {
+ this.id = id;
+ this.content = content;
+ this.icon = icon_id;
+ }
+
+ @Override
+ public String toString() {
+ return content;
+ }
+ }
+}
+
+
+
+package com.csl.cs710ademoapp.fragments;
+
+import android.os.Bundle;
+import android.os.Handler;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.TextView;
+
+import androidx.appcompat.app.ActionBar;
+import androidx.appcompat.app.AppCompatActivity;
+
+import com.csl.cs710ademoapp.BuildConfig;
+import com.csl.cs710ademoapp.MainActivity;
+import com.csl.cs710ademoapp.R;
+
+public class AboutFragment extends CommonFragment {
+ Handler mHandler = new Handler();
+ long timeMillis = 0;
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ super.onCreateView(inflater, container, savedInstanceState, true);
+ return inflater.inflate(R.layout.fragment_about, container, false);
+ }
+
+ @Override
+ public void onActivityCreated(Bundle savedInstanceState) {
+ super.onActivityCreated(savedInstanceState);
+
+ ActionBar actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
+ actionBar.setIcon(R.drawable.dl_about);
+ actionBar.setTitle(R.string.title_activity_about);
+
+ TextView appVersionView = (TextView) getActivity().findViewById(R.id.appVersion);
+ appVersionView.setText(BuildConfig.VERSION_NAME);
+ TextView libVersionView = (TextView) getActivity().findViewById(R.id.libVersion);
+ libVersionView.setText(MainActivity.csLibrary4A.getlibraryVersion());
+
+ MainActivity.mSensorConnector.mLocationDevice.turnOn(true);
+ MainActivity.mSensorConnector.mSensorDevice.turnOn(true);
+ mHandler.post(updateRunnable);
+ }
+
+ @Override
+ public void onDestroy() {
+ MainActivity.mSensorConnector.mLocationDevice.turnOn(false);
+ MainActivity.mSensorConnector.mSensorDevice.turnOn(false);
+ mHandler.removeCallbacks(updateRunnable);
+ super.onDestroy();
+ }
+
+ public AboutFragment() {
+ super("AboutFragment");
+ }
+
+ private final Runnable updateRunnable = new Runnable() {
+ @Override
+ public void run() {
+ TextView timeStampView = (TextView) getActivity().findViewById(R.id.timeStamp);
+ TextView locationView = (TextView) getActivity().findViewById(R.id.GeoLocation);
+ TextView eCompassView = (TextView) getActivity().findViewById(R.id.eCompass);
+
+ TextView radioVersion = (TextView) getActivity().findViewById(R.id.radioVersion);
+ TextView modelVersion = (TextView) getActivity().findViewById(R.id.modelVersion);
+ TextView moduleRfidOnStatus = (TextView) getActivity().findViewById(R.id.moduleRfid_onStatus);
+ TextView moduleBarOnStatus = (TextView) getActivity().findViewById(R.id.moduleBar_onStatus);
+ TextView triggerOnStatus = (TextView) getActivity().findViewById(R.id.trigger_onStatus);
+ TextView moduleBattery = (TextView) getActivity().findViewById(R.id.module_battery);
+ TextView moduleVersionLabel = (TextView) getActivity().findViewById(R.id.module_versionLabel);
+ if (MainActivity.csLibrary4A.get98XX() == 2) moduleVersionLabel.setText("Atmel firmware version");
+ else if (MainActivity.csLibrary4A.get98XX() == 0) moduleVersionLabel.setText("SiliconLab firmware version");
+ TextView moduleVersion = (TextView) getActivity().findViewById(R.id.module_version);
+ TextView radioSerial = (TextView) getActivity().findViewById(R.id.radio_serialnumber);
+ TextView radioBoardVersion = (TextView) getActivity().findViewById(R.id.radio_boardVersion);
+ TextView productSerial = (TextView) getActivity().findViewById(R.id.module_productserialnumber);
+ TextView boardVersion = (TextView) getActivity().findViewById(R.id.module_boardversion);
+ TextView barcodeSerial = (TextView) getActivity().findViewById(R.id.moduleBar_serialNumber);
+ TextView barcodeDate = (TextView) getActivity().findViewById(R.id.moduleBar_date);
+ TextView barcodeVersion = (TextView) getActivity().findViewById(R.id.moduleBar_version);
+
+ TextView bluetoothVersion = (TextView) getActivity().findViewById(R.id.bluetooth_version);
+ TextView bluetoothAddress = (TextView) getActivity().findViewById(R.id.bluetooth_address);
+ TextView bluetoothRssi = (TextView) getActivity().findViewById(R.id.bluetooth_rssi);
+
+ timeStampView.setText(MainActivity.mSensorConnector.getTimeStamp());
+ locationView.setText(MainActivity.mSensorConnector.mLocationDevice.getLocation());
+ eCompassView.setText(MainActivity.mSensorConnector.mSensorDevice.getEcompass());
+ if (MainActivity.csLibrary4A.isBleConnected()) {
+ if (System.currentTimeMillis() - timeMillis > 5000) {
+ timeMillis = System.currentTimeMillis();
+ radioVersion.setText(MainActivity.csLibrary4A.getMacVer());
+ modelVersion.setText(MainActivity.csLibrary4A.getModelNumber());
+ moduleVersion.setText(MainActivity.csLibrary4A.hostProcessorICGetFirmwareVersion());
+ bluetoothVersion.setText(MainActivity.csLibrary4A.getBluetoothICFirmwareVersion());
+ MainActivity.csLibrary4A.batteryLevelRequest();
+ }
+ moduleRfidOnStatus.setText(MainActivity.csLibrary4A.getRfidOnStatus() ? "on" : "off");
+ triggerOnStatus.setText(MainActivity.csLibrary4A.getTriggerButtonStatus() ? "pressed" : "released");
+ moduleBarOnStatus.setText(MainActivity.csLibrary4A.getBarcodeOnStatus() ? "on" : "off");
+ moduleBattery.setText(MainActivity.csLibrary4A.getBatteryDisplay(true));
+ if (MainActivity.csLibrary4A.isRfidFailure()) radioSerial.setText("Not available");
+ else radioSerial.setText(MainActivity.csLibrary4A.getRadioSerial());
+ radioBoardVersion.setText(MainActivity.csLibrary4A.getRadioBoardVersion());
+ productSerial.setText(MainActivity.csLibrary4A.getHostProcessorICSerialNumber());
+ boardVersion.setText(MainActivity.csLibrary4A.getHostProcessorICBoardVersion());
+ if (MainActivity.csLibrary4A.isBarcodeFailure()) barcodeSerial.setText("Not available");
+ else {
+ barcodeSerial.setText(MainActivity.csLibrary4A.getBarcodeSerial());
+ barcodeDate.setText(MainActivity.csLibrary4A.getBarcodeDate());
+ barcodeVersion.setText(MainActivity.csLibrary4A.getBarcodeVersion());
+ }
+ bluetoothAddress.setText(MainActivity.csLibrary4A.getBluetoothDeviceAddress());
+ bluetoothRssi.setText(String.valueOf(MainActivity.csLibrary4A.getRssi()));
+ } else {
+ radioVersion.setText("");
+ moduleRfidOnStatus.setText("");
+ moduleBarOnStatus.setText("");
+ triggerOnStatus.setText("");
+ moduleBattery.setText("");
+ moduleVersion.setText("");
+ bluetoothVersion.setText("");
+ radioSerial.setText("");
+ radioBoardVersion.setText("");
+ productSerial.setText("");
+ boardVersion.setText("");
+ barcodeSerial.setText("");
+ bluetoothAddress.setText("");
+ bluetoothRssi.setText("");
+ }
+ mHandler.postDelayed(updateRunnable, 1000);
+ }
+ };
+}
+
+
+
+package com.csl.cs710ademoapp.fragments;
+
+import static com.csl.cs710ademoapp.MainActivity.tagSelected;
+import static com.csl.cslibrary4a.RfidReader.TagType.TAG_EM;
+import static com.csl.cslibrary4a.RfidReader.TagType.TAG_EM_AURASENSE;
+import static com.csl.cslibrary4a.RfidReader.TagType.TAG_EM_AURASENSE_ATBOOT;
+import static com.csl.cslibrary4a.RfidReader.TagType.TAG_EM_AURASENSE_ATSELECT;
+import static com.csl.cslibrary4a.RfidReader.TagType.TAG_EM_BAP;
+import static com.csl.cslibrary4a.RfidReader.TagType.TAG_EM_COLDCHAIN;
+
+import android.app.Activity;
+import android.os.AsyncTask;
+import android.os.Bundle;
+import android.text.InputType;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.AdapterView;
+import android.widget.ArrayAdapter;
+import android.widget.Button;
+import android.widget.CheckBox;
+import android.widget.EditText;
+import android.widget.LinearLayout;
+import android.widget.RadioButton;
+import android.widget.Spinner;
+import android.widget.TableRow;
+import android.widget.TextView;
+import android.widget.Toast;
+
+import com.csl.cs710ademoapp.AccessTask;
+import com.csl.cs710ademoapp.MainActivity;
+import com.csl.cs710ademoapp.R;
+import com.csl.cs710ademoapp.SelectTag;
+import com.csl.cslibrary4a.RfidReaderChipData;
+
+public class AccessAuraSenseFragment extends CommonFragment {
+ final boolean DEBUG = true;
+ Spinner spinnerTagSelect;
+ SelectTag selectTag;
+ RadioButton radioButtonAuraSensAtBoot, radioButtonAuraSensAtSelect;
+ TextView textViewAuraSensorDataOK, textViewAuraSystemConfigurationOK, textViewAuraSensorCalibrationOK, textViewAuraSensorControlOK, textViewAuraSensorDataStoredOK;
+ CheckBox checkBoxAuraSensorDataRCommandW, checkBoxAuraSystemConfiguration, checkBoxAuraCalibration, checkBoxAuraControl, checkBoxAuraDataStored;
+ EditText editTextAuraSensorData, editTextAuraSystemConfiguration, editTextAuraSensorCalibration, editTextAuraSensorDataStored;
+ CheckBox checkBoxAuraSensAtBootCheck, checkBoxAuraSensAtSelectCheck, checkBoxAuraSensWriteCheck;
+ TextView textViewConfigOk, textViewTemperatureOk, textViewEnableOk;
+ CheckBox checkBoxConfig, checkBoxTemperature, checkBoxEnable;
+ TextView textViewTemperature, textViewUnderAlarm, textViewOverAlarm, textViewBatteryAlarm;
+ EditText editTextTempThresUnder, editTextTempThresOver, editTextTempCountUnder, editTextTempCountOver, editTextMonitorDelay, editTextSamplingInterval;
+ Spinner spinnerDelayUnit, spinnerIntervalUnit, spinnerEnable;
+ Spinner spinnerCustomTagType;
+ TextView textViewCustomTagFound;
+ Button buttonCs8304StartLogging, buttonCs8304StopLogging, buttonCs8304CheckAlarm, buttonCs8304GetLogging;
+ TextView textViewCs8304StartLoggingStatus, textViewCs8304StopLoggingStatus, textViewCs8304CheckAlaramStatus, textViewCs8304GetLoggingStatus;
+
+ Button buttonRead, buttonWrite;
+
+ enum ReadWriteTypes {
+ NULL, AURA_SENSORDATARCOMMANDW, AURA_SYSTEMCONFIGURATION, AURA_CALIBRATION, AURA_CONTROL, AURA_DATASTORED,
+ COLDCHAIN_CONFIGURATION, COLDCHAIN_TEMPERATURE, COLDCHAIN_ENABLE,
+ STARTLOGGING, STOPLOGGING, CHECKLOGGING, GETLOGGING
+ }
+
+ enum eMicroTag {
+ emAuraSense, emColdChain, emBap, others
+ }
+ ReadWriteTypes readWriteTypes;
+ boolean operationRead = false;
+ boolean bRequestCheck;
+
+ private AccessTask accessTask;
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ super.onCreateView(inflater, container, savedInstanceState, false);
+ return inflater.inflate(R.layout.fragment_access_aurasense, container, false);
+ }
+
+ @Override
+ public void onActivityCreated(Bundle savedInstanceState) {
+ super.onActivityCreated(savedInstanceState);
+
+ spinnerTagSelect = (Spinner) getActivity().findViewById(R.id.accessEmicroTagSelect);
+ ArrayAdapter targetAdapter1 = ArrayAdapter.createFromResource(getActivity(), R.array.emicro_options, R.layout.custom_spinner_layout);
+ targetAdapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+ spinnerTagSelect.setAdapter(targetAdapter1); spinnerTagSelect.setSelection(0);
+ spinnerTagSelect.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
+ @Override
+ public void onItemSelected(AdapterView> parentView, View selectedItemView, int position, long id) {
+ LinearLayout layout0 = (LinearLayout) getActivity().findViewById(R.id.accessEmicroSelectLayout);
+ LinearLayout layout1 = (LinearLayout) getActivity().findViewById(R.id.accessEmMicroAuroSenseLayout);
+ LinearLayout layout2 = (LinearLayout) getActivity().findViewById(R.id.accessEmMicroColdChainLayout);
+ TableRow tableRow = (TableRow) getActivity().findViewById(R.id.accessEmicroCCTemperature);
+ if (MainActivity.csLibrary4A.get98XX() == 2) tableRow.setVisibility(View.GONE);
+ LinearLayout layout4 = (LinearLayout) getActivity().findViewById(R.id.accessCustomReadWrite);
+ if (position == eMicroTag.emAuraSense.ordinal()) {
+ MainActivity.tagType = TAG_EM_AURASENSE; MainActivity.mDid = "E280B12";
+ layout0.setVisibility(View.VISIBLE);
+ layout1.setVisibility(View.VISIBLE);
+ layout2.setVisibility(View.GONE);
+ layout4.setVisibility(View.VISIBLE);
+ } else if (position == eMicroTag.emColdChain.ordinal()) {
+ MainActivity.tagType = TAG_EM_COLDCHAIN; MainActivity.mDid = "E280B0";
+ layout0.setVisibility(View.VISIBLE);
+ layout1.setVisibility(View.GONE);
+ layout2.setVisibility(View.VISIBLE);
+ layout4.setVisibility(View.VISIBLE);
+ } else if (position == eMicroTag.emBap.ordinal()) {
+ MainActivity.tagType = TAG_EM_BAP; MainActivity.mDid = "E200B0";
+ layout0.setVisibility(View.GONE);
+ layout1.setVisibility(View.GONE);
+ layout2.setVisibility(View.GONE);
+ layout4.setVisibility(View.GONE);
+ } else {
+ MainActivity.tagType = TAG_EM; MainActivity.mDid = "E280B";
+ layout0.setVisibility(View.GONE);
+ layout1.setVisibility(View.GONE);
+ layout2.setVisibility(View.GONE);
+ layout4.setVisibility(View.GONE);
+ }
+ }
+
+ @Override
+ public void onNothingSelected(AdapterView> parentView) {
+ // your code here
+ }
+
+ });
+
+ selectTag = new SelectTag((Activity)getActivity(), 0);
+ selectTag.tableRowSelectMemoryBank.setVisibility(View.GONE);
+
+ radioButtonAuraSensAtBoot = (RadioButton) getActivity().findViewById(R.id.accessAuraSensAtBoot);
+ radioButtonAuraSensAtSelect = (RadioButton) getActivity().findViewById(R.id.accessAuraSensAtSelect);
+
+ textViewAuraSystemConfigurationOK = (TextView) getActivity().findViewById(R.id.accessAuraSystemConfigurationOK);
+ textViewAuraSensorCalibrationOK = (TextView) getActivity().findViewById(R.id.accessAuraSensorCalibrationOK);
+ textViewAuraSensorControlOK = (TextView) getActivity().findViewById(R.id.accessAuraSensorControlOK);
+ textViewAuraSensorDataStoredOK = (TextView) getActivity().findViewById(R.id.accessAuraSensorDataStoredOK);
+
+ checkBoxAuraSystemConfiguration = (CheckBox) getActivity().findViewById(R.id.accessAuraSystemConfigurationCheck);
+ checkBoxAuraCalibration = (CheckBox) getActivity().findViewById(R.id.accessAuraSensorCalibrationCheck);
+ checkBoxAuraControl = (CheckBox) getActivity().findViewById(R.id.accessAuraSensorControlCheck);
+ checkBoxAuraDataStored = (CheckBox) getActivity().findViewById(R.id.accessAuraSensorDataStoredCheck);
+
+ editTextAuraSensorData = (EditText) getActivity().findViewById(R.id.accessAuraSensorData); editTextAuraSensorData.setEnabled(false);
+ editTextAuraSystemConfiguration = (EditText) getActivity().findViewById(R.id.accessAuraSystemConfiguration); editTextAuraSystemConfiguration.setEnabled(false);
+ editTextAuraSensorCalibration = (EditText) getActivity().findViewById(R.id.accessAuraSensorCalibration); editTextAuraSensorCalibration.setInputType(InputType.TYPE_CLASS_NUMBER);
+ editTextAuraSensorDataStored = (EditText) getActivity().findViewById(R.id.accessAuraSensorDataStored); editTextAuraSensorDataStored.setEnabled(false);
+ checkBoxAuraSensAtBootCheck = (CheckBox) getActivity().findViewById(R.id.accessAuraSensAtBootCheck);
+ checkBoxAuraSensAtSelectCheck = (CheckBox) getActivity().findViewById(R.id.accessAuraSensAtSelectCheck);
+ checkBoxAuraSensWriteCheck = (CheckBox) getActivity().findViewById(R.id.accessAuraSensAtWriteCheck);
+
+ textViewConfigOk = (TextView) getActivity().findViewById(R.id.accessCCConfigOK);
+ textViewTemperatureOk = (TextView) getActivity().findViewById(R.id.accessCCTemperatureOK);
+ textViewEnableOk = (TextView) getActivity().findViewById(R.id.accessCCEnableOK);
+
+ checkBoxConfig = (CheckBox) getActivity().findViewById(R.id.accessCCConfigTitle);
+ checkBoxTemperature = (CheckBox) getActivity().findViewById(R.id.accessCCTemperatureTitle);
+ checkBoxEnable = (CheckBox) getActivity().findViewById(R.id.accessCCEnableTitle);
+
+ textViewTemperature = (TextView) getActivity().findViewById(R.id.accessCCTemperature);
+ textViewUnderAlarm = (TextView) getActivity().findViewById(R.id.accessCCUnderTempAlarm);
+ textViewOverAlarm = (TextView) getActivity().findViewById(R.id.accessCCOverTempAlarm);
+ textViewBatteryAlarm = (TextView) getActivity().findViewById(R.id.accessCCBatteryAlarm);
+
+ editTextTempThresUnder = (EditText) getActivity().findViewById(R.id.accessCCTempThresUnder);
+ editTextTempThresOver = (EditText) getActivity().findViewById(R.id.accessCCTempThresOver);
+ editTextTempCountUnder = (EditText) getActivity().findViewById(R.id.accessCCTempCountUnder);
+ editTextTempCountOver = (EditText) getActivity().findViewById(R.id.accessCCTempCountOver);
+ editTextMonitorDelay = (EditText) getActivity().findViewById(R.id.accessCCMonitorDelay);
+ editTextSamplingInterval = (EditText) getActivity().findViewById(R.id.accessCCSamplingInverval);
+
+ ArrayAdapter arrayAdapterUnit = ArrayAdapter.createFromResource(getActivity(), R.array.coldChain_unit_options, R.layout.custom_spinner_layout);
+ arrayAdapterUnit.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+ spinnerDelayUnit = (Spinner) getActivity().findViewById(R.id.accessCCMonitorUnit);
+ spinnerDelayUnit.setAdapter(arrayAdapterUnit);
+
+ ArrayAdapter arrayAdapterUnit1 = ArrayAdapter.createFromResource(getActivity(), R.array.coldChain_IntervalUnit_options, R.layout.custom_spinner_layout);
+ arrayAdapterUnit1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+ spinnerIntervalUnit = (Spinner) getActivity().findViewById(R.id.accessCCSamplingIntervalUnit);
+ spinnerIntervalUnit.setAdapter(arrayAdapterUnit1);
+
+ ArrayAdapter arrayAdapterEnable = ArrayAdapter.createFromResource(getActivity(), R.array.coldChain_enable_options, R.layout.custom_spinner_layout);
+ arrayAdapterEnable.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+ spinnerEnable = (Spinner) getActivity().findViewById(R.id.accessCCEnable);
+ spinnerEnable.setAdapter(arrayAdapterEnable);
+
+ textViewCustomTagFound = (TextView) getActivity().findViewById(R.id.accessCustomTagFound);
+/*
+ ArrayAdapter arrayAdapterTagType = ArrayAdapter.createFromResource(getActivity(), R.array.coldChain_tagtype_options, R.layout.custom_spinner_layout);
+ arrayAdapterTagType.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+ spinnerCustomTagType = (Spinner) getActivity().findViewById(R.id.selectCustomTagType);
+ spinnerCustomTagType.setAdapter(arrayAdapterTagType);
+ spinnerCustomTagType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
+ @Override
+ public void onItemSelected(AdapterView> parentView, View selectedItemView, int position, long id) {
+ switch(position) {
+ case 0:
+ LinearLayout linearLayout = (LinearLayout) getActivity().findViewById(R.id.accessCC8304Layout);
+ linearLayout.setVisibility(View.VISIBLE);
+ linearLayout = (LinearLayout) getActivity().findViewById(R.id.accessCCmaxduraLayout);
+ linearLayout.setVisibility(View.GONE);
+ break;
+ case 1:
+ linearLayout = (LinearLayout) getActivity().findViewById(R.id.accessCC8304Layout);
+ linearLayout.setVisibility(View.GONE);
+ linearLayout = (LinearLayout) getActivity().findViewById(R.id.accessCCmaxduraLayout);
+ linearLayout.setVisibility(View.VISIBLE);
+ break;
+ }
+ }
+
+ @Override
+ public void onNothingSelected(AdapterView> parentView) {
+ // your code here
+ }
+ });
+*/
+ buttonCs8304StartLogging = (Button) getActivity().findViewById(R.id.accessCs8304StartLogging);
+ buttonCs8304StartLogging.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (isOperationRunning()) return;
+ readWriteTypes = ReadWriteTypes.STARTLOGGING;
+ operationRead = true; startAccessTask();
+ }
+ });
+ buttonCs8304StopLogging = (Button) getActivity().findViewById(R.id.accessCs8304StopLogging);
+ buttonCs8304StopLogging.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (isOperationRunning()) return;
+ readWriteTypes = ReadWriteTypes.STOPLOGGING;
+ operationRead = true; startAccessTask();
+ }
+ });
+ buttonCs8304CheckAlarm = (Button) getActivity().findViewById(R.id.accessCs8304CheckAlarm);
+ buttonCs8304CheckAlarm.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (isOperationRunning()) return;
+ readWriteTypes = ReadWriteTypes.CHECKLOGGING;
+ operationRead = true; startAccessTask();
+ }
+ });
+ buttonCs8304GetLogging = (Button) getActivity().findViewById(R.id.accessCs8304GetLogging);
+ buttonCs8304GetLogging.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (isOperationRunning()) return;
+ readWriteTypes = ReadWriteTypes.GETLOGGING;
+ operationRead = true; startAccessTask();
+ }
+ });
+
+ textViewCs8304StartLoggingStatus = (TextView) getActivity().findViewById(R.id.accessCs8304StartLoggingStatus);
+ textViewCs8304StopLoggingStatus = (TextView) getActivity().findViewById(R.id.accessCs8304StopLoggingStatus);
+ textViewCs8304CheckAlaramStatus = (TextView) getActivity().findViewById(R.id.accessCs8304CheckAlarmStatus);
+ textViewCs8304GetLoggingStatus = (TextView) getActivity().findViewById(R.id.accessCs8304GetLoggingStatus);
+
+ buttonRead = (Button) getActivity().findViewById(R.id.accessRWReadButton);
+ buttonRead.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (isOperationRunning()) return;
+ textViewAuraSensorDataOK = (TextView) getActivity().findViewById(R.id.accessAuraSensorDataOK);
+ checkBoxAuraSensorDataRCommandW = (CheckBox) getActivity().findViewById(R.id.accessAuraSensorDataCheck);
+ readWriteTypes = ReadWriteTypes.NULL;
+ operationRead = true; startAccessTask();
+ }
+ });
+
+ buttonWrite = (Button) getActivity().findViewById(R.id.accessRWWriteButton);
+ buttonWrite.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (isOperationRunning()) return;
+ textViewAuraSensorDataOK = (TextView) getActivity().findViewById(R.id.accessAuraWriteSensorDataOK);
+ checkBoxAuraSensorDataRCommandW = (CheckBox) getActivity().findViewById(R.id.accessAuraWriteSensorDataCheck);
+ readWriteTypes = ReadWriteTypes.NULL;
+ operationRead = false; startAccessTask();
+ }
+ });
+
+ MainActivity.csLibrary4A.setSameCheck(false);
+ }
+
+ @Override
+ public void onDestroy() {
+ if (accessTask != null) accessTask.cancel(true);
+ MainActivity.csLibrary4A.setSameCheck(true);
+ super.onDestroy();
+ }
+
+ boolean userVisibleHint = false;
+ @Override
+ public void setUserVisibleHint(boolean isVisibleToUser) {
+ super.setUserVisibleHint(isVisibleToUser);
+ if(getUserVisibleHint()) {
+ if (selectTag != null) selectTag.updateBankSelected();
+ userVisibleHint = true;
+ if (textViewCustomTagFound != null) {
+ if (tagSelected != null) {
+ MainActivity.csLibrary4A.appendToLog("tagSelected = " + tagSelected.getUser());
+ if (tagSelected.getUser() != null && tagSelected.getUser().indexOf("830") == 0) {
+ textViewCustomTagFound.setText("CS" + tagSelected.getUser().substring(0, 4) + "-" + tagSelected.getUser().substring(4, 5));
+ } else textViewCustomTagFound.setText("");
+ }
+ LinearLayout layout = (LinearLayout) getActivity().findViewById(R.id.accessEmicroCS8304Layout);
+ if (textViewCustomTagFound.getText().toString().contains("8304")) {
+ layout.setVisibility(View.VISIBLE);
+ } else layout.setVisibility(View.GONE);
+ }
+ }
+ else {
+ if (spinnerTagSelect != null && spinnerTagSelect.getSelectedItemPosition() == eMicroTag.emAuraSense.ordinal()) {
+ if (radioButtonAuraSensAtBoot != null && radioButtonAuraSensAtSelect != null) {
+ if (radioButtonAuraSensAtBoot.isChecked()) {
+ MainActivity.tagType = TAG_EM_AURASENSE_ATBOOT; MainActivity.mDid = "E280B12A";
+ }
+ if (radioButtonAuraSensAtSelect.isChecked()) {
+ MainActivity.tagType = TAG_EM_AURASENSE_ATSELECT; MainActivity.mDid = "E280B12B";
+ }
+ }
+ }
+ userVisibleHint = false;
+ }
+ }
+
+ public AccessAuraSenseFragment() {
+ super("AccessAuraSenseFragment");
+ }
+
+ boolean isOperationRunning() {
+ if (MainActivity.csLibrary4A.isBleConnected() == false) {
+ Toast.makeText(MainActivity.mContext, R.string.toast_ble_not_connected, Toast.LENGTH_SHORT).show();
+ return true;
+ } else if (MainActivity.csLibrary4A.isRfidFailure()) {
+ Toast.makeText(MainActivity.mContext, "Rfid is disabled", Toast.LENGTH_SHORT).show();
+ return true;
+ } else if (accessTask != null) {
+ if (accessTask.getStatus() == AsyncTask.Status.RUNNING) {
+ Toast.makeText(MainActivity.mContext, "Running acccess task. Please wait", Toast.LENGTH_SHORT).show();
+ return true;
+ }
+ }
+ return false;
+ }
+ void startAccessTask() {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("startAccessTask()");
+ if (updating == false) {
+ updating = true;
+ bankProcessing = 0; checkProcessing = 0;
+ mHandler.removeCallbacks(updateRunnable);
+ mHandler.post(updateRunnable);
+ }
+ }
+ boolean updating = false;
+ int bankProcessing = 0, checkProcessing = 0;
+ private final Runnable updateRunnable = new Runnable() {
+ @Override
+ public void run() {
+ boolean rerunRequest = false; boolean taskRequest = false;
+ if (accessTask == null) {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("AccessAuraSenseFragment().updateRunnable(): NULL accessReadWriteTask");
+ taskRequest = true;
+ } else if (accessTask.getStatus() != AsyncTask.Status.FINISHED) {
+ rerunRequest = true;
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("AccessAuraSenseFragment().updateRunnable(): accessReadWriteTask.getStatus() = " + accessTask.getStatus().toString());
+ } else {
+ taskRequest = true;
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("AccessAuraSenseFragment().updateRunnable(): FINISHED accessReadWriteTask");
+ }
+ if (processResult()) { rerunRequest = true; MainActivity.csLibrary4A.appendToLog("processResult is TRUE");}
+ else if (taskRequest) {
+ boolean invalid = processTickItems();
+ MainActivity.csLibrary4A.appendToLog("processTickItems, invalid = " + invalid);
+ if (bankProcessing++ != 0 && invalid) rerunRequest = false;
+ else {
+ String selectMask = selectTag.editTextTagID.getText().toString();
+ int selectBank = selectTag.spinnerSelectBank.getSelectedItemPosition()+1;
+ int selectOffset = Integer.valueOf(selectTag.editTextSelectOffset.getText().toString());
+ RfidReaderChipData.HostCommands hostCommand;
+ Button buttonAccess;
+ if (readWriteTypes == ReadWriteTypes.COLDCHAIN_TEMPERATURE && operationRead) {
+ hostCommand = RfidReaderChipData.HostCommands.CMD_GETSENSORDATA;
+ buttonAccess = buttonRead;
+ } else if (operationRead) {
+ hostCommand = RfidReaderChipData.HostCommands.CMD_18K6CREAD;
+ buttonAccess = buttonRead;
+ } else {
+ hostCommand = RfidReaderChipData.HostCommands.CMD_18K6CWRITE;
+ buttonAccess = buttonWrite;
+ }
+ MainActivity.csLibrary4A.appendToLog("hostCommand 1 = " + hostCommand.toString());
+ accessTask = new AccessTask(buttonAccess, null, invalid, true,
+ selectMask, selectBank, selectOffset,
+ selectTag.editTextAccessPassword.getText().toString(),
+ Integer.valueOf(selectTag.editTextAccessAntennaPower.getText().toString()),
+ hostCommand,
+ 0, 0, true, false,
+ null, null, null, null, null);
+ accessTask.execute();
+ rerunRequest = true;
+ MainActivity.csLibrary4A.appendToLog("accessTask is created with selectBank = " + selectBank);
+ }
+ }
+ if (rerunRequest) {
+ mHandler.postDelayed(updateRunnable, 500);
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("AccessAuraSenseFragment().updateRunnable(): Restart");
+ } else updating = false;
+ MainActivity.csLibrary4A.appendToLog("AccessAuraSenseFragment().updateRunnable(): Ending with updating = " + updating);
+ }
+ };
+
+ boolean processResult() {
+ String accessResult = null;
+ if (accessTask == null) return false;
+ else if (accessTask.getStatus() != AsyncTask.Status.FINISHED) return false;
+ else {
+ accessResult = accessTask.accessResult;
+ if (DEBUG || true) MainActivity.csLibrary4A.appendToLog("accessResult = " + accessResult);
+ if (readWriteTypes == ReadWriteTypes.STARTLOGGING) textViewCs8304StartLoggingStatus.setText(accessResult);
+ else if (readWriteTypes == ReadWriteTypes.STOPLOGGING) textViewCs8304StopLoggingStatus.setText(accessResult);
+ else if (readWriteTypes == ReadWriteTypes.CHECKLOGGING) textViewCs8304CheckAlaramStatus.setText(accessResult);
+ else if (readWriteTypes == ReadWriteTypes.GETLOGGING) textViewCs8304GetLoggingStatus.setText(accessResult);
+ else if (accessResult == null) {
+ if (readWriteTypes == ReadWriteTypes.AURA_SENSORDATARCOMMANDW) {
+ textViewAuraSensorDataOK.setText("E");
+ //checkBoxUserCode1.setChecked(false);
+ } else if (readWriteTypes == ReadWriteTypes.AURA_SYSTEMCONFIGURATION) {
+ textViewAuraSystemConfigurationOK.setText("E");
+ //checkBoxUserCode2.setChecked(false);
+ } else if (readWriteTypes == ReadWriteTypes.AURA_CALIBRATION) {
+ textViewAuraSensorCalibrationOK.setText("E");
+ //checkBoxUserCode3.setChecked(false);
+ } else if (readWriteTypes == ReadWriteTypes.AURA_CONTROL) {
+ textViewAuraSensorControlOK.setText("E");
+ //checkBoxUserCode4.setChecked(false);
+ } else if (readWriteTypes == ReadWriteTypes.AURA_DATASTORED) {
+ textViewAuraSensorDataStoredOK.setText("E");
+ //checkBoxUserCode5.setChecked(false);
+ } else if (readWriteTypes == ReadWriteTypes.COLDCHAIN_CONFIGURATION) {
+ textViewConfigOk.setText("E"); checkBoxConfig.setChecked(false);
+ } else if (readWriteTypes == ReadWriteTypes.COLDCHAIN_TEMPERATURE && operationRead) {
+ textViewTemperatureOk.setText("E"); checkBoxTemperature.setChecked(false);
+ } else if (readWriteTypes == ReadWriteTypes.COLDCHAIN_ENABLE) {
+ textViewEnableOk.setText("E");
+ checkBoxEnable.setChecked(false);
+ }
+ } else {
+ if (readWriteTypes == ReadWriteTypes.AURA_SENSORDATARCOMMANDW) {
+ textViewAuraSensorDataOK.setText("O");
+ //checkBoxUserCode1.setChecked(false);
+ readWriteTypes = ReadWriteTypes.NULL;
+ if (operationRead) editTextAuraSensorData.setText(showSensorData(accessResult));
+ } else if (readWriteTypes == ReadWriteTypes.AURA_SYSTEMCONFIGURATION) {
+ textViewAuraSystemConfigurationOK.setText("O");
+ //checkBoxUserCode2.setChecked(false);
+ readWriteTypes = ReadWriteTypes.NULL;
+ if (operationRead) editTextAuraSystemConfiguration.setText(accessResult);
+ } else if (readWriteTypes == ReadWriteTypes.AURA_CALIBRATION) {
+ textViewAuraSensorCalibrationOK.setText("O");
+ //checkBoxUserCode3.setChecked(false);
+ readWriteTypes = ReadWriteTypes.NULL;
+ if (operationRead) {
+ int iValue = Integer.parseInt(accessResult, 16);
+ editTextAuraSensorCalibration.setText(String.valueOf(iValue & 0xFF));
+ }
+ } else if (readWriteTypes == ReadWriteTypes.AURA_CONTROL) {
+ textViewAuraSensorControlOK.setText("O");
+ //checkBoxUserCode4.setChecked(false);
+ readWriteTypes = ReadWriteTypes.NULL;
+ if (operationRead) {
+ int iValue = Integer.parseInt(accessResult, 16);
+ if ((iValue & 0x2000) != 0) checkBoxAuraSensAtBootCheck.setChecked(true);
+ if ((iValue & 0x4000) != 0) checkBoxAuraSensAtSelectCheck.setChecked(true);
+ if ((iValue & 0x8000) != 0) checkBoxAuraSensWriteCheck.setChecked(true);
+ }
+ } else if (readWriteTypes == ReadWriteTypes.AURA_DATASTORED) {
+ textViewAuraSensorDataStoredOK.setText("O");
+ //checkBoxUserCode5.setChecked(false);
+ readWriteTypes = ReadWriteTypes.NULL;
+ if (operationRead) editTextAuraSensorDataStored.setText(showSensorData(accessResult));
+ } else if (readWriteTypes == ReadWriteTypes.COLDCHAIN_TEMPERATURE && operationRead == false) {
+ } else if (readWriteTypes == ReadWriteTypes.COLDCHAIN_CONFIGURATION) {
+ textViewConfigOk.setText("O"); checkBoxConfig.setChecked(false); readWriteTypes = ReadWriteTypes.NULL;
+ if (accessResult.length() == 12 && operationRead) { // 43 60 42 FC 04 06
+ byte bValue = Byte.parseByte(accessResult.substring(0, 1), 16);
+ if ((bValue & 8) == 0) {
+ bValue = Byte.parseByte(accessResult.substring(0, 2), 16);
+ bValue &= 0x3F;
+ editTextTempCountUnder.setText(String.valueOf(bValue >> 1));
+ editTextTempThresUnder.setText(getTemperatue(accessResult.substring(1, 4)));
+
+ bValue = Byte.parseByte(accessResult.substring(4, 6), 16);
+ bValue &= 0x3F;
+ editTextTempCountOver.setText(String.valueOf(bValue >> 1));
+ editTextTempThresOver.setText(getTemperatue(accessResult.substring(5, 8)));
+
+ byte bValue2 = Byte.parseByte(accessResult.substring(8, 10), 16);
+ spinnerDelayUnit.setSelection(((bValue2 & 0xFF) >> 6) + 1);
+ editTextMonitorDelay.setText(String.valueOf(bValue2 & 0x3F));
+
+ bValue2 = Byte.parseByte(accessResult.substring(10, 12), 16);
+ spinnerIntervalUnit.setSelection(((bValue2 & 0xFF) >> 6) + 1);
+ editTextSamplingInterval.setText(String.valueOf(bValue2 & 0x3F));
+ }
+ }
+ } else if (readWriteTypes == ReadWriteTypes.COLDCHAIN_TEMPERATURE && operationRead) {
+ textViewTemperatureOk.setText("O"); checkBoxTemperature.setChecked(false); readWriteTypes = ReadWriteTypes.NULL;
+ MainActivity.csLibrary4A.appendToLog("accessResult of Temperature = " + accessResult);
+
+ if (accessResult.length() >= 16) {
+ int indexBegin = accessResult.length() - 16;
+ String stringValue = accessResult.substring(indexBegin, indexBegin + 4);
+ MainActivity.csLibrary4A.appendToLog("temperature part of Temperature accessResult = " + stringValue);
+ accessResult = stringValue;
+ }
+ if (accessResult.length() == 4) {
+ byte bValue = Byte.parseByte(accessResult.substring(0, 1), 16);
+ if ((bValue & 0x8) != 0) textViewBatteryAlarm.setVisibility(View.VISIBLE);
+ else if ((bValue & 0x2) != 0) textViewOverAlarm.setVisibility(View.VISIBLE);
+ else if ((bValue & 01) != 0) textViewUnderAlarm.setVisibility(View.VISIBLE);
+
+ bValue = Byte.parseByte(accessResult.substring(1, 2), 16);
+ Integer iValue2 = Integer.parseInt(accessResult.substring(2, 4), 16);
+ iValue2 &= 0x1FF;
+ if ((bValue & 0x01) != 0 && iValue2 == 0) textViewTemperature.setText("Invalid");
+ else {
+ String stringValue = getTemperatue(accessResult.substring(1, 4));
+ stringValue += (char) 0x00B0 + "C";
+ textViewTemperature.setText(stringValue);
+ }
+ }
+ } else if (readWriteTypes == ReadWriteTypes.COLDCHAIN_ENABLE) {
+ textViewEnableOk.setText("O"); checkBoxEnable.setChecked(false); readWriteTypes = ReadWriteTypes.NULL;
+ if (accessResult.length() == 4 && operationRead) {
+ byte bValue = Byte.parseByte(accessResult.substring(3, 4), 16);
+ if ((bValue & 0x01) != 0) spinnerEnable.setSelection(2);
+ else spinnerEnable.setSelection(1);
+ }
+ }
+ }
+ accessTask = null;
+ return true;
+ }
+ }
+ String showSensorData(String accessResult) {
+ String strValue = "";
+ int iValue = Integer.parseInt(accessResult,16);
+ if ((iValue & 0xFC00) == 0x0C00) {
+ iValue &= 0x3FF;
+ if ((iValue & 0x200) == 0) strValue = String.valueOf(iValue);
+ else {
+ iValue &= 0x1FF;
+ iValue ^= 0x1FF; iValue++; iValue = -iValue;
+ strValue = String.valueOf(iValue);
+ }
+ }
+ return strValue;
+ }
+
+ boolean processTickItems() {
+ boolean invalidRequest1 = false;
+ int accBank = 0, accSize = 0, accOffset = 0;
+ String writeData = "";
+
+ if (selectTag.editTextTagID.getText().toString().length() == 0) invalidRequest1 = true;
+ else if (spinnerTagSelect.getSelectedItemPosition() == eMicroTag.emAuraSense.ordinal()) {
+ if (checkBoxAuraSensorDataRCommandW != null && checkBoxAuraSensorDataRCommandW.isChecked() == true && checkProcessing < 1) {
+ accBank = 1; accSize = 1; accOffset = 0x22; readWriteTypes = ReadWriteTypes.AURA_SENSORDATARCOMMANDW; checkProcessing = 1;
+ if (operationRead) {
+ textViewAuraSensorDataOK.setText("");
+ editTextAuraSensorData.setText("");
+ } else {
+ int iValue = 0;
+ RadioButton radioButtonAuraSens2Null = (RadioButton) getActivity().findViewById(R.id.accessAuraSens2Null);
+ RadioButton radioButtonAuraSens2Store = (RadioButton) getActivity().findViewById(R.id.accessAuraSens2Store);
+ RadioButton radioButtonAuraSens2Calibration = (RadioButton) getActivity().findViewById(R.id.accessAuraSens2Calibration);
+
+ if (radioButtonAuraSens2Null.isChecked()) iValue = 0x8001;
+ else if (radioButtonAuraSens2Store.isChecked()) iValue = 0x1000;
+ else if (radioButtonAuraSens2Calibration.isChecked()) iValue = 0x2000;
+ writeData = String.format("%04X", iValue);
+ MainActivity.csLibrary4A.appendToLog("WriteData = " + writeData);
+ }
+ } else if (checkBoxAuraSystemConfiguration != null && checkBoxAuraSystemConfiguration.isChecked() == true && checkProcessing < 2 && operationRead) {
+ accBank = 3; accSize = 1; accOffset = 0x120; readWriteTypes = ReadWriteTypes.AURA_SYSTEMCONFIGURATION; checkProcessing = 2;
+ if (operationRead) {
+ textViewAuraSystemConfigurationOK.setText("");
+ editTextAuraSystemConfiguration.setText("");
+ }
+ } else if (checkBoxAuraCalibration != null && checkBoxAuraCalibration.isChecked() == true && checkProcessing < 3) {
+ accBank = 3; accSize = 1; accOffset = 0x122; readWriteTypes = ReadWriteTypes.AURA_CALIBRATION; checkProcessing = 3;
+ if (operationRead) {
+ textViewAuraSensorCalibrationOK.setText("");
+ editTextAuraSensorCalibration.setText("");
+ } else {
+ String strValue = editTextAuraSensorCalibration.getText().toString();
+ Integer iValue = Integer.valueOf(strValue);
+ iValue &= 0xFF;
+ writeData = String.format("%04X", iValue);
+ }
+ } else if (checkBoxAuraControl != null && checkBoxAuraControl.isChecked() == true && checkProcessing < 4) {
+ accBank = 3; accSize = 1; accOffset = 0x123; readWriteTypes = ReadWriteTypes.AURA_CONTROL; checkProcessing = 4;
+ if (operationRead) {
+ textViewAuraSensorControlOK.setText("");
+ checkBoxAuraSensAtBootCheck.setChecked(false); checkBoxAuraSensAtSelectCheck.setChecked(false); checkBoxAuraSensWriteCheck.setChecked(false);
+ } else {
+ int iValue = (checkBoxAuraSensAtBootCheck.isChecked() ? 0x2000 : 0) | (checkBoxAuraSensAtSelectCheck.isChecked() ? 0x4000 : 0) | (checkBoxAuraSensWriteCheck.isChecked() ? 0x8000 : 0);
+ writeData = String.format("%04X", iValue);
+ }
+ } else if (checkBoxAuraDataStored != null && checkBoxAuraDataStored.isChecked() == true && checkProcessing < 5 && operationRead) {
+ accBank = 3;
+ accSize = 1;
+ accOffset = 0x124;
+ readWriteTypes = ReadWriteTypes.AURA_DATASTORED;
+ checkProcessing = 5;
+ if (operationRead) {
+ textViewAuraSensorDataStoredOK.setText("");
+ editTextAuraSensorDataStored.setText("");
+ }
+ } else {
+ invalidRequest1 = true;
+ }
+ } else if (spinnerTagSelect.getSelectedItemPosition() == eMicroTag.emColdChain.ordinal()) {
+ accBank = 3;
+ if (bRequestCheck) {
+ readWriteTypes = ReadWriteTypes.COLDCHAIN_TEMPERATURE;
+ if (bankProcessing == 0) {
+ if (operationRead) {
+ textViewTemperature.setText("");
+ accOffset = 0x10D;
+ accSize = 1;
+ writeData = "0000";
+ } else invalidRequest1 = true;
+ } else {
+ operationRead = true;
+ MainActivity.csLibrary4A.macWrite(0x11F, 3);
+ return false;
+ }
+ } else if (checkBoxConfig.isChecked() == true) {
+ accOffset = 0xEC; accSize = 3; readWriteTypes = ReadWriteTypes.COLDCHAIN_CONFIGURATION; textViewConfigOk.setText("");
+ if (operationRead) {
+ editTextTempThresUnder.setText("");
+ editTextTempThresOver.setText("");
+ editTextTempCountUnder.setText("");
+ editTextTempCountOver.setText("");
+ editTextMonitorDelay.setText("");
+ editTextSamplingInterval.setText("");
+ spinnerDelayUnit.setSelection(0);
+ spinnerIntervalUnit.setSelection(0);
+ } else {
+ try {
+ int underTempCount, underTempThreshold, overTempCount, overTempThreshold;
+ byte tempBytes[] = new byte[6];
+
+ tempBytes[0] = 0x40;
+ tempBytes[0] |= (Byte.parseByte(editTextTempCountUnder.getText().toString()) << 1);
+ float fValue = Float.parseFloat(editTextTempThresUnder.getText().toString());
+ short sValue = setTemperature(fValue);
+ if ((sValue & (short)0x100) != 0) tempBytes[0] |= 1;
+ tempBytes[1] = (byte)sValue;
+
+ tempBytes[2] = 0;
+ tempBytes[2] |= (Byte.parseByte(editTextTempCountOver.getText().toString()) << 1);
+ fValue = Float.parseFloat(editTextTempThresOver.getText().toString());
+ sValue = setTemperature(fValue);
+ if ((sValue & (short)0x100) != 0) tempBytes[2] |= 1;
+ tempBytes[3] = (byte)sValue;
+
+ int iTemp = spinnerDelayUnit.getSelectedItemPosition();
+ if (iTemp < 1) iTemp = 1;
+ else if (iTemp > 4) iTemp = 4;
+ iTemp--;
+ tempBytes[4] = (byte)iTemp; tempBytes[4] <<= 6;
+ byte bValue = Byte.parseByte(editTextMonitorDelay.getText().toString());
+ tempBytes[4] |= (bValue & 0x3F);
+
+ iTemp = spinnerIntervalUnit.getSelectedItemPosition();
+ if (iTemp < 1) iTemp = 1;
+ else if (iTemp > 4) iTemp = 4;
+ iTemp--;
+ tempBytes[5] = (byte)iTemp; tempBytes[5] <<= 6;
+ bValue = Byte.parseByte(editTextSamplingInterval.getText().toString());
+ tempBytes[5] |= (bValue & 0x3F);
+
+ writeData = MainActivity.csLibrary4A.byteArrayToString(tempBytes);
+ MainActivity.csLibrary4A.appendToLog("editTextTempCountUnder = " + MainActivity.csLibrary4A.byteArrayToString(tempBytes));
+ } catch (Exception ex) {
+ MainActivity.csLibrary4A.appendToLog("Invalid String.parse !!!");
+ invalidRequest1 = true;
+ }
+ }
+ } else if (checkBoxTemperature.isChecked() == true) {
+ readWriteTypes = ReadWriteTypes.COLDCHAIN_TEMPERATURE;
+ if (bankProcessing == 0) {
+ if (operationRead) {
+ textViewTemperature = (TextView) getActivity().findViewById(R.id.accessCCTemperature);
+ textViewTemperature.setText("");
+ textViewUnderAlarm = (TextView) getActivity().findViewById(R.id.accessCCUnderTempAlarm);
+ textViewUnderAlarm.setVisibility(View.INVISIBLE);
+ textViewOverAlarm = (TextView) getActivity().findViewById(R.id.accessCCOverTempAlarm);
+ textViewOverAlarm.setVisibility(View.INVISIBLE);
+ textViewBatteryAlarm = (TextView) getActivity().findViewById(R.id.accessCCBatteryAlarm);
+ textViewBatteryAlarm.setVisibility(View.INVISIBLE);
+ textViewTemperatureOk.setText("");
+ if (true) {
+ MainActivity.csLibrary4A.macWrite(0x11F, 3);
+ return false;
+ }
+ accOffset = 0x100;
+ accSize = 1;
+ operationRead = false;
+ } else invalidRequest1 = true;
+ } else {
+ accOffset = 0x100;
+ accSize = 1;
+ operationRead = true;
+ }
+ } else if (checkBoxEnable.isChecked() == true) {
+ accOffset = 0x10D;
+ accSize = 1;
+ readWriteTypes = ReadWriteTypes.COLDCHAIN_ENABLE;
+ textViewEnableOk.setText("");
+ if (operationRead) spinnerEnable.setSelection(0);
+ else {
+ int iSelect = spinnerEnable.getSelectedItemPosition();
+ if (iSelect == 0) invalidRequest1 = true;
+ else if (iSelect == 1) writeData = "0000";
+ else writeData = "0001";
+ String stringValue = "0000";
+ }
+ } else if (readWriteTypes == ReadWriteTypes.STARTLOGGING || readWriteTypes == ReadWriteTypes.STOPLOGGING || readWriteTypes == ReadWriteTypes.CHECKLOGGING || readWriteTypes == ReadWriteTypes.GETLOGGING) {
+ MainActivity.csLibrary4A.appendToLog("accessResult 1 bankProcewssing = " + bankProcessing );
+ accOffset = 0xF0; accSize = 1; operationRead = true;
+ if (readWriteTypes == ReadWriteTypes.STARTLOGGING) {
+ switch(bankProcessing) {
+ case 0:
+ textViewCs8304StartLoggingStatus.setText("");
+ break;
+ case 1:
+ long seconds = System.currentTimeMillis() / (long)1000;
+ int interval = 10;
+ float temperatureOffset = 10; //range 20 to 0 represents -20 to 0 degreeC
+ accOffset = 0; accSize = 4; writeData = "";
+
+ writeData += String.format("%08X", seconds);
+ writeData += String.format("%04X", interval);
+ float fTemp = temperatureOffset / (float) 0.25;
+ short sTemp = (short) fTemp;
+ writeData += String.format("%04X", sTemp);
+ operationRead = false;
+ MainActivity.csLibrary4A.appendToLog("accessResult: UTC seconds = " + seconds + ", writedata = " + writeData);
+ break;
+ case 2:
+ float overTemperature = 20;
+ float underTemperature = -10;
+ accOffset = 0x106; accSize = 3; writeData = "";
+
+ fTemp = overTemperature / (float) 0.25;
+ sTemp = (short) fTemp;
+ writeData += String.format("%04X", sTemp);
+ fTemp = underTemperature / (float) 0.25;
+ sTemp = (short) fTemp;
+ writeData += String.format("%04X", sTemp);
+ writeData += "0000"; //clear Alarm status
+ operationRead = false;
+ MainActivity.csLibrary4A.appendToLog("accessResult: temperature alarm: writeData = " + writeData);
+ break;
+ case 3:
+ accOffset = 0x104; accSize = 1; writeData = "0001";
+ operationRead = false;
+ MainActivity.csLibrary4A.appendToLog("accessResult: status: writeData = " + writeData);
+ break;
+ case 4:
+ accOffset = 0xF0; accSize = 1; writeData = "A000";
+ operationRead = false;
+ MainActivity.csLibrary4A.appendToLog("accessResult: control: writeData = " + writeData);
+ break;
+ default:
+ invalidRequest1 = true; readWriteTypes = ReadWriteTypes.NULL;
+ break;
+ }
+ } else if (readWriteTypes == ReadWriteTypes.STOPLOGGING) {
+ switch(bankProcessing) {
+ case 0:
+ textViewCs8304StartLoggingStatus.setText("");
+ break;
+ case 1:
+ accOffset = 0x104; accSize = 1; writeData = "0002";
+ operationRead = false;
+ MainActivity.csLibrary4A.appendToLog("accessResult: status: writeData = " + writeData);
+ break;
+ case 2:
+ case 3:
+ accOffset = 0xF0; accSize = 1; writeData = "A600";
+ operationRead = false;
+ MainActivity.csLibrary4A.appendToLog("accessResult: control: writeData = " + writeData);
+ break;
+ default:
+ invalidRequest1 = true; readWriteTypes = ReadWriteTypes.NULL;
+ break;
+ }
+ } else if (readWriteTypes == ReadWriteTypes.CHECKLOGGING) {
+ switch(bankProcessing) {
+ case 0:
+ textViewCs8304StartLoggingStatus.setText("");
+ break;
+ case 1:
+ accOffset = 0x108; accSize = 1; writeData = "";
+ operationRead = true;
+ break;
+ case 2:
+ int iValue = 0;
+ try {
+ iValue = Integer.parseInt(textViewCs8304CheckAlaramStatus.getText().toString(), 16);
+ } catch (Exception ex) { }
+ if ((iValue & 2) != 0) {
+ accOffset = 0x108; accSize = 1; writeData = "";
+ iValue &= 0x3; iValue |= 1;
+ writeData = String.format("%04X", iValue);
+ operationRead = false;
+ MainActivity.csLibrary4A.appendToLog("accessResult: writeData = " + writeData);
+ break;
+ }
+ default:
+ invalidRequest1 = true; readWriteTypes = ReadWriteTypes.NULL;
+ break;
+ }
+ } else if (readWriteTypes == ReadWriteTypes.GETLOGGING) {
+ switch(bankProcessing) {
+ case 0:
+ textViewCs8304GetLoggingStatus.setText("");
+ break;
+ default:
+ invalidRequest1 = true; readWriteTypes = ReadWriteTypes.NULL;
+ break;
+ }
+ }
+ } else {
+ invalidRequest1 = true;
+ }
+ } else {
+ invalidRequest1 = true;
+ }
+
+ if (invalidRequest1 == false) {
+ if (MainActivity.csLibrary4A.setAccessBank(accBank) == false) {
+ invalidRequest1 = true;
+ }
+ }
+ if (invalidRequest1 == false) {
+ if (MainActivity.csLibrary4A.setAccessOffset(accOffset) == false) {
+ invalidRequest1 = true;
+ }
+ }
+ if (invalidRequest1 == false) {
+ if (accSize == 0) {
+ invalidRequest1 = true;
+ } else if (MainActivity.csLibrary4A.setAccessCount(accSize) == false) {
+ invalidRequest1 = true;
+ }
+ }
+ if (invalidRequest1 == false && operationRead == false) {
+ if (invalidRequest1 == false) {
+ if (MainActivity.csLibrary4A.setAccessWriteData(writeData) == false) {
+ invalidRequest1 = true;
+ }
+ }
+ }
+ MainActivity.csLibrary4A.appendToLog("found invalidRequest1 = " + invalidRequest1);
+ return invalidRequest1;
+ }
+
+ short setTemperature(float fTemperature) {
+ if (fTemperature > 63.75) fTemperature = (float) 63.75;
+ else if (fTemperature < -64) fTemperature = -64;
+ boolean bNegative = false;
+ if (fTemperature < 0) { bNegative = true; fTemperature = 0 - fTemperature; }
+ fTemperature += 0.125; fTemperature /= 0.25;
+ short retValue = (short)fTemperature;
+ if (bNegative) { retValue--; retValue &= 0xFF; retValue ^= 0xFF; retValue |= 0x100; }
+ return retValue;
+ }
+ String getTemperatue(String stringInput) {
+ byte bValue = Byte.parseByte(stringInput.substring(0,1), 16);
+ byte bValue2 = Byte.parseByte(stringInput.substring(1, 2), 16); bValue2 <<= 4;
+ byte bValue3 = Byte.parseByte(stringInput.substring(2, 3), 16); bValue2 |= bValue3;
+ String stringValue = ""; short sValue = (short)(bValue2 & 0xFF);
+ if ((bValue & 0x01) != 0) { stringValue = "-"; bValue2 ^= 0xFF; sValue = (short)(bValue2 & 0xFF); sValue++; }
+ stringValue += String.valueOf((sValue & 0x1FF) >> 2);
+ switch (sValue & 0x03) {
+ case 1:
+ stringValue += ".25";
+ break;
+ case 2:
+ stringValue += ".50";
+ break;
+ case 3:
+ stringValue += ".75";
+ break;
+ }
+ return stringValue;
+ }
+}
+
+
+
+package com.csl.cs710ademoapp.fragments;
+
+import android.os.AsyncTask;
+import android.os.Bundle;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.AdapterView;
+import android.widget.ArrayAdapter;
+import android.widget.Button;
+import android.widget.CheckBox;
+import android.widget.EditText;
+import android.widget.LinearLayout;
+import android.widget.Spinner;
+import android.widget.TextView;
+import android.widget.Toast;
+
+import com.csl.cs710ademoapp.AccessTask;
+import com.csl.cs710ademoapp.GenericTextWatcher;
+import com.csl.cs710ademoapp.MainActivity;
+import com.csl.cs710ademoapp.R;
+import com.csl.cslibrary4a.ReaderDevice;
+import com.csl.cslibrary4a.RfidReaderChipData;
+
+public class AccessColdChainFragment extends CommonFragment {
+ final boolean DEBUG = true;
+ EditText editTextRWTagID, editTextAccessRWAccPassword, editTextaccessRWAntennaPower;
+ TextView textViewConfigOk, textViewTemperatureOk, textViewEnableOk;
+ CheckBox checkBoxConfig, checkBoxTemperature, checkBoxEnable;
+
+ EditText editTextTempThresUnder, editTextTempThresOver, editTextTempCountUnder, editTextTempCountOver, editTextMonitorDelay, editTextSamplingInterval;
+ TextView textViewTemperature, textViewUnderAlarm, textViewOverAlarm, textViewBatteryAlarm;
+ Spinner spinnerDelayUnit, spinnerIntervalUnit, spinnerEnable, spinnerTagType;
+ Button buttonRead, buttonWrite, buttonStartLogging, buttonStopLogging, buttonCheckAlarm, buttonGetLogging;
+ TextView textViewStartLoggingStatus, textViewStopLoggingStatus, textViewCheckAlaramStatus, textViewGetLoggingStatus;
+
+ enum ReadWriteTypes {
+ NULL, TEMPERATURE, CONFIGURATION, ENABLE,
+ STARTLOGGING, STOPLOGGING, CHECKLOGGING, GETLOGGING
+ }
+ boolean operationRead = false;
+ ReadWriteTypes readWriteTypes;
+
+ private AccessTask accessTask;
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ super.onCreateView(inflater, container, savedInstanceState, false);
+ return inflater.inflate(R.layout.fragment_access_coldchain, container, false);
+ }
+
+ @Override
+ public void onActivityCreated(Bundle savedInstanceState) {
+ super.onActivityCreated(savedInstanceState);
+
+ editTextRWTagID = (EditText) getActivity().findViewById(R.id.accessCCTagID);
+ editTextAccessRWAccPassword = (EditText) getActivity().findViewById(R.id.accessCCAccPasswordValue);
+ editTextAccessRWAccPassword.addTextChangedListener(new GenericTextWatcher(editTextAccessRWAccPassword, 8));
+ editTextAccessRWAccPassword.setText("00000000");
+
+ textViewConfigOk = (TextView) getActivity().findViewById(R.id.accessCCConfigOK);
+ textViewTemperatureOk = (TextView) getActivity().findViewById(R.id.accessCCTemperatureOK);
+ textViewEnableOk = (TextView) getActivity().findViewById(R.id.accessCCEnableOK);
+ checkBoxConfig = (CheckBox) getActivity().findViewById(R.id.accessCCConfigTitle);
+ checkBoxTemperature = (CheckBox) getActivity().findViewById(R.id.accessCCTemperatureTitle);
+ checkBoxEnable = (CheckBox) getActivity().findViewById(R.id.accessCCEnableTitle);
+
+ textViewTemperature = (TextView) getActivity().findViewById(R.id.accessCCTemperature);
+ textViewUnderAlarm = (TextView) getActivity().findViewById(R.id.accessCCUnderTempAlarm);
+ textViewOverAlarm = (TextView) getActivity().findViewById(R.id.accessCCOverTempAlarm);
+ textViewBatteryAlarm = (TextView) getActivity().findViewById(R.id.accessCCBatteryAlarm);
+
+ editTextTempThresUnder = (EditText) getActivity().findViewById(R.id.accessCCTempThresUnder);
+ editTextTempThresOver = (EditText) getActivity().findViewById(R.id.accessCCTempThresOver);
+ editTextTempCountUnder = (EditText) getActivity().findViewById(R.id.accessCCTempCountUnder);
+ editTextTempCountOver = (EditText) getActivity().findViewById(R.id.accessCCTempCountOver);
+ editTextMonitorDelay = (EditText) getActivity().findViewById(R.id.accessCCMonitorDelay);
+ editTextSamplingInterval = (EditText) getActivity().findViewById(R.id.accessCCSamplingInverval);
+
+ TextView textViewDegreeC = (TextView) getActivity().findViewById(R.id.accessCCDegreeC);
+ textViewDegreeC.setText(textViewDegreeC.getText().toString() + (char) 0x00B0 + "C)");
+
+ ArrayAdapter arrayAdapterUnit = ArrayAdapter.createFromResource(getActivity(), R.array.coldChain_unit_options, R.layout.custom_spinner_layout);
+ arrayAdapterUnit.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+ spinnerDelayUnit = (Spinner) getActivity().findViewById(R.id.accessCCMonitorUnit);
+ spinnerDelayUnit.setAdapter(arrayAdapterUnit);
+
+ ArrayAdapter arrayAdapterUnit1 = ArrayAdapter.createFromResource(getActivity(), R.array.coldChain_IntervalUnit_options, R.layout.custom_spinner_layout);
+ arrayAdapterUnit1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+ spinnerIntervalUnit = (Spinner) getActivity().findViewById(R.id.accessCCSamplingIntervalUnit);
+ spinnerIntervalUnit.setAdapter(arrayAdapterUnit1);
+
+ ArrayAdapter arrayAdapterEnable = ArrayAdapter.createFromResource(getActivity(), R.array.coldChain_enable_options, R.layout.custom_spinner_layout);
+ arrayAdapterEnable.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+ spinnerEnable = (Spinner) getActivity().findViewById(R.id.accessCCEnable);
+ spinnerEnable.setAdapter(arrayAdapterEnable);
+
+ ArrayAdapter arrayAdapterTagType = ArrayAdapter.createFromResource(getActivity(), R.array.coldChain_tagtype_options, R.layout.custom_spinner_layout);
+ arrayAdapterTagType.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+ spinnerTagType = (Spinner) getActivity().findViewById(R.id.selectCCTagType);
+ spinnerTagType.setAdapter(arrayAdapterTagType);
+ spinnerTagType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
+ @Override
+ public void onItemSelected(AdapterView> parentView, View selectedItemView, int position, long id) {
+ switch(position) {
+ case 0:
+ LinearLayout linearLayout = (LinearLayout) getActivity().findViewById(R.id.accessCC8304Layout);
+ linearLayout.setVisibility(View.VISIBLE);
+ linearLayout = (LinearLayout) getActivity().findViewById(R.id.accessCCmaxduraLayout);
+ linearLayout.setVisibility(View.GONE);
+ break;
+ case 1:
+ linearLayout = (LinearLayout) getActivity().findViewById(R.id.accessCC8304Layout);
+ linearLayout.setVisibility(View.GONE);
+ linearLayout = (LinearLayout) getActivity().findViewById(R.id.accessCCmaxduraLayout);
+ linearLayout.setVisibility(View.VISIBLE);
+ break;
+ }
+ }
+
+ @Override
+ public void onNothingSelected(AdapterView> parentView) {
+ // your code here
+ }
+ });
+
+ editTextaccessRWAntennaPower = (EditText) getActivity().findViewById(R.id.accessCCAntennaPower);
+ editTextaccessRWAntennaPower.setText(String.valueOf(300));
+
+ buttonStartLogging = (Button) getActivity().findViewById(R.id.accessCCStartLogging);
+ buttonStartLogging.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (isOperationRunning()) return;
+ readWriteTypes = ReadWriteTypes.STARTLOGGING;
+ operationRead = true; startAccessTask();
+ }
+ });
+ buttonStopLogging = (Button) getActivity().findViewById(R.id.accessCCStopLogging);
+ buttonStopLogging.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (isOperationRunning()) return;
+ readWriteTypes = ReadWriteTypes.STOPLOGGING;
+ operationRead = true; startAccessTask();
+ }
+ });
+ buttonCheckAlarm = (Button) getActivity().findViewById(R.id.accessCCcheckAlarm);
+ buttonCheckAlarm.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (isOperationRunning()) return;
+ readWriteTypes = ReadWriteTypes.CHECKLOGGING;
+ operationRead = true; startAccessTask();
+ }
+ });
+ buttonGetLogging = (Button) getActivity().findViewById(R.id.accessCCGetLogging);
+ buttonGetLogging.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (isOperationRunning()) return;
+ readWriteTypes = ReadWriteTypes.GETLOGGING;
+ operationRead = true; startAccessTask();
+ }
+ });
+
+ textViewStartLoggingStatus = (TextView) getActivity().findViewById(R.id.accessCCStartLoggingStatus);
+ textViewStopLoggingStatus = (TextView) getActivity().findViewById(R.id.accessCCStopLoggingStatus);
+ textViewCheckAlaramStatus = (TextView) getActivity().findViewById(R.id.accessCCcheckAlarmStatus);
+ textViewGetLoggingStatus = (TextView) getActivity().findViewById(R.id.accessCCGetLoggingStatus);
+
+ buttonRead = (Button) getActivity().findViewById(R.id.accessCCReadButton);
+ buttonRead.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (isOperationRunning()) return;
+ readWriteTypes = ReadWriteTypes.NULL;
+ operationRead = true; startAccessTask();
+ }
+ });
+
+ buttonWrite = (Button) getActivity().findViewById(R.id.accessCCWriteButton);
+ buttonWrite.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (isOperationRunning()) return;
+ readWriteTypes = ReadWriteTypes.NULL;
+ operationRead = false; startAccessTask();
+ }
+ });
+
+ setupTagID();
+ MainActivity.csLibrary4A.setSameCheck(false);
+ }
+
+ @Override
+ public void onDestroy() {
+ if (accessTask != null) accessTask.cancel(true);
+ MainActivity.csLibrary4A.setSameCheck(true);
+ MainActivity.csLibrary4A.restoreAfterTagSelect();
+ super.onDestroy();
+ }
+
+ boolean userVisibleHint = false;
+ @Override
+ public void setUserVisibleHint(boolean isVisibleToUser) {
+ super.setUserVisibleHint(isVisibleToUser);
+ if(getUserVisibleHint()) {
+ userVisibleHint = true;
+ MainActivity.csLibrary4A.appendToLog("AccessColdChainFragment is now VISIBLE");
+ setupTagID();
+ // setNotificationListener();
+ } else {
+ userVisibleHint = false;
+ MainActivity.csLibrary4A.appendToLog("AccessColdChainFragment is now INVISIBLE");
+// MainActivity.mCs108Library4a.setNotificationListener(null);
+ }
+ }
+
+ public AccessColdChainFragment() {
+ super("AccessColdChainFragment");
+ }
+
+ void setupTagID() {
+ ReaderDevice tagSelected = MainActivity.tagSelected;
+ boolean bSelected = false;
+ if (tagSelected != null) {
+ if (tagSelected.getSelected() == true) {
+ bSelected = true;
+ if (editTextRWTagID != null) editTextRWTagID.setText(tagSelected.getAddress());
+
+ String stringDetail = tagSelected.getDetails();
+ int indexUser = stringDetail.indexOf("USER=");
+ if (indexUser != -1) {
+ String stringUser = stringDetail.substring(indexUser + 5);
+ MainActivity.csLibrary4A.appendToLog("stringUser = " + stringUser);
+
+ boolean bEnableBAPMode = false;
+ int number = Integer.valueOf(stringUser.substring(3, 4), 16);
+ if ((number % 2) == 1) bEnableBAPMode = true;
+// CheckBox checkBoxBAP = (CheckBox) getActivity().findViewById(R.id.coldChainEnableBAP);
+// checkBoxBAP.setChecked(bEnableBAPMode);
+ }
+ }
+ }
+ }
+
+ boolean isOperationRunning() {
+ if (MainActivity.csLibrary4A.isBleConnected() == false) {
+ Toast.makeText(MainActivity.mContext, R.string.toast_ble_not_connected, Toast.LENGTH_SHORT).show();
+ return true;
+ } else if (MainActivity.csLibrary4A.isRfidFailure()) {
+ Toast.makeText(MainActivity.mContext, "Rfid is disabled", Toast.LENGTH_SHORT).show();
+ return true;
+ } else if (accessTask != null) {
+ if (accessTask.getStatus() == AsyncTask.Status.RUNNING) {
+ Toast.makeText(MainActivity.mContext, "Running acccess task. Please wait", Toast.LENGTH_SHORT).show();
+ return true;
+ }
+ }
+ return false;
+ }
+
+ void startAccessTask() {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("startAccessTask()");
+ if (updating == false) {
+ updating = true; bankProcessing = 0;
+ mHandler.removeCallbacks(updateRunnable);
+ mHandler.post(updateRunnable);
+ }
+ }
+ boolean updating = false; int bankProcessing = 0;
+ private final Runnable updateRunnable = new Runnable() {
+ @Override
+ public void run() {
+ boolean rerunRequest = false; boolean taskRequest = false;
+ if (accessTask == null) {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("AccessColdChainFragment().updateRunnable(): NULL accessReadWriteTask");
+ taskRequest = true;
+ } else if (accessTask.getStatus() != AsyncTask.Status.FINISHED) {
+ rerunRequest = true;
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("AccessColdChainFragment().updateRunnable(): accessReadWriteTask.getStatus() = " + accessTask.getStatus().toString());
+ } else {
+ taskRequest = true;
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("AccessColdChainFragment().updateRunnable(): FINISHED accessReadWriteTask");
+ }
+ if (processResult()) { rerunRequest = true; MainActivity.csLibrary4A.appendToLog("processResult is TRUE");}
+ else if (taskRequest) {
+ boolean invalid = processTickItems();
+ MainActivity.csLibrary4A.appendToLog("processTickItems, invalid = " + invalid);
+ if (bankProcessing++ != 0 && invalid) rerunRequest = false;
+ else {
+ RfidReaderChipData.HostCommands hostCommand;
+ if (readWriteTypes == ReadWriteTypes.TEMPERATURE) hostCommand = RfidReaderChipData.HostCommands.CMD_GETSENSORDATA;
+ else if (operationRead) hostCommand = RfidReaderChipData.HostCommands.CMD_18K6CREAD;
+ else hostCommand = RfidReaderChipData.HostCommands.CMD_18K6CWRITE;
+ accessTask = new AccessTask((operationRead ? buttonRead : buttonWrite), null, invalid, true,
+ editTextRWTagID.getText().toString(), 1, 32,
+ editTextAccessRWAccPassword.getText().toString(),
+ Integer.valueOf(editTextaccessRWAntennaPower.getText().toString()),
+ hostCommand,
+ 0, 0, true, false,
+ null, null, null, null, null);
+ accessTask.execute();
+ rerunRequest = true;
+ MainActivity.csLibrary4A.appendToLog("accessTask is created");
+ }
+ }
+ if (rerunRequest) {
+ mHandler.postDelayed(updateRunnable, 500);
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("AccessColdChainFragment().updateRunnable(): Restart");
+ }
+ else updating = false;
+ MainActivity.csLibrary4A.appendToLog("AccessColdChainFragment().updateRunnable(): Ending with updating = " + updating);
+ }
+ };
+
+ short setTemperature(float fTemperature) {
+ if (fTemperature > 63.75) fTemperature = (float) 63.75;
+ else if (fTemperature < -64) fTemperature = -64;
+ boolean bNegative = false;
+ if (fTemperature < 0) { bNegative = true; fTemperature = 0 - fTemperature; }
+ fTemperature += 0.125; fTemperature /= 0.25;
+ short retValue = (short)fTemperature;
+ if (bNegative) { retValue--; retValue &= 0xFF; retValue ^= 0xFF; retValue |= 0x100; }
+ return retValue;
+ }
+ String getTemperatue(String stringInput) {
+ byte bValue = Byte.parseByte(stringInput.substring(0,1), 16);
+ byte bValue2 = Byte.parseByte(stringInput.substring(1, 2), 16); bValue2 <<= 4;
+ byte bValue3 = Byte.parseByte(stringInput.substring(2, 3), 16); bValue2 |= bValue3;
+ String stringValue = ""; short sValue = (short)(bValue2 & 0xFF);
+ if ((bValue & 0x01) != 0) { stringValue = "-"; bValue2 ^= 0xFF; sValue = (short)(bValue2 & 0xFF); sValue++; }
+ stringValue += String.valueOf((sValue & 0x1FF) >> 2);
+ switch (sValue & 0x03) {
+ case 1:
+ stringValue += ".25";
+ break;
+ case 2:
+ stringValue += ".50";
+ break;
+ case 3:
+ stringValue += ".75";
+ break;
+ }
+ return stringValue;
+ }
+
+ // int accessBank, accSize, accOffset;
+// int restartCounter = 0; int restartAccessBank = -1;
+ boolean processResult() {
+ String accessResult = null;
+ if (accessTask == null) return false;
+ else if (accessTask.getStatus() != AsyncTask.Status.FINISHED) return false;
+ else {
+ accessResult = accessTask.accessResult;
+ MainActivity.csLibrary4A.appendToLog("accessResult 2 bankProcewssing = " + bankProcessing + ", accessResult = " + accessTask.accessResult );
+ if (readWriteTypes == ReadWriteTypes.STARTLOGGING) textViewStartLoggingStatus.setText(accessResult);
+ else if (readWriteTypes == ReadWriteTypes.STOPLOGGING) textViewStopLoggingStatus.setText(accessResult);
+ else if (readWriteTypes == ReadWriteTypes.CHECKLOGGING) textViewCheckAlaramStatus.setText(accessResult);
+ else if (readWriteTypes == ReadWriteTypes.GETLOGGING) textViewGetLoggingStatus.setText(accessResult);
+ else if (accessResult == null) {
+ if (readWriteTypes == ReadWriteTypes.CONFIGURATION) {
+ textViewConfigOk.setText("E"); checkBoxConfig.setChecked(false);
+ } else if (readWriteTypes == ReadWriteTypes.TEMPERATURE && operationRead) {
+ textViewTemperatureOk.setText("E"); checkBoxTemperature.setChecked(false);
+ } else if (readWriteTypes == ReadWriteTypes.ENABLE) {
+ textViewEnableOk.setText("E"); checkBoxEnable.setChecked(false);
+ }
+ } else {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("accessResult = " + accessResult);
+ if (readWriteTypes == ReadWriteTypes.CONFIGURATION) {
+ textViewConfigOk.setText("O"); checkBoxConfig.setChecked(false); readWriteTypes = ReadWriteTypes.NULL;
+ if (accessResult.length() == 12 && operationRead) { // 43 60 42 FC 04 06
+ byte bValue = Byte.parseByte(accessResult.substring(0, 1), 16);
+ if ((bValue & 8) == 0) {
+ bValue = Byte.parseByte(accessResult.substring(0, 2), 16);
+ bValue &= 0x3F;
+ editTextTempCountUnder.setText(String.valueOf(bValue >> 1));
+ editTextTempThresUnder.setText(getTemperatue(accessResult.substring(1, 4)));
+
+ bValue = Byte.parseByte(accessResult.substring(4, 6), 16);
+ bValue &= 0x3F;
+ editTextTempCountOver.setText(String.valueOf(bValue >> 1));
+ editTextTempThresOver.setText(getTemperatue(accessResult.substring(5, 8)));
+
+ byte bValue2 = Byte.parseByte(accessResult.substring(8, 10), 16);
+ spinnerDelayUnit.setSelection(((bValue2 & 0xFF) >> 6) + 1);
+ editTextMonitorDelay.setText(String.valueOf(bValue2 & 0x3F));
+
+ bValue2 = Byte.parseByte(accessResult.substring(10, 12), 16);
+ spinnerIntervalUnit.setSelection(((bValue2 & 0xFF) >> 6) + 1);
+ editTextSamplingInterval.setText(String.valueOf(bValue2 & 0x3F));
+ }
+ }
+ } else if (readWriteTypes == ReadWriteTypes.TEMPERATURE && operationRead) {
+ textViewTemperatureOk.setText("O"); checkBoxTemperature.setChecked(false); readWriteTypes = ReadWriteTypes.NULL;
+ MainActivity.csLibrary4A.appendToLog("accessResult of Temperature = " + accessResult);
+
+ if (accessResult.length() >= 16) {
+ int indexBegin = accessResult.length() - 16;
+ String stringValue = accessResult.substring(indexBegin, indexBegin + 4);
+ MainActivity.csLibrary4A.appendToLog("temperature part of Temperature accessResult = " + stringValue);
+ accessResult = stringValue;
+ }
+ if (accessResult.length() == 4) {
+ byte bValue = Byte.parseByte(accessResult.substring(0, 1), 16);
+ if ((bValue & 0x8) != 0) textViewBatteryAlarm.setVisibility(View.VISIBLE);
+ else if ((bValue & 0x2) != 0) textViewOverAlarm.setVisibility(View.VISIBLE);
+ else if ((bValue & 01) != 0) textViewUnderAlarm.setVisibility(View.VISIBLE);
+
+ bValue = Byte.parseByte(accessResult.substring(1, 2), 16);
+ Integer iValue2 = Integer.parseInt(accessResult.substring(2, 4), 16);
+ iValue2 &= 0x1FF;
+ if ((bValue & 0x01) != 0 && iValue2 == 0) textViewTemperature.setText("Invalid");
+ else {
+ String stringValue = getTemperatue(accessResult.substring(1, 4));
+ stringValue += (char) 0x00B0 + "C";
+ textViewTemperature.setText(stringValue);
+ }
+ }
+ } else if (readWriteTypes == ReadWriteTypes.ENABLE) {
+ textViewEnableOk.setText("O"); checkBoxEnable.setChecked(false); readWriteTypes = ReadWriteTypes.NULL;
+ if (accessResult.length() == 4 && operationRead) {
+ byte bValue = Byte.parseByte(accessResult.substring(3, 4), 16);
+ if ((bValue & 0x01) != 0) spinnerEnable.setSelection(2);
+ else spinnerEnable.setSelection(1);
+ }
+ }
+ }
+ accessTask = null;
+ return true;
+ }
+ }
+ boolean processTickItems() {
+ boolean invalidRequest1 = false;
+ int accSize = 0, accOffset = 0;
+ String writeData = "";
+
+ if (readWriteTypes == ReadWriteTypes.STARTLOGGING || readWriteTypes == ReadWriteTypes.STOPLOGGING || readWriteTypes == ReadWriteTypes.CHECKLOGGING || readWriteTypes == ReadWriteTypes.GETLOGGING) {
+ MainActivity.csLibrary4A.appendToLog("accessResult 1 bankProcewssing = " + bankProcessing );
+ accOffset = 0xF0; accSize = 1; operationRead = true;
+ if (readWriteTypes == ReadWriteTypes.STARTLOGGING) {
+ switch(bankProcessing) {
+ case 0:
+ textViewStartLoggingStatus.setText("");
+ break;
+ case 1:
+ long seconds = System.currentTimeMillis() / (long)1000;
+ int interval = 10;
+ float temperatureOffset = 10; //range 20 to 0 represents -20 to 0 degreeC
+ accOffset = 0; accSize = 4; writeData = "";
+
+ writeData += String.format("%08X", seconds);
+ writeData += String.format("%04X", interval);
+ float fTemp = temperatureOffset / (float) 0.25;
+ short sTemp = (short) fTemp;
+ writeData += String.format("%04X", sTemp);
+ operationRead = false;
+ MainActivity.csLibrary4A.appendToLog("accessResult: UTC seconds = " + seconds + ", writedata = " + writeData);
+ break;
+ case 2:
+ float overTemperature = 20;
+ float underTemperature = -10;
+ accOffset = 0x106; accSize = 3; writeData = "";
+
+ fTemp = overTemperature / (float) 0.25;
+ sTemp = (short) fTemp;
+ writeData += String.format("%04X", sTemp);
+ fTemp = underTemperature / (float) 0.25;
+ sTemp = (short) fTemp;
+ writeData += String.format("%04X", sTemp);
+ writeData += "0000"; //clear Alarm status
+ operationRead = false;
+ MainActivity.csLibrary4A.appendToLog("accessResult: temperature alarm: writeData = " + writeData);
+ break;
+ case 3:
+ accOffset = 0x104; accSize = 1; writeData = "0001";
+ operationRead = false;
+ MainActivity.csLibrary4A.appendToLog("accessResult: status: writeData = " + writeData);
+ break;
+ case 4:
+ accOffset = 0xF0; accSize = 1; writeData = "A000";
+ operationRead = false;
+ MainActivity.csLibrary4A.appendToLog("accessResult: control: writeData = " + writeData);
+ break;
+ default:
+ invalidRequest1 = true; readWriteTypes = ReadWriteTypes.NULL;
+ break;
+ }
+ } else if (readWriteTypes == ReadWriteTypes.STOPLOGGING) {
+ switch(bankProcessing) {
+ case 0:
+ textViewStartLoggingStatus.setText("");
+ break;
+ case 1:
+ accOffset = 0x104; accSize = 1; writeData = "0002";
+ operationRead = false;
+ MainActivity.csLibrary4A.appendToLog("accessResult: status: writeData = " + writeData);
+ break;
+ case 2:
+ case 3:
+ accOffset = 0xF0; accSize = 1; writeData = "A600";
+ operationRead = false;
+ MainActivity.csLibrary4A.appendToLog("accessResult: control: writeData = " + writeData);
+ break;
+ default:
+ invalidRequest1 = true; readWriteTypes = ReadWriteTypes.NULL;
+ break;
+ }
+ } else if (readWriteTypes == ReadWriteTypes.CHECKLOGGING) {
+ switch(bankProcessing) {
+ case 0:
+ textViewStartLoggingStatus.setText("");
+ break;
+ case 1:
+ accOffset = 0x108; accSize = 1; writeData = "";
+ operationRead = true;
+ break;
+ case 2:
+ int iValue = 0;
+ try {
+ iValue = Integer.parseInt(textViewCheckAlaramStatus.getText().toString(), 16);
+ } catch (Exception ex) { }
+ if ((iValue & 2) != 0) {
+ accOffset = 0x108; accSize = 1; writeData = "";
+ iValue &= 0x3; iValue |= 1;
+ writeData = String.format("%04X", iValue);
+ operationRead = false;
+ MainActivity.csLibrary4A.appendToLog("accessResult: writeData = " + writeData);
+ break;
+ }
+ default:
+ invalidRequest1 = true; readWriteTypes = ReadWriteTypes.NULL;
+ break;
+ }
+ } else if (readWriteTypes == ReadWriteTypes.GETLOGGING) {
+ switch(bankProcessing) {
+ case 0:
+ textViewGetLoggingStatus.setText("");
+ break;
+ default:
+ invalidRequest1 = true; readWriteTypes = ReadWriteTypes.NULL;
+ break;
+ }
+ }
+ } else if (checkBoxConfig.isChecked() == true) {
+ accOffset = 0xEC; accSize = 3; readWriteTypes = ReadWriteTypes.CONFIGURATION; textViewConfigOk.setText("");
+ if (operationRead) {
+ editTextTempThresUnder.setText("");
+ editTextTempThresOver.setText("");
+ editTextTempCountUnder.setText("");
+ editTextTempCountOver.setText("");
+ editTextMonitorDelay.setText("");
+ editTextSamplingInterval.setText("");
+ spinnerDelayUnit.setSelection(0);
+ spinnerIntervalUnit.setSelection(0);
+ } else {
+ try {
+ int underTempCount, underTempThreshold, overTempCount, overTempThreshold;
+ byte tempBytes[] = new byte[6];
+
+ tempBytes[0] = 0x40;
+ tempBytes[0] |= (Byte.parseByte(editTextTempCountUnder.getText().toString()) << 1);
+ float fValue = Float.parseFloat(editTextTempThresUnder.getText().toString());
+ short sValue = setTemperature(fValue);
+ if ((sValue & (short)0x100) != 0) tempBytes[0] |= 1;
+ tempBytes[1] = (byte)sValue;
+
+ tempBytes[2] = 0;
+ tempBytes[2] |= (Byte.parseByte(editTextTempCountOver.getText().toString()) << 1);
+ fValue = Float.parseFloat(editTextTempThresOver.getText().toString());
+ sValue = setTemperature(fValue);
+ if ((sValue & (short)0x100) != 0) tempBytes[2] |= 1;
+ tempBytes[3] = (byte)sValue;
+
+ int iTemp = spinnerDelayUnit.getSelectedItemPosition();
+ if (iTemp < 1) iTemp = 1;
+ else if (iTemp > 4) iTemp = 4;
+ iTemp--;
+ tempBytes[4] = (byte)iTemp; tempBytes[4] <<= 6;
+ byte bValue = Byte.parseByte(editTextMonitorDelay.getText().toString());
+ tempBytes[4] |= (bValue & 0x3F);
+
+ iTemp = spinnerIntervalUnit.getSelectedItemPosition();
+ if (iTemp < 1) iTemp = 1;
+ else if (iTemp > 4) iTemp = 4;
+ iTemp--;
+ tempBytes[5] = (byte)iTemp; tempBytes[5] <<= 6;
+ bValue = Byte.parseByte(editTextSamplingInterval.getText().toString());
+ tempBytes[5] |= (bValue & 0x3F);
+
+ writeData = MainActivity.csLibrary4A.byteArrayToString(tempBytes);
+ MainActivity.csLibrary4A.appendToLog("editTextTempCountUnder = " + MainActivity.csLibrary4A.byteArrayToString(tempBytes));
+ } catch (Exception ex) {
+ MainActivity.csLibrary4A.appendToLog("Invalid String.parse !!!");
+ invalidRequest1 = true;
+ }
+ }
+ } else if (checkBoxTemperature.isChecked() == true) {
+ readWriteTypes = ReadWriteTypes.TEMPERATURE;
+ if (bankProcessing == 0) {
+ if (operationRead) {
+ textViewTemperature = (TextView) getActivity().findViewById(R.id.accessCCTemperature);
+ textViewTemperature.setText("");
+ textViewUnderAlarm = (TextView) getActivity().findViewById(R.id.accessCCUnderTempAlarm);
+ textViewUnderAlarm.setVisibility(View.INVISIBLE);
+ textViewOverAlarm = (TextView) getActivity().findViewById(R.id.accessCCOverTempAlarm);
+ textViewOverAlarm.setVisibility(View.INVISIBLE);
+ textViewBatteryAlarm = (TextView) getActivity().findViewById(R.id.accessCCBatteryAlarm);
+ textViewBatteryAlarm.setVisibility(View.INVISIBLE);
+ textViewTemperatureOk.setText("");
+ if (true) {
+ MainActivity.csLibrary4A.macWrite(0x11F, 3);
+ return false;
+ }
+ accOffset = 0x100; accSize = 1; operationRead = false;
+ } else invalidRequest1 = true;
+ } else {
+ accOffset = 0x100; accSize = 1; operationRead = true;
+ }
+ } else if (checkBoxEnable.isChecked() == true) {
+ accOffset = 0x10D; accSize = 1; readWriteTypes = ReadWriteTypes.ENABLE; textViewEnableOk.setText("");
+ if (operationRead) spinnerEnable.setSelection(0);
+ else {
+ int iSelect = spinnerEnable.getSelectedItemPosition();
+ if (iSelect == 0) invalidRequest1 = true;
+ else if (iSelect == 1) writeData = "0000";
+ else writeData = "0001";
+ String stringValue = "0000";
+ }
+ } else {
+ invalidRequest1 = true;
+ }
+
+ if (invalidRequest1 == false) {
+ if (MainActivity.csLibrary4A.setAccessBank(3) == false) {
+ invalidRequest1 = true;
+ }
+ }
+ if (invalidRequest1 == false) {
+ if (MainActivity.csLibrary4A.setAccessOffset(accOffset) == false) {
+ invalidRequest1 = true;
+ }
+ }
+ if (invalidRequest1 == false) {
+ if (accSize == 0) {
+ invalidRequest1 = true;
+ } else if (MainActivity.csLibrary4A.setAccessCount(accSize) == false) {
+ invalidRequest1 = true;
+ }
+ }
+ if (invalidRequest1 == false && operationRead == false) {
+ if (invalidRequest1 == false) {
+ if (MainActivity.csLibrary4A.setAccessWriteData(writeData) == false) {
+ invalidRequest1 = true;
+ }
+ }
+ }
+ return invalidRequest1;
+ }
+}
+
+
+
+package com.csl.cs710ademoapp.fragments;
+
+import android.os.Bundle;
+import androidx.fragment.app.Fragment;
+import androidx.fragment.app.FragmentManager;
+import androidx.fragment.app.FragmentTransaction;
+import androidx.appcompat.app.ActionBar;
+import androidx.appcompat.app.AppCompatActivity;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.Button;
+import android.widget.EditText;
+import android.widget.TextView;
+
+import com.csl.cs710ademoapp.MainActivity;
+import com.csl.cs710ademoapp.R;
+
+public class AccessConfigFragment extends CommonFragment {
+ boolean bXerxesEnable = false;
+ EditText editTextPassWord, editTextPower, editText0, editText1, editText2;
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ super.onCreateView(inflater, container, savedInstanceState, false);
+ return inflater.inflate(R.layout.fragment_access_config, container, false);
+ }
+
+ @Override
+ public void onActivityCreated(Bundle savedInstanceState) {
+ super.onActivityCreated(savedInstanceState);
+
+ if (((AppCompatActivity) getActivity()).getSupportActionBar() != null) {
+ ActionBar actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
+ actionBar.setTitle(R.string.title_activity_axzonConfig);
+ }
+
+ editTextPassWord = (EditText) getActivity().findViewById(R.id.accessConfigPasswordValue);
+ editTextPassWord.setText("00000000");
+ editTextPower = (EditText) getActivity().findViewById(R.id.accessConfigAntennaPower);
+ editTextPower.setText("300");
+
+ TextView textView0 = (TextView) getActivity().findViewById(R.id.accessConfigData0Label);
+ textView0.setText("select hold(ms)");
+ editText0 = (EditText) getActivity().findViewById(R.id.accessConfigData0);
+
+ if (MainActivity.mDid == null) editText0.setText("0");
+ else if (MainActivity.mDid.indexOf("E282405") == 0) editText0.setText("9");
+ else if (MainActivity.mDid.indexOf("E282403") == 0) editText0.setText("3");
+ else editText0.setText("0");
+
+ TextView textView1 = (TextView) getActivity().findViewById(R.id.accessConfigData1Label);
+ textView1.setText("Upper Limit of On Chip RSSI");
+ editText1 = (EditText) getActivity().findViewById(R.id.accessConfigData1);
+ editText1.setText("21");
+
+ TextView textView2 = (TextView) getActivity().findViewById(R.id.accessConfigData2Label);
+ textView2.setText("Lower Limit On Chip RSSI");
+ editText2 = (EditText) getActivity().findViewById(R.id.accessConfigData2);
+ editText2.setText("13");
+
+ Button button = (Button) getActivity().findViewById(R.id.accessConfigOKButton);
+ button.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ MainActivity.config.configPassword = editTextPassWord.getText().toString();
+ MainActivity.config.configPower = editTextPower.getText().toString();
+ MainActivity.config.config0 = editText0.getText().toString();
+ MainActivity.config.config1 = editText1.getText().toString();
+ MainActivity.config.config2 = editText2.getText().toString();
+
+ if (MainActivity.mDid != null) if (MainActivity.mDid.indexOf("E282405") == 0) bXerxesEnable = true;
+
+ Fragment fragment;
+ if (bXerxesEnable) fragment = new AxzonFragment();
+ else fragment = new MicronFragment();
+
+ FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
+ FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
+ fragmentTransaction.replace(R.id.content_frame, fragment);
+ fragmentTransaction.addToBackStack(null);
+ fragmentTransaction.commit();
+ }
+ });
+ }
+
+ public static AccessConfigFragment newInstance(boolean bXerxesEnable) {
+ AccessConfigFragment myFragment = new AccessConfigFragment();
+ myFragment.bXerxesEnable = bXerxesEnable;
+ return myFragment;
+ }
+ public AccessConfigFragment() {
+ super("AccessConfigFragment");
+ }
+}
+
+
+
+package com.csl.cs710ademoapp.fragments;
+
+import android.os.AsyncTask;
+import android.os.Bundle;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.Button;
+import android.widget.EditText;
+import android.widget.TextView;
+import android.widget.Toast;
+
+import com.csl.cs710ademoapp.AccessTask;
+import com.csl.cs710ademoapp.GenericTextWatcher;
+import com.csl.cs710ademoapp.MainActivity;
+import com.csl.cs710ademoapp.R;
+import com.csl.cslibrary4a.ReaderDevice;
+import com.csl.cslibrary4a.RfidReaderChipData;
+
+public class AccessEm4325PassiveFragment extends CommonFragment {
+ final boolean DEBUG = true;
+ EditText editTextRWTagID, editTextAccessRWAccPassword, editTextaccessRWAntennaPower;
+
+ TextView textViewTemperature;
+ Button buttonRead;
+
+ enum ReadWriteTypes {
+ NULL, TEMPERATURE
+ }
+ boolean operationRead = false;
+ ReadWriteTypes readWriteTypes;
+
+ private AccessTask accessTask;
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ super.onCreateView(inflater, container, savedInstanceState, false);
+ return inflater.inflate(R.layout.fragment_access_em4325passive, container, false);
+ }
+
+ @Override
+ public void onActivityCreated(Bundle savedInstanceState) {
+ super.onActivityCreated(savedInstanceState);
+
+ editTextRWTagID = (EditText) getActivity().findViewById(R.id.accessCCPTagID);
+ editTextAccessRWAccPassword = (EditText) getActivity().findViewById(R.id.accessCCPAccPasswordValue);
+ editTextAccessRWAccPassword.addTextChangedListener(new GenericTextWatcher(editTextAccessRWAccPassword, 8));
+ editTextAccessRWAccPassword.setText("00000000");
+
+ textViewTemperature = (TextView) getActivity().findViewById(R.id.accessCCPTemperature);
+
+ editTextaccessRWAntennaPower = (EditText) getActivity().findViewById(R.id.accessCCPAntennaPower);
+ editTextaccessRWAntennaPower.setText(String.valueOf(300));
+
+ buttonRead = (Button) getActivity().findViewById(R.id.accessCCPReadButton);
+ buttonRead.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (isOperationRunning()) return;
+ readWriteTypes = ReadWriteTypes.NULL;
+ bRequestCheck = true;
+ operationRead = true; startAccessTask();
+ }
+ });
+
+ setupTagID();
+ MainActivity.csLibrary4A.setSameCheck(false);
+ }
+
+ @Override
+ public void onDestroy() {
+ if (accessTask != null) accessTask.cancel(true);
+ MainActivity.csLibrary4A.setSameCheck(true);
+ MainActivity.csLibrary4A.restoreAfterTagSelect();
+ super.onDestroy();
+ }
+
+ boolean userVisibleHint = false;
+ @Override
+ public void setUserVisibleHint(boolean isVisibleToUser) {
+ super.setUserVisibleHint(isVisibleToUser);
+ if(getUserVisibleHint()) {
+ userVisibleHint = true;
+ MainActivity.csLibrary4A.appendToLog("AccessEm4325PassiveFragment is now VISIBLE");
+ setupTagID();
+ // setNotificationListener();
+ } else {
+ userVisibleHint = false;
+ MainActivity.csLibrary4A.appendToLog("AccessEm4325PassiveFragment is now INVISIBLE");
+// MainActivity.mCs108Library4a.setNotificationListener(null);
+ }
+ }
+
+ public AccessEm4325PassiveFragment() {
+ super("AccessEm4325PassiveFragment");
+ }
+
+ void setupTagID() {
+ ReaderDevice tagSelected = MainActivity.tagSelected;
+ if (tagSelected != null) {
+ if (tagSelected.getSelected() == true) {
+ if (editTextRWTagID != null) editTextRWTagID.setText(tagSelected.getAddress());
+ }
+ }
+ }
+
+ boolean isOperationRunning() {
+ if (MainActivity.csLibrary4A.isBleConnected() == false) {
+ Toast.makeText(MainActivity.mContext, R.string.toast_ble_not_connected, Toast.LENGTH_SHORT).show();
+ return true;
+ } else if (MainActivity.csLibrary4A.isRfidFailure()) {
+ Toast.makeText(MainActivity.mContext, "Rfid is disabled", Toast.LENGTH_SHORT).show();
+ return true;
+ } else if (accessTask != null) {
+ if (accessTask.getStatus() == AsyncTask.Status.RUNNING) {
+ Toast.makeText(MainActivity.mContext, "Running acccess task. Please wait", Toast.LENGTH_SHORT).show();
+ return true;
+ }
+ }
+ return false;
+ }
+
+ void startAccessTask() {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("startAccessTask()");
+ if (updating == false) {
+ updating = true; bankProcessing = 0;
+ mHandler.removeCallbacks(updateRunnable);
+ mHandler.post(updateRunnable);
+ }
+ }
+ boolean updating = false; int bankProcessing = 0;
+ private final Runnable updateRunnable = new Runnable() {
+ @Override
+ public void run() {
+ boolean rerunRequest = false; boolean taskRequest = false;
+ if (accessTask == null) {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("AccessEm4325PassiveFragment().updateRunnable(): NULL accessReadWriteTask");
+ taskRequest = true;
+ } else if (accessTask.getStatus() != AsyncTask.Status.FINISHED) {
+ rerunRequest = true;
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("AccessEm4325PassiveFragment().updateRunnable(): accessReadWriteTask.getStatus() = " + accessTask.getStatus().toString());
+ } else {
+ taskRequest = true;
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("AccessEm4325PassiveFragment().updateRunnable(): FINISHED accessReadWriteTask");
+ }
+ if (processResult()) { rerunRequest = true; MainActivity.csLibrary4A.appendToLog("updateRunnable: processResult is TRUE with bankprocessing = " + bankProcessing);}
+ else if (taskRequest) {
+ boolean invalid = processTickItems();
+ MainActivity.csLibrary4A.appendToLog("updateRunnable: processTickItems Result = " + invalid + ", bankprocessing = " + bankProcessing);
+ if (bankProcessing++ != 0 && invalid) rerunRequest = false;
+ else {
+ RfidReaderChipData.HostCommands hostCommand;
+ if (readWriteTypes == ReadWriteTypes.TEMPERATURE && operationRead) hostCommand = RfidReaderChipData.HostCommands.CMD_GETSENSORDATA;
+ else if (operationRead) hostCommand = RfidReaderChipData.HostCommands.CMD_18K6CREAD;
+ else hostCommand = RfidReaderChipData.HostCommands.CMD_18K6CWRITE;
+ MainActivity.csLibrary4A.appendToLog("hostCommand = " + hostCommand.toString());
+ accessTask = new AccessTask(buttonRead, null, invalid, true,
+ editTextRWTagID.getText().toString(), 1, 32,
+ editTextAccessRWAccPassword.getText().toString(),
+ Integer.valueOf(editTextaccessRWAntennaPower.getText().toString()),
+ hostCommand,
+ 0, 0, true, false,
+ null, null, null, null, null);
+ accessTask.execute();
+ rerunRequest = true;
+ MainActivity.csLibrary4A.appendToLog("accessTask is created");
+ }
+ }
+ if (rerunRequest) {
+ mHandler.postDelayed(updateRunnable, 500);
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("AccessEm4325PassiveFragment().updateRunnable(): Restart");
+ }
+ else updating = false;
+ MainActivity.csLibrary4A.appendToLog("AccessEm4325PassiveFragment().updateRunnable(): Ending with updating = " + updating);
+ }
+ };
+
+ short setTemperature(float fTemperature) {
+ if (fTemperature > 63.75) fTemperature = (float) 63.75;
+ else if (fTemperature < -64) fTemperature = -64;
+ boolean bNegative = false;
+ if (fTemperature < 0) { bNegative = true; fTemperature = 0 - fTemperature; }
+ fTemperature += 0.125; fTemperature /= 0.25;
+ short retValue = (short)fTemperature;
+ if (bNegative) { retValue--; retValue &= 0xFF; retValue ^= 0xFF; retValue |= 0x100; }
+ return retValue;
+ }
+ String getTemperatue(String stringInput) {
+ byte bValue = Byte.parseByte(stringInput.substring(0,1), 16);
+ byte bValue2 = Byte.parseByte(stringInput.substring(1, 2), 16); bValue2 <<= 4;
+ byte bValue3 = Byte.parseByte(stringInput.substring(2, 3), 16); bValue2 |= bValue3;
+ String stringValue = ""; short sValue = (short)(bValue2 & 0xFF);
+ if ((bValue & 0x01) != 0) { stringValue = "-"; bValue2 ^= 0xFF; sValue = (short)(bValue2 & 0xFF); sValue++; }
+ stringValue += String.valueOf((sValue & 0x1FF) >> 2);
+ switch (sValue & 0x03) {
+ case 1:
+ stringValue += ".25";
+ break;
+ case 2:
+ stringValue += ".50";
+ break;
+ case 3:
+ stringValue += ".75";
+ break;
+ }
+ return stringValue;
+ }
+
+
+ boolean bRequestCheck;
+ boolean processResult() {
+ String accessResult = null;
+ if (accessTask == null) return false;
+ else if (accessTask.getStatus() != AsyncTask.Status.FINISHED) return false;
+ else {
+ accessResult = accessTask.accessResult;
+ MainActivity.csLibrary4A.appendToLog("accessResult 2 bankProcessing = " + bankProcessing + ", accessResult = " + accessTask.accessResult );
+ if (accessResult == null) {
+ if (readWriteTypes == ReadWriteTypes.TEMPERATURE && operationRead) {
+ bRequestCheck = false;
+ }
+ } else {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("accessResult = " + accessResult);
+ if (readWriteTypes == ReadWriteTypes.TEMPERATURE && operationRead == false) {
+ } else if (readWriteTypes == ReadWriteTypes.TEMPERATURE && operationRead) {
+ bRequestCheck = false; readWriteTypes = ReadWriteTypes.NULL;
+ MainActivity.csLibrary4A.appendToLog("accessResult of Temperature = " + accessResult);
+
+ if (accessResult.length() >= 16) {
+ int indexBegin = accessResult.length() - 16;
+ String stringValue = accessResult.substring(indexBegin, indexBegin + 4);
+ MainActivity.csLibrary4A.appendToLog("temperature part of Temperature accessResult = " + stringValue);
+ accessResult = stringValue; //"00B5"; //stringValue;
+ }
+ if (accessResult.length() == 4) {
+ byte bValue = Byte.parseByte(accessResult.substring(1, 2), 16);
+ Integer iValue2 = Integer.parseInt(accessResult.substring(2, 4), 16);
+ iValue2 &= 0x1FF;
+ if ((bValue & 0x01) != 0 && iValue2 == 0) textViewTemperature.setText("Invalid");
+ else {
+ String stringValue = getTemperatue(accessResult.substring(1, 4));
+ stringValue += (char) 0x00B0 + "C";
+ textViewTemperature.setText(stringValue);
+ }
+ }
+ }
+ }
+ accessTask = null;
+ return true;
+ }
+ }
+ boolean processTickItems() {
+ boolean invalidRequest1 = false;
+ int accSize = 0, accOffset = 0;
+ String writeData = "";
+
+ if (bRequestCheck) {
+ readWriteTypes = ReadWriteTypes.TEMPERATURE;
+ if (bankProcessing == 0) {
+ if (operationRead) {
+ textViewTemperature = (TextView) getActivity().findViewById(R.id.accessCCPTemperature);
+ textViewTemperature.setText("");
+ accOffset = 0x10D; accSize = 1; operationRead = false; writeData = "0000";
+ } else invalidRequest1 = true;
+ } else {
+ operationRead = true;
+ MainActivity.csLibrary4A.macWrite(0x11F, 3);
+ return false;
+ }
+ } else {
+ invalidRequest1 = true;
+ }
+
+ if (invalidRequest1 == false) {
+ if (MainActivity.csLibrary4A.setAccessBank(3) == false) {
+ invalidRequest1 = true;
+ }
+ }
+ if (invalidRequest1 == false) {
+ if (MainActivity.csLibrary4A.setAccessOffset(accOffset) == false) {
+ invalidRequest1 = true;
+ }
+ }
+ if (invalidRequest1 == false) {
+ if (accSize == 0) {
+ invalidRequest1 = true;
+ } else if (MainActivity.csLibrary4A.setAccessCount(accSize) == false) {
+ invalidRequest1 = true;
+ }
+ }
+ if (invalidRequest1 == false && operationRead == false) {
+ if (invalidRequest1 == false) {
+ if (MainActivity.csLibrary4A.setAccessWriteData(writeData) == false) {
+ invalidRequest1 = true;
+ }
+ }
+ }
+ return invalidRequest1;
+ }
+}
+
+
+
+package com.csl.cs710ademoapp.fragments;
+
+import android.app.Activity;
+import android.os.AsyncTask;
+import android.os.Bundle;
+import android.os.Handler;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.AdapterView;
+import android.widget.ArrayAdapter;
+import android.widget.Button;
+import android.widget.CheckBox;
+import android.widget.EditText;
+import android.widget.Spinner;
+import android.widget.TableRow;
+import android.widget.TextView;
+import android.widget.Toast;
+
+import com.csl.cs710ademoapp.AccessTask;
+import com.csl.cs710ademoapp.CustomPopupWindow;
+import com.csl.cs710ademoapp.MainActivity;
+import com.csl.cs710ademoapp.R;
+import com.csl.cs710ademoapp.SaveList2ExternalTask;
+import com.csl.cs710ademoapp.SelectTag;
+import com.csl.cslibrary4a.RfidReaderChipData;
+
+import java.text.SimpleDateFormat;
+import java.util.Date;
+
+import static com.csl.cs710ademoapp.MainActivity.mContext;
+
+public class AccessFdmicroFragment extends CommonFragment {
+ SelectTag selectTag;
+ Spinner spinnerSelectCommand, spinnerSelectAuth, spinnerSelectGetSource;
+ TableRow tableRowOffsetLength, tableRowValue, tableRowAuth, tableRowGetTemperature, tableRowGetTemperature1, tableRowLogging, tableRowReg, tableRowEnable;
+ EditText editTextMemoryValue, editTextDelayStart, editTextCntLimit, editTextStep;
+ TextView textViewTemperatureValue, textViewBatteryValue, textViewLoggingValue, textViewLoggingValue1;
+ Button buttonRead, buttonWrite;
+ SimpleDateFormat formatter;
+
+ boolean operationRunning = false, operationRead = false, operationReadTemperature = false, operationReadBattery = false, operationSetLogging = false, operationCheckLogging = false, operationStopLogging = false, operationGetLogging = false;
+ AccessTask accessTask;
+
+ void clearOperationSelect() {
+ operationReadTemperature = false; operationReadBattery = false; operationSetLogging = false; operationCheckLogging = false; operationStopLogging = false; operationGetLogging = false;
+ }
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ super.onCreateView(inflater, container, savedInstanceState, false);
+ return inflater.inflate(R.layout.fragment_access_fdmicro, container, false);
+ }
+
+ @Override
+ public void onActivityCreated(Bundle savedInstanceState) {
+ super.onActivityCreated(savedInstanceState);
+
+ selectTag = new SelectTag((Activity)getActivity(), 0);
+
+ tableRowOffsetLength = (TableRow) getActivity().findViewById(R.id.accessFDOffsetLengthRow);
+ tableRowValue = (TableRow) getActivity().findViewById(R.id.accessFDValueRow);
+ tableRowAuth = (TableRow) getActivity().findViewById(R.id.accessFDAuthRow);
+ tableRowGetTemperature = (TableRow) getActivity().findViewById(R.id.accessFDGetTemperatureRow);
+ tableRowGetTemperature1 = (TableRow) getActivity().findViewById(R.id.accessFDGetTemperatureRow1);
+ tableRowLogging = (TableRow) getActivity().findViewById(R.id.accessFDLoggingRow);
+ tableRowReg = (TableRow) getActivity().findViewById(R.id.accessFDRegRow);
+ tableRowEnable = (TableRow) getActivity().findViewById(R.id.accessFDEnableRow);
+
+ spinnerSelectCommand = (Spinner) getActivity().findViewById(R.id.selectCommand);
+ ArrayAdapter targetAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.fd_command_options, R.layout.custom_spinner_layout);
+ targetAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+ spinnerSelectCommand.setAdapter(targetAdapter);
+ spinnerSelectCommand.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
+ @Override
+ public void onItemSelected(AdapterView> parent, View view, int position, long id) {
+ commandSelected(position);
+ }
+
+ @Override
+ public void onNothingSelected(AdapterView> parent) {
+
+ }
+ });
+
+ editTextMemoryValue = (EditText) getActivity().findViewById(R.id.accessFDMemoryValue);
+
+ spinnerSelectAuth = (Spinner) getActivity().findViewById(R.id.accessFDselectAuth);
+ ArrayAdapter targetAdapterAuth = ArrayAdapter.createFromResource(getActivity(), R.array.fd_auth_options, R.layout.custom_spinner_layout);
+ targetAdapterAuth.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+ spinnerSelectAuth.setAdapter(targetAdapterAuth);
+
+ spinnerSelectGetSource = (Spinner) getActivity().findViewById(R.id.accessFDSelectGetSource);
+ ArrayAdapter targetAdapterGetSource = ArrayAdapter.createFromResource(getActivity(), R.array.fd_getSource_options, R.layout.custom_spinner_layout);
+ targetAdapterAuth.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+ spinnerSelectGetSource.setAdapter(targetAdapterGetSource);
+
+ Button buttonCheckTemperature = (Button) getActivity().findViewById(R.id.accessFDcheckTemperature);
+ buttonCheckTemperature.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (isOperationRunning()) return;
+ clearOperationSelect(); operationReadTemperature = true;
+ textViewTemperatureValue.setText("");
+ readWriteOperation();
+ }
+ });
+ textViewTemperatureValue = (TextView) getActivity().findViewById(R.id.accessFDtemperatureValue);
+
+ Button buttonCheckBattery = (Button) getActivity().findViewById(R.id.accessFDcheckBattery);
+ buttonCheckBattery.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (isOperationRunning()) return;
+ clearOperationSelect(); operationReadBattery = true;
+ textViewBatteryValue.setText("");
+ readWriteOperation();
+ }
+ });
+ textViewBatteryValue = (TextView) getActivity().findViewById(R.id.accessFDbatteryValue);
+
+ editTextDelayStart = (EditText) getActivity().findViewById(R.id.accessFDvdetDelayStartCfg);
+ editTextCntLimit = (EditText) getActivity().findViewById(R.id.accessFDrtcCntLimit);
+ editTextStep = (EditText) getActivity().findViewById(R.id.accessFDstepCfg);
+ formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
+
+ Button buttonSetLogging = (Button) getActivity().findViewById(R.id.accessFDSetLogging);
+ buttonSetLogging.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (isOperationRunning()) return;
+ clearOperationSelect(); operationSetLogging = true;
+ textViewLoggingValue.setText("");
+ readWriteOperation();
+ }
+ });
+ Button buttonCheckLogging = (Button) getActivity().findViewById(R.id.accessFDCheckLogging);
+ buttonCheckLogging.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (isOperationRunning()) return;
+ clearOperationSelect(); operationCheckLogging = true;
+ textViewLoggingValue.setText("");
+ readWriteOperation();
+ }
+ });
+ Button buttonStopLogging = (Button) getActivity().findViewById(R.id.accessFDStopLogging);
+ buttonStopLogging.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (isOperationRunning()) return;
+ clearOperationSelect(); operationStopLogging = true;
+ textViewLoggingValue.setText("");
+ readWriteOperation();
+ }
+ });
+ Button buttonGetLogging = (Button) getActivity().findViewById(R.id.accessFDGetLogging);
+ buttonGetLogging.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (isOperationRunning()) return;
+ clearOperationSelect(); operationGetLogging = true;
+ textViewLoggingValue1.setText("");
+ readWriteOperation();
+ }
+ });
+ textViewLoggingValue = (TextView) getActivity().findViewById(R.id.accessFDloggingValue);
+ textViewLoggingValue1 = (TextView) getActivity().findViewById(R.id.accessFDloggingValue1);
+
+ Button buttonSaveLogging = (Button) getActivity().findViewById(R.id.accessFDSaveLogging);
+ buttonSaveLogging.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (isOperationRunning()) return;
+ SaveList2ExternalTask saveExternalTask = new SaveList2ExternalTask(MainActivity.sharedObjects.tagsList);
+ String strMessage = "EPC: " + selectTag.editTextTagID.getText().toString() + "\n";
+ strMessage += textViewLoggingValue1.getText().toString();
+ if (logData != null) {
+ Date date = logData.dateLogStart;
+ if (date != null) {
+ long ltime = date.getTime();
+ ltime += (logData.minLogStartDelay * 1000 * 60);
+ if (logData.iSampleSize > 0) {
+ ltime += (logData.iSampleSize -1 ) * logData.secLogSampleInterval * 1000;
+ }
+ date.setTime(ltime);
+ strMessage += ("Stop: " + formatter.format(date) + "\n");
+ }
+ }
+ String resultDisplay = saveExternalTask.save2File(strMessage, false);
+ CustomPopupWindow customPopupWindow = new CustomPopupWindow(mContext);
+ customPopupWindow.popupStart(resultDisplay, false);
+ }
+ });
+
+ buttonRead = (Button) getActivity().findViewById(R.id.accessRWReadButton);
+ buttonRead.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (isOperationRunning()) return;
+ clearOperationSelect(); operationRead = true;
+ readWriteOperation();
+ }
+ });
+
+ buttonWrite = (Button) getActivity().findViewById(R.id.accessRWWriteButton);
+ buttonWrite.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (isOperationRunning()) return;
+ clearOperationSelect(); operationRead = false;
+ readWriteOperation();
+ }
+ });
+
+ MainActivity.csLibrary4A.setSameCheck(true);
+ }
+
+ @Override
+ public void onResume() {
+ super.onResume();
+ MainActivity.csLibrary4A.appendToLog("AccessFdmicro onResume !!!");
+ }
+
+ @Override
+ public void onPause() {
+ super.onPause();
+ }
+
+ @Override
+ public void onDestroy() {
+ MainActivity.csLibrary4A.setSameCheck(true);
+ MainActivity.csLibrary4A.restoreAfterTagSelect();
+ super.onDestroy();
+ }
+
+ boolean userVisibleHint = false;
+ @Override
+ public void setUserVisibleHint(boolean isVisibleToUser) {
+ super.setUserVisibleHint(isVisibleToUser);
+ if (getUserVisibleHint()) {
+ userVisibleHint = true;
+ selectTag.updateBankSelected();
+ MainActivity.csLibrary4A.appendToLog("AccessFdmicroFragment is now VISIBLE");
+ } else {
+ userVisibleHint = false;
+ MainActivity.csLibrary4A.appendToLog("AccessFdmicroFragment is now INVISIBLE");
+ }
+ }
+
+ public AccessFdmicroFragment() {
+ super("AccessFdmicroFragment");
+ }
+
+ class LogData {
+ Date dateLogStart;
+ int minLogStartDelay;
+ int secLogSampleInterval;
+ int iSampleSize;
+ }
+ LogData logData;
+
+ void commandSelected(int position) {
+ if (position < 0 || position > 2) position = spinnerSelectCommand.getSelectedItemPosition();
+ MainActivity.csLibrary4A.appendToLog("commandSelected position = " + position);
+ switch (position) {
+ case 0:
+ tableRowOffsetLength.setVisibility(View.VISIBLE);
+ tableRowValue.setVisibility(View.VISIBLE);
+ tableRowValue.setVisibility(View.VISIBLE);
+ tableRowAuth.setVisibility(View.GONE);
+ tableRowGetTemperature.setVisibility(View.GONE);
+ tableRowGetTemperature1.setVisibility(View.GONE);
+ tableRowLogging.setVisibility(View.GONE);
+ tableRowReg.setVisibility(View.GONE);
+ tableRowEnable.setVisibility(View.GONE);
+ buttonRead.setText(getResources().getString(R.string.read_title));
+ buttonWrite.setText("WRITE");
+ buttonWrite.setVisibility(View.VISIBLE);
+ break;
+ case 1:
+ tableRowOffsetLength.setVisibility(View.GONE);
+ tableRowValue.setVisibility(View.GONE);
+ tableRowAuth.setVisibility(View.VISIBLE);
+ tableRowGetTemperature.setVisibility(View.GONE);
+ tableRowGetTemperature1.setVisibility(View.GONE);
+ tableRowLogging.setVisibility(View.GONE);
+ tableRowReg.setVisibility(View.GONE);
+ tableRowEnable.setVisibility(View.GONE);
+ buttonRead.setText(getResources().getString(R.string.start_title));
+ buttonWrite.setVisibility(View.GONE);
+ break;
+ case 2:
+ tableRowOffsetLength.setVisibility(View.GONE);
+ tableRowValue.setVisibility(View.GONE);
+ tableRowAuth.setVisibility(View.GONE);
+ tableRowGetTemperature.setVisibility(View.VISIBLE);
+ tableRowGetTemperature1.setVisibility(View.VISIBLE);
+ tableRowLogging.setVisibility(View.GONE);
+ tableRowReg.setVisibility(View.GONE);
+ tableRowEnable.setVisibility(View.GONE);
+ buttonRead.setText(getResources().getString(R.string.read_title));
+ buttonWrite.setText("MEASURE");
+ buttonWrite.setVisibility(View.VISIBLE);
+ break;
+ case 3:
+ tableRowOffsetLength.setVisibility(View.GONE);
+ tableRowValue.setVisibility(View.GONE);
+ tableRowAuth.setVisibility(View.GONE);
+ tableRowGetTemperature.setVisibility(View.GONE);
+ tableRowGetTemperature1.setVisibility(View.GONE);
+ tableRowLogging.setVisibility(View.VISIBLE);
+ tableRowReg.setVisibility(View.GONE);
+ tableRowEnable.setVisibility(View.GONE);
+ buttonRead.setText(getResources().getString(R.string.start_title));
+ buttonWrite.setText("STOP");
+ buttonWrite.setVisibility(View.VISIBLE);
+ break;
+ case 4:
+ tableRowOffsetLength.setVisibility(View.GONE);
+ tableRowValue.setVisibility(View.GONE);
+ tableRowValue.setVisibility(View.GONE);
+ tableRowAuth.setVisibility(View.GONE);
+ tableRowGetTemperature.setVisibility(View.GONE);
+ tableRowGetTemperature1.setVisibility(View.GONE);
+ tableRowLogging.setVisibility(View.GONE);
+ tableRowReg.setVisibility(View.VISIBLE);
+ tableRowEnable.setVisibility(View.GONE);
+ buttonRead.setText(getResources().getString(R.string.read_title));
+ buttonWrite.setText("WRITE");
+ buttonWrite.setVisibility(View.VISIBLE);
+ break;
+ case 5:
+ case 6:
+ case 7:
+ case 8:
+ tableRowOffsetLength.setVisibility(View.GONE);
+ tableRowValue.setVisibility(View.GONE);
+ tableRowValue.setVisibility(View.GONE);
+ tableRowAuth.setVisibility(View.GONE);
+ tableRowGetTemperature.setVisibility(View.GONE);
+ tableRowGetTemperature1.setVisibility(View.GONE);
+ tableRowLogging.setVisibility(View.GONE);
+ tableRowReg.setVisibility(View.GONE);
+ CheckBox checkBox = (CheckBox) getActivity().findViewById(R.id.accessFDEnable);
+ if (position == 6) checkBox.setText("refresh temperature measurement");
+ else checkBox.setText("Enable");
+ if (position == 7) tableRowEnable.setVisibility(View.GONE);
+ else tableRowEnable.setVisibility(View.VISIBLE);
+ buttonRead.setText(getResources().getString(R.string.read_title));
+ buttonRead.setText(getResources().getString(R.string.start_title));
+ buttonWrite.setVisibility(View.GONE);
+ break;
+ default:
+ buttonRead.setText(getResources().getString(R.string.read_title));
+ buttonWrite.setText("WRITE");
+ buttonWrite.setVisibility(View.VISIBLE);
+ break;
+ }
+ }
+
+ boolean isOperationRunning() {
+ if (accessTask != null) {
+ if (accessTask.getStatus() == AsyncTask.Status.RUNNING) {
+ Toast.makeText(MainActivity.mContext, "Running acccess task. Please wait", Toast.LENGTH_SHORT).show();
+ return true;
+ }
+ }
+ return false;
+ }
+ void readWriteOperation() {
+ RfidReaderChipData.HostCommands hostCommand = null;
+ if (isOperationRunning()) return;
+ iOtherFlowCount = 0; bLogging = false; iTimeNumber = 0; iTimeTotal = 0;
+ if (operationReadTemperature || operationReadBattery || operationSetLogging || operationCheckLogging || operationGetLogging) {
+ operationRead = true;
+ tableRowEnable.setVisibility(View.GONE);
+ buttonRead.setText(getResources().getString(R.string.start_title));
+ buttonWrite.setVisibility(View.GONE);
+
+ MainActivity.csLibrary4A.set_fdCmdCfg(0x0000);
+ hostCommand = RfidReaderChipData.HostCommands.CMD_FDM_OPMODE_CHECK;
+ } else {
+ MainActivity.csLibrary4A.appendToLog("Item Selected is " + spinnerSelectCommand.getSelectedItemPosition());
+ int position = spinnerSelectCommand.getSelectedItemPosition();
+ if (operationStopLogging) {
+ position = 3; operationRead = false;
+ }
+ switch (position) {
+ case 0:
+ EditText editTextMemoryOffset = (EditText) getActivity().findViewById(R.id.accessFDmemoryOffset);
+ int iMemoryOffset = getEditTextHexValue(editTextMemoryOffset, 4);
+ iMemoryOffset &= 0xFFFC;
+ editTextMemoryOffset.setText(String.format("%X", iMemoryOffset));
+
+ EditText editTextMemoryLength = (EditText) getActivity().findViewById(R.id.accessFDmemoryLength);
+ int iMemoryLength = 0;
+ try {
+ iMemoryLength = Integer.parseInt(editTextMemoryLength.getText().toString());
+ } catch (Exception ex) { }
+ if (iMemoryLength <= 0) iMemoryLength = 1;
+ if (operationRead) {
+ if (iMemoryLength != (iMemoryLength / 4) * 4)
+ iMemoryLength = ((iMemoryLength / 4) + 1) * 4;
+ if (iMemoryLength > 512) iMemoryLength = 512;
+ } else {
+ if (iMemoryLength > 4) iMemoryLength = 4;
+ }
+ editTextMemoryLength.setText(String.valueOf(iMemoryLength));
+
+ if (operationRead) {
+ editTextMemoryValue.setText("");
+ MainActivity.csLibrary4A.set_fdReadMem(iMemoryOffset, iMemoryLength);
+ } else {
+ String strValue = editTextMemoryValue.getText().toString();
+ if (strValue.length() > 8)
+ strValue = strValue.substring(strValue.length() - 8);
+ if (strValue.length() > 2 * iMemoryLength)
+ strValue = strValue.substring(strValue.length() - 2 * iMemoryLength);
+ int iValue = 0;
+ try {
+ iValue = Integer.parseInt(strValue, 16);
+ } catch (Exception ex) {
+ strValue = "00";
+ }
+ strValue = String.format("%X", iValue);
+ editTextMemoryValue.setText(strValue);
+ MainActivity.csLibrary4A.set_fdWriteMem(iMemoryOffset, iMemoryLength, iValue);
+ }
+
+ hostCommand = (operationRead ? RfidReaderChipData.HostCommands.CMD_FDM_RDMEM : RfidReaderChipData.HostCommands.CMD_FDM_WRMEM);
+ break;
+ case 1:
+ int iConfig = spinnerSelectAuth.getSelectedItemPosition();
+ switch (iConfig) {
+ case 1:
+ iConfig = 3;
+ break;
+ case 2:
+ iConfig = 4;
+ break;
+ default:
+ break;
+ }
+ MainActivity.csLibrary4A.set_fdCmdCfg(iConfig); //0 (user area password), 3 (unlock password), 4 (stop logging password)
+
+ EditText editTextAuthPassword = (EditText) getActivity().findViewById(R.id.selectFDAuthPassword);
+ int iValue = getEditTextHexValue(editTextAuthPassword, 8);
+ MainActivity.csLibrary4A.set_fdPwd(iValue);
+
+ hostCommand = RfidReaderChipData.HostCommands.CMD_FDM_AUTH;
+ break;
+ case 2:
+ iConfig = 0;
+ CheckBox checkBoxGetTemperatureStartGet = (CheckBox) getActivity().findViewById(R.id.accessFDGetTemperatureStartGet);
+ if (true) {
+ if (operationRead) checkBoxGetTemperatureStartGet.setChecked(true);
+ else checkBoxGetTemperatureStartGet.setChecked(false);
+ }
+ if (checkBoxGetTemperatureStartGet.isChecked()) iConfig |= 0x80;
+ switch (spinnerSelectGetSource.getSelectedItemPosition()) {
+ case 1:
+ iConfig |= 0x10;
+ break;
+ case 2:
+ iConfig |= 0x20;
+ break;
+ case 3:
+ iConfig |= 0x30;
+ break;
+ }
+ CheckBox checkBoxGetTemperatureResultType = (CheckBox) getActivity().findViewById(R.id.accessFDGetTemperatureResultType);
+ if (checkBoxGetTemperatureResultType.isChecked()) iConfig |= 4;
+ CheckBox checkBoxGetTemperatureCheckField = (CheckBox) getActivity().findViewById(R.id.accessFDGetTemperatureCheckField);
+ if (checkBoxGetTemperatureCheckField.isChecked()) iConfig |= 2;
+ CheckBox checkBoxGetTemperatureStorageEnable = (CheckBox) getActivity().findViewById(R.id.accessFDGetTemperatureStorageEnable);
+ if (checkBoxGetTemperatureStorageEnable.isChecked()) iConfig |= 1;
+ MainActivity.csLibrary4A.set_fdCmdCfg(iConfig);
+
+ EditText editTextStoreOffset = (EditText) getActivity().findViewById(R.id.accessFDStoreOffset);
+ int iStoreOffset = getEditTextHexValue(editTextStoreOffset, 2);
+ MainActivity.csLibrary4A.set_fdBlockAddr4GetTemperature(iStoreOffset);
+
+ hostCommand = RfidReaderChipData.HostCommands.CMD_FDM_GET_TEMPERATURE;
+ break;
+ case 3:
+ MainActivity.csLibrary4A.set_fdCmdCfg(operationRead ? 0 : 80);
+
+ if (operationRead)
+ hostCommand = RfidReaderChipData.HostCommands.CMD_FDM_START_LOGGING;
+ else {
+ EditText editText = (EditText) getActivity().findViewById(R.id.selectFDLoggingPassword);
+ int iPassword = getEditTextHexValue(editText, 8);
+ MainActivity.csLibrary4A.set_fdPwd(iPassword);
+
+ hostCommand = RfidReaderChipData.HostCommands.CMD_FDM_STOP_LOGGING;
+ }
+ break;
+ case 4:
+ EditText editText = (EditText) getActivity().findViewById(R.id.accessFDRegOffset);
+ iValue = getEditTextHexValue(editText, 2);
+ iValue += 0xC000;
+ editText.setText(String.format("%04X", iValue));
+
+ EditText editText1 = (EditText) getActivity().findViewById(R.id.accessFDRegValue);
+ if (operationRead) {
+ editText1.setText("");
+ MainActivity.csLibrary4A.set_fdRegAddr(iValue);
+ hostCommand = RfidReaderChipData.HostCommands.CMD_FDM_RDREG;
+ } else {
+ int iValue1 = getEditTextHexValue(editText1, 4);
+ MainActivity.csLibrary4A.set_fdWrite(iValue, iValue1);
+ hostCommand = RfidReaderChipData.HostCommands.CMD_FDM_WRREG;
+ }
+ break;
+ case 5:
+ case 6:
+ case 7:
+ case 8:
+ CheckBox checkBox1 = (CheckBox) getActivity().findViewById(R.id.accessFDEnable);
+ iValue = 0;
+ if (checkBox1.isChecked()) {
+ if (position == 8) iValue = 2;
+ else if (position != 7) iValue = 1;
+ }
+ MainActivity.csLibrary4A.set_fdCmdCfg(iValue);
+ if (position == 5) hostCommand = RfidReaderChipData.HostCommands.CMD_FDM_DEEP_SLEEP;
+ else if (position == 6)
+ hostCommand = RfidReaderChipData.HostCommands.CMD_FDM_OPMODE_CHECK;
+ else if (position == 7)
+ hostCommand = RfidReaderChipData.HostCommands.CMD_FDM_INIT_REGFILE;
+ else if (position == 8)
+ hostCommand = RfidReaderChipData.HostCommands.CMD_FDM_LED_CTRL;
+ break;
+ default:
+ break;
+ }
+ }
+ doAccessTask(hostCommand);
+ }
+
+ void doAccessTask(RfidReaderChipData.HostCommands hostCommand) {
+ String selectMask = selectTag.editTextTagID.getText().toString();
+ int selectBank = selectTag.spinnerSelectBank.getSelectedItemPosition() + 1;
+ int selectOffset = Integer.valueOf(selectTag.editTextSelectOffset.getText().toString());
+ boolean invalid = false;
+ accessTask = new AccessTask((operationRead ? buttonRead : buttonWrite), null, invalid, true,
+ selectMask, selectBank, selectOffset,
+ selectTag.editTextAccessPassword.getText().toString(),
+ Integer.valueOf(selectTag.editTextAccessAntennaPower.getText().toString()),
+ hostCommand,
+ 0, 0, true, false,
+ null, null, null, null, null);
+ accessTask.setRunnable(updateRunnable);
+ accessTask.execute();
+ }
+
+ Handler handler = new Handler(); boolean bLogging = false; int iOtherFlowCount = 0, iTimeNumber = 0, iTimeTotal = 0, iDelayToStart = 0;
+ private final Runnable updateRunnable = new Runnable() {
+ final boolean DEBUG = true;
+ @Override
+ public void run() {
+ if (accessTask == null) return;
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("AAA: " + "accessTask.status = " + accessTask.getStatus().toString());
+ if (accessTask.getStatus() == AsyncTask.Status.RUNNING) {
+ mHandler.postDelayed(updateRunnable, 100);
+ return;
+ }
+
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("AAA: " + accessTask.accessResult + ": blogging with iOtherFlowCount = " + iOtherFlowCount);
+ if ((operationReadTemperature || operationReadBattery || operationSetLogging || operationCheckLogging || operationGetLogging) && (iOtherFlowCount == 0)) {
+ int iValue = 0;
+ try {
+ iValue = Integer.parseInt(accessTask.accessResult, 16);
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("AAA: " + accessTask.accessResult + ": blogging with iValue = " + iValue);
+ } catch (Exception ex) { }
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("AAA: " + accessTask.accessResult + ": blogging with iValue after catch = " + iValue);
+ if ((iValue & 0x1000) != 0) {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("AAA: " + accessTask.accessResult + ": blogging A is true");
+ bLogging = true;
+ if (operationCheckLogging == false && operationGetLogging == false) {
+ iOtherFlowCount = 99;
+ accessTask.accessResult += ": logging is in processed";
+ }
+ } else bLogging = false;
+ if (operationReadBattery && (iValue & 0x0100) == 0) {
+ iOtherFlowCount = 99;
+ accessTask.accessResult += ": less than 0.9V or no battery.";
+ }
+ }
+ if (operationGetLogging) {
+ switch (iOtherFlowCount) {
+ case 0:
+ MainActivity.csLibrary4A.set_fdReadMem(0, 12);
+ doAccessTask(RfidReaderChipData.HostCommands.CMD_FDM_RDMEM);
+ break;
+ case 1:
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("case 1: bLogging = " + bLogging + ", accessTask.accessResult = " + accessTask.accessResult);
+ if (accessTask.accessResult != null) {
+ Date date = null;
+ long lDateTime = -1;
+ int iDelay = -1, iInterval = -1;
+ if (accessTask.accessResult.length() >= 24) {
+ try {
+ String strDateTime = accessTask.accessResult.substring(6, 8);
+ strDateTime += accessTask.accessResult.substring(4, 6);
+ strDateTime += accessTask.accessResult.substring(2, 4);
+ strDateTime += accessTask.accessResult.substring(0, 2);
+ lDateTime = 1000 * Long.parseLong(strDateTime, 16);
+
+ String strDelay = accessTask.accessResult.substring(18, 20);
+ strDelay += accessTask.accessResult.substring(16, 18);
+ iDelay = Integer.parseInt(strDelay, 16);
+
+ String strInterval = accessTask.accessResult.substring(22, 24);
+ strInterval += accessTask.accessResult.substring(20, 22);
+ iInterval = Integer.parseInt(strInterval, 16);
+ } catch(Exception ex) { }
+ if (iInterval != -1) {
+ date = new Date();
+ date.setTime(lDateTime);
+ textViewLoggingValue1.append("Start: " + formatter.format(date) + "\n");
+ textViewLoggingValue1.append("delay: " + iDelay + " minutes\n");
+ textViewLoggingValue1.append("interval: " + iInterval + " seconds\n");
+ }
+ logData = new LogData();
+ logData.dateLogStart = date;
+ logData.minLogStartDelay = iDelay;
+ logData.secLogSampleInterval = iInterval;
+ }
+ }
+ if (bLogging) {
+ MainActivity.csLibrary4A.set_fdRegAddr(0xc094);
+ doAccessTask(RfidReaderChipData.HostCommands.CMD_FDM_RDREG);
+ } else {
+ MainActivity.csLibrary4A.set_fdReadMem(0xb188, 4);
+ doAccessTask(RfidReaderChipData.HostCommands.CMD_FDM_RDMEM);
+ }
+ break;
+ case 2:
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("bLogging = " + bLogging + ", accessTask.accessResult = " + accessTask.accessResult);
+ if (bLogging) {
+ operationGetLogging = false;
+ int iValue = 0;
+ try {
+ iValue = Integer.parseInt(accessTask.accessResult.substring(2,4), 16) & 0x30;
+ } catch (Exception ex) { }
+ String strMessage = "";
+ if (iValue == 0x10) strMessage = "Initial Delay Start";
+ else if (iValue == 0x20) strMessage = "Logging in Progress";
+ else if (iValue == 00) strMessage = "non-rtc";
+ textViewLoggingValue1.setText(accessTask.accessResult + ": " + strMessage + "\n");
+ break;
+ } else {
+ String strTemp = accessTask.accessResult;
+ iTimeTotal = Integer.parseInt(strTemp.substring(2, 4) + strTemp.substring(0, 2), 16);
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("iTimeTotal is set to " + iTimeTotal + ", with strTemp = " + strTemp);
+ textViewLoggingValue1.append("status: " + accessTask.accessResult + "\n");
+ iTimeTotal++;
+ }
+ logData.iSampleSize = 0;
+ default:
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("iOtherFlowCount = " + iOtherFlowCount + ", accessTask.accessResult = " + accessTask.accessResult);
+ if (iOtherFlowCount != 2) {
+ String strMessage = ""; //accessTask.accessResult + ": ";
+ String strAccessResult = accessTask.accessResult.substring(6, 8) + accessTask.accessResult.substring(4, 6) + accessTask.accessResult.substring(2, 4) + accessTask.accessResult.substring(0, 2);
+ Long lValue = Long.parseLong(strAccessResult, 16);
+ int iOddBit = 0;
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog(String.format("accessResult to lValue = %X", lValue));
+ for (int i = 0; i < 32; i++) {
+ if ((lValue & 1) != 0) {
+ iOddBit++;
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("accessResult, i=" + i + ", iOddbit=" + iOddBit);
+ }
+ lValue = lValue >> 1;
+ }
+ if ((iOddBit & 1) != 0)
+ strMessage += ("invalid checksum, " + strAccessResult);
+ else {
+ iTimeNumber = Integer.parseInt(strAccessResult.substring(0, 4), 16) & 0x7FFF;
+ strMessage += ("item " + iTimeNumber + ": ");
+ int iTemperature = Integer.parseInt(strAccessResult.substring(5, 8), 16) & 0x3FF;
+ strMessage += i2TemperatureString(iTemperature);
+ logData.iSampleSize++;
+ }
+ textViewLoggingValue1.append(strMessage + "\n");
+ }
+
+ if (iTimeTotal <= (iOtherFlowCount - 2) || bLogging) {
+ textViewLoggingValue1.append("end of logging data\n");
+ operationGetLogging = false;
+ commandSelected(spinnerSelectCommand.getSelectedItemPosition());
+ }
+ else {
+ int iValue = 0x1000 + (iOtherFlowCount - 2) * 4;
+ MainActivity.csLibrary4A.set_fdReadMem(iValue, 4);
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog(String.format("set_fdReadMem address = 0x%04x", iValue));
+ doAccessTask(RfidReaderChipData.HostCommands.CMD_FDM_RDMEM);
+ }
+ break;
+ }
+ iOtherFlowCount++;
+ } else if (operationCheckLogging) {
+ switch (iOtherFlowCount) {
+ case 0:
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog(accessTask.accessResult + ": blogging B is " + bLogging);
+ if (bLogging) {
+ MainActivity.csLibrary4A.set_fdRegAddr(0xc096);
+ doAccessTask(RfidReaderChipData.HostCommands.CMD_FDM_RDREG);
+ } else {
+ MainActivity.csLibrary4A.set_fdReadMem(0xb188, 4);
+ doAccessTask(RfidReaderChipData.HostCommands.CMD_FDM_RDMEM);
+ }
+ break;
+ default:
+ operationCheckLogging = false;
+ textViewLoggingValue.setText(accessTask.accessResult);
+ commandSelected(spinnerSelectCommand.getSelectedItemPosition());
+ break;
+ }
+ iOtherFlowCount++;
+ } else if (operationSetLogging) {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("AAA: " + "operationSetLogging: iOtherFlowCount = " + iOtherFlowCount + ", accessResult = " + accessTask.accessResult + ", resultError= " + accessTask.resultError);
+ switch (iOtherFlowCount) {
+ case 0: //0x4cb3,29d6
+ CheckBox checkBox = (CheckBox) getActivity().findViewById(R.id.accessFDenableLEDAutoFlash);
+ long lValue = 0x4db229d6;
+ if (checkBox.isChecked()) {
+ lValue |= 0x2000; lValue &= ~0x20;
+ lValue &= 0xFFFFFFFF;
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("AAA: " + "lValue = " + String.format("%08x", lValue));
+ } else {
+ lValue &= ~0x2000; lValue |= 0x20;
+ lValue &= 0xFFFFFFFF;
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("AAA: " + "lValue1 = " + String.format("%08x", lValue));
+ }
+ MainActivity.csLibrary4A.set_fdWriteMem(0xb040, 4, lValue); //~user_cfg1,user_cfg1,~user_cfg0,user_cfg0: default as 0xd629b34c
+ doAccessTask(RfidReaderChipData.HostCommands.CMD_FDM_WRMEM);
+ logData = new LogData();
+ break;
+ case 1:
+ int iValue0 = 3;
+ try {
+ iValue0 = Integer.parseInt(editTextCntLimit.getText().toString());
+ } catch (Exception ex) {
+ }
+ editTextCntLimit.setText(String.valueOf(iValue0));
+
+ String string1 = String.format("%04X", iValue0);
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("AAA: " + "accessResult: string1 = " + string1);
+ String string2 = string1.substring(2, 4) + string1.substring(0, 2) + "0000";
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("AAA: " + "accessResult: string2 = " + string2);
+ int iValue = Integer.parseInt(string2, 16);
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("AAA: " + String.format("accessResult: iValue = %X, iValue1 = %X", iValue0, iValue));
+
+ MainActivity.csLibrary4A.set_fdWriteMem(0xb094, 4, iValue); //rtc_cnt_limit: default as 0x00000003
+ doAccessTask(RfidReaderChipData.HostCommands.CMD_FDM_WRMEM);
+ break;
+ case 2:
+ MainActivity.csLibrary4A.set_fdWriteMem(0xb0a4, 4, 0x0A000100); //vdet_alarm_step_cfg, vdet_step_cfg: default as 0
+ doAccessTask(RfidReaderChipData.HostCommands.CMD_FDM_WRMEM);
+ break;
+ case 3:
+ iValue = 1;
+ try {
+ iValue = Integer.parseInt(editTextDelayStart.getText().toString());
+ } catch (Exception ex) { }
+ iDelayToStart = iValue;
+ editTextDelayStart.setText(String.valueOf(iValue));
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("AAA: " + String.format("accessResult: iValue = %X", iValue));
+
+ MainActivity.csLibrary4A.set_fdWrite(0xc084, iValue); //vdet_delay_cfg: default as 0xffff in minute
+ doAccessTask(RfidReaderChipData.HostCommands.CMD_FDM_WRREG);
+ logData.minLogStartDelay = iValue;
+ break;
+ case 4:
+ iValue = 1;
+ try {
+ iValue = Integer.parseInt(editTextStep.getText().toString());
+ } catch (Exception ex) { }
+ editTextStep.setText(String.valueOf(iValue));
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("AAA: " + String.format("accessResult: iValue = %X", iValue));
+
+ MainActivity.csLibrary4A.set_fdWrite(0xc085, iValue); //vdet_step_cfg: default as 0xffff in seconds
+ doAccessTask(RfidReaderChipData.HostCommands.CMD_FDM_WRREG);
+ logData.secLogSampleInterval = iValue;
+ break;
+ case 5:
+ MainActivity.csLibrary4A.set_fdWrite(0xc099, 0); //summary_min_temperature: default 0
+ doAccessTask(RfidReaderChipData.HostCommands.CMD_FDM_WRREG);
+ break;
+ case 6:
+ MainActivity.csLibrary4A.set_fdWrite(0xc098, 0x100); //summary_max_temperature: default 0
+ doAccessTask(RfidReaderChipData.HostCommands.CMD_FDM_WRREG);
+ break;
+ case 7:
+ MainActivity.csLibrary4A.set_fdRegAddr(0xc084); //vdet_delay_cfg: default as 0xffff in minute
+ doAccessTask(RfidReaderChipData.HostCommands.CMD_FDM_RDREG);
+ break;
+ case 8:
+ iValue = -1;
+ try {
+ iValue = Integer.parseInt(accessTask.accessResult);
+ } catch (Exception ex) { }
+ if (iValue != iDelayToStart) {
+ iOtherFlowCount = 99;
+ accessTask.accessResult += ": logging failure";
+ textViewLoggingValue.setText(accessTask.accessResult);
+ break;
+ }
+ MainActivity.csLibrary4A.set_fdCmdCfg(0);
+ doAccessTask(RfidReaderChipData.HostCommands.CMD_FDM_START_LOGGING);
+ break;
+ case 9:
+ Date date = new Date();
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("AAA: " + "Current time is " + formatter.format(date));
+
+ long longTemp = date.getTime() / 1000;
+ Long longValue = ((longTemp & 0xFF) << 24);
+ longValue |= ((longTemp & 0xFF00) << 8) ;
+ longValue |= ((longTemp & 0xFF0000) >> 8);
+ longValue |= ((longTemp & 0xFF000000) >> 24) ;
+ MainActivity.csLibrary4A.set_fdWriteMem(0, 4, longValue); //rtc_cnt_limit: default as 0x00000003
+ doAccessTask(RfidReaderChipData.HostCommands.CMD_FDM_WRMEM);
+ break;
+ case 10:
+ longValue = (((long)logData.minLogStartDelay & 0xFF) << 24);
+ longValue |= ((logData.minLogStartDelay & 0xFF00) << 8) ;
+ longValue |= ((logData.secLogSampleInterval & 0XFF) << 8 );
+ longValue |= ((logData.secLogSampleInterval & 0xFF00) >> 8) ;
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("AAA: " + String.format("longValue = %08x, minLogStartDelay = %04x, secLogSampleInterval = %04x", longValue, logData.minLogStartDelay, logData.secLogSampleInterval));
+ MainActivity.csLibrary4A.set_fdWriteMem(8, 4, longValue); //rtc_cnt_limit: default as 0x00000003
+ doAccessTask(RfidReaderChipData.HostCommands.CMD_FDM_WRMEM);
+ break;
+ default:
+ operationSetLogging = false;
+ if (iOtherFlowCount < 88) {
+ String strMessage = accessTask.accessResult;
+ iValue = Integer.parseInt(accessTask.accessResult, 16);
+ if (iValue != 0xFFFF) strMessage += ": Logging Program Started\n";
+ else strMessage += ": invalid logging. Please stop it and try again.\n";
+ textViewLoggingValue.setText(strMessage);
+ } else textViewLoggingValue.setText(accessTask.accessResult);
+ commandSelected(spinnerSelectCommand.getSelectedItemPosition());
+ break;
+ }
+ iOtherFlowCount++;
+ }
+ else if (operationReadBattery) {
+ switch(iOtherFlowCount) {
+ case 0:
+ MainActivity.csLibrary4A.set_fdWrite(0xc012, 0x0008);
+ doAccessTask(RfidReaderChipData.HostCommands.CMD_FDM_WRREG);
+ break;
+ case 1:
+ MainActivity.csLibrary4A.set_fdCmdCfg(0x12);
+ doAccessTask(RfidReaderChipData.HostCommands.CMD_FDM_GET_TEMPERATURE);
+ break;
+ case 2:
+ MainActivity.csLibrary4A.set_fdCmdCfg(0x92);
+ doAccessTask(RfidReaderChipData.HostCommands.CMD_FDM_GET_TEMPERATURE);
+ break;
+ default:
+ operationReadBattery = false;
+ if (iOtherFlowCount < 88) {
+ int iValue = 0;
+ try {
+ iValue = Integer.parseInt(accessTask.accessResult, 16);
+ float fValue = (float) (iValue & 0xFFFF);
+ fValue = fValue / 8192 * (float) 2.5;
+ textViewBatteryValue.setText(String.format("%.2fV", fValue));
+ } catch (Exception ex) {
+ }
+ } else textViewBatteryValue.setText(accessTask.accessResult);
+ commandSelected(spinnerSelectCommand.getSelectedItemPosition());
+ break;
+ }
+ iOtherFlowCount++;
+ }
+ else if (operationReadTemperature) {
+ switch(iOtherFlowCount) {
+ case 0:
+ MainActivity.csLibrary4A.set_fdWrite(0xc012, 0x0000);
+ doAccessTask(RfidReaderChipData.HostCommands.CMD_FDM_WRREG);
+ break;
+ case 1:
+ MainActivity.csLibrary4A.set_fdCmdCfg(0x06);
+ doAccessTask(RfidReaderChipData.HostCommands.CMD_FDM_GET_TEMPERATURE);
+ break;
+ case 2:
+ MainActivity.csLibrary4A.set_fdCmdCfg(0x86);
+ doAccessTask(RfidReaderChipData.HostCommands.CMD_FDM_GET_TEMPERATURE);
+ break;
+ default:
+ operationReadTemperature = false;
+ if (iOtherFlowCount < 88) {
+ int iValue = 0;
+ try {
+ iValue = Integer.parseInt(accessTask.accessResult, 16);
+ if ((iValue & 0x8000) != 0)
+ textViewTemperatureValue.setText("Store addr overflow");
+ else textViewTemperatureValue.setText(i2TemperatureString(iValue));
+ } catch (Exception ex) {
+ }
+ } else textViewTemperatureValue.setText(accessTask.accessResult);
+ commandSelected(spinnerSelectCommand.getSelectedItemPosition());
+ break;
+ }
+ iOtherFlowCount++;
+ } else {
+ int position = spinnerSelectCommand.getSelectedItemPosition();
+ if (operationStopLogging) {
+ operationStopLogging = false;
+ position = 3; operationRead = false;
+ }
+ switch (position) {
+ case 0:
+ if (operationRead) editTextMemoryValue.setText(accessTask.accessResult);
+ break;
+ case 1:
+ int iValue = Integer.parseInt(accessTask.accessResult, 16);
+ String strMessage = accessTask.accessResult + ":";
+ switch (iValue & 0x7) {
+ case 0:
+ strMessage = "User area";
+ break;
+ case 3:
+ strMessage = "Unlock";
+ break;
+ case 4:
+ strMessage = "Stop loggging";
+ break;
+ }
+ strMessage += " password:\nAuth is ";
+ if ((iValue & 0x80) != 0) strMessage += "passed";
+ else strMessage += "failed";
+ strMessage += "\nPassword is ";
+ if ((iValue & 0x40) != 0) strMessage += "zero";
+ else strMessage += "non-zero";
+ CustomPopupWindow customPopupWindow = new CustomPopupWindow(MainActivity.mContext);
+ customPopupWindow.popupStart(strMessage, false);
+ break;
+ case 2:
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("accessResult = " + accessTask.accessResult);
+ strMessage = accessTask.accessResult;
+ CheckBox checkBoxGetTemperatureResultType = (CheckBox) getActivity().findViewById(R.id.accessFDGetTemperatureResultType);
+ if (operationRead) {
+ iValue = Integer.parseInt(strMessage, 16);
+ if ((iValue & 0x8000) != 0) strMessage += ": store addr overflow";
+ else if (checkBoxGetTemperatureResultType.isChecked()) {
+ strMessage += ": temperature = ";
+ strMessage += i2TemperatureString(iValue);
+ } else
+ strMessage += String.format(": raw temperature data = %X", iValue & 0x1FFF);
+ } else {
+ if (strMessage.matches("FFFA")) strMessage += ": enough field energy";
+ else if (strMessage.matches("FFF5"))
+ strMessage += ": insufficient field energy";
+ else if (strMessage.matches("FFF0"))
+ strMessage += ": not yet enable field check";
+ }
+ customPopupWindow = new CustomPopupWindow(MainActivity.mContext);
+ customPopupWindow.popupStart(strMessage, false);
+ break;
+ case 3:
+ textViewLoggingValue.setText(accessTask.accessResult);
+ strMessage = accessTask.accessResult.trim();
+ if (operationRead) {
+ if (strMessage.matches("0000")) strMessage = null;
+ } else {
+ iValue = Integer.parseInt(strMessage, 16);
+ if ((iValue & 2) != 0) strMessage += ": password check is failed";
+ if ((iValue & 1) != 0) strMessage += ": RTC stop password is all zero";
+ }
+ if (strMessage != null) {
+ customPopupWindow = new CustomPopupWindow(MainActivity.mContext);
+ customPopupWindow.popupStart(strMessage, false);
+ }
+ break;
+ case 4:
+ strMessage = null;
+ if (operationRead) {
+ if (false && accessTask.accessResult.matches("FFFF"))
+ strMessage = accessTask.accessResult + ": invalid empty address";
+ else {
+ EditText editText = (EditText) getActivity().findViewById(R.id.accessFDRegValue);
+ editText.setText(accessTask.accessResult);
+ }
+ } else {
+ iValue = 0;
+ try {
+ iValue = Integer.parseInt(accessTask.accessResult, 16);
+ } catch (Exception ex) {
+ }
+ if (iValue != 0) {
+ strMessage = accessTask.accessResult;
+ if (iValue == (byte) 0xFFFF) strMessage += ": invalid/busy address";
+ else {
+ if ((iValue & 0x4) != 0)
+ strMessage += ": the register cannot be written";
+ if ((iValue & 0x02) != 0)
+ strMessage += ": invalid register addresss";
+ }
+ }
+ }
+ if (strMessage != null) {
+ customPopupWindow = new CustomPopupWindow(MainActivity.mContext);
+ customPopupWindow.popupStart(strMessage, false);
+ }
+ break;
+ case 5:
+ case 7:
+ case 8:
+ strMessage = accessTask.accessResult.trim();
+ if (strMessage != null && strMessage.length() != 0 && strMessage.matches("0000") == false) {
+ customPopupWindow = new CustomPopupWindow(MainActivity.mContext);
+ customPopupWindow.popupStart(strMessage, false);
+ }
+ if (position == 8 && iOtherFlowCount == 0) {
+ iOtherFlowCount++;
+ MainActivity.csLibrary4A.set_fdWriteMem(0xb040, 4, 0x4db229d6); //~user_cfg1,user_cfg1,~user_cfg0,user_cfg0: default as 0xd629b34c
+ doAccessTask(RfidReaderChipData.HostCommands.CMD_FDM_WRMEM);
+ }
+ break;
+ case 6:
+ strMessage = accessTask.accessResult;
+ iValue = Integer.parseInt(strMessage, 16);
+ if ((iValue & 0x2000) != 0) strMessage += ": user_access_en";
+ if ((iValue & 0x1000) != 0) strMessage += ": rtc logging";
+ if ((iValue & 0x800) != 0) strMessage += ": vdet_process_flag";
+ if ((iValue & 0x200) != 0) strMessage += ": light_chk_flag";
+ if ((iValue & 0x100) != 0) strMessage += ": vbat_pwr_flag";
+ customPopupWindow = new CustomPopupWindow(MainActivity.mContext);
+ customPopupWindow.popupStart(strMessage, false);
+ break;
+ default:
+ break;
+ }
+ }
+ }
+ };
+
+ String i2TemperatureString(int iValue) {
+ String strMessage = "";
+ if ((iValue & 0x200) != 0) {
+ strMessage += "-";
+ iValue ^= 0x3FF;
+ iValue++;
+ }
+ if (true) { //8 bit data, 2 bit decimal
+ strMessage += String.format("%d.", (iValue >> 2) & 0xFF);
+ strMessage += String.format("%d\u2103", (iValue & 3) * 100 / 4);
+ } else { //7 bit data, 3 bit decimal
+ strMessage += String.format("%d.", (iValue >> 3) & 0x7F);
+ strMessage += String.format("%d\u2103", (iValue & 7) * 1000 / 8);
+ }
+ return strMessage;
+ }
+
+ int getEditTextHexValue(EditText editText, int iStrLen) {
+ String strValue = editText.getText().toString().trim();
+ MainActivity.csLibrary4A.appendToLog("getEditTextHexValue: editText.string=" + strValue + ", iStrLen=" + iStrLen);
+ if (strValue.length() > iStrLen) strValue = strValue.substring(strValue.length() - iStrLen);
+ int iValue = 0;
+ try {
+ iValue = Integer.parseInt(strValue, 16);
+ } catch (Exception ex) { }
+ int iValue2 = 0;
+ for (int i = 0; i < iStrLen; i++) { iValue2 <<= 4; iValue2 |= 0xFF; }
+ strValue = String.format("%0" + String.valueOf(iStrLen) + "X", iValue & iValue2);
+ MainActivity.csLibrary4A.appendToLog("getEditTextHexValue: exit string = " + strValue);
+ editText.setText(strValue);
+ return iValue;
+ }
+}
+
+
+
+package com.csl.cs710ademoapp.fragments;
+
+import static com.csl.cslibrary4a.RfidReader.TagType.TAG_IMPINJ;
+
+import android.app.Activity;
+import android.os.AsyncTask;
+import android.os.Bundle;
+import android.os.SystemClock;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.AdapterView;
+import android.widget.ArrayAdapter;
+import android.widget.Button;
+import android.widget.CheckBox;
+import android.widget.EditText;
+import android.widget.LinearLayout;
+import android.widget.Spinner;
+import android.widget.TextView;
+import android.widget.Toast;
+
+import com.csl.cs710ademoapp.AccessTask;
+import com.csl.cs710ademoapp.AccessTask1;
+import com.csl.cs710ademoapp.CustomPopupWindow;
+import com.csl.cs710ademoapp.MainActivity;
+import com.csl.cs710ademoapp.R;
+import com.csl.cs710ademoapp.SelectTag;
+import com.csl.cslibrary4a.ReaderDevice;
+import com.csl.cslibrary4a.RfidReaderChipData;
+import com.google.android.material.tabs.TabLayout;
+
+public class AccessImpinjFragment extends CommonFragment {
+ CheckBox checkBoxTagFocus, checkBoxFastId, checkBoxProtectSelect, checkBoxAutoTuneDisable, checkBoxProtect, checkBoxShortRange, checkBoxMemorySelect, checkBoxUnkillable;
+ Spinner spinnerTagSelect;
+
+ TextView textViewUserValue;
+ Button buttonReadUserBank, buttonWriteUserBank;
+ TextView textViewRunTime;
+ enum impinjTag {
+ m775, m780, m830, m770, m730, monza_R6A, monza_R6P, monza_x8k, others
+ }
+
+ SelectTag selectTag;
+ TextView textViewAuthenticatedResult, textViewAutotuneValue, textViewProtectValue, textViewProtectNormalValue, textViewEpc128Value, textViewConfiguration;
+ Button button, buttonAutoTuneValueRead, buttonProtectValueRead, buttonProtectResumeRead, buttonEpc128ValueRead, buttonRead, buttonWrite;
+ boolean operationRead = false;
+ AccessTask accessTask;
+ AccessTask1 accessTask1;
+ int iRunType = -1; String stringNewAutoTuneConfig = null;
+ int unprotecting = 0;
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ super.onCreateView(inflater, container, savedInstanceState, false);
+ return inflater.inflate(R.layout.fragment_access_impinj, container, false);
+ }
+
+ @Override
+ public void onActivityCreated(Bundle savedInstanceState) {
+ super.onActivityCreated(savedInstanceState);
+
+ checkBoxTagFocus = (CheckBox) getActivity().findViewById(R.id.accessImpinjTagFocus);
+ if (MainActivity.csLibrary4A.get98XX() == 2) checkBoxTagFocus.setText(checkBoxTagFocus.getText().toString() + " (When enabled, tag select is disabled.)");
+ MainActivity.csLibrary4A.appendToLog("CheckBoxTagFocus is set");
+ checkBoxFastId = (CheckBox) getActivity().findViewById(R.id.accessImpinjFastId);
+
+ checkBoxAutoTuneDisable = (CheckBox) getActivity().findViewById(R.id.accessImpinjAutoTune);
+ checkBoxProtect = (CheckBox) getActivity().findViewById(R.id.accessImpinjProtect);
+ checkBoxShortRange = (CheckBox) getActivity().findViewById(R.id.accessImpinjShortRange);
+ checkBoxMemorySelect = (CheckBox) getActivity().findViewById(R.id.accessImpinjMemorySelect);
+ checkBoxUnkillable = (CheckBox) getActivity().findViewById(R.id.accessImpinjUnkillable);
+
+ spinnerTagSelect = (Spinner) getActivity().findViewById(R.id.accessImpinjTagSelect);
+ ArrayAdapter targetAdapter1 = ArrayAdapter.createFromResource(getActivity(), R.array.impinj_options, R.layout.custom_spinner_layout);
+ targetAdapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+ spinnerTagSelect.setAdapter(targetAdapter1); spinnerTagSelect.setSelection(0);
+ spinnerTagSelect.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
+ @Override
+ public void onItemSelected(AdapterView> parentView, View selectedItemView, int position, long id) {
+ TabLayout tabLayout = (TabLayout) getActivity().findViewById(R.id.OperationsTabLayout);
+ TabLayout.TabView tabView = tabLayout.getTabAt(2).view;
+ //LinearLayout layout = (LinearLayout) getActivity().findViewById(R.id.accessImpinjAuthenticateLayout);
+ if (position == impinjTag.m775.ordinal()) {
+ //layout.setVisibility(View.VISIBLE);
+ textViewAuthenticatedResult.setText("");
+ tabView.setVisibility(View.VISIBLE);
+ } else {
+ //layout.setVisibility(View.GONE);
+ tabView.setVisibility(View.GONE);
+ }
+
+ LinearLayout layoutA = (LinearLayout) getActivity().findViewById(R.id.accessImpinjProtectLayout);
+ LinearLayout layoutA1 = (LinearLayout) getActivity().findViewById(R.id.accessImpinjProtectLayout1);
+ if (position == impinjTag.m775.ordinal() ||
+ position == impinjTag.m780.ordinal() ||
+ position == impinjTag.m830.ordinal() ||
+ position == impinjTag.m770.ordinal() ||
+ position == impinjTag.m730.ordinal()) {
+ layoutA.setVisibility(View.VISIBLE);
+ layoutA1.setVisibility(View.VISIBLE);
+ textViewProtectValue.setText("");
+ } else {
+ layoutA.setVisibility(View.GONE);
+ layoutA1.setVisibility(View.GONE);
+ }
+
+ LinearLayout layout0 = (LinearLayout) getActivity().findViewById(R.id.accessImpinjMemorySelectLayout);
+ if (position == impinjTag.m830.ordinal() || position == impinjTag.monza_R6P.ordinal()) {
+ layout0.setVisibility(View.VISIBLE);
+ textViewEpc128Value.setText("");
+ } else layout0.setVisibility(View.GONE);
+
+ LinearLayout layout1 = (LinearLayout) getActivity().findViewById(R.id.accessImpinjSelectLayout);
+ if (position == impinjTag.others.ordinal()) layout1.setVisibility(View.GONE);
+ else layout1.setVisibility(View.VISIBLE);
+
+ LinearLayout layout2 = (LinearLayout) getActivity().findViewById(R.id.accessImpinjAutotuneLayout);
+ LinearLayout layout3 = (LinearLayout) getActivity().findViewById(R.id.accessImpinjConfigLayout);
+ if (position == impinjTag.monza_x8k.ordinal() || position == impinjTag.others.ordinal()) {
+ layout2.setVisibility(View.GONE);
+ layout3.setVisibility(View.GONE);
+ } else {
+ layout2.setVisibility(View.VISIBLE);
+ layout3.setVisibility(View.VISIBLE);
+
+ textViewAutotuneValue.setText("");
+
+ if (position == impinjTag.monza_R6A.ordinal() || position == impinjTag.monza_R6P.ordinal() || position == impinjTag.others.ordinal()) checkBoxProtect.setVisibility(View.GONE);
+ else checkBoxProtect.setVisibility(View.VISIBLE);
+ if (position == impinjTag.m830.ordinal() || position == impinjTag.monza_R6P.ordinal()) checkBoxMemorySelect.setVisibility(View.VISIBLE);
+ else checkBoxMemorySelect.setVisibility(View.GONE);
+ if (position == impinjTag.m775.ordinal() || position == impinjTag.m780.ordinal() || position == impinjTag.m770.ordinal()) checkBoxUnkillable.setVisibility(View.VISIBLE);
+ else checkBoxUnkillable.setVisibility(View.GONE);
+
+ checkBoxAutoTuneDisable.setChecked(false); checkBoxAutoTuneDisable.setEnabled(false);
+ checkBoxProtect.setChecked(false); checkBoxProtect.setEnabled(false);
+ checkBoxShortRange.setChecked(false); checkBoxShortRange.setEnabled(false);
+ checkBoxMemorySelect.setChecked(false); checkBoxMemorySelect.setEnabled(false);
+ checkBoxUnkillable.setChecked(false); checkBoxUnkillable.setEnabled(false);
+ textViewConfiguration.setText("");
+ }
+
+ LinearLayout layout4 = (LinearLayout) getActivity().findViewById(R.id.accessImpinjReadUserLayout);
+ if (position == impinjTag.monza_x8k.ordinal()) layout4.setVisibility(View.VISIBLE);
+ else layout4.setVisibility(View.GONE);
+ }
+
+ @Override
+ public void onNothingSelected(AdapterView> parentView) {
+ // your code here
+ }
+
+ });
+
+ MainActivity.csLibrary4A.setSameCheck(false);
+ data2Restore.iQuerySession = MainActivity.csLibrary4A.getQuerySession();
+ data2Restore.iQueryTarget = MainActivity.csLibrary4A.getQueryTarget();
+ data2Restore.tagDelay = MainActivity.csLibrary4A.getTagDelay();
+ data2Restore.dwellTime = MainActivity.csLibrary4A.getAntennaDwell();
+ data2Restore.tagFocus = MainActivity.csLibrary4A.getTagFocus();
+
+ selectTag = new SelectTag((Activity)getActivity(), 0);
+
+ if (true) {
+ textViewAuthenticatedResult = (TextView) getActivity().findViewById(R.id.accessImpinjAuthenticatedResult);
+ button = (Button) getActivity().findViewById(R.id.accessImpinjAuthenticateButton);
+ button.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (isRfidConnectionValid() == false) return;
+ if (isRunningAccessTask()) return;
+
+ textViewAuthenticatedResult.setText("");
+ boolean invalidRequest = MainActivity.csLibrary4A.setAuthenticateConfiguration();
+ accessTask = new AccessTask(button, null, false, true,
+ selectTag.editTextTagID.getText().toString(), 1, 32,
+ selectTag.editTextAccessPassword.getText().toString(), Integer.valueOf(selectTag.editTextAccessAntennaPower.getText().toString()), RfidReaderChipData.HostCommands.CMD_18K6CAUTHENTICATE,
+ -1, -1, false, false,
+ null, null, null, null, null);
+ accessTask.execute();
+
+ mHandler.removeCallbacks(updateRunnable);
+ iRunType = 1; mHandler.post(updateRunnable);
+ }
+ });
+ }
+
+ if (true) {
+ textViewAutotuneValue = (TextView) getActivity().findViewById(R.id.accessImpinjAutoTuneValue);
+ buttonAutoTuneValueRead = (Button) getActivity().findViewById(R.id.accessImpinjAutotuneValueButton);
+ buttonAutoTuneValueRead.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (isRfidConnectionValid() == false) return;
+ if (isRunningAccessTask()) return;
+
+ textViewAutotuneValue.setText("");
+ boolean invalidRequest = false;
+ int iAccOffset = 0x1c; int itagSelect = spinnerTagSelect.getSelectedItemPosition();
+ if (itagSelect == impinjTag.m775.ordinal()) iAccOffset = 0x1c;
+ else if (itagSelect == impinjTag.m780.ordinal()) iAccOffset = 0x34;
+ else if (itagSelect == impinjTag.m830.ordinal()) iAccOffset = 0x14;
+ else if (itagSelect == impinjTag.m770.ordinal()) iAccOffset = 0x1c;
+ else if (itagSelect == impinjTag.m730.ordinal()) iAccOffset = 0x14;
+ else if (itagSelect == impinjTag.monza_R6A.ordinal()) iAccOffset = 0x14;
+ else if (itagSelect == impinjTag.monza_R6P.ordinal()) iAccOffset = 0x14;
+ MainActivity.csLibrary4A.appendToLog(String.format("AutoTune offset is 0x%X", iAccOffset));
+ if (set_before_access(0, itagSelect, 1) == false) invalidRequest = true;
+ accessTask = new AccessTask(buttonAutoTuneValueRead, null, invalidRequest, true,
+ selectTag.editTextTagID.getText().toString(), 1, 32,
+ selectTag.editTextAccessPassword.getText().toString(), Integer.valueOf(selectTag.editTextAccessAntennaPower.getText().toString()), RfidReaderChipData.HostCommands.CMD_18K6CREAD,
+ -1, -1, false, checkProtectedBoxBeforeAccess(),
+ null, null, null, null, null);
+ accessTask.execute();
+ mHandler.removeCallbacks(updateRunnable);
+ iRunType = 2; mHandler.post(updateRunnable);
+ }
+ });
+
+ textViewProtectValue = (TextView) getActivity().findViewById(R.id.accessImpinjProtectValue);
+ checkBoxProtectSelect = (CheckBox) getActivity().findViewById(R.id.accessImpinjProtectSelect);
+ textViewProtectNormalValue = (TextView) getActivity().findViewById(R.id.accessImpinjProtectNormalValue);
+ buttonProtectValueRead = (Button) getActivity().findViewById(R.id.accessImpinjProtectValueButton);
+ buttonProtectValueRead.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (isRfidConnectionValid() == false) return;
+ if (isRunningAccessTask()) return;
+
+ textViewProtectValue.setText("");
+ boolean invalidRequest = false;
+ if (set_before_access(1, 2, 6) == false) invalidRequest = true;
+ accessTask = new AccessTask(buttonProtectValueRead, null, invalidRequest, true,
+ selectTag.editTextTagID.getText().toString(), 1, 32,
+ selectTag.editTextAccessPassword.getText().toString(), Integer.valueOf(selectTag.editTextAccessAntennaPower.getText().toString()), RfidReaderChipData.HostCommands.CMD_18K6CREAD,
+ -1, -1, false, checkProtectedBoxBeforeAccess(),
+ null, null, null, null, null);
+ MainActivity.csLibrary4A.appendToLog("setSelectCriteria: before execute");
+ accessTask.execute();
+ MainActivity.csLibrary4A.appendToLog("setSelectCriteria: after execute");
+ mHandler.removeCallbacks(updateRunnable);
+ iRunType = 3; mHandler.post(updateRunnable);
+ }
+ });
+
+ buttonProtectResumeRead = (Button) getActivity().findViewById(R.id.accessImpinjProtectResumeButton);
+ buttonProtectResumeRead.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (isZeroPassword()) return;
+ if (isRfidConnectionValid() == false) return;
+ if (isRunningAccessTask()) {
+ if (accessTask != null) accessTask.taskCancelReason = AccessTask.TaskCancelRReason.DESTORY;
+ }
+
+ if (unprotecting > 0) stopProtectResuming();
+ else {
+ unprotecting = 1;
+ if (spinnerTagSelect.getSelectedItemPosition() == impinjTag.m775.ordinal()) selectTag.editTextTagID.setText("E2C011A2");
+ else if (spinnerTagSelect.getSelectedItemPosition() == impinjTag.m780.ordinal()) selectTag.editTextTagID.setText("E28011C");
+ else if (spinnerTagSelect.getSelectedItemPosition() == impinjTag.m770.ordinal()) selectTag.editTextTagID.setText("E28011A0");
+ else if (spinnerTagSelect.getSelectedItemPosition() == impinjTag.m830.ordinal()) selectTag.editTextTagID.setText("E28011B0");
+ else if (spinnerTagSelect.getSelectedItemPosition() == impinjTag.m730.ordinal()) selectTag.editTextTagID.setText("E280119");
+ selectTag.spinnerSelectBank.setSelection(1);
+ checkBoxProtectSelect.setChecked(true);
+ buttonProtectResumeRead.setText("Stop resuming to normal");
+
+ startConfigRead();
+ }
+ }
+ });
+
+ textViewEpc128Value = (TextView) getActivity().findViewById(R.id.accessImpinjEpc128Value);
+ buttonEpc128ValueRead = (Button) getActivity().findViewById(R.id.accessImpinjEpc128ValueButton);
+ buttonEpc128ValueRead.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (isRfidConnectionValid() == false) return;
+ if (isRunningAccessTask()) return;
+
+ textViewEpc128Value.setText("");
+ boolean invalidRequest = false;
+ if (set_before_access(1, 2, 8) == false) invalidRequest = true;
+ accessTask = new AccessTask(buttonEpc128ValueRead, null, invalidRequest, true,
+ selectTag.editTextTagID.getText().toString(), 1, 32,
+ selectTag.editTextAccessPassword.getText().toString(), Integer.valueOf(selectTag.editTextAccessAntennaPower.getText().toString()), RfidReaderChipData.HostCommands.CMD_18K6CREAD,
+ -1, -1, false, checkProtectedBoxBeforeAccess(),
+ null, null, null, null, null);
+ accessTask.execute();
+ mHandler.removeCallbacks(updateRunnable);
+ iRunType = 4; mHandler.post(updateRunnable);
+ }
+ });
+
+ textViewRunTime = (TextView) getActivity().findViewById(R.id.accessImpinjRunTime);
+ buttonReadUserBank = (Button) getActivity().findViewById(R.id.accessRWReadButton);
+ buttonReadUserBank.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (MainActivity.csLibrary4A.isBleConnected() == false) {
+ Toast.makeText(MainActivity.mContext, R.string.toast_ble_not_connected, Toast.LENGTH_SHORT).show();
+ return;
+ } else if (MainActivity.csLibrary4A.isRfidFailure()) {
+ Toast.makeText(MainActivity.mContext, "Rfid is disabled", Toast.LENGTH_SHORT).show();
+ return;
+ }
+ operationRead = true; startAccessUserTask();
+ }
+ });
+
+ buttonWriteUserBank = (Button) getActivity().findViewById(R.id.accessRWWriteButton);
+ buttonWriteUserBank.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (MainActivity.csLibrary4A.isBleConnected() == false) {
+ Toast.makeText(MainActivity.mContext, R.string.toast_ble_not_connected, Toast.LENGTH_SHORT).show();
+ return;
+ } else if (MainActivity.csLibrary4A.isRfidFailure()) {
+ Toast.makeText(MainActivity.mContext, "Rfid is disabled", Toast.LENGTH_SHORT).show();
+ return;
+ }
+ operationRead = false; startAccessUserTask();
+ }
+ });
+
+ textViewConfiguration = (TextView) getActivity().findViewById(R.id.accessImpinjConfiguration);
+ buttonRead = (Button) getActivity().findViewById(R.id.accessImpinjReadButton);
+ buttonRead.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (isRfidConnectionValid() == false) return;
+ if (isRunningAccessTask()) return;
+
+ startConfigRead();
+ }
+ });
+
+ buttonWrite = (Button) getActivity().findViewById(R.id.accessImpinjWriteButton);
+ buttonWrite.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (isZeroPassword()) return;
+ if (isRfidConnectionValid() == false) return;
+ if (isRunningAccessTask()) return;
+
+ if (textViewConfiguration.getText().toString().length() < 4) {
+ Toast.makeText(MainActivity.mContext, "Please read configuration first", Toast.LENGTH_SHORT).show();
+ return;
+ }
+ startConfigWrite();
+ }
+ });
+ }
+ }
+ boolean isZeroPassword() {
+ boolean bValue = false;
+ int iValue = 0;
+ try {
+ iValue = Integer.parseInt(selectTag.editTextAccessPassword.getText().toString(), 16);
+ } catch (Exception ex) {
+ iValue = -1;
+ }
+ MainActivity.csLibrary4A.appendToLog("Password = " + iValue);
+ if (iValue == 0) {
+ CustomPopupWindow customPopupWindow = new CustomPopupWindow(MainActivity.mContext);
+ customPopupWindow.popupStart("Before operation, please enter non-zero access password !!!", false);
+ bValue = true;
+ }
+ return bValue;
+ }
+ void stopProtectResuming() {
+ unprotecting = 0;
+ checkBoxProtectSelect.setChecked(false);
+ buttonProtectResumeRead.setText("Resume invisible tag to normal");
+ }
+
+ boolean updating = false; long msStartTime; int bankProcessing = 0; int restartAccessBank = -1;
+ void startAccessUserTask() {
+ msStartTime = SystemClock.elapsedRealtime();
+ textViewRunTime.setText("");
+
+ int iSelectBank = selectTag.spinnerSelectBank.getSelectedItemPosition() + 1;
+ int iSelectOffset = 32;
+ if (iSelectBank != 1) iSelectOffset = 0;
+
+ EditText editTextBlockCount = (EditText) getActivity().findViewById(R.id.accessImpinjBlockCount);
+ EditText editTextUserOffset = (EditText) getActivity().findViewById(R.id.accessImpinjUserOffset);
+ EditText editTextUserLength = (EditText) getActivity().findViewById(R.id.accessImpinjUserLength);
+ int accBlockCount = 32, accOffset = 1, accSize = 1;
+ try {
+ accBlockCount = Integer.parseInt(editTextBlockCount.getText().toString());
+ } catch (Exception ex) { }
+ try {
+ accOffset = Integer.valueOf(editTextUserOffset.getText().toString(), 10);
+ } catch (Exception ex) { }
+ try {
+ accSize = Integer.valueOf(editTextUserLength.getText().toString(), 10);
+ } catch (Exception ex) { }
+
+ textViewUserValue = (TextView) getActivity().findViewById(R.id.accessImpinjUserValue);
+ if (operationRead) textViewUserValue.setText("");
+ boolean invalidRequest = false;
+
+ MainActivity.csLibrary4A.appendToLog("Start accessTask1 with accBlockCount + " + accBlockCount + "F" + editTextBlockCount.getText().toString() + ", accOffset = " + accOffset + "F" + editTextUserOffset.getText().toString() + ", accSize = " + accSize + "F" + editTextUserLength.getText().toString());
+ accessTask1 = new AccessTask1(
+ (operationRead ? buttonReadUserBank : buttonWriteUserBank), invalidRequest,
+ 3, accOffset, accSize, accBlockCount, null,
+ selectTag.editTextTagID.getText().toString(), iSelectBank, iSelectOffset,
+ selectTag.editTextAccessPassword.getText().toString(),
+ Integer.valueOf(selectTag.editTextAccessAntennaPower.getText().toString()),
+ (operationRead ? RfidReaderChipData.HostCommands.CMD_18K6CREAD: RfidReaderChipData.HostCommands.CMD_18K6CWRITE), updateRunnable);
+ accessTask1.execute();
+ iRunType = 7;
+ }
+ void startConfigRead() {
+ textViewConfiguration.setText("");
+ boolean invalidRequest = false;
+ if (set_before_access(0, 4, 1) == false) invalidRequest = true;
+ int iSelectBank = selectTag.spinnerSelectBank.getSelectedItemPosition() + 1;
+ int iSelectOffset = 32;
+ if (iSelectBank != 1) iSelectOffset = 0;
+ accessTask = new AccessTask(buttonRead, null, invalidRequest, true,
+ selectTag.editTextTagID.getText().toString(), iSelectBank, iSelectOffset,
+ selectTag.editTextAccessPassword.getText().toString(), Integer.valueOf(selectTag.editTextAccessAntennaPower.getText().toString()), RfidReaderChipData.HostCommands.CMD_18K6CREAD,
+ -1, -1, false, checkProtectedBoxBeforeAccess(),
+ null, null, null, null, null);
+ accessTask.execute();
+ mHandler.removeCallbacks(updateRunnable);
+ iRunType = 5; mHandler.post(updateRunnable);
+ }
+ void startConfigWrite() {
+ boolean invalidRequest = false;
+ if (set_before_access(0, 4, 1) == false) invalidRequest = true;
+ int iSelectBank = selectTag.spinnerSelectBank.getSelectedItemPosition() + 1;
+ int iSelectOffset = 32;
+ if (iSelectBank != 1) iSelectOffset = 0;
+ if (invalidRequest == false) {
+ String string = textViewConfiguration.getText().toString();
+ int iValue = Integer.valueOf(string, 16);
+ MainActivity.csLibrary4A.appendToLog(String.format("iValue = 0x%02X", iValue));
+
+ if (checkBoxAutoTuneDisable.isChecked()) iValue |= 0x01;
+ else iValue &= ~0x01;
+
+ if (spinnerTagSelect.getSelectedItemPosition() == impinjTag.m775.ordinal() ||
+ spinnerTagSelect.getSelectedItemPosition() == impinjTag.m780.ordinal() ||
+ spinnerTagSelect.getSelectedItemPosition() == impinjTag.m830.ordinal() ||
+ spinnerTagSelect.getSelectedItemPosition() == impinjTag.m770.ordinal() ||
+ spinnerTagSelect.getSelectedItemPosition() == impinjTag.m730.ordinal()) {
+ if (checkBoxProtect.isChecked()) iValue |= 0x02;
+ else iValue &= ~0x02;
+ }
+
+ int iValueModified = 0x02;
+ if (spinnerTagSelect.getSelectedItemPosition() == impinjTag.m775.ordinal()) iValueModified = 0x04;
+ else if (spinnerTagSelect.getSelectedItemPosition() == impinjTag.m780.ordinal()) iValueModified = 0x04;
+ else if (spinnerTagSelect.getSelectedItemPosition() == impinjTag.m770.ordinal()) iValueModified = 0x04;
+ else if (spinnerTagSelect.getSelectedItemPosition() == impinjTag.m830.ordinal()) iValueModified = 0x10;
+ else if (spinnerTagSelect.getSelectedItemPosition() == impinjTag.m730.ordinal()) iValueModified = 0x10;
+ if (checkBoxShortRange.isChecked()) iValue |= iValueModified;
+ else iValue &= ~iValueModified;
+
+ iValueModified = 0;
+ if (spinnerTagSelect.getSelectedItemPosition() == impinjTag.m830.ordinal()) iValueModified = 0x08;
+ else if (spinnerTagSelect.getSelectedItemPosition() == impinjTag.monza_R6P.ordinal()) iValueModified = 0x04;
+ if (iValueModified != 0) {
+ if (checkBoxMemorySelect.isChecked()) iValue |= iValueModified;
+ else iValue &= ~iValueModified;
+ }
+
+ if (spinnerTagSelect.getSelectedItemPosition() == impinjTag.m775.ordinal() ||
+ spinnerTagSelect.getSelectedItemPosition() == impinjTag.m780.ordinal() ||
+ spinnerTagSelect.getSelectedItemPosition() == impinjTag.m770.ordinal()) {
+ if (checkBoxUnkillable.isChecked()) iValue |= 0x08;
+ else iValue &= ~0x08;
+ }
+
+ MainActivity.csLibrary4A.appendToLog(String.format("revised iValue = 0x%02X", iValue));
+ string = String.format("%04X", iValue);
+ MainActivity.csLibrary4A.appendToLog("string = " + string);
+ MainActivity.csLibrary4A.appendToLog("new AutotuneConfiguration = " + string);
+ stringNewAutoTuneConfig = string;
+ if (MainActivity.csLibrary4A.setAccessWriteData(string) == false) {
+ invalidRequest = true;
+ }
+ }
+
+ accessTask = new AccessTask(buttonWrite, null, invalidRequest, true,
+ selectTag.editTextTagID.getText().toString(), 1, 32,
+ selectTag.editTextAccessPassword.getText().toString(), Integer.valueOf(selectTag.editTextAccessAntennaPower.getText().toString()), RfidReaderChipData.HostCommands.CMD_18K6CWRITE,
+ -1, -1, false, checkProtectedBoxBeforeAccess(),
+ null, null, null, null, null);
+ accessTask.execute();
+ mHandler.removeCallbacks(updateRunnable);
+ iRunType = 6; mHandler.post(updateRunnable);
+ }
+ boolean bReadySelected = false;
+ boolean checkProtectedBoxBeforeAccess() {
+ bReadySelected = false;
+ if (checkBoxProtectSelect.isChecked()) {
+ MainActivity.csLibrary4A.appendToLog("Going to setSelectCriteria disable");
+ MainActivity.csLibrary4A.setSelectCriteriaDisable(-1);
+ MainActivity.csLibrary4A.appendToLog("Going to setSelectCriteria");
+ MainActivity.csLibrary4A.setSelectCriteria(-1, true, 4, 0, 3, 0, selectTag.editTextAccessPassword.getText().toString(), false);
+ bReadySelected = true;
+ }
+ return checkBoxProtectSelect.isChecked();
+ }
+ boolean isRfidConnectionValid() {
+ boolean bValue = false;
+ if (MainActivity.csLibrary4A.isBleConnected() == false) {
+ Toast.makeText(MainActivity.mContext, R.string.toast_ble_not_connected, Toast.LENGTH_SHORT).show();
+ } else if (MainActivity.csLibrary4A.isRfidFailure()) {
+ Toast.makeText(MainActivity.mContext, "Rfid is disabled", Toast.LENGTH_SHORT).show();
+ } else bValue = true;
+ return bValue;
+ }
+ boolean set_before_access(int accBank, int accOffset, int accSize) {
+ boolean invalidRequest = false;
+ if (invalidRequest == false) {
+ if (MainActivity.csLibrary4A.setAccessBank(accBank) == false) {
+ MainActivity.csLibrary4A.appendToLog("HelloK: accBank, invalidRequest=" + invalidRequest);
+ invalidRequest = true;
+ }
+ }
+ if (invalidRequest == false) {
+ if (MainActivity.csLibrary4A.setAccessOffset(accOffset) == false) {
+ MainActivity.csLibrary4A.appendToLog("HelloK: accOffset, invalidRequest=" + invalidRequest);
+ invalidRequest = true;
+ }
+ }
+ if (invalidRequest == false) {
+ if (MainActivity.csLibrary4A.setAccessCount(accSize) == false) {
+ invalidRequest = true;
+ }
+ }
+ if (invalidRequest) return false;
+ return true;
+ }
+
+ boolean isRunningAccessTask() {
+ boolean retValue = false;
+ if (accessTask != null) {
+ if (accessTask.getStatus() != AsyncTask.Status.FINISHED) retValue = true;
+ }
+ return retValue;
+ }
+ private final Runnable updateRunnable = new Runnable() {
+ @Override
+ public void run() {
+ if (accessTask == null && accessTask1 == null) {
+ MainActivity.csLibrary4A.appendToLog("updateRunnable(): null AccessTask");
+ } else if (accessTask != null && accessTask.getStatus() == AsyncTask.Status.FINISHED) {
+ MainActivity.csLibrary4A.appendToLog("accessResult = " + accessTask.accessResult + " with iRunType = " + iRunType);
+ if (accessTask.accessResult == null) {
+ MainActivity.csLibrary4A.appendToLog("updateRunnable(): accessTask is finished without result but with error = " + accessTask.resultError);
+ if (unprotecting > 0) stopProtectResuming();
+ } else if (iRunType == 1) textViewAuthenticatedResult.setText(accessTask.accessResult);
+ else if (iRunType == 2) textViewAutotuneValue.setText(accessTask.accessResult);
+ else if (iRunType == 3) textViewProtectValue.setText(accessTask.accessResult);
+ else if (iRunType == 4) textViewEpc128Value.setText(accessTask.accessResult);
+ else if (iRunType == 5) {
+ textViewConfiguration.setText(accessTask.accessResult);
+ int iValue = Integer.valueOf(accessTask.accessResult.substring(accessTask.accessResult.length()-2, accessTask.accessResult.length()), 16);
+ MainActivity.csLibrary4A.appendToLog("updateRunnable(): " + String.format("accessResult = %s, iValue = 0x%02X", accessTask.accessResult, iValue));
+
+ if ((iValue & 0x01) != 0) checkBoxAutoTuneDisable.setChecked(true); else checkBoxAutoTuneDisable.setChecked(false);
+ checkBoxAutoTuneDisable.setEnabled(true);
+
+ if (spinnerTagSelect.getSelectedItemPosition() == impinjTag.m775.ordinal() ||
+ spinnerTagSelect.getSelectedItemPosition() == impinjTag.m780.ordinal() ||
+ spinnerTagSelect.getSelectedItemPosition() == impinjTag.m830.ordinal() ||
+ spinnerTagSelect.getSelectedItemPosition() == impinjTag.m770.ordinal() ||
+ spinnerTagSelect.getSelectedItemPosition() == impinjTag.m730.ordinal()) {
+ if ((iValue & 0x02) != 0) checkBoxProtect.setChecked(true); else checkBoxProtect.setChecked(false);
+ checkBoxProtect.setEnabled(true);
+ }
+
+ int iBitCompared = 0x02;
+ if (spinnerTagSelect.getSelectedItemPosition() == impinjTag.m775.ordinal()) iBitCompared = 0x04;
+ else if (spinnerTagSelect.getSelectedItemPosition() == impinjTag.m780.ordinal()) iBitCompared = 0x04;
+ else if (spinnerTagSelect.getSelectedItemPosition() == impinjTag.m770.ordinal()) iBitCompared = 0x04;
+ else if (spinnerTagSelect.getSelectedItemPosition() == impinjTag.m830.ordinal()) iBitCompared = 0x10;
+ else if (spinnerTagSelect.getSelectedItemPosition() == impinjTag.m730.ordinal()) iBitCompared = 0x10;
+ if ((iValue & iBitCompared) != 0) checkBoxShortRange.setChecked(true); else checkBoxShortRange.setChecked(false);
+ checkBoxShortRange.setEnabled(true);
+
+ iBitCompared = 0;
+ if (spinnerTagSelect.getSelectedItemPosition() == impinjTag.m830.ordinal()) iBitCompared = 0x08;
+ else if (spinnerTagSelect.getSelectedItemPosition() == impinjTag.monza_R6P.ordinal()) iBitCompared = 0x04;
+ if (iBitCompared != 0) {
+ if ((iValue & iBitCompared) != 0) checkBoxMemorySelect.setChecked(true); else checkBoxMemorySelect.setChecked(false);
+ checkBoxMemorySelect.setEnabled(true);
+ }
+
+ if (spinnerTagSelect.getSelectedItemPosition() == impinjTag.m775.ordinal() ||
+ spinnerTagSelect.getSelectedItemPosition() == impinjTag.m780.ordinal() ||
+ spinnerTagSelect.getSelectedItemPosition() == impinjTag.m770.ordinal()) {
+ if ((iValue & 0x08) != 0) checkBoxUnkillable.setChecked(true);
+ else checkBoxUnkillable.setChecked(false);
+ checkBoxUnkillable.setEnabled(true);
+ }
+
+ if (unprotecting > 0) {
+ textViewProtectValue.setText(accessTask.accessTagEpc);
+ textViewProtectNormalValue.setText("" + unprotecting);
+ unprotecting++;
+ if (checkBoxProtect.isChecked()) {
+ selectTag.editTextTagID.setText(accessTask.accessTagEpc);
+ selectTag.spinnerSelectBank.setSelection(0);
+ checkBoxProtect.setChecked(false);
+ MainActivity.csLibrary4A.appendToLog("updateRunnable(): startConfigWrite");
+ startConfigWrite();
+ } else {
+ MainActivity.csLibrary4A.appendToLog("updateRunnable(): startConfigRead");
+ startConfigRead();
+ }
+ }
+ }
+ else if (iRunType == 6) {
+ MainActivity.csLibrary4A.appendToLog("updateRunnable(): accessResult = " + accessTask.accessResult + ", accessError = " + accessTask.resultError);
+ if (accessTask.resultError.trim().length() != 0) Toast.makeText(MainActivity.mContext, accessTask.resultError, Toast.LENGTH_SHORT).show();
+ else if (accessTask.accessResult.length() == 0) textViewConfiguration.setText(stringNewAutoTuneConfig);
+
+ if (unprotecting > 0) stopProtectResuming();
+ }
+ else if (iRunType == 7) textViewUserValue.setText(accessTask.accessResult);
+ else MainActivity.csLibrary4A.appendToLog("updateRunnable(): No procedure for iRunType == " + iRunType);
+ } else if (accessTask1 != null && accessTask1.isResultReady()) {
+ long duration = SystemClock.elapsedRealtime() - msStartTime;
+ textViewRunTime.setText(String.format("Run time: %.2f sec", ((float) duration / 1000))); MainActivity.csLibrary4A.appendToLog("StreamOut: End of running time");
+ MainActivity.csLibrary4A.appendToLog("access1Result = " + accessTask1.getResult() + " with iRunType = " + iRunType);
+ if (iRunType == 7) textViewUserValue.setText(accessTask1.getResult());
+ else MainActivity.csLibrary4A.appendToLog("updateRunnable(): No procedure for iRunType == " + iRunType);
+ }else {
+// MainActivity.csLibrary4A.appendToLog("updateRunnable(): rerun after 100ms with accessTask.getStatus() = " + accessTask.getStatus().toString());
+ mHandler.postDelayed(updateRunnable, 100);
+ }
+ }
+ };
+ class Data2Restore {
+ int iQuerySession;
+ int iQueryTarget;
+ byte tagDelay;
+ long dwellTime;
+ int tagFocus;
+ }
+ Data2Restore data2Restore = new Data2Restore();
+
+ @Override
+ public void onDestroy() {
+ MainActivity.csLibrary4A.abortOperation();
+ MainActivity.csLibrary4A.setSameCheck(true);
+ MainActivity.csLibrary4A.setTagGroup(MainActivity.csLibrary4A.getQuerySelect(), data2Restore.iQuerySession, data2Restore.iQueryTarget);
+ MainActivity.csLibrary4A.setTagDelay((byte)data2Restore.tagDelay);
+ MainActivity.csLibrary4A.setAntennaDwell(data2Restore.dwellTime);
+ MainActivity.csLibrary4A.setTagFocus(data2Restore.tagFocus > 0 ? true : false);
+ MainActivity.csLibrary4A.restoreAfterTagSelect();
+ super.onDestroy();
+ }
+
+ boolean userVisibleHint = false;
+ @Override
+ public void setUserVisibleHint(boolean isVisibleToUser) {
+ super.setUserVisibleHint(isVisibleToUser);
+ if(getUserVisibleHint()) {
+ userVisibleHint = true;
+ MainActivity.csLibrary4A.appendToLog("AccessImpinjFragment is now VISIBLE");
+ setupTagID();
+ } else {
+ int iValue = 0;
+ if (checkBoxTagFocus != null && checkBoxFastId != null) {
+ if (checkBoxTagFocus.isChecked()) {
+ MainActivity.csLibrary4A.setTagGroup(MainActivity.csLibrary4A.getQuerySelect(), 1, 0);
+ MainActivity.csLibrary4A.setTagDelay((byte)0);
+ MainActivity.csLibrary4A.setAntennaDwell(2000);
+ iValue |= 0x10;
+ } else MainActivity.csLibrary4A.setTagGroup(MainActivity.csLibrary4A.getQuerySelect(), 0, 2);
+ if (checkBoxFastId.isChecked()) iValue |= 0x20;
+ if (spinnerTagSelect.getSelectedItemPosition() != impinjTag.others.ordinal()) iValue |= (spinnerTagSelect.getSelectedItemPosition() + 1);
+ MainActivity.tagType = TAG_IMPINJ; /* need more tagType */ MainActivity.mDid = "E28011" + String.format("%02X", iValue);
+ MainActivity.csLibrary4A.appendToLog(String.format("HelloK: iValue = 0x%02X, mDid = %s", iValue, MainActivity.mDid));
+ MainActivity.csLibrary4A.setImpinJExtension(checkBoxTagFocus.isChecked(), checkBoxFastId.isChecked());
+ }
+ userVisibleHint = false;
+ MainActivity.csLibrary4A.appendToLog("AccessImpinjFragment is now INVISIBLE" + (checkBoxFastId != null ? (" with Value = " + iValue) : ""));
+ }
+ }
+
+ public AccessImpinjFragment(boolean b775) {
+ super("AccessImpinjFragment");
+ }
+
+ void setupTagID() {
+ ReaderDevice tagSelected = MainActivity.tagSelected;
+ boolean bSelected = false;
+ if (tagSelected != null) {
+ if (tagSelected.getSelected() == true) {
+ bSelected = true;
+ if (selectTag != null) {
+ selectTag.editTextTagID.setText(tagSelected.getAddress());
+ selectTag.spinnerSelectBank.setSelection(0);
+ }
+
+ String stringDetail = tagSelected.getDetails();
+ int indexUser = stringDetail.indexOf("USER=");
+ if (indexUser != -1) {
+ String stringUser = stringDetail.substring(indexUser + 5);
+ MainActivity.csLibrary4A.appendToLog("stringUser = " + stringUser);
+
+ boolean bEnableBAPMode = false;
+ int number = Integer.valueOf(stringUser.substring(3, 4), 16);
+ if ((number % 2) == 1) bEnableBAPMode = true;
+// CheckBox checkBoxBAP = (CheckBox) getActivity().findViewById(R.id.coldChainEnableBAP);
+// checkBoxBAP.setChecked(bEnableBAPMode);
+ }
+ }
+ }
+ }
+}
+
+
+
+package com.csl.cs710ademoapp.fragments;
+
+import androidx.lifecycle.Lifecycle;
+import android.os.AsyncTask;
+import android.os.Bundle;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.Button;
+import android.widget.CheckBox;
+import android.widget.EditText;
+import android.widget.TextView;
+import android.widget.Toast;
+
+import com.csl.cs710ademoapp.AccessTask;
+import com.csl.cs710ademoapp.MainActivity;
+import com.csl.cs710ademoapp.R;
+import com.csl.cslibrary4a.ReaderDevice;
+import com.csl.cslibrary4a.RfidReaderChipData;
+
+public class AccessKilowayFragment extends CommonFragment {
+ final boolean DEBUG = true;
+ EditText editTextRWTagID, editTextaccessRWAntennaPower;
+
+ TextView textViewOk;
+ CheckBox checkBoxRepeat, checkBox;
+ TextView textView;
+
+ private Button buttonRead;
+
+ enum ReadWriteTypes {
+ NULL, READVALUE
+ }
+ ReadWriteTypes readWriteTypes;
+
+ private AccessTask accessTask;
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ super.onCreateView(inflater, container, savedInstanceState, false);
+ return inflater.inflate(R.layout.fragment_access_kiloway, container, false);
+ }
+
+ @Override
+ public void onActivityCreated(Bundle savedInstanceState) {
+ super.onActivityCreated(savedInstanceState);
+
+ editTextRWTagID = (EditText) getActivity().findViewById(R.id.accessKilowayID);
+ editTextaccessRWAntennaPower = (EditText) getActivity().findViewById(R.id.accessLEDAntennaPower);
+
+ checkBoxRepeat = (CheckBox) getActivity().findViewById(R.id.accessKilowayRepeat);
+ textViewOk = (TextView) getActivity().findViewById(R.id.accessKilowayResultOK);
+ checkBox = (CheckBox) getActivity().findViewById(R.id.accessKilowayResultTitle);
+ textView = (TextView) getActivity().findViewById(R.id.accessKilowayResult);
+
+ buttonRead = (Button) getActivity().findViewById(R.id.accessKilowayStartButton);
+ buttonRead.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (MainActivity.csLibrary4A.isBleConnected() == false) {
+ Toast.makeText(MainActivity.mContext, R.string.toast_ble_not_connected, Toast.LENGTH_SHORT).show();
+ return;
+ } else if (MainActivity.csLibrary4A.isRfidFailure()) {
+ Toast.makeText(MainActivity.mContext, "Rfid is disabled", Toast.LENGTH_SHORT).show();
+ return;
+ }
+ startAccessTask();
+ }
+ });
+
+ MainActivity.csLibrary4A.setSameCheck(false);
+ }
+
+ @Override
+ public void onResume() {
+ super.onResume();
+ setupTagID();
+ }
+
+ @Override
+ public void onDestroy() {
+ if (accessTask != null) accessTask.cancel(true);
+ MainActivity.csLibrary4A.setSameCheck(true);
+ super.onDestroy();
+ }
+
+ @Override
+ public void setUserVisibleHint(boolean isVisibleToUser) {
+ super.setUserVisibleHint(isVisibleToUser);
+ if (getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.RESUMED) == false) return;
+ if(getUserVisibleHint()) {
+ setupTagID();
+ } else checkBoxRepeat.setChecked(false);
+ }
+
+ boolean isLongjing = false;
+ public AccessKilowayFragment(boolean isLongjing) {
+ super("AccessLedTagFragment");
+ this.isLongjing = isLongjing;
+ }
+
+ void setupTagID() {
+ ReaderDevice tagSelected = MainActivity.tagSelected;
+ if (tagSelected != null) {
+ if (tagSelected.getSelected() == true) {
+ if (editTextRWTagID != null) editTextRWTagID.setText(tagSelected.getAddress());
+ }
+ }
+ }
+
+ void startAccessTask() {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("startAccessTask()");
+ if (updating == false) {
+ updating = true; bankProcessing = 0; checkProcessing = 0;
+ mHandler.removeCallbacks(updateRunnable);
+ mHandler.post(updateRunnable);
+ }
+ }
+ boolean updating = false; int bankProcessing = 0; int checkProcessing = 0;
+ private final Runnable updateRunnable = new Runnable() {
+ @Override
+ public void run() {
+ MainActivity.csLibrary4A.appendToLog("AccessLedTagFragment(): Beginning"); ///
+ boolean rerunRequest = false; boolean taskRequest = false;
+ if (accessTask == null) {
+ taskRequest = true;
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("AccessLedTagFragment(): NULL accessReadWriteTask"); ///
+ } else if (accessTask.getStatus() != AsyncTask.Status.FINISHED) {
+ rerunRequest = true;
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("AccessLedTagFragment(): accessReadWriteTask.getStatus() = " + accessTask.getStatus().toString());
+ } else {
+ taskRequest = true;
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("AccessLedTagFragment(): FINISHED accessReadWriteTask"); ///
+ }
+ if (processResult()) {
+ rerunRequest = true; MainActivity.csLibrary4A.appendToLog("AccessLedTagFragment(): processResult is TRUE");
+ } else {
+ MainActivity.csLibrary4A.appendToLog("AccessLedTagFragment: processResult is false with taskRequest = " + taskRequest); ///
+ if (taskRequest) {
+ boolean invalid = processTickItems();
+ MainActivity.csLibrary4A.appendToLog("AccessLedTagFragment(): processTickItems with invalid = " + invalid + ", bankProcessing = " + bankProcessing + ", checkProcessing = " + checkProcessing); ///
+ if (bankProcessing++ != 0 && invalid == true) {
+ rerunRequest = true;
+ if (checkBoxRepeat != null && checkBoxRepeat.isChecked()) { bankProcessing = 0; checkProcessing = 0; }
+ else rerunRequest = false;
+ } else {
+ accessTask = new AccessTask(buttonRead, invalid, true,
+ editTextRWTagID.getText().toString(), 1, 32,
+ "00000000", Integer.valueOf(editTextaccessRWAntennaPower.getText().toString()), RfidReaderChipData.HostCommands.CMD_18K6CREAD,
+ false, null);
+ accessTask.execute();
+ rerunRequest = true;
+ MainActivity.csLibrary4A.appendToLog("AccessLedTagFragment(): accessTask is created"); ///
+ }
+ }
+ }
+ if (rerunRequest) {
+ mHandler.postDelayed(updateRunnable, 500);
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("AccessLedTagFragment(): Restart"); ///
+ }
+ else updating = false;
+ MainActivity.csLibrary4A.appendToLog("AccessLedTagFragment(): Ending with updating = " + updating); ///
+ }
+ };
+
+ boolean processResult() {
+ String accessResult = null;
+ if (accessTask == null) return false;
+ else if (accessTask.getStatus() != AsyncTask.Status.FINISHED) return false;
+ else {
+ accessResult = accessTask.accessResult;
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("AccessLedTagFragment(): accessResult = " + accessResult);
+ if (accessResult == null) {
+ if (readWriteTypes == ReadWriteTypes.READVALUE) {
+ textViewOk.setText("E");
+ }
+ } else {
+ if (readWriteTypes == ReadWriteTypes.READVALUE) {
+ textViewOk.setText("O");
+ textView.setText(accessResult);
+ readWriteTypes = ReadWriteTypes.NULL;
+ }
+ }
+ accessTask = null;
+ return true;
+ }
+ }
+
+ boolean processTickItems() {
+ boolean invalidRequest1 = false;
+ int accBank = 0, accSize = 0, accOffset = 0;
+
+ if (editTextRWTagID.getText().toString().length() == 0) invalidRequest1 = true;
+ MainActivity.csLibrary4A.appendToLog("1: invalidRequest1 = " + invalidRequest1);
+
+ if (checkBox.isChecked() == true && checkProcessing < 1) {
+ accBank = 0; accSize = 1; accOffset = 4;
+ if (isLongjing) {
+ accBank = 3; accOffset = 112;
+ }
+
+ readWriteTypes = ReadWriteTypes.READVALUE; checkProcessing = 1;
+ textViewOk.setText(""); textView.setText("");
+ } else {
+ invalidRequest1 = true;
+ }
+ MainActivity.csLibrary4A.appendToLog("2: invalidRequest1 = " + invalidRequest1);
+
+ if (invalidRequest1 == false) {
+ if (MainActivity.csLibrary4A.setAccessBank(accBank) == false) {
+ invalidRequest1 = true;
+ }
+ }
+ MainActivity.csLibrary4A.appendToLog("3: invalidRequest1 = " + invalidRequest1);
+
+ if (invalidRequest1 == false) {
+ if (MainActivity.csLibrary4A.setAccessOffset(accOffset) == false) {
+ invalidRequest1 = true;
+ }
+ }
+ MainActivity.csLibrary4A.appendToLog("4: invalidRequest1 = " + invalidRequest1);
+
+ if (invalidRequest1 == false) {
+ if (accSize == 0) {
+ invalidRequest1 = true;
+ } else if (MainActivity.csLibrary4A.setAccessCount(accSize) == false) {
+ invalidRequest1 = true;
+ }
+ }
+ MainActivity.csLibrary4A.appendToLog("5: invalidRequest1 = " + invalidRequest1);
+
+ return invalidRequest1;
+ }
+}
+
+
+
+package com.csl.cs710ademoapp.fragments;
+
+import static com.csl.cslibrary4a.RfidReader.TagType.TAG_AXZON;
+import static com.csl.cslibrary4a.RfidReader.TagType.TAG_MAGNUS_S2;
+import static com.csl.cslibrary4a.RfidReader.TagType.TAG_MAGNUS_S3;
+import static com.csl.cslibrary4a.RfidReader.TagType.TAG_AXZON_XERXES;
+
+import androidx.lifecycle.Lifecycle;
+import android.graphics.Color;
+import android.os.AsyncTask;
+import android.os.Bundle;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.AdapterView;
+import android.widget.ArrayAdapter;
+import android.widget.Button;
+import android.widget.CheckBox;
+import android.widget.EditText;
+import android.widget.Spinner;
+import android.widget.TableRow;
+import android.widget.TextView;
+import android.widget.Toast;
+
+import com.csl.cs710ademoapp.AccessTask;
+import com.csl.cs710ademoapp.GenericTextWatcher;
+import com.csl.cs710ademoapp.MainActivity;
+import com.csl.cs710ademoapp.R;
+import com.csl.cslibrary4a.ReaderDevice;
+import com.csl.cslibrary4a.RfidReaderChipData;
+
+public class AccessMicronFragment extends CommonFragment {
+ final boolean DEBUG = true;
+ boolean bXerxesEnable = false;
+ EditText editTextaccessRWSelectHoldTime, editTextRWTagID, editTextAccessRWAccPassword, editTextaccessRWAntennaPower;
+ TextView textViewSelectHoldTimeLabel, textViewConfigOk, textViewCalibrationOk, textViewAnalogPort2CodeOk, textViewAnalogPort1CodeOk, textViewSensorCodeOk, textViewRssiCodeOk, textViewTemperatureCodeOk;
+ CheckBox checkBoxConfig, checkBoxCalibration, checkBoxAnalogPort1Code, checkBoxAnalogPort2Code, checkBoxSensorCode, checkBoxRssiCode, checkBoxTemperatureCode;
+ Spinner spinnerTagType, spinnerSensorUnit, spinnerTemperatureUnit;
+ boolean btagTypeSelected = false;
+
+ TextView textViewModelCode, textViewCalibrationVersion, textViewAnalogPort1Code, textViewAnalogPort2Code, textViewSensorCode, textViewRssiCode, textViewTemperatureCode;
+ private Button buttonRead;
+
+ enum ReadWriteTypes {
+ NULL, MODELCODE, CALIBRATION, SENSORCODE, RSSICODE, TEMPERATURECODE
+ }
+ ReadWriteTypes readWriteTypes;
+ boolean operationRead = false;
+
+ private AccessTask accessTask;
+ private int modelCode = 0, selectHold = 15;
+ private int calCode1, calTemp1, calCode2, calTemp2, calVer = -1;
+ private boolean changedSelectIndex = false;
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ super.onCreateView(inflater, container, savedInstanceState, false);
+ return inflater.inflate(R.layout.fragment_access_micron, container, false);
+ }
+
+ @Override
+ public void onActivityCreated(Bundle savedInstanceState) {
+ super.onActivityCreated(savedInstanceState);
+
+ editTextRWTagID = (EditText) getActivity().findViewById(R.id.accessMNTagID);
+ editTextAccessRWAccPassword = (EditText) getActivity().findViewById(R.id.accessMNAccPasswordValue);
+ editTextAccessRWAccPassword.addTextChangedListener(new GenericTextWatcher(editTextAccessRWAccPassword, 8));
+ editTextAccessRWAccPassword.setText(MainActivity.config.configPassword);
+
+ if (MainActivity.config != null) { if (MainActivity.config.config0 != null) selectHold = Integer.parseInt(MainActivity.config.config0); }
+ EditText editText = (EditText) getActivity().findViewById(R.id.accessMNRssiUpperLimit);
+ editText.setText(MainActivity.config.config1);
+ editText = (EditText) getActivity().findViewById(R.id.accessMNRssiLowerLimit);
+ editText.setText(MainActivity.config.config2);
+ editText = (EditText) getActivity().findViewById(R.id.accessMNHumidityThreshold);
+ editText.setText(MainActivity.config.config3);
+ TableRow tableRow = (TableRow) getActivity().findViewById(R.id.accessMNHumidityThresholdRow);
+ if (MainActivity.mDid.matches("E28240")) tableRow.setVisibility(View.GONE);
+
+ textViewConfigOk = (TextView) getActivity().findViewById(R.id.accessMNModelCodeOK);
+ textViewCalibrationOk = (TextView) getActivity().findViewById(R.id.accessMNCalibrationOK);
+ textViewAnalogPort1CodeOk = (TextView) getActivity().findViewById(R.id.accessMNAnalogPort1CodeOK);
+ textViewAnalogPort2CodeOk = (TextView) getActivity().findViewById(R.id.accessMNAnalogPort2CodeOK);
+ textViewSensorCodeOk = (TextView) getActivity().findViewById(R.id.accessMNSensorCodeOK);
+ textViewRssiCodeOk = (TextView) getActivity().findViewById(R.id.accessMNRssiCodeOK);
+ textViewTemperatureCodeOk = (TextView) getActivity().findViewById(R.id.accessMNTemperatureCodeOK);
+
+ checkBoxConfig = (CheckBox) getActivity().findViewById(R.id.accessMNModelCodeTitle);
+ checkBoxCalibration = (CheckBox) getActivity().findViewById(R.id.accessMNCalibrationTitle);
+ checkBoxAnalogPort1Code = (CheckBox) getActivity().findViewById(R.id.accessMNAnalogPort1CodeTitle); checkBoxAnalogPort1Code.setEnabled(false);
+ checkBoxAnalogPort2Code = (CheckBox) getActivity().findViewById(R.id.accessMNAnalogPort2CodeTitle); checkBoxAnalogPort2Code.setEnabled(false);
+ checkBoxSensorCode = (CheckBox) getActivity().findViewById(R.id.accessMNSensorCodeTitle);
+ checkBoxRssiCode = (CheckBox) getActivity().findViewById(R.id.accessMNRssiCodeTitle);
+ checkBoxTemperatureCode = (CheckBox) getActivity().findViewById(R.id.accessMNTemperatureCodeTitle);
+
+ textViewModelCode = (TextView) getActivity().findViewById(R.id.accessMNModelCode);
+
+ textViewAnalogPort1Code = (TextView) getActivity().findViewById(R.id.accessMNAnalogPort1Code);
+ textViewAnalogPort2Code = (TextView) getActivity().findViewById(R.id.accessMNAnalogPort2Code);
+ textViewSensorCode = (TextView) getActivity().findViewById(R.id.accessMNSensorCode);
+ textViewRssiCode = (TextView) getActivity().findViewById(R.id.accessMNRssiCode);
+ textViewCalibrationVersion = (TextView) getActivity().findViewById(R.id.accessMNCalibrationVersion);
+ textViewTemperatureCode = (TextView) getActivity().findViewById(R.id.accessMNTemperatureCode);
+
+ ArrayAdapter arrayAdapterTagType;
+ if (bXerxesEnable) arrayAdapterTagType = ArrayAdapter.createFromResource(getActivity(), R.array.xerxesTag_options, R.layout.custom_spinner_layout);
+ else arrayAdapterTagType = ArrayAdapter.createFromResource(getActivity(), R.array.rfMicronTag_options, R.layout.custom_spinner_layout);
+ arrayAdapterTagType.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+ spinnerTagType = (Spinner) getActivity().findViewById(R.id.accessMNTagType);
+ spinnerTagType.setAdapter(arrayAdapterTagType);
+ spinnerTagType.setEnabled(false);
+ if (MainActivity.mDid != null) {
+ if (MainActivity.mDid.matches("E28240")) spinnerTagType.setSelection(0);
+ else if (MainActivity.mDid.matches("E282402")) spinnerTagType.setSelection(1);
+ else if (MainActivity.mDid.matches("E282403")) spinnerTagType.setSelection(2);
+ else if (MainActivity.mDid.matches("E282405")) spinnerTagType.setSelection(3);
+ }
+ spinnerTagType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
+ @Override
+ public void onItemSelected(AdapterView> adapterView, View view, int i, long l) {
+ TableRow tableRowCalibration = (TableRow) getActivity().findViewById(R.id.accessMNCalibrationRow);
+ TableRow tableRowTemperatureCode = (TableRow) getActivity().findViewById(R.id.accessMNTemperatureCodeRow);
+ TableRow tableRowAnalogPort1 = (TableRow) getActivity().findViewById(R.id.accessMNAnalogPort1CodeRow);
+ TableRow tableRowAnalogPort2 = (TableRow) getActivity().findViewById(R.id.accessMNAnalogPort2CodeRow);
+
+ switch (spinnerTagType.getSelectedItemPosition()) {
+ case 0:
+ MainActivity.tagType = TAG_AXZON; MainActivity.mDid = "E28240";
+ break;
+ case 1:
+ MainActivity.tagType = TAG_MAGNUS_S2; MainActivity.mDid = "E282402";
+ break;
+ case 2:
+ MainActivity.tagType = TAG_MAGNUS_S3; MainActivity.mDid = "E282403";
+ break;
+ case 3:
+ MainActivity.tagType = TAG_AXZON_XERXES; MainActivity.mDid = "E282405";
+ break;
+ }
+ if (btagTypeSelected) {
+ switch (spinnerTagType.getSelectedItemPosition()) {
+ case 0:
+ case 1:
+ editTextaccessRWSelectHoldTime.setText("0");
+ break;
+ case 2:
+ editTextaccessRWSelectHoldTime.setText("3");
+ break;
+ case 3:
+ editTextaccessRWSelectHoldTime.setText("9");
+ break;
+ }
+ } else btagTypeSelected = true;
+ switch (spinnerTagType.getSelectedItemPosition()) {
+ case 0:
+ case 1:
+ case 2:
+ textViewSelectHoldTimeLabel.setVisibility(View.GONE);
+ editTextaccessRWSelectHoldTime.setVisibility(View.GONE);
+ tableRowAnalogPort1.setVisibility(View.GONE);
+ tableRowAnalogPort2.setVisibility(View.GONE);
+ break;
+ case 3:
+ textViewSelectHoldTimeLabel.setVisibility(View.VISIBLE);
+ editTextaccessRWSelectHoldTime.setVisibility(View.VISIBLE);
+ tableRowAnalogPort1.setVisibility(View.VISIBLE);
+ tableRowAnalogPort2.setVisibility(View.VISIBLE);
+ break;
+ }
+ switch (spinnerTagType.getSelectedItemPosition()) {
+ case 0:
+ case 1:
+ tableRowCalibration.setVisibility(View.GONE);
+ tableRowTemperatureCode.setVisibility(View.GONE);
+ break;
+ case 2:
+ case 3:
+ tableRowCalibration.setVisibility(View.VISIBLE);
+ tableRowTemperatureCode.setVisibility(View.VISIBLE);
+ break;
+ }
+ }
+
+ @Override
+ public void onNothingSelected(AdapterView> adapterView) {
+
+ }
+ });
+
+ ArrayAdapter arrayAdapterSensorUnit = ArrayAdapter.createFromResource(getActivity(), R.array.sensor_unit_options, R.layout.custom_spinner_layout);
+ arrayAdapterSensorUnit.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+ spinnerSensorUnit = (Spinner) getActivity().findViewById(R.id.accessMNSensorUnit);
+ spinnerSensorUnit.setAdapter(arrayAdapterSensorUnit);
+ spinnerSensorUnit.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
+ @Override
+ public void onItemSelected(AdapterView> adapterView, View view, int i, long l) {
+ setSensorCode(null);
+ }
+
+ @Override
+ public void onNothingSelected(AdapterView> adapterView) {
+
+ }
+ });
+ if (MainActivity.mDid.matches("E28240")) spinnerSensorUnit.setEnabled(false);
+
+ ArrayAdapter arrayAdapterTemperatureUnit = ArrayAdapter.createFromResource(getActivity(), R.array.temperature_unit_options, R.layout.custom_spinner_layout);
+ arrayAdapterTemperatureUnit.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+ spinnerTemperatureUnit = (Spinner) getActivity().findViewById(R.id.accessMNTemperatureUnit);
+ spinnerTemperatureUnit.setAdapter(arrayAdapterTemperatureUnit);
+ spinnerTemperatureUnit.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
+ @Override
+ public void onItemSelected(AdapterView> adapterView, View view, int i, long l) {
+ setTemperatureCode(null);
+ }
+
+ @Override
+ public void onNothingSelected(AdapterView> adapterView) {
+
+ }
+ });
+
+ textViewSelectHoldTimeLabel = (TextView) getActivity().findViewById(R.id.accessMNSelectHoldTimeLabel);
+ editTextaccessRWSelectHoldTime = (EditText) getActivity().findViewById(R.id.accessMNSelectHoldTime);
+ editTextaccessRWSelectHoldTime.setText(String.valueOf(selectHold));
+
+ editTextaccessRWAntennaPower = (EditText) getActivity().findViewById(R.id.accessMNAntennaPower);
+ editTextaccessRWAntennaPower.setText(String.valueOf(MainActivity.config.configPower));
+
+ buttonRead = (Button) getActivity().findViewById(R.id.accessMNReadButton);
+ buttonRead.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (MainActivity.csLibrary4A.isBleConnected() == false) {
+ Toast.makeText(MainActivity.mContext, R.string.toast_ble_not_connected, Toast.LENGTH_SHORT).show();
+ return;
+ } else if (MainActivity.csLibrary4A.isRfidFailure()) {
+ Toast.makeText(MainActivity.mContext, "Rfid is disabled", Toast.LENGTH_SHORT).show();
+ return;
+ }
+ selectHold = Integer.parseInt(editTextaccessRWSelectHoldTime.getText().toString());
+ operationRead = true; startAccessTask();
+ }
+ });
+
+ MainActivity.csLibrary4A.setSameCheck(false);
+ }
+
+ @Override
+ public void onResume() {
+ super.onResume();
+ setupTagID();
+ }
+
+ @Override
+ public void onDestroy() {
+ if (accessTask != null) accessTask.cancel(true);
+ MainActivity.csLibrary4A.setSameCheck(true);
+ super.onDestroy();
+ }
+
+ boolean userVisibleHint = false;
+ @Override
+ public void setUserVisibleHint(boolean isVisibleToUser) {
+ super.setUserVisibleHint(isVisibleToUser);
+ if (getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.RESUMED) == false) return;
+ if(getUserVisibleHint()) {
+ userVisibleHint = true;
+ setupTagID();
+ } else {
+ userVisibleHint = false;
+
+ if (editTextaccessRWSelectHoldTime == null) return;
+ int iValue = Integer.parseInt(editTextaccessRWSelectHoldTime.getText().toString());
+ if (iValue > 255) editTextaccessRWSelectHoldTime.setText("255");
+ else if (iValue < 0) editTextaccessRWSelectHoldTime.setText("0");
+ iValue = Integer.parseInt(editTextaccessRWSelectHoldTime.getText().toString());
+ MainActivity.selectHold = iValue;
+
+ EditText editText = (EditText) getActivity().findViewById(R.id.accessMNRssiUpperLimit);
+ MainActivity.config.config1 = editText.getText().toString();
+ editText = (EditText) getActivity().findViewById(R.id.accessMNRssiLowerLimit);
+ MainActivity.config.config2 = editText.getText().toString();
+ editText = (EditText) getActivity().findViewById(R.id.accessMNHumidityThreshold);
+ MainActivity.config.config3 = editText.getText().toString();
+ }
+ }
+
+ public static AccessMicronFragment newInstance(boolean bXerxesEnable) {
+ AccessMicronFragment myFragment = new AccessMicronFragment();
+ myFragment.bXerxesEnable = bXerxesEnable;
+ return myFragment;
+ }
+ public AccessMicronFragment() {
+ super("AccessMicronFragment");
+ }
+
+ void setupTagID() {
+ ReaderDevice tagSelected = MainActivity.tagSelected;
+ boolean bSelected = false;
+ if (tagSelected != null) {
+ if (tagSelected.getSelected() == true) {
+ String stringDetail = tagSelected.getDetails();
+ int indexUser = stringDetail.indexOf("TID=");
+ if (indexUser != -1) {
+ //
+ }
+ bSelected = true;
+ if (editTextRWTagID != null) editTextRWTagID.setText(tagSelected.getAddress());
+
+ if (setModelCode(tagSelected.getTid())) {
+ textViewModelCode.setText(tagSelected.getTid().substring(5));
+ } else if (tagSelected.getMdid() == null) {
+ } else if (tagSelected.getMdid().contains("E282402")) {
+ textViewModelCode.setText("02"); modelCode = 2;
+ } else if (tagSelected.getMdid().contains("E282403")) {
+ textViewModelCode.setText("03"); modelCode = 3;
+ } else if (tagSelected.getMdid().contains("E282405")) {
+ textViewModelCode.setText("05"); modelCode = 5;
+ }
+
+ String strRes = tagSelected.getRes();
+ if (strRes != null) {
+ int ibracket = strRes.indexOf("(");
+ if (ibracket > 0) strRes = strRes.substring(0, ibracket);
+
+ if (modelCode == 5) {
+ if (strRes.length() < 4) textViewAnalogPort1Code.setText("");
+ else textViewAnalogPort1Code.setText(str2Decimal(strRes.substring(0,4)));
+ if (strRes.length() < 8) textViewAnalogPort2Code.setText("");
+ else textViewAnalogPort2Code.setText(str2Decimal(strRes.substring(4, 8)));
+ if (strRes.length() < 8) strRes = "";
+ else strRes = strRes.substring(8);
+ }
+
+ if (strRes.length() < 4) textViewSensorCode.setText("");
+ else setSensorCode(strRes.substring(0, 4));
+ if (strRes.length() < 4) strRes = "";
+ else strRes = strRes.substring(4);
+
+ if (modelCode == 2) strRes = tagSelected.getRes2();
+ if (strRes.length() < 4) textViewRssiCode.setText("");
+ else textViewRssiCode.setText(str2Decimal(strRes.substring(0, 4)));
+ if (strRes.length() < 4) strRes = "";
+ else strRes = strRes.substring(4);
+
+ if (modelCode == 3 || modelCode == 5) {
+ if (setCalibrationVersion(tagSelected.getUser()))
+ setTemperatureCode(strRes);
+ }
+ }
+
+ stringDetail = tagSelected.getDetails();
+ indexUser = stringDetail.indexOf("USER=");
+ if (indexUser != -1) {
+ String stringUser = stringDetail.substring(indexUser + 5);
+ MainActivity.csLibrary4A.appendToLog("stringUser = " + stringUser);
+
+ boolean bEnableBAPMode = false;
+ int number = Integer.valueOf(stringUser.substring(3, 4), 16);
+ if ((number % 2) == 1) bEnableBAPMode = true;
+ }
+ }
+ }
+ }
+
+ void startAccessTask() {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("startAccessTask()");
+ if (updating == false) {
+ updating = true; bankProcessing = 0;
+ checkProcessing = 0;
+ mHandler.removeCallbacks(updateRunnable);
+ mHandler.post(updateRunnable);
+ }
+ }
+ boolean updating = false; int bankProcessing = 0;
+ int checkProcessing = 0;
+ private final Runnable updateRunnable = new Runnable() {
+ @Override
+ public void run() {
+ boolean rerunRequest = false; boolean taskRequest = false;
+ if (accessTask == null) {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("AccessMicronFragment().updateRunnable(): NULL accessReadWriteTask");
+ taskRequest = true;
+ } else if (accessTask.getStatus() != AsyncTask.Status.FINISHED) {
+ rerunRequest = true;
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("AccessMicronFragment().updateRunnable(): accessReadWriteTask.getStatus() = " + accessTask.getStatus().toString());
+ } else {
+ taskRequest = true;
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("AccessMicronFragment().updateRunnable(): FINISHED accessReadWriteTask");
+ }
+ if (processResult()) { rerunRequest = true; MainActivity.csLibrary4A.appendToLog("processResult is TRUE");}
+ else if (taskRequest) {
+ boolean invalid = processTickItems();
+ MainActivity.csLibrary4A.appendToLog("processTickItems, invalid = " + invalid);
+ if (bankProcessing++ != 0 && invalid == true) rerunRequest = false;
+ else {
+ int selectBank = 1;
+ int selectOffset = 32;
+ String selectMask = editTextRWTagID.getText().toString();
+ accessTask = new AccessTask(buttonRead, null, invalid, true,
+ selectMask, selectBank, selectOffset,
+ editTextAccessRWAccPassword.getText().toString(),
+ Integer.valueOf(editTextaccessRWAntennaPower.getText().toString()),
+ (operationRead ? RfidReaderChipData.HostCommands.CMD_18K6CREAD: RfidReaderChipData.HostCommands.CMD_18K6CWRITE),
+ 0, 0, true, bSkipClearPrefilter,
+ null, null, null, null, null);
+ accessTask.execute();
+ rerunRequest = true;
+ MainActivity.csLibrary4A.appendToLog("accessTask is created with selectBank = " + selectBank);
+ }
+ }
+ if (rerunRequest) {
+ mHandler.postDelayed(updateRunnable, 500);
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("AccessMicronFragment().updateRunnable(): Restart");
+ }
+ else updating = false;
+ MainActivity.csLibrary4A.appendToLog("AccessMicronFragment().updateRunnable(): Ending with updating = " + updating);
+ }
+ };
+
+ boolean setModelCode(String strTid) {
+ if (strTid == null) return false;
+ if (strTid.length() <= 7) return false;
+ if (strTid.substring(0, 7).matches("E282401")) {
+ modelCode = 1; return true;
+ } else if (strTid.substring(0, 7).matches("E282402")) {
+ modelCode = 2; return true;
+ } else if (strTid.substring(0, 7).matches("E282403")) {
+ modelCode = 3; return true;
+ } else if (strTid.substring(0, 7).matches("E282405")) {
+ modelCode = 5; return true;
+ }
+ return false;
+ }
+ boolean setCalibrationVersion(String strUser) {
+ MainActivity.csLibrary4A.appendToLog("strUser = " + strUser);
+ textViewCalibrationVersion.setText("");
+ if (strUser == null) return false;
+ if (strUser.length() < 16) return false;
+ if (modelCode == 3) {
+ int crc = Integer.parseInt(strUser.substring(0, 4), 16);
+ calCode1 = Integer.parseInt(strUser.substring(4, 7), 16);
+ calTemp1 = Integer.parseInt(strUser.substring(7, 10), 16);
+ calTemp1 >>= 1;
+ calCode2 = Integer.parseInt(strUser.substring(9, 13), 16);
+ calCode2 >>= 1;
+ calCode2 &= 0xFFF;
+ calTemp2 = Integer.parseInt(strUser.substring(12, 16), 16);
+ calTemp2 >>= 2;
+ calTemp2 &= 0x7FF;
+ calVer = Integer.parseInt(strUser.substring(15, 16), 16);
+ calVer &= 0x3;
+ if (DEBUG)
+ MainActivity.csLibrary4A.appendToLog("crc = " + crc + ", code1 = " + calCode1 + ", temp1 = " + calTemp1 + ", code2 = " + calCode2 + ", temp2 = " + calTemp2 + ", ver = " + calVer);
+ strUser += String.format(", v%d", calVer);
+ }
+ textViewCalibrationVersion.setText(strUser);
+ return true;
+ }
+ String str2Decimal(String strData) {
+ int iTemp = -1;
+ if (strData != null) if (strData.length() >= 4) iTemp = Integer.parseInt(strData.substring(0, 4), 16);
+ if (iTemp == -1) return "";
+ return String.format("%d", iTemp);
+ }
+ boolean setRssiCode(String strData) {
+ if (strData == null) return false;
+ if (strData.length() < 4) return false;
+
+ int iTemp = Integer.parseInt(strData.substring(0,4), 16); iTemp &= 0x1F;
+ textViewRssiCode.setText(String.format("%d", iTemp)); //"%02X"
+ EditText editText = (EditText) getActivity().findViewById(R.id.accessMNRssiLowerLimit);
+ int iTempLower = Integer.parseInt(editText.getText().toString());
+ editText = (EditText) getActivity().findViewById(R.id.accessMNRssiUpperLimit);
+ int iTempUpper = Integer.parseInt(editText.getText().toString());
+ if (iTemp >= iTempLower && iTemp <= iTempUpper) textViewRssiCode.setTextColor(Color.BLACK);
+ else textViewRssiCode.setTextColor(Color.RED);
+ return true;
+ }
+
+ String strSensorCode0;
+ boolean setSensorCode(String strData) {
+ if (strData == null) {
+ if (strSensorCode0 != null && textViewSensorCode.getText().toString().length() != 0) strData = strSensorCode0;
+ else return false;
+ }
+ if (strData.length() < 4) return false;
+ strSensorCode0 = strData;
+ strData = str2Decimal(strData);
+ if (spinnerSensorUnit.getSelectedItemPosition() == 1) {
+ float fValue = (float) Integer.parseInt(strData);
+ if (true) {
+ EditText editText = (EditText) getActivity().findViewById(R.id.accessMNHumidityThreshold);
+ int iValue = Integer.parseInt(editText.getText().toString());
+ MainActivity.csLibrary4A.appendToLog("iValue for Dry/Wet comparision = " + iValue);
+ if (fValue >= iValue) strData = "dry";
+ else strData = "wet";
+ } else {
+ if (modelCode == 2) fValue /= (float) 0x1F;
+ else fValue /= (float) 0x1FF;
+ fValue *= 100;
+ strData = String.format("%.1f", fValue);
+ }
+ }
+ textViewSensorCode.setText(strData);
+ return true;
+ }
+
+ String strTemperatureCode0;
+ boolean setTemperatureCode(String strData) {
+ if (strData == null) {
+ if (strTemperatureCode0 != null && textViewTemperatureCode.getText().toString().length() != 0) strData = strTemperatureCode0;
+ else return false;
+ }
+ if (strData.length() < 4) return false;
+ float fTemperature = -500;
+ if (modelCode == 3 && calVer != -1) {
+ fTemperature = Integer.parseInt(strData.substring(0, 4), 16);
+ fTemperature = ((float) calTemp2 - (float) calTemp1) * (fTemperature - (float) calCode1);
+ fTemperature /= ((float) (calCode2) - (float) calCode1);
+ fTemperature += (float) calTemp1;
+ fTemperature -= 800;
+ fTemperature /= 10;
+ } else if (modelCode == 5) {
+ String strCalData = textViewCalibrationVersion.getText().toString();
+ if (strCalData != null) fTemperature = MainActivity.csLibrary4A.decodeMicronTemperature(5, strData, strCalData);
+ }
+ if (fTemperature != -500) {
+ if (spinnerTemperatureUnit.getSelectedItemPosition() == 1) {
+ fTemperature *= 1.8;
+ fTemperature += 32;
+ }
+ strTemperatureCode0 = strData;
+ strData = String.format("%.1f", fTemperature);
+ } else {
+ strTemperatureCode0 = null;
+ strData = "";
+ }
+ textViewTemperatureCode.setText(strData);
+ return true;
+ }
+
+ boolean processResult() {
+ String accessResult = null;
+ if (accessTask == null) return false;
+ else if (accessTask.getStatus() != AsyncTask.Status.FINISHED) return false;
+ else {
+ if (changedSelectIndex) {
+ changedSelectIndex = false; MainActivity.selectFor = 0;
+ MainActivity.csLibrary4A.setSelectCriteriaDisable(-1);
+ }
+ accessResult = accessTask.accessResult;
+ if (accessResult == null) {
+ if (readWriteTypes == ReadWriteTypes.MODELCODE) {
+ textViewConfigOk.setText("E");
+ //checkBoxConfig.setChecked(false);
+ } else if (readWriteTypes == ReadWriteTypes.CALIBRATION) {
+ textViewCalibrationOk.setText("E");
+ //checkBoxCalibration.setChecked(false);
+ } else if (readWriteTypes == ReadWriteTypes.SENSORCODE) {
+ textViewSensorCodeOk.setText("E");
+ //checkBoxSensorCode.setChecked(false);
+ } else if (readWriteTypes == ReadWriteTypes.RSSICODE) {
+ textViewRssiCodeOk.setText("E");
+ //checkBoxRssiCode.setChecked(false);
+ } else if (readWriteTypes == ReadWriteTypes.TEMPERATURECODE) {
+ textViewTemperatureCodeOk.setText("E");
+ //checkBoxTemperatureCode.setChecked(false);
+ }
+ } else {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("accessResult = " + accessResult);
+ if (readWriteTypes == ReadWriteTypes.MODELCODE) {
+ textViewConfigOk.setText("O");
+ //checkBoxConfig.setChecked(false);
+ readWriteTypes = ReadWriteTypes.NULL;
+ boolean valid = setModelCode(accessResult);
+ if (valid) textViewModelCode.setText(accessResult.substring(5));
+ else Toast.makeText(MainActivity.mContext, "This is not Micron 0X tag !!!", Toast.LENGTH_SHORT).show();
+ } else if (readWriteTypes == ReadWriteTypes.CALIBRATION) {
+ textViewCalibrationOk.setText("O");
+ //checkBoxCalibration.setChecked(false);
+ readWriteTypes = ReadWriteTypes.NULL;
+ setCalibrationVersion(accessResult);
+ } else if (readWriteTypes == ReadWriteTypes.SENSORCODE) {
+ textViewSensorCodeOk.setText("O");
+ //checkBoxSensorCode.setChecked(false);
+ readWriteTypes = ReadWriteTypes.NULL;
+ setSensorCode(accessResult);
+ } else if (readWriteTypes == ReadWriteTypes.RSSICODE) {
+ textViewRssiCodeOk.setText("O");
+ //checkBoxRssiCode.setChecked(false);
+ readWriteTypes = ReadWriteTypes.NULL;
+ setRssiCode(accessResult);
+ } else if (readWriteTypes == ReadWriteTypes.TEMPERATURECODE) {
+ textViewTemperatureCodeOk.setText("O");
+ //checkBoxTemperatureCode.setChecked(false);
+ readWriteTypes = ReadWriteTypes.NULL;
+ if (accessResult.length() >= 4) {
+ setTemperatureCode(accessResult.substring(0,4));
+ }
+ }
+ }
+ accessTask = null;
+ return true;
+ }
+ }
+
+ boolean bSkipClearPrefilter = false;
+ boolean processTickItems() {
+ boolean invalidRequest1 = false;
+ int accBank = 0, accSize = 0, accOffset = 0;
+ String writeData = "";
+
+ bSkipClearPrefilter = false;
+ if (editTextRWTagID.getText().toString().length() == 0) invalidRequest1 = true;
+ else if (checkBoxConfig.isChecked() == true && checkProcessing < 1 && operationRead) {
+ accBank = 2; accOffset = 0; accSize = 2; readWriteTypes = ReadWriteTypes.MODELCODE; checkProcessing = 1;
+ textViewConfigOk.setText(""); textViewModelCode.setText(""); modelCode = -1;
+ } else if (checkBoxCalibration.isChecked() == true && checkProcessing < 2 && operationRead && (modelCode == 3 || modelCode == 5)) {
+ accBank = 3; accSize = 4; readWriteTypes = ReadWriteTypes.CALIBRATION; checkProcessing = 2;
+ accOffset = 8; if (modelCode == 5) accOffset = 18;
+ textViewCalibrationOk.setText(""); textViewCalibrationVersion.setText(""); calVer = -1;
+ } else if (checkBoxSensorCode.isChecked() == true && modelCode != -1 && checkProcessing < 3 && operationRead) {
+ accBank = 0; if (modelCode == 1) accBank = 3;
+ accOffset = 11; if (modelCode == 3 || modelCode == 5) accOffset = 12;
+ accSize = 1; readWriteTypes = ReadWriteTypes.SENSORCODE; checkProcessing = 3;
+ textViewSensorCodeOk.setText(""); textViewSensorCode.setText("");
+ } else if (checkBoxRssiCode.isChecked() == true && modelCode != -1 && checkProcessing < 4 && operationRead) {
+ int offset = 0xA0;
+ if (modelCode == 3) offset = 0xD0;
+ else if (modelCode == 5) offset = 0x3D0;
+ bSkipClearPrefilter = true;
+ MainActivity.csLibrary4A.setSelectCriteriaDisable(-1);
+ MainActivity.csLibrary4A.setSelectCriteria(-1, true, 4, 5, selectHold,3, offset, "1F");
+ changedSelectIndex = true;
+ accBank = 0; accOffset = 13; if (modelCode == 1) { accBank = 3; accOffset = 9; }
+ accSize = 1; readWriteTypes = ReadWriteTypes.RSSICODE; checkProcessing = 4;
+ textViewRssiCodeOk.setText(""); textViewRssiCode.setText("");
+ } else if (checkBoxTemperatureCode.isChecked() == true && (modelCode == 3 || modelCode == 5) && checkProcessing < 5 && operationRead) {
+ bSkipClearPrefilter = true;
+ MainActivity.csLibrary4A.setSelectCriteriaDisable(-1);
+ if (modelCode == 3) MainActivity.csLibrary4A.setSelectCriteria(-1, true, 4, 2, 0,3, 0xE0, "");
+ else MainActivity.csLibrary4A.setSelectCriteria(-1, true, 4, 5, selectHold,3, 0x3B0, "00");
+ changedSelectIndex = true;
+ accBank = 0; accOffset = 14; accSize = 1; readWriteTypes = ReadWriteTypes.TEMPERATURECODE; checkProcessing = 5;
+ textViewTemperatureCodeOk.setText(""); textViewTemperatureCode.setText("");
+ } else {
+ invalidRequest1 = true;
+ }
+
+ if (invalidRequest1 == false) {
+ if (MainActivity.csLibrary4A.setAccessBank(accBank) == false) {
+ invalidRequest1 = true;
+ }
+ }
+ if (invalidRequest1 == false) {
+ if (MainActivity.csLibrary4A.setAccessOffset(accOffset) == false) {
+ invalidRequest1 = true;
+ }
+ }
+ if (invalidRequest1 == false) {
+ if (accSize == 0) {
+ invalidRequest1 = true;
+ } else if (MainActivity.csLibrary4A.setAccessCount(accSize) == false) {
+ invalidRequest1 = true;
+ }
+ }
+ if (invalidRequest1 == false && operationRead == false) {
+ if (invalidRequest1 == false) {
+ if (MainActivity.csLibrary4A.setAccessWriteData(writeData) == false) {
+ invalidRequest1 = true;
+ }
+ }
+ }
+ return invalidRequest1;
+ }
+}
+
+
+
+package com.csl.cs710ademoapp.fragments;
+
+import android.app.Activity;
+import android.graphics.Typeface;
+import android.os.Bundle;
+import android.os.Handler;
+import android.os.SystemClock;
+import androidx.appcompat.app.AppCompatActivity;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.AdapterView;
+import android.widget.ArrayAdapter;
+import android.widget.Button;
+import android.widget.CheckBox;
+import android.widget.EditText;
+import android.widget.Spinner;
+import android.widget.TextView;
+import android.widget.Toast;
+
+import com.csl.cs710ademoapp.AccessTask1;
+import com.csl.cs710ademoapp.CustomPopupWindow;
+import com.csl.cs710ademoapp.GenericTextWatcher;
+import com.csl.cs710ademoapp.SelectTag;
+import com.csl.cs710ademoapp.MainActivity;
+import com.csl.cs710ademoapp.R;
+import com.csl.cslibrary4a.ReaderDevice;
+import com.csl.cslibrary4a.RfidReaderChipData;
+
+import static com.csl.cs710ademoapp.MainActivity.mContext;
+import static com.csl.cs710ademoapp.MainActivity.tagSelected;
+
+public class AccessReadWriteFragment extends CommonFragment {
+ SelectTag selectTag;
+ Spinner spinnerSelectBank, spinnerRWSelectEpc1;
+ EditText editTextRWSelectOffset, editTextAccessRWAccPassword, editTextAccessRWKillPwd, editTextAccessRWAccPwd, editTextAccPc, editTextAccessRWEpc, editTExtAccessRWXpc;
+ EditText editTextTidValue, editTextUserValue, editTextEpcValue, editTextaccessRWAntennaPower;
+ TextView textViewEpcLength, textViewRunTime;
+ private Button buttonRead;
+ private Button buttonWrite;
+ Handler mHandler = new Handler();
+ String strPCValueRef = "";
+
+ String accEpcValue = ""; String accXpcValue = ""; String accTidValue = ""; String accUserValue = "";
+ enum ReadWriteTypes {
+ NULL, RESERVE, PC, EPC, XPC, TID, USER, EPC1
+ }
+ boolean operationRead = false;
+ ReadWriteTypes readWriteTypes;
+
+ private AccessTask1 accessTask;
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ super.onCreateView(inflater, container, savedInstanceState, true);
+ return inflater.inflate(R.layout.fragment_access_readwrite, container, false);
+ }
+
+ @Override
+ public void onActivityCreated(Bundle savedInstanceState) {
+ super.onActivityCreated(savedInstanceState);
+
+ androidx.appcompat.app.ActionBar actionBar;
+ actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
+ actionBar.setIcon(R.drawable.dl_access);
+ actionBar.setTitle(R.string.title_activity_readwrite);
+
+ selectTag = new SelectTag((Activity)getActivity(), 0);
+
+ spinnerSelectBank = (Spinner) getActivity().findViewById(R.id.selectMemoryBank);
+ ArrayAdapter targetAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.read_memoryBank_options, R.layout.custom_spinner_layout);
+ targetAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+ spinnerSelectBank.setAdapter(targetAdapter);
+ spinnerSelectBank.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
+ @Override
+ public void onItemSelected(AdapterView> parent, View view, int position, long id) {
+ switch (position) {
+ case 0: //if EPC
+ if (tagSelected != null) selectTag.editTextTagID.setText(tagSelected.getAddress());
+ editTextRWSelectOffset.setText("32");
+ break;
+ case 1:
+ if (tagSelected != null) { if (tagSelected.getTid() != null) selectTag.editTextTagID.setText(tagSelected.getTid()); }
+ editTextRWSelectOffset.setText("0");
+ break;
+ case 2:
+ if (tagSelected != null) { if (tagSelected.getUser() != null) selectTag.editTextTagID.setText(tagSelected.getUser()); }
+ editTextRWSelectOffset.setText("0");
+ break;
+ default:
+ break;
+ }
+ }
+
+ @Override
+ public void onNothingSelected(AdapterView> parent) {
+
+ }
+ });
+
+ editTextRWSelectOffset = (EditText) getActivity().findViewById(R.id.selectMemoryOffset);
+ spinnerRWSelectEpc1 = (Spinner) getActivity().findViewById(R.id.accessRWEpc1Title1);
+ ArrayAdapter targetAdapter1 = ArrayAdapter.createFromResource(getActivity(), R.array.memoryBank_options, R.layout.custom_spinner_layout);
+ targetAdapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+ spinnerRWSelectEpc1.setAdapter(targetAdapter1); spinnerRWSelectEpc1.setSelection(1);
+
+ editTextAccessRWAccPassword = (EditText) getActivity().findViewById(R.id.selectPasswordValue);
+ editTextAccessRWAccPassword.addTextChangedListener(new GenericTextWatcher(editTextAccessRWAccPassword, 8));
+ editTextAccessRWAccPassword.setText("00000000");
+ editTextAccessRWKillPwd = (EditText) getActivity().findViewById(R.id.accessRWKillPwdValue);
+ editTextAccessRWKillPwd.addTextChangedListener(new GenericTextWatcher(editTextAccessRWKillPwd, 8));
+ editTextAccessRWAccPwd = (EditText) getActivity().findViewById(R.id.accessRWAccPwdValue);
+ editTextAccessRWAccPwd.addTextChangedListener(new GenericTextWatcher(editTextAccessRWAccPwd, 8));
+ editTextAccPc = (EditText) getActivity().findViewById(R.id.accessRWAccPcValue);
+ editTextAccPc.setHint("PC value");
+ editTextAccPc.addTextChangedListener(new GenericTextWatcher(editTextAccPc, 4));
+ editTextAccessRWEpc = (EditText) getActivity().findViewById(R.id.accessRWAccEpcValue);
+ editTExtAccessRWXpc = (EditText) getActivity().findViewById(R.id.accessRWAccXpcValue);
+ editTextTidValue = (EditText) getActivity().findViewById(R.id.accessRWTidValue);
+ editTextTidValue.setHint("Data Pattern");
+ editTextUserValue = (EditText) getActivity().findViewById(R.id.accessRWUserValue); editTextUserValue.setTypeface(Typeface.MONOSPACE);
+ editTextUserValue.setHint("Data Pattern");
+ editTextEpcValue = (EditText) getActivity().findViewById(R.id.accessRWEpcValue);
+ editTextEpcValue.setHint("Data Pattern");
+
+ editTextaccessRWAntennaPower = (EditText) getActivity().findViewById(R.id.selectAntennaPower);
+ editTextaccessRWAntennaPower.setText(String.valueOf(300));
+
+ textViewEpcLength = (TextView) getActivity().findViewById(R.id.accessRWAccEpcLength);
+ textViewRunTime = (TextView) getActivity().findViewById(R.id.accessRWRunTime);
+
+ buttonRead = (Button) getActivity().findViewById(R.id.accessRWReadButton);
+ buttonRead.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (MainActivity.csLibrary4A.isBleConnected() == false) {
+ Toast.makeText(MainActivity.mContext, R.string.toast_ble_not_connected, Toast.LENGTH_SHORT).show();
+ return;
+ } else if (MainActivity.csLibrary4A.isRfidFailure()) {
+ Toast.makeText(MainActivity.mContext, "Rfid is disabled", Toast.LENGTH_SHORT).show();
+ return;
+ }
+ operationRead = true; startAccessTask();
+ }
+ });
+
+ buttonWrite = (Button) getActivity().findViewById(R.id.accessRWWriteButton);
+ buttonWrite.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (MainActivity.csLibrary4A.isBleConnected() == false) {
+ Toast.makeText(MainActivity.mContext, R.string.toast_ble_not_connected, Toast.LENGTH_SHORT).show();
+ return;
+ } else if (MainActivity.csLibrary4A.isRfidFailure()) {
+ Toast.makeText(MainActivity.mContext, "Rfid is disabled", Toast.LENGTH_SHORT).show();
+ return;
+ }
+ operationRead = false; startAccessTask();
+ }
+ });
+
+ ReaderDevice tagSelected = MainActivity.tagSelected;
+ if (tagSelected != null) {
+ if (tagSelected.getSelected() == true) {
+ String strEpcValue = tagSelected.getAddress();
+ String detail = tagSelected.getDetails();
+ String header = "PC=";
+ if (detail != null && detail.indexOf(header) >= 0) {
+ int index = detail.indexOf(header) + header.length();
+ strPCValueRef = detail.substring(index, index + 4);
+ updatePCEpc(strPCValueRef, strEpcValue);
+ }
+ }
+ }
+ MainActivity.csLibrary4A.setSameCheck(true);
+ }
+
+ @Override
+ public void onDestroy() {
+ if (accessTask != null) accessTask.cancel(true);
+ MainActivity.csLibrary4A.setSameCheck(true);
+ MainActivity.csLibrary4A.restoreAfterTagSelect();
+ super.onDestroy();
+ }
+
+ public AccessReadWriteFragment() {
+ super("AccessReadWriteFragment");
+ }
+
+ int getPC2EpcWordCount(String detail) {
+ String detail2 = detail.substring(0, 1);
+ int number2 = Integer.valueOf(detail2, 16) * 2;
+ String detail3 = detail.substring(1, 2);
+ int number3 = Integer.valueOf(detail3, 16);
+ if ((number3 / 8) != 0) number2 += 1;
+ return number2;
+ }
+ void updatePCEpc(String strPCValue, String strEpcValue) {
+ boolean needPopup = false;
+ if (strPCValue == null) strPCValue = "";
+ if (strPCValue.length() != 0) editTextAccPc.setText(strPCValue);
+ else strPCValue = strPCValueRef;
+ if (strPCValueRef != null && strPCValue != null) {
+ if (strPCValue.matches(strPCValueRef) == false && strPCValue.length() == 4) {
+ needPopup = true;
+ strPCValueRef = strPCValue;
+ }
+ }
+
+ int iWordCount = getPC2EpcWordCount(strPCValue);
+ textViewEpcLength.setText("EPC has " + (iWordCount * 16) + " bits");
+ if (strEpcValue != null) {
+ tagSelected.setAddress(strEpcValue); if (spinnerSelectBank.getSelectedItemPosition() == 0) selectTag.editTextTagID.setText(strEpcValue);
+ editTextAccessRWEpc.setText(strEpcValue);
+ } else {
+ if (iWordCount * 4 < selectTag.editTextTagID.getText().toString().length()) {
+ // needPopup = true;
+ String strTemp = selectTag.editTextTagID.getText().toString().substring(0, iWordCount * 4);
+ tagSelected.setAddress(strEpcValue); if (spinnerSelectBank.getSelectedItemPosition() == 0) selectTag.editTextTagID.setText(strTemp);
+ }
+ if (iWordCount * 4 < editTextAccessRWEpc.getText().toString().length()) {
+ // needPopup = true;
+ String strTemp = editTextAccessRWEpc.getText().toString().substring(0, iWordCount * 4);
+ editTextAccessRWEpc.setText(strTemp);
+ }
+ if (editTextAccessRWEpc.getText().toString().length() != 0) {
+ String strTemp = editTextAccessRWEpc.getText().toString();
+ if (selectTag.editTextTagID.getText().toString().matches(strTemp) == false) {
+ // needPopup = true;
+ tagSelected.setAddress(strTemp); if (spinnerSelectBank.getSelectedItemPosition() == 0) selectTag.editTextTagID.setText(strTemp);
+ }
+ }
+ }
+ editTextAccessRWEpc.addTextChangedListener(new GenericTextWatcher(editTextAccessRWEpc, iWordCount * 4));
+ String strTemp = editTextAccessRWEpc.getText().toString();
+ editTextAccessRWEpc.setText(strTemp);
+
+ if (needPopup) {
+ CustomPopupWindow customPopupWindow = new CustomPopupWindow(mContext);
+ customPopupWindow.popupStart("Changing EPC Length will automatically modify to " + (iWordCount * 16) + " bits.", false);
+ }
+ }
+
+ long msStartTime;
+ void startAccessTask() {
+ if (selectTag.editTextTagID.getText().toString().length() == 0) {
+ Toast.makeText(MainActivity.mContext, "Please select tag first !!!", Toast.LENGTH_SHORT).show();
+ return;
+ }
+ if (updating == false) {
+ msStartTime = SystemClock.elapsedRealtime();
+ textViewRunTime.setText("");
+ updating = true; bankProcessing = 0; restartAccessBank = -1;
+// MainActivity.mCs108Library4a.
+ mHandler.removeCallbacks(updateRunnable);
+ mHandler.post(updateRunnable);
+ }
+ }
+ boolean updating = false; int bankProcessing = 0;
+ private final Runnable updateRunnable = new Runnable() {
+ @Override
+ public void run() {
+ boolean rerunRequest = true; boolean taskRequest = false;
+ if (processResult()) { rerunRequest = true; }
+ else if (accessTask == null || accessTask.isResultReady()) {
+ bcheckBoxAll = false;
+ boolean invalid = processTickItems();
+ if (bankProcessing == 0 && bcheckBoxAll) rerunRequest = false;
+ else if (bankProcessing++ != 0 && invalid == true) rerunRequest = false;
+ else {
+ if (restartAccessBank != accessBank) {
+ restartAccessBank = accessBank;
+ restartCounter = 3;
+ }
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("AccessReadWriteFragment().InventoryRfidTask(): tagID=" + selectTag.editTextTagID.getText() + ", operationrRead=" + operationRead + ", accessBank=" + accessBank + ", accOffset=" + accOffset + ", accSize=" + accSize);
+ int selectOffset = 0;
+ selectOffset = Integer.parseInt(editTextRWSelectOffset.getText().toString());
+ EditText editTextBlockCount = (EditText) getActivity().findViewById(R.id.accessRWBlockCount);
+ Integer accBlockCount = 32;
+ try {
+ accBlockCount = Integer.parseInt(editTextBlockCount.getText().toString());
+ } catch (Exception ex) { }
+ MainActivity.csLibrary4A.appendToLog("strOut: accWriteData=" + accWriteData);
+ accessTask = new AccessTask1(
+ (operationRead ? buttonRead : buttonWrite), invalid,
+ accessBank, accOffset, accSize, accBlockCount, accWriteData,
+ selectTag.editTextTagID.getText().toString(), spinnerSelectBank.getSelectedItemPosition() + 1, selectOffset,
+ editTextAccessRWAccPassword.getText().toString(),
+ Integer.valueOf(editTextaccessRWAntennaPower.getText().toString()),
+ (operationRead ? RfidReaderChipData.HostCommands.CMD_18K6CREAD: RfidReaderChipData.HostCommands.CMD_18K6CWRITE), updateRunnable);
+ accessTask.execute();
+ rerunRequest = true;
+ }
+ }
+ if (rerunRequest) {
+ mHandler.postDelayed(updateRunnable, 100);
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("AccessReadWriteFragment().updateRunnable(): Restart");
+ }
+ else {
+ if (bankProcessing == 0 && bcheckBoxAll) {
+ Toast.makeText(MainActivity.mContext, "no choice selected yet", Toast.LENGTH_SHORT).show();
+ }
+ updating = false;
+ }
+ }
+ };
+
+ TextView textViewReserveOk, textViewPcOk, textViewEpcOk, textViewTidOk, textViewUserOk, textViewEpc1Ok;
+ CheckBox checkBoxReserve, checkBoxPc, checkBoxEpc, checkBoxTid, checkBoxUser, checkBoxEpc1;
+ int accessBank, accSize, accOffset; String accWriteData;
+ int restartCounter = 0; int restartAccessBank = -1;
+ boolean processResult() {
+ String accessResult = null;
+ if (accessTask == null) return false;
+ if (accessTask.isResultReady() == false) return false;
+ else {
+ long duration = SystemClock.elapsedRealtime() - msStartTime;
+ textViewRunTime.setText(String.format("Run time: %.2f sec", ((float) duration / 1000)));
+ accessResult = accessTask.getResult();
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("processResult(): accessResult = " + accessResult);
+ if (accessResult == null) {
+ if (readWriteTypes == ReadWriteTypes.RESERVE) {
+ textViewReserveOk.setText("E"); checkBoxReserve.setChecked(false);
+ }
+ if (readWriteTypes == ReadWriteTypes.PC) {
+ textViewPcOk.setText("E"); checkBoxPc.setChecked(false);
+ }
+ if (readWriteTypes == ReadWriteTypes.EPC) {
+ textViewEpcOk.setText("E"); checkBoxEpc.setChecked(false);
+ }
+ if (readWriteTypes == ReadWriteTypes.TID) {
+ textViewTidOk.setText("E"); checkBoxTid.setChecked(false);
+ }
+ if (readWriteTypes == ReadWriteTypes.USER) {
+ textViewUserOk.setText("E"); checkBoxUser.setChecked(false);
+ }
+ if (readWriteTypes == ReadWriteTypes.EPC1) {
+ textViewEpc1Ok.setText("E"); checkBoxEpc1.setChecked(false);
+ }
+ } else {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("accessResult = " + accessResult);
+ if (readWriteTypes == ReadWriteTypes.RESERVE) {
+ textViewReserveOk.setText("O"); checkBoxReserve.setChecked(false);
+ readWriteTypes = ReadWriteTypes.NULL;
+ if (accessResult.length() == 0 || operationRead == false) {
+ } else if (accessResult.length() < 8) {
+ editTextAccessRWKillPwd.setText(accessResult);
+ } else {
+ editTextAccessRWKillPwd.setText(accessResult.substring(0, 8));
+ }
+ if (accessResult.length() <= 8) {
+ editTextAccessRWAccPwd.setText("");
+ } else if (accessResult.length() < 16) {
+ editTextAccessRWAccPwd.setText(accessResult.subSequence(8, accessResult.length()));
+ } else {
+ editTextAccessRWAccPwd.setText(accessResult.subSequence(8, 16));
+ }
+ } else if (readWriteTypes == ReadWriteTypes.PC) {
+ textViewPcOk.setText("O"); checkBoxPc.setChecked(false);
+ readWriteTypes = ReadWriteTypes.NULL;
+ if (operationRead) {
+ String newValue = "";
+ if (accessResult.length() <= 4) {
+ newValue = accessResult.subSequence(0, accessResult.length()).toString();
+ } else {
+ newValue = accessResult.subSequence(0, 4).toString();
+ }
+ editTextAccPc.setText(newValue);
+ }
+ updatePCEpc(editTextAccPc.getText().toString(), null);
+ } else if (readWriteTypes == ReadWriteTypes.EPC) {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("AccessReadWrite(). EPC DATA with accessBank = " + accessBank + ", with accessResult.length = " + accessResult.length());
+ textViewEpcOk.setText("O"); checkBoxEpc.setChecked(false);
+ readWriteTypes = ReadWriteTypes.NULL;
+ if (operationRead) {
+ String newValue = "";
+ if (accessResult.length() <= 4) {
+ newValue = accessResult.subSequence(0, accessResult.length()).toString();
+ } else {
+ newValue = accessResult.subSequence(0, 4).toString();
+ }
+ editTextAccPc.setText(newValue);
+ }
+ updatePCEpc(editTextAccPc.getText().toString(), null);
+
+ if (operationRead) {
+ String newValue = "";
+ if (accessResult.length() > 4) {
+ newValue = accessResult.subSequence(4, accessResult.length()).toString();
+ }
+ editTextAccessRWEpc.setText(newValue);
+ }
+ } else if (readWriteTypes == ReadWriteTypes.XPC) {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("AccessReadWrite(). XPC DATA with accessBank = " + accessBank + ", with accessResult.length = " + accessResult.length() + ", with accessResult=" + accessResult);
+ readWriteTypes = ReadWriteTypes.NULL;
+ if (operationRead) {
+ String newValue = accessResult.toString();
+ editTExtAccessRWXpc.setText(newValue);
+ accXpcValue = newValue;
+ } else {
+ accXpcValue = editTExtAccessRWXpc.getText().toString();
+ }
+ } else if (readWriteTypes == ReadWriteTypes.TID) {
+ textViewTidOk.setText("O"); checkBoxTid.setChecked(false);
+ readWriteTypes = ReadWriteTypes.NULL;
+ if (accessResult.length() == 0 || operationRead == false) {
+ } else editTextTidValue.setText(accessResult);
+ } else if (readWriteTypes == ReadWriteTypes.USER) {
+ textViewUserOk.setText("O"); checkBoxUser.setChecked(false);
+ readWriteTypes = ReadWriteTypes.NULL;
+ if (operationRead) {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("AccessReadWrite(). DATA with accessBank = " + accessBank);
+ if (accessTask != null) {
+ int iLength = accessTask.deformatWriteAccessData(accessResult).length();
+ MainActivity.csLibrary4A.appendToLog("endingMessage length=" + iLength);
+ if (iLength < accSize*4) textViewUserOk.setText("H");
+ }
+ editTextUserValue.setText(accessResult);
+ accUserValue = accessResult;
+ } else {
+ accUserValue = editTextUserValue.getText().toString();
+ }
+ } else if (readWriteTypes == ReadWriteTypes.EPC1) {
+ textViewEpc1Ok.setText("O"); checkBoxEpc1.setChecked(false);
+ readWriteTypes = ReadWriteTypes.NULL;
+ if (accessResult.length() == 0 || operationRead == false) {
+ } else {
+ editTextEpcValue.setText(accessResult);
+ accEpcValue = accessResult;
+ }
+ if (operationRead == false) accEpcValue = editTextEpcValue.getText().toString();
+ }
+ accessResult = null;
+ }
+ accessTask = null;
+ return true;
+ }
+ }
+ boolean bcheckBoxAll = false;
+ boolean processTickItems() {
+ String writeData = "";
+ boolean invalidRequest1 = false;
+
+ textViewReserveOk = (TextView) getActivity().findViewById(R.id.accessRWReserveOK);
+ textViewPcOk = (TextView) getActivity().findViewById(R.id.accessRWPcOK);
+ textViewEpcOk = (TextView) getActivity().findViewById(R.id.accessRWEpcOK);
+ textViewTidOk = (TextView) getActivity().findViewById(R.id.accessRWTidOK);
+ textViewUserOk = (TextView) getActivity().findViewById(R.id.accessRWUserOK);
+ textViewEpc1Ok = (TextView) getActivity().findViewById(R.id.accessRWEpc1OK);
+
+ checkBoxReserve = (CheckBox) getActivity().findViewById(R.id.accessRWReserveTitle);
+ checkBoxPc = (CheckBox) getActivity().findViewById(R.id.accessRWPcTitle);
+ checkBoxEpc = (CheckBox) getActivity().findViewById(R.id.accessRWEpcTitle);
+ checkBoxTid = (CheckBox) getActivity().findViewById(R.id.accessRWTidTitle);
+ checkBoxUser = (CheckBox) getActivity().findViewById(R.id.accessRWUserTitle);
+ checkBoxEpc1 = (CheckBox) getActivity().findViewById(R.id.accessRWEpc1);
+
+ if (checkBoxReserve.isChecked() == true) {
+ textViewReserveOk.setText("");
+ accessBank = 0; accOffset = 0; accSize = 4; readWriteTypes = ReadWriteTypes.RESERVE;
+ if (operationRead) {
+ editTextAccessRWKillPwd.setText("");
+ editTextAccessRWAccPwd.setText("");
+ } else {
+ String strValue = editTextAccessRWKillPwd.getText().toString();
+ String strValue1 = editTextAccessRWAccPwd.getText().toString();
+ if (strValue.length() != 8 || strValue1.length() != 8) {
+ invalidRequest1 = true;
+ } else {
+ writeData = strValue + strValue1;
+ }
+ }
+ } else if (checkBoxPc.isChecked() == true || ((checkBoxEpc.isChecked() == true) && (strPCValueRef.length() != 4) )) {
+ textViewPcOk.setText("");
+ accessBank = 1; accOffset = 1; accSize = 1; readWriteTypes = ReadWriteTypes.PC;
+ if (operationRead) {
+ editTextAccPc.setText("");
+ } else {
+ String strValue = editTextAccPc.getText().toString();
+ if (strValue.length() != 4) invalidRequest1 = true;
+ else writeData = strValue;
+ }
+ } else if (checkBoxEpc.isChecked() == true) {
+ textViewEpcOk.setText("");
+ accessBank = 1; accOffset = 1; accSize = 0; readWriteTypes = ReadWriteTypes.EPC;
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("processTickItems(): start EPC operation");
+ if (operationRead) {
+ if (strPCValueRef.length() != 4) accSize = 1;
+ else {
+ accSize = getPC2EpcWordCount(strPCValueRef) + 1;
+ editTextAccessRWEpc.setText("");
+ }
+ } else {
+ String strValue = editTextAccPc.getText().toString();
+ String strValue1 = editTextAccessRWEpc.getText().toString();
+ if (strValue1.length() == 0) {
+ if (strValue.length() != 4) invalidRequest1 = true;
+ else {
+ accSize = 1;
+ writeData = strValue;
+ }
+ } else {
+ accSize += strValue1.length() / 4;
+ if (strValue1.length() % 4 != 0) accSize++;
+ if (strValue.length() == 4) {
+ int iPCWordCount = getPC2EpcWordCount(strValue);
+ if (iPCWordCount < accSize) accSize = iPCWordCount;
+ accSize++;
+ writeData = strValue + strValue1;
+ } else {
+ accOffset = 2;
+ writeData = strValue1;
+ }
+ }
+ }
+ } else if (checkBoxTid.isChecked() == true) {
+ textViewTidOk.setText("");
+ accessBank = 2; accOffset = 0; accSize = 0; readWriteTypes = ReadWriteTypes.TID;
+ EditText editTextTidValue = (EditText) getActivity().findViewById(R.id.accessRWTidValue);
+ if (operationRead) {
+ int iValue = 0;
+ try {
+ EditText editTextTidOffset = (EditText) getActivity().findViewById(R.id.accessRWTidOffset);
+ iValue = Integer.parseInt(editTextTidOffset.getText().toString());
+ } catch (Exception ex) {
+ }
+ accOffset = iValue;
+ iValue = 0;
+ try {
+ EditText editTextTidLength = (EditText) getActivity().findViewById(R.id.accessRWTidLength);
+ iValue = Integer.parseInt(editTextTidLength.getText().toString());
+ } catch (Exception ex) {
+ }
+ accSize = iValue;
+ editTextTidValue.setText("");
+ } else {
+ invalidRequest1 = true;
+ editTextTidValue.setText("");
+
+ }
+ } else if (checkBoxUser.isChecked() == true) {
+ textViewUserOk.setText("");
+ accessBank = 3; accOffset = 0; accSize = 0; readWriteTypes = ReadWriteTypes.USER;
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("processTickItems(): start USER operation");
+ int iValue = 0;
+ try {
+ EditText editTextTidOffset = (EditText) getActivity().findViewById(R.id.accessRWUserOffset);
+ iValue = Integer.parseInt(editTextTidOffset.getText().toString());
+ } catch (Exception ex) {
+ }
+ accOffset = iValue;
+ iValue = 0;
+ try {
+ EditText editTextUserLength = (EditText) getActivity().findViewById(R.id.accessRWUserLength);
+ iValue = Integer.parseInt(editTextUserLength.getText().toString());
+ } catch (Exception ex) {
+ }
+ accSize = iValue;
+ if (operationRead) {
+ editTextUserValue.setText("");
+ } else {
+ String strValue = editTextUserValue.getText().toString();
+ MainActivity.csLibrary4A.appendToLog("strOut: strValue=" + strValue + ", strValue.length=" + strValue.length() + ", accUserValue=" + accUserValue + ", accUserValue.lengt=" + accUserValue.length());
+ if (strValue.length() >= 4 && accUserValue.matches(strValue) == false) {
+ writeData = strValue;
+ }
+ }
+ } else if (checkBoxEpc1.isChecked() == true) {
+ textViewEpc1Ok.setText("");
+ accessBank = spinnerRWSelectEpc1.getSelectedItemPosition(); accOffset = 0; accSize = 0; readWriteTypes = ReadWriteTypes.EPC1;
+ int iValue = 0;
+ try {
+ EditText editTextEpcOffset = (EditText) getActivity().findViewById(R.id.accessRWEpcOffset);
+ iValue = Integer.parseInt(editTextEpcOffset.getText().toString());
+ } catch (Exception ex) {
+ }
+ accOffset = iValue;
+ iValue = 0;
+ try {
+ EditText editTextEpcLength = (EditText) getActivity().findViewById(R.id.accessRWEpcLength);
+ iValue = Integer.parseInt(editTextEpcLength.getText().toString());
+ } catch (Exception ex) {
+ }
+ accSize = iValue;
+ if (operationRead) {
+ editTextEpcValue.setText("");
+ } else {
+ String strValue = editTextEpcValue.getText().toString();
+ if (strValue.length() >= 4 && strValue.matches(accEpcValue) == false) {
+ accSize = strValue.length() / 4;
+ if (strValue.length() %4 != 0) accSize++;
+ writeData = strValue;
+ }
+ }
+ } else {
+ invalidRequest1 = true;
+ bcheckBoxAll = true;
+ }
+
+ if (restartAccessBank == accessBank) {
+ if (restartCounter == 0) invalidRequest1 = true;
+ else restartCounter--;
+ }
+ accWriteData = writeData;
+ return invalidRequest1;
+ }
+}
+
+
+
+package com.csl.cs710ademoapp.fragments;
+
+import android.app.Activity;
+import android.graphics.Typeface;
+import android.os.Bundle;
+import android.os.Handler;
+import android.os.SystemClock;
+import androidx.appcompat.app.AppCompatActivity;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.AdapterView;
+import android.widget.ArrayAdapter;
+import android.widget.Button;
+import android.widget.CheckBox;
+import android.widget.EditText;
+import android.widget.Spinner;
+import android.widget.TableRow;
+import android.widget.TextView;
+import android.widget.Toast;
+
+import com.csl.cs710ademoapp.AccessTask1;
+import com.csl.cs710ademoapp.CustomPopupWindow;
+import com.csl.cs710ademoapp.GenericTextWatcher;
+import com.csl.cs710ademoapp.SelectTag;
+import com.csl.cs710ademoapp.MainActivity;
+import com.csl.cs710ademoapp.R;
+import com.csl.cslibrary4a.ReaderDevice;
+import com.csl.cslibrary4a.RfidReaderChipData;
+
+import static com.csl.cs710ademoapp.MainActivity.mContext;
+import static com.csl.cs710ademoapp.MainActivity.tagSelected;
+
+public class AccessReadWriteUserFragment extends CommonFragment {
+ SelectTag selectTag;
+ Spinner spinnerSelectBank, spinnerRWSelectBank;
+ EditText editTextRWSelectOffset, editTextAccessRWAccPassword, editTextAccessRWKillPwd, editTextAccessRWAccPwd, editTextAccPc, editTextAccessRWEpc;
+ EditText editTextUserValue, editTextEpcValue, editTextaccessRWAntennaPower;
+ TextView textViewEpcLength, textViewRunTime;
+ private Button buttonRead;
+ private Button buttonWrite;
+ Handler mHandler = new Handler();
+ String strPCValueRef = "";
+
+ String accEpcValue = ""; String accUserValue = "";
+ enum ReadWriteTypes {
+ NULL, USER, SBANK
+ }
+ boolean operationRead = false;
+ ReadWriteTypes readWriteTypes;
+
+ private AccessTask1 accessTask;
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ super.onCreateView(inflater, container, savedInstanceState, true);
+ return inflater.inflate(R.layout.fragment_access_readwrite, container, false);
+ }
+
+ @Override
+ public void onActivityCreated(Bundle savedInstanceState) {
+ super.onActivityCreated(savedInstanceState);
+
+ androidx.appcompat.app.ActionBar actionBar;
+ actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
+ actionBar.setIcon(R.drawable.dl_access);
+ actionBar.setTitle(R.string.title_activity_readWriteUser);
+
+ selectTag = new SelectTag((Activity)getActivity(), 0);
+ spinnerSelectBank = (Spinner) getActivity().findViewById(R.id.selectMemoryBank);
+ ArrayAdapter targetAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.read_memoryBank_options, R.layout.custom_spinner_layout);
+ targetAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+ spinnerSelectBank.setAdapter(targetAdapter);
+ spinnerSelectBank.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
+ @Override
+ public void onItemSelected(AdapterView> parent, View view, int position, long id) {
+ switch (position) {
+ case 0: //if EPC
+ if (tagSelected != null) selectTag.editTextTagID.setText(tagSelected.getAddress());
+ editTextRWSelectOffset.setText("32");
+ break;
+ case 1:
+ if (tagSelected != null) { if (tagSelected.getTid() != null) selectTag.editTextTagID.setText(tagSelected.getTid()); }
+ editTextRWSelectOffset.setText("0");
+ break;
+ case 2:
+ if (tagSelected != null) { if (tagSelected.getUser() != null) selectTag.editTextTagID.setText(tagSelected.getUser()); }
+ editTextRWSelectOffset.setText("0");
+ break;
+ default:
+ break;
+ }
+ }
+
+ @Override
+ public void onNothingSelected(AdapterView> parent) {
+
+ }
+ });
+
+ TableRow tableRow = (TableRow) getActivity().findViewById(R.id.accessRWReserveTitleRow);
+ tableRow.setVisibility(View.GONE);
+ tableRow = (TableRow) getActivity().findViewById(R.id.accessRWReserveValueRow);
+ tableRow.setVisibility(View.GONE);
+ tableRow = (TableRow) getActivity().findViewById(R.id.accessRWPcTitleRow);
+ tableRow.setVisibility(View.GONE);
+ tableRow = (TableRow) getActivity().findViewById(R.id.accessRWEpcTitleRow);
+ tableRow.setVisibility(View.GONE);
+ tableRow = (TableRow) getActivity().findViewById(R.id.accessRWTidTitleRow);
+ tableRow.setVisibility(View.GONE);
+ tableRow = (TableRow) getActivity().findViewById(R.id.accessRWTidValueRow);
+ tableRow.setVisibility(View.GONE);
+ tableRow = (TableRow) getActivity().findViewById(R.id.accessRWAnyTitleRow);
+ tableRow.setVisibility(View.GONE);
+ tableRow = (TableRow) getActivity().findViewById(R.id.accessRWAnyValueRow);
+ tableRow.setVisibility(View.GONE);
+
+ editTextRWSelectOffset = (EditText) getActivity().findViewById(R.id.selectMemoryOffset);
+ spinnerRWSelectBank = (Spinner) getActivity().findViewById(R.id.accessRWEpc1Title1);
+ ArrayAdapter targetAdapter1 = ArrayAdapter.createFromResource(getActivity(), R.array.memoryBank_options, R.layout.custom_spinner_layout);
+ targetAdapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+ spinnerRWSelectBank.setAdapter(targetAdapter1); spinnerRWSelectBank.setSelection(1);
+
+ editTextAccessRWAccPassword = (EditText) getActivity().findViewById(R.id.selectPasswordValue);
+ editTextAccessRWAccPassword.addTextChangedListener(new GenericTextWatcher(editTextAccessRWAccPassword, 8));
+ editTextAccessRWAccPassword.setText("00000000");
+ editTextAccessRWKillPwd = (EditText) getActivity().findViewById(R.id.accessRWKillPwdValue);
+ editTextAccessRWKillPwd.addTextChangedListener(new GenericTextWatcher(editTextAccessRWKillPwd, 8));
+ editTextAccessRWAccPwd = (EditText) getActivity().findViewById(R.id.accessRWAccPwdValue);
+ editTextAccessRWAccPwd.addTextChangedListener(new GenericTextWatcher(editTextAccessRWAccPwd, 8));
+ editTextAccPc = (EditText) getActivity().findViewById(R.id.accessRWAccPcValue);
+ editTextAccPc.setHint("PC value");
+ editTextAccPc.addTextChangedListener(new GenericTextWatcher(editTextAccPc, 4));
+ editTextAccessRWEpc = (EditText) getActivity().findViewById(R.id.accessRWAccEpcValue);
+ EditText editTextBlockCount = (EditText) getActivity().findViewById(R.id.accessRWBlockCount);
+ editTextBlockCount.setText("48");
+ EditText editTextUserLength = (EditText) getActivity().findViewById(R.id.accessRWUserLength);
+ editTextUserLength.setText("512");
+ editTextUserValue = (EditText) getActivity().findViewById(R.id.accessRWUserValue); editTextUserValue.setTypeface(Typeface.MONOSPACE);
+ editTextUserValue.setHint("Data Pattern");
+ editTextEpcValue = (EditText) getActivity().findViewById(R.id.accessRWEpcValue);
+ editTextEpcValue.setHint("Data Pattern");
+
+ editTextaccessRWAntennaPower = (EditText) getActivity().findViewById(R.id.selectAntennaPower);
+ editTextaccessRWAntennaPower.setText(String.valueOf(300));
+
+ textViewEpcLength = (TextView) getActivity().findViewById(R.id.accessRWAccEpcLength);
+ textViewRunTime = (TextView) getActivity().findViewById(R.id.accessRWRunTime);
+
+ buttonRead = (Button) getActivity().findViewById(R.id.accessRWReadButton);
+ buttonRead.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (MainActivity.csLibrary4A.isBleConnected() == false) {
+ Toast.makeText(MainActivity.mContext, R.string.toast_ble_not_connected, Toast.LENGTH_SHORT).show();
+ return;
+ } else if (MainActivity.csLibrary4A.isRfidFailure()) {
+ Toast.makeText(MainActivity.mContext, "Rfid is disabled", Toast.LENGTH_SHORT).show();
+ return;
+ }
+ operationRead = true; startAccessTask();
+ }
+ });
+
+ buttonWrite = (Button) getActivity().findViewById(R.id.accessRWWriteButton);
+ buttonWrite.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (MainActivity.csLibrary4A.isBleConnected() == false) {
+ Toast.makeText(MainActivity.mContext, R.string.toast_ble_not_connected, Toast.LENGTH_SHORT).show();
+ return;
+ } else if (MainActivity.csLibrary4A.isRfidFailure()) {
+ Toast.makeText(MainActivity.mContext, "Rfid is disabled", Toast.LENGTH_SHORT).show();
+ return;
+ }
+ operationRead = false; startAccessTask();
+ }
+ });
+
+ ReaderDevice tagSelected = MainActivity.tagSelected;
+ if (tagSelected != null) {
+ if (tagSelected.getSelected() == true) {
+ String strEpcValue = tagSelected.getAddress();
+ String detail = tagSelected.getDetails();
+ String header = "PC=";
+ int index = detail.indexOf(header) + header.length();
+ strPCValueRef = detail.substring(index, index + 4);
+ updatePCEpc(strPCValueRef, strEpcValue);
+ }
+ }
+ MainActivity.csLibrary4A.setSameCheck(true);
+ }
+
+ @Override
+ public void onDestroy() {
+ if (accessTask != null) accessTask.cancel(true);
+ MainActivity.csLibrary4A.setSameCheck(true);
+ MainActivity.csLibrary4A.restoreAfterTagSelect();
+ super.onDestroy();
+ }
+
+ public AccessReadWriteUserFragment() {
+ super("AccessReadWriteUserFragment");
+ }
+
+ int getPC2EpcWordCount(String detail) {
+ String detail2 = detail.substring(0, 1);
+ int number2 = Integer.valueOf(detail2, 16) * 2;
+ String detail3 = detail.substring(1, 2);
+ int number3 = Integer.valueOf(detail3, 16);
+ if ((number3 / 8) != 0) number2 += 1;
+ return number2;
+ }
+ void updatePCEpc(String strPCValue, String strEpcValue) {
+ boolean needPopup = false;
+ if (strPCValue == null) strPCValue = "";
+ if (strPCValue.length() != 0) editTextAccPc.setText(strPCValue);
+ else strPCValue = strPCValueRef;
+ if (strPCValueRef != null && strPCValue != null) {
+ if (strPCValue.matches(strPCValueRef) == false && strPCValue.length() == 4) {
+ needPopup = true;
+ strPCValueRef = strPCValue;
+ }
+ }
+
+ int iWordCount = getPC2EpcWordCount(strPCValue);
+ textViewEpcLength.setText("EPC has " + (iWordCount * 16) + " bits");
+ if (strEpcValue != null) {
+ tagSelected.setAddress(strEpcValue); if (spinnerSelectBank.getSelectedItemPosition() == 0) selectTag.editTextTagID.setText(strEpcValue);
+ editTextAccessRWEpc.setText(strEpcValue);
+ } else {
+ if (iWordCount * 4 < selectTag.editTextTagID.getText().toString().length()) {
+ // needPopup = true;
+ String strTemp = selectTag.editTextTagID.getText().toString().substring(0, iWordCount * 4);
+ tagSelected.setAddress(strEpcValue); if (spinnerSelectBank.getSelectedItemPosition() == 0) selectTag.editTextTagID.setText(strTemp);
+ }
+ if (iWordCount * 4 < editTextAccessRWEpc.getText().toString().length()) {
+ // needPopup = true;
+ String strTemp = editTextAccessRWEpc.getText().toString().substring(0, iWordCount * 4);
+ editTextAccessRWEpc.setText(strTemp);
+ }
+ if (editTextAccessRWEpc.getText().toString().length() != 0) {
+ String strTemp = editTextAccessRWEpc.getText().toString();
+ if (selectTag.editTextTagID.getText().toString().matches(strTemp) == false) {
+ // needPopup = true;
+ tagSelected.setAddress(strEpcValue); if (spinnerSelectBank.getSelectedItemPosition() == 0) selectTag.editTextTagID.setText(strTemp);
+ }
+ }
+ }
+ editTextAccessRWEpc.addTextChangedListener(new GenericTextWatcher(editTextAccessRWEpc, iWordCount * 4));
+ String strTemp = editTextAccessRWEpc.getText().toString();
+ editTextAccessRWEpc.setText(strTemp);
+
+ if (needPopup) {
+ CustomPopupWindow customPopupWindow = new CustomPopupWindow(mContext);
+ customPopupWindow.popupStart("Changing EPC Length will automatically modify to " + (iWordCount * 16) + " bits.", false);
+ }
+ }
+
+ long msStartTime;
+ void startAccessTask() {
+ if (selectTag.editTextTagID.getText().toString().length() == 0) {
+ Toast.makeText(MainActivity.mContext, "Please select tag first !!!", Toast.LENGTH_SHORT).show();
+ return;
+ }
+ CheckBox checkBox = (CheckBox) getActivity().findViewById(R.id.accessRWUserTitle);
+ checkBox.setChecked(true);
+ if (updating == false) {
+ msStartTime = SystemClock.elapsedRealtime();
+ textViewRunTime.setText(""); MainActivity.csLibrary4A.appendToLog("StreamOut: Start of running time");
+ updating = true; bankProcessing = 0; restartAccessBank = -1;
+ mHandler.removeCallbacks(updateRunnable);
+ mHandler.post(updateRunnable);
+ }
+ }
+ boolean updating = false; int bankProcessing = 0;
+ private final Runnable updateRunnable = new Runnable() {
+ @Override
+ public void run() {
+ boolean rerunRequest = true; boolean taskRequest = false;
+ if (processResult()) { rerunRequest = true; }
+ else if (accessTask == null || accessTask.isResultReady()) {
+ bcheckBoxAll = false;
+ boolean invalid = processTickItems();
+ if (bankProcessing == 0 && bcheckBoxAll) rerunRequest = false;
+ else if (bankProcessing++ != 0 && invalid == true) rerunRequest = false;
+ else {
+ if (restartAccessBank != accessBank) {
+ restartAccessBank = accessBank;
+ restartCounter = 3;
+ }
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("AccessReadWriteUserFragment().InventoryRfidTask(): tagID=" + selectTag.editTextTagID.getText() + ", operationrRead=" + operationRead + ", accessBank=" + accessBank + ", accOffset=" + accOffset + ", accSize=" + accSize);
+ int selectOffset = 0;
+ selectOffset = Integer.parseInt(editTextRWSelectOffset.getText().toString());
+ EditText editTextBlockCount = (EditText) getActivity().findViewById(R.id.accessRWBlockCount);
+ Integer accBlockCount = 32;
+ try {
+ accBlockCount = Integer.parseInt(editTextBlockCount.getText().toString());
+ } catch (Exception ex) { }
+ MainActivity.csLibrary4A.appendToLog("strOut: accWriteData=" + accWriteData);
+ accessTask = new AccessTask1(
+ (operationRead ? buttonRead : buttonWrite), invalid,
+ accessBank, accOffset, accSize, accBlockCount, accWriteData,
+ selectTag.editTextTagID.getText().toString(), spinnerSelectBank.getSelectedItemPosition() + 1, selectOffset,
+ editTextAccessRWAccPassword.getText().toString(),
+ Integer.valueOf(editTextaccessRWAntennaPower.getText().toString()),
+ (operationRead ? RfidReaderChipData.HostCommands.CMD_18K6CREAD: RfidReaderChipData.HostCommands.CMD_18K6CWRITE), updateRunnable);
+ accessTask.execute();
+ rerunRequest = true;
+ }
+ }
+ if (rerunRequest) {
+ mHandler.postDelayed(updateRunnable, 100);
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("AccessReadWriteUserFragment().updateRunnable(): Restart");
+ }
+ else {
+ if (bankProcessing == 0 && bcheckBoxAll) {
+ Toast.makeText(MainActivity.mContext, "no choice selected yet", Toast.LENGTH_SHORT).show();
+ }
+ updating = false;
+ }
+ }
+ };
+
+ TextView textViewUserOk, textViewBankOk;
+ CheckBox checkBoxUser, checkBoxBank;
+ int accessBank, accSize, accOffset; String accWriteData;
+ int restartCounter = 0; int restartAccessBank = -1;
+ boolean processResult() {
+ String accessResult = null;
+ if (accessTask == null) return false;
+ if (accessTask.isResultReady() == false) return false;
+ else {
+ long duration = SystemClock.elapsedRealtime() - msStartTime;
+ textViewRunTime.setText(String.format("Run time: %.2f sec", ((float) duration / 1000))); MainActivity.csLibrary4A.appendToLog("StreamOut: End of running time");
+ accessResult = accessTask.getResult();
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("processResult(): accessResult = " + accessResult);
+ if (accessResult == null) {
+ if (readWriteTypes == ReadWriteTypes.USER) {
+ textViewUserOk.setText("E"); checkBoxUser.setChecked(false);
+ }
+ if (readWriteTypes == ReadWriteTypes.SBANK) {
+ textViewBankOk.setText("E"); checkBoxBank.setChecked(false);
+ }
+ } else {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("accessResult = " + accessResult);
+ if (readWriteTypes == ReadWriteTypes.USER) {
+ textViewUserOk.setText("O"); checkBoxUser.setChecked(false);
+ readWriteTypes = ReadWriteTypes.NULL;
+ if (operationRead) {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("AccessReadWrite(). DATA with accessBank = " + accessBank);
+ if (accessTask != null) {
+ int iLength = accessTask.deformatWriteAccessData(accessResult).length();
+ MainActivity.csLibrary4A.appendToLog("endingMessage length=" + iLength);
+ if (iLength < accSize*4) textViewUserOk.setText("H");
+ }
+ editTextUserValue.setText(accessResult);
+ accUserValue = accessResult;
+ } else {
+ accUserValue = editTextUserValue.getText().toString();
+ }
+ } else if (readWriteTypes == ReadWriteTypes.SBANK) {
+ textViewBankOk.setText("O"); checkBoxBank.setChecked(false);
+ readWriteTypes = ReadWriteTypes.NULL;
+ if (accessResult.length() == 0 || operationRead == false) {
+ } else {
+ editTextEpcValue.setText(accessResult);
+ accEpcValue = accessResult;
+ }
+ if (operationRead == false) accEpcValue = editTextEpcValue.getText().toString();
+ }
+ accessResult = null;
+ }
+ accessTask = null;
+ return true;
+ }
+ }
+ boolean bcheckBoxAll = false;
+ boolean processTickItems() {
+ String writeData = "";
+ boolean invalidRequest1 = false;
+
+ textViewUserOk = (TextView) getActivity().findViewById(R.id.accessRWUserOK);
+ textViewBankOk = (TextView) getActivity().findViewById(R.id.accessRWEpc1OK);
+
+ checkBoxUser = (CheckBox) getActivity().findViewById(R.id.accessRWUserTitle);
+ checkBoxBank = (CheckBox) getActivity().findViewById(R.id.accessRWEpc1);
+
+ if (checkBoxUser.isChecked() == true) {
+ textViewUserOk.setText("");
+ accessBank = 3; accOffset = 0; accSize = 0; readWriteTypes = ReadWriteTypes.USER;
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("processTickItems(): start USER operation");
+ int iValue = 0;
+ try {
+ EditText editTextTidOffset = (EditText) getActivity().findViewById(R.id.accessRWUserOffset);
+ iValue = Integer.parseInt(editTextTidOffset.getText().toString());
+ } catch (Exception ex) {
+ }
+ accOffset = iValue;
+ iValue = 0;
+ try {
+ EditText editTextUserLength = (EditText) getActivity().findViewById(R.id.accessRWUserLength);
+ iValue = Integer.parseInt(editTextUserLength.getText().toString());
+ } catch (Exception ex) {
+ }
+ accSize = iValue;
+ if (operationRead) {
+ editTextUserValue.setText("");
+ } else {
+ String strValue = editTextUserValue.getText().toString();
+ MainActivity.csLibrary4A.appendToLog("strOut: strValue=" + strValue + ", strValue.length=" + strValue.length() + ", accUserValue=" + accUserValue + ", accUserValue.lengt=" + accUserValue.length());
+ if (strValue.length() >= 4 && accUserValue.matches(strValue) == false) {
+ writeData = strValue;
+ }
+ }
+ } else if (checkBoxBank.isChecked() == true) {
+ textViewBankOk.setText("");
+ accessBank = spinnerRWSelectBank.getSelectedItemPosition(); accOffset = 0; accSize = 0; readWriteTypes = ReadWriteTypes.SBANK;
+ int iValue = 0;
+ try {
+ EditText editTextEpcOffset = (EditText) getActivity().findViewById(R.id.accessRWEpcOffset);
+ iValue = Integer.parseInt(editTextEpcOffset.getText().toString());
+ } catch (Exception ex) {
+ }
+ accOffset = iValue;
+ iValue = 0;
+ try {
+ EditText editTextEpcLength = (EditText) getActivity().findViewById(R.id.accessRWEpcLength);
+ iValue = Integer.parseInt(editTextEpcLength.getText().toString());
+ } catch (Exception ex) {
+ }
+ accSize = iValue;
+ if (operationRead) {
+ editTextEpcValue.setText("");
+ } else {
+ String strValue = editTextEpcValue.getText().toString();
+ if (strValue.length() >= 4 && strValue.matches(accEpcValue) == false) {
+ accSize = strValue.length() / 4;
+ if (strValue.length() %4 != 0) accSize++;
+ writeData = strValue;
+ }
+ }
+ } else {
+ invalidRequest1 = true;
+ bcheckBoxAll = true;
+ }
+
+ if (restartAccessBank == accessBank) {
+ if (restartCounter == 0) invalidRequest1 = true;
+ else restartCounter--;
+ }
+ accWriteData = writeData;
+ return invalidRequest1;
+ }
+}
+
+
+
+package com.csl.cs710ademoapp.fragments;
+
+import static com.csl.cs710ademoapp.MainActivity.mContext;
+
+import android.graphics.Color;
+import android.os.AsyncTask;
+import android.os.Bundle;
+import androidx.appcompat.app.ActionBar;
+import androidx.appcompat.app.AppCompatActivity;
+import android.text.Editable;
+import android.text.TextWatcher;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.AdapterView;
+import android.widget.ArrayAdapter;
+import android.widget.Button;
+import android.widget.CheckBox;
+import android.widget.CompoundButton;
+import android.widget.EditText;
+import android.widget.Spinner;
+import android.widget.TableRow;
+import android.widget.TextView;
+import android.widget.Toast;
+
+import com.csl.cs710ademoapp.AccessTask;
+import com.csl.cs710ademoapp.CustomPopupWindow;
+import com.csl.cs710ademoapp.InventoryBarcodeTask;
+import com.csl.cs710ademoapp.InventoryRfidTask;
+import com.csl.cs710ademoapp.MainActivity;
+import com.csl.cs710ademoapp.R;
+import com.csl.cslibrary4a.NotificationConnector;
+import com.csl.cslibrary4a.ReaderDevice;
+import com.csl.cslibrary4a.RfidReaderChipData;
+import com.csl.cslibrary4a.Utility;
+
+import java.util.ArrayList;
+
+public class AccessRegisterFragment extends CommonFragment {
+ CustomPopupWindow customPopupWindow;
+
+ TableRow tableRowSelectMask, tableRowSelectBank;
+ Spinner spinnerSelectBank, spinnerAccessBank, spinnerWriteEpcClass, spinnerWriteDataType;
+ EditText editTextSelectMask, editTextSelectPopulation, editTextPassword, editTextAntennaPower, editTextWriteData, editTextWriteLength;
+ CheckBox checkBoxWriteLengthEnable;
+ TextView textViewSelectedTags, textViewWriteCount, textViewRunTime, textViewTagGot, textViewVoltageLevel;
+ TextView textViewYield, textViewTotal;
+ Button buttonSelect, buttonClearSelect, buttonReadBar, buttonWrite;
+
+ InventoryRfidTask inventoryRfidTask;
+ InventoryBarcodeTask inventoryBarcodeTask;
+ AccessTask accessTask;
+
+ ReaderDevice tagSelected = MainActivity.tagSelected;
+ boolean newWriteData;
+ String writeValueOld = "";
+ int iAutoRun = 0;
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ super.onCreateView(inflater, container, savedInstanceState, true);
+ return inflater.inflate(R.layout.fragment_access_register, container, false);
+ }
+
+ @Override
+ public void onActivityCreated(Bundle savedInstanceState) {
+ super.onActivityCreated(savedInstanceState);
+
+ ActionBar actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
+ actionBar.setIcon(R.drawable.dl_access);
+ actionBar.setTitle(R.string.title_activity_registertag);
+
+ customPopupWindow = new CustomPopupWindow(mContext);
+
+ tableRowSelectMask = (TableRow) getActivity().findViewById(R.id.registerSelectMaskRow);
+ tableRowSelectBank = (TableRow) getActivity().findViewById(R.id.registerSelectBankRow);
+
+ spinnerSelectBank = (Spinner) getActivity().findViewById(R.id.registerSelectBank);
+ ArrayAdapter targetAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.read_memoryBank_options, R.layout.custom_spinner_layout);
+ targetAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+ spinnerSelectBank.setAdapter(targetAdapter);
+ spinnerSelectBank.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
+ @Override
+ public void onItemSelected(AdapterView> parent, View view, int position, long id) {
+ switch (position) {
+ case 0: //if EPC
+ if (tagSelected != null) editTextSelectMask.setText(tagSelected.getAddress());
+ break;
+ case 1:
+ if (tagSelected != null) { if (tagSelected.getTid() != null) editTextSelectMask.setText(tagSelected.getTid()); }
+ break;
+ case 2:
+ if (tagSelected != null) { if (tagSelected.getUser() != null) editTextSelectMask.setText(tagSelected.getUser()); }
+ break;
+ default:
+ break;
+ }
+ }
+
+ @Override
+ public void onNothingSelected(AdapterView> parent) {
+
+ }
+ });
+
+ spinnerAccessBank = (Spinner) getActivity().findViewById(R.id.registerAccessBank);
+ targetAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.write_memoryBank_options, R.layout.custom_spinner_layout);
+ targetAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+ spinnerAccessBank.setAdapter(targetAdapter);
+
+ spinnerWriteEpcClass = (Spinner) getActivity().findViewById(R.id.registerWriteEpcClass);
+ targetAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.write_Epc_options, R.layout.custom_spinner_layout);
+ targetAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+ spinnerWriteEpcClass.setAdapter(targetAdapter);
+ spinnerWriteEpcClass.setEnabled(false);
+
+ spinnerWriteDataType = (Spinner) getActivity().findViewById(R.id.registerWriteDataType);
+ targetAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.write_data_options, R.layout.custom_spinner_layout);
+ targetAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+ spinnerWriteDataType.setAdapter(targetAdapter);
+
+ Button buttonConfirm = (Button) getActivity().findViewById(R.id.registerConfirm2Button);
+ buttonConfirm.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View view) {
+ Toast.makeText(MainActivity.mContext, "Step 2 data is confirmed.", Toast.LENGTH_SHORT).show();
+ }
+ });
+
+ editTextSelectMask = (EditText) getActivity().findViewById(R.id.registerSelectMask);
+ editTextSelectPopulation = (EditText) getActivity().findViewById(R.id.registerSelectPopulation);
+ editTextPassword = (EditText) getActivity().findViewById(R.id.registerPassword);
+ editTextPassword.setText("00000000");
+ editTextAntennaPower = (EditText) getActivity().findViewById(R.id.registerAntennaPower);
+ editTextWriteData = (EditText) getActivity().findViewById(R.id.registerWriteData);
+ editTextWriteData.setEnabled(true);
+// editTextBarValue.setText("19dec163");
+ newWriteData = false; editTextWriteData.setTextColor(Color.RED);
+ editTextWriteData.addTextChangedListener(new TextWatcher() {
+ @Override
+ public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { }
+
+ @Override
+ public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { }
+
+ @Override
+ public void afterTextChanged(Editable editable) {
+ String writeValue = editTextWriteData.getText().toString().trim();
+ if (true) newWriteData = true;
+ if (writeValue.matches(writeValueOld) == false) {
+ writeValueOld = writeValue;
+ editTextWriteData.setTextColor(Color.BLACK);
+ //checkBoxNewValue.setEnabled(true);
+ //checkBoxNewValue.setText("Reset to old value");
+ newWriteData = true;
+ }
+
+ if (inventoryBarcodeTask != null) {
+ if (inventoryBarcodeTask.getStatus() == AsyncTask.Status.RUNNING) {
+ barcodeReadDone = true; MainActivity.csLibrary4A.appendToLog("barcodeReadDone = true in textChanged");
+ MainActivity.csLibrary4A.appendToLog("going to startStopBarcodeHandler 1"); startStopBarcodeHandler(false);
+ }
+ }
+ if (checkBoxWriteLengthEnable.isChecked() == false) {
+ int length1 = writeValue.length() * 4;
+ int length = length1 / 16;
+ if (length * 16 != length1) length++;
+ editTextWriteLength.setText(String.valueOf(length));
+ }
+ }
+ });
+ editTextWriteLength = (EditText) getActivity().findViewById(R.id.registerWriteLength);
+
+ checkBoxWriteLengthEnable = (CheckBox) getActivity().findViewById(R.id.registerWriteLengthEnable);
+ checkBoxWriteLengthEnable.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
+ @Override
+ public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
+ if (isChecked) editTextWriteLength.setEnabled(true);
+ else editTextWriteLength.setEnabled(false);
+ }
+ });
+
+ buttonClearSelect = (Button) getActivity().findViewById(R.id.registerClearSelectButton);
+ buttonClearSelect.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View view) {
+ tagSelected = null;
+ editTextSelectMask.setText("");
+ }
+ });
+
+ buttonSelect = (Button) getActivity().findViewById(R.id.registerSelectButton);
+ buttonSelect.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View view) {
+ if (buttonSelect.getText().toString().contains("Clear")) {
+ buttonClearSelect.setVisibility(View.VISIBLE);
+ tableRowSelectMask.setVisibility(View.VISIBLE);
+ tableRowSelectBank.setVisibility(View.VISIBLE);
+ textViewSelectedTags.setText("");
+ buttonSelect.setText("Read");
+ } else if (buttonSelect.getText().toString().contains("Stop")) {
+ inventoryRfidTask.taskCancelReason = InventoryRfidTask.TaskCancelRReason.BUTTON_RELEASE;
+ mHandler.removeCallbacks(runnableSelect);
+ textViewSelectedTags.setText("");
+ for (int i = 0; i < epcArrayList.size(); i++) {
+ MainActivity.csLibrary4A.appendToLog("epcArrayList.get[" + i + "] = " + epcArrayList.get(i));
+ textViewSelectedTags.append(epcArrayList.get(i) + "\n");
+ }
+ if (textViewSelectedTags.getText().toString().trim().length() == 0) {
+ buttonSelect.setText("Read");
+ } else {
+ buttonClearSelect.setVisibility(View.GONE);
+ tableRowSelectMask.setVisibility(View.GONE);
+ tableRowSelectBank.setVisibility(View.GONE);
+ buttonSelect.setText("Clear");
+ }
+ }
+ else {
+ textViewSelectedTags.setText("");
+ String strTagId = editTextSelectMask.getText().toString();
+ int selectBank = spinnerSelectBank.getSelectedItemPosition() + 1;
+ long pwrlevel = Integer.parseInt(editTextAntennaPower.getText().toString());
+ MainActivity.csLibrary4A.setTagRead(0);
+ MainActivity.csLibrary4A.setSelectedTag(strTagId, selectBank, pwrlevel);
+ MainActivity.csLibrary4A.appendToLog("Debug_Compact: AccessRegisterFragment.onActivityCreated.onClick");
+ MainActivity.csLibrary4A.startOperation(RfidReaderChipData.OperationTypes.TAG_INVENTORY);
+ inventoryRfidTask = new InventoryRfidTask();
+ inventoryRfidTask.execute();
+ MainActivity.sharedObjects.serviceArrayList.clear(); epcArrayList.clear();
+ mHandler.post(runnableSelect); buttonSelect.setText("Stop");
+ }
+ }
+ });
+
+ Button buttonConvert = (Button) getActivity().findViewById(R.id.registerWriteConvert);
+ buttonConvert.setOnClickListener(new View.OnClickListener() {
+ EditText editTextWriteEpcFilter = (EditText) getActivity().findViewById(R.id.registerWriteEpcFilter);
+ EditText editTextWriteEpcCompanyPrefix = (EditText) getActivity().findViewById(R.id.registerWriteEpcCompanyPrefix);
+ EditText editTextWriteEpcItemReference = (EditText) getActivity().findViewById(R.id.registerWriteEpcItemReference);
+ EditText editTextWriteEpcSerial = (EditText) getActivity().findViewById(R.id.registerWriteEpcSerial);
+ @Override
+ public void onClick(View view) {
+ String strValue = MainActivity.csLibrary4A.getEpc4upcSerial(
+ Utility.EpcClass.values()[spinnerWriteEpcClass.getSelectedItemPosition()],
+ editTextWriteEpcFilter.getText().toString(),
+ editTextWriteEpcCompanyPrefix.getText().toString(),
+ editTextWriteEpcItemReference.getText().toString(),
+ editTextWriteEpcSerial.getText().toString()
+ );
+ if (strValue != null) editTextWriteData.setText(strValue);
+ }
+ });
+
+ buttonReadBar = (Button) getActivity().findViewById(R.id.registerReadBarButton);
+ buttonReadBar.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View view) {
+ MainActivity.csLibrary4A.appendToLog("going to startStopBarcodeHandler 2"); startStopBarcodeHandler(false);
+ }
+ });
+
+ textViewSelectedTags = (TextView) getActivity().findViewById(R.id.registerSelectedTags);
+ //textViewWriteCount = (TextView) getActivity().findViewById(R.id.registerWrittenCount);
+ textViewRunTime = (TextView) getActivity().findViewById(R.id.registerRunTime);
+ textViewTagGot = (TextView) getActivity().findViewById(R.id.registetTagGotView);
+ textViewVoltageLevel = (TextView) getActivity().findViewById(R.id.registerVoltageLevel);
+
+ buttonWrite = (Button) getActivity().findViewById(R.id.registerWriteButton);
+ buttonWrite.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View view) {
+ if (buttonWrite.getText().toString().trim().length() == 0) return;
+ runningAuto123 = 0; startStopAccessHandler(false);
+ }
+ });
+
+ Button buttonWrite3 = (Button) getActivity().findViewById(R.id.registerWrite3Button);
+ buttonWrite3.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View view) {
+ if (accessTask != null) if (accessTask.getStatus() == AsyncTask.Status.RUNNING) return;
+ runningAuto123 = 0; startStopAccessHandler(false);
+ }
+ });
+
+ Button buttonAuto = (Button) getActivity().findViewById(R.id.registerAutoButton);
+ buttonAuto.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View view) {
+ if (accessTask != null) if (accessTask.getStatus() == AsyncTask.Status.RUNNING) return;
+ runningAuto123 = 1; startStopAccessHandler(false);
+ }
+ });
+
+ Button buttonAuto123 = (Button) getActivity().findViewById(R.id.registerAutoButtonWBarcodeRead);
+ buttonAuto123.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View view) {
+ if (accessTask != null) if (accessTask.getStatus() == AsyncTask.Status.RUNNING) return;
+ runningAuto123 = 2; mHandler.post(runnableAuto123);
+ }
+ });
+
+ textViewYield = (TextView) getActivity().findViewById(R.id.registerYieldView);
+ textViewTotal = (TextView) getActivity().findViewById(R.id.registerTotalView);
+
+ Button buttonResetCount = (Button) getActivity().findViewById(R.id.registerResetCountButton);
+ buttonResetCount.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View view) {
+ resetCount = true;
+ textViewRunTime.setText(""); textViewTagGot.setText(""); textViewVoltageLevel.setText("");
+ textViewYield.setText(""); textViewTotal.setText("");
+ }
+ });
+
+ MainActivity.csLibrary4A.setSameCheck(false);
+ }
+
+ @Override
+ public void onResume() {
+ super.onResume();
+ setNotificationListener();
+ }
+
+ @Override
+ public void onPause() {
+ MainActivity.csLibrary4A.setNotificationListener(null);
+ super.onPause();
+ }
+
+ @Override
+ public void onDestroy() {
+ MainActivity.csLibrary4A.setNotificationListener(null);
+ mHandler.removeCallbacks(runnableSelect);
+ mHandler.removeCallbacks(runnableAuto123);
+ if (inventoryBarcodeTask != null) inventoryBarcodeTask.taskCancelReason = InventoryBarcodeTask.TaskCancelRReason.DESTORY;
+ if (accessTask != null) accessTask.taskCancelReason = AccessTask.TaskCancelRReason.DESTORY;
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("AcccessRegisterFragment().onDestory(): onDestory()");
+ MainActivity.csLibrary4A.setSameCheck(true);
+ MainActivity.csLibrary4A.restoreAfterTagSelect();
+ super.onDestroy();
+ }
+
+ public AccessRegisterFragment() {
+ super("AccessRegisterFragment");
+ }
+
+ void setNotificationListener() {
+ MainActivity.csLibrary4A.setNotificationListener(new NotificationConnector.NotificationListener() {
+ @Override
+ public void onChange() {
+ MainActivity.csLibrary4A.appendToLog("TRIGGER key is pressed.");
+ if (barcodeReadRequesting) {
+ if (customPopupWindow.popupWindow.isShowing()) {
+ customPopupWindow.popupWindow.dismiss();
+ barcodeReadRequesting = false; MainActivity.csLibrary4A.appendToLog("barcodeReadRequesting = false");
+ ready2nextRun = true; MainActivity.csLibrary4A.appendToLog("ready2nextRun 1 = true after popup");
+ }
+ }
+ }
+ });
+ }
+
+ ArrayList epcArrayList = new ArrayList();
+ Runnable runnableSelect = new Runnable() {
+ @Override
+ public void run() {
+ while (MainActivity.sharedObjects.serviceArrayList.size() != 0) {
+ String strEpc = MainActivity.sharedObjects.serviceArrayList.get(0); MainActivity.sharedObjects.serviceArrayList.remove(0);
+ MainActivity.csLibrary4A.appendToLog("epcArrayList.add[" + epcArrayList.size() + "] = " + strEpc);
+ boolean matched = false;
+ for (int i = 0; i < epcArrayList.size(); i++) {
+ if (epcArrayList.get(i).matches(strEpc)) {
+ matched = true;
+ break;
+ }
+ }
+ if (matched == false && strEpc != null) {
+ epcArrayList.add(strEpc);
+ }
+ }
+ textViewSelectedTags.setText("unique tag number = " + epcArrayList.size());
+ mHandler.postDelayed(runnableSelect, 1000);
+ }
+ };
+
+ boolean ready2nextRun = true, barcodeReadRequesting = false, barcodeReadDone = false;
+ boolean runningAccessTask = false; int runningAuto123 = 0, totalTag = 0;
+ Runnable runnableAuto123 = new Runnable() {
+ @Override
+ public void run() {
+ boolean running = false;
+ MainActivity.csLibrary4A.appendToLog("found barcodeReadRequesting as " + barcodeReadRequesting );
+ if (barcodeReadRequesting) {
+ if (customPopupWindow.popupWindow.isShowing()) running = true;
+ else {
+ barcodeReadRequesting = false; MainActivity.csLibrary4A.appendToLog("barcodeReadRequesting = false");
+ ready2nextRun = true; MainActivity.csLibrary4A.appendToLog("ready2nextRun 1 = true after popup");
+ }
+ }
+ MainActivity.csLibrary4A.appendToLog("runnableAuto123: runningAuto123 = " + runningAuto123 + ", inventoryBarcodeTask = " + (inventoryBarcodeTask != null ? "valid" : "null"));
+ if (runningAuto123 == 2 && inventoryBarcodeTask != null) { if (inventoryBarcodeTask.getStatus() == AsyncTask.Status.RUNNING) running = true; }
+ MainActivity.csLibrary4A.appendToLog("runnableAuto123: accessTask = " + (accessTask != null ? "valid" : "null"));
+ if (accessTask != null) { if (accessTask.getStatus() == AsyncTask.Status.RUNNING) running = true; }
+ MainActivity.csLibrary4A.appendToLog("runnableAuto123: running = " + running);
+ if (running == false) {
+ int totalTagNew = getTotalTag();
+ if (runningAccessTask) {
+ if (totalTagNew > totalTag) {
+ if (spinnerWriteDataType.getSelectedItemPosition() == 2) editTextWriteData.setText(incrementString(editTextWriteData.getText().toString()));
+ } else runningAuto123 = 0;
+ }
+ MainActivity.csLibrary4A.appendToLog("runnableAuto123: totalTagNew = " + totalTagNew + ", totalTag = " + totalTag + ", runningAuto123 = " + runningAuto123 + ", runningAccessTask = " + runningAccessTask);
+ runningAccessTask = false;
+
+ boolean bcontinue = true;
+ if (spinnerWriteDataType.getSelectedItemPosition() == 1 && ready2nextRun == false) {
+ if (buttonSelect.getText().toString().contains("Clear")) {
+ if (textViewSelectedTags.getText().toString().trim().length() == 0) bcontinue = false;
+ }
+ if (bcontinue) {
+ customPopupWindow.popupStart("Next barcode.", false);
+ barcodeReadRequesting = true; MainActivity.csLibrary4A.appendToLog("barcodeReadRequesting = true");
+ barcodeReadDone = false; MainActivity.csLibrary4A.appendToLog("barcodeReadDone = false as popup");
+ bcontinue = false;
+ running = true;
+ }
+ }
+ if (bcontinue) {
+ if (ready2nextRun == false) {
+ if (buttonSelect.getText().toString().contains("Clear")) {
+ if (textViewSelectedTags.getText().toString().trim().length() != 0) {
+ ready2nextRun = true; MainActivity.csLibrary4A.appendToLog("ready2nextRun = true as valid selected tag in textview");
+ }
+ } else {
+ ready2nextRun = true; MainActivity.csLibrary4A.appendToLog("ready2nextRun = true as not clear");
+ }
+ }
+ if (ready2nextRun) {
+ if (startStopAccessHandler(false)) running = true;
+ }
+ }
+ }
+ if (running && runningAuto123 == 2) mHandler.postDelayed(runnableAuto123, 250);
+ else {
+ ready2nextRun = true; MainActivity.csLibrary4A.appendToLog("ready2nextRun = true at the runnable end");
+ barcodeReadRequesting = false; barcodeReadDone = false; MainActivity.csLibrary4A.appendToLog("barcodeReadDone = false at the runnable end");
+ }
+ }
+ };
+
+ String incrementString(String string1) {
+ for (int i = 0; i < string1.length(); i++) {
+ String string2 = string1.substring(string1.length() - 1 - i, string1.length() - i);
+ Integer iValue = Integer.valueOf(string2, 16);
+ if (++iValue >= 16) iValue = 0;
+ String stringA = string1.substring(0, string1.length() - 1 - i);
+ String stringB = String.format("%X", iValue);
+ String stringC = null;
+ if (i > 0) stringC = string1.substring(string1.length() - i, string1.length());
+ MainActivity.csLibrary4A.appendToLog("stringABC = " + stringA + "," + stringB + "," + stringC);
+ String stringABC = (stringA != null ? stringA : "") + stringB + (stringC != null ? stringC : "");
+ string1 = stringABC;
+ if (iValue != 0) break;
+ }
+ return string1;
+ }
+
+ int getTotalTag() {
+ int iValue = 0;
+ String stringTotal = textViewTotal.getText().toString();
+ String stringTotalTag = stringTotal.replaceAll("[^0-9.]", "");
+ try {
+ iValue = Integer.parseInt(stringTotalTag);
+ } catch (Exception ex) {
+ }
+ MainActivity.csLibrary4A.appendToLog("totalTag = " + iValue);
+ return iValue;
+ }
+
+ void startStopBarcodeHandler(boolean buttonTrigger) {
+ if (MainActivity.sharedObjects.runningInventoryRfidTask) {
+ Toast.makeText(MainActivity.mContext, "Running RFID access", Toast.LENGTH_SHORT).show();
+ return;
+ }
+
+ boolean started = false;
+ if (inventoryBarcodeTask != null) if (inventoryBarcodeTask.getStatus() == AsyncTask.Status.RUNNING) started = true;
+ if (buttonTrigger && ((started && MainActivity.csLibrary4A.getTriggerButtonStatus()) || (started == false && MainActivity.csLibrary4A.getTriggerButtonStatus() == false))) return;
+ if (started == false) {
+ if (MainActivity.csLibrary4A.isBleConnected() == false) {
+ Toast.makeText(MainActivity.mContext, R.string.toast_ble_not_connected, Toast.LENGTH_SHORT).show();
+ return;
+ }
+ if (MainActivity.csLibrary4A.isBarcodeFailure()) {
+ MainActivity.csLibrary4A.appendToLog("Toasted 'Barcode is disable'");
+ Toast.makeText(MainActivity.mContext, "Barcode is disabled", Toast.LENGTH_SHORT).show();
+ return;
+ }
+ boolean noToast = true; //runningAuto123;
+ inventoryBarcodeTask = new InventoryBarcodeTask(null, null, editTextWriteData, null, null, null, buttonReadBar, buttonWrite, null, noToast);
+ inventoryBarcodeTask.execute();
+ } else inventoryBarcodeTask.taskCancelReason = InventoryBarcodeTask.TaskCancelRReason.STOP;
+ }
+
+ boolean startStopAccessHandler(boolean buttonTrigger) {
+ boolean runningBarcode = false;
+ if (inventoryBarcodeTask != null) {
+ if (inventoryBarcodeTask.getStatus() == AsyncTask.Status.RUNNING) {
+ MainActivity.csLibrary4A.appendToLog("going to startStopBarcodeHandler 1"); startStopBarcodeHandler(buttonTrigger);
+ runningBarcode = true;
+ }
+ }
+
+ boolean runningAccessTask = false;
+ if (accessTask != null) { if (accessTask.getStatus() == AsyncTask.Status.RUNNING) runningAccessTask = true; }
+ if (buttonTrigger && ((runningAccessTask && MainActivity.csLibrary4A.getTriggerButtonStatus()) || (runningAccessTask == false && MainActivity.csLibrary4A.getTriggerButtonStatus() == false))) {
+ return true;
+ }
+
+ boolean validResult = true;
+ if (runningBarcode) { }
+ else if (runningAccessTask) {
+ if (buttonTrigger) accessTask.taskCancelReason = AccessTask.TaskCancelRReason.BUTTON_RELEASE;
+ else accessTask.taskCancelReason = AccessTask.TaskCancelRReason.STOP;
+ } else {
+ if (MainActivity.csLibrary4A.isBleConnected() == false) {
+ Toast.makeText(MainActivity.mContext, R.string.toast_ble_not_connected, Toast.LENGTH_SHORT).show();
+ validResult = false;
+ } else if (MainActivity.csLibrary4A.isRfidFailure()) {
+ Toast.makeText(MainActivity.mContext, "Rfid is disabled", Toast.LENGTH_SHORT).show();
+ validResult = false;
+ } else if (MainActivity.csLibrary4A.mrfidToWriteSize() != 0) {
+ Toast.makeText(MainActivity.mContext, R.string.toast_not_ready, Toast.LENGTH_SHORT).show();
+ validResult = false;
+ }
+
+ if (validResult) {
+ if (barcodeReadDone == false && spinnerWriteDataType.getSelectedItemPosition() == 1) {
+ MainActivity.csLibrary4A.appendToLog("going to startStopBarcodeHandler 2");
+ startStopBarcodeHandler(buttonTrigger);
+ } else {
+ totalTag = getTotalTag();
+ if (startAccessTask()) validResult = false;
+ else if (runningAuto123 == 2) this.runningAccessTask = true;
+ MainActivity.csLibrary4A.appendToLog("runningAccessTask = " + this.runningAccessTask);
+ resetOldValue();
+ ready2nextRun = false;
+ MainActivity.csLibrary4A.appendToLog("ready2nextRun = false after startStopAccessHandler");
+ }
+ }
+ }
+ return validResult;
+ }
+
+ void resetOldValue() {
+ editTextWriteData.setTextColor(Color.RED);
+ /*checkBoxNewValue.setEnabled(false);
+ checkBoxNewValue.setText("Old value");
+ checkBoxNewValue.setChecked(false);*/
+ newWriteData = false;
+ }
+
+ boolean resetCount = true;
+ boolean startAccessTask() {
+ boolean invalidRequest1 = false;
+
+ int selectQValue = -1, selectPopulation = -1;
+ try {
+ selectPopulation = Integer.parseInt(editTextSelectPopulation.getText().toString());
+ } catch (Exception ex) { }
+ if (selectPopulation < 0) invalidRequest1 = true;
+ else if (selectPopulation <= getTotalTag()) invalidRequest1 = true;
+ else {
+ selectQValue = MainActivity.csLibrary4A.getPopulation2Q(selectPopulation);
+ if (selectQValue < 0) invalidRequest1 = true;
+ }
+ MainActivity.csLibrary4A.appendToLog("selectQValue = " + selectQValue + ", selectPopulation = " + selectPopulation);
+
+ String selectMask = "";
+ int selectBank1 = -1;
+ int selectOffset1 = -1;
+ if (buttonSelect.getText().toString().contains("Clear")) {
+ String[] stringSplited = textViewSelectedTags.getText().toString().split("\n", 2);
+ if (stringSplited != null && stringSplited.length > 0 && stringSplited[0] != null && stringSplited[0].trim().length() != 0) {
+ selectMask = stringSplited[0].trim();
+ selectBank1 = 1;
+ selectOffset1 = 32;
+ if (stringSplited.length > 1 && stringSplited[1] != null && stringSplited[1].trim().length() != 0) textViewSelectedTags.setText(stringSplited[1].trim());
+ else textViewSelectedTags.setText("");
+ }
+ } else {
+ selectMask = editTextSelectMask.getText().toString().trim();
+ int selectBankPosition = spinnerSelectBank.getSelectedItemPosition();
+ selectBank1 = selectBankPosition + 1;
+ int selectOffset = 0;
+ try {
+ EditText editTextSelectOffset = (EditText) getActivity().findViewById(R.id.registerSelectOffset);
+ selectOffset = Integer.parseInt(editTextSelectOffset.getText().toString());
+ } catch (Exception ex) { }
+ selectOffset1 = selectBankPosition == 0 ? selectOffset + 32 : selectOffset;
+ }
+ if (selectMask.trim().length() == 0 || selectBank1 < 0 || selectOffset1 < 0) {
+ invalidRequest1 = true;
+ }
+
+ String password = editTextPassword.getText().toString();
+ if (password.length() != 8) invalidRequest1 = true;
+
+ int antennaPower = -1;
+ try {
+ editTextAntennaPower = (EditText) getActivity().findViewById(R.id.registerAntennaPower);
+ antennaPower = Integer.parseInt(editTextAntennaPower.getText().toString());
+ } catch (Exception ex) { }
+ if (antennaPower < 0) invalidRequest1 = true;
+
+ int accessBank = spinnerAccessBank.getSelectedItemPosition() == 0 ? 1 : 3;
+ MainActivity.csLibrary4A.appendToLog("accessBank = " + accessBank);
+ if (invalidRequest1 == false) {
+ if (MainActivity.csLibrary4A.setAccessBank(accessBank) == false) invalidRequest1 = true;
+ }
+
+ int writeOffset = -1;
+ try {
+ EditText editTextWriteOffset = (EditText) getActivity().findViewById(R.id.registerWriteOffset);
+ writeOffset = Integer.parseInt(editTextWriteOffset.getText().toString());
+ if (spinnerAccessBank.getSelectedItemPosition() == 0) writeOffset += 2;
+ } catch (Exception ex) { }
+ if (writeOffset < 0) invalidRequest1 = true;
+ MainActivity.csLibrary4A.appendToLog("writeOffset = " + writeOffset);
+ if (invalidRequest1 == false) {
+ if (MainActivity.csLibrary4A.setAccessOffset(writeOffset) == false) invalidRequest1 = true;
+ }
+
+ int writeLength = -1;
+ try {
+ writeLength = Integer.parseInt(editTextWriteLength.getText().toString());
+ } catch (Exception ex) { }
+ if (writeLength < 0) invalidRequest1 = true;
+ MainActivity.csLibrary4A.appendToLog("writeLength = " + writeLength);
+ if (invalidRequest1 == false) {
+ if (writeLength == 0) invalidRequest1 = true;
+ else if (MainActivity.csLibrary4A.setAccessCount(writeLength) == false) {
+ invalidRequest1 = true;
+ }
+ }
+
+ String writeData = editTextWriteData.getText().toString().trim();
+ if (writeData.length() == 0) invalidRequest1 = true;
+ MainActivity.csLibrary4A.appendToLog("writeData = " + writeData);
+ if (invalidRequest1 == false) {
+ if (MainActivity.csLibrary4A.setAccessWriteData(writeData) == false) {
+ invalidRequest1 = true;
+ }
+ }
+
+ int repeatCount = 0;
+ if (runningAuto123 == 1) repeatCount = selectPopulation;
+
+ MainActivity.csLibrary4A.appendToLog("invalidRequest1 = " + invalidRequest1
+ + ", selectMask = " + selectMask + ", selectBank1 = " + selectBank1 + ", selectOffset1 = " + selectOffset1
+ + ", password = " + password + ", power = " + antennaPower + ", repeatCount = " + repeatCount + ", resetCount = " + resetCount);
+ accessTask = new AccessTask(buttonWrite, textViewWriteCount, invalidRequest1, true,
+ selectMask, selectBank1, selectOffset1,
+ password, antennaPower, RfidReaderChipData.HostCommands.CMD_18K6CWRITE,
+ selectQValue, repeatCount, resetCount, false,
+ textViewRunTime, textViewTagGot, textViewVoltageLevel, textViewYield, textViewTotal);
+ accessTask.execute();
+ resetCount = false;
+ return invalidRequest1;
+ }
+}
+
+
+
+package com.csl.cs710ademoapp.fragments;
+
+import android.os.Bundle;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+
+import androidx.appcompat.app.ActionBar;
+import androidx.appcompat.app.AppCompatActivity;
+import androidx.viewpager.widget.ViewPager;
+
+import com.csl.cs710ademoapp.MainActivity;
+import com.csl.cs710ademoapp.R;
+import com.csl.cslibrary4a.AdapterTab;
+import com.google.android.material.tabs.TabLayout;
+
+public class AccessSecurityFragment extends CommonFragment {
+ private ActionBar actionBar;
+ private ViewPager viewPager;
+ AdapterTab adapter;
+
+ private String[] tabs = {"Lock", "Kill"};
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ super.onCreateView(inflater, container, savedInstanceState, true);
+ return inflater.inflate(R.layout.custom_tabbed_layout, container, false);
+ }
+
+ @Override
+ public void onActivityCreated(Bundle savedInstanceState) {
+ super.onActivityCreated(savedInstanceState);
+
+ actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
+ actionBar.setIcon(R.drawable.dl_access);
+ actionBar.setTitle(R.string.title_activity_security);
+
+ TabLayout tabLayout = (TabLayout) getActivity().findViewById(R.id.OperationsTabLayout);
+
+ adapter = new AdapterTab(getActivity().getSupportFragmentManager(), tabs.length);
+ adapter.setFragment(0, new AccessSecurityLockFragment());
+ adapter.setFragment(1, new AccessSecurityKillFragment());
+
+ viewPager = (ViewPager) getActivity().findViewById(R.id.OperationsPager);
+ viewPager.setAdapter(adapter);
+ viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
+
+ for (String tab_name : tabs) {
+ tabLayout.addTab(tabLayout.newTab().setText(tab_name));
+ }
+
+ tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
+ @Override
+ public void onTabSelected(TabLayout.Tab tab) {
+ viewPager.setCurrentItem(tab.getPosition());
+ }
+
+ @Override
+ public void onTabUnselected(TabLayout.Tab tab) {
+ }
+
+ @Override
+ public void onTabReselected(TabLayout.Tab tab) {
+ }
+ });
+ }
+
+ @Override
+ public void onPause() {
+ adapter.fragment0.onPause();
+ adapter.fragment1.onPause();
+ super.onPause();
+ }
+
+ @Override
+ public void onStop() {
+ adapter.fragment0.onStop();
+ adapter.fragment1.onStop();
+ super.onStop();
+ }
+
+ @Override
+ public void onDestroyView() {
+ adapter.fragment0.onDestroyView();
+ adapter.fragment1.onDestroyView();
+ super.onDestroyView();
+ }
+
+ @Override
+ public void onDestroy() {
+ adapter.fragment0.onDestroy();
+ adapter.fragment1.onDestroy();
+ MainActivity.csLibrary4A.setSameCheck(true);
+ MainActivity.csLibrary4A.restoreAfterTagSelect();
+ super.onDestroy();
+ }
+
+ @Override
+ public void onDetach() {
+ adapter.fragment0.onDetach();
+ adapter.fragment1.onDetach();
+ super.onDetach();
+ }
+
+ public AccessSecurityFragment() {
+ super("AccessSecurityFragment");
+ }
+}
+
+
+
+package com.csl.cs710ademoapp.fragments;
+
+import android.os.AsyncTask;
+import android.os.Bundle;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.Button;
+import android.widget.EditText;
+import android.widget.Toast;
+
+import com.csl.cs710ademoapp.AccessTask;
+import com.csl.cs710ademoapp.GenericTextWatcher;
+import com.csl.cs710ademoapp.MainActivity;
+import com.csl.cs710ademoapp.R;
+import com.csl.cslibrary4a.NotificationConnector;
+import com.csl.cslibrary4a.ReaderDevice;
+import com.csl.cslibrary4a.RfidReaderChipData;
+
+public class AccessSecurityKillFragment extends CommonFragment {
+ private EditText editTextTagID, editTextPassword, editTextAntennaPower;
+ private Button button;
+
+ private AccessTask accessTask;
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ super.onCreateView(inflater, container, savedInstanceState, false);
+ return inflater.inflate(R.layout.fragment_access_kill, container, false);
+ }
+
+ @Override
+ public void onActivityCreated(Bundle savedInstanceState) {
+ super.onActivityCreated(savedInstanceState);
+
+ editTextTagID = (EditText) getActivity().findViewById(R.id.accessKillTagID);
+ editTextPassword = (EditText) getActivity().findViewById(R.id.accessKillPasswordValue);
+ editTextPassword.addTextChangedListener(new GenericTextWatcher(editTextPassword, 8));
+ editTextPassword.setText("00000000");
+
+ editTextAntennaPower = (EditText) getActivity().findViewById(R.id.accessKillAntennaPower);
+ editTextAntennaPower.setText(String.valueOf(300));
+
+ button = (Button) getActivity().findViewById(R.id.accessKillButton);
+ button.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (MainActivity.csLibrary4A.isBleConnected() == false) {
+ Toast.makeText(MainActivity.mContext, R.string.toast_ble_not_connected, Toast.LENGTH_SHORT).show();
+ return;
+ } else if (MainActivity.csLibrary4A.isRfidFailure()) {
+ Toast.makeText(MainActivity.mContext, "Rfid is disabled", Toast.LENGTH_SHORT).show();
+ return;
+ }
+ startAccessTask();
+ }
+ });
+
+ ReaderDevice tagSelected = MainActivity.tagSelected;
+ if (tagSelected != null) {
+ if (tagSelected.getSelected() == true) {
+ editTextTagID.setText(tagSelected.getAddress());
+ }
+ }
+ MainActivity.csLibrary4A.setSameCheck(false);
+ }
+
+ @Override
+ public void onResume() {
+ super.onResume();
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("AccessSecurityKillFragment().onResume(): userVisibleHint = " + userVisibleHint);
+ if (userVisibleHint) {
+ setNotificationListener();
+ }
+ }
+
+ @Override
+ public void onPause() {
+ MainActivity.csLibrary4A.setNotificationListener(null);
+ super.onPause();
+ }
+
+ @Override
+ public void onDestroy() {
+ MainActivity.csLibrary4A.setNotificationListener(null);
+ if (accessTask != null) accessTask.cancel(true);
+ super.onDestroy();
+ }
+
+ boolean userVisibleHint = false;
+ @Override
+ public void setUserVisibleHint(boolean isVisibleToUser) {
+ super.setUserVisibleHint(isVisibleToUser);
+ if(getUserVisibleHint()) {
+ userVisibleHint = true;
+ MainActivity.csLibrary4A.appendToLog("AccessSecurityKillFragment is now VISIBLE");
+ setNotificationListener();
+ } else {
+ userVisibleHint = false;
+ MainActivity.csLibrary4A.appendToLog("AccessSecurityKillFragment is now INVISIBLE");
+ MainActivity.csLibrary4A.setNotificationListener(null);
+ }
+ }
+
+ public AccessSecurityKillFragment() {
+ super("AccessSecurityKillFragment");
+ }
+
+ void setNotificationListener() {
+ MainActivity.csLibrary4A.setNotificationListener(new NotificationConnector.NotificationListener() {
+ @Override
+ public void onChange() {
+ MainActivity.csLibrary4A.appendToLog("TRIGGER key is pressed.");
+ if (MainActivity.csLibrary4A.getTriggerButtonStatus()) startAccessTask();
+ }
+ });
+ }
+
+ void startAccessTask() {
+ if (accessTask != null) if (accessTask.getStatus() == AsyncTask.Status.RUNNING) return;
+ boolean invalidRequest = false;
+ String strTagID = editTextTagID.getText().toString();
+ String strPassword = editTextPassword.getText().toString();
+ int powerLevel = Integer.valueOf(editTextAntennaPower.getText().toString());
+ accessTask = new AccessTask(button, null, invalidRequest, true,
+ strTagID, 1, 32,
+ strPassword, powerLevel, RfidReaderChipData.HostCommands.CMD_18K6CKILL,
+ 0, 0, true, false,
+ null, null, null, null, null);
+ accessTask.execute();
+ }
+}
+
+
+
+package com.csl.cs710ademoapp.fragments;
+
+import android.os.AsyncTask;
+import android.os.Bundle;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.ArrayAdapter;
+import android.widget.Button;
+import android.widget.CheckBox;
+import android.widget.EditText;
+import android.widget.Spinner;
+import android.widget.Toast;
+
+import com.csl.cs710ademoapp.AccessTask;
+import com.csl.cs710ademoapp.GenericTextWatcher;
+import com.csl.cs710ademoapp.MainActivity;
+import com.csl.cs710ademoapp.R;
+import com.csl.cslibrary4a.NotificationConnector;
+import com.csl.cslibrary4a.ReaderDevice;
+import com.csl.cslibrary4a.RfidReaderChipData;
+
+public class AccessSecurityLockFragment extends CommonFragment {
+ private EditText editTextTagID, editTextPassword, editTextAntennaPower;
+ private CheckBox checkBox;
+ private Spinner spinner4KillPwd, spinner4AccessPwd, spinner4EpcMemory, spinner4TidMemory, spinner4UserMemory;
+ private Button button;
+
+ private AccessTask accessTask;
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ super.onCreateView(inflater, container, savedInstanceState, false);
+ return inflater.inflate(R.layout.fragment_access_lock, container, false);
+ }
+
+ @Override
+ public void onActivityCreated(Bundle savedInstanceState) {
+ super.onActivityCreated(savedInstanceState);
+
+ editTextTagID = (EditText) getActivity().findViewById(R.id.accessLockTagID);
+ editTextPassword = (EditText) getActivity().findViewById(R.id.accessLockPasswordValue);
+ editTextPassword.addTextChangedListener(new GenericTextWatcher(editTextPassword, 8));
+ editTextPassword.setText("00000000");
+
+ checkBox = (CheckBox) getActivity().findViewById(R.id.accessLockAllPermLock);
+
+ ArrayAdapter arrayAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.access_lock_privilege_array, R.layout.custom_spinner_layout);
+ arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+
+ spinner4KillPwd = (Spinner) getActivity().findViewById(R.id.accessLockPrivilege4KillPwd);
+ spinner4KillPwd.setAdapter(arrayAdapter);
+
+ spinner4AccessPwd = (Spinner) getActivity().findViewById(R.id.accessLockPrivilege4AccessPwd);
+ spinner4AccessPwd.setAdapter(arrayAdapter);
+
+ spinner4EpcMemory = (Spinner) getActivity().findViewById(R.id.accessLockPrivilege4EpcMemory);
+ spinner4EpcMemory.setAdapter(arrayAdapter);
+
+ spinner4TidMemory = (Spinner) getActivity().findViewById(R.id.accessLockPrivilege4TidMemory);
+ spinner4TidMemory.setAdapter(arrayAdapter);
+
+ spinner4UserMemory = (Spinner) getActivity().findViewById(R.id.accessLockPrivilege4UserMemory);
+ spinner4UserMemory.setAdapter(arrayAdapter);
+
+ editTextAntennaPower = (EditText) getActivity().findViewById(R.id.accessLockAntennaPower);
+ editTextAntennaPower.setText(String.valueOf(300));
+
+ button = (Button) getActivity().findViewById(R.id.accessLockButton);
+ button.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (MainActivity.csLibrary4A.isBleConnected() == false) {
+ Toast.makeText(MainActivity.mContext, R.string.toast_ble_not_connected, Toast.LENGTH_SHORT).show();
+ return;
+ } else if (MainActivity.csLibrary4A.isRfidFailure()) {
+ Toast.makeText(MainActivity.mContext, "Rfid is disabled", Toast.LENGTH_SHORT).show();
+ return;
+ }
+ startAccessTask();
+ }
+ });
+
+ ReaderDevice tagSelected = MainActivity.tagSelected;
+ if (tagSelected != null) {
+ if (tagSelected.getSelected() == true) {
+ editTextTagID.setText(tagSelected.getAddress());
+ }
+ }
+ MainActivity.csLibrary4A.setSameCheck(false);
+ }
+
+ @Override
+ public void onResume() {
+ super.onResume();
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("AccessSecurityLockFragment().onResume(): userVisibleHint = " + userVisibleHint);
+ if (userVisibleHint) {
+ setNotificationListener();
+ }
+ }
+
+ @Override
+ public void onPause() {
+ MainActivity.csLibrary4A.setNotificationListener(null);
+ super.onPause();
+ }
+
+ @Override
+ public void onDestroy() {
+ MainActivity.csLibrary4A.setNotificationListener(null);
+ if (accessTask != null) accessTask.cancel(true);
+ super.onDestroy();
+ }
+
+ boolean userVisibleHint = false;
+ @Override
+ public void setUserVisibleHint(boolean isVisibleToUser) {
+ super.setUserVisibleHint(isVisibleToUser);
+ if(getUserVisibleHint()) {
+ userVisibleHint = true;
+ MainActivity.csLibrary4A.appendToLog("AccessSecurityLockFragment is now VISIBLE");
+ setNotificationListener();
+ } else {
+ userVisibleHint = false;
+ MainActivity.csLibrary4A.appendToLog("AccessSecurityLockFragment is now INVISIBLE");
+ MainActivity.csLibrary4A.setNotificationListener(null);
+ }
+ }
+
+ public AccessSecurityLockFragment() {
+ super("AccessSecurityLockFragment");
+ }
+
+ void setNotificationListener() {
+ MainActivity.csLibrary4A.setNotificationListener(new NotificationConnector.NotificationListener() {
+ @Override
+ public void onChange() {
+ MainActivity.csLibrary4A.appendToLog("TRIGGER key is pressed.");
+ if (MainActivity.csLibrary4A.getTriggerButtonStatus()) startAccessTask();
+ }
+ });
+ }
+
+ void startAccessTask() {
+ int accessLockAction = 0;
+ int accessLockMask = 0;
+ int lockAction;
+
+ if (accessTask != null) if (accessTask.getStatus() == AsyncTask.Status.RUNNING) return;
+ if (checkBox.isChecked()) {
+ accessLockAction = 0x3FF;
+ accessLockMask = 0x3FF;
+ } else {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("accessLockAction = " + String.format("%x", accessLockAction) + ", accessLockMask = " + String.format("%x", accessLockMask));
+ lockAction = spinner4KillPwd.getSelectedItemPosition();
+ accessLockAction |= ((lockAction == 0 ? 0 : lockAction - 1) << 8);
+ accessLockMask |= ((lockAction == 0 ? 0 : 3) << 8);
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("Kill: accessLockAction = " + String.format("%x", accessLockAction) + ", accessLockMask = " + String.format("%x", accessLockMask));
+
+ lockAction = spinner4AccessPwd.getSelectedItemPosition();
+ accessLockAction |= ((lockAction == 0 ? 0 : lockAction - 1) << 6);
+ accessLockMask |= ((lockAction == 0 ? 0 : 3) << 6);
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("Access: accessLockAction = " + String.format("%x", accessLockAction) + ", accessLockMask = " + String.format("%x", accessLockMask));
+
+ lockAction = spinner4EpcMemory.getSelectedItemPosition();
+ accessLockAction |= ((lockAction == 0 ? 0 : lockAction - 1) << 4);
+ accessLockMask |= ((lockAction == 0 ? 0 : 3) << 4);
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("Epc: accessLockAction = " + String.format("%x", accessLockAction) + ", accessLockMask = " + String.format("%x", accessLockMask));
+
+ lockAction = spinner4TidMemory.getSelectedItemPosition();
+ accessLockAction |= ((lockAction == 0 ? 0 : lockAction - 1) << 2);
+ accessLockMask |= ((lockAction == 0 ? 0 : 3) << 2);
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("Tid: accessLockAction = " + String.format("%x", accessLockAction) + ", accessLockMask = " + String.format("%x", accessLockMask));
+
+ lockAction = spinner4UserMemory.getSelectedItemPosition();
+ accessLockAction |= (lockAction == 0 ? 0 : lockAction - 1);
+ accessLockMask |= (lockAction == 0 ? 0 : 3);
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("Uesr: accessLockAction = " + String.format("%x", accessLockAction) + ", accessLockMask = " + String.format("%x", accessLockMask));
+ }
+
+ boolean invalidRequest = false;
+ String strTagID = editTextTagID.getText().toString();
+ String strPassword = editTextPassword.getText().toString();
+ int powerLevel = Integer.valueOf(editTextAntennaPower.getText().toString());
+ if (invalidRequest == false) {
+ if (MainActivity.csLibrary4A.setAccessLockAction(accessLockAction, accessLockMask) == false) {
+ invalidRequest = true;
+ }
+ }
+ accessTask = new AccessTask(button, null, invalidRequest, true,
+ strTagID, 1, 32,
+ strPassword, powerLevel, RfidReaderChipData.HostCommands.CMD_18K6CLOCK,
+ 0, 0, true, false,
+ null, null, null, null, null);
+ accessTask.execute();
+ }
+}
+
+
+
+package com.csl.cs710ademoapp.fragments;
+
+import static com.csl.cslibrary4a.RfidReader.TagType.TAG_NXP;
+import static com.csl.cslibrary4a.RfidReader.TagType.TAG_NXP_UCODE8_EPC;
+import static com.csl.cslibrary4a.RfidReader.TagType.TAG_NXP_UCODE8_EPCBRAND;
+import static com.csl.cslibrary4a.RfidReader.TagType.TAG_NXP_UCODE8_EPCBRANDTID;
+import static com.csl.cslibrary4a.RfidReader.TagType.TAG_NXP_UCODE8_EPCTID;
+import static com.csl.cslibrary4a.RfidReader.TagType.TAG_NXP_UCODEDNA;
+
+import android.os.Bundle;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.AdapterView;
+import android.widget.ArrayAdapter;
+import android.widget.LinearLayout;
+import android.widget.RadioButton;
+import android.widget.Spinner;
+
+import com.csl.cs710ademoapp.MainActivity;
+import com.csl.cs710ademoapp.R;
+import com.google.android.material.tabs.TabLayout;
+
+public class AccessUcode8Fragment extends CommonFragment {
+ final boolean DEBUG = true;
+ Spinner spinnerTagSelect;
+ RadioButton radioButtonSelectEpc, radioButtonSelectEpcTid, radioButtonSelectEpcBrand, radioButtonSelectEpcBrandTidCheck;
+ enum nxpTag {
+ ucode8, ucodeDNA, others
+ }
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ super.onCreateView(inflater, container, savedInstanceState, false);
+ return inflater.inflate(R.layout.fragment_access_ucode8, container, false);
+ }
+
+ @Override
+ public void onActivityCreated(Bundle savedInstanceState) {
+ super.onActivityCreated(savedInstanceState);
+
+ spinnerTagSelect = (Spinner) getActivity().findViewById(R.id.accessNxpTagSelect);
+ ArrayAdapter targetAdapter1 = ArrayAdapter.createFromResource(getActivity(), R.array.nxp_options, R.layout.custom_spinner_layout);
+ targetAdapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+ spinnerTagSelect.setAdapter(targetAdapter1); spinnerTagSelect.setSelection(0);
+ spinnerTagSelect.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
+ @Override
+ public void onItemSelected(AdapterView> parentView, View selectedItemView, int position, long id) {
+ TabLayout tabLayout = (TabLayout) getActivity().findViewById(R.id.OperationsTabLayout);
+ TabLayout.TabView tabView = tabLayout.getTabAt(2).view; tabView.setVisibility(View.GONE);
+ TabLayout.TabView tabViewUntrace = tabLayout.getTabAt(3).view; tabViewUntrace.setVisibility(View.GONE);
+ LinearLayout layout = (LinearLayout) getActivity().findViewById(R.id.accessNxpUcode8Select); layout.setVisibility(View.GONE);
+ if (position == nxpTag.ucode8.ordinal()) {
+ updateUcode8Type();
+ MainActivity.csLibrary4A.appendToLog("AccessUcode8Fragment.onItemSelected[spinnerTagSelect] set MainActivity.mDid as " + MainActivity.mDid);
+ if (MainActivity.csLibrary4A.get98XX() == 0) tabViewUntrace.setVisibility(View.VISIBLE);
+ layout.setVisibility(View.VISIBLE);
+ } else if (position == nxpTag.ucodeDNA.ordinal()) {
+ MainActivity.tagType = TAG_NXP_UCODEDNA; MainActivity.mDid = "E2C06";
+ MainActivity.csLibrary4A.appendToLog("AccessUcode8Fragment.onItemSelected set MainActivity.mDid as E2C06");
+ tabView.setVisibility(View.VISIBLE);
+ if (MainActivity.csLibrary4A.get98XX() == 0) tabViewUntrace.setVisibility(View.VISIBLE);
+ } else {
+ MainActivity.tagType = TAG_NXP; MainActivity.mDid = "E2806";
+ MainActivity.csLibrary4A.appendToLog("AccessUcode8Fragment.onItemSelected set MainActivity.mDid as E2806");
+ }
+ MainActivity.csLibrary4A.appendToLog("new mDid = " + MainActivity.mDid);
+ }
+
+ @Override
+ public void onNothingSelected(AdapterView> parentView) {
+ // your code here
+ }
+
+ });
+
+ radioButtonSelectEpc = (RadioButton) getActivity().findViewById(R.id.accessUC8SelectEpc);
+ radioButtonSelectEpcTid = (RadioButton) getActivity().findViewById(R.id.accessUC8SelectEpcTid);
+ radioButtonSelectEpcBrand = (RadioButton) getActivity().findViewById(R.id.accessUC8SelectEpcBrand);
+ radioButtonSelectEpcBrandTidCheck = (RadioButton) getActivity().findViewById(R.id.accessUC8SelectEpcBrandTidCheck);
+ if (MainActivity.csLibrary4A.get98XX() == 2) {
+ radioButtonSelectEpc.setChecked(true);
+ radioButtonSelectEpcBrand.setVisibility(View.GONE);
+ radioButtonSelectEpcBrandTidCheck.setVisibility(View.GONE);
+ } else radioButtonSelectEpcBrand.setChecked(true);
+
+ MainActivity.csLibrary4A.setSameCheck(false);
+ }
+
+ @Override
+ public void onDestroy() {
+ MainActivity.csLibrary4A.setSameCheck(true);
+ super.onDestroy();
+ }
+
+ boolean userVisibleHint = false;
+ @Override
+ public void setUserVisibleHint(boolean isVisibleToUser) {
+ super.setUserVisibleHint(isVisibleToUser);
+ if(getUserVisibleHint()) {
+ userVisibleHint = true;
+ MainActivity.csLibrary4A.appendToLog("AccessUcode8Fragment is now VISIBLE");
+ // setNotificationListener();
+ } else {
+ updateUcode8Type();
+ MainActivity.csLibrary4A.appendToLog("AccessUcode8Fragment.setUserVisibleHint set MainActivity.mDid as " + MainActivity.mDid);
+ userVisibleHint = false;
+ MainActivity.csLibrary4A.appendToLog("AccessUcode8Fragment is now INVISIBLE");
+ }
+ }
+
+ void updateUcode8Type() {
+ if (spinnerTagSelect != null && spinnerTagSelect.getSelectedItemPosition() == nxpTag.ucode8.ordinal()) {
+ if (radioButtonSelectEpc != null && radioButtonSelectEpcTid != null && radioButtonSelectEpcBrand != null && radioButtonSelectEpcBrandTidCheck != null) {
+ if (radioButtonSelectEpc.isChecked()) {
+ MainActivity.csLibrary4A.appendToLog("Selected EPC");
+ MainActivity.tagType = TAG_NXP_UCODE8_EPC; MainActivity.mDid = "E2806894A";
+ MainActivity.csLibrary4A.appendToLog("AccessUcode8Fragment.setUserVisibleHint set MainActivity.mDid as E2806894A");
+ }
+ if (radioButtonSelectEpcTid.isChecked()) {
+ MainActivity.csLibrary4A.appendToLog("Selected EPC+TID");
+ MainActivity.tagType = TAG_NXP_UCODE8_EPCTID; MainActivity.mDid = "E2806894B";
+ MainActivity.csLibrary4A.appendToLog("AccessUcode8Fragment.setUserVisibleHint set MainActivity.mDid as E2806894b");
+ }
+ if (radioButtonSelectEpcBrand.isChecked()) {
+ MainActivity.csLibrary4A.appendToLog("Selected EPC+BRAND");
+ MainActivity.tagType = TAG_NXP_UCODE8_EPCBRAND; MainActivity.mDid = "E2806894C";
+ MainActivity.csLibrary4A.appendToLog("AccessUcode8Fragment.setUserVisibleHint set MainActivity.mDid as E2806894C");
+ }
+ if (radioButtonSelectEpcBrandTidCheck.isChecked()) {
+ MainActivity.csLibrary4A.appendToLog("Selected EPC+BRAND");
+ MainActivity.tagType = TAG_NXP_UCODE8_EPCBRANDTID; MainActivity.mDid = "E2806894d";
+ MainActivity.csLibrary4A.appendToLog("AccessUcode8Fragment.setUserVisibleHint set MainActivity.mDid as E2806894d");
+ }
+ MainActivity.csLibrary4A.appendToLog("newDid 1 = " + MainActivity.mDid);
+ }
+ }
+ }
+
+ public AccessUcode8Fragment() {
+ super("AccessUcode8Fragment");
+ }
+}
+
+
+
+package com.csl.cs710ademoapp.fragments;
+
+import static com.csl.cs710ademoapp.MainActivity.csLibrary4A;
+
+import android.app.Activity;
+import android.os.AsyncTask;
+import android.os.Bundle;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.ArrayAdapter;
+import android.widget.Button;
+import android.widget.CheckBox;
+import android.widget.EditText;
+import android.widget.LinearLayout;
+import android.widget.Spinner;
+import android.widget.TableRow;
+import android.widget.TextView;
+import android.widget.Toast;
+
+import com.csl.cs710ademoapp.AccessTask;
+import com.csl.cs710ademoapp.GenericTextWatcher;
+import com.csl.cs710ademoapp.MainActivity;
+import com.csl.cs710ademoapp.R;
+import com.csl.cs710ademoapp.SaveList2ExternalTask;
+import com.csl.cs710ademoapp.SelectTag;
+import com.csl.cslibrary4a.AesCmac;
+import com.csl.cslibrary4a.ReaderDevice;
+import com.csl.cslibrary4a.RfidReaderChipData;
+
+import org.json.JSONArray;
+import org.json.JSONException;
+import org.json.JSONObject;
+
+import javax.crypto.Cipher;
+import javax.crypto.Mac;
+import javax.crypto.spec.IvParameterSpec;
+import javax.crypto.spec.SecretKeySpec;
+
+public class AccessUcodeFragment extends CommonFragment {
+ final boolean DEBUG = true; int iTagType = -1;
+ SelectTag selectTag;
+ TextView textViewAesKey0ActivateOk, textViewAesKey1ActivateOk, textViewAesKey0Ok, textViewAesKey1Ok;
+ Spinner spinnerHideTid;
+ CheckBox checkBoxAuthEncryptMode, checkBoxAuthValidMode;
+ CheckBox checkBoxHideEpc, checkBoxHideTid, checkBoxHideUser, checkBoxHideRange;
+ CheckBox checkBoxAesKey0Activate, checkBoxAesKey1Activate, checkBoxAesKey0, checkBoxAesKey1;
+
+ EditText editTextAuthKeyId, editTextAuthMsg, editTextAuthProfile, editTextAuthOffset, editTextAuthBlockId, editTextAuthProtMode, editTextEpcSize, editTextAesKey0, editTextAesKey1, editTextAuthResponse;
+ TextView textViewAuthResponseDecoded, textViewAuthResponseDecodedCustom, editTextAuthResponseEncodedMac, textViewImpinjResponse;
+ EditText editTextAccessUCTid, editTextAccessUCserverImpinj, editTextAccessUCemail, editTextAccessUCpassword;
+ private Button buttonRead, buttonWrite;
+ private Button buttonReadBuffer, buttonTam1, buttonTam2, buttonUntrace, buttonShowEpc; String strShowEpcButtonBackup;
+
+ enum ReadWriteTypes {
+ NULL, TEMPERATURE, AESKEY0, AESKEY1, AESKEY0ACTIVATE, AESKEY1ACTIVATE, ENABLE
+ }
+ boolean operationRead = false;
+ boolean readBufferChecked = false;
+ boolean authenChecked = false; boolean authenTam1; int keyId, profile, offset, blockId, protMode; String strChallenge;
+ boolean untraceChecked = false;
+ boolean showEpcChecked = false;
+ ReadWriteTypes readWriteTypes;
+ boolean bImpinJTag = false;
+
+ private AccessTask accessTask;
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ super.onCreateView(inflater, container, savedInstanceState, false);
+ return inflater.inflate(R.layout.fragment_access_ucode, container, false);
+ }
+
+ @Override
+ public void onActivityCreated(Bundle savedInstanceState) {
+ super.onActivityCreated(savedInstanceState);
+ if (MainActivity.mDid != null) if (MainActivity.mDid.contains("E28240")) iTagType = 5;
+
+ selectTag = new SelectTag((Activity)getActivity(), 1);
+ if (MainActivity.mDid != null && MainActivity.mDid.indexOf("E2801") == 0) bImpinJTag = true;
+
+ spinnerHideTid = (Spinner) getActivity().findViewById(R.id.accessUCHideTid);
+ ArrayAdapter targetAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.hideTid_options, R.layout.custom_spinner_layout);
+ targetAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+ spinnerHideTid.setAdapter(targetAdapter);
+
+ checkBoxHideEpc = (CheckBox) getActivity().findViewById(R.id.accessUCHideEpc);
+ checkBoxHideTid = (CheckBox) getActivity().findViewById(R.id.accessUCHideTid1);
+ checkBoxHideUser = (CheckBox) getActivity().findViewById(R.id.accessUCHideUser);
+ checkBoxHideRange = (CheckBox) getActivity().findViewById(R.id.accessUCHideRange);
+ textViewAesKey0ActivateOk = (TextView) getActivity().findViewById(R.id.accessUCAesKey0ActivateOK);
+ textViewAesKey1ActivateOk = (TextView) getActivity().findViewById(R.id.accessUCAesKey1ActivateOK);
+ checkBoxAesKey0Activate = (CheckBox) getActivity().findViewById(R.id.accessUCAesKey0Activate);
+ checkBoxAesKey1Activate = (CheckBox) getActivity().findViewById(R.id.accessUCAesKey1Activate);
+
+ TableRow tableRow = (TableRow) getActivity().findViewById(R.id.accessUCAesKeysRow);
+ if (iTagType == 5) tableRow.setVisibility(View.GONE);
+ textViewAesKey0Ok = (TextView) getActivity().findViewById(R.id.accessUCAesKey0OK);
+ textViewAesKey1Ok = (TextView) getActivity().findViewById(R.id.accessUCAesKey1OK);
+ checkBoxAesKey0 = (CheckBox) getActivity().findViewById(R.id.accessUCAesKey0Title);
+ checkBoxAesKey1 = (CheckBox) getActivity().findViewById(R.id.accessUCAesKey1Title);
+
+ editTextAuthKeyId = (EditText) getActivity().findViewById(R.id.accessUCAuthKeyId);
+ editTextAuthKeyId.setText(String.valueOf(0));
+ editTextAuthMsg = (EditText) getActivity().findViewById(R.id.accessUCAuthMsg);
+ editTextAuthMsg.addTextChangedListener(new GenericTextWatcher(editTextAuthMsg, bImpinJTag ? 12 : 20));
+ editTextAuthProfile = (EditText) getActivity().findViewById(R.id.accessUCAuthProfile);
+ editTextAuthProfile.setText(String.valueOf(0));
+ editTextAuthOffset = (EditText) getActivity().findViewById(R.id.accessUCAuthOffset);
+ editTextAuthOffset.setText(String.valueOf(0));
+ editTextAuthBlockId = (EditText) getActivity().findViewById(R.id.accessUCAuthBlockId);
+ editTextAuthBlockId.setText(String.valueOf(1));
+
+ TextView textViewAuthProtModeLabel = (TextView) getActivity().findViewById(R.id.accessUCAuthProtModeLabel);
+ editTextAuthProtMode = (EditText) getActivity().findViewById(R.id.accessUCAuthProtMode);
+ TableRow tableRowAuthProtMode = (TableRow) getActivity().findViewById(R.id.accessUCAuthtModeRow);
+ checkBoxAuthEncryptMode = (CheckBox) getActivity().findViewById(R.id.accessUCAuthEncryptMode);
+ checkBoxAuthValidMode = (CheckBox) getActivity().findViewById(R.id.accessUCAuthValidMode);
+ if (iTagType == 5) {
+ textViewAuthProtModeLabel.setVisibility(View.GONE);
+ editTextAuthProtMode.setVisibility(View.GONE);
+ } else {
+ tableRowAuthProtMode.setVisibility(View.GONE);
+ editTextAuthProtMode.setText(String.valueOf(1));
+ }
+
+ editTextAuthResponse = (EditText) getActivity().findViewById(R.id.accessUCAuthResponse);
+ textViewAuthResponseDecoded = (TextView) getActivity().findViewById(R.id.accessUCAuthResponseDecoded);
+ textViewAuthResponseDecodedCustom = (TextView) getActivity().findViewById(R.id.accessUCAuthResponseDecodedCustom);
+ editTextAuthResponseEncodedMac = (TextView) getActivity().findViewById(R.id.accessUCAuthResponseEecodedMac);
+ textViewImpinjResponse = (TextView) getActivity().findViewById(R.id.accessUCImpinjResponse);
+ editTextEpcSize = (EditText) getActivity().findViewById(R.id.accessUCEpcSize);
+ editTextAesKey0 = (EditText) getActivity().findViewById(R.id.accessUCAesKey0);
+ editTextAesKey0.addTextChangedListener(new GenericTextWatcher(editTextAesKey0, 32));
+ editTextAesKey1 = (EditText) getActivity().findViewById(R.id.accessUCAesKey1);
+ editTextAesKey1.addTextChangedListener(new GenericTextWatcher(editTextAesKey1, 32));
+
+ buttonRead = (Button) getActivity().findViewById(R.id.accessUCReadButton);
+ if (iTagType == 5) buttonRead.setVisibility(View.GONE);
+ buttonRead.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (MainActivity.csLibrary4A.isBleConnected() == false) {
+ Toast.makeText(MainActivity.mContext, R.string.toast_ble_not_connected, Toast.LENGTH_SHORT).show();
+ return;
+ } else if (MainActivity.csLibrary4A.isRfidFailure()) {
+ Toast.makeText(MainActivity.mContext, "Rfid is disabled", Toast.LENGTH_SHORT).show();
+ return;
+ }
+ operationRead = true; startAccessTask();
+ }
+ });
+
+ buttonWrite = (Button) getActivity().findViewById(R.id.accessUCWriteButton);
+ buttonWrite.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (MainActivity.csLibrary4A.isBleConnected() == false) {
+ Toast.makeText(MainActivity.mContext, R.string.toast_ble_not_connected, Toast.LENGTH_SHORT).show();
+ return;
+ } else if (MainActivity.csLibrary4A.isRfidFailure()) {
+ Toast.makeText(MainActivity.mContext, "Rfid is disabled", Toast.LENGTH_SHORT).show();
+ return;
+ }
+ operationRead = false; startAccessTask();
+ }
+ });
+
+ buttonReadBuffer = (Button) getActivity().findViewById(R.id.accessUCReadBufferButton);
+ buttonReadBuffer.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (MainActivity.csLibrary4A.isBleConnected() == false) {
+ Toast.makeText(MainActivity.mContext, R.string.toast_ble_not_connected, Toast.LENGTH_SHORT).show();
+ return;
+ } else if (MainActivity.csLibrary4A.isRfidFailure()) {
+ Toast.makeText(MainActivity.mContext, "Rfid is disabled", Toast.LENGTH_SHORT).show();
+ return;
+ }
+ readBufferChecked = true; startAccessTask();
+ }
+ });
+
+ buttonTam1 = (Button) getActivity().findViewById(R.id.accessUCTam1AuthButton);
+ buttonTam1.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (MainActivity.csLibrary4A.isBleConnected() == false) {
+ Toast.makeText(MainActivity.mContext, R.string.toast_ble_not_connected, Toast.LENGTH_SHORT).show();
+ return;
+ } else if (MainActivity.csLibrary4A.isRfidFailure()) {
+ Toast.makeText(MainActivity.mContext, "Rfid is disabled", Toast.LENGTH_SHORT).show();
+ return;
+ }
+ MainActivity.csLibrary4A.appendToLog("buttonTam1 is pressed");
+ authenTam1 = true; authenChecked = true; keyId = Integer.parseInt(editTextAuthKeyId.getText().toString()); strChallenge = editTextAuthMsg.getText().toString();
+ startAccessTask();
+ }
+ });
+
+ buttonTam2 = (Button) getActivity().findViewById(R.id.accessUCTam2AuthButton);
+ buttonTam2.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (MainActivity.csLibrary4A.isBleConnected() == false) {
+ Toast.makeText(MainActivity.mContext, R.string.toast_ble_not_connected, Toast.LENGTH_SHORT).show();
+ return;
+ } else if (MainActivity.csLibrary4A.isRfidFailure()) {
+ Toast.makeText(MainActivity.mContext, "Rfid is disabled", Toast.LENGTH_SHORT).show();
+ return;
+ }
+ MainActivity.csLibrary4A.appendToLog("buttonTam2 is pressed");
+ authenTam1 = false; authenChecked = true; keyId = Integer.parseInt(editTextAuthKeyId.getText().toString()); strChallenge = editTextAuthMsg.getText().toString();
+ profile = Integer.parseInt(editTextAuthProfile.getText().toString());
+ offset = Integer.parseInt(editTextAuthOffset.getText().toString());
+ blockId = Integer.parseInt(editTextAuthBlockId.getText().toString());
+ if (iTagType != 5) protMode = Integer.parseInt(editTextAuthProtMode.getText().toString());
+ else {
+ protMode = 0;
+ if (checkBoxAuthEncryptMode.isChecked()) protMode += 1;
+ if (checkBoxAuthValidMode.isChecked()) protMode += 2;
+ }
+ startAccessTask();
+ }
+ });
+
+ buttonUntrace = (Button) getActivity().findViewById(R.id.accessUCUntraceButton);
+ buttonUntrace.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (MainActivity.csLibrary4A.isBleConnected() == false) {
+ Toast.makeText(MainActivity.mContext, R.string.toast_ble_not_connected, Toast.LENGTH_SHORT).show();
+ return;
+ } else if (MainActivity.csLibrary4A.isRfidFailure()) {
+ Toast.makeText(MainActivity.mContext, "Rfid is disabled", Toast.LENGTH_SHORT).show();
+ return;
+ }
+ untraceChecked = true; startAccessTask();
+ }
+ });
+
+ tableRow = (TableRow) getActivity().findViewById(R.id.accessUCShowEpcRow);
+ if (iTagType == 5) tableRow.setVisibility(View.GONE);
+ buttonShowEpc = (Button) getActivity().findViewById(R.id.accessUCShowEpcButton);
+ buttonShowEpc.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (MainActivity.csLibrary4A.isBleConnected() == false) {
+ Toast.makeText(MainActivity.mContext, R.string.toast_ble_not_connected, Toast.LENGTH_SHORT).show();
+ return;
+ } else if (MainActivity.csLibrary4A.isRfidFailure()) {
+ Toast.makeText(MainActivity.mContext, "Rfid is disabled", Toast.LENGTH_SHORT).show();
+ return;
+ }
+ showEpcChecked = true; startAccessTask();
+ }
+ });
+
+ TextView textViewWarning = (TextView) getActivity().findViewById(R.id.accessUCWarning);
+ if (iTagType == 5) textViewWarning.setText("Notice: Xerxes assumes Key0 for Tam1 and Tam 2");
+ else textViewWarning.setText("Notice: Ucode assumes Key1 for Tam2");
+
+ MainActivity.csLibrary4A.getAuthenticateReplyLength();
+ MainActivity.csLibrary4A.getUntraceableEpcLength();
+ MainActivity.csLibrary4A.setSameCheck(false);
+
+ MainActivity.csLibrary4A.appendToLog("mDid in AccessUcodeFragment = " + MainActivity.mDid);
+ TextView textView = (TextView) getActivity().findViewById(R.id.accessUCAuthKeyIdLabel);
+ EditText editText = (EditText) getActivity().findViewById(R.id.accessUCAuthKeyId);
+ TableRow tableRow1 = (TableRow) getActivity().findViewById(R.id.accessUCAuthProfileRow);
+ LinearLayout layout1 = (LinearLayout) getActivity().findViewById(R.id.accessUCKeyLayout);
+ LinearLayout layout = (LinearLayout) getActivity().findViewById(R.id.accessUCButtons);
+ if (bImpinJTag) {
+ textView.setVisibility(View.GONE);
+ editText.setVisibility(View.GONE);
+ editTextAuthMsg.setText("049CA53E55EA");
+ tableRow1.setVisibility(View.GONE);
+ layout1.setVisibility(View.GONE);
+ layout.setVisibility(View.GONE);
+ }
+
+ Button buttonImpinjCheck = (Button) getActivity().findViewById(R.id.accessUCImpinjCheck);
+ buttonImpinjCheck.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View view) {
+ if (!bRunning) {
+ textViewImpinjResponse.setText("");
+ mHandler.post(runnable);
+ }
+ }
+ });
+
+ editTextAccessUCserverImpinj = (EditText) getActivity().findViewById(R.id.accessUCserverImpinj);
+ editTextAccessUCemail = (EditText) getActivity().findViewById(R.id.accessUCemail);
+ editTextAccessUCpassword = (EditText) getActivity().findViewById(R.id.accessUCpassword);
+ if (true) {
+ editTextAccessUCserverImpinj.setText(csLibrary4A.getServerImpinjLocation());
+ editTextAccessUCemail.setText(csLibrary4A.getServerImpinjName());
+ editTextAccessUCpassword.setText(csLibrary4A.getServerImpinjPassword());
+ } else if (false) {
+ editTextAccessUCserverImpinj.setText("https://h9tqczg9-7275.asse.devtunnels.ms");
+ editTextAccessUCemail.setText("wallace.sit@cne.com.hk");
+ editTextAccessUCpassword.setText("Cne12345678?");
+ } else {
+ editTextAccessUCserverImpinj.setText("https://democloud.convergence.com.hk/ias");
+ editTextAccessUCemail.setText("wallace.sit@cne.com.hk");
+ editTextAccessUCpassword.setText("Cne12345678?");
+ }
+ }
+
+ SaveList2ExternalTask saveExternalTask; boolean bRunning = false; int bStep = 0; String strBearer = null;
+ Runnable runnable = new Runnable() {
+ @Override
+ public void run() {
+ csLibrary4A.appendToLog("0 bRunning = " + bRunning + ", bStep = " + bStep);
+ if (saveExternalTask != null && saveExternalTask.getStatus() == AsyncTask.Status.FINISHED) {
+ bStep++;
+ if (saveExternalTask.responseCode != 200) bStep++;
+ else {
+ if (bStep == 1) strBearer = saveExternalTask.response;
+ else {
+ String strTid = null, strResult = null;
+ JSONObject obj = null;
+ try {
+ obj = new JSONObject(saveExternalTask.response);
+ JSONArray jsonArray = obj.getJSONArray("tagValidity");
+ MainActivity.csLibrary4A.appendToLog("Json tagValidity is " + (jsonArray == null ? "null" : "valid"));
+ strTid = jsonArray.getJSONObject(0).getString("tid");
+ strResult = jsonArray.getJSONObject(0).getString("tagValid");
+ } catch (JSONException e) {
+ csLibrary4A.appendToLog("Json exception = " + e.toString());
+ }
+ if (strTid != null && strResult != null) {
+ //textViewImpinjResponse.setText(strResult + " " + strTid);
+ textViewImpinjResponse.setText((strResult.matches("true") ? "Valid" : "Invalid"));
+ }
+ }
+ }
+ MainActivity.csLibrary4A.appendToLog("responseCode = " + saveExternalTask.responseCode + ", response = " + saveExternalTask.response);
+ saveExternalTask = null;
+ }
+ csLibrary4A.appendToLog("bRunning = " + bRunning + ", bStep = " + bStep);
+ if (bStep < 2) {
+ if (saveExternalTask == null || saveExternalTask.getStatus() != AsyncTask.Status.RUNNING) {
+ csLibrary4A.appendToLog("1 bRunning = " + bRunning + ", bStep = " + bStep);
+ bRunning = true;
+ if (bStep == 0) {
+ bStep = 0;
+ saveExternalTask = new SaveList2ExternalTask(true);
+
+ JSONObject object = new JSONObject();
+ try {
+ //object.put("Username", "CslAuth2047#$");
+ //object.put("Password", "Sheungwan123#$");
+ object.put("email", editTextAccessUCemail.getText().toString()); //"wallace.sit@cne.com.hk");
+ object.put("password", editTextAccessUCpassword.getText().toString()); //"Cne12345678?");
+ } catch (Exception ex) {
+ MainActivity.csLibrary4A.appendToLog("Error in creating Json");
+ }
+ saveExternalTask.messageStr = object.toString();
+ //saveExternalTask.url = "https://ias.authenticate.impinj.io/external/jwt/authenticate";
+ saveExternalTask.url = editTextAccessUCserverImpinj.getText().toString() + "/api/Auth/login"; // "https://h9tqczg9-7275.asse.devtunnels.ms/api/Auth/login";
+ MainActivity.csLibrary4A.appendToLog("Adddress: " + saveExternalTask.url + ", json message:" + saveExternalTask.messageStr);
+ saveExternalTask.execute();
+ MainActivity.csLibrary4A.appendToLog("responseCode = " + saveExternalTask.responseCode + ", response = " + saveExternalTask.response);
+ } else {
+ saveExternalTask = new SaveList2ExternalTask(true);
+
+ JSONObject object = new JSONObject();
+ try {
+ JSONArray jsonArray = new JSONArray();
+ JSONObject object1 = new JSONObject();
+ object1.put("tid", editTextAccessUCTid.getText().toString()); //tagSelected.getTid()); //"E2C011A21234123412341234"); //
+ object1.put("challenge", editTextAuthMsg.getText().toString());
+ object1.put("tagResponse", editTextAuthResponse.getText().toString());
+ jsonArray.put(object1);
+ object.put("tagVerify", jsonArray);
+ object.put("sendSignature", true);
+ object.put("sendSalt", true);
+ object.put("sendTime", true);
+ } catch (Exception ex) {
+ MainActivity.csLibrary4A.appendToLog("Error in creating Json");
+ }
+ saveExternalTask.messageStr = object.toString();
+ saveExternalTask.url = editTextAccessUCserverImpinj.getText().toString() + "/api/ImpinjAuthentication/authenticate"; //"https://h9tqczg9-7275.asse.devtunnels.ms/api/ImpinjAuthentication/authenticate";
+ saveExternalTask.strBearer = "Bearer " + strBearer;
+ MainActivity.csLibrary4A.appendToLog("Adddress: " + saveExternalTask.url + ", json message:" + saveExternalTask.messageStr);
+ saveExternalTask.execute();
+ MainActivity.csLibrary4A.appendToLog("responseCode = " + saveExternalTask.responseCode + ", response = " + saveExternalTask.response);
+ }
+ }
+ mHandler.postDelayed(runnable, 100);
+ } else {
+ bRunning = false; bStep = 0;
+ }
+ }
+ };
+
+ @Override
+ public void onResume() {
+ super.onResume();
+ setupTagID();
+ }
+
+ @Override
+ public void onDestroy() {
+ if (accessTask != null) accessTask.cancel(true);
+ MainActivity.csLibrary4A.setSameCheck(true);
+ //MainActivity.mCs108Library4a.appendToLog("onDestroy");
+ super.onDestroy();
+ }
+
+ boolean userVisibleHint = false;
+ @Override
+ public void setUserVisibleHint(boolean isVisibleToUser) {
+ super.setUserVisibleHint(isVisibleToUser);
+ if(getUserVisibleHint()) {
+ userVisibleHint = true;
+ MainActivity.csLibrary4A.appendToLog("AccessUcodeFragment is now VISIBLE");
+ setupTagID();
+ // setNotificationListener();
+ } else {
+ userVisibleHint = false;
+ MainActivity.csLibrary4A.appendToLog("AccessUcodeFragment is now INVISIBLE");
+// MainActivity.mCs108Library4a.setNotificationListener(null);
+ }
+ }
+
+ public AccessUcodeFragment() {
+ super("AccessUcodeFragment");
+ }
+
+ void setupTagID() {
+ if (selectTag == null) return;
+ ReaderDevice tagSelected = MainActivity.tagSelected;
+ MainActivity.csLibrary4A.appendToLog("Start with tagSelected = " + (tagSelected == null ? "NULL" : (tagSelected.getSelected() + ", " + tagSelected.getAddress())));
+ boolean bSelected = false;
+ if (tagSelected != null) {
+ if (tagSelected.getSelected() == true) {
+ bSelected = true;
+ MainActivity.csLibrary4A.appendToLog("selectTag is " + (selectTag == null ? "NULL" : "valid"));
+ if (selectTag != null) MainActivity.csLibrary4A.appendToLog("selectTag.editTextTag is " + (selectTag.editTextTagID == null ? "NULL" : "valid"));
+ if (selectTag.editTextTagID != null) {
+ MainActivity.csLibrary4A.appendToLog("editTextRWTagID.setTTEXT " + tagSelected.getAddress());
+ selectTag.editTextTagID.setText(tagSelected.getAddress());
+ }
+
+ String stringDetail = tagSelected.getDetails();
+ int indexUser = stringDetail.indexOf("USER=");
+ if (indexUser != -1) {
+ String stringUser = stringDetail.substring(indexUser + 5);
+ MainActivity.csLibrary4A.appendToLog("stringUser = " + stringUser);
+
+ boolean bEnableBAPMode = false;
+ int number = Integer.valueOf(stringUser.substring(3, 4), 16);
+ if ((number % 2) == 1) bEnableBAPMode = true;
+// CheckBox checkBoxBAP = (CheckBox) getActivity().findViewById(R.id.coldChainEnableBAP);
+// checkBoxBAP.setChecked(bEnableBAPMode);
+ }
+
+ editTextAccessUCTid = (EditText) getActivity().findViewById(R.id.accessUCTid);
+ editTextAccessUCTid.setText(tagSelected.getTid());
+ }
+ }
+ }
+
+ private byte[] doubleSubKey(byte[] k) {
+ byte[] ret = new byte[k.length];
+
+ boolean firstBitSet = ((k[0]&0x80) != 0);
+ for (int i=0; i= 2) {
+ if (true) {
+ AesCmac mac = null;
+ mac = new AesCmac();
+ secretKey = new SecretKeySpec(key1, "AES");
+ mac.init(secretKey); //set master key
+ mac.updateBlock(dataIn); //given input
+ decValue = mac.doFinal();
+ } else if (true) {
+ cipher = Cipher.getInstance(strAlgo);
+ secretKey = new SecretKeySpec(key1, "AES");
+ cipher.init(Cipher.ENCRYPT_MODE, secretKey, new IvParameterSpec(iv));
+
+ // First calculate k0 from zero bytes
+ byte[] k0 = new byte[16];
+ cipher.update(k0, 0, k0.length, k0, 0);
+
+ // Calculate values for k1 and k2
+ byte[] k1 = doubleSubKey(k0);
+ byte[] k2 = doubleSubKey(k1);
+ cipher.init(Cipher.ENCRYPT_MODE, secretKey, new IvParameterSpec(iv));
+ int bufferCount;
+ } else if (false) {
+ secretKey = new SecretKeySpec(key1, "AES");
+ Mac hmac = Mac.getInstance("HmacSHA256"); //HmacMD5, HmacSHA1, HmacSHA256
+ hmac.init(secretKey);
+ hmac.update(iv);
+ decValue = hmac.doFinal(dataIn);
+ MainActivity.csLibrary4A.appendToLog("decValue1.length = " + decValue.length);
+ } else {
+ secretKey = new SecretKeySpec(key1, "AES");
+ cipher = Cipher.getInstance(strAlgo);
+ cipher.init(Cipher.ENCRYPT_MODE, secretKey, new IvParameterSpec(iv));
+ decValue = cipher.doFinal(dataIn);
+ }
+ String strMac = MainActivity.csLibrary4A.byteArrayToString(decValue).substring(0, 24);
+ editTextAuthResponseEncodedMac.setText(strMac);
+
+ strMatchResult += ", MAC";
+ strMatching = editTextAuthResponse.getText().toString();
+ while (strMatching.length() > 32)
+ strMatching = strMatching.substring(32).trim();
+ bMatch = false;
+ if (strMatching.matches(strMac)) bMatch = true;
+ if (bMatch) strMatchResult += " Matched";
+ else strMatchResult += " Not Matched";
+ }
+ }
+ Toast.makeText(MainActivity.mContext, strMatchResult, Toast.LENGTH_SHORT).show();
+ retValue = true;
+ }
+
+ if (false) {
+ secretKey = new SecretKeySpec(key, "HmacSHA256");
+ try {
+ Mac hmac = Mac.getInstance("HmacSHA256");
+
+ byte[] data2dec = dataIn;
+ byte[] iv = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
+
+ hmac.init(secretKey);
+ hmac.update(iv);
+ byte[] decValue = hmac.doFinal(data2dec);
+ MainActivity.csLibrary4A.appendToLog("decValue.length = " + decValue.length);
+ editTextAuthResponseEncodedMac.setText(MainActivity.csLibrary4A.byteArrayToString(decValue));
+ if (false) {
+ byte[] decValue16 = new byte[16];
+ System.arraycopy(decValue, 0, decValue16, 0, 16);
+ textViewAuthResponseDecoded.setText(MainActivity.csLibrary4A.byteArrayToString(decValue16));
+ if (protMode == 0 || protMode == 2) {
+ decValue16 = new byte[16];
+ System.arraycopy(data2dec, 16, decValue16, 0, 16);
+ } else {
+ decValue16 = new byte[16];
+ System.arraycopy(decValue, 16, decValue16, 0, 16);
+ }
+ textViewAuthResponseDecodedCustom.setText(MainActivity.csLibrary4A.byteArrayToString(decValue16));
+ retValue = true;
+ }
+ } catch (Exception ex) {
+ MainActivity.csLibrary4A.appendToLog("Error while encrypting: " + ex.toString());
+ }
+ }
+ } catch (Exception ex) {
+ MainActivity.csLibrary4A.appendToLog("Error while encrypting: " + ex.toString());
+ }
+ return retValue;
+ }
+ void startAccessTask() {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("startAccessTask()");
+ MainActivity.csLibrary4A.setInvAlgo(false);
+ if (MainActivity.csLibrary4A.getRetryCount() < 2) MainActivity.csLibrary4A.setRetryCount(2);
+ if (updating == false) {
+ updating = true; bankProcessing = 0;
+ mHandler.removeCallbacks(updateRunnable);
+ mHandler.post(updateRunnable);
+ }
+ }
+ boolean updating = false; int bankProcessing = 0;
+ private final Runnable updateRunnable = new Runnable() {
+ @Override
+ public void run() {
+ boolean rerunRequest = false; boolean taskRequest = false;
+ if (accessTask == null) {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("updateRunnable(): NULL accessReadWriteTask");
+ taskRequest = true;
+ } else if (accessTask.getStatus() != AsyncTask.Status.FINISHED) {
+ rerunRequest = true;
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("updateRunnable(): accessReadWriteTask.getStatus() = " + accessTask.getStatus().toString());
+ } else {
+ taskRequest = true;
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("updateRunnable(): FINISHED accessReadWriteTask");
+ }
+ if (processResult()) { rerunRequest = true; MainActivity.csLibrary4A.appendToLog("processResult is TRUE"); }
+ else if (taskRequest) {
+ boolean invalid = processTickItems();
+ MainActivity.csLibrary4A.appendToLog("processTickItems, invalid = " + invalid);
+ if (bankProcessing++ != 0 && invalid == true) rerunRequest = false;
+ else {
+ Button button;
+ if (readBufferChecked) button = buttonReadBuffer;
+ else if (authenChecked && authenTam1) button = buttonTam1;
+ else if (authenChecked) button = buttonTam2;
+ else if (untraceChecked) button = buttonUntrace;
+ else if (showEpcChecked) { if (strShowEpcButtonBackup == null) strShowEpcButtonBackup = buttonShowEpc.getText().toString(); buttonShowEpc.setText("Show"); button = buttonShowEpc; }
+ else if (operationRead) button = buttonRead;
+ else button = buttonWrite;
+
+ RfidReaderChipData.HostCommands hostCommand;
+ if (readBufferChecked) hostCommand = RfidReaderChipData.HostCommands.CMD_READBUFFER;
+ else if (authenChecked) hostCommand = RfidReaderChipData.HostCommands.CMD_18K6CAUTHENTICATE;
+ else if (untraceChecked || showEpcChecked) hostCommand = RfidReaderChipData.HostCommands.CMD_UNTRACEABLE;
+ else if (operationRead) hostCommand = RfidReaderChipData.HostCommands.CMD_18K6CREAD;
+ else hostCommand = RfidReaderChipData.HostCommands.CMD_18K6CWRITE;
+
+ accessTask = new AccessTask(button, null, invalid, true,
+ selectTag.editTextTagID.getText().toString(), 1, 32,
+ selectTag.editTextAccessPassword.getText().toString(), Integer.valueOf(selectTag.editTextAccessAntennaPower.getText().toString()), hostCommand,
+ 0, 0, true, false,
+ null, null, null, null, null);
+ accessTask.execute();
+ rerunRequest = true;
+ MainActivity.csLibrary4A.appendToLog("accessTask is created");
+ }
+ }
+ if (rerunRequest) {
+ mHandler.postDelayed(updateRunnable, 500);
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("updateRunnable(): Restart");
+ }
+ else updating = false;
+ MainActivity.csLibrary4A.appendToLog("updateRunnable(): Ending with updating = " + updating);
+ }
+ };
+
+ short setTemperature(float fTemperature) {
+ if (fTemperature > 63.75) fTemperature = (float) 63.75;
+ else if (fTemperature < -64) fTemperature = -64;
+ boolean bNegative = false;
+ if (fTemperature < 0) { bNegative = true; fTemperature = 0 - fTemperature; }
+ fTemperature += 0.125; fTemperature /= 0.25;
+ short retValue = (short)fTemperature;
+ if (bNegative) { retValue--; retValue &= 0xFF; retValue ^= 0xFF; retValue |= 0x100; }
+ return retValue;
+ }
+ String getTemperatue(String stringInput) {
+ byte bValue = Byte.parseByte(stringInput.substring(0,1), 16);
+ byte bValue2 = Byte.parseByte(stringInput.substring(1, 2), 16); bValue2 <<= 4;
+ byte bValue3 = Byte.parseByte(stringInput.substring(2, 3), 16); bValue2 |= bValue3;
+ String stringValue = ""; short sValue = (short)(bValue2 & 0xFF);
+ if ((bValue & 0x01) != 0) { stringValue = "-"; bValue2 ^= 0xFF; sValue = (short)(bValue2 & 0xFF); sValue++; }
+ stringValue += String.valueOf((sValue & 0x1FF) >> 2);
+ switch (sValue & 0x03) {
+ case 1:
+ stringValue += ".25";
+ break;
+ case 2:
+ stringValue += ".50";
+ break;
+ case 3:
+ stringValue += ".75";
+ break;
+ }
+ return stringValue;
+ }
+
+ boolean processResult() {
+ String accessResult = null;
+ if (accessTask == null) return false;
+ else if (accessTask.getStatus() != AsyncTask.Status.FINISHED) return false;
+ else {
+ accessResult = accessTask.accessResult;
+ if (readBufferChecked) readBufferChecked = false;
+ else if (authenChecked) {
+ authenChecked = false; if (accessResult != null) {
+ String strValue = "";
+ for (int i = 0; i < accessResult.length(); i += 32) {
+ int i_end = i + 32; if (i_end >= accessResult.length()) i_end = accessResult.length();
+ if (i != 0) strValue += "\n";
+ strValue += accessResult.substring(i, i_end);
+ }
+ editTextAuthResponse.setText(strValue);
+ if (bImpinJTag) {
+ LinearLayout layout = (LinearLayout) getActivity().findViewById(R.id.accessUCImpinjLayout);
+ if (authenTam1) layout.setVisibility(View.VISIBLE);
+ else layout.setVisibility(View.GONE);
+ } else processAESdata(accessResult);
+ }
+ }
+ else if (untraceChecked) untraceChecked = false;
+ else if (showEpcChecked) { showEpcChecked = false; if (strShowEpcButtonBackup != null) buttonShowEpc.setText(strShowEpcButtonBackup); strShowEpcButtonBackup = null; }
+ else if (accessResult == null) {
+ if (readWriteTypes == ReadWriteTypes.AESKEY0ACTIVATE) {
+ textViewAesKey0ActivateOk.setText("E"); checkBoxAesKey0Activate.setChecked(false);
+ } else if (readWriteTypes == ReadWriteTypes.AESKEY1ACTIVATE) {
+ textViewAesKey1ActivateOk.setText("E"); checkBoxAesKey1Activate.setChecked(false);
+ } else if (readWriteTypes == ReadWriteTypes.AESKEY0) {
+ textViewAesKey0Ok.setText("E"); checkBoxAesKey0.setChecked(false);
+ } else if (readWriteTypes == ReadWriteTypes.AESKEY1) {
+ textViewAesKey1Ok.setText("E"); checkBoxAesKey1.setChecked(false);
+ }
+ } else {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("accessResult = " + accessResult);
+ if (readWriteTypes == ReadWriteTypes.AESKEY0ACTIVATE) {
+ textViewAesKey0ActivateOk.setText("O"); checkBoxAesKey0Activate.setChecked(false); readWriteTypes = ReadWriteTypes.NULL;
+ } else if (readWriteTypes == ReadWriteTypes.AESKEY1ACTIVATE) {
+ textViewAesKey1ActivateOk.setText("O"); checkBoxAesKey1Activate.setChecked(false); readWriteTypes = ReadWriteTypes.NULL;
+ } else if (readWriteTypes == ReadWriteTypes.AESKEY0) {
+ textViewAesKey0Ok.setText("O"); checkBoxAesKey0.setChecked(false); readWriteTypes = ReadWriteTypes.NULL;
+ if (operationRead) editTextAesKey0.setText(accessResult);
+ } else if (readWriteTypes == ReadWriteTypes.AESKEY1) {
+ textViewAesKey1Ok.setText("O"); checkBoxAesKey1.setChecked(false); readWriteTypes = ReadWriteTypes.NULL;
+ if (operationRead) editTextAesKey1.setText(accessResult);
+ }
+ }
+ accessTask = null;
+ return true;
+ }
+ }
+ boolean processTickItems() {
+ boolean invalidRequest1 = false;
+ int accSize = 0, accOffset = 0, accBank = 3;
+ String writeData = "";
+
+ if (readBufferChecked) {
+ accOffset = 0; accSize = 1;
+ } else if (authenChecked) {
+ if (authenTam1) {
+ if (bImpinJTag) {
+ if (MainActivity.csLibrary4A.setTamConfiguration(false, strChallenge) == false)
+ invalidRequest1 = true;
+ } else if (MainActivity.csLibrary4A.setTam1Configuration(keyId, strChallenge) == false)
+ invalidRequest1 = true;
+ } else if (bImpinJTag) {
+ if (MainActivity.csLibrary4A.setTamConfiguration(true, strChallenge) == false)
+ invalidRequest1 = true;
+ } else if (MainActivity.csLibrary4A.setTam2Configuration(keyId, strChallenge, profile, offset, blockId, protMode) == false)
+ invalidRequest1 = true;
+ if (invalidRequest1 == false) { editTextAuthResponse.setText(""); textViewAuthResponseDecoded.setText(""); textViewAuthResponseDecodedCustom.setText(""); editTextAuthResponseEncodedMac.setText(""); }
+ return invalidRequest1;
+ } else if (untraceChecked) {
+ if (MainActivity.csLibrary4A.setUntraceable(checkBoxHideEpc.isChecked(), checkBoxHideEpc.isChecked() ? 2 : 6, checkBoxHideTid.isChecked() ? 1: 0, checkBoxHideUser.isChecked(), checkBoxHideRange.isChecked()) == false) invalidRequest1 = true;
+ return invalidRequest1;
+ } else if (showEpcChecked) {
+ try {
+ if (MainActivity.csLibrary4A.setUntraceable(false, Integer.parseInt(editTextEpcSize.getText().toString()), 0, false, false) == false) invalidRequest1 = true;
+ } catch (Exception ex) {
+ invalidRequest1 = true;
+ }
+ return invalidRequest1;
+ } else if (checkBoxAesKey0Activate.isChecked() == true) {
+ accOffset = 0xC8; accSize = 1; readWriteTypes = ReadWriteTypes.AESKEY0ACTIVATE; textViewAesKey0ActivateOk.setText("");
+ if (operationRead == false) writeData = "E200";
+ } else if (checkBoxAesKey1Activate.isChecked() == true) {
+ accOffset = 0xD8; accSize = 1; readWriteTypes = ReadWriteTypes.AESKEY1ACTIVATE; textViewAesKey0ActivateOk.setText("");
+ if (operationRead == false) writeData = "E200";
+ } else if (checkBoxAesKey0.isChecked() == true) {
+ accOffset = 0xC0; if (iTagType == 5) { accOffset = 0x10; accBank = 0; }
+ accSize = 8; readWriteTypes = ReadWriteTypes.AESKEY0; textViewAesKey0Ok.setText("");
+ if (operationRead) editTextAesKey0.setText("");
+ else writeData = editTextAesKey0.getText().toString();
+ } else if (checkBoxAesKey1.isChecked() == true) {
+ accOffset = 0xD0; if (iTagType == 5) { accOffset = 0x18; accBank = 0; }
+ accSize = 8; readWriteTypes = ReadWriteTypes.AESKEY1; textViewAesKey1Ok.setText("");
+ if (operationRead) editTextAesKey1.setText("");
+ else writeData = editTextAesKey1.getText().toString();
+ } else {
+ invalidRequest1 = true;
+ }
+
+ if (invalidRequest1 == false) {
+ if (MainActivity.csLibrary4A.setAccessBank(accBank) == false) {
+ invalidRequest1 = true;
+ }
+ }
+ if (invalidRequest1 == false) {
+ if (MainActivity.csLibrary4A.setAccessOffset(accOffset) == false) {
+ invalidRequest1 = true;
+ }
+ }
+ if (invalidRequest1 == false) {
+ if (accSize == 0) {
+ invalidRequest1 = true;
+ } else if (MainActivity.csLibrary4A.setAccessCount(accSize) == false) {
+ invalidRequest1 = true;
+ }
+ }
+ if (invalidRequest1 == false && operationRead == false) {
+ if (invalidRequest1 == false) {
+ if (MainActivity.csLibrary4A.setAccessWriteData(writeData) == false) {
+ invalidRequest1 = true;
+ }
+ }
+ }
+ return invalidRequest1;
+ }
+}
+
+
+
+package com.csl.cs710ademoapp.fragments;
+
+import androidx.lifecycle.Lifecycle;
+import android.os.AsyncTask;
+import android.os.Bundle;
+import android.text.InputType;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.AdapterView;
+import android.widget.ArrayAdapter;
+import android.widget.Button;
+import android.widget.CheckBox;
+import android.widget.EditText;
+import android.widget.Spinner;
+import android.widget.TextView;
+import android.widget.Toast;
+
+import com.csl.cs710ademoapp.AccessTask;
+import com.csl.cs710ademoapp.GenericTextWatcher;
+import com.csl.cs710ademoapp.MainActivity;
+import com.csl.cs710ademoapp.R;
+import com.csl.cslibrary4a.ReaderDevice;
+import com.csl.cslibrary4a.RfidReaderChipData;
+
+public class AccessXerxesLoggerFragment extends CommonFragment {
+ final boolean DEBUG = true;
+ boolean bXerxesEnable = false;
+ EditText editTextRWTagID, editTextAccessRWAccPassword, editTextaccessRWAntennaPower;
+ TextView textViewUserCode1OK, textViewUserCode2OK, textViewUserCode3OK, textViewUserCode4OK, textViewUserCode5OK;
+ CheckBox checkBoxUserCode1, checkBoxUserCode2, checkBoxUserCode3, checkBoxUserCode4, checkBoxUserCode5;
+ EditText editTextUserCode1, editTextUserCode2, editTextUserCode3, editTextUserCode4, editTextUserCode5;
+ Spinner spinnerUserCode2Unit, spinnerUserCode3Unit; int iUserCode2UnitPosition, iUserCode3UnitPosition;
+ String strReadUserCode1, strReadUserCode2, strReadUserCode3, strReadUserCode4, strReadUserCode5;
+ private Button buttonRead, buttonWrite;
+
+ enum ReadWriteTypes {
+ NULL, USERCODE1, USERCODE2, USERCODE3, USERCODE4, USERCODE5
+ }
+ ReadWriteTypes readWriteTypes;
+ boolean operationRead = false;
+
+ private AccessTask accessTask;
+ private int modelCode = 0;
+ private int calCode1, calTemp1, calCode2, calTemp2, calVer = -1;
+ private boolean changedSelectIndex = false;
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ super.onCreateView(inflater, container, savedInstanceState, false);
+ return inflater.inflate(R.layout.fragment_access_xerxes, container, false);
+ }
+
+ @Override
+ public void onActivityCreated(Bundle savedInstanceState) {
+ super.onActivityCreated(savedInstanceState);
+
+ editTextRWTagID = (EditText) getActivity().findViewById(R.id.accessXXTagID);
+ editTextAccessRWAccPassword = (EditText) getActivity().findViewById(R.id.accessXXAccPasswordValue);
+ editTextAccessRWAccPassword.addTextChangedListener(new GenericTextWatcher(editTextAccessRWAccPassword, 8));
+ editTextAccessRWAccPassword.setText("00000000");
+
+ textViewUserCode1OK = (TextView) getActivity().findViewById(R.id.accessXXXerxes1OK);
+ textViewUserCode2OK = (TextView) getActivity().findViewById(R.id.accessXXXerxes2OK);
+ textViewUserCode3OK = (TextView) getActivity().findViewById(R.id.accessXXXerxes3OK);
+ textViewUserCode4OK = (TextView) getActivity().findViewById(R.id.accessXXXerxes4OK);
+ textViewUserCode5OK = (TextView) getActivity().findViewById(R.id.accessXXXerxes5OK);
+
+ checkBoxUserCode1 = (CheckBox) getActivity().findViewById(R.id.accessXXXerxees1Title); checkBoxUserCode1.setText("Log number:");
+ checkBoxUserCode2 = (CheckBox) getActivity().findViewById(R.id.accessXXXerxees2Title); checkBoxUserCode2.setText("Temperature:");
+ checkBoxUserCode3 = (CheckBox) getActivity().findViewById(R.id.accessXXXerxees3Title); checkBoxUserCode3.setText("Maximum temperature:");
+ checkBoxUserCode4 = (CheckBox) getActivity().findViewById(R.id.accessXXXerxees4Title); checkBoxUserCode4.setText("Alarm high trigger count:");
+ checkBoxUserCode5 = (CheckBox) getActivity().findViewById(R.id.accessXXXerxees5Title); checkBoxUserCode5.setText("Alarm low trigger count:");
+
+ editTextUserCode1 = (EditText) getActivity().findViewById(R.id.accessXXXerxes1Code); editTextUserCode1.setInputType(InputType.TYPE_CLASS_NUMBER);
+ editTextUserCode2 = (EditText) getActivity().findViewById(R.id.accessXXXerxes2Code); editTextUserCode2.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL | InputType.TYPE_NUMBER_FLAG_SIGNED);
+ editTextUserCode3 = (EditText) getActivity().findViewById(R.id.accessXXXerxes3Code); editTextUserCode3.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL | InputType.TYPE_NUMBER_FLAG_SIGNED);
+ editTextUserCode4 = (EditText) getActivity().findViewById(R.id.accessXXXerxes4Code); editTextUserCode4.setInputType(InputType.TYPE_CLASS_NUMBER);
+ editTextUserCode5 = (EditText) getActivity().findViewById(R.id.accessXXXerxes5Code); editTextUserCode5.setInputType(InputType.TYPE_CLASS_NUMBER);
+
+ ArrayAdapter arrayAdapterUserCode2Unit = ArrayAdapter.createFromResource(getActivity(), R.array.temperature_unit_options, R.layout.custom_spinner_layout);
+ arrayAdapterUserCode2Unit.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+ spinnerUserCode2Unit = (Spinner) getActivity().findViewById(R.id.accessXXXerxes2Unit);
+ spinnerUserCode2Unit.setAdapter(arrayAdapterUserCode2Unit);
+ spinnerUserCode2Unit.setSelection(0); iUserCode2UnitPosition = 0;
+ spinnerUserCode2Unit.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
+ @Override
+ public void onItemSelected(AdapterView> adapterView, View view, int i, long l) {
+ if (i != iUserCode2UnitPosition) {
+ String strValue = editTextUserCode2.getText().toString();
+ if (iUserCode2UnitPosition == 0 && i == 1) strValue = MainActivity.csLibrary4A.temperatureC2F(strValue);
+ else if (iUserCode2UnitPosition == 1 && i == 0) strValue = MainActivity.csLibrary4A.temperatureF2C(strValue);
+ editTextUserCode2.setText(strValue);
+ }
+ iUserCode2UnitPosition = i;
+ }
+
+ @Override
+ public void onNothingSelected(AdapterView> adapterView) {
+ }
+ });
+
+ spinnerUserCode3Unit = (Spinner) getActivity().findViewById(R.id.accessXXXerxes3Unit);
+ spinnerUserCode3Unit.setAdapter(arrayAdapterUserCode2Unit);
+ spinnerUserCode3Unit.setSelection(0); iUserCode3UnitPosition = 0;
+ spinnerUserCode3Unit.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
+ @Override
+ public void onItemSelected(AdapterView> adapterView, View view, int i, long l) {
+ if (i != iUserCode3UnitPosition) {
+ String strValue = editTextUserCode3.getText().toString();
+ if (iUserCode3UnitPosition == 0 && i == 1) strValue = MainActivity.csLibrary4A.temperatureC2F(strValue);
+ else if (iUserCode3UnitPosition == 1 && i == 0) strValue = MainActivity.csLibrary4A.temperatureF2C(strValue);
+ editTextUserCode3.setText(strValue);
+ }
+ iUserCode3UnitPosition = i;
+ }
+
+ @Override
+ public void onNothingSelected(AdapterView> adapterView) {
+ }
+ });
+
+ editTextaccessRWAntennaPower = (EditText) getActivity().findViewById(R.id.accessXXAntennaPower);
+ editTextaccessRWAntennaPower.setText(String.valueOf(300));
+
+ buttonRead = (Button) getActivity().findViewById(R.id.accessRWReadButton);
+ buttonRead.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (MainActivity.csLibrary4A.isBleConnected() == false) {
+ Toast.makeText(MainActivity.mContext, R.string.toast_ble_not_connected, Toast.LENGTH_SHORT).show();
+ return;
+ } else if (MainActivity.csLibrary4A.isRfidFailure()) {
+ Toast.makeText(MainActivity.mContext, "Rfid is disabled", Toast.LENGTH_SHORT).show();
+ return;
+ }
+ operationRead = true; startAccessTask();
+ }
+ });
+
+ buttonWrite = (Button) getActivity().findViewById(R.id.accessRWWriteButton);
+ buttonWrite.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (MainActivity.csLibrary4A.isBleConnected() == false) {
+ Toast.makeText(MainActivity.mContext, R.string.toast_ble_not_connected, Toast.LENGTH_SHORT).show();
+ return;
+ } else if (MainActivity.csLibrary4A.isRfidFailure()) {
+ Toast.makeText(MainActivity.mContext, "Rfid is disabled", Toast.LENGTH_SHORT).show();
+ return;
+ }
+ operationRead = false; startAccessTask();
+ }
+ });
+
+ MainActivity.csLibrary4A.setSameCheck(false);
+ }
+
+ @Override
+ public void onResume() {
+ super.onResume();
+ setupTagID();
+ }
+
+ @Override
+ public void onDestroy() {
+ if (accessTask != null) accessTask.cancel(true);
+ MainActivity.csLibrary4A.setSameCheck(true);
+ super.onDestroy();
+ }
+
+ boolean userVisibleHint = false;
+ @Override
+ public void setUserVisibleHint(boolean isVisibleToUser) {
+ super.setUserVisibleHint(isVisibleToUser);
+ if (getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.RESUMED) == false) return;
+ if(getUserVisibleHint()) {
+ userVisibleHint = true;
+ setupTagID();
+ } else {
+ userVisibleHint = false;
+ }
+ }
+
+ public AccessXerxesLoggerFragment() {
+ super("AccessXerxesLoggerFragment");
+ }
+
+ void setupTagID() {
+ ReaderDevice tagSelected = MainActivity.tagSelected;
+ boolean bSelected = false;
+ if (tagSelected != null) {
+ if (tagSelected.getSelected() == true) {
+ String stringDetail = tagSelected.getDetails();
+ int indexUser = stringDetail.indexOf("TID=");
+ if (indexUser != -1) {
+ //
+ }
+ bSelected = true;
+ if (editTextRWTagID != null) editTextRWTagID.setText(tagSelected.getAddress());
+
+ if (tagSelected.getMdid() == null) {
+ } else if (tagSelected.getMdid().contains("E282402")) {
+ modelCode = 2;
+ } else if (tagSelected.getMdid().contains("E282403")) {
+ modelCode = 3;
+ } else if (tagSelected.getMdid().contains("E282405")) {
+ modelCode = 5;
+ }
+
+ String strRes = tagSelected.getRes();
+ if (strRes != null) {
+ int ibracket = strRes.indexOf("(");
+ if (ibracket > 0) strRes = strRes.substring(0, ibracket);
+ }
+
+ stringDetail = tagSelected.getDetails();
+ indexUser = stringDetail.indexOf("USER=");
+ if (indexUser != -1) {
+ String stringUser = stringDetail.substring(indexUser + 5);
+ MainActivity.csLibrary4A.appendToLog("stringUser = " + stringUser);
+
+ boolean bEnableBAPMode = false;
+ int number = Integer.valueOf(stringUser.substring(3, 4), 16);
+ if ((number % 2) == 1) bEnableBAPMode = true;
+ }
+ }
+ }
+ }
+
+ void startAccessTask() {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("startAccessTask()");
+ if (updating == false) {
+ updating = true; bankProcessing = 0;
+ checkProcessing = 0;
+ mHandler.removeCallbacks(updateRunnable);
+ mHandler.post(updateRunnable);
+ }
+ }
+ boolean updating = false; int bankProcessing = 0;
+ int checkProcessing = 0;
+ private final Runnable updateRunnable = new Runnable() {
+ @Override
+ public void run() {
+ boolean rerunRequest = false; boolean taskRequest = false;
+ if (accessTask == null) {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("AccessXerxesLoggerFragment().updateRunnable(): NULL accessReadWriteTask");
+ taskRequest = true;
+ } else if (accessTask.getStatus() != AsyncTask.Status.FINISHED) {
+ rerunRequest = true;
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("AccessXerxesLoggerFragment().updateRunnable(): accessReadWriteTask.getStatus() = " + accessTask.getStatus().toString());
+ } else {
+ taskRequest = true;
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("AccessXerxesLoggerFragment().updateRunnable(): FINISHED accessReadWriteTask");
+ }
+ if (processResult()) { rerunRequest = true; MainActivity.csLibrary4A.appendToLog("processResult is TRUE");}
+ else if (taskRequest) {
+ boolean invalid = processTickItems();
+ MainActivity.csLibrary4A.appendToLog("processTickItems, invalid = " + invalid);
+ if (bankProcessing++ != 0 && invalid == true) rerunRequest = false;
+ else {
+ int selectBank = 1;
+ int selectOffset = 32;
+ String selectMask = editTextRWTagID.getText().toString();
+ accessTask = new AccessTask((operationRead ? buttonRead : buttonWrite), null, invalid, true,
+ selectMask, selectBank, selectOffset,
+ editTextAccessRWAccPassword.getText().toString(), Integer.valueOf(editTextaccessRWAntennaPower.getText().toString()), (operationRead ? RfidReaderChipData.HostCommands.CMD_18K6CREAD: RfidReaderChipData.HostCommands.CMD_18K6CWRITE),
+ 0, 0, true, false,
+ null, null, null, null, null);
+ accessTask.execute();
+ rerunRequest = true;
+ MainActivity.csLibrary4A.appendToLog("accessTask is created with selectBank = " + selectBank);
+ }
+ }
+ if (rerunRequest) {
+ mHandler.postDelayed(updateRunnable, 500);
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("AccessXerxesLoggerFragment().updateRunnable(): Restart");
+ }
+ else updating = false;
+ MainActivity.csLibrary4A.appendToLog("AccessXerxesLoggerFragment().updateRunnable(): Ending with updating = " + updating);
+ }
+ };
+
+ boolean setTemperatureCode(String strData, int iTempIndex) {
+ if (strData == null) return false;
+ if (strData.length() < 4) return false;
+
+ String strValue = MainActivity.csLibrary4A.strFloat16toFloat32(strData);
+ if (strValue == null) return false;
+ else {
+ if ( (iTempIndex == 0 && spinnerUserCode2Unit.getSelectedItemPosition() == 1)
+ || (iTempIndex == 1 && spinnerUserCode3Unit.getSelectedItemPosition() == 1) )
+ strValue = MainActivity.csLibrary4A.temperatureC2F(strValue);
+ if (iTempIndex == 0) editTextUserCode2.setText(strValue);
+ else editTextUserCode3.setText(strValue);
+ }
+ return true;
+ }
+
+ boolean processResult() {
+ String accessResult = null;
+ if (accessTask == null) return false;
+ else if (accessTask.getStatus() != AsyncTask.Status.FINISHED) return false;
+ else {
+ if (changedSelectIndex) {
+ changedSelectIndex = false; MainActivity.selectFor = 0;
+ MainActivity.csLibrary4A.setSelectCriteriaDisable(-1);
+ }
+ accessResult = accessTask.accessResult;
+ if (accessResult == null) {
+ if (readWriteTypes == ReadWriteTypes.USERCODE1) {
+ textViewUserCode1OK.setText("E");
+ //checkBoxUserCode1.setChecked(false);
+ } else if (readWriteTypes == ReadWriteTypes.USERCODE2) {
+ textViewUserCode2OK.setText("E");
+ //checkBoxUserCode2.setChecked(false);
+ } else if (readWriteTypes == ReadWriteTypes.USERCODE3) {
+ textViewUserCode3OK.setText("E");
+ //checkBoxUserCode3.setChecked(false);
+ } else if (readWriteTypes == ReadWriteTypes.USERCODE4) {
+ textViewUserCode4OK.setText("E");
+ //checkBoxUserCode4.setChecked(false);
+ } else if (readWriteTypes == ReadWriteTypes.USERCODE5) {
+ textViewUserCode5OK.setText("E");
+ //checkBoxUserCode5.setChecked(false);
+ }
+ } else {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("accessResult = " + accessResult);
+ if (readWriteTypes == ReadWriteTypes.USERCODE1) {
+ textViewUserCode1OK.setText("O");
+ //checkBoxUserCode1.setChecked(false);
+ readWriteTypes = ReadWriteTypes.NULL;
+ if (operationRead) {
+ int iValue = Integer.parseInt(accessResult, 16);
+ strReadUserCode1 = String.valueOf(iValue);
+ editTextUserCode1.setText(strReadUserCode1);
+ }
+ } else if (readWriteTypes == ReadWriteTypes.USERCODE2) {
+ textViewUserCode2OK.setText("O");
+ //checkBoxUserCode2.setChecked(false);
+ readWriteTypes = ReadWriteTypes.NULL;
+ if (operationRead) setTemperatureCode(accessResult, 0);
+ } else if (readWriteTypes == ReadWriteTypes.USERCODE3) {
+ textViewUserCode3OK.setText("O");
+ //checkBoxUserCode3.setChecked(false);
+ readWriteTypes = ReadWriteTypes.NULL;
+ if (operationRead) setTemperatureCode(accessResult, 1);
+ } else if (readWriteTypes == ReadWriteTypes.USERCODE4) {
+ textViewUserCode4OK.setText("O");
+ //checkBoxUserCode4.setChecked(false);
+ readWriteTypes = ReadWriteTypes.NULL;
+ if (operationRead) {
+ int iValue = Integer.parseInt(accessResult, 16);
+ strReadUserCode4 = String.valueOf(iValue);
+ editTextUserCode4.setText(strReadUserCode4);
+ }
+ } else if (readWriteTypes == ReadWriteTypes.USERCODE5) {
+ textViewUserCode5OK.setText("O");
+ //checkBoxUserCode5.setChecked(false);
+ readWriteTypes = ReadWriteTypes.NULL;
+ if (operationRead) {
+ int iValue = Integer.parseInt(accessResult, 16);
+ strReadUserCode5 = String.valueOf(iValue);
+ editTextUserCode5.setText(strReadUserCode5);
+ }
+ }
+ }
+ accessTask = null;
+ return true;
+ }
+ }
+
+ boolean processTickItems() {
+ boolean invalidRequest1 = false;
+ int accBank = 0, accSize = 0, accOffset = 0;
+ String writeData = "";
+
+ if (editTextRWTagID.getText().toString().length() == 0) invalidRequest1 = true;
+ else if (checkBoxUserCode1.isChecked() == true && checkProcessing < 1 && modelCode == 5) {
+ accBank = 3; accSize = 1; accOffset = 2; readWriteTypes = ReadWriteTypes.USERCODE1; checkProcessing = 1;
+ if (operationRead) {
+ textViewUserCode1OK.setText("");
+ editTextUserCode1.setText("");
+ } else {
+ String strValue = editTextUserCode1.getText().toString();
+ if (strValue.length() == 0) invalidRequest1 = true;
+ else {
+ int iValue = Integer.parseInt(strValue);
+ if (iValue > 0xFFFF) invalidRequest1 = true;
+ else writeData = String.format("%04X", iValue);
+ }
+ }
+ } else if (checkBoxUserCode2.isChecked() == true && checkProcessing < 2 && modelCode == 5) {
+ accBank = 3; accSize = 1; accOffset = 3; readWriteTypes = ReadWriteTypes.USERCODE2; checkProcessing = 2;
+ if (operationRead) {
+ textViewUserCode2OK.setText("");
+ editTextUserCode2.setText("");
+ } else {
+ String strValue = editTextUserCode2.getText().toString();
+ if (strValue.length() == 0) invalidRequest1 = true;
+ else {
+ if (spinnerUserCode2Unit.getSelectedItemPosition() == 1) strValue = MainActivity.csLibrary4A.temperatureF2C(strValue);
+ strValue = MainActivity.csLibrary4A.str2float16(strValue);
+ if (strValue.length() != 4) invalidRequest1 = true;
+ else writeData = strValue;
+ }
+ }
+ } else if (checkBoxUserCode3.isChecked() == true && checkProcessing < 3 && modelCode == 5) {
+ accBank = 3; accSize = 1; accOffset = 4; readWriteTypes = ReadWriteTypes.USERCODE3; checkProcessing = 3;
+ if (operationRead) {
+ textViewUserCode3OK.setText("");
+ editTextUserCode3.setText("");
+ } else {
+ String strValue = editTextUserCode3.getText().toString();
+ if (strValue.length() == 0) invalidRequest1 = true;
+ else {
+ if (spinnerUserCode3Unit.getSelectedItemPosition() == 1) strValue = MainActivity.csLibrary4A.temperatureF2C(strValue);
+ strValue = MainActivity.csLibrary4A.str2float16(strValue);
+ if (strValue.length() != 4) invalidRequest1 = true;
+ else writeData = strValue;
+ }
+ }
+ } else if (checkBoxUserCode4.isChecked() == true && checkProcessing < 4 && modelCode == 5) {
+ accBank = 3; accSize = 1; accOffset = 5; readWriteTypes = ReadWriteTypes.USERCODE4; checkProcessing = 4;
+ if (operationRead) {
+ textViewUserCode4OK.setText("");
+ editTextUserCode4.setText("");
+ } else {
+ String strValue = editTextUserCode4.getText().toString();
+ if (strValue.length() == 0) invalidRequest1 = true;
+ else {
+ int iValue = Integer.parseInt(strValue);
+ if (iValue > 0xFFFF) invalidRequest1 = true;
+ else writeData = String.format("%04X", iValue);
+ }
+ }
+ } else if (checkBoxUserCode5.isChecked() == true && checkProcessing < 5 && modelCode == 5) {
+ accBank = 3; accSize = 1; accOffset = 6; readWriteTypes = ReadWriteTypes.USERCODE5; checkProcessing = 5;
+ if (operationRead) {
+ textViewUserCode5OK.setText("");
+ editTextUserCode5.setText("");
+ } else {
+ String strValue = editTextUserCode5.getText().toString();
+ if (strValue.length() == 0) invalidRequest1 = true;
+ else {
+ int iValue = Integer.parseInt(strValue);
+ if (iValue > 0xFFFF) invalidRequest1 = true;
+ else writeData = String.format("%04X", iValue);
+ }
+ }
+ } else {
+ invalidRequest1 = true;
+ }
+
+ if (invalidRequest1 == false) {
+ if (MainActivity.csLibrary4A.setAccessBank(accBank) == false) {
+ invalidRequest1 = true;
+ }
+ }
+ if (invalidRequest1 == false) {
+ if (MainActivity.csLibrary4A.setAccessOffset(accOffset) == false) {
+ invalidRequest1 = true;
+ }
+ }
+ if (invalidRequest1 == false) {
+ if (accSize == 0) {
+ invalidRequest1 = true;
+ } else if (MainActivity.csLibrary4A.setAccessCount(accSize) == false) {
+ invalidRequest1 = true;
+ }
+ }
+ if (invalidRequest1 == false && operationRead == false) {
+ if (invalidRequest1 == false) {
+ if (MainActivity.csLibrary4A.setAccessWriteData(writeData) == false) {
+ invalidRequest1 = true;
+ }
+ }
+ }
+ return invalidRequest1;
+ }
+}
+
+
+
+package com.csl.cs710ademoapp.fragments;
+
+import static com.csl.cslibrary4a.RfidReader.TagType.TAG_EM_AURASENSE;
+
+import android.os.Bundle;
+
+import com.google.android.material.tabs.TabLayout;
+import androidx.fragment.app.Fragment;
+import androidx.fragment.app.FragmentManager;
+import androidx.fragment.app.FragmentStatePagerAdapter;
+import androidx.viewpager.widget.PagerAdapter;
+import androidx.viewpager.widget.ViewPager;
+import androidx.appcompat.app.ActionBar;
+import androidx.appcompat.app.AppCompatActivity;
+import android.view.LayoutInflater;
+import android.view.MenuItem;
+import android.view.View;
+import android.view.ViewGroup;
+
+import com.csl.cs710ademoapp.MainActivity;
+import com.csl.cs710ademoapp.R;
+
+public class AuraSenseFragment extends CommonFragment {
+ private ActionBar actionBar;
+ private ViewPager viewPager;
+ AuraSenseAdapter mAdapter;
+
+ private String[] tabs = {"Configuration", "Scan" };
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ super.onCreateView(inflater, container, savedInstanceState, true);
+ return inflater.inflate(R.layout.custom_tabbed_layout, container, false);
+ }
+
+ @Override
+ public boolean onOptionsItemSelected(MenuItem item) {
+ InventoryRfidiMultiFragment fragment1 = (InventoryRfidiMultiFragment) mAdapter.fragment1;
+ if (item.getItemId() == R.id.menuAction_clear) {
+ fragment1.clearTagsList();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_sortRssi) {
+ fragment1.sortTagsListByRssi();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_sort) {
+ fragment1.sortTagsList();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_save) {
+ fragment1.saveTagsList();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_share) {
+ fragment1.shareTagsList();
+ return true;
+ } else return super.onOptionsItemSelected(item);
+ }
+
+ @Override
+ public void onActivityCreated(Bundle savedInstanceState) {
+ super.onActivityCreated(savedInstanceState);
+
+ actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
+ actionBar.setIcon(R.drawable.dl_inv);
+ actionBar.setTitle(R.string.title_activity_auraSense);
+
+ TabLayout tabLayout = (TabLayout) getActivity().findViewById(R.id.OperationsTabLayout);
+
+ mAdapter = new AuraSenseAdapter(getActivity().getSupportFragmentManager());
+ viewPager = (ViewPager) getActivity().findViewById(R.id.OperationsPager);
+ viewPager.setAdapter(mAdapter);
+ viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
+
+ for (String tab_name : tabs) {
+ tabLayout.addTab(tabLayout.newTab().setText(tab_name));
+ }
+
+ tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
+ @Override
+ public void onTabSelected(TabLayout.Tab tab) {
+ viewPager.setCurrentItem(tab.getPosition());
+ }
+
+ @Override
+ public void onTabUnselected(TabLayout.Tab tab) {
+ }
+
+ @Override
+ public void onTabReselected(TabLayout.Tab tab) {
+ }
+ });
+ }
+
+ @Override
+ public void onPause() {
+ mAdapter.fragment0.onPause();
+ mAdapter.fragment1.onPause();
+ super.onPause();
+ }
+
+ @Override
+ public void onStop() {
+ mAdapter.fragment0.onStop();
+ mAdapter.fragment1.onStop();
+ super.onStop();
+ }
+
+ @Override
+ public void onDestroyView() {
+ mAdapter.fragment0.onDestroyView();
+ mAdapter.fragment1.onDestroyView();
+ super.onDestroyView();
+ }
+
+ @Override
+ public void onDestroy() {
+ mAdapter.fragment0.onDestroy();
+ mAdapter.fragment1.onDestroy();
+ MainActivity.csLibrary4A.setSelectCriteriaDisable(-1);
+ MainActivity.csLibrary4A.setSameCheck(true);
+ MainActivity.csLibrary4A.restoreAfterTagSelect();
+ super.onDestroy();
+ }
+
+ @Override
+ public void onDetach() {
+ mAdapter.fragment0.onDetach();
+ mAdapter.fragment1.onDetach();
+ super.onDetach();
+ }
+
+ public AuraSenseFragment() {
+ super("AuraSenseFragment");
+ }
+
+ class AuraSenseAdapter extends FragmentStatePagerAdapter {
+ private final int NO_OF_TABS = 2;
+ public Fragment fragment0, fragment1, fragment2;
+
+ @Override
+ public Fragment getItem(int index) {
+ Fragment fragment = null;
+ switch (index) {
+ case 0:
+ fragment = new AccessAuraSenseFragment();
+ fragment0 = fragment;
+ break;
+ default:
+ fragment = InventoryRfidiMultiFragment.newInstance(true, TAG_EM_AURASENSE, "E280B12");
+ fragment1 = fragment;
+ break;
+ }
+ return fragment;
+ }
+
+ @Override
+ public int getCount() {
+ return NO_OF_TABS;
+ }
+
+ @Override
+ public int getItemPosition(Object object) {
+ return PagerAdapter.POSITION_NONE;
+ }
+
+ public AuraSenseAdapter(FragmentManager fm) {
+ super(fm);
+ }
+ }
+}
+
+
+
+package com.csl.cs710ademoapp.fragments;
+
+import androidx.lifecycle.Lifecycle;
+import android.os.Bundle;
+
+import com.csl.cslibrary4a.AdapterTab;
+import com.google.android.material.tabs.TabLayout;
+import androidx.viewpager.widget.ViewPager;
+import androidx.appcompat.app.ActionBar;
+import androidx.appcompat.app.AppCompatActivity;
+import android.view.LayoutInflater;
+import android.view.MenuItem;
+import android.view.View;
+import android.view.ViewGroup;
+
+import com.csl.cs710ademoapp.MainActivity;
+import com.csl.cs710ademoapp.R;
+
+public class AxzonFragment extends CommonFragment {
+ private ActionBar actionBar;
+ private ViewPager viewPager;
+ AdapterTab adapter;
+
+ private String[] tabs = { "Scan/Select", "Read" };
+ private String[] tabsXerxes0 = { "Logger" };
+ private String[] tabsXerxes = { "Logger", "Security" };
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ super.onCreateView(inflater, container, savedInstanceState, true);
+ return inflater.inflate(R.layout.custom_tabbed_layout, container, false);
+ }
+
+ @Override
+ public boolean onOptionsItemSelected(MenuItem item) {
+ InventoryRfidiMultiFragment fragment = (InventoryRfidiMultiFragment) adapter.fragment0;
+ if (item.getItemId() == R.id.menuAction_clear) {
+ fragment.clearTagsList();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_sortRssi) {
+ fragment.sortTagsListByRssi();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_sort) {
+ fragment.sortTagsList();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_save) {
+ fragment.saveTagsList();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_share) {
+ fragment.shareTagsList();
+ return true;
+ } else return super.onOptionsItemSelected(item);
+ }
+
+ @Override
+ public void onActivityCreated(Bundle savedInstanceState) {
+ super.onActivityCreated(savedInstanceState);
+
+ actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
+ actionBar.setIcon(R.drawable.dl_inv);
+ MainActivity.csLibrary4A.appendToLog("MainActivity.mDid = " + MainActivity.mDid);
+ if (false) actionBar.setTitle(R.string.title_activity_axzon);
+ else {
+ String stringTitle = getResources().getString(R.string.title_activity_axzon);
+ if (MainActivity.mDid.matches("E282402")) stringTitle = "S2";
+ else if (MainActivity.mDid.matches("E282403")) stringTitle = "S3";
+ if (MainActivity.mDid.matches("E282405")) stringTitle = "Xerxes";
+ actionBar.setTitle(stringTitle);
+ }
+
+ boolean bXervesTag = false;
+ if (MainActivity.mDid != null) if (MainActivity.mDid.matches("E282405")) bXervesTag = true;
+
+ TabLayout tabLayout = (TabLayout) getActivity().findViewById(R.id.OperationsTabLayout);
+
+ adapter = new AdapterTab(getActivity().getSupportFragmentManager(), (bXervesTag ? 4 : 2));
+ adapter.setFragment(0, InventoryRfidiMultiFragment.newInstance(true, null, ""));
+ adapter.setFragment(1, AccessMicronFragment.newInstance(true));
+ adapter.setFragment(2, new AccessXerxesLoggerFragment());
+ adapter.setFragment(3, new AccessUcodeFragment());
+
+ viewPager = (ViewPager) getActivity().findViewById(R.id.OperationsPager);
+ viewPager.setAdapter(adapter);
+ viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
+
+ for (String tab_name : tabs) {
+ tabLayout.addTab(tabLayout.newTab().setText(tab_name));
+ }
+ if (bXervesTag) {
+ if (MainActivity.csLibrary4A.get98XX() == 2 && MainActivity.csLibrary4A.getMacVer().indexOf("1.2") != 0) {
+ for (String tab_name : tabsXerxes0) {
+ tabLayout.addTab(tabLayout.newTab().setText(tab_name));
+ }
+ } else {
+ for (String tab_name : tabsXerxes) {
+ tabLayout.addTab(tabLayout.newTab().setText(tab_name));
+ }
+ }
+ }
+
+ tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
+ @Override
+ public void onTabSelected(TabLayout.Tab tab) {
+ viewPager.setCurrentItem(tab.getPosition());
+ }
+
+ @Override
+ public void onTabUnselected(TabLayout.Tab tab) {
+ }
+
+ @Override
+ public void onTabReselected(TabLayout.Tab tab) {
+ }
+ });
+
+ MainActivity.csLibrary4A.setBasicCurrentLinkProfile();
+ }
+
+ @Override
+ public void onPause() {
+ if (adapter.fragment0 != null) if (adapter.fragment0.getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.RESUMED)) adapter.fragment0.onPause();
+ if (adapter.fragment1 != null) if (adapter.fragment1.getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.RESUMED)) adapter.fragment1.onPause();
+ if (adapter.fragment2 != null) if (adapter.fragment2.getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.RESUMED)) adapter.fragment2.onPause();
+ if (adapter.fragment3 != null) if (adapter.fragment3.getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.RESUMED)) adapter.fragment3.onPause();
+ super.onPause();
+ }
+
+ @Override
+ public void onStop() {
+ if (adapter.fragment0 != null) if (adapter.fragment0.getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.RESUMED)) adapter.fragment0.onStop();
+ if (adapter.fragment1 != null) if (adapter.fragment1.getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.RESUMED)) adapter.fragment1.onStop();
+ if (adapter.fragment2 != null) if (adapter.fragment2.getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.RESUMED)) adapter.fragment2.onStop();
+ if (adapter.fragment3 != null) if (adapter.fragment3.getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.RESUMED)) adapter.fragment3.onStop();
+ super.onStop();
+ }
+
+ @Override
+ public void onDestroyView() {
+ if (adapter.fragment0 != null) if (adapter.fragment0.getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.RESUMED)) adapter.fragment0.onDestroyView();
+ if (adapter.fragment1 != null) if (adapter.fragment1.getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.RESUMED)) adapter.fragment1.onDestroyView();
+ if (adapter.fragment2 != null) if (adapter.fragment2.getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.RESUMED)) adapter.fragment2.onDestroyView();
+ if (adapter.fragment3 != null) if (adapter.fragment3.getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.RESUMED)) adapter.fragment3.onDestroyView();
+ super.onDestroyView();
+ }
+
+ @Override
+ public void onDestroy() {
+ if (adapter.fragment0 != null) if (adapter.fragment0.getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.RESUMED)) adapter.fragment0.onDestroy();
+ if (adapter.fragment1 != null) if (adapter.fragment1.getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.RESUMED)) adapter.fragment1.onDestroy();
+ if (adapter.fragment2 != null) if (adapter.fragment2.getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.RESUMED)) adapter.fragment2.onDestroy();
+ if (adapter.fragment3 != null) if (adapter.fragment3.getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.RESUMED)) adapter.fragment3.onDestroy();
+ if (MainActivity.selectFor != -1) {
+ MainActivity.csLibrary4A.setSelectCriteriaDisable(-1);
+ MainActivity.selectFor = -1;
+ }
+ MainActivity.csLibrary4A.restoreAfterTagSelect();
+ super.onDestroy();
+ }
+
+ @Override
+ public void onDetach() {
+ if (adapter.fragment0 != null) if (adapter.fragment0.getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.RESUMED)) adapter.fragment0.onDetach();
+ if (adapter.fragment1 != null) if (adapter.fragment1.getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.RESUMED)) adapter.fragment1.onDetach();
+ if (adapter.fragment2 != null) if (adapter.fragment2.getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.RESUMED)) adapter.fragment2.onDetach();
+ if (adapter.fragment3 != null) if (adapter.fragment3.getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.RESUMED)) adapter.fragment3.onDetach();
+ super.onDetach();
+ }
+
+ public AxzonFragment() { super("AxzonFragment"); }
+}
+
+
+
+package com.csl.cs710ademoapp.fragments;
+
+import static com.csl.cslibrary4a.RfidReader.TagType.TAG_AXZON;
+import static com.csl.cslibrary4a.RfidReader.TagType.TAG_MAGNUS_S2;
+import static com.csl.cslibrary4a.RfidReader.TagType.TAG_MAGNUS_S3;
+import static com.csl.cslibrary4a.RfidReader.TagType.TAG_AXZON_XERXES;
+
+import android.os.Bundle;
+import androidx.fragment.app.Fragment;
+import androidx.fragment.app.FragmentManager;
+import androidx.fragment.app.FragmentTransaction;
+import androidx.appcompat.app.ActionBar;
+import androidx.appcompat.app.AppCompatActivity;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.Button;
+
+import com.csl.cs710ademoapp.MainActivity;
+import com.csl.cs710ademoapp.R;
+
+public class AxzonSelectorFragment extends CommonFragment {
+ boolean bXerxesEnable = false;
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ super.onCreateView(inflater, container, savedInstanceState, true);
+ return inflater.inflate(R.layout.fragment_select_axzon, container, false);
+ }
+
+ @Override
+ public void onActivityCreated(Bundle savedInstanceState) {
+ super.onActivityCreated(savedInstanceState);
+
+ if (((AppCompatActivity) getActivity()).getSupportActionBar() != null) {
+ ActionBar actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
+ actionBar.setTitle(R.string.title_activity_axzonSelector);
+ }
+
+ Button button_s2 = (Button) getActivity().findViewById(R.id.select_axzon_s2);
+ button_s2.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ gotoAxzonFragment(2);
+ }
+ });
+ Button button_s3 = (Button) getActivity().findViewById(R.id.select_axzon_s3);
+ button_s3.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ gotoAxzonFragment(3);
+ }
+ });
+ Button button_xx = (Button) getActivity().findViewById(R.id.select_axzon_xx);
+ button_xx.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ gotoAxzonFragment(5);
+ }
+ });
+ Button button_all = (Button) getActivity().findViewById(R.id.select_axzon_all);
+ button_all.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ gotoAxzonFragment(0);
+ }
+ });
+ if (bXerxesEnable == false) {
+ button_xx.setVisibility(View.GONE);
+ button_all.setText("All Magnus");
+ }
+ }
+
+ public static AxzonSelectorFragment newInstance(boolean bXerxesEnable) {
+ AxzonSelectorFragment myFragment = new AxzonSelectorFragment();
+ myFragment.bXerxesEnable = bXerxesEnable;
+ return myFragment;
+ }
+ public AxzonSelectorFragment() {
+ super("AxzonSelectorFragment");
+ }
+
+ void gotoAxzonFragment(int tagType) {
+ switch(tagType) {
+ case 2:
+ MainActivity.tagType = TAG_MAGNUS_S2; MainActivity.mDid = "E282402";
+ break;
+ case 3:
+ MainActivity.tagType = TAG_MAGNUS_S3; MainActivity.mDid = "E282403";
+ break;
+ case 5:
+ MainActivity.tagType = TAG_AXZON_XERXES; MainActivity.mDid = "E282405";
+ break;
+ default:
+ MainActivity.tagType = TAG_AXZON; MainActivity.mDid = "E2824";
+ break;
+ }
+ MainActivity.csLibrary4A.appendToLog("HelloABC: gotoAxzonFragment with tagType = " + tagType + ", MainActivity.mDid = " + MainActivity.mDid);
+
+ MainActivity.csLibrary4A.appendToLog("HelloABC: config is " + (MainActivity.config == null ? "null" : "Valid"));
+ MainActivity.config.configPassword = "00000000";
+ MainActivity.config.configPower = Integer.toString(300);
+ MainActivity.config.config0 = Integer.toString(9);
+ MainActivity.config.config1 = Integer.toString(21);
+ MainActivity.config.config2 = Integer.toString(13);
+ if (tagType == 2) MainActivity.config.config3 = Integer.toString(13);
+ else MainActivity.config.config3 = Integer.toString(160);
+
+ if (true) {
+ Fragment fragment;
+ if (bXerxesEnable) fragment = new AxzonFragment();
+ else fragment = new MicronFragment();
+
+ FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
+ FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
+ fragmentTransaction.replace(R.id.content_frame, fragment);
+ fragmentTransaction.addToBackStack(null);
+ fragmentTransaction.commit();
+ } else {
+ Fragment fragment = AccessConfigFragment.newInstance(bXerxesEnable);
+ FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
+ FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
+ fragmentTransaction.replace(R.id.content_frame, fragment);
+ fragmentTransaction.addToBackStack(null);
+ fragmentTransaction.commit();
+ }
+ }
+}
+
+
+
+package com.csl.cs710ademoapp.fragments;
+
+import static com.csl.cslibrary4a.RfidReader.TagType.TAG_EM_COLDCHAIN;
+
+import android.os.Bundle;
+import android.view.LayoutInflater;
+import android.view.MenuItem;
+import android.view.View;
+import android.view.ViewGroup;
+
+import androidx.appcompat.app.ActionBar;
+import androidx.appcompat.app.AppCompatActivity;
+import androidx.viewpager.widget.ViewPager;
+
+import com.csl.cs710ademoapp.MainActivity;
+import com.csl.cs710ademoapp.R;
+import com.csl.cslibrary4a.AdapterTab;
+import com.google.android.material.tabs.TabLayout;
+
+public class ColdChainFragment extends CommonFragment {
+ private ActionBar actionBar;
+ private ViewPager viewPager;
+ AdapterTab adapter;
+
+ private String[] tabs = {"Select Tag", "Logging", "One-shot"};
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ super.onCreateView(inflater, container, savedInstanceState, true);
+ return inflater.inflate(R.layout.custom_tabbed_layout, container, false);
+ }
+
+ @Override
+ public boolean onOptionsItemSelected(MenuItem item) {
+ InventoryRfidiMultiFragment fragment1 = (InventoryRfidiMultiFragment) adapter.fragment0;
+ if (item.getItemId() == R.id.menuAction_clear) {
+ fragment1.clearTagsList();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_sortRssi) {
+ fragment1.sortTagsListByRssi();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_sort) {
+ fragment1.sortTagsList();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_save) {
+ fragment1.saveTagsList();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_share) {
+ fragment1.shareTagsList();
+ return true;
+ } else return super.onOptionsItemSelected(item);
+ }
+
+ @Override
+ public void onActivityCreated(Bundle savedInstanceState) {
+ super.onActivityCreated(savedInstanceState);
+
+ actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
+ actionBar.setIcon(R.drawable.dl_inv);
+ actionBar.setTitle(R.string.title_activity_coldChain);
+
+ TabLayout tabLayout = (TabLayout) getActivity().findViewById(R.id.OperationsTabLayout);
+
+ adapter = new AdapterTab(getActivity().getSupportFragmentManager(), tabs.length);
+ adapter.setFragment(0, InventoryRfidiMultiFragment.newInstance(true, TAG_EM_COLDCHAIN, "E280B0"));
+ adapter.setFragment(1, new AccessColdChainFragment());
+ adapter.setFragment(2, new AccessEm4325PassiveFragment());
+
+ viewPager = (ViewPager) getActivity().findViewById(R.id.OperationsPager);
+ viewPager.setAdapter(adapter);
+ viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
+
+ for (int i = 0; i < tabs.length; i++) {
+ if (MainActivity.csLibrary4A.get98XX() == 2 && i == tabs.length -1) break;;
+ String tab_name = tabs[i];
+ tabLayout.addTab(tabLayout.newTab().setText(tab_name));
+ }
+
+ tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
+ @Override
+ public void onTabSelected(TabLayout.Tab tab) {
+ viewPager.setCurrentItem(tab.getPosition());
+ }
+
+ @Override
+ public void onTabUnselected(TabLayout.Tab tab) {
+ }
+
+ @Override
+ public void onTabReselected(TabLayout.Tab tab) {
+ }
+ });
+ }
+
+ @Override
+ public void onPause() {
+ if (adapter.fragment0 != null) adapter.fragment0.onPause();
+ if (adapter.fragment1 != null) adapter.fragment1.onPause();
+ if (adapter.fragment2 != null) adapter.fragment2.onPause();
+ super.onPause();
+ }
+
+ @Override
+ public void onStop() {
+ if (adapter.fragment0 != null) adapter.fragment0.onStop();
+ if (adapter.fragment1 != null) adapter.fragment1.onStop();
+ if (adapter.fragment2 != null) adapter.fragment2.onStop();
+ super.onStop();
+ }
+
+ @Override
+ public void onDestroyView() {
+ if (adapter.fragment0 != null) adapter.fragment0.onDestroyView();
+ if (adapter.fragment1 != null) adapter.fragment1.onDestroyView();
+ if (adapter.fragment2 != null) adapter.fragment2.onDestroyView();
+ super.onDestroyView();
+ }
+
+ @Override
+ public void onDestroy() {
+ if (adapter.fragment0 != null) adapter.fragment0.onDestroy();
+ if (adapter.fragment1 != null) adapter.fragment1.onDestroy();
+ if (adapter.fragment2 != null) adapter.fragment2.onDestroy();
+ super.onDestroy();
+ }
+
+ @Override
+ public void onDetach() {
+ if (adapter.fragment0 != null) adapter.fragment0.onDetach();
+ if (adapter.fragment1 != null) adapter.fragment1.onDetach();
+ if (adapter.fragment2 != null) adapter.fragment2.onDetach();
+ super.onDetach();
+ }
+
+ public ColdChainFragment() {
+ super("ColdChainFragment");
+ }
+}
+
+
+
+package com.csl.cs710ademoapp.fragments;
+
+import android.app.Activity;
+import android.content.Context;
+import android.graphics.Color;
+import android.os.Bundle;
+import android.os.Handler;
+import android.text.SpannableString;
+import android.text.style.ForegroundColorSpan;
+import android.util.Log;
+import android.view.LayoutInflater;
+import android.view.Menu;
+import android.view.MenuInflater;
+import android.view.MenuItem;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.Toast;
+
+import androidx.appcompat.app.ActionBar;
+import androidx.appcompat.app.AppCompatActivity;
+import androidx.fragment.app.Fragment;
+
+import com.csl.cs710ademoapp.CustomAlertDialog;
+import com.csl.cs710ademoapp.CustomPopupWindow;
+import com.csl.cs710ademoapp.MainActivity;
+import com.csl.cs710ademoapp.R;
+
+public abstract class CommonFragment extends Fragment {
+ final boolean DEBUG = false; final String TAG = "Hello";
+ private String fragmentName;
+ MenuItem menuTriggerItem, menuBatteryVoltageItem;
+ Handler mHandler = new Handler();
+ boolean fragmentActive = false;
+
+ @Override
+ public void onAttach(Context context) {
+ if (DEBUG) {
+ if (fragmentName == null) Log.i(TAG, "CommonFragment.onAttach: NULL fragmentName");
+ else Log.i(TAG, "CommonFragment.onAttach: fragmentName = " + fragmentName);
+ if (MainActivity.csLibrary4A == null) Log.i(TAG, "CommonFragment.onAttach: NULL MainActivity.csLibrary4a");
+ if (fragmentName == null) MainActivity.csLibrary4A.appendToLog("NULL fragmentName");
+ MainActivity.csLibrary4A.appendToLog(fragmentName);
+ }
+ super.onAttach(context);
+ }
+
+ @Override
+ public void onCreate(Bundle savedInstanceState) {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog(fragmentName);
+ super.onCreate(savedInstanceState);
+ }
+
+ boolean menuFragment = false;
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState, boolean menuFragment) {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog(fragmentName);
+ this.menuFragment = menuFragment;
+
+ bleConnected = false; if (MainActivity.csLibrary4A.isBleConnected()) bleConnected = true;
+ rfidFailure = false; if (MainActivity.csLibrary4A.isRfidFailure()) rfidFailure = true;
+ ActionBar actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
+ boolean bHomeAsUpEnabled = true;
+ if (fragmentName.matches("HomeFragment")) bHomeAsUpEnabled = false;
+ if (fragmentName.matches("HomeWFragment")) bHomeAsUpEnabled = false;
+ actionBar.setDisplayHomeAsUpEnabled(bHomeAsUpEnabled);
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("CommonFragment: onCreateView with fragmentName = " + fragmentName + " , onOptionsItemSelected = " + menuFragment + ", DisplayHomeAsUpEnabled = " + bHomeAsUpEnabled);
+
+ if (menuFragment) setHasOptionsMenu(true);
+ return super.onCreateView(inflater, container, savedInstanceState);
+ }
+
+ int triggerCount_old;
+ private final Runnable updateTriggerRunnable = new Runnable() {
+ @Override
+ public void run() {
+ short reportCount = 5;
+ if (MainActivity.csLibrary4A.isBleConnected()) {
+ byte[] notificationData = MainActivity.csLibrary4A.onNotificationEvent();
+ if (false && notificationData != null) {
+ MainActivity.csLibrary4A.appendToLog("2 matched Error: " + MainActivity.csLibrary4A.byteArrayToString(notificationData));
+ CustomPopupWindow customPopupWindow = new CustomPopupWindow(MainActivity.mContext);
+ customPopupWindow.popupStart("Common Notification Error Code A101: " + MainActivity.csLibrary4A.byteArrayToString(notificationData), false);
+ }
+ reportCount = MainActivity.csLibrary4A.getTriggerReportingCount();
+ }
+
+ mHandler.postDelayed(updateTriggerRunnable, reportCount * 1100);
+ if (menuTriggerItem == null) return;
+ if (MainActivity.csLibrary4A.isBleConnected() == false) { menuTriggerItem.setTitle(""); return; }
+
+ int triggerCount = MainActivity.csLibrary4A.getTriggerCount();
+ if (triggerCount != triggerCount_old) {
+ triggerCount_old = triggerCount;
+ if (MainActivity.csLibrary4A.getTriggerButtonStatus()) menuTriggerItem.setTitle("Ton");
+ else menuTriggerItem.setTitle("Toff");
+ } else menuTriggerItem.setTitle("");
+ }
+ };
+
+ boolean bleDisConnecting = false;
+ boolean bleConnected = false, rfidFailure = false;
+ int batteryCount_old; boolean batteryUpdate = false; CustomPopupWindow batteryWarningPopupWindow; String strBatteryLow;
+ private final Runnable updateBatteryRunnable = new Runnable() {
+ @Override
+ public void run() {
+ mHandler.postDelayed(updateBatteryRunnable, 5000); //normal battery level updates every 4 seconds
+
+ if (menuBatteryVoltageItem == null) return;
+ if (MainActivity.csLibrary4A.isBleConnected() == false) {
+ if (bleDisConnecting) bleConnected = false; bleDisConnecting = true;
+ if (bleConnected) {
+ bleConnected = false; if (DEBUG) MainActivity.csLibrary4A.appendToLog("bleConnected is FALSE in " + fragmentName);
+ if (false) Toast.makeText(MainActivity.mContext, "Bluetooth is disconnected", Toast.LENGTH_SHORT).show();
+ else {
+ CustomAlertDialog appdialog = new CustomAlertDialog();
+ appdialog.Confirm((Activity) MainActivity.mContext, "Bluetooth is DISCONNECTED",
+ "Do you want to reconnect the Bluetooth ?",
+ "No thanks", "Reconnect",
+ new Runnable() {
+ @Override
+ public void run() {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("Confirm is pressed");
+ MainActivity.csLibrary4A.connect(null);
+ }
+ },
+ new Runnable() {
+ @Override
+ public void run() {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("Cancel is pressed.");
+ }
+ });
+ }
+ } else if (DEBUG) MainActivity.csLibrary4A.appendToLog("bleConnected is Kept as FALSE in " + fragmentName);
+ MainActivity.sharedObjects.batteryWarningShown = 0; menuBatteryVoltageItem.setTitle("");
+ return;
+ } else {
+ bleConnected = true;
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("bleConnected is TRUE in " + fragmentName);
+ }
+
+ if (MainActivity.csLibrary4A.isRfidFailure()) {
+ if (rfidFailure == false) {
+ rfidFailure = true;
+ if (false) {
+ CustomAlertDialog appdialog = new CustomAlertDialog();
+ appdialog.Confirm((Activity) MainActivity.mContext, "Rfid Transmission failure",
+ "Do you want to disconnect the Bluetooth ?",
+ "No thanks", "Disconnect",
+ new Runnable() {
+ @Override
+ public void run() {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("Confirm is pressed");
+ MainActivity.csLibrary4A.forceBTdisconnect();
+ }
+ },
+ new Runnable() {
+ @Override
+ public void run() {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("Cancel is pressed.");
+ }
+ });
+ }
+ }
+ } else {
+ rfidFailure = false;
+ }
+
+ int batteryCount = MainActivity.csLibrary4A.getBatteryCount();
+ String strText = MainActivity.csLibrary4A.getBatteryDisplay(false);
+ if (batteryCount_old != batteryCount) strBatteryLow = MainActivity.csLibrary4A.isBatteryLow();
+
+ if (strBatteryLow == null) MainActivity.sharedObjects.batteryWarningShown = 0;
+ else if (++MainActivity.sharedObjects.batteryWarningShown == 1) {
+ if (batteryWarningPopupWindow != null)
+ batteryWarningPopupWindow.popupWindow.dismiss();
+ batteryWarningPopupWindow = new CustomPopupWindow(MainActivity.mContext);
+ batteryWarningPopupWindow.popupStart(strBatteryLow + "% Battery Life Left, Please Recharge CSL Reader or Replace with Freshly Charged CSL Reader battery", false);
+ } else if (false && MainActivity.sharedObjects.batteryWarningShown > 10) MainActivity.sharedObjects.batteryWarningShown = 0;
+
+ if (batteryCount_old == batteryCount && strText.length() != 0) {
+ if (batteryUpdate) strText = "B" + strText;
+ else strText = "A" + strText;
+ batteryUpdate = !batteryUpdate;
+ menuBatteryVoltageItem.setTitle(strText);
+ MainActivity.csLibrary4A.batteryLevelRequest();
+ } else {
+ batteryCount_old = batteryCount;
+ SpannableString spanString = new SpannableString(strText);
+ spanString.setSpan(new ForegroundColorSpan(Color.RED), 0, spanString.length(), 0); //fix the color to white
+ if (false || strBatteryLow != null) menuBatteryVoltageItem.setTitle(spanString);
+ else menuBatteryVoltageItem.setTitle(strText);
+ }
+ }
+ };
+
+ @Override
+ public void onActivityCreated(Bundle savedInstanceState) {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog(fragmentName);
+ super.onActivityCreated(savedInstanceState);
+ }
+
+ @Override
+ public void onViewStateRestored(Bundle savedInstanceState) {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog(fragmentName);
+ super.onViewStateRestored(savedInstanceState);
+ }
+
+ @Override
+ public void onStart() {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog(fragmentName);
+ super.onStart();
+ }
+
+ @Override
+ public void onResume() {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog(fragmentName);
+ if (menuFragment) {
+ batteryCount_old = -1;
+ mHandler.post(updateTriggerRunnable);
+ mHandler.post(updateBatteryRunnable);
+ }
+ super.onResume();
+ fragmentActive = true;
+ }
+
+ @Override
+ public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog(fragmentName + " with fragmentActive = " + fragmentActive);
+ if (fragmentActive == false) return;
+ if (fragmentName.matches("ConnectionFragment")) {
+ inflater.inflate(R.menu.menu_connection, menu);
+ if (MainActivity.csLibrary4A.isBleScanning()) {
+ menu.findItem(R.id.action_refresh).setActionView(R.layout.actionbar_indeterminate_progress);
+ } else {
+ menu.findItem(R.id.action_refresh).setActionView(null);
+ }
+ } else {
+ inflater.inflate(R.menu.menu_home, menu);
+ menuBatteryVoltageItem = menu.findItem(R.id.home_voltage);;
+ menuTriggerItem = menu.findItem(R.id.home_trigger);
+ menu.removeItem(R.id.home_menu);
+ if (fragmentName.matches("InventoryFragment")
+ || fragmentName.contains("InventoryRfidiMultiFragment")
+ || fragmentName.contains("InventoryRfidSimpleFragment")
+
+ || fragmentName.contains("ImpinjFragment")
+ || fragmentName.contains("Ucode8Fragment")
+ || fragmentName.contains("UcodeFragment")
+ || fragmentName.contains("ColdChainFragment")
+ || fragmentName.contains("AuraSenseFragment")
+ || fragmentName.contains("AxzonFragment")
+ || fragmentName.contains("MicronFragment")
+ || fragmentName.contains("FdmicroFragment")
+ || fragmentName.contains("LedTagFragment")
+
+ || fragmentName.contains("InventoryRfidSimpleFragment")
+ ) {
+ menu.findItem(R.id.menuAction_clear).setTitle("Clear");
+ menu.findItem(R.id.menuAction_save).setTitle("Save");
+ menu.findItem(R.id.menuAction_share).setTitle("Share");
+ menu.findItem(R.id.menuAction_share).setIcon(android.R.drawable.ic_menu_share);
+ if (fragmentName.contains("InventoryBarcodeFragment")) {
+ menu.removeItem(R.id.menuAction_sort);
+ menu.removeItem(R.id.menuAction_sortRssi);
+ } else {
+ menu.findItem(R.id.menuAction_sort).setTitle("Sort by EPC");
+ menu.findItem(R.id.menuAction_sortRssi).setTitle("Sort by Rssi");
+ }
+ } else {
+ menu.removeItem(R.id.menuAction_clear);
+ menu.removeItem(R.id.menuAction_save);
+ menu.removeItem(R.id.menuAction_share);
+ menu.removeItem(R.id.menuAction_sort);
+ menu.removeItem(R.id.menuAction_sortRssi);
+ }
+ }
+ }
+
+ @Override
+ public boolean onOptionsItemSelected(MenuItem item) {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("CommonFragment: onOptionsItemSelected");
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog(fragmentName + " with fragmentActive = " + fragmentActive);
+ if (fragmentActive == false) return false;
+ switch (item.getItemId()) {
+ case android.R.id.home:
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("CommonFragment: onOptionsItemSelected: getActivity().onBackPressed");
+ getActivity().onBackPressed();
+ return true;
+ default:
+ return super.onOptionsItemSelected(item);
+ }
+ }
+
+ @Override
+ public void onPause() {
+ fragmentActive = false;
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog(fragmentName);
+ super.onPause();
+ }
+
+ @Override
+ public void onStop() {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog(fragmentName);
+ mHandler.removeCallbacks(updateTriggerRunnable);
+ mHandler.removeCallbacks(updateBatteryRunnable);
+ super.onStop();
+ }
+
+ @Override
+ public void onDestroyView() {
+ if (false) MainActivity.csLibrary4A.appendToLog(fragmentName);
+ super.onDestroyView();
+ }
+
+ @Override
+ public void onDestroy() {
+ if (DEBUG && MainActivity.csLibrary4A != null) MainActivity.csLibrary4A.appendToLog(fragmentName);
+ super.onDestroy();
+ }
+
+ @Override
+ public void onDetach() {
+ if (DEBUG && MainActivity.csLibrary4A != null) MainActivity.csLibrary4A.appendToLog(fragmentName);
+ super.onDetach();
+ }
+
+ CommonFragment(String text) {
+ fragmentName = text;
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog(",,," + fragmentName);
+ }
+}
+
+
+
+package com.csl.cs710ademoapp.fragments;
+
+import android.Manifest;
+import android.bluetooth.BluetoothAdapter;
+import android.bluetooth.BluetoothDevice;
+import android.bluetooth.le.ScanCallback;
+import android.content.pm.PackageManager;
+import android.os.AsyncTask;
+import android.os.Build;
+import android.os.Bundle;
+import android.os.Handler;
+
+import androidx.appcompat.app.ActionBar;
+import androidx.appcompat.app.AppCompatActivity;
+import androidx.core.app.ActivityCompat;
+
+import android.os.ParcelUuid;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.AdapterView;
+import android.widget.ListView;
+import android.widget.TextView;
+import android.widget.Toast;
+
+import com.csl.cs710ademoapp.CustomProgressDialog;
+import com.csl.cs710ademoapp.MainActivity;
+import com.csl.cs710ademoapp.R;
+import com.csl.cslibrary4a.BluetoothGatt;
+import com.csl.cslibrary4a.ReaderDevice;
+import com.csl.cs710ademoapp.adapters.ReaderListAdapter;
+
+import java.util.ArrayList;
+
+public class ConnectionFragment extends CommonFragment {
+ private DeviceScanTask deviceScanTask;
+ private ReaderListAdapter readerListAdapter;
+ private BluetoothAdapter.LeScanCallback mLeScanCallback;
+ private ScanCallback mScanCallback;
+ private ArrayList readersList = MainActivity.sharedObjects.readersList;
+
+ private ArrayList mScanResultList = new ArrayList<>();
+ private Handler mHandler = new Handler();
+ private DeviceConnectTask deviceConnectTask;
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ super.onCreateView(inflater, container, savedInstanceState, true);
+ return inflater.inflate(R.layout.fragment_connection, container, false);
+ }
+
+ @Override
+ public void onActivityCreated(Bundle savedInstanceState) {
+ super.onActivityCreated(savedInstanceState);
+
+ ActionBar actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
+ actionBar.setIcon(R.drawable.dl_rdl);
+ actionBar.setTitle(R.string.title_activity_connection);
+
+ TextView textview = (TextView) getActivity().findViewById(R.id.connection_warning);
+ MainActivity.csLibrary4A.appendToLog("getActivity().getPackageName() = " + getActivity().getPackageName());
+ if (getActivity().getPackageName().contains("com.csl.cs710ademoapp")) textview.setVisibility(View.VISIBLE);
+
+ if (MainActivity.csLibrary4A.isBleConnected() == false) readersList.clear();
+ final ListView readerListView = (ListView) getActivity().findViewById(R.id.readersList);
+ TextView readerEmptyView = (TextView) getActivity().findViewById(R.id.empty);
+ readerListView.setEmptyView(readerEmptyView);
+ readerListAdapter = new ReaderListAdapter(getActivity(), R.layout.readers_list_item, readersList, true, true);
+ readerListView.setAdapter(readerListAdapter);
+ readerListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
+ readerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
+ boolean DEBUG = false;
+ @Override
+ public void onItemClick(AdapterView> parent, View view, int position, long id) {
+ if (bConnecting) return;
+
+ ReaderDevice readerDevice = readerListAdapter.getItem(position);
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("ConnectionFragment.OnItemClickListener: bConnecting = " + bConnecting + ", postion = " + position);
+ boolean bSelectOld = readerDevice.getSelected();
+
+ if (MainActivity.csLibrary4A.isBleConnected() && readerDevice.isConnected() && (readerDevice.getSelected() || false)) {
+ MainActivity.csLibrary4A.appendToLog("ConnectionFragment.onItemClick, Fragment: ");
+ MainActivity.csLibrary4A.disconnect(false); bleDisConnecting = true;
+ readersList.clear();
+ } else if (MainActivity.csLibrary4A.isBleConnected() == false && readerDevice.getSelected() == false) {
+ boolean validStart = false;
+ if (deviceConnectTask == null) {
+ validStart = true;
+ } else if (deviceConnectTask.getStatus() == AsyncTask.Status.FINISHED) {
+ validStart = true;
+ }
+ if (validStart) {
+ bConnecting = true;
+ if (deviceScanTask != null) deviceScanTask.cancel(true);
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("ConnectionFragment.OnItemClickListener: Connecting");
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
+ deviceConnectTask = new DeviceConnectTask(position, readerDevice, "Connecting with " + readerDevice.getName());
+ deviceConnectTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
+ } else {
+ deviceConnectTask = new DeviceConnectTask(position, readerDevice, "Connecting with " + readerDevice.getName());
+ deviceConnectTask.execute();
+ }
+ }
+ }
+
+ if (readersList.size() > position) {
+ if (readerDevice.getSelected()) readerDevice.setSelected(false);
+ else readerDevice.setSelected(true);
+ readersList.set(position, readerDevice);
+ for (int i = 0; i < readersList.size(); i++) {
+ if (i != position) {
+ ReaderDevice readerDevice1 = readersList.get(i);
+ if (readerDevice1.getSelected()) {
+ readerDevice1.setSelected(false);
+ readersList.set(i, readerDevice1);
+ }
+ }
+ }
+ }
+ readerListAdapter.notifyDataSetChanged();
+ }
+ });
+ if (MainActivity.csLibrary4A.isBleConnected() == false) {
+ for (int i = 0; i < readersList.size(); i++) {
+ ReaderDevice readerDevice1 = readersList.get(i);
+ if (readerDevice1.isConnected()) {
+ readerDevice1.setConnected(false);
+ readersList.set(i, readerDevice1);
+ }
+ }
+ }
+ readerListAdapter.notifyDataSetChanged();
+ }
+
+ @Override
+ public void onResume() {
+ mHandler.post(checkRunnable);
+ super.onResume();
+ }
+
+ @Override
+ public void onStop() {
+ mHandler.removeCallbacks(checkRunnable);
+ if (deviceScanTask != null) {
+ deviceScanTask.cancel(true);
+ }
+ if (deviceConnectTask != null) {
+ deviceConnectTask.cancel(true);
+ }
+ super.onStop();
+ }
+
+ public ConnectionFragment() {
+ super("ConnectionFragment");
+ }
+
+ private final Runnable checkRunnable = new Runnable() {
+ @Override
+ public void run() {
+ boolean operating = false;
+ if (MainActivity.csLibrary4A.isBleConnected()) operating = true;
+ if (operating == false && deviceScanTask != null) {
+ if (deviceScanTask.isCancelled() == false) operating = true;
+ }
+ if (operating == false && deviceConnectTask != null) {
+ if (deviceConnectTask.isCancelled() == false) operating = true;
+ }
+ if (operating == false) {
+ deviceScanTask = new DeviceScanTask();
+ deviceScanTask.execute();
+ }
+ mHandler.postDelayed(checkRunnable, 5000);
+ }
+ };
+
+ private class DeviceScanTask extends AsyncTask {
+ private long timeMillisUpdate = System.currentTimeMillis();
+ ArrayList readersListOld = new ArrayList();
+ boolean wait4process = false; boolean scanning = false, DEBUG = false;
+
+ @Override
+ protected String doInBackground(Void... a) {
+ while (isCancelled() == false) {
+ if (wait4process == false) {
+ BluetoothGatt.CsScanData csScanData = MainActivity.csLibrary4A.getNewDeviceScanned();
+ if (csScanData != null) mScanResultList.add(csScanData);
+ if (scanning == false || mScanResultList.size() != 0 || System.currentTimeMillis() - timeMillisUpdate > 10000) {
+ wait4process = true; publishProgress("");
+ }
+ }
+ }
+ return "End of Asynctask()";
+ }
+
+ @Override
+ protected void onProgressUpdate(String... output) {
+ if (scanning == false) {
+ scanning = true;
+ if (MainActivity.csLibrary4A.scanLeDevice(true) == false) cancel(true);
+ else getActivity().invalidateOptionsMenu();
+ }
+ boolean listUpdated = false;
+ while (mScanResultList.size() != 0) {
+ BluetoothGatt.CsScanData scanResultA = mScanResultList.get(0);
+ mScanResultList.remove(0);
+ if (getActivity() == null) continue;
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
+ if (ActivityCompat.checkSelfPermission(getActivity().getApplicationContext(), Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) continue;
+ } else if (ActivityCompat.checkSelfPermission(getActivity().getApplicationContext(), Manifest.permission.BLUETOOTH) != PackageManager.PERMISSION_GRANTED) continue;
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("scanResultA.device.getType() = " + scanResultA.device.getType() + ". scanResultA.rssi = " + scanResultA.rssi);
+ if (/*scanResultA.device.getType() == BluetoothDevice.DEVICE_TYPE_LE &&*/(true || scanResultA.rssi < 0)) {
+ boolean match = false;
+ for (int i = 0; i < readersList.size(); i++) {
+ String stringReaderAddress = readersList.get(i).getAddress();
+ String stringDeviceAddress = (scanResultA.device == null ? scanResultA.getAddress() : scanResultA.device.getAddress());
+ if (stringReaderAddress.matches(stringDeviceAddress)) {
+ ReaderDevice readerDevice1 = readersList.get(i);
+ int count = readerDevice1.getCount();
+ count++;
+ readerDevice1.setCount(count);
+ readerDevice1.setRssi(scanResultA.rssi);
+ readerDevice1.setServiceUUID2p1(scanResultA.serviceUUID2p2);
+ readersList.set(i, readerDevice1); listUpdated = true;
+ match = true;
+ break;
+ }
+ }
+ if (match == false) {
+ String name = scanResultA.getName(); //(scanResultA.device == null ? scanResultA.getName() : scanResultA.device.getName());
+ if (false) {
+ if (scanResultA.device != null && scanResultA.rssi == 0) {
+ BluetoothDevice bluetoothDevice = scanResultA.device;
+ ParcelUuid[] parcelUuids = bluetoothDevice.getUuids();
+ for (int k = 0; parcelUuids != null && k < parcelUuids.length; k++) {
+ name += (", " + parcelUuids[k].toString());
+ }
+ }
+ }
+ String address = (scanResultA.device == null ? scanResultA.getAddress() : scanResultA.device.getAddress());
+ ReaderDevice readerDevice = new ReaderDevice(name, address, false, "", 1, scanResultA.rssi, scanResultA.serviceUUID2p2);
+ String strInfo = "";
+ if (scanResultA.device != null && scanResultA.device.getBondState() == 12) {
+ strInfo += "BOND_BONDED\n";
+ }
+ readerDevice.setDetails(strInfo + "scanRecord=" + MainActivity.csLibrary4A.byteArrayToString(scanResultA.scanRecord));
+ readersList.add(readerDevice); listUpdated = true;
+ }
+ } else {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("deviceScanTask: rssi=" + scanResultA.rssi + ", error type=" + scanResultA.device.getType());
+ }
+ }
+ if (System.currentTimeMillis() - timeMillisUpdate > 10000) {
+ timeMillisUpdate = System.currentTimeMillis();
+ for (int i = 0; i < readersList.size(); i++) {
+ ReaderDevice readerDeviceNew = readersList.get(i);
+ boolean matched = false;
+ for (int k = 0; k < readersListOld.size(); k++) {
+ ReaderDevice readerDeviceOld = readersListOld.get(k);
+ if (readerDeviceOld.getAddress().matches(readerDeviceNew.getAddress())) {
+ matched = true;
+ if (readerDeviceOld.getCount() >= readerDeviceNew.getCount()) {
+ readersList.remove(i); listUpdated = true;
+ readersListOld.remove(k);
+ } else readerDeviceOld.setCount(readerDeviceNew.getCount());
+ break;
+ }
+ }
+ if (matched == false) {
+ ReaderDevice readerDevice1 = new ReaderDevice(null, readerDeviceNew.getAddress(), false, null, readerDeviceNew.getCount(), 0);
+ readersListOld.add(readerDevice1);
+ }
+ }
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("Matched. Updated readerListOld with size = " + readersListOld.size());
+ MainActivity.csLibrary4A.scanLeDevice(false);
+ getActivity().invalidateOptionsMenu();
+ scanning = false;
+ }
+ if (listUpdated) readerListAdapter.notifyDataSetChanged();
+ wait4process = false;
+ }
+
+ @Override
+ protected void onCancelled() {
+ super.onCancelled();
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("Stop Scanning 1A");
+ deviceScanEnding();
+ }
+
+ @Override
+ protected void onPostExecute(String result) {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("Stop Scanning 1B");
+ deviceScanEnding();
+ }
+
+ void deviceScanEnding() {
+ MainActivity.csLibrary4A.scanLeDevice(false);
+ }
+ }
+
+ long connectTimeMillis; boolean bConnecting = false;
+ private class DeviceConnectTask extends AsyncTask {
+ boolean DEBUG = false;
+ private int position;
+ private final ReaderDevice connectingDevice;
+ private String prgressMsg;
+ int waitTime;
+ private CustomProgressDialog progressDialog;
+ private int setting;
+
+ DeviceConnectTask(int position, ReaderDevice connectingDevice, String prgressMsg) {
+ this.position = position;
+ this.connectingDevice = connectingDevice;
+ this.prgressMsg = prgressMsg;
+ }
+
+ @Override
+ protected void onPreExecute() {
+ super.onPreExecute();
+
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("start of Connection with mrfidToWriteSize = " + MainActivity.csLibrary4A.mrfidToWriteSize());
+ MainActivity.csLibrary4A.connect(connectingDevice);
+ waitTime = 30;
+ setting = -1;
+ progressDialog = new CustomProgressDialog(getActivity(), prgressMsg);
+ progressDialog.show();
+ }
+
+ @Override
+ protected Integer doInBackground(Void... a) {
+ do {
+ try {
+ Thread.sleep(500);
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ publishProgress("kkk ");
+ if (MainActivity.csLibrary4A.isBleConnected()) {
+ setting = 0; break;
+ }
+ } while (--waitTime > 0);
+ if (progressDialog.isShowing())
+ progressDialog.dismiss();
+ if (setting != 0 || waitTime <= 0) {
+ cancel(true);
+ }
+ publishProgress("mmm ");
+ return waitTime;
+ }
+
+ @Override
+ protected void onProgressUpdate(String... output) {
+ }
+
+ @Override
+ protected void onCancelled(Integer result) {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("ConnectionFragment.deviceConnectTask: onCancelled(): setting = " + setting + ", waitTime = " + waitTime);
+ if (setting >= 0) {
+ Toast.makeText(getActivity().getApplicationContext(), getResources().getString(R.string.toast_ble_setup_problem), Toast.LENGTH_SHORT).show();
+ } else {
+ MainActivity.csLibrary4A.isBleConnected();
+ Toast.makeText(getActivity().getApplicationContext(), getResources().getString(R.string.error_bluetooth_connection_failed), Toast.LENGTH_SHORT).show();
+ }
+ super.onCancelled();
+ MainActivity.csLibrary4A.disconnect(false); bleDisConnecting = true;
+
+ bConnecting = false;
+ }
+
+ protected void onPostExecute(Integer result) {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("ConnectionFragment.deviceConnectTask: onPostExecute(): setting = " + setting + ", waitTime = " + waitTime);
+ ReaderDevice readerDevice = readersList.get(position);
+ readerDevice.setConnected(true);
+ readersList.set(position, readerDevice);
+ readerListAdapter.notifyDataSetChanged();
+
+ String connectedBleAddress = connectingDevice.getAddress();
+ if (connectedBleAddress.matches(MainActivity.sharedObjects.connectedBleAddressOld) == false) MainActivity.sharedObjects.versionWarningShown = false;
+ MainActivity.sharedObjects.connectedBleAddressOld = connectedBleAddress;
+ MainActivity.sharedObjects.barsList.clear();
+ MainActivity.sharedObjects.tagsList.clear();
+ MainActivity.sharedObjects.tagsIndexList.clear();
+
+ Toast.makeText(getActivity().getApplicationContext(), getResources().getString(R.string.toast_ble_connected), Toast.LENGTH_SHORT).show();
+
+ connectTimeMillis = System.currentTimeMillis();
+ super.onPostExecute(result);
+
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("ConnectionFragment: onPostExecute: getActivity().onBackPressed");
+ getActivity().onBackPressed();
+ bConnecting = false;
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("end of Connection with mrfidToWriteSize = " + MainActivity.csLibrary4A.mrfidToWriteSize());
+ }
+ }
+}
+
+
+
+package com.csl.cs710ademoapp.fragments;
+
+import static android.Manifest.permission.ACCESS_COARSE_LOCATION;
+import static android.Manifest.permission.ACCESS_FINE_LOCATION;
+import static android.Manifest.permission.BLUETOOTH;
+import static android.Manifest.permission.BLUETOOTH_CONNECT;
+import static android.Manifest.permission.BLUETOOTH_SCAN;
+import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
+import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
+import static android.content.Context.LOCATION_SERVICE;
+
+import static com.csl.cs710ademoapp.MainActivity.mContext;
+
+import android.content.Intent;
+import android.content.pm.PackageManager;
+import android.graphics.drawable.ColorDrawable;
+import android.location.LocationManager;
+import android.os.Build;
+import android.os.Bundle;
+import android.os.Handler;
+import android.os.IBinder;
+import android.provider.Settings;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.view.inputmethod.InputMethodInfo;
+import android.view.inputmethod.InputMethodManager;
+import android.view.inputmethod.InputMethodSubtype;
+import android.widget.AdapterView;
+import android.widget.Button;
+import android.widget.ListView;
+import android.widget.TableRow;
+import android.widget.TextView;
+import android.widget.Toast;
+
+import androidx.appcompat.app.ActionBar;
+import androidx.appcompat.app.AppCompatActivity;
+import androidx.core.app.ActivityCompat;
+
+import com.csl.cs710ademoapp.CustomPopupWindow;
+import com.csl.cs710ademoapp.DrawerListContent;
+import com.csl.cs710ademoapp.adapters.ReaderListAdapter;
+import com.csl.cs710ademoapp.MainActivity;
+import com.csl.cs710ademoapp.R;
+import com.csl.cs710ademoapp.CustomAlertDialog;
+import com.csl.cslibrary4a.BluetoothGatt;
+import com.csl.cslibrary4a.ReaderDevice;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public class DirectWedgeFragment extends CommonFragment {
+ Button buttonConnect;
+ private ArrayList readersList = MainActivity.sharedObjects.readersList;
+ Handler handler = new Handler();
+ private ReaderListAdapter readerListAdapter;
+ boolean bWedgeConnecting = false, bWedgeConnected = false;
+ boolean bCurrentIMEmatched = false;
+ String stringImeExpected, stringLabelExpected;
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ super.onCreateView(inflater, container, savedInstanceState, true);
+ return inflater.inflate(R.layout.fragment_directwedge, container, false);
+ }
+
+ @Override
+ public void onActivityCreated(Bundle savedInstanceState) {
+ super.onActivityCreated(savedInstanceState);
+
+ TableRow tableRow1 = getActivity().findViewById(R.id.directWedgeRow1);
+ TableRow tableRow2 = getActivity().findViewById(R.id.directWedgeRow2);
+ TableRow tableRow3 = getActivity().findViewById(R.id.directWedgeRow3);
+ TableRow tableRow4 = getActivity().findViewById(R.id.directWedgeRow4);
+ TableRow tableRow5 = getActivity().findViewById(R.id.directWedgeRow5);
+ TableRow tableRowStart = getActivity().findViewById(R.id.directWedgeRowStart);
+ MainActivity.csLibrary4A.appendToLog("getPackageName = " + getActivity().getPackageName());
+ if (getActivity().getPackageName().contains("cs710awedgeapp")) {
+ androidx.appcompat.app.ActionBar actionBar;
+ actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
+ actionBar.setIcon(R.drawable.dl_access);
+ ColorDrawable colorDrawable = new ColorDrawable(getResources().getColor(R.color.colorPrimary));
+ actionBar.setBackgroundDrawable(colorDrawable);
+ actionBar.setTitle(R.string.app_ime_simplewedge1);
+ actionBar.setDisplayHomeAsUpEnabled(false);
+ //String strTitle = actionBar.getTitle().toString() + " v" + BuildConfig.VERSION_NAME;
+ //actionBar.setTitle(strTitle);
+ } else { //if (getActivity().getPackageName().contains("cs710ademoapp")) {
+ ActionBar actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
+ actionBar.setIcon(R.drawable.dl_inv);
+ actionBar.setTitle("Wedge");
+
+ tableRow1.setVisibility(View.GONE);
+ tableRow2.setVisibility(View.GONE);
+ tableRow3.setVisibility(View.GONE);
+ tableRow4.setVisibility(View.GONE);
+ tableRow5.setVisibility(View.GONE);
+ tableRowStart.setVisibility(View.VISIBLE);
+ }
+
+ if (false) {
+ ReaderDevice readerDevice1 = new ReaderDevice(null, "123456", false, null, 0, 0);
+ ReaderDevice readerDevice2 = new ReaderDevice(null, "1234567890", false, null, 0, 0);
+ readersList.add(readerDevice1);
+ readersList.add(readerDevice2);
+ }
+
+ ListView readerListView = (ListView) getActivity().findViewById(R.id.directWedgeListView);
+ TextView readerEmptyView = (TextView) getActivity().findViewById(R.id.directWedgeTextViewEmpty);
+ readerListView.setEmptyView(readerEmptyView);
+ readerListAdapter = new ReaderListAdapter(getActivity(), R.layout.readers_list_item, readersList, true, true);
+ readerListView.setAdapter(readerListAdapter);
+ readerListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
+ readerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
+ boolean DEBUG = true;
+ @Override
+ public void onItemClick(AdapterView> parent, View view, int position, long id) {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("OnItemClickListener: bConnecting = " + bWedgeConnecting + ", position = " + position);
+ if (bWedgeConnecting) return;
+
+ ReaderDevice readerDevice = readerListAdapter.getItem(position);
+ if (readersList.size() > position) {
+ if (readerDevice.getSelected()) readerDevice.setSelected(false);
+ else readerDevice.setSelected(true);
+ readersList.set(position, readerDevice);
+ for (int i = 0; i < readersList.size(); i++) {
+ if (i != position) {
+ ReaderDevice readerDevice1 = readersList.get(i);
+ if (readerDevice1.getSelected()) {
+ readerDevice1.setSelected(false);
+ readersList.set(i, readerDevice1);
+ }
+ }
+ }
+ }
+ readerListAdapter.notifyDataSetChanged();
+
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("OnItemClickListener: readerDevice.getSelected = " + readerDevice.getSelected());
+ if (MainActivity.csLibrary4A.isBleConnected() && readerDevice.getSelected() == false && readerDevice.isConnected()) {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("OnItemClickListener: going to disconnect");
+ disconnectWedge();
+ } else if (MainActivity.csLibrary4A.isBleConnected() == false && readerDevice.getSelected()) {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("OnItemClickListener: going to CONNECT");
+ if (true) connectWedge(readerDevice);
+ }
+ }
+ });
+
+ Button buttonSetup = (Button) getActivity().findViewById(R.id.directWedgeButtonSetup);
+ buttonSetup.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (MainActivity.csLibrary4A.isBleConnected() || true) new SettingWedgeFragment().show(getChildFragmentManager(), "TAG");
+ else if (MainActivity.csLibrary4A.mrfidToWriteSize() != 0) Toast.makeText(getActivity().getApplicationContext(), getResources().getString(R.string.toast_not_ready), Toast.LENGTH_SHORT).show();
+ else Toast.makeText(getActivity().getApplicationContext(), getResources().getString(R.string.toast_ble_not_connected), Toast.LENGTH_SHORT).show();
+ }
+ });
+
+ buttonConnect = (Button) getActivity().findViewById(R.id.directWedgeButtonConnect);
+ buttonConnect.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (bWedgeConnecting) return;
+ if (MainActivity.csLibrary4A.isBleConnected()) {
+ disconnectWedge();
+ readerListAdapter.notifyDataSetChanged();
+ } else {
+ boolean bFound = false;
+ for (int i = 0; i < readersList.size(); i++) {
+ ReaderDevice readerDevice = readersList.get(i);
+ if (readerDevice.getSelected() && readerDevice.isConnected() == false) {
+ connectWedge(readerDevice);
+ bFound = true;
+ break;
+ }
+ }
+ if (bFound == false) Toast.makeText(getActivity().getApplicationContext(), getResources().getString(R.string.toast_select_reader_first), Toast.LENGTH_SHORT).show();
+ }
+ }
+ });
+
+ Button buttonStart = (Button) getActivity().findViewById(R.id.directWedgeButtonStart);
+ if (!getActivity().getPackageName().matches("com.csl.cs710awedgeapp")) buttonStart.setVisibility(View.VISIBLE);
+ buttonStart.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (MainActivity.csLibrary4A.isBleConnected()) {
+ if (MainActivity.csLibrary4A.mrfidToWriteSize() == 0) {
+ MainActivity.wedged = true;
+ Intent i = new Intent(Intent.ACTION_MAIN);
+ i.addCategory(Intent.CATEGORY_HOME);
+ startActivity(i);
+ }
+ } else Toast.makeText(getActivity().getApplicationContext(), getResources().getString(R.string.toast_ble_not_connected), Toast.LENGTH_SHORT).show();
+ }
+ });
+
+ Button buttonInfo = (Button) getActivity().findViewById(R.id.directWedgeButtonInfo);
+ buttonInfo.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ CustomPopupWindow customPopupWindow = new CustomPopupWindow(mContext);
+ String stringInfo =
+ "1. For the first time launching the application, please grant device permission for location, connectivity and enabling . \n\n" +
+ "2. Readers will be discovered by the app and please check the box on the right hand side to select the reader to be connected. \n\n" +
+ "3. Once connected, put the application in background.\n\n" +
+ "4. Open the target application where you would like data to be printed.\n\n" +
+ "5. On the target applicatoin , put the cursor to the text field where data will be printed. Switch your keyboard to .\n\n" +
+ "6. Press and hold the trigger key of the reader to start reading tags. EPC values will be printed to the cursor on your target application.\n\n" +
+ "7. Switch back to the CSL Data Wedge application. Now you can press the \"Disconnect\" button to disconnect from the reader.\n\n" +
+ "8. Configuration button: Press the button to modify parameters such as power, prefix, suffix and delimiter.\n\n";
+ MainActivity.csLibrary4A.appendToLog(stringInfo);
+ customPopupWindow.popupStart(stringInfo, false);
+ }
+ });
+
+ handler.post(runnableStartService);
+ handler.postDelayed(runnableStart, 1000);
+ }
+
+ @Override
+ public void onResume() {
+ super.onResume();
+ readerListAdapter.notifyDataSetChanged();
+ updateCurrentIMEMatched();
+ }
+
+ @Override
+ public void onDestroy() {
+ MainActivity.csLibrary4A.setSameCheck(true);
+ MainActivity.csLibrary4A.restoreAfterTagSelect();
+ super.onDestroy();
+ }
+
+ public DirectWedgeFragment() {
+ super("DirectWedgeFragment");
+ }
+
+ public static boolean bUserRequestedDisconnect = false;
+ void disconnectWedge() {
+ MainActivity.csLibrary4A.appendToLog("foregroundReader108: updated 2A");
+ MainActivity.csLibrary4A.setForegroundServiceEnable(false);
+ MainActivity.csLibrary4A.appendToLog("getForegroundReader = " + MainActivity.csLibrary4A.getForegroundReader());
+
+ MainActivity.csLibrary4A.disconnect(false); bleDisConnecting = true; bWedgeConnecting = false; bUserRequestedDisconnect = true;
+ readersList.clear();
+ buttonConnect.setText("Connect");
+ handler.removeCallbacks(runnableStart); handler.postDelayed(runnableStart, 2000);
+
+ MainActivity.csLibrary4A.setWedgeDeviceName(null); MainActivity.csLibrary4A.setWedgeDeviceAddress(null);
+ }
+ void connectWedge(ReaderDevice readerDevice) {
+ MainActivity.csLibrary4A.scanLeDevice(false);
+ MainActivity.csLibrary4A.connect(readerDevice); bWedgeConnecting = true; bWedgeConnected = false; bUserRequestedDisconnect = false;
+ buttonConnect.setText("Connecting");
+ MainActivity.csLibrary4A.setWedgeDeviceName(readerDevice.getName()); MainActivity.csLibrary4A.setWedgeDeviceAddress(readerDevice.getAddress());
+ MainActivity.csLibrary4A.setWedgeDeviceUUID2p1(readerDevice.getServiceUUID2p1());
+ }
+
+ Runnable runnableStartService = new Runnable() {
+ boolean DEBUG = false;
+
+ @Override
+ public void run() {
+ MainActivity.csLibrary4A.appendToLog("runnableStartService: ActivityCompat.checkSelfPermission(activity, WRITE_EXTERNAL_STORAGE) = " + ActivityCompat.checkSelfPermission(mContext, WRITE_EXTERNAL_STORAGE));
+ MainActivity.csLibrary4A.appendToLog("runnableStartService: ActivityCompat.checkSelfPermission(activity, READ_EXTERNAL_STORAGE) = " + ActivityCompat.checkSelfPermission(mContext, READ_EXTERNAL_STORAGE));
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
+ if (mContext.checkSelfPermission(WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
+ MainActivity.csLibrary4A.appendToLog("runnableStartService: requestPermissions WRITE_EXTERNAL_STORAGE"); //
+ requestPermissions(new String[] { WRITE_EXTERNAL_STORAGE, READ_EXTERNAL_STORAGE }, 1);
+ //Toast.makeText(mContext, com.csl.cslibrary4a.R.string.toast_permission_not_granted, Toast.LENGTH_SHORT).show();
+ } else MainActivity.csLibrary4A.appendToLog("runnableStartService: WRITE_EXTERNAL_STORAGE is permitted"); ///
+ } else MainActivity.csLibrary4A.appendToLog("runnableStartService: no need to handle WRITE_EXTERNAL_STORAGE");
+
+ LocationManager locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
+ MainActivity.csLibrary4A.appendToLog("runnableStartService: locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) = " + locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER));
+ MainActivity.csLibrary4A.appendToLog("runnableStartService: locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER) = " + locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER));
+ MainActivity.csLibrary4A.appendToLog("runnableStartService: ActivityCompat.checkSelfPermission(activity, ACCESS_FINE_LOCATION) = " + ActivityCompat.checkSelfPermission(mContext, ACCESS_FINE_LOCATION));
+ MainActivity.csLibrary4A.appendToLog("runnableStartService: ActivityCompat.checkSelfPermission(activity, ACCESS_COARSE_LOCATION) = " + ActivityCompat.checkSelfPermission(mContext, ACCESS_COARSE_LOCATION));
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
+ if ((ActivityCompat.checkSelfPermission(mContext, ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
+ || ActivityCompat.checkSelfPermission(mContext, ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)) {
+ CustomAlertDialog appdialog = new CustomAlertDialog();
+ appdialog.Confirm(getActivity(), "Use your location",
+ "This app collects location data in the background. In terms of the features using this location data in the background, this App collects location data when it is reading RFID tag in all inventory pages. The purpose of this is to correlate the RFID tag with the actual GNSS(GPS) location of the tag. In other words, this is to track the physical location of the logistics item tagged with the RFID tag.",
+ "No thanks", "Turn on",
+ new Runnable() {
+ @Override
+ public void run() {
+ MainActivity.csLibrary4A.appendToLog("runnableStartService: allow permission in ACCESS_FINE_LOCATION handler");
+ MainActivity.csLibrary4A.appendToLog("runnableStartService: requestPermissions ACCESS_FINE_LOCATION");
+ requestPermissions(new String[] { ACCESS_FINE_LOCATION }, 123); //ACCESS_FINE_LOCATION, ACCESS_COARSE_LOCATION
+ //if (false) Toast.makeText(mContext, com.csl.cslibrary4a.R.string.toast_permission_not_granted, Toast.LENGTH_SHORT).show();
+ /*{
+ LocationManager locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
+ if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) == false && locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER) == false) {
+ MainActivity.csLibrary4A.appendToLog("popupAlert: StreamOut: start activity ACTION_LOCATION_SOURCE_SETTINGS");
+ Intent intent1 = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
+ mContext.startActivity(intent1);
+ }
+ }*/
+ //bleEnableRequestShown0 = true; mHandler.postDelayed(mRquestAllowRunnable, 60000);
+ //bAlerting = false;
+ }
+ },
+ new Runnable() {
+ @Override
+ public void run() {
+ MainActivity.csLibrary4A.appendToLog("runnableStartService: reject permission in ACCESS_FINE_LOCATION handler");
+ //bAlerting = false;
+ //bleEnableRequestShown0 = true; mHandler.postDelayed(mRquestAllowRunnable, 60000);
+ }
+ });
+ MainActivity.csLibrary4A.appendToLog("runnableStartService: started ACCESS_FINE_LOCATION handler");
+ } else MainActivity.csLibrary4A.appendToLog("runnableStartService: handled ACCESS_FINE_LOCATION");
+ } else MainActivity.csLibrary4A.appendToLog("runnableStartService: no need to handle ACCESS_FINE_LOCATION");
+
+ MainActivity.csLibrary4A.appendToLog("runnableStartService: ActivityCompat.checkSelfPermission(activity, BLUETOOTH_CONNECT) = " + ActivityCompat.checkSelfPermission(mContext, BLUETOOTH_CONNECT));
+ MainActivity.csLibrary4A.appendToLog("runnableStartService: ActivityCompat.checkSelfPermission(activity, BLUETOOTH_SCAN) = " + ActivityCompat.checkSelfPermission(mContext, BLUETOOTH_SCAN));
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
+ if (ActivityCompat.checkSelfPermission(mContext, BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED || ActivityCompat.checkSelfPermission(mContext, BLUETOOTH_SCAN) != PackageManager.PERMISSION_GRANTED) {
+ MainActivity.csLibrary4A.appendToLog("runnableStartService: requestPermissions BLUETOOTH_SCAN and BLUETOOTH_CONNECT");
+ requestPermissions(new String[] { BLUETOOTH_SCAN, BLUETOOTH_CONNECT }, 123);
+ } else MainActivity.csLibrary4A.appendToLog("runnableStartService: handled BLUETOOTH_CONNECT and BLUETOOTH_SCAN");
+ } else MainActivity.csLibrary4A.appendToLog("runnableStartService: no need to handle BLUETOOTH_SCAN and BLUETOOTH_CONNECT");
+ }
+ };
+
+ int runningMode = -1, connectWait = 0, scanWait = 0;
+ Runnable runnableStart = new Runnable() {
+ @Override
+ public void run() {
+ boolean bValue = true;
+ if (MainActivity.csLibrary4A.isBleConnected()) {
+ if (MainActivity.csLibrary4A.mrfidToWriteSize() == 0) {
+ bWedgeConnecting = false;
+ if (bWedgeConnected == false) {
+ bWedgeConnected = true;
+ MainActivity.csLibrary4A.setPowerLevel(MainActivity.csLibrary4A.getWedgePower());
+ MainActivity.csLibrary4A.appendToLog("runnableStart: isBleConnected is true with mrfidToWriteSize = " + MainActivity.csLibrary4A.mrfidToWriteSize());
+ for (int i = 0; i < readersList.size(); i++) {
+ ReaderDevice readerDevice = readersList.get(i);
+ if (readerDevice.getSelected() && readerDevice.isConnected() == false) {
+ readerDevice.setConnected(true);
+ readersList.set(i, readerDevice);
+ readerListAdapter.notifyDataSetChanged();
+ }
+ }
+ if (getActivity().getPackageName().contains("cs710awedgeapp")) {
+ MainActivity.csLibrary4A.appendToLog("foregroundReader108: updated 2b");
+ MainActivity.csLibrary4A.setForegroundServiceEnable(true);
+ MainActivity.csLibrary4A.saveSetting2File();
+ }
+ }
+ buttonConnect.setText("Disconnect");
+ } //else Toast.makeText(getActivity().getApplicationContext(), getResources().getString(R.string.toast_not_ready), Toast.LENGTH_SHORT).show();
+ } else if (bWedgeConnecting) {
+ MainActivity.csLibrary4A.appendToLog("runnableStart: bConnecting is true");
+ } else if (MainActivity.csLibrary4A.isBleScanning()) {
+ MainActivity.csLibrary4A.appendToLog("runnableStart: isBleScanning is true");
+ boolean listUpdated = false;
+ if (++scanWait > 10) {
+ boolean bValue1 = MainActivity.csLibrary4A.scanLeDevice(false);
+ MainActivity.csLibrary4A.appendToLog("runnableStart: STOP scanning with result = " + bValue1);
+ scanWait = 0;
+ readersList.clear();
+ listUpdated = true;
+ } else {
+ while (true) {
+ BluetoothGatt.CsScanData csScanData = MainActivity.csLibrary4A.getNewDeviceScanned();
+ if (csScanData != null) {
+ BluetoothGatt.CsScanData scanResultA = csScanData;
+ if (getActivity() == null) continue;
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
+ if (ActivityCompat.checkSelfPermission(getActivity().getApplicationContext(), BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
+ continue;
+ }
+ } else if (ActivityCompat.checkSelfPermission(getActivity().getApplicationContext(), BLUETOOTH) != PackageManager.PERMISSION_GRANTED) {
+ continue;
+ }
+ if (DEBUG)
+ MainActivity.csLibrary4A.appendToLog("runnableStart: scanResultA.device.getType() = " + scanResultA.device.getType() + ". scanResultA.rssi = " + scanResultA.rssi);
+ if (/*scanResultA.device.getType() == BluetoothDevice.DEVICE_TYPE_LE &&*/ (true || scanResultA.rssi < 0)) {
+ boolean match = false;
+ for (int i = 0; i < readersList.size(); i++) {
+ if (readersList.get(i).getAddress().matches(scanResultA.device.getAddress())) {
+ ReaderDevice readerDevice1 = readersList.get(i);
+ int count = readerDevice1.getCount();
+ count++;
+ readerDevice1.setCount(count);
+ readerDevice1.setRssi(scanResultA.rssi);
+ readersList.set(i, readerDevice1);
+ listUpdated = true;
+ match = true;
+ break;
+ }
+ }
+ if (match == false) {
+ ReaderDevice readerDevice = new ReaderDevice(scanResultA.device.getName(), scanResultA.device.getAddress(), false, "", 1, scanResultA.rssi, scanResultA.serviceUUID2p2);
+ String strInfo = "";
+ if (scanResultA.device.getBondState() == 12) {
+ strInfo += "BOND_BONDED\n";
+ }
+ //readerDevice.setDetails(strInfo + "scanRecord=" + mCsLibrary4A.byteArrayToString(scanResultA.scanRecord));
+ readersList.add(readerDevice);
+ listUpdated = true;
+ }
+ } else {
+ if (DEBUG)
+ MainActivity.csLibrary4A.appendToLog("runnableStart: deviceScanTask: rssi=" + scanResultA.rssi + ", error type=" + scanResultA.device.getType());
+ }
+ //scanWait = 0;
+ } else {
+ MainActivity.csLibrary4A.appendToLog("runnableStart: NO reader is found with scanWait = " + scanWait);
+ break;
+ }
+ }
+ if (listUpdated) readerListAdapter.notifyDataSetChanged();
+ }
+ } else {
+ MainActivity.csLibrary4A.appendToLog("bbb 4");
+ if (bWedgeConnected) {
+ bWedgeConnected = false;
+ MainActivity.csLibrary4A.appendToLog("bbb 4A");
+ readersList.clear(); readerListAdapter.notifyDataSetChanged();
+ buttonConnect.setText("Connect");
+ }
+ MainActivity.csLibrary4A.appendToLog("runnableStart: isBleScanning is FALSE");
+ boolean bScanPermitted = true;
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { //that is android 12 or above
+ if (ActivityCompat.checkSelfPermission(mContext, BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED
+ || ActivityCompat.checkSelfPermission(mContext, BLUETOOTH_SCAN) != PackageManager.PERMISSION_GRANTED) {
+ bScanPermitted = false;
+ //MainActivity.csLibrary4A.appendToLog("runnableStartService: requestPermissions BLUETOOTH_SCAN and BLUETOOTH_CONNECT");
+ //requestPermissions(new String[] { BLUETOOTH_SCAN, BLUETOOTH_CONNECT }, 123);
+ MainActivity.csLibrary4A.appendToLog("runnableStart: CANNOT start scanLeDevice as BLUETOOTH_CONNECT && BLUETOOTH_SCAN is NOT yet permitted");
+ } else {
+ MainActivity.csLibrary4A.appendToLog("runnableStartService: BLUETOOTH_CONNECT and BLUETOOTH_SCAN and (ACCESS_FINE_LOCATION or ACCESS_COARSE_LOCATION) is permitted");
+ }
+ } else {
+ MainActivity.csLibrary4A.appendToLog("runnableStartService: no need to handle BLUETOOTH_SCAN and BLUETOOTH_CONNECT");
+ if (ActivityCompat.checkSelfPermission(mContext, BLUETOOTH) != PackageManager.PERMISSION_GRANTED) {
+ bScanPermitted = false;
+ MainActivity.csLibrary4A.appendToLog("runnableStart: CANNOT start scanLeDevice as BLUETOOTH is NOT yet permitted");
+ } else {
+ MainActivity.csLibrary4A.appendToLog("runnableStartService: BLUETOOTH_CONNECT and BLUETOOTH_SCAN and (ACCESS_FINE_LOCATION or ACCESS_COARSE_LOCATION) is permitted");
+ }
+ }
+ if ((ActivityCompat.checkSelfPermission(mContext, ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
+ || ActivityCompat.checkSelfPermission(mContext, ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)) {
+ bScanPermitted = false;
+ MainActivity.csLibrary4A.appendToLog("runnableStart: CANNOT start scanLeDevice as ACCESS_FINE_LOCATION or ACCESS_COARSE_LOCATION is NOT yet permitted");
+ }
+ bWedgeConnecting = false; connectWait = 0; scanWait = 0;
+ boolean bValue1 = false;
+ if (bScanPermitted) bValue1 = MainActivity.csLibrary4A.scanLeDevice(true);
+ MainActivity.csLibrary4A.appendToLog("runnableStart: starting scanLeDevice is " + bValue1 + " with isScanning = " + MainActivity.csLibrary4A.isBleScanning());
+ }
+ handler.postDelayed(runnableStart, 1000);
+ }
+ };
+ CustomAlertDialog appdialog;
+ void popupAlert() {
+ MainActivity.csLibrary4A.appendToLog("DirectWedgeFragment: entering popupAlert");
+ if (appdialog != null && appdialog.isShowing()) {
+ MainActivity.csLibrary4A.appendToLog("DirectWedgeFragment: skip popupAlert");
+ return;
+ }
+ appdialog = new CustomAlertDialog();
+ appdialog.Confirm(getActivity(), "Enable <" + stringLabelExpected + ">",
+ "<" + stringLabelExpected + "> is not enabled. Click OK to open Languages & Input Settings. You will need to select <" + stringLabelExpected + "> in your current keyboard to use it",
+ "No thanks", "OK",
+ new Runnable() {
+ @Override
+ public void run() {
+ MainActivity.csLibrary4A.appendToLog("Ok Procedure");
+ Intent enableIntent = new Intent(Settings.ACTION_INPUT_METHOD_SETTINGS);
+ enableIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+ getActivity().startActivity(enableIntent);
+ }
+ },
+ new Runnable() {
+ @Override
+ public void run() {
+ MainActivity.csLibrary4A.appendToLog("Cancel procedure");
+ getActivity().finish();
+ //System.exit(0);
+ }
+ });
+ MainActivity.csLibrary4A.appendToLog("DirectWedgeFragment: EXIT popupAlert");
+ }
+
+ void updateCurrentIMEMatched() {
+ if (true) {
+ boolean bFound = false;
+ List list = null;
+ stringImeExpected = getActivity().getPackageName() + ".CustomIME";
+ if (MainActivity.drawerPositionsDefault != DrawerListContent.DrawerPositions.MAIN) stringLabelExpected = getResources().getString(R.string.app_ime_simplewedge1);
+ else if (getActivity().getPackageName().contains("cs710ademoapp")) stringLabelExpected = getResources().getString(R.string.app_ime_cs710);
+ else stringLabelExpected = getResources().getString(R.string.app_ime_cs108);
+ InputMethodManager inputMethodManager = inputMethodManager = (InputMethodManager) getActivity().getSystemService(getActivity().INPUT_METHOD_SERVICE);
+
+ MainActivity.csLibrary4A.appendToLog("FEATURE_INPUT_METHODS is " + getActivity().getPackageManager().hasSystemFeature(PackageManager.FEATURE_INPUT_METHODS));
+ list = inputMethodManager.getEnabledInputMethodList(); bFound = false;
+ MainActivity.csLibrary4A.appendToLog("getCurrentInputMethodSubtype = " + inputMethodManager.getCurrentInputMethodSubtype().getLanguageTag());
+ for (int i = 0; i < list.size(); i++) {
+ MainActivity.csLibrary4A.appendToLog("enabled " + i + ": " + list.get(i).getServiceName()
+ + ", " + list.get(i).getPackageName()
+ + ", " + list.get(i).loadLabel(getActivity().getPackageManager()).toString()
+ + ", " + list.get(i).getIsDefaultResourceId());
+ if (list.get(i).getServiceName().contains(stringImeExpected) && list.get(i).loadLabel(getActivity().getPackageManager()).toString().contains(stringLabelExpected)) {
+ bFound = true;
+ MainActivity.csLibrary4A.appendToLog("Found expected IME");
+ }
+ }
+
+ if (bFound == false) {
+ MainActivity.csLibrary4A.appendToLog("DirectWedgeFragment: No " + stringImeExpected + " is found");
+ if (false) inputMethodManager.showInputMethodPicker();
+ else popupAlert();
+ } else if (true) {
+ list = inputMethodManager.getInputMethodList(); bFound = false;
+ for (int i = 0; i < list.size(); i++) {
+ MainActivity.csLibrary4A.appendToLog(i + ": " + list.get(i).getServiceName()
+ + ", " + list.get(i).getPackageName()
+ + ", " + list.get(i).loadLabel(getActivity().getPackageManager()).toString()
+ + ", " + list.get(i).getIsDefaultResourceId());
+
+ List submethods = inputMethodManager.getEnabledInputMethodSubtypeList(list.get(i), true);
+ for (InputMethodSubtype submethod : submethods) {
+ if (submethod.getMode().equals("keyboard")) {
+ String currentLocale = submethod.getLocale();
+ MainActivity.csLibrary4A.appendToLog("Available input method locale: " + currentLocale);
+ }
+ }
+
+ if (list.get(i).getServiceName().contains(stringImeExpected) && list.get(i).loadLabel(getActivity().getPackageManager()).toString().contains(stringLabelExpected)) {
+ bFound = true;
+ MainActivity.csLibrary4A.appendToLog("Found expected IME with id = " + list.get(i).getId());
+ String idCurrent = Settings.Secure.getString(mContext.getContentResolver(), Settings.Secure.DEFAULT_INPUT_METHOD);
+ MainActivity.csLibrary4A.appendToLog("Found current IME with id = " + idCurrent);
+ if (list.get(i).getId().matches(idCurrent)) {
+ MainActivity.csLibrary4A.appendToLog("expected IME matches current IME");
+ bCurrentIMEmatched = true;
+ } else {
+ MainActivity.csLibrary4A.appendToLog("expected IME does NOT match current IME");
+ bCurrentIMEmatched = false;
+ }
+/*
+ CustomIME customIME = new CustomIME();
+ InputMethodService inputMethodService = getActivity().get
+ customIME.switchInputMethod(list.get(i).getId());
+*/
+ //String oldDefaultKeyboard = Settings.Secure.getString(resolver, Setting.Secure.DEFAULT_INPUT_METHOD);
+ //MainActivity.csLibrary4A.appendToLog("oldDefaultKeyboard = " + oldDefaultKeyboard);
+ /*inputMethodManager.toggleSoftInputFromWindow(
+ linearLayout.getApplicationWindowToken(),
+ InputMethodManager.SHOW_FORCED, 0);*/
+
+ IBinder iBinder = getView().getWindowToken();
+ MainActivity.csLibrary4A.appendToLog("iBinder is " + (iBinder == null ? "null" : "valid"));
+ if (iBinder != null) inputMethodManager.setInputMethod(iBinder, list.get(i).getId());
+ }
+ }
+ }
+ }
+ }
+}
+
+
+
+package com.csl.cs710ademoapp.fragments;
+
+import static com.csl.cslibrary4a.RfidReader.TagType.TAG_FDMICRO;
+
+import android.os.Bundle;
+
+import com.csl.cslibrary4a.AdapterTab;
+import com.google.android.material.tabs.TabLayout;
+
+import androidx.viewpager.widget.ViewPager;
+import androidx.appcompat.app.ActionBar;
+import androidx.appcompat.app.AppCompatActivity;
+import android.view.LayoutInflater;
+import android.view.MenuItem;
+import android.view.View;
+import android.view.ViewGroup;
+
+import com.csl.cs710ademoapp.R;
+
+public class FdmicroFragment extends CommonFragment {
+ private ActionBar actionBar;
+ private ViewPager viewPager;
+ AdapterTab adapter;
+
+ private String[] tabs = {"Scan", "Configuration"};
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ super.onCreateView(inflater, container, savedInstanceState, true);
+ return inflater.inflate(R.layout.custom_tabbed_layout, container, false);
+ }
+
+ @Override
+ public boolean onOptionsItemSelected(MenuItem item) {
+ InventoryRfidiMultiFragment fragment = (InventoryRfidiMultiFragment) adapter.fragment0;
+ if (item.getItemId() == R.id.menuAction_clear) {
+ fragment.clearTagsList();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_sortRssi) {
+ fragment.sortTagsListByRssi();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_sort) {
+ fragment.sortTagsList();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_save) {
+ fragment.saveTagsList();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_share) {
+ fragment.shareTagsList();
+ return true;
+ } else return super.onOptionsItemSelected(item);
+ }
+
+ @Override
+ public void onActivityCreated(Bundle savedInstanceState) {
+ super.onActivityCreated(savedInstanceState);
+
+ actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
+ actionBar.setIcon(R.drawable.dl_inv);
+ actionBar.setTitle(R.string.title_activity_fdMicro);
+
+ TabLayout tabLayout = (TabLayout) getActivity().findViewById(R.id.OperationsTabLayout);
+ for (String tab_name : tabs) {
+ tabLayout.addTab(tabLayout.newTab().setText(tab_name));
+ }
+ tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
+ @Override
+ public void onTabSelected(TabLayout.Tab tab) {
+ viewPager.setCurrentItem(tab.getPosition());
+ }
+
+ @Override
+ public void onTabUnselected(TabLayout.Tab tab) {
+ }
+
+ @Override
+ public void onTabReselected(TabLayout.Tab tab) {
+ }
+ });
+
+ adapter = new AdapterTab(getActivity().getSupportFragmentManager(), tabs.length);
+ adapter.setFragment(0, InventoryRfidiMultiFragment.newInstance(true, TAG_FDMICRO, "E2827001"));
+ adapter.setFragment(1, new AccessFdmicroFragment());
+
+ viewPager = (ViewPager) getActivity().findViewById(R.id.OperationsPager);
+ viewPager.setAdapter(adapter);
+ viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
+ }
+
+ @Override
+ public void onPause() {
+ adapter.fragment0.onPause();
+ adapter.fragment1.onPause();
+ super.onPause();
+ }
+
+ @Override
+ public void onStop() {
+ adapter.fragment0.onStop();
+ adapter.fragment1.onStop();
+ super.onStop();
+ }
+
+ @Override
+ public void onDestroyView() {
+ adapter.fragment0.onDestroyView();
+ adapter.fragment1.onDestroyView();
+ super.onDestroyView();
+ }
+
+ @Override
+ public void onDestroy() {
+ adapter.fragment0.onDestroy();
+ adapter.fragment1.onDestroy();
+ super.onDestroy();
+ }
+
+ @Override
+ public void onDetach() {
+ adapter.fragment0.onDetach();
+ adapter.fragment1.onDetach();
+ super.onDetach();
+ }
+
+ public FdmicroFragment() {
+ super("FdmicroFragment");
+ }
+}
+
+
+
+package com.csl.cs710ademoapp.fragments;
+
+import android.os.Bundle;
+import android.os.Handler;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.TextView;
+
+import androidx.appcompat.app.ActionBar;
+import androidx.appcompat.app.AppCompatActivity;
+
+import com.csl.cs710ademoapp.BuildConfig;
+import com.csl.cs710ademoapp.MainActivity;
+import com.csl.cs710ademoapp.R;
+
+public class ForegroundFragment extends CommonFragment {
+ Handler mHandler = new Handler();
+ long timeMillis = 0;
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ super.onCreateView(inflater, container, savedInstanceState, true);
+ return inflater.inflate(R.layout.fragment_about, container, false);
+ }
+
+ @Override
+ public void onActivityCreated(Bundle savedInstanceState) {
+ super.onActivityCreated(savedInstanceState);
+
+ ActionBar actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
+ actionBar.setIcon(R.drawable.dl_about);
+ actionBar.setTitle(R.string.title_activity_about);
+
+ TextView appVersionView = (TextView) getActivity().findViewById(R.id.appVersion);
+ appVersionView.setText(BuildConfig.VERSION_NAME);
+ TextView libVersionView = (TextView) getActivity().findViewById(R.id.libVersion);
+ libVersionView.setText(MainActivity.csLibrary4A.getlibraryVersion());
+
+ MainActivity.mSensorConnector.mLocationDevice.turnOn(true);
+ MainActivity.mSensorConnector.mSensorDevice.turnOn(true);
+ mHandler.post(updateRunnable);
+ }
+
+ @Override
+ public void onDestroy() {
+ MainActivity.mSensorConnector.mLocationDevice.turnOn(false);
+ MainActivity.mSensorConnector.mSensorDevice.turnOn(false);
+ mHandler.removeCallbacks(updateRunnable);
+ super.onDestroy();
+ }
+
+ public ForegroundFragment() {
+ super("AboutFragment");
+ }
+
+ private final Runnable updateRunnable = new Runnable() {
+ @Override
+ public void run() {
+ TextView timeStampView = (TextView) getActivity().findViewById(R.id.timeStamp);
+ TextView locationView = (TextView) getActivity().findViewById(R.id.GeoLocation);
+ TextView eCompassView = (TextView) getActivity().findViewById(R.id.eCompass);
+
+ TextView radioVersion = (TextView) getActivity().findViewById(R.id.radioVersion);
+ TextView modelVersion = (TextView) getActivity().findViewById(R.id.modelVersion);
+ TextView moduleRfidOnStatus = (TextView) getActivity().findViewById(R.id.moduleRfid_onStatus);
+ TextView moduleBarOnStatus = (TextView) getActivity().findViewById(R.id.moduleBar_onStatus);
+ TextView triggerOnStatus = (TextView) getActivity().findViewById(R.id.trigger_onStatus);
+ TextView moduleBattery = (TextView) getActivity().findViewById(R.id.module_battery);
+ TextView moduleVersionLabel = (TextView) getActivity().findViewById(R.id.module_versionLabel);
+ if (MainActivity.csLibrary4A.get98XX() == 2) moduleVersionLabel.setText("Atmel firmware version");
+ else if (MainActivity.csLibrary4A.get98XX() == 0) moduleVersionLabel.setText("SiliconLab firmware version");
+ TextView moduleVersion = (TextView) getActivity().findViewById(R.id.module_version);
+ TextView radioSerial = (TextView) getActivity().findViewById(R.id.radio_serialnumber);
+ TextView radioBoardVersion = (TextView) getActivity().findViewById(R.id.radio_boardVersion);
+ TextView productSerial = (TextView) getActivity().findViewById(R.id.module_productserialnumber);
+ TextView boardVersion = (TextView) getActivity().findViewById(R.id.module_boardversion);
+ TextView barcodeSerial = (TextView) getActivity().findViewById(R.id.moduleBar_serialNumber);
+ TextView barcodeDate = (TextView) getActivity().findViewById(R.id.moduleBar_date);
+ TextView barcodeVersion = (TextView) getActivity().findViewById(R.id.moduleBar_version);
+
+ TextView bluetoothVersion = (TextView) getActivity().findViewById(R.id.bluetooth_version);
+ TextView bluetoothAddress = (TextView) getActivity().findViewById(R.id.bluetooth_address);
+ TextView bluetoothRssi = (TextView) getActivity().findViewById(R.id.bluetooth_rssi);
+
+ timeStampView.setText(MainActivity.mSensorConnector.getTimeStamp());
+ locationView.setText(MainActivity.mSensorConnector.mLocationDevice.getLocation());
+ eCompassView.setText(MainActivity.mSensorConnector.mSensorDevice.getEcompass());
+ if (MainActivity.csLibrary4A.isBleConnected()) {
+ if (System.currentTimeMillis() - timeMillis > 5000) {
+ timeMillis = System.currentTimeMillis();
+ radioVersion.setText(MainActivity.csLibrary4A.getMacVer());
+ modelVersion.setText(MainActivity.csLibrary4A.getModelNumber());
+ moduleVersion.setText(MainActivity.csLibrary4A.hostProcessorICGetFirmwareVersion());
+ bluetoothVersion.setText(MainActivity.csLibrary4A.getBluetoothICFirmwareVersion());
+ MainActivity.csLibrary4A.batteryLevelRequest();
+ }
+ moduleRfidOnStatus.setText(MainActivity.csLibrary4A.getRfidOnStatus() ? "on" : "off");
+ triggerOnStatus.setText(MainActivity.csLibrary4A.getTriggerButtonStatus() ? "pressed" : "released");
+ moduleBarOnStatus.setText(MainActivity.csLibrary4A.getBarcodeOnStatus() ? "on" : "off");
+ moduleBattery.setText(MainActivity.csLibrary4A.getBatteryDisplay(true));
+ if (MainActivity.csLibrary4A.isRfidFailure()) radioSerial.setText("Not available");
+ else radioSerial.setText(MainActivity.csLibrary4A.getRadioSerial());
+ radioBoardVersion.setText(MainActivity.csLibrary4A.getRadioBoardVersion());
+ productSerial.setText(MainActivity.csLibrary4A.getHostProcessorICSerialNumber());
+ boardVersion.setText(MainActivity.csLibrary4A.getHostProcessorICBoardVersion());
+ if (MainActivity.csLibrary4A.isBarcodeFailure()) barcodeSerial.setText("Not available");
+ else {
+ barcodeSerial.setText(MainActivity.csLibrary4A.getBarcodeSerial());
+ barcodeDate.setText(MainActivity.csLibrary4A.getBarcodeDate());
+ barcodeVersion.setText(MainActivity.csLibrary4A.getBarcodeVersion());
+ }
+ bluetoothAddress.setText(MainActivity.csLibrary4A.getBluetoothDeviceAddress());
+ bluetoothRssi.setText(String.valueOf(MainActivity.csLibrary4A.getRssi()));
+ } else {
+ radioVersion.setText("");
+ moduleRfidOnStatus.setText("");
+ moduleBarOnStatus.setText("");
+ triggerOnStatus.setText("");
+ moduleBattery.setText("");
+ moduleVersion.setText("");
+ bluetoothVersion.setText("");
+ radioSerial.setText("");
+ radioBoardVersion.setText("");
+ productSerial.setText("");
+ boardVersion.setText("");
+ barcodeSerial.setText("");
+ bluetoothAddress.setText("");
+ bluetoothRssi.setText("");
+ }
+ mHandler.postDelayed(updateRunnable, 1000);
+ }
+ };
+}
+
+
+
+package com.csl.cs710ademoapp.fragments;
+
+import static android.Manifest.permission.ACCESS_COARSE_LOCATION;
+import static android.Manifest.permission.ACCESS_FINE_LOCATION;
+import static android.Manifest.permission.BLUETOOTH_CONNECT;
+import static android.Manifest.permission.BLUETOOTH_SCAN;
+import static android.Manifest.permission.POST_NOTIFICATIONS;
+import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
+import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
+import static android.content.Context.LOCATION_SERVICE;
+import static androidx.core.app.ServiceCompat.STOP_FOREGROUND_REMOVE;
+import static androidx.core.app.ServiceCompat.stopForeground;
+import static androidx.core.content.ContextCompat.getSystemService;
+import static com.csl.cs710ademoapp.MainActivity.isHomeFragment;
+import static com.csl.cs710ademoapp.MainActivity.mContext;
+
+import android.app.ActivityManager;
+import android.app.Service;
+import android.content.Context;
+import android.content.Intent;
+import android.content.pm.PackageManager;
+import android.location.LocationManager;
+import android.os.Build;
+import android.os.Bundle;
+import android.util.Log;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.Button;
+import android.widget.FrameLayout;
+import android.widget.LinearLayout;
+
+import androidx.appcompat.app.ActionBar;
+import androidx.appcompat.app.AppCompatActivity;
+import androidx.core.app.ActivityCompat;
+import androidx.core.app.NotificationManagerCompat;
+import androidx.core.content.ContextCompat;
+
+import com.csl.cs710ademoapp.CustomAlertDialog;
+import com.csl.cs710ademoapp.CustomPopupWindow;
+import com.csl.cs710ademoapp.CustomProgressDialog;
+import com.csl.cs710ademoapp.MainActivity;
+import com.csl.cs710ademoapp.MyForegroundService;
+import com.csl.cs710ademoapp.R;
+
+public class HomeFragment extends CommonFragment {
+ final boolean DEBUG = false;
+
+ @Override
+ public void onAttach(Context context) {
+ Log.i("Hello", "HomeFragment.onAttach");
+ super.onAttach(context);
+ }
+ @Override
+ public void onStart() {
+ Log.i("Hello", "HomeFragment.onStart");
+ isHomeFragment = true;
+ MainActivity.csLibrary4A.appendToLog("isHomeFragment1 = " + isHomeFragment);
+ super.onStart();
+ }
+
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ super.onCreateView(inflater, container, savedInstanceState, true);
+ if (getActivity().getPackageName().contains("com.csl.cs710ademoapp")) return inflater.inflate(R.layout.home_layout710, container, false);
+ else return inflater.inflate(R.layout.home_layout108, container, false);
+ }
+
+ @Override
+ public void onActivityCreated(Bundle savedInstanceState) {
+ super.onActivityCreated(savedInstanceState);
+
+ if (true) {
+ String strForegroundReader = MainActivity.csLibrary4A.getForegroundReader();
+ MainActivity.csLibrary4A.appendToLog("strForegroundReader = " + strForegroundReader + ", getForegroundServiceEnable = " + MainActivity.csLibrary4A.getForegroundServiceEnable());
+ if (!getActivity().getPackageName().contains("com.csl.cs710awedgeapp") && strForegroundReader != null && strForegroundReader.length() != 0) {
+ MainActivity.csLibrary4A.appendToLog("strForegroundReader = " + strForegroundReader + ", getForegroundServiceEnable = " + MainActivity.csLibrary4A.getForegroundServiceEnable());
+ LinearLayout linearLayout1, linearLayout2, linearLayout3, linearLayout4, linearLayout5;
+ linearLayout1 = (LinearLayout) getActivity().findViewById(R.id.mainRow1);
+ linearLayout2 = (LinearLayout) getActivity().findViewById(R.id.mainRow2);
+ linearLayout3 = (LinearLayout) getActivity().findViewById(R.id.mainRow3);
+ linearLayout4 = (LinearLayout) getActivity().findViewById(R.id.mainRow4);
+ linearLayout5 = (LinearLayout) getActivity().findViewById(R.id.mainRow5);
+ if (getActivity().getPackageName().contains("com.csl.cs710ademoapp")) {
+ FrameLayout frameLayout = (FrameLayout) getActivity().findViewById(R.id.mainButton1);
+ frameLayout.setVisibility(View.INVISIBLE);
+ } else {
+ Button button = (Button) getActivity().findViewById(R.id.mainButton1);
+ button.setVisibility(View.INVISIBLE);
+ }
+ linearLayout1.setVisibility(View.INVISIBLE);
+ linearLayout2.setVisibility(View.GONE);
+ linearLayout3.setVisibility(View.VISIBLE);
+ linearLayout4.setVisibility(View.INVISIBLE);
+ //linearLayout5.setVisibility(View.INVISIBLE);
+
+ }
+ }
+ MainActivity.tagType = null; MainActivity.mDid = null;
+ if (true || MainActivity.sharedObjects.versionWarningShown == false)
+ mHandler.post(runnableConfiguring);
+ mHandler.postDelayed(runnableStartService, 1000);
+ }
+
+ @Override
+ public void onStop() {
+ stopProgressDialog();
+ mHandler.removeCallbacks(runnableConfiguring);
+ super.onStop();
+ }
+
+ @Override
+ public void onDestroyView() {
+ isHomeFragment = false;
+ //MainActivity.csLibrary4A.appendToLog("isHomeFragment1 = " + isHomeFragment);
+ super.onDestroyView();
+ }
+
+ public HomeFragment() {
+ super("HomeFragment");
+ }
+
+ CustomProgressDialog progressDialog;
+ void stopProgressDialog() {
+ if (progressDialog != null) { if (progressDialog.isShowing()) progressDialog.dismiss(); }
+ }
+ Runnable runnableConfiguring = new Runnable() {
+ boolean DEBUG = false;
+ @Override
+ public void run() {
+ if (true) {
+ MainActivity.csLibrary4A.appendToLog("runnableConfiguring(): isBleConnected = " + MainActivity.csLibrary4A.isBleConnected() + ", isRfidFailure = " + MainActivity.csLibrary4A.isRfidFailure());
+ MainActivity.csLibrary4A.appendToLog("runnableConfiguring(): mrfidToWriteSize = " + MainActivity.csLibrary4A.mrfidToWriteSize());
+ }
+ boolean progressShown = false;
+ if (progressDialog != null) { if (progressDialog.isShowing()) progressShown = true; }
+ if (MainActivity.csLibrary4A.isBleConnected() == false || MainActivity.csLibrary4A.isRfidFailure()) {
+ if (progressShown) {
+ stopProgressDialog();
+ /*String stringPopup = "Connection failed, please rescan.";
+ CustomPopupWindow customPopupWindow = new CustomPopupWindow((Context) getActivity());
+ customPopupWindow.popupStart(stringPopup, false); */
+ }
+ } else if (MainActivity.csLibrary4A.mrfidToWriteSize() != 0) {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("mrfidToWriteSize = " + MainActivity.csLibrary4A.mrfidToWriteSize());
+ mHandler.postDelayed(runnableConfiguring, 250);
+ if (progressShown == false) {
+ progressDialog = new CustomProgressDialog(getActivity(), "Initializing reader. Please wait.");
+ progressDialog.show();
+ }
+ } else {
+ stopProgressDialog();
+ if (MainActivity.sharedObjects.versionWarningShown == false) {
+ String stringPopup = MainActivity.csLibrary4A.checkVersion();
+ if (stringPopup != null && stringPopup.length() != 0) {
+ if (stringPopup.indexOf("Unknown") != 0) stringPopup = "Firmware too old\nPlease upgrade firmware to at least:" + stringPopup;
+ CustomPopupWindow customPopupWindow = new CustomPopupWindow((Context)getActivity());
+ customPopupWindow.popupStart(stringPopup, false);
+ }
+ MainActivity.sharedObjects.versionWarningShown = true;
+ }
+ }
+ MainActivity.csLibrary4A.setPwrManagementMode(true);
+ }
+ };
+
+ Runnable runnableStartService = new Runnable() {
+ boolean DEBUG = false;
+
+ @Override
+ public void run() {
+ MainActivity.csLibrary4A.appendToLog("runnableStartService: ActivityCompat.checkSelfPermission(activity, WRITE_EXTERNAL_STORAGE) = " + ActivityCompat.checkSelfPermission(mContext, WRITE_EXTERNAL_STORAGE));
+ MainActivity.csLibrary4A.appendToLog("runnableStartService: ActivityCompat.checkSelfPermission(activity, READ_EXTERNAL_STORAGE) = " + ActivityCompat.checkSelfPermission(mContext, READ_EXTERNAL_STORAGE));
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
+ if (mContext.checkSelfPermission(WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
+ MainActivity.csLibrary4A.appendToLog("runnableStartService: requestPermissions WRITE_EXTERNAL_STORAGE"); //
+ requestPermissions(new String[] { WRITE_EXTERNAL_STORAGE, READ_EXTERNAL_STORAGE }, 1);
+ //Toast.makeText(mContext, com.csl.cslibrary4a.R.string.toast_permission_not_granted, Toast.LENGTH_SHORT).show();
+ } else MainActivity.csLibrary4A.appendToLog("runnableStartService: WRITE_EXTERNAL_STORAGE is permitted"); ///
+ } else MainActivity.csLibrary4A.appendToLog("runnableStartService: no need to handle WRITE_EXTERNAL_STORAGE");
+
+ LocationManager locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
+ MainActivity.csLibrary4A.appendToLog("runnableStartService: locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) = " + locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER));
+ MainActivity.csLibrary4A.appendToLog("runnableStartService: locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER) = " + locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER));
+ MainActivity.csLibrary4A.appendToLog("runnableStartService: ActivityCompat.checkSelfPermission(activity, ACCESS_FINE_LOCATION) = " + ActivityCompat.checkSelfPermission(mContext, ACCESS_FINE_LOCATION));
+ MainActivity.csLibrary4A.appendToLog("runnableStartService: ActivityCompat.checkSelfPermission(activity, ACCESS_COARSE_LOCATION) = " + ActivityCompat.checkSelfPermission(mContext, ACCESS_COARSE_LOCATION));
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
+ if ((ActivityCompat.checkSelfPermission(mContext, ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED || ActivityCompat.checkSelfPermission(mContext, ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)) {
+ CustomAlertDialog appdialog = new CustomAlertDialog();
+ appdialog.Confirm(getActivity(), "Use your location",
+ "This app collects location data in the background. In terms of the features using this location data in the background, this App collects location data when it is reading RFID tag in all inventory pages. The purpose of this is to correlate the RFID tag with the actual GNSS(GPS) location of the tag. In other words, this is to track the physical location of the logistics item tagged with the RFID tag.",
+ "No thanks", "Turn on",
+ new Runnable() {
+ @Override
+ public void run() {
+ MainActivity.csLibrary4A.appendToLog("runnableStartService: allow permission in ACCESS_FINE_LOCATION handler");
+ MainActivity.csLibrary4A.appendToLog("runnableStartService: requestPermissions ACCESS_FINE_LOCATION");
+ requestPermissions(new String[] { ACCESS_FINE_LOCATION }, 123); //ACCESS_FINE_LOCATION, ACCESS_COARSE_LOCATION
+ //if (false) Toast.makeText(mContext, com.csl.cslibrary4a.R.string.toast_permission_not_granted, Toast.LENGTH_SHORT).show();
+ /*{
+ LocationManager locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
+ if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) == false && locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER) == false) {
+ MainActivity.csLibrary4A.appendToLog("popupAlert: StreamOut: start activity ACTION_LOCATION_SOURCE_SETTINGS");
+ Intent intent1 = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
+ mContext.startActivity(intent1);
+ }
+ }*/
+ //bleEnableRequestShown0 = true; mHandler.postDelayed(mRquestAllowRunnable, 60000);
+ //bAlerting = false;
+ }
+ },
+ new Runnable() {
+ @Override
+ public void run() {
+ MainActivity.csLibrary4A.appendToLog("runnableStartService: reject permission in ACCESS_FINE_LOCATION handler");
+ //bAlerting = false;
+ //bleEnableRequestShown0 = true; mHandler.postDelayed(mRquestAllowRunnable, 60000);
+ }
+ });
+ MainActivity.csLibrary4A.appendToLog("runnableStartService: started ACCESS_FINE_LOCATION handler");
+ } else MainActivity.csLibrary4A.appendToLog("runnableStartService: handled ACCESS_FINE_LOCATION");
+ } else MainActivity.csLibrary4A.appendToLog("runnableStartService: no need to handle ACCESS_FINE_LOCATION");
+
+ MainActivity.csLibrary4A.appendToLog("runnableStartService: ActivityCompat.checkSelfPermission(activity, BLUETOOTH_CONNECT) = " + ActivityCompat.checkSelfPermission(mContext, BLUETOOTH_CONNECT));
+ MainActivity.csLibrary4A.appendToLog("runnableStartService: ActivityCompat.checkSelfPermission(activity, BLUETOOTH_SCAN) = " + ActivityCompat.checkSelfPermission(mContext, BLUETOOTH_SCAN));
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
+ if (ActivityCompat.checkSelfPermission(mContext, BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED || ActivityCompat.checkSelfPermission(mContext, BLUETOOTH_SCAN) != PackageManager.PERMISSION_GRANTED) {
+ MainActivity.csLibrary4A.appendToLog("runnableStartService: requestPermissions BLUETOOTH_SCAN and BLUETOOTH_CONNECT");
+ requestPermissions(new String[] { BLUETOOTH_SCAN, BLUETOOTH_CONNECT }, 123);
+ } else MainActivity.csLibrary4A.appendToLog("runnableStartService: handled BLUETOOTH_CONNECT and BLUETOOTH_SCAN");
+ } else MainActivity.csLibrary4A.appendToLog("runnableStartService: no need to handle BLUETOOTH_SCAN and BLUETOOTH_CONNECT");
+
+ MainActivity.csLibrary4A.appendToLog("runnableStartService: ActivityCompat.checkSelfPermission(activity, POST_NOTIFICATIONS) = " + ActivityCompat.checkSelfPermission(mContext, POST_NOTIFICATIONS));
+ if (NotificationManagerCompat.from(getActivity()).areNotificationsEnabled()) MainActivity.csLibrary4A.appendToLog("Notification is enabled");
+ else MainActivity.csLibrary4A.appendToLog("Notification is disabled");
+ if (!MainActivity.foregroundServiceEnable) { }
+ else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
+ if (ActivityCompat.checkSelfPermission(mContext, POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
+ MainActivity.csLibrary4A.appendToLog("runnableStartService: requestPermissions POST_NOTIFICATIONS");
+ requestPermissions(new String[] { POST_NOTIFICATIONS }, 10); //POST_NOTIFICATIONS, FOREGROUND_SERVICE_LOCATION
+ } else {
+ MainActivity.csLibrary4A.appendToLog("runnableStartService: handled POST_NOTIFICATIONS");
+ startService();
+ }
+ } else {
+ MainActivity.csLibrary4A.appendToLog("runnableStartService: no need to handle POST_NOTIFICATIONS");
+ startService();
+ }
+ }
+ };
+ Intent serviceIntent;
+ Service serviceStarted;
+ public void startService() {
+ ActivityManager activityManager = (ActivityManager) getSystemService(getContext(), ActivityManager.class);
+ for (ActivityManager.RunningServiceInfo service: activityManager.getRunningServices(Integer.MAX_VALUE)) {
+ MainActivity.csLibrary4A.appendToLog("MyForegroundService.class.getName = " + MyForegroundService.class.getName() + ", service.service.getClassName = " + service.service.getClassName());
+ if (MyForegroundService.class.getName().equals(service.service.getClassName())) {
+ return;
+ }
+ }
+ serviceIntent = new Intent(getActivity(), MyForegroundService.class);
+ Log.i("Hello", "getActivity is " + (getActivity() == null ? "NULL" : "Valid"));
+ serviceIntent.putExtra("inputExtra", "Foreground Service Example in Android");
+ Log.i("Hello", "getContext is " + (getContext() == null ? "NULL" : "Valid"));
+ ContextCompat.startForegroundService(getContext(), serviceIntent);
+ }
+ public void stopService1() {
+ //Intent serviceIntent = new Intent(getActivity(), CustomForegroundService.class);
+ stopForeground(serviceStarted, STOP_FOREGROUND_REMOVE);
+ }
+
+ void popupAlert() {
+
+ }
+}
+
+
+
+package com.csl.cs710ademoapp.fragments;
+
+import android.os.Bundle;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.Button;
+
+import androidx.appcompat.app.ActionBar;
+import androidx.appcompat.app.AppCompatActivity;
+
+import com.csl.cs710ademoapp.MainActivity;
+import com.csl.cs710ademoapp.R;
+
+public class HomeSpecialFragment extends CommonFragment {
+ final boolean DEBUG = false;
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ super.onCreateView(inflater, container, savedInstanceState, true);
+ return inflater.inflate(R.layout.home_special_layout, container, false);
+ }
+
+ @Override
+ public void onActivityCreated(Bundle savedInstanceState) {
+ super.onActivityCreated(savedInstanceState);
+
+ if (((AppCompatActivity) getActivity()).getSupportActionBar() != null) {
+ ActionBar actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
+ actionBar.setTitle(R.string.title_activity_special);
+ }
+
+ Button buttonAuraSense = (Button) getActivity().findViewById(R.id.SpecialButtonAurasense);
+ Button buttonFdmicro = (Button) getActivity().findViewById(R.id.SpecialButtonFdmicro);
+ Button buttonLanda = (Button) getActivity().findViewById(R.id.SpecialButtonLanda);
+ if (MainActivity.csLibrary4A.get98XX() == 2) {
+ buttonAuraSense.setVisibility(View.GONE);
+ buttonFdmicro.setVisibility(View.GONE); buttonLanda.setVisibility(View.GONE);
+ }
+ MainActivity.tagType = null; MainActivity.mDid = null;
+ if (MainActivity.csLibrary4A.isBleConnected()) MainActivity.csLibrary4A.restoreAfterTagSelect();
+ }
+
+ public HomeSpecialFragment() {
+ super("HomeSpecialFragment");
+ }
+}
+
+
+
+package com.csl.cs710ademoapp.fragments;
+
+import android.os.Bundle;
+import android.view.LayoutInflater;
+import android.view.MenuItem;
+import android.view.View;
+import android.view.ViewGroup;
+
+import androidx.appcompat.app.ActionBar;
+import androidx.appcompat.app.AppCompatActivity;
+import androidx.viewpager.widget.ViewPager;
+
+import com.csl.cs710ademoapp.MainActivity;
+import com.csl.cs710ademoapp.R;
+import com.csl.cslibrary4a.AdapterTab;
+import com.google.android.material.tabs.TabLayout;
+
+public class HomeWFragment extends CommonFragment {
+ private ActionBar actionBar;
+ private ViewPager viewPager;
+ AdapterTab adapter;
+
+ private String[] tabs = {"Normal", "Simple"};
+ int iTargetOld, iSessionOld;
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ super.onCreateView(inflater, container, savedInstanceState, true);
+ return inflater.inflate(R.layout.custom_tabbed_layout, container, false);
+ }
+
+ @Override
+ public boolean onOptionsItemSelected(MenuItem item) {
+ InventoryRfidiMultiFragment fragment1 = (InventoryRfidiMultiFragment) adapter.fragment1;
+ if (item.getItemId() == R.id.menuAction_clear) {
+ fragment1.clearTagsList();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_sortRssi) {
+ fragment1.sortTagsListByRssi();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_sort) {
+ fragment1.sortTagsList();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_save) {
+ fragment1.saveTagsList();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_share) {
+ fragment1.shareTagsList();
+ return true;
+ } else return super.onOptionsItemSelected(item);
+ }
+
+ @Override
+ public void onActivityCreated(Bundle savedInstanceState) {
+ super.onActivityCreated(savedInstanceState);
+
+ actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
+ actionBar.setIcon(R.drawable.dl_inv);
+ actionBar.setTitle(R.string.title_activity_home_cs108);
+
+ TabLayout tabLayout = (TabLayout) getActivity().findViewById(R.id.OperationsTabLayout);
+
+ MainActivity.csLibrary4A.appendToLog("adaptoer is " + (adapter == null ? "null" : "valid"));
+ if (adapter != null) {
+ adapter.fragment0.onDestroy();
+ adapter.fragment1.onDestroy();
+ }
+
+ adapter = new AdapterTab(getActivity().getSupportFragmentManager(), tabs.length);
+ adapter.setFragment(0, new HomeFragment());
+ adapter.setFragment(1, new DirectWedgeFragment());
+
+ MainActivity.csLibrary4A.appendToLog("viewPager is " + (viewPager == null ? "null" : "valid"));
+ viewPager = (ViewPager) getActivity().findViewById(R.id.OperationsPager);
+ viewPager.setAdapter(null); viewPager.setAdapter(adapter);
+ viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
+
+ for (String tab_name : tabs) {
+ MainActivity.csLibrary4A.appendToLog("adding tab_name = " + tab_name);
+ tabLayout.addTab(tabLayout.newTab().setText(tab_name));
+ }
+
+ tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
+ @Override
+ public void onTabSelected(TabLayout.Tab tab) {
+ viewPager.setCurrentItem(tab.getPosition());
+ }
+
+ @Override
+ public void onTabUnselected(TabLayout.Tab tab) {
+ }
+
+ @Override
+ public void onTabReselected(TabLayout.Tab tab) {
+ }
+ });
+ }
+
+ @Override
+ public void onPause() {
+ adapter.fragment0.onPause();
+ adapter.fragment1.onPause();
+ super.onPause();
+ }
+
+ @Override
+ public void onStop() {
+ adapter.fragment0.onStop();
+ adapter.fragment1.onStop();
+ super.onStop();
+ }
+
+ @Override
+ public void onDestroyView() {
+ adapter.fragment0.onDestroyView();
+ adapter.fragment1.onDestroyView();
+ super.onDestroyView();
+ }
+
+ @Override
+ public void onDestroy() {
+ adapter.fragment0.onDestroy();
+ adapter.fragment1.onDestroy();
+ super.onDestroy();
+ }
+
+ @Override
+ public void onDetach() {
+ adapter.fragment0.onDetach();
+ adapter.fragment1.onDetach();
+ super.onDetach();
+ }
+
+ public HomeWFragment() {
+ super("HomeWFragment");
+ }
+}
+
+
+
+package com.csl.cs710ademoapp.fragments;
+
+import android.os.Bundle;
+import android.view.LayoutInflater;
+import android.view.MenuItem;
+import android.view.View;
+import android.view.ViewGroup;
+
+import androidx.appcompat.app.ActionBar;
+import androidx.appcompat.app.AppCompatActivity;
+import androidx.viewpager.widget.ViewPager;
+
+import com.csl.cs710ademoapp.MainActivity;
+import com.csl.cs710ademoapp.R;
+import com.csl.cslibrary4a.AdapterTab;
+import com.google.android.material.tabs.TabLayout;
+
+public class ImpinjFragment extends CommonFragment {
+ private ActionBar actionBar;
+ private ViewPager viewPager;
+ AdapterTab adapter;
+
+ private String[] tabs = {"Configure", "Scan", "Authenticate"};
+ int iTargetOld, iSessionOld;
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ super.onCreateView(inflater, container, savedInstanceState, true);
+ return inflater.inflate(R.layout.custom_tabbed_layout, container, false);
+ }
+
+ @Override
+ public boolean onOptionsItemSelected(MenuItem item) {
+ InventoryRfidiMultiFragment fragment = (InventoryRfidiMultiFragment) adapter.getItem(1);
+ if (item.getItemId() == R.id.menuAction_clear) {
+ fragment.clearTagsList();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_sortRssi) {
+ fragment.sortTagsListByRssi();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_sort) {
+ fragment.sortTagsList();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_save) {
+ fragment.saveTagsList();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_share) {
+ fragment.shareTagsList();
+ return true;
+ } else return super.onOptionsItemSelected(item);
+ }
+
+ @Override
+ public void onActivityCreated(Bundle savedInstanceState) {
+ super.onActivityCreated(savedInstanceState);
+
+ actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
+ actionBar.setIcon(R.drawable.dl_inv);
+ actionBar.setTitle(R.string.title_activity_impinj);
+
+ TabLayout tabLayout = (TabLayout) getActivity().findViewById(R.id.OperationsTabLayout);
+
+ adapter = new AdapterTab(getActivity().getSupportFragmentManager(), tabs.length);
+ adapter.setFragment(0, new AccessImpinjFragment(false));
+ adapter.setFragment(1, InventoryRfidiMultiFragment.newInstance(true, null, ""));
+ adapter.setFragment(2, new AccessUcodeFragment());
+
+ viewPager = (ViewPager) getActivity().findViewById(R.id.OperationsPager);
+ viewPager.setAdapter(adapter);
+ viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
+
+ for (String tab_name : tabs) {
+ tabLayout.addTab(tabLayout.newTab().setText(tab_name));
+ }
+
+ tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
+ @Override
+ public void onTabSelected(TabLayout.Tab tab) {
+ viewPager.setCurrentItem(tab.getPosition());
+ }
+
+ @Override
+ public void onTabUnselected(TabLayout.Tab tab) {
+ }
+
+ @Override
+ public void onTabReselected(TabLayout.Tab tab) {
+ }
+ });
+
+ iTargetOld = MainActivity.csLibrary4A.getQueryTarget();
+ iSessionOld = MainActivity.csLibrary4A.getQuerySession();
+ }
+
+ @Override
+ public void onPause() {
+ adapter.fragment0.onPause();
+ adapter.fragment1.onPause();
+ super.onPause();
+ }
+
+ @Override
+ public void onStop() {
+ adapter.fragment0.onStop();
+ adapter.fragment1.onStop();
+ super.onStop();
+ }
+
+ @Override
+ public void onDestroyView() {
+ adapter.fragment0.onDestroyView();
+ adapter.fragment1.onDestroyView();
+ super.onDestroyView();
+ }
+
+ @Override
+ public void onDestroy() {
+ adapter.fragment0.onDestroy();
+ adapter.fragment1.onDestroy();
+ MainActivity.csLibrary4A.setTagGroup(MainActivity.csLibrary4A.getQuerySelect(), iSessionOld, iTargetOld);
+ //MainActivity.mCs108Library4a.macWrite(0x203, 0);
+ super.onDestroy();
+ }
+
+ @Override
+ public void onDetach() {
+ adapter.fragment0.onDetach();
+ adapter.fragment1.onDetach();
+ super.onDetach();
+ }
+
+ public ImpinjFragment() {
+ super("ImpinjFragment");
+ }
+}
+
+
+
+package com.csl.cs710ademoapp.fragments;
+
+import static com.csl.cslibrary4a.RfidReader.TagType.TAG_IMPINJ_M755;
+
+import androidx.appcompat.app.ActionBar;
+import androidx.appcompat.app.AppCompatActivity;
+import androidx.viewpager.widget.ViewPager;
+
+import android.os.Bundle;
+import android.view.LayoutInflater;
+import android.view.MenuItem;
+import android.view.View;
+import android.view.ViewGroup;
+
+import com.csl.cs710ademoapp.MainActivity;
+import com.csl.cs710ademoapp.R;
+import com.csl.cslibrary4a.AdapterTab;
+import com.google.android.material.tabs.TabLayout;
+
+public class ImpinjM775Fragment extends CommonFragment {
+ private ActionBar actionBar;
+ private ViewPager viewPager;
+ AdapterTab adapter;
+
+ private String[] tabs = {"Configuration", "Scan"};
+ int iTargetOld, iSessionOld;
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ super.onCreateView(inflater, container, savedInstanceState, true);
+ return inflater.inflate(R.layout.custom_tabbed_layout, container, false);
+ }
+
+ @Override
+ public boolean onOptionsItemSelected(MenuItem item) {
+ InventoryRfidiMultiFragment fragment = (InventoryRfidiMultiFragment) adapter.getItem(1);
+ return fragment.onOptionsItemSelected(item);
+ }
+
+ @Override
+ public void onActivityCreated(Bundle savedInstanceState) {
+ super.onActivityCreated(savedInstanceState);
+
+ actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
+ actionBar.setIcon(R.drawable.dl_inv);
+ actionBar.setTitle(R.string.title_activity_m775);
+
+ TabLayout tabLayout = (TabLayout) getActivity().findViewById(R.id.OperationsTabLayout);
+
+ adapter = new AdapterTab(getActivity().getSupportFragmentManager(), tabs.length);
+ adapter.setFragment(0, new AccessImpinjFragment(true));
+ adapter.setFragment(1, InventoryRfidiMultiFragment.newInstance(true, TAG_IMPINJ_M755, "E2C011"));
+
+ viewPager = (ViewPager) getActivity().findViewById(R.id.OperationsPager);
+ viewPager.setAdapter(adapter);
+ viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
+
+ for (String tab_name : tabs) {
+ tabLayout.addTab(tabLayout.newTab().setText(tab_name));
+ }
+
+ tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
+ @Override
+ public void onTabSelected(TabLayout.Tab tab) {
+ viewPager.setCurrentItem(tab.getPosition());
+ }
+
+ @Override
+ public void onTabUnselected(TabLayout.Tab tab) {
+ }
+
+ @Override
+ public void onTabReselected(TabLayout.Tab tab) {
+ }
+ });
+
+ iTargetOld = MainActivity.csLibrary4A.getQueryTarget();
+ iSessionOld = MainActivity.csLibrary4A.getQuerySession();
+ }
+
+ @Override
+ public void onPause() {
+ adapter.fragment0.onPause();
+ adapter.fragment1.onPause();
+ super.onPause();
+ }
+
+ @Override
+ public void onStop() {
+ adapter.fragment0.onStop();
+ adapter.fragment1.onStop();
+ super.onStop();
+ }
+
+ @Override
+ public void onDestroyView() {
+ adapter.fragment0.onDestroyView();
+ adapter.fragment1.onDestroyView();
+ super.onDestroyView();
+ }
+
+ @Override
+ public void onDestroy() {
+ adapter.fragment0.onDestroy();
+ adapter.fragment1.onDestroy();
+ MainActivity.csLibrary4A.setTagGroup(MainActivity.csLibrary4A.getQuerySelect(), iSessionOld, iTargetOld);
+ //MainActivity.library4a.macWrite(0x203, 0);
+ super.onDestroy();
+ }
+
+ @Override
+ public void onDetach() {
+ adapter.fragment0.onDetach();
+ adapter.fragment1.onDetach();
+ super.onDetach();
+ }
+
+ public ImpinjM775Fragment() {
+ super("ImpinjM775Fragment");
+ }
+}
+
+
+
+package com.csl.cs710ademoapp.fragments;
+
+import android.content.Intent;
+import android.media.MediaPlayer;
+import android.os.AsyncTask;
+import android.os.Bundle;
+import android.view.LayoutInflater;
+import android.view.MenuItem;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.AdapterView;
+import android.widget.Button;
+import android.widget.ListView;
+import android.widget.TextView;
+import android.widget.Toast;
+
+import com.csl.cs710ademoapp.InventoryBarcodeTask;
+import com.csl.cs710ademoapp.MainActivity;
+import com.csl.cs710ademoapp.R;
+import com.csl.cs710ademoapp.SaveList2ExternalTask;
+import com.csl.cs710ademoapp.adapters.ReaderListAdapter;
+import com.csl.cslibrary4a.NotificationConnector;
+import com.csl.cslibrary4a.ReaderDevice;
+
+import java.util.Collections;
+
+public class InventoryBarcodeFragment extends CommonFragment {
+ private ListView barcodeListView;
+ private TextView barcodeEmptyView;
+ private TextView barcodeRunTime, barcodeVoltageLevel;
+ private TextView barcodeYieldView, barcodeTotal;
+ private Button button;
+
+ MediaPlayer playerO, playerN;
+
+ private ReaderListAdapter readerListAdapter;
+
+ InventoryBarcodeTask inventoryBarcodeTask;
+
+ void clearTagsList() {
+ barcodeYieldView.setText(""); barcodeTotal.setText("");
+ MainActivity.sharedObjects.barsList.clear();
+ readerListAdapter.notifyDataSetChanged();
+ }
+ void sortTagsList() {
+ Collections.sort(MainActivity.sharedObjects.barsList);
+ readerListAdapter.notifyDataSetChanged();
+ }
+ void saveTagsList() {
+ SaveList2ExternalTask saveExternalTask = new SaveList2ExternalTask(MainActivity.sharedObjects.barsList);
+ saveExternalTask.execute();
+ }
+ void shareTagsList() {
+ SaveList2ExternalTask saveExternalTask = new SaveList2ExternalTask(MainActivity.sharedObjects.barsList);
+ String stringOutput = saveExternalTask.createStrEpcList();
+
+ Intent sendIntent = new Intent();
+ sendIntent.setAction(Intent.ACTION_SEND);
+ sendIntent.putExtra(Intent.EXTRA_TEXT, stringOutput);
+ sendIntent.setType("text/plain");
+ startActivity(Intent.createChooser(sendIntent, "Sharing to"));
+ }
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ super.onCreateView(inflater, container, savedInstanceState, false);
+ return inflater.inflate(R.layout.fragment_inventory_barcode, container, false);
+ }
+
+ @Override
+ public boolean onOptionsItemSelected(MenuItem item) {
+ if (item.getItemId() == R.id.menuAction_clear) {
+ clearTagsList();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_sortRssi) {
+ //sortTagsListByRssi();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_sort) {
+ sortTagsList();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_save) {
+ saveTagsList();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_share) {
+ shareTagsList();
+ return true;
+ } else return super.onOptionsItemSelected(item);
+ }
+
+ @Override
+ public void onActivityCreated(Bundle savedInstanceState) {
+ super.onActivityCreated(savedInstanceState);
+
+ barcodeListView = (ListView) getActivity().findViewById(R.id.inventoryBarcodeList);
+ barcodeEmptyView = (TextView) getActivity().findViewById(R.id.inventoryBarcodeEmpty);
+ barcodeListView.setEmptyView(barcodeEmptyView);
+ readerListAdapter = new ReaderListAdapter(getActivity(), R.layout.readers_list_item, MainActivity.sharedObjects.barsList, true, false);
+ barcodeListView.setAdapter(readerListAdapter);
+ barcodeListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
+ barcodeListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
+ @Override
+ public void onItemClick(AdapterView> parent, View view, int position, long id) {
+ ReaderDevice readerDevice = readerListAdapter.getItem(position);
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("Position = " + position);
+ if (readerDevice.getSelected()) {
+ readerDevice.setSelected(false);
+ } else {
+ readerDevice.setSelected(true);
+ }
+ MainActivity.sharedObjects.barsList.set(position, readerDevice);
+ if (readerDevice.getSelected()) MainActivity.tagSelected = readerDevice;
+ else MainActivity.tagSelected = null;
+ for (int i = 0; i < MainActivity.sharedObjects.barsList.size(); i++) {
+ if (i != position) {
+ ReaderDevice readerDevice1 = MainActivity.sharedObjects.barsList.get(i);
+ if (readerDevice1.getSelected()) {
+ readerDevice1.setSelected(false);
+ MainActivity.sharedObjects.barsList.set(i, readerDevice1);
+ }
+ }
+ }
+ readerListAdapter.notifyDataSetChanged();
+ }
+ });
+
+ barcodeRunTime = (TextView) getActivity().findViewById(R.id.inventoryBarcodeRunTime);
+ barcodeVoltageLevel = (TextView) getActivity().findViewById(R.id.inventoryBarcodeVoltageLevel);
+
+ barcodeYieldView = (TextView) getActivity().findViewById(R.id.inventoryBarcodeYield);
+ button = (Button) getActivity().findViewById(R.id.inventoryBarcodeButton);
+ button.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ startStopHandler(false);
+ }
+ });
+
+ barcodeTotal = (TextView) getActivity().findViewById(R.id.inventoryBarcodeTotal);
+
+ MainActivity.csLibrary4A.getBarcodePreSuffix();
+ }
+
+ @Override
+ public void onResume() {
+ super.onResume();
+ if (true) MainActivity.csLibrary4A.appendToLog("InventoryBarcodeFragment().onResume(): userVisibleHint = " + userVisibleHint);
+ if (userVisibleHint) {
+ MainActivity.csLibrary4A.setAutoBarStartSTop(true); setNotificationListener();
+ }
+ }
+
+ @Override
+ public void onPause() {
+ if (MainActivity.csLibrary4A != null) MainActivity.csLibrary4A.setNotificationListener(null);
+ if (inventoryBarcodeTask != null) {
+ if (DEBUG && MainActivity.csLibrary4A != null) MainActivity.csLibrary4A.appendToLog("InventoryBarcodeFragment().onDestory(): VALID inventoryBarcodeTask");
+ inventoryBarcodeTask.taskCancelReason = InventoryBarcodeTask.TaskCancelRReason.DESTORY;
+ }
+ super.onPause();
+ }
+
+ @Override
+ public void onDestroy() {
+ if (MainActivity.csLibrary4A != null) {
+ MainActivity.csLibrary4A.setAutoBarStartSTop(false);
+ MainActivity.csLibrary4A.setNotificationListener(null);
+ }
+ super.onDestroy();
+ }
+
+ boolean userVisibleHint = false;
+ @Override
+ public void setUserVisibleHint(boolean isVisibleToUser) {
+ super.setUserVisibleHint(isVisibleToUser);
+ if(getUserVisibleHint()) {
+ MainActivity.csLibrary4A.appendToLog("InventoryBarcodeFragment is now VISIBLE");
+ userVisibleHint = true;
+ MainActivity.csLibrary4A.setAutoBarStartSTop(true); setNotificationListener();
+ } else {
+ MainActivity.csLibrary4A.appendToLog("InventoryBarcodeFragment is now INVISIBLE");
+ userVisibleHint = false;
+ MainActivity.csLibrary4A.setAutoBarStartSTop(false); MainActivity.csLibrary4A.setNotificationListener(null);
+ }
+ }
+
+ public InventoryBarcodeFragment() {
+ super("InventoryBarcodeFragment");
+ }
+
+ void setNotificationListener() {
+ MainActivity.csLibrary4A.setNotificationListener(new NotificationConnector.NotificationListener() {
+ @Override
+ public void onChange() {
+ startStopHandler(true);
+ }
+ });
+ }
+
+ void startStopHandler(boolean buttonTrigger) {
+ if (buttonTrigger) MainActivity.csLibrary4A.appendToLog("BARTRIGGER: getTriggerButtonStatus = " + MainActivity.csLibrary4A.getTriggerButtonStatus());
+ if (MainActivity.sharedObjects.runningInventoryRfidTask) {
+ Toast.makeText(MainActivity.mContext, "Running RFID inventory", Toast.LENGTH_SHORT).show();
+ return;
+ }
+ boolean started = false;
+ if (inventoryBarcodeTask != null) if (inventoryBarcodeTask.getStatus() == AsyncTask.Status.RUNNING) started = true;
+ if (buttonTrigger && ((started && MainActivity.csLibrary4A.getTriggerButtonStatus()) || (started == false && MainActivity.csLibrary4A.getTriggerButtonStatus() == false))) {
+ MainActivity.csLibrary4A.appendToLog("BARTRIGGER: trigger ignore");
+ return;
+ }
+ if (started == false) {
+ if (MainActivity.csLibrary4A.isBleConnected() == false) {
+ Toast.makeText(MainActivity.mContext, R.string.toast_ble_not_connected, Toast.LENGTH_SHORT).show();
+ return;
+ }
+ if (MainActivity.csLibrary4A.isBarcodeFailure()) {
+ Toast.makeText(MainActivity.mContext, "Barcode is disabled", Toast.LENGTH_SHORT).show();
+ return;
+ }
+ MainActivity.csLibrary4A.appendToLog("BARTRIGGER: Start Barcode inventory");
+ started = true;
+ inventoryBarcodeTask = new InventoryBarcodeTask(MainActivity.sharedObjects.barsList, readerListAdapter, null, barcodeRunTime, barcodeVoltageLevel, barcodeYieldView, button, null, barcodeTotal, false);
+ inventoryBarcodeTask.execute();
+ } else {
+ MainActivity.csLibrary4A.appendToLog("BARTRIGGER: Stop Barcode inventory");
+ if (buttonTrigger) inventoryBarcodeTask.taskCancelReason = InventoryBarcodeTask.TaskCancelRReason.BUTTON_RELEASE;
+ else inventoryBarcodeTask.taskCancelReason = InventoryBarcodeTask.TaskCancelRReason.STOP;
+ }
+ }
+}
+
+
+
+package com.csl.cs710ademoapp.fragments;
+
+import android.os.Bundle;
+import android.util.Log;
+import android.view.LayoutInflater;
+import android.view.MenuItem;
+import android.view.View;
+import android.view.ViewGroup;
+
+import androidx.appcompat.app.ActionBar;
+import androidx.appcompat.app.AppCompatActivity;
+import androidx.viewpager.widget.ViewPager;
+
+import com.csl.cs710ademoapp.MainActivity;
+import com.csl.cs710ademoapp.R;
+import com.csl.cslibrary4a.AdapterTab;
+import com.google.android.material.tabs.TabLayout;
+
+public class InventoryFragment extends CommonFragment {
+ private ActionBar actionBar;
+ private ViewPager viewPager;
+ AdapterTab adapter;
+
+ private String[] tabs = {"RFID", "Barcode"};
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ savedInstanceState = null;
+ super.onCreateView(inflater, container, savedInstanceState, true);
+ return inflater.inflate(R.layout.custom_tabbed_layout, container, false);
+ }
+
+ @Override
+ public boolean onOptionsItemSelected(MenuItem item) {
+ MainActivity.csLibrary4A.appendToLog("InventoryFragment: onOptionsItemSelected with viewPager as " + viewPager.getCurrentItem());
+ InventoryRfidiMultiFragment fragment0 = (InventoryRfidiMultiFragment) adapter.getItem(0);
+ InventoryBarcodeFragment fragment1 = (InventoryBarcodeFragment) adapter.getItem(1);
+ switch (viewPager.getCurrentItem()) {
+ case 0:
+ return fragment0.onOptionsItemSelected(item);
+ case 1:
+ return fragment1.onOptionsItemSelected(item);
+ default:
+ return super.onOptionsItemSelected(item);
+ }
+ }
+
+ @Override
+ public void onActivityCreated(Bundle savedInstanceState) {
+ super.onActivityCreated(savedInstanceState);
+
+ actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
+ actionBar.setIcon(R.drawable.dl_inv);
+ actionBar.setTitle(R.string.title_activity_inventory);
+
+ TabLayout tabLayout = (TabLayout) getActivity().findViewById(R.id.OperationsTabLayout);
+
+ adapter = new AdapterTab(getActivity().getSupportFragmentManager(), tabs.length);
+ adapter.setFragment(0, InventoryRfidiMultiFragment.newInstance(false, null, null));
+ adapter.setFragment(1, new InventoryBarcodeFragment());
+
+ viewPager = (ViewPager) getActivity().findViewById(R.id.OperationsPager);
+ Log.i("Hello", "InventoryFragment.onActivity");
+ viewPager.setAdapter(adapter);
+ viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
+
+ for (String tab_name : tabs) {
+ tabLayout.addTab(tabLayout.newTab().setText(tab_name));
+ }
+
+ tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
+ @Override
+ public void onTabSelected(TabLayout.Tab tab) {
+ viewPager.setCurrentItem(tab.getPosition());
+ }
+
+ @Override
+ public void onTabUnselected(TabLayout.Tab tab) {
+ }
+
+ @Override
+ public void onTabReselected(TabLayout.Tab tab) {
+ }
+ });
+ }
+
+ @Override
+ public void onPause() {
+ adapter.fragment0.onPause();
+ adapter.fragment1.onPause();
+ super.onPause();
+ }
+
+ @Override
+ public void onStop() {
+ adapter.fragment0.onStop();
+ adapter.fragment1.onStop();
+ super.onStop();
+ }
+
+ @Override
+ public void onDestroyView() {
+ adapter.fragment0.onDestroyView();
+ adapter.fragment1.onDestroyView();
+ super.onDestroyView();
+ }
+
+ @Override
+ public void onDestroy() {
+ adapter.fragment0.onDestroy();
+ adapter.fragment1.onDestroy();
+ super.onDestroy();
+ }
+
+ @Override
+ public void onDetach() {
+ adapter.fragment0.onDetach();
+ adapter.fragment1.onDetach();
+ super.onDetach();
+ }
+
+ public InventoryFragment() {
+ super("InventoryFragment");
+ }
+}
+
+
+
+package com.csl.cs710ademoapp.fragments;
+
+import static com.csl.cslibrary4a.RfidReader.TagType.TAG_ASYGN;
+import static com.csl.cslibrary4a.RfidReader.TagType.TAG_CTESIUS;
+
+import android.content.Intent;
+import android.os.AsyncTask;
+import android.os.Bundle;
+import android.util.Log;
+import android.view.LayoutInflater;
+import android.view.MenuItem;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.AbsListView;
+import android.widget.AdapterView;
+import android.widget.ArrayAdapter;
+import android.widget.Button;
+import android.widget.CheckBox;
+import android.widget.EditText;
+import android.widget.LinearLayout;
+import android.widget.ListView;
+import android.widget.Spinner;
+import android.widget.TextView;
+import android.widget.Toast;
+
+import androidx.appcompat.app.ActionBar;
+import androidx.appcompat.app.AppCompatActivity;
+
+import com.csl.cs710ademoapp.CustomPopupWindow;
+import com.csl.cs710ademoapp.GenericTextWatcher;
+import com.csl.cs710ademoapp.InventoryRfidTask;
+import com.csl.cs710ademoapp.MainActivity;
+import com.csl.cs710ademoapp.R;
+import com.csl.cs710ademoapp.SaveList2ExternalTask;
+import com.csl.cs710ademoapp.adapters.ReaderListAdapter;
+import com.csl.cslibrary4a.NotificationConnector;
+import com.csl.cslibrary4a.ReaderDevice;
+import com.csl.cslibrary4a.RfidReader;
+import com.csl.cslibrary4a.RfidReaderChipData;
+
+import java.util.Collections;
+import java.util.Comparator;
+
+public class InventoryRfidiMultiFragment extends CommonFragment {
+ final private boolean bAdd2End = false;
+ private boolean bMultiBank = false, bMultiBankInventory = false, bctesiusInventory = false;
+ private RfidReader.TagType tagType;
+ private String mDid = null;
+ int vibrateTimeBackup = 0;
+
+ private CheckBox checkBoxDupElim, checkBoxFilterByTid, checkBoxFilterByEpc, checkBoxFilterByProtect;
+ private EditText editTextProtectPassword;
+ private Spinner spinnerBank1, spinnerBank2;
+ private ListView rfidListView;
+ private TextView rfidEmptyView;
+ private TextView rfidRunTime, rfidVoltageLevel;
+ private TextView rfidYieldView;
+ private TextView rfidRateView;
+ private Button button;
+
+ private ReaderListAdapter readerListAdapter;
+ private InventoryRfidTask inventoryRfidTask;
+
+ void clearTagsList() {
+ MainActivity.csLibrary4A.appendToLog("InventoryRfidMultiFragment: NOT onOptionsItemSelected: clearTagsList");
+ MainActivity.csLibrary4A.appendToLog("runningInventoryRfidTask = " + MainActivity.sharedObjects.runningInventoryRfidTask + ", readerListAdapter" + (readerListAdapter != null ? " tagCount = " + String.valueOf(readerListAdapter.getCount()) : " = NULL"));
+ if (MainActivity.sharedObjects.runningInventoryRfidTask) return;
+ rfidYieldView.setText("");
+ rfidRateView.setText("");
+ MainActivity.tagSelected = null;
+ MainActivity.sharedObjects.tagsList.clear();
+ MainActivity.sharedObjects.tagsIndexList.clear();
+ readerListAdapter.notifyDataSetChanged();
+ MainActivity.mLogView.setText("");
+ }
+ void sortTagsList() {
+ if (MainActivity.sharedObjects.runningInventoryRfidTask) return;
+ Collections.sort(MainActivity.sharedObjects.tagsList);
+ readerListAdapter.notifyDataSetChanged();
+ }
+ void sortTagsListByRssi() {
+ if (MainActivity.sharedObjects.runningInventoryRfidTask) return;
+ Collections.sort(MainActivity.sharedObjects.tagsList, new Comparator() {
+ @Override
+ public int compare(ReaderDevice deviceTag, ReaderDevice t1) {
+ if (deviceTag.getRssi() == t1.getRssi()) return 0;
+ else if (deviceTag.getRssi() < t1.getRssi()) return 1;
+ else return -1;
+ }
+ });
+ readerListAdapter.notifyDataSetChanged();
+ }
+ void saveTagsList() {
+ if (MainActivity.sharedObjects.runningInventoryRfidTask) return;
+ SaveList2ExternalTask saveExternalTask = new SaveList2ExternalTask(MainActivity.sharedObjects.tagsList);
+ saveExternalTask.execute();
+ }
+ void shareTagsList() {
+ SaveList2ExternalTask saveExternalTask = new SaveList2ExternalTask(MainActivity.sharedObjects.tagsList);
+ String stringOutput = saveExternalTask.createStrEpcList();
+
+ Intent sendIntent = new Intent();
+ sendIntent.setAction(Intent.ACTION_SEND);
+ sendIntent.putExtra(Intent.EXTRA_TEXT, stringOutput);
+ sendIntent.setType("text/plain");
+ startActivity(Intent.createChooser(sendIntent, "Sharing to"));
+ }
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ super.onCreateView(inflater, container, savedInstanceState, bMultiBankInventory | bctesiusInventory);
+ return inflater.inflate(R.layout.fragment_inventory_rfid_multi, container, false);
+ }
+
+ @Override
+ public boolean onOptionsItemSelected(MenuItem item) {
+ MainActivity.csLibrary4A.appendToLog("InventoryRfidMultiFragment: onOptionsItemSelected");
+ if (item.getItemId() == R.id.menuAction_clear) {
+ clearTagsList();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_sortRssi) {
+ sortTagsListByRssi();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_sort) {
+ sortTagsList();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_save) {
+ saveTagsList();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_share) {
+ shareTagsList();
+ return true;
+ } else return super.onOptionsItemSelected(item);
+ }
+
+ @Override
+ public void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ if (getArguments() != null) {
+ bMultiBank = getArguments().getBoolean("bMultiBank");
+ mDid = getArguments().getString("mDid");
+ try {
+ int iValue = getArguments().getInt("enumTagType");
+ MainActivity.csLibrary4A.appendToLog("onCreate: enumTagType iValue = " + iValue);
+ tagType = RfidReader.TagType.values()[iValue];
+ MainActivity.csLibrary4A.appendToLog("onCreate: enumTagType = " + tagType.toString());
+ } catch (Exception e) { }
+ if (bMultiBank && mDid == null) {
+ bMultiBankInventory = true;
+ } else if (bMultiBank && mDid != null) {
+ if (mDid.matches("E2003")
+ || mDid.matches("E200B0")
+ || (tagType == TAG_CTESIUS /*mDid.matches("E203510"*/)
+ || (tagType == TAG_ASYGN /*mDid.matches("E283A")*/)) {
+ bctesiusInventory = true;
+ }
+ }
+ }
+ }
+
+ @Override
+ public void onActivityCreated(Bundle savedInstanceState) {
+ super.onActivityCreated(savedInstanceState);
+
+ MainActivity.selectFor = -1;
+ if (bMultiBankInventory | bctesiusInventory) {
+ ActionBar actionBar;
+ actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
+ actionBar.setIcon(R.drawable.dl_inv);
+ if (bMultiBankInventory) actionBar.setTitle(R.string.title_activity_inventoryRfidMulti);
+ else if (bctesiusInventory) {
+ if (mDid.matches("E2003")) actionBar.setTitle("Alien");
+ else if (mDid.matches("E200B0")) actionBar.setTitle(R.string.title_activity_bap);
+ else if (tagType == TAG_CTESIUS /*mDid.matches("E203510")*/) actionBar.setTitle(R.string.title_activity_ctesisu);
+ else if (tagType == TAG_ASYGN /*mDid.matches("E283A")*/) actionBar.setTitle("AS321x");
+ }
+ }
+ if (bMultiBankInventory) {
+ LinearLayout linearLayout = (LinearLayout) getActivity().findViewById(R.id.inventoryMultibankSetting);
+ linearLayout.setVisibility(View.VISIBLE);
+ checkBoxDupElim = (CheckBox) getActivity().findViewById(R.id.accessInventoryDupElim);
+ checkBoxDupElim.setVisibility(View.VISIBLE);
+ checkBoxDupElim.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View view) {
+ if (checkBoxDupElim.isChecked()) readerListAdapter.setSelectDupElim(true);
+ else readerListAdapter.setSelectDupElim(false);
+ }
+ });
+ }
+
+ checkBoxFilterByTid = (CheckBox) getActivity().findViewById(R.id.accessInventoryFilterByTid);
+ MainActivity.csLibrary4A.appendToLog("InventoryRfidMultiFragment.onActivityCreated: mDid = " + mDid + ", MainActivity.mDid = " + MainActivity.mDid);
+ if (mDid != null) {
+ if (mDid.indexOf("E2827001") == 0) {
+ checkBoxFilterByTid.setVisibility(View.VISIBLE);
+ //checkBoxFilterByTid.setText("filter FM13DT160 only");
+ }
+ } else if (bMultiBankInventory == false) {
+ checkBoxFilterByEpc = (CheckBox) getActivity().findViewById(R.id.accessInventoryFilterByEpc);
+ checkBoxFilterByEpc.setVisibility(View.VISIBLE);
+ }
+
+ checkBoxFilterByProtect = (CheckBox) getActivity().findViewById(R.id.accessInventoryFilterByProtect);
+ editTextProtectPassword = (EditText) getActivity().findViewById(R.id.accessInventoryProtectPassword);
+ editTextProtectPassword.addTextChangedListener(new GenericTextWatcher(editTextProtectPassword, 8));
+ editTextProtectPassword.setText("00000000");
+
+ ArrayAdapter lockAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.memoryBank_options, R.layout.custom_spinner_layout);
+ lockAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+
+ spinnerBank1 = (Spinner) getActivity().findViewById(R.id.accessInventoryBank1);
+ spinnerBank1.setAdapter(lockAdapter); spinnerBank1.setSelection(2);
+ spinnerBank2 = (Spinner) getActivity().findViewById(R.id.accessInventoryBank2);
+ spinnerBank2.setAdapter(lockAdapter); spinnerBank2.setSelection(3);
+
+ rfidListView = (ListView) getActivity().findViewById(R.id.inventoryRfidList1);
+ rfidEmptyView = (TextView) getActivity().findViewById(R.id.inventoryRfidEmpty1);
+ rfidListView.setEmptyView(rfidEmptyView);
+ boolean bSelect4detail = true;
+ if (bMultiBankInventory) bSelect4detail = false;
+ boolean needDupElim = true;
+
+ boolean need4Extra1 = MainActivity.csLibrary4A.getPortNumber() > 1 ? true : false;
+ boolean need4Extra2 = (mDid != null ? true : false);
+
+ readerListAdapter = new ReaderListAdapter(getActivity(), R.layout.readers_list_item, MainActivity.sharedObjects.tagsList, bSelect4detail, true, needDupElim, need4Extra1, need4Extra2);
+ rfidListView.setAdapter(readerListAdapter);
+ rfidListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
+ rfidListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
+ @Override
+ public void onItemClick(AdapterView> parent, View view, int position, long id) {
+ ReaderDevice readerDevice = readerListAdapter.getItem(position);
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("Position = " + position);
+ if (readerDevice.getSelected()) {
+ readerDevice.setSelected(false);
+ } else {
+ readerDevice.setSelected(true);
+ String strPopup = readerDevice.getUpcSerial();
+ MainActivity.csLibrary4A.appendToLog("strPopup = " + (strPopup == null ? "null" : strPopup));
+ if (strPopup != null && strPopup.trim().length() != 0) {
+ strPopup = MainActivity.csLibrary4A.getUpcSerialDetail(strPopup);
+ CustomPopupWindow epcSerialPopupWindow = new CustomPopupWindow(MainActivity.mContext);
+ epcSerialPopupWindow.popupStart(strPopup, false);
+ }
+ }
+ MainActivity.sharedObjects.tagsList.set(position, readerDevice);
+ if (readerDevice.getSelected()) MainActivity.tagSelected = readerDevice;
+ else MainActivity.tagSelected = null;
+ for (int i = 0; i < MainActivity.sharedObjects.tagsList.size(); i++) {
+ if (i != position) {
+ ReaderDevice readerDevice1 = MainActivity.sharedObjects.tagsList.get(i);
+ if (readerDevice1.getSelected()) {
+ readerDevice1.setSelected(false);
+ MainActivity.sharedObjects.tagsList.set(i, readerDevice1);
+ }
+ }
+ }
+ readerListAdapter.notifyDataSetChanged();
+ }
+ });
+
+ rfidRunTime = (TextView) getActivity().findViewById(R.id.inventoryRfidRunTime1);
+ rfidVoltageLevel = (TextView) getActivity().findViewById(R.id.inventoryRfidVoltageLevel1);
+ TextView rfidFilterOn = (TextView) getActivity().findViewById(R.id.inventoryRfidFilterOn1);
+ if (mDid != null || (MainActivity.csLibrary4A.getSelectEnable() == false && MainActivity.csLibrary4A.getInvMatchEnable() == false && MainActivity.csLibrary4A.getRssiFilterEnable() == false))
+ rfidFilterOn.setVisibility(View.INVISIBLE);
+
+ rfidYieldView = (TextView) getActivity().findViewById(R.id.inventoryRfidYield1);
+ rfidRateView = (TextView) getActivity().findViewById(R.id.inventoryRfidRate1);
+ button = (Button) getActivity().findViewById(R.id.inventoryRfidButton1);
+ button.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ startStopHandler(false);
+ }
+ });
+
+ vibrateTimeBackup = MainActivity.csLibrary4A.getVibrateTime();
+ final Button buttonT1 = (Button) getActivity().findViewById(R.id.inventoryRfidButtonT1);
+ buttonT1.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ String buttonText = buttonT1.getText().toString().trim();
+ if (buttonText.toUpperCase().matches("BUZ")) {
+ MainActivity.csLibrary4A.appendToLog("setVibrateOn G 1");
+ MainActivity.csLibrary4A.setVibrateTime(0); MainActivity.csLibrary4A.setVibrateOn(1);
+ buttonT1.setText("STOP");
+ }
+ else {
+ MainActivity.csLibrary4A.appendToLog("setVibrateOn H 0");
+ MainActivity.csLibrary4A.setVibrateOn(0);
+ buttonT1.setText("BUZ");
+ }
+ }
+ });
+ }
+
+ @Override
+ public void onResume() {
+ super.onResume();
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("InventoryRfidiMultiFragment().onResume(): userVisibleHint = " + userVisibleHint);
+ if (userVisibleHint) setNotificationListener();
+ }
+
+ @Override
+ public void onPause() {
+ MainActivity.csLibrary4A.setNotificationListener(null);
+ super.onPause();
+ }
+
+ @Override
+ public void onDestroy() {
+ mHandler.removeCallbacks(runnableCheckReady);
+ if (MainActivity.csLibrary4A != null) MainActivity.csLibrary4A.setNotificationListener(null);
+ if (inventoryRfidTask != null) {
+ inventoryRfidTask.taskCancelReason = InventoryRfidTask.TaskCancelRReason.DESTORY;
+ if (MainActivity.csLibrary4A != null) {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("InventoryRfidiMultiFragment().onDestory(): VALID inventoryRfidTask");
+ MainActivity.csLibrary4A.abortOperation(); //added in case inventoryRiidTask is removed
+ }
+ }
+ if (MainActivity.csLibrary4A != null) {
+ MainActivity.csLibrary4A.setSameCheck(true);
+ MainActivity.csLibrary4A.setInvBrandId(false);
+ resetSelectData();
+ MainActivity.csLibrary4A.setVibrateTime(vibrateTimeBackup);
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("InventoryRfidiMultiFragment().onDestory(): onDestory()");
+ }
+ super.onDestroy();
+ }
+
+ boolean userVisibleHint = true;
+ @Override
+ public void setUserVisibleHint(boolean isVisibleToUser) {
+ super.setUserVisibleHint(isVisibleToUser);
+ if(getUserVisibleHint()) {
+ userVisibleHint = true;
+ MainActivity.csLibrary4A.appendToLog("InventoryRfidiMultiFragment is now VISIBLE");
+ MainActivity.csLibrary4A.appendToLog("11 mDid = " + mDid + ", MainActivity.mDid = " + MainActivity.mDid);
+ if (MainActivity.mDid != null && MainActivity.mDid.indexOf("E28011") == 0) {
+ int iValue = Integer.valueOf(MainActivity.mDid.substring(6, 8), 16);
+ iValue &= 0x0F;
+ MainActivity.csLibrary4A.appendToLog(String.format("iValue = 0x%X", iValue));
+ if (iValue > 0 && iValue < 6) {
+ checkBoxFilterByProtect.setVisibility(View.VISIBLE);
+ editTextProtectPassword.setVisibility(View.VISIBLE);
+ } else {
+ checkBoxFilterByProtect.setVisibility(View.GONE); checkBoxFilterByProtect.setChecked(false);
+ editTextProtectPassword.setVisibility(View.GONE);
+ }
+ }
+ MainActivity.csLibrary4A.appendToLog("setNotificationListener in multibank inventory");
+ setNotificationListener();
+ } else {
+ userVisibleHint = false;
+ MainActivity.csLibrary4A.appendToLog("InventoryRfidiMultiFragment is now INVISIBLE");
+ MainActivity.csLibrary4A.appendToLog("setNotificationListener null in multibank inventory");
+ MainActivity.csLibrary4A.setNotificationListener(null);
+ if (inventoryRfidTask != null) {
+ inventoryRfidTask.taskCancelReason = InventoryRfidTask.TaskCancelRReason.STOP;
+ }
+ }
+ }
+
+ public static InventoryRfidiMultiFragment newInstance(boolean bMultiBank, RfidReader.TagType tagType, String mDid) {
+ InventoryRfidiMultiFragment myFragment = new InventoryRfidiMultiFragment();
+
+ Bundle args = new Bundle();
+ MainActivity.csLibrary4A.appendToLog("newInstance: enumTagType = " + (tagType == null ? "null" : tagType.toString()));
+ if (tagType != null) args.putInt("enumTagType", tagType.ordinal());
+ args.putBoolean("bMultiBank", bMultiBank);
+ args.putString("mDid", mDid);
+ myFragment.setArguments(args);
+
+ return myFragment;
+ }
+ public InventoryRfidiMultiFragment() {
+ super("InventoryRfidiMultiFragment");
+ }
+
+ void setNotificationListener() {
+ MainActivity.csLibrary4A.appendToLog("setNotificationListener A in multibank inventory");
+ MainActivity.csLibrary4A.setNotificationListener(new NotificationConnector.NotificationListener() {
+ @Override
+ public void onChange() {
+ MainActivity.csLibrary4A.appendToLog("setNotificationListener TRIGGER key is pressed in multibank inventory.");
+ startStopHandler(true);
+ }
+ });
+ }
+
+ boolean needResetData = false;
+ void resetSelectData() {
+ MainActivity.csLibrary4A.appendToLog("InventoryRfidMultiFragment.resetSelectData: mDid = " + mDid + ", MainActivity.mDid = " + MainActivity.mDid);
+ if (MainActivity.mDid != null && MainActivity.mDid.indexOf("E282405") == 0) { }
+ else MainActivity.csLibrary4A.restoreAfterTagSelect();
+ if (needResetData) {
+ MainActivity.csLibrary4A.setTagRead(0);
+ MainActivity.csLibrary4A.setAccessBank(1);
+ MainActivity.csLibrary4A.setAccessOffset(0);
+ MainActivity.csLibrary4A.setAccessCount(0);
+ needResetData = false;
+ }
+ if (mDid != null && tagType == TAG_CTESIUS /*mDid.matches("E203510")*/) MainActivity.csLibrary4A.setSelectCriteriaDisable(1);
+ }
+ void startStopHandler(boolean buttonTrigger) {
+ MainActivity.csLibrary4A.appendToLog("0 buttonTrigger is " + buttonTrigger);
+ if (buttonTrigger) MainActivity.csLibrary4A.appendToLog("BARTRIGGER: getTriggerButtonStatus = " + MainActivity.csLibrary4A.getTriggerButtonStatus());
+ if (MainActivity.sharedObjects.runningInventoryBarcodeTask) {
+ Toast.makeText(MainActivity.mContext, "Running barcode inventory", Toast.LENGTH_SHORT).show();
+ return;
+ }
+ boolean started = false;
+ if (inventoryRfidTask != null) if (inventoryRfidTask.getStatus() == AsyncTask.Status.RUNNING) started = true;
+ if (buttonTrigger && ((started && MainActivity.csLibrary4A.getTriggerButtonStatus()) || (started == false && MainActivity.csLibrary4A.getTriggerButtonStatus() == false))) {
+ MainActivity.csLibrary4A.appendToLog("BARTRIGGER: trigger ignore");
+ return;
+ }
+ if (started == false) {
+ if (MainActivity.csLibrary4A.isBleConnected() == false) {
+ Toast.makeText(MainActivity.mContext, R.string.toast_ble_not_connected, Toast.LENGTH_SHORT).show();
+ return;
+ } else if (MainActivity.csLibrary4A.isRfidFailure()) {
+ Toast.makeText(MainActivity.mContext, "Rfid is disabled", Toast.LENGTH_SHORT).show();
+ return;
+ } else if (MainActivity.csLibrary4A.mrfidToWriteSize() != 0) {
+ //Toast.makeText(MainActivity.mContext, R.string.toast_not_ready, Toast.LENGTH_SHORT).show();
+ mHandler.post(runnableCheckReady);
+ return;
+ }
+ if (bAdd2End) rfidListView.setTranscriptMode(AbsListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
+ else rfidListView.setSelection(0);
+ startInventoryTask();
+ } else if (MainActivity.csLibrary4A.mrfidToWriteSize() == 0) {
+ if (bAdd2End) rfidListView.setTranscriptMode(AbsListView.TRANSCRIPT_MODE_NORMAL);
+ if (buttonTrigger) inventoryRfidTask.taskCancelReason = InventoryRfidTask.TaskCancelRReason.BUTTON_RELEASE;
+ else inventoryRfidTask.taskCancelReason = InventoryRfidTask.TaskCancelRReason.STOP;
+ MainActivity.csLibrary4A.appendToLogView("CANCELLING: StartStopHandler generates taskCancelReason = " + inventoryRfidTask.taskCancelReason.toString());
+ } else MainActivity.csLibrary4A.appendToLog("BtData. Stop when still writing !!!");
+ }
+ void startInventoryTask() {
+ MainActivity.csLibrary4A.appendToLog("startInventoryTask");
+ //RfidReader.ExtraBankData extraBankData = new RfidReader.ExtraBankData();
+ String mDid = this.mDid;
+
+ MainActivity.csLibrary4A.appendToLog("Rin: mDid = " + (mDid == null ? "null" : mDid) + ", MainActivity.mDid = " + MainActivity.mDid + ", bMultiBankInventory = " + bMultiBankInventory);
+ if (mDid != null && MainActivity.mDid != null) {
+ if (MainActivity.mDid.indexOf("E280B12") != 0) mDid = MainActivity.mDid;
+ }
+
+ RfidReader.ExtraBankData extraBankData = new RfidReader.ExtraBankData();
+ if (mDid != null) extraBankData.setExtraBankData(MainActivity.tagType, mDid);
+ else if (bMultiBank) {
+ CheckBox checkBox = (CheckBox) getActivity().findViewById(R.id.accessInventoryBankTitle1);
+ int extra1Bank = 0, extra2Bank = 0;
+ int extra1Count, extra2Count;
+ int extra1Offset = 0, extra2Offset = 0;
+ if (checkBox.isChecked()) {
+ extra1Bank = spinnerBank1.getSelectedItemPosition();
+ EditText editText = (EditText) getActivity().findViewById(R.id.accessInventoryOffset1);
+ extra1Offset = Integer.valueOf(editText.getText().toString());
+ editText = (EditText) getActivity().findViewById(R.id.accessInventoryLength1);
+ extra1Count = Integer.valueOf(editText.getText().toString());
+ } else extra1Count = 0;
+ checkBox = (CheckBox) getActivity().findViewById(R.id.accessInventoryBankTitle2);
+ if (checkBox.isChecked()) {
+ extra2Bank = spinnerBank2.getSelectedItemPosition();
+ EditText editText = (EditText) getActivity().findViewById(R.id.accessInventoryOffset2);
+ extra2Offset = Integer.valueOf(editText.getText().toString());
+ editText = (EditText) getActivity().findViewById(R.id.accessInventoryLength2);
+ extra2Count = Integer.valueOf(editText.getText().toString());
+ } else extra2Count = 0;
+ extraBankData.setExtraBankData(extra1Bank, extra1Count, extra1Offset, extra2Bank, extra2Count, extra2Offset);
+ }
+
+ if (mDid != null) {
+ MainActivity.csLibrary4A.appendToLog("mDid is valid as " + mDid);
+ if (MainActivity.mDid != null && mDid.length() == 0) mDid = MainActivity.mDid;
+ MainActivity.csLibrary4A.appendToLog("new mDid is " + mDid);
+
+ MainActivity.csLibrary4A.appendToLog("mDid = " + mDid);
+ if (tagType == TAG_CTESIUS /*mDid.matches("E203510")*/) {
+ if (MainActivity.csLibrary4A.get98XX() == 2) MainActivity.csLibrary4A.setCurrentLinkProfile(1); //set profile 302
+ } else if (tagType == TAG_ASYGN /*mDid.matches("E283A")*/) {
+ if (MainActivity.csLibrary4A.get98XX() == 2) MainActivity.csLibrary4A.setCurrentLinkProfile(9); //set profile 244
+ } else if (mDid.matches("E282405")) {
+ if (MainActivity.csLibrary4A.getRetryCount() < 2) MainActivity.csLibrary4A.setRetryCount(2);
+ }
+ boolean bNeedSelectedTagByTID = true;
+ if (mDid.indexOf("E2806894") == 0) {
+ Log.i(TAG, "HelloK: Find E2806894 with MainActivity.mDid = " + MainActivity.mDid + ", mDid = " + mDid);
+ if (mDid.matches("E2806894A")) {
+ Log.i(TAG, "HelloK: Find E2806894A");
+ MainActivity.csLibrary4A.setInvBrandId(false);
+ } else if (mDid.matches("E2806894B")) {
+ Log.i(TAG, "HelloK: Find E2806894B");
+ MainActivity.csLibrary4A.setInvBrandId(false);
+ if (true) bNeedSelectedTagByTID = false;
+ } else if (mDid.matches("E2806894C") || mDid.matches("E2806894d")) {
+ Log.i(TAG, "HelloK: Find " + MainActivity.mDid);
+ MainActivity.csLibrary4A.setInvBrandId(true);
+ if (true) bNeedSelectedTagByTID = false;
+ }
+ }
+ MainActivity.csLibrary4A.setOtherInventoryData(tagType, mDid);
+ int iValue123 = MainActivity.csLibrary4A.setSelectData(tagType, mDid,
+ bNeedSelectedTagByTID && checkBoxFilterByTid.isChecked(),
+ (checkBoxFilterByProtect.isChecked() ? editTextProtectPassword.getText().toString(): null),
+ MainActivity.selectFor, MainActivity.selectHold);
+ if (mDid.indexOf("E2806894") == 0) {
+ mDid = "E2806894";
+ }
+ if (iValue123 > 0) MainActivity.selectFor = iValue123;
+ }
+
+ MainActivity.csLibrary4A.appendToLog("bSgtinOnly: bMultiBank is " + bMultiBank + ", checkBoxFilterByEpc is " + (checkBoxFilterByEpc == null ? "null" : checkBoxFilterByEpc.isChecked()));
+ if (bMultiBank == false) {
+ if (checkBoxFilterByEpc.isChecked()) {
+ MainActivity.csLibrary4A.appendToLog("bSgtinOnly: clearTagList");
+ clearTagsList();
+ }
+ MainActivity.csLibrary4A.restoreAfterTagSelect();
+ inventoryRfidTask = new InventoryRfidTask(getContext(), -1, -1, 0, 0, 0, 0,
+ false, MainActivity.csLibrary4A.getInventoryBeep(),
+ MainActivity.sharedObjects.tagsList, readerListAdapter, null, RfidReader.TagType.TAG_NULL, null,
+ rfidRunTime, null, rfidVoltageLevel, rfidYieldView, button, rfidRateView);
+ inventoryRfidTask.bSgtinOnly = checkBoxFilterByEpc.isChecked();
+ MainActivity.csLibrary4A.appendToLog("Debug_Compact 1: InventoryRfidMultiFragment.startInventoryTask");
+ MainActivity.csLibrary4A.startOperation(RfidReaderChipData.OperationTypes.TAG_INVENTORY_COMPACT);
+ } else {
+ boolean inventoryUcode8_bc = mDid != null && mDid.matches("E2806894") && MainActivity.mDid != null && (MainActivity.mDid.matches("E2806894B") || MainActivity.mDid.matches("E2806894C"));
+ if ((extraBankData.extra1Bank != -1 && extraBankData.extra1Count != 0) || (extraBankData.extra2Bank != -1 && extraBankData.extra2Count != 0)) {
+ extraBankData.adjustExtraBank1();
+ MainActivity.csLibrary4A.appendToLog("HelloK: mDid = " + mDid + ", MainActivity.mDid = " + MainActivity.mDid + " with extra1Bank = " + extraBankData.extra1Bank + "," + extraBankData.extra1Offset + "," + extraBankData.extra1Count + ", extra2Bank = " + extraBankData.extra2Bank + "," + extraBankData.extra2Offset + "," + extraBankData.extra2Count);
+ if (mDid != null) MainActivity.csLibrary4A.setResReadNoReply(mDid.matches("E281D"));
+ if (inventoryUcode8_bc == false) {
+ MainActivity.csLibrary4A.appendToLog("BleStreamOut: Set Multibank");
+ MainActivity.csLibrary4A.setTagRead(extraBankData.extra2Count != 0 && extraBankData.extra2Count != 0 ? 2 : 1);
+ MainActivity.csLibrary4A.setAccessBank(extraBankData.extra1Bank, extraBankData.extra2Bank);
+ MainActivity.csLibrary4A.setAccessOffset(extraBankData.extra1Offset, extraBankData.extra2Offset);
+ MainActivity.csLibrary4A.setAccessCount(extraBankData.extra1Count, extraBankData.extra2Count);
+ needResetData = true;
+ } else if (needResetData) {
+ MainActivity.csLibrary4A.setTagRead(0);
+ MainActivity.csLibrary4A.setAccessBank(1);
+ MainActivity.csLibrary4A.setAccessOffset(0);
+ MainActivity.csLibrary4A.setAccessCount(0);
+ needResetData = false;
+ }
+ } else resetSelectData();
+ MainActivity.csLibrary4A.appendToLog("startInventoryTask: going to startOperation with extra1Bank = " + extraBankData.extra1Bank + "," + extraBankData.extra1Offset + "," + extraBankData.extra1Count + ", extra2Bank = " + extraBankData.extra2Bank + "," + extraBankData.extra2Offset + "," + extraBankData.extra2Count);
+ inventoryRfidTask = new InventoryRfidTask(getContext(), extraBankData.extra1Bank, extraBankData.extra2Bank, extraBankData.extra1Count, extraBankData.extra2Count, extraBankData.extra1Offset, extraBankData.extra2Offset,
+ false, MainActivity.csLibrary4A.getInventoryBeep(),
+ MainActivity.sharedObjects.tagsList, readerListAdapter, null, tagType, mDid,
+ rfidRunTime, null, rfidVoltageLevel, rfidYieldView, button, rfidRateView);
+ inventoryRfidTask.bProtectOnly = checkBoxFilterByProtect.isChecked();
+ if (inventoryUcode8_bc) {
+ MainActivity.csLibrary4A.appendToLog("Debug_Compact 2: InventoryRfidMultiFragment.startInventoryTask");
+ MainActivity.csLibrary4A.startOperation(RfidReaderChipData.OperationTypes.TAG_INVENTORY_COMPACT);
+ } else {
+ MainActivity.csLibrary4A.appendToLog("Debug_Compact 3: InventoryRfidMultiFragment.startInventoryTask");
+ MainActivity.csLibrary4A.startOperation(RfidReaderChipData.OperationTypes.TAG_INVENTORY);
+ }
+ }
+ inventoryRfidTask.execute();
+ }
+
+ private final Runnable runnableCheckReady = new Runnable() {
+ @Override
+ public void run() {
+ if (MainActivity.csLibrary4A.mrfidToWriteSize() != 0) {
+ button.setEnabled(false);
+ button.setText("Please wait");
+ MainActivity.csLibrary4A.setNotificationListener(null);
+ mHandler.postDelayed(runnableCheckReady, 500);
+ } else {
+ button.setText("Start");
+ button.setEnabled(true);
+ if (userVisibleHint) setNotificationListener();
+ }
+ }
+ };
+}
+
+
+
+package com.csl.cs710ademoapp.fragments;
+
+import static com.csl.cs710ademoapp.MainActivity.tagSelected;
+
+import android.app.Activity;
+import android.os.AsyncTask;
+import android.os.Bundle;
+import androidx.appcompat.app.AppCompatActivity;
+import android.text.Editable;
+import android.text.TextWatcher;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.AdapterView;
+import android.widget.ArrayAdapter;
+import android.widget.Button;
+import android.widget.CheckBox;
+import android.widget.EditText;
+import android.widget.ProgressBar;
+import android.widget.SeekBar;
+import android.widget.Spinner;
+import android.widget.TableRow;
+import android.widget.TextView;
+import android.widget.Toast;
+
+import com.csl.cs710ademoapp.CustomMediaPlayer;
+import com.csl.cs710ademoapp.InventoryRfidTask;
+import com.csl.cs710ademoapp.SelectTag;
+import com.csl.cs710ademoapp.MainActivity;
+import com.csl.cs710ademoapp.R;
+import com.csl.cslibrary4a.NotificationConnector;
+import com.csl.cslibrary4a.ReaderDevice;
+import com.csl.cslibrary4a.RfidReader;
+import com.csl.cslibrary4a.RfidReaderChipData;
+
+public class InventoryRfidSearchFragment extends CommonFragment {
+ double dBuV_dBm_constant = MainActivity.csLibrary4A.dBuV_dBm_constant;
+ final int labelMin = -90;
+ final int labelMax = -10;
+
+ SelectTag selectTag;
+ private ProgressBar geigerProgress;
+ private CheckBox checkBoxGeigerTone;
+ private SeekBar seekGeiger;
+ private Spinner memoryBankSpinner;
+ private EditText editTextRWSelectOffset, editTextGeigerAntennaPower;
+ private TextView geigerThresholdView;
+ private TextView geigerTagRssiView;
+ private TextView geigerTagGotView;
+ private TextView geigerRunTime, geigerVoltageLevelView;
+ private TextView rfidYieldView;
+ private TextView rfidRateView;
+ private Button button;
+
+ private boolean started = false;
+ int thresholdValue = 0;
+
+ private InventoryRfidTask geigerSearchTask;
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ super.onCreateView(inflater, container, savedInstanceState, true);
+ return inflater.inflate(R.layout.fragment_geiger_search, container, false);
+ }
+
+ @Override
+ public void onActivityCreated(Bundle savedInstanceState) {
+ super.onActivityCreated(savedInstanceState);
+
+ if (!isTabbed) {
+ androidx.appcompat.app.ActionBar actionBar;
+ actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
+ actionBar.setIcon(R.drawable.dl_loc);
+ actionBar.setTitle(R.string.title_activity_geiger);
+ }
+
+ selectTag = new SelectTag((Activity)getActivity(), 0);
+ TableRow tableRowProgressLabel;
+ TextView textViewProgressLabelMin = (TextView) getActivity().findViewById(R.id.geigerProgressLabelMin);
+ TextView textViewProgressLabelMid = (TextView) getActivity().findViewById(R.id.geigerProgressLabelMid);
+ TextView textViewProgressLabelMax = (TextView) getActivity().findViewById(R.id.geigerProgressLabelMax);
+ textViewProgressLabelMin.setText(String.format("%.0f", MainActivity.csLibrary4A.getRssiDisplaySetting() != 0 ? labelMin : labelMin + dBuV_dBm_constant));
+ textViewProgressLabelMid.setText(String.format("%.0f", MainActivity.csLibrary4A.getRssiDisplaySetting() != 0 ? labelMin + (labelMax - labelMin) / 2 : labelMin + (labelMax - labelMin) / 2 + dBuV_dBm_constant));
+ textViewProgressLabelMax.setText(String.format("%.0f", MainActivity.csLibrary4A.getRssiDisplaySetting() != 0 ? labelMax : labelMax + dBuV_dBm_constant));
+
+ geigerProgress = (ProgressBar) getActivity().findViewById(R.id.geigerProgress);
+ checkBoxGeigerTone = (CheckBox) getActivity().findViewById(R.id.geigerToneCheck);
+
+ seekGeiger = (SeekBar) getActivity().findViewById(R.id.geigerSeek);
+ seekGeiger.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
+ @Override
+ public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
+ if (seekBar == seekGeiger && fromUser == true) {
+ thresholdValue = progress;
+ geigerThresholdView.setText(String.format("%.2f", MainActivity.csLibrary4A.getRssiDisplaySetting() == 0 ? thresholdValue : thresholdValue - dBuV_dBm_constant));
+ }
+ }
+
+ @Override
+ public void onStartTrackingTouch(SeekBar seekBar) { }
+ @Override
+ public void onStopTrackingTouch(SeekBar seekBar) { }
+ });
+
+ memoryBankSpinner = (Spinner) getActivity().findViewById(R.id.selectMemoryBank);
+ ArrayAdapter memoryBankAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.read_memoryBank_options, R.layout.custom_spinner_layout);
+ memoryBankAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+ memoryBankSpinner.setAdapter(memoryBankAdapter);
+ memoryBankSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
+ @Override
+ public void onItemSelected(AdapterView> parent, View view, int position, long id) {
+ switch (position) {
+ case 0: //if EPC
+ if (tagSelected != null) selectTag.editTextTagID.setText(tagSelected.getAddress());
+ editTextRWSelectOffset.setText("32");
+ break;
+ case 1:
+ if (tagSelected != null) selectTag.editTextTagID.setText(tagSelected.getTid());
+ editTextRWSelectOffset.setText("0");
+ break;
+ case 2:
+ if (tagSelected != null) selectTag.editTextTagID.setText(tagSelected.getUser());
+ editTextRWSelectOffset.setText("0");
+ break;
+ default:
+ break;
+ }
+ }
+
+ @Override
+ public void onNothingSelected(AdapterView> parent) {
+
+ }
+ });
+
+ editTextRWSelectOffset = (EditText) getActivity().findViewById(R.id.selectMemoryOffset);
+
+ TableRow tableRowSelectPassword = (TableRow) getActivity().findViewById(R.id.selectPasswordRow);
+ tableRowSelectPassword.setVisibility(View.GONE);
+
+ editTextGeigerAntennaPower = (EditText) getActivity().findViewById(R.id.selectAntennaPower);
+ editTextGeigerAntennaPower.setText(String.valueOf(300));
+
+ geigerThresholdView = (TextView) getActivity().findViewById(R.id.geigerThreshold);
+ geigerTagRssiView = (TextView) getActivity().findViewById(R.id.geigerTagRssi);
+ geigerTagRssiView.addTextChangedListener(new TextWatcher() {
+ @Override
+ public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { }
+
+ @Override
+ public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { }
+
+ @Override
+ public void afterTextChanged(Editable editable) {
+ if (alertRssiUpdateTime < 0) return;
+ double rssi = Double.parseDouble(geigerTagRssiView.getText().toString());
+ if (MainActivity.csLibrary4A.getRssiDisplaySetting() != 0) rssi += dBuV_dBm_constant;
+
+ double progressPos = geigerProgress.getMax() * ( rssi - labelMin - dBuV_dBm_constant) / (labelMax - labelMin);
+ if (progressPos < 0) progressPos = 0;
+ if (progressPos > geigerProgress.getMax()) progressPos = geigerProgress.getMax();
+ geigerProgress.setProgress((int) (progressPos));
+
+ alertRssiUpdateTime = System.currentTimeMillis(); alertRssi = rssi;
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("afterTextChanged(): alerting = " + alerting + ", alertRssi = " + alertRssi);
+ if (rssi > thresholdValue && checkBoxGeigerTone.isChecked()) {
+ if (alerting == false) {
+ alerting = true;
+ mHandler.removeCallbacks(mAlertRunnable);
+ mHandler.post(mAlertRunnable);
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("afterTextChanged(): mAlertRunnable starts");
+ }
+ }
+ }
+ });
+ geigerRunTime = (TextView) getActivity().findViewById(R.id.geigerRunTime);
+ geigerTagGotView = (TextView) getActivity().findViewById(R.id.geigerTagGot);
+ geigerVoltageLevelView = (TextView) getActivity().findViewById(R.id.geigerVoltageLevel);
+ rfidYieldView = (TextView) getActivity().findViewById(R.id.geigerYield);
+ rfidRateView = (TextView) getActivity().findViewById(R.id.geigerRate);
+ button = (Button) getActivity().findViewById(R.id.geigerStart);
+ button.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ startStopHandler(false);
+ }
+ });
+
+ playerN = MainActivity.sharedObjects.playerL;
+ setupTagID();
+ }
+
+ @Override
+ public void onResume() {
+ super.onResume();
+ if (userVisibleHint) setNotificationListener();
+ }
+
+ @Override
+ public void onPause() {
+ MainActivity.csLibrary4A.setNotificationListener(null);
+ super.onPause();
+ }
+
+ @Override
+ public void onDestroy() {
+ MainActivity.csLibrary4A.setNotificationListener(null);
+ if (geigerSearchTask != null) {
+ geigerSearchTask.taskCancelReason = InventoryRfidTask.TaskCancelRReason.DESTORY;
+ }
+ MainActivity.csLibrary4A.restoreAfterTagSelect();
+ super.onDestroy();
+ }
+
+ boolean userVisibleHint = true;
+ @Override
+ public void setUserVisibleHint(boolean isVisibleToUser) {
+ super.setUserVisibleHint(isVisibleToUser);
+ if(getUserVisibleHint()) {
+ userVisibleHint = true;
+ MainActivity.csLibrary4A.appendToLog("InventoryRfidSearchFragment is now VISIBLE");
+ setupTagID();
+ MainActivity.csLibrary4A.appendToLog("setNotificationListener in search inventory");
+ setNotificationListener();
+ } else {
+ userVisibleHint = false;
+ MainActivity.csLibrary4A.appendToLog("InventoryRfidSearchFragment is now INVISIBLE");
+ MainActivity.csLibrary4A.appendToLog("setNotificationListener NULL in search inventory");
+ MainActivity.csLibrary4A.setNotificationListener(null);
+ }
+ }
+
+ boolean isTabbed = false;
+ public InventoryRfidSearchFragment(boolean isTabbed) {
+ super("InventoryRfidSearchFragment");
+ this.isTabbed = isTabbed;
+ }
+ void setupTagID() {
+ final ReaderDevice tagSelected = MainActivity.tagSelected;
+ if (tagSelected != null) {
+ if (tagSelected.getSelected() == true) {
+ if (tagSelected.getTid() != null) {
+ if (tagSelected.getTid().indexOf("E281D") == 0 || tagSelected.getTid().indexOf("E201E") == 0) {
+ memoryBankSpinner.setSelection(1);
+ }
+ }
+ switch (memoryBankSpinner.getSelectedItemPosition()) {
+ case 0:
+ selectTag.editTextTagID.setText(tagSelected.getAddress());
+ break;
+ case 1:
+ selectTag.editTextTagID.setText(tagSelected.getTid());
+ break;
+ case 2:
+ selectTag.editTextTagID.setText(tagSelected.getUser());
+ break;
+ }
+ }
+ }
+ }
+
+ double alertRssi; boolean alerting = false; long alertRssiUpdateTime;
+ CustomMediaPlayer playerN;
+ private final Runnable mAlertRunnable = new Runnable() {
+ @Override
+ public void run() {
+ boolean alerting1 = true;
+ final int toneLength = 50;
+
+ mHandler.removeCallbacks(mAlertRunnable);
+
+ if (alertRssi < 20 || alertRssi < thresholdValue || checkBoxGeigerTone.isChecked() == false || alertRssiUpdateTime < 0 || System.currentTimeMillis() - alertRssiUpdateTime > 200) alerting1 = false;
+ if (alerting1 == false) {
+ playerN.pause(); alerting = false;
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("mAlertRunnable(): ENDS with new alerting1 = " + alerting1 + ", alertRssi = " + alertRssi);
+ } else if (playerN.isPlaying() == false) {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("mAlertRunnable(): TONE starts");
+ mHandler.postDelayed(mAlertRunnable, toneLength);
+ playerN.start();
+ } else {
+ int tonePause = 0;
+ if (alertRssi >= 60) tonePause = toneLength;
+ else if (alertRssi >= 50) tonePause = 250 - toneLength;
+ else if (alertRssi >= 40) tonePause = 500 - toneLength;
+ else if (alertRssi >= 30) tonePause = 1000 - toneLength;
+ else if (alertRssi >= 20) tonePause = 2000 - toneLength;
+ if (tonePause > 0) mHandler.postDelayed(mAlertRunnable, tonePause);
+ if (tonePause <= 0 || alertRssi < 60) { playerN.pause(); if (DEBUG) MainActivity.csLibrary4A.appendToLog("Pause"); }
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("mAlertRunnable(): START with new alerting1 = " + alerting1 + ", alertRssi = " + alertRssi);
+ alerting = tonePause > 0 ? true : false;
+ }
+ }
+ };
+
+ void setNotificationListener() {
+ MainActivity.csLibrary4A.appendToLog("setNotificationListener A in search inventory");
+ MainActivity.csLibrary4A.setNotificationListener(new NotificationConnector.NotificationListener() {
+ @Override
+ public void onChange() {
+ MainActivity.csLibrary4A.appendToLog("setNotificationListener TRIGGER key is pressed in search inventory.");
+ startStopHandler(true);
+ }
+ });
+ }
+
+ void startStopHandler(boolean buttonTrigger) {
+ boolean started = false;
+ if (geigerSearchTask != null) {
+ if (geigerSearchTask.getStatus() == AsyncTask.Status.RUNNING) started = true;
+ }
+ if (buttonTrigger == true &&
+ ((started && MainActivity.csLibrary4A.getTriggerButtonStatus())
+ || (started == false && MainActivity.csLibrary4A.getTriggerButtonStatus() == false))) return;
+ if (started == false) {
+ if (MainActivity.csLibrary4A.isBleConnected() == false) {
+ Toast.makeText(MainActivity.mContext, R.string.toast_ble_not_connected, Toast.LENGTH_SHORT).show();
+ return;
+ } else if (MainActivity.csLibrary4A.isRfidFailure()) {
+ Toast.makeText(MainActivity.mContext, "Rfid is disabled", Toast.LENGTH_SHORT).show();
+ return;
+ } else if (MainActivity.csLibrary4A.mrfidToWriteSize() != 0) {
+ Toast.makeText(MainActivity.mContext, R.string.toast_not_ready, Toast.LENGTH_SHORT).show();
+ return;
+ }
+ startInventoryTask();
+ alertRssiUpdateTime = 0;
+ } else {
+ if (buttonTrigger) geigerSearchTask.taskCancelReason = InventoryRfidTask.TaskCancelRReason.BUTTON_RELEASE;
+ else geigerSearchTask.taskCancelReason = InventoryRfidTask.TaskCancelRReason.STOP;
+ alertRssiUpdateTime = -1;
+ }
+ }
+
+ void startInventoryTask() {
+ started = true; boolean invalidRequest = false;
+ if (tagSelected != null) {
+ if (tagSelected.getTid() != null) {
+ if (tagSelected.getTid().indexOf("E201E") == 0) {
+ MainActivity.csLibrary4A.setTagRead(1);
+ MainActivity.csLibrary4A.setAccessBank(3);
+ MainActivity.csLibrary4A.setAccessOffset(112);
+ MainActivity.csLibrary4A.setAccessCount(1);
+ }
+ }
+ }
+ int memorybank = memoryBankSpinner.getSelectedItemPosition();
+ int powerLevel = Integer.valueOf(editTextGeigerAntennaPower.getText().toString());
+ if (powerLevel < 0 || powerLevel > MainActivity.powerLevelMax) {
+ MainActivity.csLibrary4A.appendToLog("invalidRequest = " + invalidRequest + ", with powerLevel = " + powerLevel);
+ invalidRequest = true;
+ } else if (MainActivity.csLibrary4A.setSelectedTag(selectTag.editTextTagID.getText().toString(), memorybank+1, powerLevel) == false) {
+ invalidRequest = true;
+ MainActivity.csLibrary4A.appendToLog("invalidRequest = " + invalidRequest + ", with setSelectedTag as false, string = " + selectTag.editTextTagID.getText().toString() + ", bank = " + memorybank+1 + ", power = " + powerLevel);
+ } else {
+ MainActivity.csLibrary4A.startOperation(RfidReaderChipData.OperationTypes.TAG_SEARCHING);
+ }
+ MainActivity.csLibrary4A.appendToLog("invalidRequest = " + invalidRequest);
+ geigerSearchTask = new InventoryRfidTask(getContext(), -1,-1, 0, 0, 0, 0, invalidRequest, true,
+ null, null, geigerTagRssiView, RfidReader.TagType.TAG_NULL, null,
+ geigerRunTime, geigerTagGotView, geigerVoltageLevelView, null, button, rfidRateView);
+ geigerSearchTask.execute();
+ }
+}
+
+
+
+package com.csl.cs710ademoapp.fragments;
+
+import android.content.Intent;
+import android.os.Bundle;
+import androidx.appcompat.app.AppCompatActivity;
+
+import android.os.Handler;
+import android.os.Looper;
+import android.view.LayoutInflater;
+import android.view.MenuItem;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.AbsListView;
+import android.widget.AdapterView;
+import android.widget.Button;
+import android.widget.EditText;
+import android.widget.ListView;
+import android.widget.TextView;
+import android.widget.Toast;
+import com.csl.cs710ademoapp.MainActivity;
+import com.csl.cs710ademoapp.R;
+import com.csl.cs710ademoapp.SaveList2ExternalTask;
+import com.csl.cs710ademoapp.SharedObjects;
+import com.csl.cs710ademoapp.adapters.ReaderListAdapter;
+import com.csl.cslibrary4a.NotificationConnector;
+import com.csl.cslibrary4a.ReaderDevice;
+import com.csl.cslibrary4a.RfidReaderChipData;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Comparator;
+
+public class InventoryRfidSimpleFragment extends CommonFragment {
+ final private boolean bAdd2End = false;
+ int vibrateTimeBackup = 0;
+
+ private ListView rfidListView;
+ private TextView rfidEmptyView;
+ private TextView rfidRunTime;
+ private TextView rfidYieldView;
+ private TextView rfidRateView;
+ private Button button, buttonShow;
+
+ private ReaderListAdapter readerListAdapter;
+
+ void clearTagsList() {
+ if (bRunningInventory) return;
+ rfidYieldView.setText("");
+ rfidRateView.setText("");
+ MainActivity.tagSelected = null;
+ MainActivity.sharedObjects.tagsList.clear(); MainActivity.sharedObjects.tagsIndexList.clear();
+ readerListAdapter.notifyDataSetChanged();
+ MainActivity.mLogView.setText("");
+ }
+ void sortTagsList() {
+ if (bRunningInventory) return;
+ Collections.sort(MainActivity.sharedObjects.tagsList);
+ readerListAdapter.notifyDataSetChanged();
+ }
+ void sortTagsListByRssi() {
+ if (bRunningInventory) return;
+ Collections.sort(MainActivity.sharedObjects.tagsList, new Comparator() {
+ @Override
+ public int compare(ReaderDevice deviceTag, ReaderDevice t1) {
+ if (deviceTag.getRssi() == t1.getRssi()) return 0;
+ else if (deviceTag.getRssi() < t1.getRssi()) return 1;
+ else return -1;
+ }
+ });
+ readerListAdapter.notifyDataSetChanged();
+ }
+ void saveTagsList() {
+ if (bRunningInventory) return;
+ SaveList2ExternalTask saveExternalTask = new SaveList2ExternalTask(MainActivity.sharedObjects.tagsList);
+ saveExternalTask.execute();
+ }
+ void shareTagsList() {
+ SaveList2ExternalTask saveExternalTask = new SaveList2ExternalTask(MainActivity.sharedObjects.tagsList);
+ String stringOutput = saveExternalTask.createStrEpcList();
+
+ Intent sendIntent = new Intent();
+ sendIntent.setAction(Intent.ACTION_SEND);
+ sendIntent.putExtra(Intent.EXTRA_TEXT, stringOutput);
+ sendIntent.setType("text/plain");
+ startActivity(Intent.createChooser(sendIntent, "Sharing to"));
+ }
+
+ @Override
+ public boolean onOptionsItemSelected(MenuItem item) {
+ if (item.getItemId() == R.id.menuAction_clear) {
+ clearTagsList();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_sortRssi) {
+ sortTagsListByRssi();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_sort) {
+ sortTagsList();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_save) {
+ saveTagsList();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_share) {
+ shareTagsList();
+ return true;
+ } else return super.onOptionsItemSelected(item);
+ }
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ super.onCreateView(inflater, container, savedInstanceState, true);
+ return inflater.inflate(R.layout.fragment_inventory_rfid_simple, container, false);
+ }
+
+ @Override
+ public void onActivityCreated(Bundle savedInstanceState) {
+ super.onActivityCreated(savedInstanceState);
+
+ MainActivity.selectFor = -1;
+ if (true) {
+ androidx.appcompat.app.ActionBar actionBar;
+ actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
+ actionBar.setIcon(R.drawable.dl_inv);
+ actionBar.setTitle(R.string.title_activity_simpleInventory);
+ }
+
+ rfidListView = (ListView) getActivity().findViewById(R.id.simpleInventoryinventoryRfidList1);
+ rfidEmptyView = (TextView) getActivity().findViewById(R.id.simpleInventoryRfidEmpty1);
+ rfidListView.setEmptyView(rfidEmptyView);
+ boolean bSelect4detail = true;
+
+ boolean needDupElim = true;
+ boolean need4Extra1 = MainActivity.csLibrary4A.getPortNumber() > 1 ? true : false;
+ boolean need4Extra2 = false;
+ readerListAdapter = new ReaderListAdapter(getActivity(), R.layout.readers_list_item, MainActivity.sharedObjects.tagsList, bSelect4detail, true, needDupElim, need4Extra1, need4Extra2);
+
+ rfidListView.setAdapter(readerListAdapter);
+ rfidListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
+ rfidListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
+ @Override
+ public void onItemClick(AdapterView> parent, View view, int position, long id) {
+ ReaderDevice readerDevice = readerListAdapter.getItem(position);
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("Position = " + position);
+ if (readerDevice.getSelected()) {
+ readerDevice.setSelected(false);
+ } else {
+ readerDevice.setSelected(true);
+ }
+ MainActivity.sharedObjects.tagsList.set(position, readerDevice);
+ if (readerDevice.getSelected()) MainActivity.tagSelected = readerDevice;
+ else MainActivity.tagSelected = null;
+ for (int i = 0; i < MainActivity.sharedObjects.tagsList.size(); i++) {
+ if (i != position) {
+ ReaderDevice readerDevice1 = MainActivity.sharedObjects.tagsList.get(i);
+ if (readerDevice1.getSelected()) {
+ readerDevice1.setSelected(false);
+ MainActivity.sharedObjects.tagsList.set(i, readerDevice1);
+ }
+ }
+ }
+ readerListAdapter.notifyDataSetChanged();
+ }
+ });
+
+ rfidRunTime = (TextView) getActivity().findViewById(R.id.simpleInventoryRfidRunTime1);
+ TextView rfidFilterOn = (TextView) getActivity().findViewById(R.id.SimpleInventoryRfidFilterOn1);
+ if (MainActivity.csLibrary4A.getSelectEnable() == false && MainActivity.csLibrary4A.getInvMatchEnable() == false && MainActivity.csLibrary4A.getRssiFilterEnable() == false )
+ rfidFilterOn.setVisibility(View.INVISIBLE);
+
+ rfidYieldView = (TextView) getActivity().findViewById(R.id.simpleInventoryRfidYield1);
+ rfidRateView = (TextView) getActivity().findViewById(R.id.simpleInventoryRfidRate1);
+
+ button = (Button) getActivity().findViewById(R.id.simpleInventoryRfidButton1);
+ button.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ startStopHandler(false);
+ }
+ });
+
+ buttonShow = (Button) getActivity().findViewById(R.id.simpleInventoryRfidButtonShow);
+ buttonShow.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ buttonShow.setVisibility(View.GONE);
+ inventoryHandler_tag();
+ }
+ });
+
+ vibrateTimeBackup = MainActivity.csLibrary4A.getVibrateTime();
+ }
+
+ @Override
+ public void onResume() {
+ super.onResume();
+ setNotificationListener();
+ }
+
+ @Override
+ public void onPause() {
+ MainActivity.csLibrary4A.setNotificationListener(null);
+ super.onPause();
+ }
+
+ @Override
+ public void onDestroy() {
+ mHandler.removeCallbacks(runnableCheckReady);
+ MainActivity.csLibrary4A.setNotificationListener(null);
+ MainActivity.csLibrary4A.setSameCheck(true);
+ MainActivity.csLibrary4A.setInvBrandId(false);
+ MainActivity.csLibrary4A.setVibrateTime(vibrateTimeBackup);
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("InventoryRfidSimpleFragment().onDestory(): onDestory()");
+ super.onDestroy();
+ }
+
+ public static InventoryRfidSimpleFragment newInstance(boolean bMultiBank, String mDid) {
+ InventoryRfidSimpleFragment myFragment = new InventoryRfidSimpleFragment();
+
+ Bundle args = new Bundle();
+ args.putBoolean("bMultiBank", bMultiBank);
+ args.putString("mDid", mDid);
+ myFragment.setArguments(args);
+
+ return myFragment;
+ }
+ public InventoryRfidSimpleFragment() {
+ super("InventoryRfidSimpleFragment");
+ }
+
+ void setNotificationListener() {
+ MainActivity.csLibrary4A.setNotificationListener(new NotificationConnector.NotificationListener() {
+ @Override
+ public void onChange() {
+ MainActivity.csLibrary4A.appendToLog("TRIGGER key is pressed.");
+ startStopHandler(true);
+ }
+ });
+ }
+ void startStopHandler(boolean buttonTrigger) {
+ if (buttonTrigger) MainActivity.csLibrary4A.appendToLog("getTriggerButtonStatus = " + MainActivity.csLibrary4A.getTriggerButtonStatus());
+ else MainActivity.csLibrary4A.appendToLog("TriggerButton is pressed");
+
+ boolean started = false;
+ if (bRunningInventory) started = true;
+ if (buttonTrigger && ((started && MainActivity.csLibrary4A.getTriggerButtonStatus()) || (started == false && MainActivity.csLibrary4A.getTriggerButtonStatus() == false))) {
+ MainActivity.csLibrary4A.appendToLog("BARTRIGGER: trigger ignore");
+ return;
+ }
+ MainActivity.csLibrary4A.appendToLog("started = " + started);
+ if (started == false) {
+ if (MainActivity.csLibrary4A.isBleConnected() == false) {
+ Toast.makeText(MainActivity.mContext, R.string.toast_ble_not_connected, Toast.LENGTH_SHORT).show();
+ return;
+ } else if (MainActivity.csLibrary4A.isRfidFailure()) {
+ Toast.makeText(MainActivity.mContext, "Rfid is disabled", Toast.LENGTH_SHORT).show();
+ return;
+ } else if (MainActivity.csLibrary4A.mrfidToWriteSize() != 0) {
+ //Toast.makeText(MainActivity.mContext, R.string.toast_not_ready, Toast.LENGTH_SHORT).show();
+ mHandler.post(runnableCheckReady);
+ return;
+ }
+
+ if (true) {
+ EditText editText = (EditText) getActivity().findViewById(R.id.simpleInventoryTagPopulation);
+ int iValue = Integer.valueOf(editText.getText().toString(), 16);
+ MainActivity.csLibrary4A.setPopulation(iValue);
+
+ editText = (EditText) getActivity().findViewById(R.id.simpleInventoryTagTargetNumber);
+ iTagTarget = Integer.valueOf(editText.getText().toString());
+ iTagGot = 0;
+
+ uplinkPacketList.clear();
+
+ timeMillis = System.currentTimeMillis(); startTimeMillis = timeMillis; runTimeMillis = timeMillis;
+ total = 0;
+ }
+
+ MainActivity.sharedObjects.tagsList.clear(); MainActivity.sharedObjects.tagsIndexList.clear();
+ rfidYieldView.setText("");
+ rfidRateView.setText("");
+ button.setText("Stop");
+ if (bAdd2End) rfidListView.setTranscriptMode(AbsListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
+ else rfidListView.setSelection(0);
+
+ MainActivity.csLibrary4A.appendToLog("setVibrateOn i 2 with getInventoryVibrate as " + MainActivity.csLibrary4A.getInventoryVibrate() + ", getVibrateModeSetting as " + MainActivity.csLibrary4A.getVibrateModeSetting());
+ if (MainActivity.csLibrary4A.getInventoryVibrate() && MainActivity.csLibrary4A.getVibrateModeSetting() == 1) {
+ MainActivity.csLibrary4A.setVibrateOn(2);
+ }
+ //else MainActivity.csLibrary4A.setVibrateOn(0);
+
+ startInventoryTask();
+ bRunningInventory = true;
+ myHandler.post(runnableSimpleInentory);
+ } else {
+ MainActivity.csLibrary4A.abortOperation();
+ if (bAdd2End) rfidListView.setTranscriptMode(AbsListView.TRANSCRIPT_MODE_NORMAL);
+ if (true) { bRunningInventory = false; }
+ }
+ }
+
+ boolean bRunningInventory = false;
+ int total;
+ long timeMillis, startTimeMillis, runTimeMillis, rateTimeMillis;
+ int iTagTarget, iTagGot;
+ Handler myHandler = new Handler(Looper.getMainLooper());
+ ArrayList uplinkPacketList = new ArrayList<>();
+ Runnable runnableSimpleInentory = new Runnable() {
+ @Override
+ public void run() {
+ RfidReaderChipData.Rx000pkgData uplinkPacket;
+ if (MainActivity.csLibrary4A.isBleConnected() && bRunningInventory) {
+ while (MainActivity.csLibrary4A.mrfidToWriteSize() == 0 && (iTagTarget == 0 || iTagGot < iTagTarget)) {
+ if (System.currentTimeMillis() > runTimeMillis + 1000) {
+ runTimeMillis = System.currentTimeMillis();
+ long timePeriod = (System.currentTimeMillis() - startTimeMillis) / 1000;
+ if (timePeriod > 0) {
+ if (rfidRunTime != null) rfidRunTime.setText(String.format("Run time: %d sec", timePeriod));
+ }
+ }
+ uplinkPacket = MainActivity.csLibrary4A.onRFIDEvent();
+ if (uplinkPacket == null) break;
+ else {
+ uplinkPacketList.add(uplinkPacket);
+ iTagGot++;
+ mHandler.postDelayed(runnableStartBeep, 250);
+ }
+ }
+ if (iTagTarget != 0 && iTagGot >= iTagTarget) {
+ MainActivity.csLibrary4A.abortOperation();
+ bRunningInventory = false;
+ }
+
+ if (iTagGot != 0) {
+ rfidYieldView.setText("Total:" + iTagGot);
+
+ long tagRate = MainActivity.csLibrary4A.getTagRate();
+ String strRate = ""; boolean bUpdateRate = false;
+ if (tagRate >= 0) {
+ strRate = String.valueOf(tagRate);
+ bUpdateRate = true;
+ } else {
+ if (System.currentTimeMillis() - rateTimeMillis > 1500) {
+ strRate = "___";
+ bUpdateRate = true;
+ }
+ }
+ if (bUpdateRate) {
+ rfidRateView.setText("Rate:" + strRate);
+ rateTimeMillis = System.currentTimeMillis();
+ }
+ }
+ myHandler.postDelayed(runnableSimpleInentory, 200);
+ } else {
+ bRunningInventory = false;
+ button.setText("Start"); buttonShow.setVisibility(View.VISIBLE);
+ }
+ }
+ };
+
+ void inventoryHandler_tag() {
+ double rssi = 0;
+ int phase = -1, chidx = -1, port = -1;
+ int total = 0;
+
+ while (uplinkPacketList.size() != 0) {
+ RfidReaderChipData.Rx000pkgData uplinkPacket = uplinkPacketList.get(0);
+ uplinkPacketList.remove(0);
+ RfidReaderChipData.Rx000pkgData tagData = uplinkPacket;
+
+ boolean match = false;
+ total++;
+ rssi = uplinkPacket.decodedRssi;
+ phase = uplinkPacket.decodedPhase;
+ chidx = uplinkPacket.decodedChidx;
+ port = uplinkPacket.decodedPort;
+
+ ReaderDevice deviceTag = null;
+ int iMatchItem = -1;
+ if (true) {
+ int index = Collections.binarySearch(MainActivity.sharedObjects.tagsIndexList, new SharedObjects.TagsIndex(MainActivity.csLibrary4A.byteArrayToString(tagData.decodedEpc), 0));
+ if (index >= 0) {
+ iMatchItem = MainActivity.sharedObjects.tagsIndexList.size() - 1 - MainActivity.sharedObjects.tagsIndexList.get(index).getPosition();
+ }
+ }
+ if (iMatchItem >= 0) {
+ deviceTag = MainActivity.sharedObjects.tagsList.get(iMatchItem);
+ int count = deviceTag.getCount();
+ count++;
+ deviceTag.setCount(count);
+ deviceTag.setRssi(rssi);
+ deviceTag.setPhase(phase);
+ deviceTag.setChannel(chidx);
+ deviceTag.setPort(port);
+ MainActivity.sharedObjects.tagsList.set(iMatchItem, deviceTag);
+ match = true;
+ }
+ if (match == false) {
+ deviceTag = new ReaderDevice("", MainActivity.csLibrary4A.byteArrayToString(uplinkPacket.decodedEpc), false, null,
+ MainActivity.csLibrary4A.byteArrayToString(uplinkPacket.decodedPc),
+ null,
+ (uplinkPacket.decodedCrc != null ? MainActivity.csLibrary4A.byteArrayToString(uplinkPacket.decodedCrc) : null),
+ null, null, 0, 0, null, 0, 0,null, null, null, null, 1,
+ rssi, phase, chidx, port,
+ 0, 0, 0, 0, 0, 0, null, 0);
+ if (bAdd2End) MainActivity.sharedObjects.tagsList.add(deviceTag);
+ else MainActivity.sharedObjects.tagsList.add(0, deviceTag);
+ SharedObjects.TagsIndex tagsIndex = new SharedObjects.TagsIndex(MainActivity.csLibrary4A.byteArrayToString(uplinkPacket.decodedEpc), MainActivity.sharedObjects.tagsList.size() - 1);
+ MainActivity.sharedObjects.tagsIndexList.add(tagsIndex);
+ Collections.sort(MainActivity.sharedObjects.tagsIndexList);
+ }
+ }
+ MainActivity.csLibrary4A.appendToLog("readerListAdapter is " + (readerListAdapter != null ? "valid" : "null"));
+ if (readerListAdapter != null) readerListAdapter.notifyDataSetChanged();
+ rfidYieldView.setText("Unique:" + MainActivity.sharedObjects.tagsList.size() + "\nTotal:" + total);
+ }
+
+ Runnable runnableStartBeep = new Runnable() {
+ @Override
+ public void run() {
+ //if (MainActivity.isInventoryRfidRequestNewSound()) MainActivity.sharedObjects.playerN.start(); //playerN.setVolume(300, 300);
+ //else
+ MainActivity.sharedObjects.playerO.start();
+ }
+ };
+
+ void startInventoryTask() {
+ MainActivity.csLibrary4A.appendToLog("startInventoryTask");
+ MainActivity.csLibrary4A.restoreAfterTagSelect();
+ MainActivity.csLibrary4A.startOperation(RfidReaderChipData.OperationTypes.TAG_INVENTORY_COMPACT);
+ }
+
+ private final Runnable runnableCheckReady = new Runnable() {
+ @Override
+ public void run() {
+ if (MainActivity.csLibrary4A.mrfidToWriteSize() != 0) {
+ button.setEnabled(false);
+ button.setText("Please wait");
+ MainActivity.csLibrary4A.setNotificationListener(null);
+ mHandler.postDelayed(runnableCheckReady, 500);
+ } else {
+ button.setText("Start");
+ button.setEnabled(true);
+ setNotificationListener();
+ }
+ }
+ };
+}
+
+
+
+package com.csl.cs710ademoapp.fragments;
+
+import static com.csl.cslibrary4a.RfidReader.TagType.TAG_KILOWAY;
+
+import android.os.Bundle;
+import android.view.LayoutInflater;
+import android.view.MenuItem;
+import android.view.View;
+import android.view.ViewGroup;
+
+import androidx.appcompat.app.ActionBar;
+import androidx.appcompat.app.AppCompatActivity;
+import androidx.viewpager.widget.ViewPager;
+
+import com.csl.cs710ademoapp.MainActivity;
+import com.csl.cs710ademoapp.R;
+import com.csl.cslibrary4a.AdapterTab;
+import com.google.android.material.tabs.TabLayout;
+
+public class KilowayFragment extends CommonFragment {
+ private ActionBar actionBar;
+ private ViewPager viewPager;
+ AdapterTab adapter;
+
+ private String[] tabs = {"Scan", "Geiger"}; //, "Access"};
+ int iTargetOld, iSessionOld;
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ super.onCreateView(inflater, container, savedInstanceState, true);
+ return inflater.inflate(R.layout.custom_tabbed_layout, container, false);
+ }
+
+ @Override
+ public boolean onOptionsItemSelected(MenuItem item) {
+ InventoryRfidiMultiFragment fragment = (InventoryRfidiMultiFragment) adapter.getItem(0);
+ if (item.getItemId() == R.id.menuAction_clear) {
+ fragment.clearTagsList();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_sortRssi) {
+ fragment.sortTagsListByRssi();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_sort) {
+ fragment.sortTagsList();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_save) {
+ fragment.saveTagsList();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_share) {
+ fragment.shareTagsList();
+ return true;
+ } else return super.onOptionsItemSelected(item);
+ }
+
+ @Override
+ public void onActivityCreated(Bundle savedInstanceState) {
+ super.onActivityCreated(savedInstanceState);
+
+ actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
+ actionBar.setIcon(R.drawable.dl_inv);
+ actionBar.setTitle(R.string.title_activity_kiloway);
+
+ TabLayout tabLayout = (TabLayout) getActivity().findViewById(R.id.OperationsTabLayout);
+
+ adapter = new AdapterTab(getActivity().getSupportFragmentManager(), tabs.length);
+ adapter.setFragment(0, InventoryRfidiMultiFragment.newInstance(true, TAG_KILOWAY, "E281D"));
+ adapter.setFragment(1, new InventoryRfidSearchFragment(true));
+ adapter.setFragment(2, new AccessKilowayFragment(false));
+
+ viewPager = (ViewPager) getActivity().findViewById(R.id.OperationsPager);
+ viewPager.setAdapter(adapter);
+ viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
+
+ for (String tab_name : tabs) {
+ tabLayout.addTab(tabLayout.newTab().setText(tab_name));
+ }
+
+ tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
+ @Override
+ public void onTabSelected(TabLayout.Tab tab) {
+ viewPager.setCurrentItem(tab.getPosition());
+ }
+
+ @Override
+ public void onTabUnselected(TabLayout.Tab tab) {
+ }
+
+ @Override
+ public void onTabReselected(TabLayout.Tab tab) {
+ }
+ });
+
+ iTargetOld = MainActivity.csLibrary4A.getQueryTarget();
+ iSessionOld = MainActivity.csLibrary4A.getQuerySession();
+ MainActivity.csLibrary4A.setBasicCurrentLinkProfile();
+ }
+
+ @Override
+ public void onPause() {
+ adapter.fragment0.onPause();
+ adapter.fragment1.onPause();
+ super.onPause();
+ }
+
+ @Override
+ public void onStop() {
+ adapter.fragment0.onStop();
+ adapter.fragment1.onStop();
+ super.onStop();
+ }
+
+ @Override
+ public void onDestroyView() {
+ adapter.fragment0.onDestroyView();
+ adapter.fragment1.onDestroyView();
+ super.onDestroyView();
+ }
+
+ @Override
+ public void onDestroy() {
+ adapter.fragment0.onDestroy();
+ adapter.fragment1.onDestroy();
+ MainActivity.csLibrary4A.setTagGroup(MainActivity.csLibrary4A.getQuerySelect(), iSessionOld, iTargetOld);
+ //MainActivity.mCs108Library4a.macWrite(0x203, 0);
+ super.onDestroy();
+ }
+
+ @Override
+ public void onDetach() {
+ adapter.fragment0.onDetach();
+ adapter.fragment1.onDetach();
+ super.onDetach();
+ }
+
+ public KilowayFragment() {
+ super("LedTagFragment");
+ }
+}
+
+
+
+package com.csl.cs710ademoapp.fragments;
+
+import static com.csl.cslibrary4a.RfidReader.TagType.TAG_LONGJING;
+
+import android.os.Bundle;
+import android.view.LayoutInflater;
+import android.view.MenuItem;
+import android.view.View;
+import android.view.ViewGroup;
+
+import androidx.appcompat.app.ActionBar;
+import androidx.appcompat.app.AppCompatActivity;
+import androidx.viewpager.widget.ViewPager;
+
+import com.csl.cs710ademoapp.MainActivity;
+import com.csl.cs710ademoapp.R;
+import com.csl.cslibrary4a.AdapterTab;
+import com.google.android.material.tabs.TabLayout;
+
+public class LongjingFragment extends CommonFragment {
+ private ActionBar actionBar;
+ private ViewPager viewPager;
+ AdapterTab adapter;
+
+ private String[] tabs = {"Scan", "Geiger"}; //"Access",
+ int iTargetOld, iSessionOld;
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ super.onCreateView(inflater, container, savedInstanceState, true);
+ return inflater.inflate(R.layout.custom_tabbed_layout, container, false);
+ }
+
+ @Override
+ public boolean onOptionsItemSelected(MenuItem item) {
+ InventoryRfidiMultiFragment fragment1 = (InventoryRfidiMultiFragment) adapter.getItem(0);
+ if (item.getItemId() == R.id.menuAction_clear) {
+ fragment1.clearTagsList();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_sortRssi) {
+ fragment1.sortTagsListByRssi();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_sort) {
+ fragment1.sortTagsList();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_save) {
+ fragment1.saveTagsList();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_share) {
+ fragment1.shareTagsList();
+ return true;
+ } else return super.onOptionsItemSelected(item);
+ }
+
+ @Override
+ public void onActivityCreated(Bundle savedInstanceState) {
+ super.onActivityCreated(savedInstanceState);
+
+ actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
+ actionBar.setIcon(R.drawable.dl_inv);
+ actionBar.setTitle(R.string.title_activity_longjing);
+
+ TabLayout tabLayout = (TabLayout) getActivity().findViewById(R.id.OperationsTabLayout);
+
+ adapter = new AdapterTab(getActivity().getSupportFragmentManager(), tabs.length);
+ adapter.setFragment(0, InventoryRfidiMultiFragment.newInstance(true, TAG_LONGJING, "E201E"));
+ adapter.setFragment(1, new InventoryRfidSearchFragment(true));
+ adapter.setFragment(2, new AccessKilowayFragment(true));
+
+ viewPager = (ViewPager) getActivity().findViewById(R.id.OperationsPager);
+ viewPager.setAdapter(adapter);
+ viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
+
+ for (String tab_name : tabs) {
+ tabLayout.addTab(tabLayout.newTab().setText(tab_name));
+ }
+
+ tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
+ @Override
+ public void onTabSelected(TabLayout.Tab tab) {
+ viewPager.setCurrentItem(tab.getPosition());
+ }
+
+ @Override
+ public void onTabUnselected(TabLayout.Tab tab) {
+ }
+
+ @Override
+ public void onTabReselected(TabLayout.Tab tab) {
+ }
+ });
+
+ iTargetOld = MainActivity.csLibrary4A.getQueryTarget();
+ iSessionOld = MainActivity.csLibrary4A.getQuerySession();
+ MainActivity.csLibrary4A.setBasicCurrentLinkProfile();
+ }
+
+ @Override
+ public void onPause() {
+ adapter.fragment0.onPause();
+ adapter.fragment1.onPause();
+ super.onPause();
+ }
+
+ @Override
+ public void onStop() {
+ adapter.fragment0.onStop();
+ adapter.fragment1.onStop();
+ super.onStop();
+ }
+
+ @Override
+ public void onDestroyView() {
+ adapter.fragment0.onDestroyView();
+ adapter.fragment1.onDestroyView();
+ super.onDestroyView();
+ }
+
+ @Override
+ public void onDestroy() {
+ adapter.fragment0.onDestroy();
+ adapter.fragment1.onDestroy();
+ MainActivity.csLibrary4A.setTagGroup(MainActivity.csLibrary4A.getQuerySelect(), iSessionOld, iTargetOld);
+ //MainActivity.mCs108Library4a.macWrite(0x203, 0);
+ super.onDestroy();
+ }
+
+ @Override
+ public void onDetach() {
+ adapter.fragment0.onDetach();
+ adapter.fragment1.onDetach();
+ super.onDetach();
+ }
+
+ public LongjingFragment() {
+ super("LedTagFragment");
+ }
+}
+
+
+
+package com.csl.cs710ademoapp.fragments;
+
+import android.os.Bundle;
+
+import com.csl.cslibrary4a.AdapterTab;
+import com.google.android.material.tabs.TabLayout;
+import androidx.viewpager.widget.ViewPager;
+import androidx.appcompat.app.ActionBar;
+import androidx.appcompat.app.AppCompatActivity;
+import android.view.LayoutInflater;
+import android.view.MenuItem;
+import android.view.View;
+import android.view.ViewGroup;
+
+import com.csl.cs710ademoapp.MainActivity;
+import com.csl.cs710ademoapp.R;
+
+public class MicronFragment extends CommonFragment {
+ private ActionBar actionBar;
+ private ViewPager viewPager;
+ AdapterTab adapter;
+
+ private String[] tabs = { "Scan/Select", "Read" };
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ super.onCreateView(inflater, container, savedInstanceState, true);
+ return inflater.inflate(R.layout.custom_tabbed_layout, container, false);
+ }
+
+ @Override
+ public boolean onOptionsItemSelected(MenuItem item) {
+ InventoryRfidiMultiFragment fragment = (InventoryRfidiMultiFragment) adapter.fragment0;
+ if (item.getItemId() == R.id.menuAction_clear) {
+ fragment.clearTagsList();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_sortRssi) {
+ fragment.sortTagsListByRssi();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_sort) {
+ fragment.sortTagsList();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_save) {
+ fragment.saveTagsList();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_share) {
+ fragment.shareTagsList();
+ return true;
+ } else return super.onOptionsItemSelected(item);
+ }
+
+ @Override
+ public void onActivityCreated(Bundle savedInstanceState) {
+ super.onActivityCreated(savedInstanceState);
+
+ actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
+ actionBar.setIcon(R.drawable.dl_inv);
+ actionBar.setTitle(R.string.title_activity_emMicro);
+
+ TabLayout tabLayout = (TabLayout) getActivity().findViewById(R.id.OperationsTabLayout);
+
+ adapter = new AdapterTab(getActivity().getSupportFragmentManager(), tabs.length);
+ adapter.setFragment(0, InventoryRfidiMultiFragment.newInstance(true, null, ""));
+ adapter.setFragment(1, AccessMicronFragment.newInstance(false));
+
+ viewPager = (ViewPager) getActivity().findViewById(R.id.OperationsPager);
+ viewPager.setAdapter(adapter);
+ viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
+
+ for (String tab_name : tabs) {
+ tabLayout.addTab(tabLayout.newTab().setText(tab_name));
+ }
+
+ tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
+ @Override
+ public void onTabSelected(TabLayout.Tab tab) {
+ viewPager.setCurrentItem(tab.getPosition());
+ }
+
+ @Override
+ public void onTabUnselected(TabLayout.Tab tab) {
+ }
+
+ @Override
+ public void onTabReselected(TabLayout.Tab tab) {
+ }
+ });
+
+ MainActivity.csLibrary4A.setBasicCurrentLinkProfile();
+ }
+
+ @Override
+ public void onPause() {
+ if (adapter.fragment0 != null) adapter.fragment0.onPause();
+ if (adapter.fragment1 != null) adapter.fragment1.onPause();
+ super.onPause();
+ }
+
+ @Override
+ public void onStop() {
+ if (adapter.fragment0 != null) adapter.fragment0.onStop();
+ if (adapter.fragment1 != null) adapter.fragment1.onStop();
+ super.onStop();
+ }
+
+ @Override
+ public void onDestroyView() {
+ if (adapter.fragment0 != null) adapter.fragment0.onDestroyView();
+ if (adapter.fragment1 != null) adapter.fragment1.onDestroyView();
+ super.onDestroyView();
+ }
+
+ @Override
+ public void onDestroy() {
+ if (adapter.fragment0 != null) adapter.fragment0.onDestroy();
+ if (adapter.fragment1 != null) adapter.fragment1.onDestroy();
+ if (MainActivity.selectFor != -1) {
+ MainActivity.csLibrary4A.setSelectCriteriaDisable(-1);
+ MainActivity.selectFor = -1;
+ }
+ MainActivity.csLibrary4A.restoreAfterTagSelect();
+ super.onDestroy();
+ }
+
+ @Override
+ public void onDetach() {
+ if (adapter.fragment0 != null) adapter.fragment0.onDetach();
+ if (adapter.fragment1 != null) adapter.fragment1.onDetach();
+ super.onDetach();
+ }
+
+ public MicronFragment() {
+ super("MicronFragment");
+ }
+}
+
+
+
+package com.csl.cs710ademoapp.fragments;
+
+import android.os.Bundle;
+import android.os.Handler;
+import android.text.InputFilter;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.AdapterView;
+import android.widget.ArrayAdapter;
+import android.widget.Button;
+import android.widget.CheckBox;
+import android.widget.EditText;
+import android.widget.LinearLayout;
+import android.widget.RadioButton;
+import android.widget.Spinner;
+import android.widget.TableRow;
+import android.widget.TextView;
+import android.widget.Toast;
+
+import com.csl.cs710ademoapp.CustomPopupWindow;
+import com.csl.cs710ademoapp.MainActivity;
+import com.csl.cs710ademoapp.R;
+import com.csl.cs710ademoapp.SettingTask;
+import com.csl.cslibrary4a.RfidReaderChipData;
+
+public class SettingAdminFragment extends CommonFragment {
+ private CheckBox checkBoxTriggerReporting, checkBoxInventoryBeep, checkBoxInventoryVibrate, checkBoxSaveFileEnable, checkBoxSaveCloudEnable, checkBoxSaveNewCloudEnable, checkBoxSaveAllCloudEnable, checkBoxDebugEnable, checkBoxForegroundService;
+ private CheckBox checkBoxCsvColumnResBank, checkBoxCsvColumnEpcBank, checkBoxCsvColumnTidBank, checkBoxCsvColumnUserBank, checkBoxCsvColumnPhase, checkBoxCsvColumnChannel, checkBoxCsvColumnTime, checkBoxCsvColumnTimeZone, checkBoxCsvColumnLocation, checkBoxCsvColumnDirection, checkBoxCsvColumnOthers;
+ private EditText editTextDeviceName, editTextCycleDelay, editTextTriggerReportingCount, editTextBeepCount, editTextVibrateTime, editTextVibrateWindow, editTextServer, editTextServerTimeout, editTextServerMqtt, editTextTopicMqtt, editTextForegroundDupElim, editTextServerImpinj, editTextServerImpinjName, editTextServerImpinjPasword;
+ private RadioButton radioButtonCloudSaveNone, radioButtonCloudSaveHttp, radioButtonCloudSaveMqtt;
+ private TextView textViewReaderModel;
+ private Spinner spinnerQueryBattery, spinnerQueryRssi, spinnerQueryVibrateMode, spinnerSavingFormat;
+ private Button buttonCSLServer, button;
+
+ final boolean sameCheck = true;
+ Handler mHandler = new Handler();
+
+ int batteryDisplaySelect = -1;
+ int rssiDisplaySelect = -1;
+ int vibrateModeSelect = -1;
+ int savingFormatSelect = -1;
+ int csvColumnSelect = -1;
+ String deviceName = "";
+ long cycleDelay = -1; long cycleDelayMin = 0; long cycleDelayMax = 2000;
+ int iBeepCount = -1; int iBeepCountMin = 1; int iBeepCountMax = 100;
+ short sTriggerCount = -1, sTriggerCountMin = 1, sTriggerCountMax = 100;
+ int iVibrateTime = -1; int iVibrateTimeMin = 1; int iVibrateTimeMax = 999;
+ int iVibrateWindow = -1; int iVibrateWindowMin = 1; int iVibrateWindowMax = 4;
+ boolean triggerReporting, inventoryBeep, inventoryVibrate, saveFileEnable, saveCloudEnable, saveNewCloudEnable, saveAllCloudEnable, debugEnable, foregroundServiceEnable;
+ String serverName, serverMqtt, topicMqtt, serverImpinj, serverImpinjName, serverImpinjPasword;
+ int buttonCloudSave = -1, iForegroundDupElimNew = -1;
+ int iServerTimeout = -1; int iServerTimeoutMin = 3; int iServerTimeoutMax = 9;
+
+ private SettingTask settingTask;
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ super.onCreateView(inflater, container, savedInstanceState, false);
+ return inflater.inflate(R.layout.fragment_settings_admin, container, false);
+ }
+
+ @Override
+ public void onActivityCreated(Bundle savedInstanceState) {
+ super.onActivityCreated(savedInstanceState);
+
+ textViewReaderModel = (TextView) getActivity().findViewById(R.id.settingAdminReaderModel);
+ editTextDeviceName = (EditText) getActivity().findViewById(R.id.settingAdminDeviceName);
+ editTextDeviceName.setBackgroundResource(R.drawable.my_edittext_background);
+ editTextDeviceName.setHint("Name Pattern");
+ InputFilter[] FilterArray = new InputFilter[1];
+ FilterArray[0] = new InputFilter.LengthFilter(20);
+ editTextDeviceName.setFilters(FilterArray);
+
+ spinnerQueryBattery = (Spinner) getActivity().findViewById(R.id.settingAdminBattery);
+ {
+ ArrayAdapter targetAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.admin_battery_options, R.layout.custom_spinner_layout);
+ targetAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+ spinnerQueryBattery.setAdapter(targetAdapter);
+ }
+
+ spinnerQueryRssi = (Spinner) getActivity().findViewById(R.id.settingAdminRssi);
+ {
+ ArrayAdapter targetAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.admin_rssi_options, R.layout.custom_spinner_layout);
+ targetAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+ spinnerQueryRssi.setAdapter(targetAdapter);
+ }
+
+ spinnerQueryVibrateMode = (Spinner) getActivity().findViewById(R.id.settingAdminVibrateMode);
+ {
+ ArrayAdapter targetAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.admin_vibratemode_options, R.layout.custom_spinner_layout);
+ targetAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+ spinnerQueryVibrateMode.setAdapter(targetAdapter);
+ }
+
+ if (MainActivity.csLibrary4A.get98XX() == 2) {
+ LinearLayout linearLayout = (LinearLayout) getActivity().findViewById(R.id.settingAdminCycleDelayRow);
+ linearLayout.setVisibility(View.GONE);
+ spinnerQueryVibrateMode.setEnabled(false);
+ }
+
+ spinnerSavingFormat = (Spinner) getActivity().findViewById(R.id.settingAdminSavingFormat);
+ {
+ ArrayAdapter targetAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.admin_savingformat_options, R.layout.custom_spinner_layout);
+ targetAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+ spinnerSavingFormat.setAdapter(targetAdapter);
+ spinnerSavingFormat.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
+ @Override
+ public void onItemSelected(AdapterView> adapterView, View view, int i, long l) {
+ LinearLayout linearLayout = (LinearLayout) getActivity().findViewById(R.id.settingAdminCSVColumnSelectLayout);
+ switch (i) {
+ case 1:
+ linearLayout.setVisibility(View.VISIBLE);
+ break;
+ default:
+ linearLayout.setVisibility(View.GONE);
+ break;
+ }
+ }
+
+ @Override
+ public void onNothingSelected(AdapterView> adapterView) {
+
+ }
+ });
+ }
+
+ checkBoxCsvColumnResBank = (CheckBox) getActivity().findViewById(R.id.settingAdminCSVColumnResBank);
+ checkBoxCsvColumnEpcBank = (CheckBox) getActivity().findViewById(R.id.settingAdminCSVColumnEpcBank);
+ checkBoxCsvColumnTidBank = (CheckBox) getActivity().findViewById(R.id.settingAdminCSVColumnTidBank);
+ checkBoxCsvColumnUserBank = (CheckBox) getActivity().findViewById(R.id.settingAdminCSVColumnUserBank);
+ checkBoxCsvColumnPhase = (CheckBox) getActivity().findViewById(R.id.settingAdminCSVColumnPhase);
+ checkBoxCsvColumnChannel = (CheckBox) getActivity().findViewById(R.id.settingAdminCSVColumnChannel);
+ checkBoxCsvColumnTime = (CheckBox) getActivity().findViewById(R.id.settingAdminCSVColumnTime);
+ checkBoxCsvColumnTimeZone = (CheckBox) getActivity().findViewById(R.id.settingAdminCSVColumnTimeZone);
+ checkBoxCsvColumnLocation = (CheckBox) getActivity().findViewById(R.id.settingAdminCSVColumnLocation);
+ checkBoxCsvColumnDirection = (CheckBox) getActivity().findViewById(R.id.settingAdminCSVColumnDirection);
+ checkBoxCsvColumnOthers = (CheckBox) getActivity().findViewById(R.id.settingAdminCSVColumnOthers);
+
+ TextView textViewAdminCycleDelayLabel = (TextView) getActivity().findViewById(R.id.settingAdminCycleDelayLabel);
+ String stringAdminCycleDelayLabel = textViewAdminCycleDelayLabel.getText().toString();
+ stringAdminCycleDelayLabel += "(" + String.valueOf(cycleDelayMin) + "-" + String.valueOf(cycleDelayMax) + "ms)";
+ textViewAdminCycleDelayLabel.setText(stringAdminCycleDelayLabel);
+ editTextCycleDelay = (EditText) getActivity().findViewById(R.id.settingAdminCycleDelay);
+
+ TextView textViewAdminTriggerReportingCountLabel = (TextView) getActivity().findViewById(R.id.settingAdminTriggerReportingCountLabel);
+ String stringAdminTriggeringReportingCountLabel = textViewAdminTriggerReportingCountLabel.getText().toString();
+ stringAdminTriggeringReportingCountLabel += "(" + String.valueOf(sTriggerCountMin) + "-" + String.valueOf(sTriggerCountMax) + ") sec";
+ textViewAdminTriggerReportingCountLabel.setText(stringAdminTriggeringReportingCountLabel);
+ editTextTriggerReportingCount = (EditText) getActivity().findViewById(R.id.settingAdminTriggerReportingCount);
+
+ TextView textViewAdminBeepCountLabel = (TextView) getActivity().findViewById(R.id.settingAdminBeepCountLabel);
+ String stringAdminBeepCountLabel = textViewAdminBeepCountLabel.getText().toString();
+ stringAdminBeepCountLabel += "(" + String.valueOf(iBeepCountMin) + "-" + String.valueOf(iBeepCountMax) + ")";
+ textViewAdminBeepCountLabel.setText(stringAdminBeepCountLabel);
+ editTextBeepCount = (EditText) getActivity().findViewById(R.id.settingAdminBeepCount);
+
+ TextView textViewAdminVibrateTimeLabel = (TextView) getActivity().findViewById(R.id.settingAdminVibrateTimeLabel);
+ String stringAdminVibrateTimeLabel = textViewAdminVibrateTimeLabel.getText().toString();
+ stringAdminVibrateTimeLabel += "(" + String.valueOf(iVibrateTimeMin) + "-" + String.valueOf(iVibrateTimeMax) + "ms)";
+ textViewAdminVibrateTimeLabel.setText(stringAdminVibrateTimeLabel);
+ editTextVibrateTime = (EditText) getActivity().findViewById(R.id.settingAdminVibrateTime);
+
+ TextView textViewAdminVibrateWindowLabel = (TextView) getActivity().findViewById(R.id.settingAdminVibrateWindowLabel);
+ String stringAdminVibrateWindowLabel = textViewAdminVibrateWindowLabel.getText().toString();
+ stringAdminVibrateWindowLabel += "(" + String.valueOf(iVibrateWindowMin) + "-" + String.valueOf(iVibrateWindowMax) + "sec)";
+ textViewAdminVibrateWindowLabel.setText(stringAdminVibrateWindowLabel);
+ editTextVibrateWindow = (EditText) getActivity().findViewById(R.id.settingAdminVibrateWindow);
+
+ checkBoxTriggerReporting = (CheckBox) getActivity().findViewById(R.id.settingAdminTriggerReporting);
+ checkBoxInventoryBeep = (CheckBox) getActivity().findViewById(R.id.settingAdminInventoryBeep);
+ checkBoxInventoryVibrate = (CheckBox) getActivity().findViewById(R.id.settingAdminInventoryVibrate);
+ checkBoxSaveFileEnable = (CheckBox) getActivity().findViewById(R.id.settingAdminToFileEnable);
+ checkBoxSaveCloudEnable = (CheckBox) getActivity().findViewById(R.id.settingAdminToCloudEnable);
+ checkBoxSaveNewCloudEnable = (CheckBox) getActivity().findViewById(R.id.settingAdminNewToCloudEnable);
+ checkBoxSaveAllCloudEnable = (CheckBox) getActivity().findViewById(R.id.settingAdminAllToCloudEnable);
+ editTextServer = (EditText) getActivity().findViewById(R.id.settingAdminServer);
+ editTextServer.setHint("Cloud Address Pattern");
+ editTextServerMqtt = (EditText) getActivity().findViewById(R.id.settingAdminMqttServer);
+ editTextServerMqtt.setHint("IP Address Pattern");
+ editTextTopicMqtt = (EditText) getActivity().findViewById(R.id.settingAdminTopicMqtt);
+ editTextForegroundDupElim = (EditText) getActivity().findViewById(R.id.settingAdminDupElimDelay);
+ radioButtonCloudSaveNone = (RadioButton) getActivity().findViewById(R.id.settingAdminCloudSaveNone);
+ radioButtonCloudSaveHttp = (RadioButton) getActivity().findViewById(R.id.settingAdminCloudSaveHttp);
+ radioButtonCloudSaveMqtt = (RadioButton) getActivity().findViewById(R.id.settingAdminCloudSaveMqtt);
+ editTextServerImpinj = (EditText) getActivity().findViewById(R.id.settingAdminServerImpinj);
+ editTextServerImpinjName = (EditText) getActivity().findViewById(R.id.settingAdminServerImpinjName);
+ editTextServerImpinjPasword = (EditText) getActivity().findViewById(R.id.settingAdminServerImpinjPassword);
+
+ TextView textViewAdminServerConnectTimeoutLabel = (TextView) getActivity().findViewById(R.id.settingAdminServerConnectTimeoutLabel);
+ String stringAdminServerConnectTimeoutLabel = textViewAdminServerConnectTimeoutLabel.getText().toString();
+ stringAdminServerConnectTimeoutLabel += "(" + String.valueOf(iServerTimeoutMin) + "-" + String.valueOf(iServerTimeoutMax) + "sec)";
+ textViewAdminServerConnectTimeoutLabel.setText(stringAdminServerConnectTimeoutLabel);
+ editTextServerTimeout = (EditText) getActivity().findViewById(R.id.settingAdminServerConnectTimeout);
+
+ buttonCSLServer = (Button) getActivity().findViewById(R.id.settingAdminCSLServer);
+ buttonCSLServer.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View view) {
+ String serverLocation = "https://" + "democloud.convergence.com.hk:" + "29090/WebServiceRESTs/1.0/req/" + "create-update-delete/update-entity/" + "tagdata";
+ //String serverLocation = "https://" + "www.convergence.com.hk:" + "29090/WebServiceRESTs/1.0/req/" + "create-update-delete/update-entity/" + "tagdata";
+ //String serverLocation = "http://ptsv2.com/t/10i1t-1519143332/post";
+ editTextServer.setText(serverLocation);
+ //String serverMqttLocation = "192.168.25.182";
+ //editTextServerMqtt.setText(serverMqttLocation);
+ //editTextTopicMqtt.setText("test/topic");
+ }
+ });
+
+ Button buttonReset = (Button) getActivity().findViewById(R.id.settingAdminBarcodeResetButton);
+ buttonReset.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (MainActivity.csLibrary4A.isBleConnected() == false) {
+ Toast.makeText(MainActivity.mContext, R.string.toast_ble_not_connected, Toast.LENGTH_SHORT).show();
+ return;
+ } else if (MainActivity.csLibrary4A.isBarcodeFailure()) {
+ Toast.makeText(MainActivity.mContext, "Barcode is disabled", Toast.LENGTH_SHORT).show();
+ return;
+ } else {
+ MainActivity.csLibrary4A.setBarcodeOn(true);
+ MainActivity.csLibrary4A.barcodeSendCommandConinuous();
+ MainActivity.csLibrary4A.setBarcodeOn(false);
+ MainActivity.csLibrary4A.saveSetting2File();
+ Toast.makeText(MainActivity.mContext, R.string.toast_saved, Toast.LENGTH_SHORT).show();
+ }
+ }
+ });
+
+ Button buttonReset2 = (Button) getActivity().findViewById(R.id.settingAdminBarcodeResetButtonT);
+ buttonReset2.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (MainActivity.csLibrary4A.isBleConnected() == false) {
+ Toast.makeText(MainActivity.mContext, R.string.toast_ble_not_connected, Toast.LENGTH_SHORT).show();
+ return;
+ } else if (MainActivity.csLibrary4A.isBarcodeFailure()) {
+ Toast.makeText(MainActivity.mContext, "Barcode is disabled", Toast.LENGTH_SHORT).show();
+ return;
+ } else {
+ MainActivity.csLibrary4A.setBarcodeOn(true);
+ MainActivity.csLibrary4A.barcodeSendCommandTrigger();
+ MainActivity.csLibrary4A.saveSetting2File();
+ Toast.makeText(MainActivity.mContext, R.string.toast_saved, Toast.LENGTH_SHORT).show();
+ }
+ }
+ });
+
+ Button buttonReset3 = (Button) getActivity().findViewById(R.id.settingAdminBarcodeResetButtonF);
+ buttonReset3.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (MainActivity.csLibrary4A.isBleConnected() == false) {
+ Toast.makeText(MainActivity.mContext, R.string.toast_ble_not_connected, Toast.LENGTH_SHORT).show();
+ return;
+ } else if (MainActivity.csLibrary4A.isBarcodeFailure()) {
+ Toast.makeText(MainActivity.mContext, "Barcode is disabled", Toast.LENGTH_SHORT).show();
+ return;
+ } else {
+ MainActivity.csLibrary4A.setBarcodeOn(true);
+ MainActivity.csLibrary4A.barcodeSendCommandSetPreSuffix();
+ Toast.makeText(MainActivity.mContext, R.string.toast_saved, Toast.LENGTH_SHORT).show();
+ }
+ }
+ });
+
+ Button buttonReset4 = (Button) getActivity().findViewById(R.id.settingAdminBarcodeResetButtonR);
+ buttonReset4.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (MainActivity.csLibrary4A.isBleConnected() == false) {
+ Toast.makeText(MainActivity.mContext, R.string.toast_ble_not_connected, Toast.LENGTH_SHORT).show();
+ return;
+ } else if (MainActivity.csLibrary4A.isBarcodeFailure()) {
+ Toast.makeText(MainActivity.mContext, "Barcode is disabled", Toast.LENGTH_SHORT).show();
+ return;
+ } else {
+ MainActivity.csLibrary4A.setBarcodeOn(true);
+ MainActivity.csLibrary4A.barcodeSendCommandResetPreSuffix();
+ Toast.makeText(MainActivity.mContext, R.string.toast_saved, Toast.LENGTH_SHORT).show();
+ }
+ }
+ });
+
+ Button buttonReset1 = (Button) getActivity().findViewById(R.id.settingAdminReaderResetButton);
+ buttonReset1.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (MainActivity.csLibrary4A.isBleConnected() == false) {
+ Toast.makeText(MainActivity.mContext, R.string.toast_ble_not_connected, Toast.LENGTH_SHORT).show();
+ return;
+ } else if (false && MainActivity.csLibrary4A.isRfidFailure()) {
+ Toast.makeText(MainActivity.mContext, "Rfid is disabled", Toast.LENGTH_SHORT).show();
+ return;
+ } else {
+ MainActivity.csLibrary4A.setReaderDefault();
+ MainActivity.csLibrary4A.saveSetting2File();
+ Toast.makeText(MainActivity.mContext, R.string.toast_saved, Toast.LENGTH_SHORT).show();
+
+ mHandler.post(updateRunnable);
+ CustomPopupWindow customPopupWindow = new CustomPopupWindow(MainActivity.mContext);
+ String stringInfo = "Please power cycle reader and also this application";
+ customPopupWindow.popupStart(stringInfo, false);
+ }
+ }
+ });
+
+ button = (Button) getActivity().findViewById(R.id.settingSaveButtonAdmin);
+ button.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ boolean validValue = false;
+ if (MainActivity.csLibrary4A.isBleConnected() == false) {
+ Toast.makeText(MainActivity.mContext, R.string.toast_ble_not_connected, Toast.LENGTH_SHORT).show();
+ return;
+ } else if (false && MainActivity.csLibrary4A.isRfidFailure()) {
+ Toast.makeText(MainActivity.mContext, "Rfid is disabled", Toast.LENGTH_SHORT).show();
+ return;
+ } else if (updateRunning) {
+ Toast.makeText(MainActivity.mContext, R.string.toast_not_ready, Toast.LENGTH_SHORT).show();
+ return;
+ } else {
+ try {
+ deviceName = editTextDeviceName.getText().toString();
+ batteryDisplaySelect = spinnerQueryBattery.getSelectedItemPosition();
+ rssiDisplaySelect = spinnerQueryRssi.getSelectedItemPosition();
+ vibrateModeSelect = spinnerQueryVibrateMode.getSelectedItemPosition();
+ savingFormatSelect = spinnerSavingFormat.getSelectedItemPosition();
+ {
+ csvColumnSelect = 0;
+ if (checkBoxCsvColumnResBank.isChecked()) csvColumnSelect |= (0x01 << RfidReaderChipData.CsvColumn.RESERVE_BANK.ordinal());
+ if (checkBoxCsvColumnEpcBank.isChecked()) csvColumnSelect |= (0x01 << RfidReaderChipData.CsvColumn.EPC_BANK.ordinal());
+ if (checkBoxCsvColumnTidBank.isChecked()) csvColumnSelect |= (0x01 << RfidReaderChipData.CsvColumn.TID_BANK.ordinal());
+ if (checkBoxCsvColumnUserBank.isChecked()) csvColumnSelect |= (0x01 << RfidReaderChipData.CsvColumn.USER_BANK.ordinal());
+ if (checkBoxCsvColumnPhase.isChecked()) csvColumnSelect |= (0x01 << RfidReaderChipData.CsvColumn.PHASE.ordinal());
+ if (checkBoxCsvColumnChannel.isChecked()) csvColumnSelect |= (0x01 << RfidReaderChipData.CsvColumn.CHANNEL.ordinal());
+ if (checkBoxCsvColumnTime.isChecked()) csvColumnSelect |= (0x01 << RfidReaderChipData.CsvColumn.TIME.ordinal());
+ if (checkBoxCsvColumnTimeZone.isChecked()) csvColumnSelect |= (0x01 << RfidReaderChipData.CsvColumn.TIMEZONE.ordinal());
+ if (checkBoxCsvColumnLocation.isChecked()) csvColumnSelect |= (0x01 << RfidReaderChipData.CsvColumn.LOCATION.ordinal());
+ if (checkBoxCsvColumnDirection.isChecked()) csvColumnSelect |= (0x01 << RfidReaderChipData.CsvColumn.DIRECTION.ordinal());
+ if (checkBoxCsvColumnOthers.isChecked()) csvColumnSelect |= (0x01 << RfidReaderChipData.CsvColumn.OTHERS.ordinal());
+ }
+ if (editTextCycleDelay != null) cycleDelay = Long.parseLong(editTextCycleDelay.getText().toString());
+ if (editTextTriggerReportingCount != null) sTriggerCount = Short.parseShort(editTextTriggerReportingCount.getText().toString());
+ if (editTextBeepCount != null) iBeepCount = Integer.parseInt(editTextBeepCount.getText().toString());
+ if (editTextVibrateTime != null) iVibrateTime = Integer.parseInt(editTextVibrateTime.getText().toString());
+ if (editTextVibrateWindow != null) iVibrateWindow = Integer.parseInt(editTextVibrateWindow.getText().toString());
+ triggerReporting = checkBoxTriggerReporting.isChecked();
+ inventoryBeep = checkBoxInventoryBeep.isChecked();
+ inventoryVibrate = checkBoxInventoryVibrate.isChecked();
+ saveFileEnable = checkBoxSaveFileEnable.isChecked();
+ saveCloudEnable = checkBoxSaveCloudEnable.isChecked();
+ saveNewCloudEnable = checkBoxSaveNewCloudEnable.isChecked();
+ saveAllCloudEnable = checkBoxSaveAllCloudEnable.isChecked();
+ serverName = editTextServer.getText().toString();
+ iServerTimeout = Integer.parseInt(editTextServerTimeout.getText().toString());
+ serverMqtt = editTextServerMqtt.getText().toString();
+ topicMqtt = editTextTopicMqtt.getText().toString();
+ iForegroundDupElimNew = Integer.parseInt(editTextForegroundDupElim.getText().toString());
+ buttonCloudSave = 0;
+ if (radioButtonCloudSaveNone.isChecked()) buttonCloudSave = 0;
+ else if (radioButtonCloudSaveHttp.isChecked()) buttonCloudSave = 1;
+ else if (radioButtonCloudSaveMqtt.isChecked()) buttonCloudSave = 2;
+ serverImpinj = editTextServerImpinj.getText().toString();
+ serverImpinjName = editTextServerImpinjName.getText().toString();
+ serverImpinjPasword = editTextServerImpinjPasword.getText().toString();
+ debugEnable = checkBoxDebugEnable.isChecked();
+ foregroundServiceEnable = checkBoxForegroundService.isChecked();
+ settingUpdate();
+ } catch (Exception ex) {
+ Toast.makeText(MainActivity.mContext, R.string.toast_invalid_range, Toast.LENGTH_SHORT).show();
+ }
+ }
+ }
+ });
+
+ checkBoxDebugEnable = (CheckBox) getActivity().findViewById(R.id.settingAdminDebugEnable);
+ checkBoxForegroundService = (CheckBox) getActivity().findViewById(R.id.settingAdminForegroundEnable);
+
+ if (!MainActivity.foregroundServiceEnable) {
+ LinearLayout linearLayout = (LinearLayout) getActivity().findViewById(R.id.settingAdminForegroundLayout);
+ linearLayout.setVisibility(View.GONE);
+ }
+ if (sameCheck == false) MainActivity.csLibrary4A.setSameCheck(false);
+ mHandler.post(updateRunnable);
+ }
+
+ @Override
+ public void onDestroy() {
+ if (settingTask != null) settingTask.cancel(true);
+ MainActivity.csLibrary4A.setSameCheck(true);
+ mHandler.removeCallbacks(updateRunnable);
+ super.onDestroy();
+ }
+
+ @Override
+ public void setUserVisibleHint(boolean isVisibleToUser) {
+ super.setUserVisibleHint(isVisibleToUser);
+ if(isVisibleToUser) {
+ checkBoxTriggerReporting.setChecked(MainActivity.csLibrary4A.getTriggerReporting());
+ checkBoxInventoryBeep.setChecked(MainActivity.csLibrary4A.getInventoryBeep());
+ checkBoxInventoryVibrate.setChecked(MainActivity.csLibrary4A.getInventoryVibrate());
+ checkBoxSaveFileEnable.setChecked(MainActivity.csLibrary4A.getSaveFileEnable());
+ checkBoxSaveCloudEnable.setChecked(MainActivity.csLibrary4A.getSaveCloudEnable());
+ checkBoxSaveNewCloudEnable.setChecked(MainActivity.csLibrary4A.getSaveNewCloudEnable());
+ checkBoxSaveAllCloudEnable.setChecked(MainActivity.csLibrary4A.getSaveAllCloudEnable());
+ checkBoxDebugEnable.setChecked(MainActivity.csLibrary4A.getUserDebugEnable());
+ checkBoxForegroundService.setChecked(MainActivity.csLibrary4A.getForegroundServiceEnable());
+ }
+ }
+
+ public SettingAdminFragment() {
+ super("SettingAdminFragment");
+ }
+
+ boolean updateRunning = false;
+ private final Runnable updateRunnable = new Runnable() {
+ @Override
+ public void run() {
+ int iValue;
+ long lValue;
+ boolean updating = false;
+
+ updateRunning = true;
+ spinnerQueryBattery.setSelection(MainActivity.csLibrary4A.getBatteryDisplaySetting());
+ spinnerQueryRssi.setSelection(MainActivity.csLibrary4A.getRssiDisplaySetting());
+ spinnerQueryVibrateMode.setSelection(MainActivity.csLibrary4A.getVibrateModeSetting());
+ spinnerSavingFormat.setSelection(MainActivity.csLibrary4A.getSavingFormatSetting());
+ {
+ int csvColumnSelect = MainActivity.csLibrary4A.getCsvColumnSelectSetting();
+ if ((csvColumnSelect & (0x01 << RfidReaderChipData.CsvColumn.RESERVE_BANK.ordinal())) != 0) checkBoxCsvColumnResBank.setChecked(true); else checkBoxCsvColumnResBank.setChecked(false);
+ if ((csvColumnSelect & (0x01 << RfidReaderChipData.CsvColumn.EPC_BANK.ordinal())) != 0) checkBoxCsvColumnEpcBank.setChecked(true); else checkBoxCsvColumnEpcBank.setChecked(false);
+ if ((csvColumnSelect & (0x01 << RfidReaderChipData.CsvColumn.TID_BANK.ordinal())) != 0) checkBoxCsvColumnTidBank.setChecked(true); else checkBoxCsvColumnTidBank.setChecked(false);
+ if ((csvColumnSelect & (0x01 << RfidReaderChipData.CsvColumn.USER_BANK.ordinal())) != 0) checkBoxCsvColumnUserBank.setChecked(true); else checkBoxCsvColumnUserBank.setChecked(false);
+ if ((csvColumnSelect & (0x01 << RfidReaderChipData.CsvColumn.PHASE.ordinal())) != 0) checkBoxCsvColumnPhase.setChecked(true); else checkBoxCsvColumnPhase.setChecked(false);
+ if ((csvColumnSelect & (0x01 << RfidReaderChipData.CsvColumn.CHANNEL.ordinal())) != 0) checkBoxCsvColumnChannel.setChecked(true); else checkBoxCsvColumnChannel.setChecked(false);
+ if ((csvColumnSelect & (0x01 << RfidReaderChipData.CsvColumn.TIME.ordinal())) != 0) checkBoxCsvColumnTime.setChecked(true); else checkBoxCsvColumnTime.setChecked(false);
+ if ((csvColumnSelect & (0x01 << RfidReaderChipData.CsvColumn.TIMEZONE.ordinal())) != 0) checkBoxCsvColumnTimeZone.setChecked(true); else checkBoxCsvColumnTimeZone.setChecked(false);
+ if ((csvColumnSelect & (0x01 << RfidReaderChipData.CsvColumn.LOCATION.ordinal())) != 0) checkBoxCsvColumnLocation.setChecked(true); else checkBoxCsvColumnLocation.setChecked(false);
+ if ((csvColumnSelect & (0x01 << RfidReaderChipData.CsvColumn.DIRECTION.ordinal())) != 0) checkBoxCsvColumnDirection.setChecked(true); else checkBoxCsvColumnDirection.setChecked(false);
+ if ((csvColumnSelect & (0x01 << RfidReaderChipData.CsvColumn.OTHERS.ordinal())) != 0) checkBoxCsvColumnOthers.setChecked(true); else checkBoxCsvColumnOthers.setChecked(false);
+ }
+ if (editTextCycleDelay != null) editTextCycleDelay.setText(String.valueOf(MainActivity.csLibrary4A.getCycleDelay()));
+ if (editTextTriggerReportingCount != null) {
+ int triggerReportingCount = MainActivity.csLibrary4A.getTriggerReportingCount();
+ if (triggerReportingCount != MainActivity.csLibrary4A.iNO_SUCH_SETTING) {
+ TableRow tableRow = (TableRow) getActivity().findViewById(R.id.settingAdminTriggerReportingRow);
+ tableRow.setVisibility(View.VISIBLE);
+ }
+ editTextTriggerReportingCount.setText(String.valueOf(triggerReportingCount));
+ }
+ if (editTextBeepCount != null) editTextBeepCount.setText(String.valueOf(MainActivity.csLibrary4A.getBeepCount()));
+ if (editTextVibrateTime != null) editTextVibrateTime.setText(String.valueOf(MainActivity.csLibrary4A.getVibrateTime()));
+ if (editTextVibrateWindow != null) editTextVibrateWindow.setText(String.valueOf(MainActivity.csLibrary4A.getVibrateWindow()));
+ editTextServer.setText(MainActivity.csLibrary4A.getServerLocation());
+ editTextServerTimeout.setText(String.valueOf(MainActivity.csLibrary4A.getServerTimeout()));
+ editTextServerMqtt.setText(MainActivity.csLibrary4A.getServerMqttLocation());
+ editTextTopicMqtt.setText(MainActivity.csLibrary4A.getTopicMqtt());
+ editTextForegroundDupElim.setText(String.valueOf(MainActivity.csLibrary4A.getForegroundDupElim()));
+ int inventoryCloudSave = MainActivity.csLibrary4A.getInventoryCloudSave();
+ if (inventoryCloudSave == 0) radioButtonCloudSaveNone.setChecked(true);
+ else if (inventoryCloudSave == 1) radioButtonCloudSaveHttp.setChecked(true);
+ else if (inventoryCloudSave == 2) radioButtonCloudSaveMqtt.setChecked(true);
+ editTextServerImpinj.setText(MainActivity.csLibrary4A.getServerImpinjLocation());
+ editTextServerImpinjName.setText(MainActivity.csLibrary4A.getServerImpinjName());
+ editTextServerImpinjPasword.setText(MainActivity.csLibrary4A.getServerImpinjPassword());
+ if (updating == false) {
+ String name = MainActivity.csLibrary4A.getBluetoothICFirmwareName();
+ if (name == null) {
+ MainActivity.csLibrary4A.appendToLog("updating 1");
+ updating = true;
+ }
+ else if (name.length() == 0) {
+ MainActivity.csLibrary4A.appendToLog("updating 2");
+ updating = true;
+ }
+ else editTextDeviceName.setText(name);
+ }
+ if (updating == false) {
+ String name = MainActivity.csLibrary4A.getModelNumber();
+ if (name == null) {
+ MainActivity.csLibrary4A.appendToLog("updating 3");
+ updating = true;
+ }
+ else if (name.length() == 0) {
+ MainActivity.csLibrary4A.appendToLog("updating 4");
+ updating = true;
+ }
+ else textViewReaderModel.setText(name);
+ }
+ if (updating) {
+ mHandler.postDelayed(updateRunnable, 1000);
+ } else updateRunning = false;
+ }
+ };
+
+ void settingUpdate() {
+ boolean sameSetting = true;
+ boolean invalidRequest = false;
+
+ if (invalidRequest == false && (MainActivity.csLibrary4A.getBluetoothICFirmwareName().matches(deviceName) == false || sameCheck == false)) {
+ sameSetting = false;
+ if (MainActivity.csLibrary4A.setBluetoothICFirmwareName(deviceName) == false)
+ invalidRequest = true;
+ }
+ if (invalidRequest == false && (MainActivity.csLibrary4A.getBatteryDisplaySetting() != batteryDisplaySelect || sameCheck == false)) {
+ sameSetting = false;
+ if (MainActivity.csLibrary4A.setBatteryDisplaySetting(batteryDisplaySelect) == false)
+ invalidRequest = true;
+ }
+ if (invalidRequest == false && (MainActivity.csLibrary4A.getRssiDisplaySetting() != rssiDisplaySelect || sameCheck == false)) {
+ sameSetting = false;
+ if (MainActivity.csLibrary4A.setRssiDisplaySetting(rssiDisplaySelect) == false)
+ invalidRequest = true;
+ }
+ if (invalidRequest == false && (MainActivity.csLibrary4A.getVibrateModeSetting() != vibrateModeSelect || sameCheck == false)) {
+ sameSetting = false;
+ if (MainActivity.csLibrary4A.setVibrateModeSetting(vibrateModeSelect) == false)
+ invalidRequest = true;
+ }
+ if (invalidRequest == false && (MainActivity.csLibrary4A.getSavingFormatSetting() != savingFormatSelect || sameCheck == false)) {
+ sameSetting = false;
+ if (MainActivity.csLibrary4A.setSavingFormatSetting(savingFormatSelect) == false)
+ invalidRequest = true;
+ }
+ if (invalidRequest == false && (MainActivity.csLibrary4A.getCsvColumnSelectSetting() != csvColumnSelect || sameCheck == false)) {
+ sameSetting = false;
+ if (MainActivity.csLibrary4A.setCsvColumnSelectSetting(csvColumnSelect) == false)
+ invalidRequest = true;
+ }
+ if (invalidRequest == false && editTextCycleDelay != null) {
+ if (MainActivity.csLibrary4A.getCycleDelay() != cycleDelay || sameCheck == false) {
+ sameSetting = false;
+ if (cycleDelay < cycleDelayMin || cycleDelay > cycleDelayMax) invalidRequest = true;
+ else if (MainActivity.csLibrary4A.setCycleDelay(cycleDelay) == false)
+ invalidRequest = true;
+ }
+ }
+ if (invalidRequest == false && editTextTriggerReportingCount != null) {
+ if (MainActivity.csLibrary4A.getTriggerReportingCount() != sTriggerCount || sameCheck == false) {
+ sameSetting = false;
+ if (sTriggerCount < sTriggerCountMin || sTriggerCount > sTriggerCountMax) invalidRequest = true;
+ else if (MainActivity.csLibrary4A.setTriggerReportingCount(sTriggerCount) == false)
+ invalidRequest = true;
+ }
+ }
+ if (invalidRequest == false && editTextBeepCount != null) {
+ if (MainActivity.csLibrary4A.getBeepCount() != iBeepCount || sameCheck == false) {
+ sameSetting = false;
+ if (iBeepCount < iBeepCountMin || iBeepCount > iBeepCountMax) invalidRequest = true;
+ else if (MainActivity.csLibrary4A.setBeepCount(iBeepCount) == false)
+ invalidRequest = true;
+ }
+ }
+ if (invalidRequest == false && editTextVibrateTime != null) {
+ if (MainActivity.csLibrary4A.getVibrateTime() != iVibrateTime || sameCheck == false) {
+ sameSetting = false;
+ if (iVibrateTime < iVibrateTimeMin || iVibrateTime > iVibrateTimeMax) invalidRequest = true;
+ else if (MainActivity.csLibrary4A.setVibrateTime(iVibrateTime) == false)
+ invalidRequest = true;
+ }
+ }
+ if (invalidRequest == false && editTextVibrateWindow != null) {
+ if (MainActivity.csLibrary4A.getVibrateWindow() != iVibrateWindow || sameCheck == false) {
+ sameSetting = false;
+ if (iVibrateWindow < iVibrateWindowMin || iVibrateWindow > iVibrateWindowMax) invalidRequest = true;
+ else if (MainActivity.csLibrary4A.setVibrateWindow(iVibrateWindow) == false)
+ invalidRequest = true;
+ }
+ }
+ if (invalidRequest == false && checkBoxInventoryVibrate != null) {
+ MainActivity.csLibrary4A.appendToLog("getInventoryVibrate = " + MainActivity.csLibrary4A.getInventoryVibrate() + ", inventoryVibrate = " + inventoryVibrate);
+ if (MainActivity.csLibrary4A.getInventoryVibrate() != inventoryVibrate || sameCheck == false) {
+ sameSetting = false;
+ if (MainActivity.csLibrary4A.setInventoryVibrate(inventoryVibrate) == false)
+ invalidRequest = true;
+ }
+ }
+ if (invalidRequest == false && checkBoxTriggerReporting != null) {
+ if (MainActivity.csLibrary4A.getTriggerReporting() != triggerReporting || sameCheck == false) {
+ sameSetting = false;
+ if (MainActivity.csLibrary4A.setTriggerReporting(triggerReporting) == false)
+ invalidRequest = true;
+ }
+ }
+ if (invalidRequest == false && checkBoxInventoryBeep != null) {
+ MainActivity.csLibrary4A.appendToLog("getInventoryBeep = " + MainActivity.csLibrary4A.getInventoryBeep() + ", inventoryBeep = " + inventoryBeep);
+ if (MainActivity.csLibrary4A.getInventoryBeep() != inventoryBeep || sameCheck == false) {
+ sameSetting = false;
+ if (MainActivity.csLibrary4A.setInventoryBeep(inventoryBeep) == false)
+ invalidRequest = true;
+ }
+ }
+ if (invalidRequest == false && checkBoxSaveFileEnable != null) {
+ MainActivity.csLibrary4A.appendToLog("getSaveFileEnable = " + MainActivity.csLibrary4A.getSaveFileEnable() + ", saveFileEnable = " + saveFileEnable);
+ if (MainActivity.csLibrary4A.getSaveFileEnable() != saveFileEnable || sameCheck == false) {
+ sameSetting = false;
+ if (MainActivity.csLibrary4A.setSaveFileEnable(saveFileEnable) == false)
+ invalidRequest = true;
+ }
+ }
+ if (invalidRequest == false && checkBoxSaveCloudEnable != null) {
+ MainActivity.csLibrary4A.appendToLog("getSaveCloudEnable = " + MainActivity.csLibrary4A.getSaveCloudEnable() + ", saveCloudEnable = " + saveCloudEnable);
+ if (MainActivity.csLibrary4A.getSaveCloudEnable() != saveCloudEnable || sameCheck == false) {
+ sameSetting = false;
+ if (MainActivity.csLibrary4A.setSaveCloudEnable(saveCloudEnable) == false)
+ invalidRequest = true;
+ }
+ }
+ if (invalidRequest == false && checkBoxSaveNewCloudEnable != null) {
+ MainActivity.csLibrary4A.appendToLog("getSaveNewCloudEnable = " + MainActivity.csLibrary4A.getSaveNewCloudEnable() + ", saveNewCloudEnable = " + saveNewCloudEnable);
+ if (MainActivity.csLibrary4A.getSaveNewCloudEnable() != saveNewCloudEnable || sameCheck == false) {
+ sameSetting = false;
+ if (MainActivity.csLibrary4A.setSaveNewCloudEnable(saveNewCloudEnable) == false)
+ invalidRequest = true;
+ }
+ }
+ if (invalidRequest == false && checkBoxSaveAllCloudEnable != null) {
+ MainActivity.csLibrary4A.appendToLog("getSaveAllCloudEnable = " + MainActivity.csLibrary4A.getSaveAllCloudEnable() + ", saveAllCloudEnable = " + saveAllCloudEnable);
+ if (MainActivity.csLibrary4A.getSaveAllCloudEnable() != saveAllCloudEnable || sameCheck == false) {
+ sameSetting = false;
+ if (MainActivity.csLibrary4A.setSaveAllCloudEnable(saveAllCloudEnable) == false)
+ invalidRequest = true;
+ }
+ }
+ if (invalidRequest == false && editTextServer != null) {
+ String serverLocation = MainActivity.csLibrary4A.getServerLocation(); if (serverLocation == null) serverLocation = "";
+ if (serverLocation.matches(serverName) == false || sameCheck == false) {
+ sameSetting = false;
+ if (MainActivity.csLibrary4A.setServerLocation(serverName) == false)
+ invalidRequest = true;
+ }
+ }
+ if (invalidRequest == false && editTextServerTimeout != null) {
+ if (MainActivity.csLibrary4A.getServerTimeout() != iServerTimeout || sameCheck == false) {
+ sameSetting = false;
+ if (iServerTimeout < iServerTimeoutMin || iServerTimeout > iServerTimeoutMax) invalidRequest = true;
+ else if (MainActivity.csLibrary4A.setServerTimeout(iServerTimeout) == false)
+ invalidRequest = true;
+ }
+ }
+ if (invalidRequest == false && editTextServerMqtt != null) {
+ String serverLocation = MainActivity.csLibrary4A.getServerMqttLocation(); if (serverLocation == null) serverLocation = "";
+ if (serverLocation.matches(serverMqtt) == false || sameCheck == false) {
+ sameSetting = false;
+ if (MainActivity.csLibrary4A.setServerMqttLocation(serverMqtt) == false)
+ invalidRequest = true;
+ }
+ }
+ if (invalidRequest == false && editTextTopicMqtt != null) {
+ String topic = MainActivity.csLibrary4A.getTopicMqtt(); if (topic == null) topic = "";
+ if (topic.matches(topicMqtt) == false || sameCheck == false) {
+ sameSetting = false;
+ if (MainActivity.csLibrary4A.setTopicMqtt(topicMqtt) == false)
+ invalidRequest = true;
+ }
+ }
+ if (invalidRequest == false && editTextForegroundDupElim != null) {
+ int iForegroundDupElim = MainActivity.csLibrary4A.getForegroundDupElim(); if (iForegroundDupElim < 0) iForegroundDupElim = 0;
+ if (iForegroundDupElim != iForegroundDupElimNew || sameCheck == false) {
+ sameSetting = false;
+ if (MainActivity.csLibrary4A.setForegroundDupElim(iForegroundDupElimNew) == false)
+ invalidRequest = true;
+ }
+ }
+ if (invalidRequest == false && radioButtonCloudSaveNone != null && radioButtonCloudSaveHttp != null && radioButtonCloudSaveMqtt != null) {
+ int inventoryCloudSave = MainActivity.csLibrary4A.getInventoryCloudSave();
+ if (inventoryCloudSave != buttonCloudSave || sameCheck == false) {
+ sameSetting = false;
+ if (MainActivity.csLibrary4A.setInventoryCloudSave(buttonCloudSave) == false)
+ invalidRequest = true;
+ }
+ }
+ if (invalidRequest == false && editTextServerImpinj != null) {
+ String string = MainActivity.csLibrary4A.getServerImpinjLocation(); if (string == null) string = "";
+ MainActivity.csLibrary4A.appendToLog("old serverImpinj = " + string + ", new = " + serverImpinj);
+ if (string.matches(serverImpinj) == false || sameCheck == false) {
+ sameSetting = false;
+ if (MainActivity.csLibrary4A.setServerImpinjLocation(serverImpinj) == false)
+ invalidRequest = true;
+ }
+ }
+ if (invalidRequest == false && editTextServerImpinjName != null) {
+ String string = MainActivity.csLibrary4A.getServerImpinjName(); if (string == null) string = "";
+ MainActivity.csLibrary4A.appendToLog("old serverImpinjName = " + string + ", new = " + serverImpinjName);
+ if (string.matches(serverImpinjName) == false || sameCheck == false) {
+ sameSetting = false;
+ if (MainActivity.csLibrary4A.setServerImpinjName(serverImpinjName) == false)
+ invalidRequest = true;
+ }
+ }
+ if (invalidRequest == false && editTextServerImpinjPasword != null) {
+ String string = MainActivity.csLibrary4A.getServerImpinjPassword(); if (string == null) string = "";
+ MainActivity.csLibrary4A.appendToLog("old serverImpinjPassword = " + string + ", new = " + serverImpinjPasword + ", matched = " + string.matches(serverImpinjPasword));
+ if (string.length() != serverImpinjPasword.length() || string.matches(serverImpinjPasword) == false || sameCheck == false) {
+ sameSetting = false;
+ if (MainActivity.csLibrary4A.setServerImpinjPassword(serverImpinjPasword) == false)
+ invalidRequest = true;
+ }
+ }
+ if (invalidRequest == false && checkBoxDebugEnable != null) {
+ MainActivity.csLibrary4A.appendToLog("getDebugEnable = " + MainActivity.csLibrary4A.getUserDebugEnable() + ", debugEnable = " + debugEnable);
+ if (MainActivity.csLibrary4A.getUserDebugEnable() != debugEnable || sameCheck == false) {
+ sameSetting = false;
+ if (MainActivity.csLibrary4A.setUserDebugEnable(debugEnable) == false)
+ invalidRequest = true;
+ }
+ }
+ if (invalidRequest == false && checkBoxForegroundService != null && MainActivity.foregroundServiceEnable) {
+ MainActivity.csLibrary4A.appendToLog("getForegroundServiceEnable = " + MainActivity.csLibrary4A.getForegroundServiceEnable() + ", foregroundServiceEnable = " + foregroundServiceEnable);
+ if (MainActivity.csLibrary4A.getForegroundServiceEnable() != foregroundServiceEnable || sameCheck == false) {
+ sameSetting = false;
+ MainActivity.csLibrary4A.appendToLog("foregroundReader108: updated 2C");
+ if (MainActivity.csLibrary4A.setForegroundServiceEnable(foregroundServiceEnable) == false)
+ invalidRequest = true;
+ }
+ }
+ settingTask = new SettingTask(button, sameSetting, invalidRequest);
+ settingTask.execute();
+ MainActivity.csLibrary4A.saveSetting2File();
+ }
+}
+
+
+
+package com.csl.cs710ademoapp.fragments;
+
+import android.os.Bundle;
+import android.util.Log;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+
+import androidx.appcompat.app.ActionBar;
+import androidx.appcompat.app.AppCompatActivity;
+import androidx.viewpager.widget.ViewPager;
+
+import com.csl.cs710ademoapp.R;
+import com.csl.cslibrary4a.AdapterTab;
+import com.google.android.material.tabs.TabLayout;
+
+public class SettingFilterFragment extends CommonFragment {
+ private ActionBar actionBar;
+ private ViewPager viewPager;
+ AdapterTab adapter;
+
+ private String[] tabs = {"Pre-filter", "Post-filter", "Rssi-filter"};
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ super.onCreateView(inflater, container, savedInstanceState, true);
+ return inflater.inflate(R.layout.custom_tabbed_layout, container, false);
+ }
+
+ @Override
+ public void onActivityCreated(Bundle savedInstanceState) {
+ super.onActivityCreated(savedInstanceState);
+
+ actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
+ actionBar.setIcon(R.drawable.dl_filters);
+ actionBar.setTitle(R.string.title_activity_filters);
+
+ TabLayout tabLayout = (TabLayout) getActivity().findViewById(R.id.OperationsTabLayout);
+
+ adapter = new AdapterTab(getActivity().getSupportFragmentManager(), tabs.length);
+ adapter.setFragment(0, new SettingFilterPreFragment());
+ adapter.setFragment(1, new SettingFilterPostFragment());
+ adapter.setFragment(2, new SettingFilterRssiFragment());
+
+ viewPager = (ViewPager) getActivity().findViewById(R.id.OperationsPager);
+ viewPager.setAdapter(adapter);
+ viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
+
+ for (String tab_name : tabs) {
+ tabLayout.addTab(tabLayout.newTab().setText(tab_name));
+ }
+
+ tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
+ @Override
+ public void onTabSelected(TabLayout.Tab tab) {
+ Log.i(TAG, "tab.position is " + tab.getPosition());
+ viewPager.setCurrentItem(tab.getPosition());
+ }
+
+ @Override
+ public void onTabUnselected(TabLayout.Tab tab) {
+ }
+
+ @Override
+ public void onTabReselected(TabLayout.Tab tab) {
+ }
+ });
+ }
+
+ @Override
+ public void onPause() {
+ adapter.fragment0.onPause();
+ adapter.fragment1.onPause();
+ super.onPause();
+ }
+
+ @Override
+ public void onStop() {
+ adapter.fragment0.onStop();
+ adapter.fragment1.onStop();
+ super.onStop();
+ }
+
+ @Override
+ public void onDestroyView() {
+ adapter.fragment0.onDestroyView();
+ adapter.fragment1.onDestroyView();
+ super.onDestroyView();
+ }
+
+ @Override
+ public void onDestroy() {
+ adapter.fragment0.onDestroy();
+ adapter.fragment1.onDestroy();
+ super.onDestroy();
+ }
+
+ @Override
+ public void onDetach() {
+ adapter.fragment0.onDetach();
+ adapter.fragment1.onDetach();
+ super.onDetach();
+ }
+
+ public SettingFilterFragment() {
+ super("SettingFilterFragment");
+ }
+}
+
+
+
+package com.csl.cs710ademoapp.fragments;
+
+import android.os.Bundle;
+import android.os.Handler;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.Button;
+import android.widget.CheckBox;
+import android.widget.EditText;
+import android.widget.Toast;
+
+import com.csl.cs710ademoapp.MainActivity;
+import com.csl.cs710ademoapp.R;
+import com.csl.cs710ademoapp.SettingTask;
+
+public class SettingFilterPostFragment extends CommonFragment {
+ private CheckBox checkBoxEnable;
+ private CheckBox checkBoxType;
+ private EditText postFilterOffset;
+ private EditText filterPostMaskData;
+ private Button button;
+
+ final boolean sameCheck = false;
+ Handler mHandler = new Handler();
+
+ boolean invMatchEnable;
+ boolean invMatchType;
+ int invMatchOffset = -1;
+ String invMatchData = null;
+
+ private SettingTask settingTask;
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ super.onCreateView(inflater, container, savedInstanceState, false);
+ return inflater.inflate(R.layout.fragment_filterpost_content, container, false);
+ }
+
+ @Override
+ public void onActivityCreated(Bundle savedInstanceState) {
+ super.onActivityCreated(savedInstanceState);
+
+ checkBoxEnable = (CheckBox) getActivity().findViewById(R.id.filterPostCheckEnable);
+ checkBoxType = (CheckBox) getActivity().findViewById(R.id.filterPostCheckType);
+ postFilterOffset = (EditText) getActivity().findViewById(R.id.filterPostOffset);
+ filterPostMaskData = (EditText) getActivity().findViewById(R.id.filterPostMaskData);
+
+ button = (Button) getActivity().findViewById(R.id.filterPostSaveButton);
+ button.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ boolean validValue = false;
+ if (MainActivity.csLibrary4A.isBleConnected() == false) {
+ Toast.makeText(MainActivity.mContext, R.string.toast_ble_not_connected, Toast.LENGTH_SHORT).show();
+ return;
+ } else if (MainActivity.csLibrary4A.isRfidFailure()) {
+ Toast.makeText(MainActivity.mContext, "Rfid is disabled", Toast.LENGTH_SHORT).show();
+ return;
+ } else {
+ try {
+ invMatchEnable = checkBoxEnable.isChecked();
+ invMatchType = checkBoxType.isChecked();
+ invMatchOffset = Integer.parseInt(postFilterOffset.getText().toString());
+
+ settingUpdate();
+ } catch (Exception ex) {
+ Toast.makeText(MainActivity.mContext, R.string.toast_invalid_range, Toast.LENGTH_SHORT).show();
+ }
+ }
+ }
+ });
+
+ if (sameCheck == false) MainActivity.csLibrary4A.setSameCheck(false);
+ mHandler.post(updateRunnable);
+ }
+
+ @Override
+ public void onDestroy() {
+ if (settingTask != null) settingTask.cancel(true);
+ MainActivity.csLibrary4A.setSameCheck(true);
+ mHandler.removeCallbacks(updateRunnable);
+ super.onDestroy();
+ }
+
+ public SettingFilterPostFragment() {
+ super("SettingFilterPostFragment");
+ }
+
+ private final Runnable updateRunnable = new Runnable() {
+ @Override
+ public void run() {
+ int iValue;
+ long lValue;
+ boolean updating = false;
+
+ if (MainActivity.csLibrary4A.mrfidToWriteSize() != 0) updating = true;
+ else {
+ if (updating == false) {
+ checkBoxEnable.setChecked(MainActivity.csLibrary4A.getInvMatchEnable());
+ checkBoxType.setChecked(MainActivity.csLibrary4A.getInvMatchType());
+ }
+ if (updating == false) {
+ int iValue1 = MainActivity.csLibrary4A.getInvMatchOffset();
+ if (iValue1 < 0) {
+ updating = true;
+ } else {
+ postFilterOffset.setText(String.valueOf(iValue1));
+ }
+ }
+ if (updating == false && filterPostMaskData.getText().length() == 0) {
+ String strValue = MainActivity.csLibrary4A.getInvMatchData();
+ if (strValue == null) {
+ updating = true;
+ } else {
+ filterPostMaskData.setText(strValue);
+ }
+ }
+ }
+ if (updating) {
+ mHandler.postDelayed(updateRunnable, 1000);
+ }
+ }
+ };
+
+ void settingUpdate() {
+ boolean dataMatched = false;
+ invMatchData = filterPostMaskData.getText().toString();
+ String strValue = MainActivity.csLibrary4A.getInvMatchData();
+ boolean sameSetting = true;
+ boolean invalidRequest = false;
+
+ if (invMatchData.length() != strValue.length()) {
+ dataMatched = false;
+ } else if (invMatchData.length() == 0 && strValue.length() == 0) {
+ dataMatched = true;
+ } else dataMatched = invMatchData.matches(strValue);
+ if (MainActivity.csLibrary4A.getInvMatchEnable() != invMatchEnable
+ || MainActivity.csLibrary4A.getInvMatchType() != invMatchType
+ || MainActivity.csLibrary4A.getInvMatchOffset() != invMatchOffset
+ || dataMatched == false || sameCheck == false) {
+ sameSetting = false;
+ if (MainActivity.csLibrary4A.setPostMatchCriteria(invMatchEnable, invMatchType, invMatchOffset, invMatchData) == false)
+ invalidRequest = true;
+ }
+ settingTask = new SettingTask(button, sameSetting, invalidRequest);
+ settingTask.execute();
+ }
+}
+
+
+
+package com.csl.cs710ademoapp.fragments;
+
+import android.os.Bundle;
+import android.os.Handler;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.AdapterView;
+import android.widget.ArrayAdapter;
+import android.widget.Button;
+import android.widget.CheckBox;
+import android.widget.EditText;
+import android.widget.Spinner;
+import android.widget.Toast;
+
+import com.csl.cs710ademoapp.MainActivity;
+import com.csl.cs710ademoapp.R;
+import com.csl.cs710ademoapp.SettingTask;
+
+public class SettingFilterPreFragment extends CommonFragment {
+ private EditText editTextFilterPreSelectIndex;
+ private CheckBox checkBoxEnable;
+ private Spinner targetSpinner;
+ private Spinner actionSpinner;
+ private Spinner memoryBankSpinner;
+ private Spinner spinnerMaskDataType;
+ private EditText preFilterOffset;
+ private EditText filterPreMaskDataHex, filterPreMaskDataBit;
+ private Button button;
+
+ final boolean sameCheck = false;
+ Handler mHandler = new Handler();
+
+ int invSelectIndex = -1;
+ boolean invSelectEnable;
+ int invSelectTarget = -1;
+ int invSelectAction = -1;
+ int invSelectMaskBank = -1;
+ int invSelectMaskOffset = -1;
+ String invSelectMaskData = null;
+
+ private SettingTask settingTask;
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ super.onCreateView(inflater, container, savedInstanceState, false);
+ return inflater.inflate(R.layout.fragment_filterpre_content, container, false);
+ }
+
+ @Override
+ public void onActivityCreated(Bundle savedInstanceState) {
+ super.onActivityCreated(savedInstanceState);
+
+ editTextFilterPreSelectIndex = (EditText) getActivity().findViewById(R.id.filterPreSelectxIndex);
+ checkBoxEnable = (CheckBox) getActivity().findViewById(R.id.filterPreCheck);
+
+ targetSpinner = (Spinner) getActivity().findViewById(R.id.preFilterTarget);
+ ArrayAdapter targetAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.filterPre_target_options, R.layout.custom_spinner_layout);
+ targetAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+ targetSpinner.setAdapter(targetAdapter);
+ if (false) targetSpinner.setEnabled(false);
+
+ actionSpinner = (Spinner) getActivity().findViewById(R.id.preFilterAction);
+ ArrayAdapter actionAdapter;
+ if (true) { //MainActivity.csLibrary4A.getQuerySelect() >= 2) {
+ actionAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.filterPre_SLaction_options, R.layout.custom_spinner_layout);
+ } else {
+ actionAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.filterPre_SessionAction_options, R.layout.custom_spinner_layout);
+ }
+ actionAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+ actionSpinner.setAdapter(actionAdapter);
+ if (false) actionSpinner.setEnabled(false);
+
+ memoryBankSpinner = (Spinner) getActivity().findViewById(R.id.preFilterMemoryBank);
+ ArrayAdapter memoryBankAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.read_memoryBank_options, R.layout.custom_spinner_layout);
+ memoryBankAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+ memoryBankSpinner.setAdapter(memoryBankAdapter);
+ memoryBankSpinner.setEnabled(true);
+
+ spinnerMaskDataType = (Spinner) getActivity().findViewById(R.id.filterPreMaskDataType);
+ ArrayAdapter maskDataTypeAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.dataType_options, R.layout.custom_spinner_layout);
+ maskDataTypeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+ spinnerMaskDataType.setAdapter(maskDataTypeAdapter);
+ spinnerMaskDataType.setEnabled(true);
+ spinnerMaskDataType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
+ @Override
+ public void onItemSelected(AdapterView> adapterView, View view, int i, long l) {
+ if (spinnerMaskDataType.getSelectedItemPosition() == 0) {
+ filterPreMaskDataHex.setVisibility(View.VISIBLE);
+ filterPreMaskDataBit.setVisibility(View.GONE);
+ } else {
+ filterPreMaskDataHex.setVisibility(View.GONE);
+ filterPreMaskDataBit.setVisibility(View.VISIBLE);
+ }
+ }
+ @Override
+ public void onNothingSelected(AdapterView> adapterView) {
+ }
+ });
+
+ preFilterOffset = (EditText) getActivity().findViewById(R.id.filterPreOffset);
+ filterPreMaskDataHex = (EditText) getActivity().findViewById(R.id.filterPreMaskDataHex);
+ filterPreMaskDataBit = (EditText) getActivity().findViewById(R.id.filterPreMaskDataBit);
+
+ button = (Button) getActivity().findViewById(R.id.filterPreSaveButton);
+ button.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ boolean validValue = false;
+ if (MainActivity.csLibrary4A.isBleConnected() == false) {
+ Toast.makeText(MainActivity.mContext, R.string.toast_ble_not_connected, Toast.LENGTH_SHORT).show();
+ return;
+ } else if (MainActivity.csLibrary4A.isRfidFailure()) {
+ Toast.makeText(MainActivity.mContext, "Rfid is disabled", Toast.LENGTH_SHORT).show();
+ return;
+ } else {
+ try {
+ invSelectIndex = Integer.parseInt(editTextFilterPreSelectIndex.getText().toString());
+ invSelectEnable = checkBoxEnable.isChecked();
+ invSelectTarget = targetSpinner.getSelectedItemPosition();
+ invSelectAction = actionSpinner.getSelectedItemPosition();
+ invSelectMaskBank = memoryBankSpinner.getSelectedItemPosition() + 1;
+ invSelectMaskOffset = Integer.parseInt(preFilterOffset.getText().toString()); if (invSelectMaskBank == 1) invSelectMaskOffset += 32;
+
+ settingUpdate();
+ } catch (Exception ex) {
+ Toast.makeText(MainActivity.mContext, R.string.toast_invalid_range, Toast.LENGTH_SHORT).show();
+ }
+ }
+ }
+ });
+
+ if (sameCheck == false) MainActivity.csLibrary4A.setSameCheck(false);
+ mHandler.post(updateRunnable);
+ }
+
+ @Override
+ public void onDestroy() {
+ if (settingTask != null) settingTask.cancel(true);
+ MainActivity.csLibrary4A.setSameCheck(true);
+ mHandler.removeCallbacks(updateRunnable);
+ super.onDestroy();
+ }
+
+ public SettingFilterPreFragment() {
+ super("SettingFilterPreFragment");
+ }
+
+ private final Runnable updateRunnable = new Runnable() {
+ @Override
+ public void run() {
+ int iValue;
+ long lValue;
+ boolean updating = false;
+
+ if (MainActivity.csLibrary4A.mrfidToWriteSize() != 0) updating = true;
+ else {
+ if (updating == false && editTextFilterPreSelectIndex.getText().length() == 0) {
+ lValue = MainActivity.csLibrary4A.getInvSelectIndex();
+ MainActivity.csLibrary4A.appendToLog("updateRunnable getInvSelectIndex = " + lValue);
+ if (lValue < 0) {
+ updating = true;
+ } else {
+ editTextFilterPreSelectIndex.setText(String.valueOf(lValue));
+ }
+ }
+ if (updating == false) {
+ boolean bValue = MainActivity.csLibrary4A.getSelectEnable();
+ MainActivity.csLibrary4A.appendToLog("updateRunnable getSelectEnable = " + bValue);
+ checkBoxEnable.setChecked(bValue);
+ }
+ if (updating == false) {
+ int iValue1 = MainActivity.csLibrary4A.getSelectTarget();
+ MainActivity.csLibrary4A.appendToLog("updateRunnable getSelectTarget = " + iValue1);
+ if (iValue1 < 0) {
+ updating = true;
+ } else {
+ if (iValue1 > 4) iValue1 = 4;
+ iValue1 = 4; //fixed as SL
+ targetSpinner.setSelection(iValue1);
+ }
+ }
+ if (updating == false) {
+ int iValue1 = MainActivity.csLibrary4A.getSelectAction();
+ MainActivity.csLibrary4A.appendToLog("updateRunnable getSelectAction = " + iValue1);
+ if (iValue1 < 0) {
+ updating = true;
+ } else {
+ actionSpinner.setSelection(iValue1);
+ }
+ }
+ if (updating == false) {
+ int iValue1 = MainActivity.csLibrary4A.getSelectMaskBank();
+ MainActivity.csLibrary4A.appendToLog("updateRunnable getSelectMaskBank = " + iValue1);
+ if (iValue1 < 0) {
+ updating = true;
+ } else {
+ if (iValue1 < 1) iValue1 = 1;
+ iValue1--;
+ memoryBankSpinner.setSelection(iValue1);
+ }
+ }
+ if (updating == false) {
+ int iValue1 = MainActivity.csLibrary4A.getSelectMaskOffset();
+ MainActivity.csLibrary4A.appendToLog("updateRunnable getSelectMaskOffset = " + iValue1);
+ if (iValue1 < 0) {
+ updating = true;
+ } else {
+ if (iValue1 < 32) iValue1 = 32;
+ iValue1 -= 32;
+ preFilterOffset.setText(String.valueOf(iValue1));
+ }
+ }
+ if (updating == false) {
+ String strValue = MainActivity.csLibrary4A.getSelectMaskData();
+ MainActivity.csLibrary4A.appendToLog("updateRunnable getSelectMaskData = " + strValue);
+ if (strValue == null) {
+ updating = true;
+ } else {
+ spinnerMaskDataType.setSelection(0);
+ filterPreMaskDataHex.setText(strValue);
+ }
+ }
+ }
+ if (updating) {
+ mHandler.postDelayed(updateRunnable, 1000);
+ }
+ }
+ };
+
+ void settingUpdate() {
+ boolean sameSetting = true;
+ boolean invalidRequest = false;
+
+ if (MainActivity.csLibrary4A.getInvSelectIndex() != invSelectIndex) {
+ sameSetting = false;
+ if (MainActivity.csLibrary4A.setInvSelectIndex(invSelectIndex) == false)
+ invalidRequest = true;
+ else {
+ mHandler.removeCallbacks(updateRunnable);
+ mHandler.post(updateRunnable);
+ }
+ }
+ if (sameSetting == true && invalidRequest == false) {
+ if (true)
+ {
+ boolean dataMatched = false;
+ boolean maskbit = (spinnerMaskDataType.getSelectedItemPosition() == 0 ? false : true);
+ if (maskbit) invSelectMaskData = filterPreMaskDataBit.getText().toString();
+ else invSelectMaskData = filterPreMaskDataHex.getText().toString();
+ String strValue = MainActivity.csLibrary4A.getSelectMaskData();
+ if (invSelectMaskData.length() != strValue.length()) { }
+ else if (invSelectMaskData.length() == 0 && strValue.length() == 0) { dataMatched = true; }
+ else dataMatched = invSelectMaskData.matches(strValue);
+ if (MainActivity.csLibrary4A.getSelectEnable() != invSelectEnable
+ || MainActivity.csLibrary4A.getSelectTarget() != invSelectTarget
+ || MainActivity.csLibrary4A.getSelectAction() != invSelectAction
+ || MainActivity.csLibrary4A.getSelectMaskBank() != invSelectMaskBank
+ || MainActivity.csLibrary4A.getSelectMaskOffset() != invSelectMaskOffset
+ || dataMatched == false || sameCheck == false) {
+ sameSetting = false;
+ if (MainActivity.csLibrary4A.setSelectCriteria(0, invSelectEnable, invSelectTarget, invSelectAction, invSelectMaskBank, invSelectMaskOffset, invSelectMaskData, maskbit) == false)
+ invalidRequest = true;
+ }
+ }
+ }
+
+ settingTask = new SettingTask(button, sameSetting, invalidRequest);
+ settingTask.execute();
+ MainActivity.csLibrary4A.saveSetting2File();
+ }
+}
+
+
+
+package com.csl.cs710ademoapp.fragments;
+
+import android.os.Bundle;
+import android.os.Handler;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.ArrayAdapter;
+import android.widget.Button;
+import android.widget.CheckBox;
+import android.widget.EditText;
+import android.widget.Spinner;
+import android.widget.TextView;
+import android.widget.Toast;
+
+import com.csl.cs710ademoapp.MainActivity;
+import com.csl.cs710ademoapp.R;
+import com.csl.cs710ademoapp.SettingTask;
+
+public class SettingFilterRssiFragment extends CommonFragment {
+ private CheckBox checkBoxEnable;
+ private Spinner spinnerFilterType, spinnerFilterOption;
+ private EditText editTextFilterThreshold1, editTextFilterThreshold2, editTextFilterCount;
+ private Button button;
+
+ final boolean sameCheck = false;
+ Handler mHandler = new Handler();
+
+ boolean invSelectEnable;
+ int invSelectFilterType = -1, invSelectFilterOption = -1;
+ double invSelectFilterThreshold1 = -1, invSelectFilterThreshold2 = -1;
+ long invSelectFilterCount = -1;
+
+ private SettingTask settingTask;
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ super.onCreateView(inflater, container, savedInstanceState, false);
+ return inflater.inflate(R.layout.fragment_filterrssi_content, container, false);
+ }
+
+ @Override
+ public void onActivityCreated(Bundle savedInstanceState) {
+ super.onActivityCreated(savedInstanceState);
+
+ checkBoxEnable = (CheckBox) getActivity().findViewById(R.id.filterRssiCheck);
+
+ spinnerFilterType = (Spinner) getActivity().findViewById(R.id.filterRssiFilterType);
+ ArrayAdapter filterTypeAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.filterType_options, R.layout.custom_spinner_layout);
+ filterTypeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+ spinnerFilterType.setAdapter(filterTypeAdapter);
+ spinnerFilterType.setEnabled(false);
+
+ spinnerFilterOption = (Spinner) getActivity().findViewById(R.id.filterRssiFilterOption);
+ ArrayAdapter filterOptionAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.filter_options1, R.layout.custom_spinner_layout);
+ filterOptionAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+ spinnerFilterOption.setAdapter(filterOptionAdapter);
+
+ String strUnit = MainActivity.csLibrary4A.getRssiDisplaySetting() > 0 ? "(dBm)" : "(dBuV)";
+ TextView textViewThreshold1 = (TextView) getActivity().findViewById(R.id.filterRssiThreshold1Label);
+ textViewThreshold1.setText(textViewThreshold1.getText().toString() + strUnit);
+ TextView textViewThreshold2 = (TextView) getActivity().findViewById(R.id.filterRssiThreshold2Label);
+ textViewThreshold2.setText(textViewThreshold2.getText().toString() + strUnit);
+
+ editTextFilterThreshold1 = (EditText) getActivity().findViewById(R.id.filterRssiThreshold1);
+ editTextFilterThreshold2 = (EditText) getActivity().findViewById(R.id.filterRssiThreshold2);
+ editTextFilterCount = (EditText) getActivity().findViewById(R.id.filterRssiCount);
+
+ button = (Button) getActivity().findViewById(R.id.filterRssiSaveButton);
+ button.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ boolean validValue = false;
+ if (MainActivity.csLibrary4A.isBleConnected() == false) {
+ Toast.makeText(MainActivity.mContext, R.string.toast_ble_not_connected, Toast.LENGTH_SHORT).show();
+ return;
+ } else if (MainActivity.csLibrary4A.isRfidFailure()) {
+ Toast.makeText(MainActivity.mContext, "Rfid is disabled", Toast.LENGTH_SHORT).show();
+ return;
+ } else {
+ boolean bValid = false;
+ try {
+ invSelectEnable = checkBoxEnable.isChecked();
+ invSelectFilterType = spinnerFilterType.getSelectedItemPosition();
+ invSelectFilterOption = spinnerFilterOption.getSelectedItemPosition();
+ invSelectFilterThreshold1 = Float.parseFloat(editTextFilterThreshold1.getText().toString());
+ if (MainActivity.csLibrary4A.getRssiDisplaySetting() > 0) invSelectFilterThreshold1 += MainActivity.csLibrary4A.dBuV_dBm_constant;
+ invSelectFilterThreshold2 = Float.parseFloat(editTextFilterThreshold2.getText().toString());
+ if (MainActivity.csLibrary4A.getRssiDisplaySetting() > 0) invSelectFilterThreshold2 += MainActivity.csLibrary4A.dBuV_dBm_constant;
+ invSelectFilterCount = Integer.parseInt(editTextFilterCount.getText().toString());
+ bValid = true;
+ } catch (Exception ex) {
+ Toast.makeText(MainActivity.mContext, R.string.toast_invalid_range, Toast.LENGTH_SHORT).show();
+ }
+ if (bValid) settingUpdate();
+ }
+ }
+ });
+
+ if (sameCheck == false) MainActivity.csLibrary4A.setSameCheck(false);
+ mHandler.post(updateRunnable);
+ }
+
+ @Override
+ public void onDestroy() {
+ if (settingTask != null) settingTask.cancel(true);
+ MainActivity.csLibrary4A.setSameCheck(true);
+ mHandler.removeCallbacks(updateRunnable);
+ super.onDestroy();
+ }
+
+ public SettingFilterRssiFragment() {
+ super("SettingFilterRssiFragment");
+ }
+
+ private final Runnable updateRunnable = new Runnable() {
+ @Override
+ public void run() {
+ int iValue;
+ long lValue;
+ String updating = null;
+
+ if (MainActivity.csLibrary4A.mrfidToWriteSize() != 0) updating = "waiting empty buffer";
+ else {
+ if (updating == null) {
+ boolean bValue = MainActivity.csLibrary4A.getRssiFilterEnable();
+ MainActivity.csLibrary4A.appendToLog("0 updateRunnable getSelectEnable = " + bValue);
+ checkBoxEnable.setChecked(bValue);
+ }
+ if (updating == null) {
+ int iValue1 = MainActivity.csLibrary4A.getRssiFilterType();
+ MainActivity.csLibrary4A.appendToLog("1 updateRunnable getSelectAction = " + iValue1);
+ if (iValue1 < 0) updating = "getting filter type";
+ else spinnerFilterType.setSelection(iValue1);
+ }
+ if (updating == null) {
+ int iValue1 = MainActivity.csLibrary4A.getRssiFilterOption();
+ MainActivity.csLibrary4A.appendToLog("2 updateRunnable getSelectAction = " + iValue1);
+ if (iValue1 < 0) updating = "getting filter option";
+ else spinnerFilterOption.setSelection(iValue1);
+ }
+ if (updating == null) {
+ double dValue = MainActivity.csLibrary4A.getRssiFilterThreshold1();
+ MainActivity.csLibrary4A.appendToLog(String.format("3 updateRunnable getRssiFilterThreshold1 = %f", dValue));
+ if (dValue < 0 && false) updating = "updating threshold 1";
+ else editTextFilterThreshold1.setText(String.format("%.1f", (MainActivity.csLibrary4A.getRssiDisplaySetting() > 0 ? dValue -= MainActivity.csLibrary4A.dBuV_dBm_constant : dValue)));
+ }
+ if (updating == null) {
+ double dValue = MainActivity.csLibrary4A.getRssiFilterThreshold2();
+ MainActivity.csLibrary4A.appendToLog(String.format("4 updateRunnable getRssiFilterThreshold2 = %f", dValue));
+ if (dValue < 0 && false) updating = "updating threshold 2";
+ else editTextFilterThreshold2.setText(String.format("%.1f", (MainActivity.csLibrary4A.getRssiDisplaySetting() > 0 ? dValue -= MainActivity.csLibrary4A.dBuV_dBm_constant : dValue)));
+ }
+ if (updating == null) {
+ long lValue1 = MainActivity.csLibrary4A.getRssiFilterCount();
+ MainActivity.csLibrary4A.appendToLog(String.format("5 updateRunnable getRssiFilterCount = %d", lValue1));
+ if (lValue1 < 0) updating = "updating count";
+ else editTextFilterCount.setText(String.valueOf(lValue1));
+ }
+ }
+ if (updating != null) {
+ mHandler.postDelayed(updateRunnable, 1000);
+ MainActivity.csLibrary4A.appendToLogView("Updating in " + updating);
+ }
+ }
+ };
+
+ void settingUpdate() {
+ boolean sameSetting = true;
+ String invalidRequest = null;
+
+ if (sameSetting == true && invalidRequest == null) {
+ if (MainActivity.csLibrary4A.getRssiFilterEnable() != invSelectEnable
+ || MainActivity.csLibrary4A.getRssiFilterType() != invSelectFilterType
+ || MainActivity.csLibrary4A.getRssiFilterOption() != invSelectFilterOption) {
+ sameSetting = false;
+ if (MainActivity.csLibrary4A.setRssiFilterConfig(invSelectEnable, invSelectFilterType, invSelectFilterOption) == false) invalidRequest = "setting filter type";
+ }
+ if (MainActivity.csLibrary4A.getRssiFilterThreshold1() != invSelectFilterThreshold1 || MainActivity.csLibrary4A.getRssiFilterThreshold2() != invSelectFilterThreshold2) {
+ sameSetting = false;
+ MainActivity.csLibrary4A.appendToLog(String.format("updateRunnable: getRssiFilterThreshold2 = %f, invSelectFilterThreshold2 = %f", MainActivity.csLibrary4A.getRssiFilterThreshold2(), invSelectFilterThreshold2));
+ invSelectFilterThreshold2 = 0;
+ if (MainActivity.csLibrary4A.setRssiFilterThreshold(invSelectFilterThreshold1, invSelectFilterThreshold2) == false) invalidRequest = "setting filter threshold";
+ }
+ if (MainActivity.csLibrary4A.getRssiFilterCount() != invSelectFilterCount) {
+ sameSetting = false;
+ MainActivity.csLibrary4A.appendToLog("rssiFilterCount = " + invSelectFilterCount);
+ if (MainActivity.csLibrary4A.setRssiFilterCount(invSelectFilterCount) == false) invalidRequest = "setting filter count";
+ }
+ }
+
+ if (invalidRequest != null) {
+ String strValue = "Invalid " + invalidRequest + ". Operation is cancelled.";
+ Toast.makeText(MainActivity.mContext, strValue, Toast.LENGTH_SHORT).show();
+
+ } else {
+ settingTask = new SettingTask(button, sameSetting, false);
+ settingTask.execute();
+ MainActivity.csLibrary4A.saveSetting2File();
+ }
+ }
+}
+
+
+
+package com.csl.cs710ademoapp.fragments;
+
+import android.os.Bundle;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+
+import androidx.appcompat.app.ActionBar;
+import androidx.appcompat.app.AppCompatActivity;
+import androidx.fragment.app.Fragment;
+import androidx.fragment.app.FragmentManager;
+import androidx.fragment.app.FragmentStatePagerAdapter;
+import androidx.viewpager.widget.PagerAdapter;
+import androidx.viewpager.widget.ViewPager;
+
+import com.csl.cs710ademoapp.MainActivity;
+import com.csl.cslibrary4a.AdapterTab;
+import com.csl.cs710ademoapp.R;
+import com.google.android.material.tabs.TabLayout;
+
+public class SettingFragment extends CommonFragment {
+ private ActionBar actionBar;
+ private ViewPager viewPager;
+ FragmentStatePagerAdapter pagerAdapter;
+ AdapterTab adapter;
+ Fragment fragment0, fragment1;
+
+ private String[] tabs = { "Operation", "Administration" };
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ super.onCreateView(inflater, container, savedInstanceState, true);
+ return inflater.inflate(R.layout.custom_tabbed_layout, container, false);
+ }
+
+ @Override
+ public void onActivityCreated(Bundle savedInstanceState) {
+ super.onActivityCreated(savedInstanceState);
+
+ actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
+ actionBar.setTitle(R.string.title_activity_settings);
+
+ TabLayout tabLayout = (TabLayout) getActivity().findViewById(R.id.OperationsTabLayout);
+ FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
+ pagerAdapter = new FragmentStatePagerAdapter(getActivity().getSupportFragmentManager()) {
+ @Override
+ public int getCount() {
+ return tabs.length;
+ }
+ @Override
+ public int getItemPosition(Object object) {
+ return PagerAdapter.POSITION_NONE;
+ }
+ @Override
+ public Fragment getItem(int position) {
+ Fragment fragment = null;
+ switch (position) {
+ case 0:
+ fragment = new SettingOperateFragment(); //AccessSecurityLockFragment(); //InventoryRfidiMultiFragment();
+ fragment0 = fragment;
+ break;
+ case 1:
+ fragment1 = new SettingAdminFragment();
+ break;
+ default:
+ fragment = null;
+ break;
+ }
+ return fragment;
+ }
+ };
+ adapter = new AdapterTab(getActivity().getSupportFragmentManager(), tabs.length);
+ adapter.setFragment(0, new SettingOperateFragment());
+ adapter.setFragment(1, new SettingAdminFragment());
+
+ viewPager = (ViewPager) getActivity().findViewById(R.id.OperationsPager);
+ viewPager.setAdapter(adapter); //pagerAdapter); //mAdapter);
+ viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
+
+ for (String tab_name : tabs) {
+ tabLayout.addTab(tabLayout.newTab().setText(tab_name));
+ }
+
+ tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
+ @Override
+ public void onTabSelected(TabLayout.Tab tab) {
+ viewPager.setCurrentItem(tab.getPosition());
+ }
+
+ @Override
+ public void onTabUnselected(TabLayout.Tab tab) {
+ }
+
+ @Override
+ public void onTabReselected(TabLayout.Tab tab) {
+ }
+ });
+ }
+
+ @Override
+ public void onPause() {
+ adapter.fragment0.onPause();
+ adapter.fragment1.onPause();
+ super.onPause();
+ }
+
+ @Override
+ public void onStop() {
+ adapter.fragment0.onStop();
+ adapter.fragment1.onStop();
+ MainActivity.csLibrary4A.setAntennaSelect(0);
+ super.onStop();
+ }
+
+ @Override
+ public void onDestroyView() {
+ adapter.fragment0.onDestroyView();
+ adapter.fragment1.onDestroyView();
+ super.onDestroyView();
+ }
+
+ @Override
+ public void onDestroy() {
+ adapter.fragment0.onDestroy();
+ adapter.fragment1.onDestroy();
+ super.onDestroy();
+ }
+
+ @Override
+ public void onDetach() {
+ adapter.fragment0.onDetach();
+ adapter.fragment1.onDetach();
+ super.onDetach();
+ }
+
+ public SettingFragment() {
+ super("SettingFragment");
+ }
+}
+
+
+
+package com.csl.cs710ademoapp.fragments;
+
+import android.os.Bundle;
+import android.os.Handler;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.ArrayAdapter;
+import android.widget.Button;
+import android.widget.CheckBox;
+import android.widget.CompoundButton;
+import android.widget.EditText;
+import android.widget.LinearLayout;
+import android.widget.Spinner;
+import android.widget.TableRow;
+import android.widget.TextView;
+import android.widget.Toast;
+
+import com.csl.cs710ademoapp.CustomPopupWindow;
+import com.csl.cs710ademoapp.MainActivity;
+import com.csl.cs710ademoapp.R;
+import com.csl.cs710ademoapp.SettingTask;
+
+public class SettingOperateFragment extends CommonFragment {
+ final String strOVERRIDE = "Override"; final String strRESET = "Reset";
+ private CheckBox checkBoxPortEnable, checkBoxTagFocus, checkBoxFastId, checkBoxHighCompression;
+ private Spinner spinnerRegulatoryRegion, spinnerFrequencyOrder, spinnerChannel, spinnerQueryTarget, spinnerQuerySession, spinnerInvAlgo, spinnerProfile, spinnerRflnaGain, spinnerIflnaGain, spinnerAgcGain;
+ private EditText editTextPopulation, editTextStartQValue, editTextOperatePower, editTextPortDwell, editTextTagDelay, editTextIntraPkDelay, editTextDupDelay, editTextRetry;
+ private TextView textViewPortChannel;
+ private Button buttonPortSelect, buttonOverride, button, button1;
+ private TextView textViewEnvironmentalRSSI;
+
+ boolean sameCheck = true;
+ Handler mHandler = new Handler();
+ class SettingBeforeTagFocus {
+ int querySession;
+ int queryTarget;
+ String dwell;
+ String tagDelay;//, intraPkDelay, dupDelay;
+ void store() {
+ querySession = spinnerQuerySession.getSelectedItemPosition(); spinnerQuerySession.setSelection(1); spinnerQuerySession.setEnabled(false);
+ queryTarget = spinnerQueryTarget.getSelectedItemPosition(); spinnerQueryTarget.setSelection(0); spinnerQueryTarget.setEnabled(false);
+ dwell = editTextPortDwell.getText().toString(); editTextPortDwell.setText("2000"); editTextPortDwell.setEnabled(false);
+ tagDelay = editTextTagDelay.getText().toString(); editTextTagDelay.setText("0"); editTextTagDelay.setEnabled(false);
+ //intraPkDelay = editTextIntraPkDelay.getText().toString(); editTextIntraPkDelay.setText("0"); editTextIntraPkDelay.setEnabled(false);
+ //dupDelay = editTextDupDelay.getText().toString(); editTextDupDelay.setText("0"); editTextDupDelay.setEnabled(false);
+ }
+ void restore() {
+ spinnerQuerySession.setSelection(querySession); spinnerQuerySession.setEnabled(true);
+ spinnerQueryTarget.setSelection(queryTarget); spinnerQueryTarget.setEnabled(true);
+ editTextPortDwell.setText(dwell); editTextPortDwell.setEnabled(true);
+ editTextTagDelay.setText(tagDelay); editTextTagDelay.setEnabled(true);
+ //editTextIntraPkDelay.setText(intraPkDelay); editTextIntraPkDelay.setEnabled(true);
+ //editTextDupDelay.setText(dupDelay); editTextDupDelay.setEnabled(true);
+ }
+ };
+ SettingBeforeTagFocus settingBeforeTagFocus = new SettingBeforeTagFocus();
+
+ boolean overriding = false;
+ int countrySelect = -1;
+ int channelOrder = -1; int channelSelect = -1;
+ int channel = -1; final int channelMin = 1; int channelMax = 1; int iPortNumber = 1;
+ boolean portEnable = false;
+ long powerLevel = -1; final long powerLevelMin = 0; final long powerLevelMax = 300;
+ long dwellTime = -1; final long dwellTimeMin = 0; final long dwellTimeMax = 10000;
+ byte byteTagDelay = -1; byte byteTagDelayMin = 0; byte byteTagDelayMax = 63;
+ byte byteIntraPkDelay = -1; byte byteIntraPkDelayMin = 0; byte byteIntraPkDelayMax = 63;
+ byte byteDupDelay = -1; byte byteDupDelayMin = 0; byte byteDupDelayMax = 63;
+ int iPopulation = -1; int iPopulationMin = 1; int iPopulationMax = 9999;
+ byte byteFixedQValue = -1; byte byteFixedQValueMin = 0; byte byteFixedQValueMax = 15;
+ int queryTarget;
+ int querySession = -1;
+ int tagFocus = -1, fastId = -1;
+ boolean invAlgoDynamic = false;
+ int retry = -1;
+ int profile = -1;
+ int highCompression = -1, rflnagain = -1, iflnagain = -1, agcgain = -1;
+
+ private SettingTask settingTask;
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ super.onCreateView(inflater, container, savedInstanceState, false);
+ return inflater.inflate(R.layout.fragment_settings_operate, container, false);
+ }
+
+ @Override
+ public void onActivityCreated(Bundle savedInstanceState) {
+ super.onActivityCreated(savedInstanceState);
+
+ if (MainActivity.csLibrary4A.get98XX() == 2) {
+ TableRow tableRow = (TableRow) getActivity().findViewById(R.id.settingOperateCompactDelayRow);
+ tableRow.setVisibility(View.GONE);
+ LinearLayout linearLayout = (LinearLayout) getActivity().findViewById(R.id.settingOperateGainControl);
+ linearLayout.setVisibility(View.GONE);
+ } else {
+ TableRow tableRow = (TableRow) getActivity().findViewById(R.id.settingOperateDupDelayRow);
+ tableRow.setVisibility(View.GONE);
+ TableRow tableRow1 = (TableRow) getActivity().findViewById(R.id.settingOperateIntraPkDelayRow);
+ tableRow1.setVisibility(View.GONE);
+ //TableRow tableRow2 = (TableRow) getActivity().findViewById(R.id.settingOperatePortWarningRow);
+ //tableRow2.setVisibility(View.GONE);
+ }
+
+ spinnerRegulatoryRegion = (Spinner) getActivity().findViewById(R.id.settingOperateRegulatoryRegion);
+ spinnerFrequencyOrder = (Spinner) getActivity().findViewById(R.id.settingOperateFrequencyOrder); spinnerFrequencyOrder.setEnabled(false);
+ spinnerChannel = (Spinner) getActivity().findViewById(R.id.settingOperateChannel);
+
+ iPortNumber = MainActivity.csLibrary4A.getPortNumber();
+ if (iPortNumber == 1 && false) {
+ TableRow tableRow = (TableRow) getActivity().findViewById(R.id.settingOperatePortChannelRow);
+ tableRow.setVisibility(View.GONE);
+ tableRow = (TableRow) getActivity().findViewById(R.id.settingOperatePortEnableRow);
+ tableRow.setVisibility(View.GONE);
+ tableRow = (TableRow) getActivity().findViewById(R.id.settingOperatePortDwellRow);
+ tableRow.setVisibility(View.GONE);
+ } else {
+ int iTemp = iPortNumber;
+ if (iTemp > 1) channelMax = iTemp;
+ else channelMax = 16;
+ if (channelMax != 1) {
+ TextView textViewPortChannelLabel = (TextView) getActivity().findViewById(R.id.settingOperatePortChannelLabel);
+ if (iPortNumber != 1) textViewPortChannelLabel.setText("Ant port #");
+ else textViewPortChannelLabel.setText("Power level");
+ String stringPortChannelLabel = textViewPortChannelLabel.getText().toString();
+ stringPortChannelLabel += "(" + String.valueOf(channelMin) + "-" + String.valueOf(channelMax) + ")";
+ textViewPortChannelLabel.setText(stringPortChannelLabel);
+ }
+ textViewPortChannel = (TextView) getActivity().findViewById(R.id.settingOperatePortChannel); textViewPortChannel.setText("1");
+ buttonPortSelect = (Button) getActivity().findViewById(R.id.settingOperatePortChannelSelect);
+ if (false && MainActivity.csLibrary4A.get98XX() == 2) buttonPortSelect.setEnabled(false);
+ buttonPortSelect.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ int channel = Integer.parseInt(textViewPortChannel.getText().toString());
+ if (channel < 1) channel = channelMin;
+ if (++channel > channelMax) channel = channelMin;
+ textViewPortChannel.setText(""); if (MainActivity.csLibrary4A.setAntennaSelect(channel-1)) textViewPortChannel.setText(String.valueOf(channel));
+ editTextOperatePower.setText("");
+ editTextPortDwell.setText("");
+ mHandler.post(updateRunnable);
+ }
+ });
+
+ checkBoxPortEnable = (CheckBox) getActivity().findViewById(R.id.settingOperatePortEnable);
+
+ TextView textViewPortDwellLabel = (TextView) getActivity().findViewById(R.id.settingOperatePortDwellLabel);
+ String stringPortDwellLabel = textViewPortDwellLabel.getText().toString();
+ stringPortDwellLabel += "(" + String.valueOf(dwellTimeMin) + "-" + String.valueOf(dwellTimeMax) + ")";
+ textViewPortDwellLabel.setText(stringPortDwellLabel);
+ editTextPortDwell = (EditText) getActivity().findViewById(R.id.settingOperatePortDwell);
+ }
+
+ TextView textViewAdminTagDelayLabel = (TextView) getActivity().findViewById(R.id.settingAdminTagDelayLabel);
+ String stringAdminTagDelayLabel = textViewAdminTagDelayLabel.getText().toString();
+ stringAdminTagDelayLabel += "(" + String.valueOf(byteTagDelayMin) + "-" + String.valueOf(byteTagDelayMax) + "ms)";
+ textViewAdminTagDelayLabel.setText(stringAdminTagDelayLabel);
+ editTextTagDelay = (EditText) getActivity().findViewById(R.id.settingOperateTagDelay);
+ editTextIntraPkDelay = (EditText) getActivity().findViewById(R.id.settingOperateIntraPkDelay);
+ editTextDupDelay = (EditText) getActivity().findViewById(R.id.settingOperateDupDelay);
+
+ TextView textViewOperatePowerLabel = (TextView) getActivity().findViewById(R.id.settingOperatePowerLabel);
+ String stringOperationPowerLabel = textViewOperatePowerLabel.getText().toString();
+ stringOperationPowerLabel += "(" + String.valueOf(powerLevelMin) + "-" + String.valueOf(powerLevelMax) + ")";
+ textViewOperatePowerLabel.setText(stringOperationPowerLabel);
+ editTextOperatePower = (EditText) getActivity().findViewById(R.id.settingOperatePower);
+
+ TextView textViewOperatePopulationLabel = (TextView) getActivity().findViewById(R.id.settingOperatePopulationLabel);
+ String stringOperationPopulationLabel = textViewOperatePopulationLabel.getText().toString();
+ stringOperationPopulationLabel += "(" + String.valueOf(iPopulationMin) + "-" + String.valueOf(iPopulationMax) + ")";
+ textViewOperatePopulationLabel.setText(stringOperationPopulationLabel);
+ editTextPopulation = (EditText) getActivity().findViewById(R.id.settingOperatePopulation);
+
+ editTextStartQValue = (EditText) getActivity().findViewById(R.id.settingOperateQValue);
+
+ spinnerQueryTarget = (Spinner) getActivity().findViewById(R.id.settingOperateTarget);
+ ArrayAdapter targetAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.query_target_options, R.layout.custom_spinner_layout);
+ targetAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+ spinnerQueryTarget.setAdapter(targetAdapter);
+
+ spinnerQuerySession = (Spinner) getActivity().findViewById(R.id.settingOperateSession);
+ targetAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.query_session_options, R.layout.custom_spinner_layout);
+ targetAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+ spinnerQuerySession.setAdapter(targetAdapter);
+
+ checkBoxTagFocus = (CheckBox) getActivity().findViewById(R.id.settingOperateTagFocus);
+ String string = checkBoxTagFocus.getText().toString();
+ if (MainActivity.csLibrary4A.get98XX() == 2) checkBoxTagFocus.setText(string.substring(0, string.length()-1) + ". When enabled, tag select is disabled.)");
+ checkBoxTagFocus.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
+ @Override
+ public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
+ if (isChecked) settingBeforeTagFocus.store();
+ else settingBeforeTagFocus.restore();
+ }
+ });
+
+ checkBoxFastId = (CheckBox) getActivity().findViewById(R.id.settingOperateFastId);
+
+ spinnerInvAlgo = (Spinner) getActivity().findViewById(R.id.settingOperateAlgorithmToUse);
+ targetAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.inventory_algorithm_options, R.layout.custom_spinner_layout);
+ targetAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+ spinnerInvAlgo.setAdapter(targetAdapter);
+
+ TextView textViewRetry = (TextView) getActivity().findViewById(R.id.settingOperateRetryLabel);
+ if (MainActivity.csLibrary4A.get98XX() == 2) textViewRetry.setText("Minimum minQ cycles");
+ editTextRetry = (EditText) getActivity().findViewById(R.id.settingOperateRetry);
+
+ spinnerProfile = (Spinner) getActivity().findViewById(R.id.settingOperateProfile);
+ if (true) {
+ ArrayAdapter targetAdapter1 = new ArrayAdapter(getContext(), android.R.layout.simple_spinner_dropdown_item, MainActivity.csLibrary4A.getProfileList());
+ targetAdapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+ spinnerProfile.setAdapter(targetAdapter1);
+ }
+
+ MainActivity.csLibrary4A.resetEnvironmentalRSSI();
+ textViewEnvironmentalRSSI = (TextView) getActivity().findViewById(R.id.settingOperateEnvironmentalRSSI);
+ checkBoxHighCompression = (CheckBox) getActivity().findViewById(R.id.settingOperateHighCompression);
+
+ spinnerRflnaGain = (Spinner) getActivity().findViewById(R.id.settingOperateRflnaGain);
+ targetAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.rflnagain_options, R.layout.custom_spinner_layout);
+ targetAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+ spinnerRflnaGain.setAdapter(targetAdapter);
+
+ spinnerIflnaGain = (Spinner) getActivity().findViewById(R.id.settingOperateIflnaGain);
+ targetAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.iflnagain_options, R.layout.custom_spinner_layout);
+ targetAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+ spinnerIflnaGain.setAdapter(targetAdapter);
+
+ spinnerAgcGain = (Spinner) getActivity().findViewById(R.id.settingOperateAgcGAin);
+ targetAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.agcgain_options, R.layout.custom_spinner_layout);
+ targetAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+ spinnerAgcGain.setAdapter(targetAdapter);
+
+ buttonOverride = (Button) getActivity().findViewById(R.id.settingOperateOverrideButton);
+ String strText = buttonOverride.getText().toString();
+ if (strText.contains(strOVERRIDE)) {
+ editTextPopulation.setEnabled(true);
+ editTextStartQValue.setEnabled(false);
+ } else {
+ editTextPopulation.setEnabled(false);
+ editTextStartQValue.setEnabled(true);
+ }
+ buttonOverride.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ String strText = buttonOverride.getText().toString();
+ if (strText.contains(strOVERRIDE)) {
+ editTextPopulation.setEnabled(false);
+ editTextStartQValue.setEnabled(true);
+ buttonOverride.setText(strRESET); overriding = true;
+ } else {
+ editTextPopulation.setEnabled(true);
+ editTextStartQValue.setEnabled(false);;
+ buttonOverride.setText(strOVERRIDE); overriding = false;
+
+ iPopulation = Integer.parseInt(editTextPopulation.getText().toString());
+ editTextStartQValue.setText(String.valueOf(MainActivity.csLibrary4A.getPopulation2Q(iPopulation)));
+ }
+ }
+ });
+
+ button = (Button) getActivity().findViewById(R.id.settingSaveButtonOperate);
+ button.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ sameCheck = true; settingUpdate1();
+ }
+ });
+
+ button1 = (Button) getActivity().findViewById(R.id.settingSaveButtonOperate1);
+ button1.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ sameCheck = false; settingUpdate1();
+ }
+ });
+
+ mHandler.post(updateRunnable);
+ }
+
+ void settingUpdate1() {
+ if (MainActivity.csLibrary4A.isBleConnected() == false) {
+ Toast.makeText(MainActivity.mContext, R.string.toast_ble_not_connected, Toast.LENGTH_SHORT).show();
+ return;
+ } else if (MainActivity.csLibrary4A.isRfidFailure()) {
+ Toast.makeText(MainActivity.mContext, "Rfid is disabled", Toast.LENGTH_SHORT).show();
+ return;
+ } else if (updateRunning) {
+ Toast.makeText(MainActivity.mContext, R.string.toast_not_ready, Toast.LENGTH_SHORT).show();
+ return;
+ } else {
+ MainActivity.csLibrary4A.setSameCheck(sameCheck);
+ try {
+ countrySelect = spinnerRegulatoryRegion.getSelectedItemPosition();
+ channelOrder = spinnerFrequencyOrder.getSelectedItemPosition();
+ channelSelect = spinnerChannel.getSelectedItemPosition();
+ if (textViewPortChannel != null)
+ channel = Integer.parseInt(textViewPortChannel.getText().toString());
+ if (checkBoxPortEnable != null) portEnable = checkBoxPortEnable.isChecked();
+ powerLevel = Long.parseLong(editTextOperatePower.getText().toString());
+ if (editTextPortDwell != null)
+ dwellTime = Long.parseLong(editTextPortDwell.getText().toString());
+ if (editTextTagDelay != null)
+ byteTagDelay = Byte.parseByte(editTextTagDelay.getText().toString());
+ if (editTextIntraPkDelay != null)
+ byteIntraPkDelay = Byte.parseByte(editTextIntraPkDelay.getText().toString());
+ if (editTextDupDelay != null)
+ byteDupDelay = Byte.parseByte(editTextDupDelay.getText().toString());
+ iPopulation = Integer.parseInt(editTextPopulation.getText().toString());
+ byteFixedQValue = Byte.parseByte(editTextStartQValue.getText().toString());
+ queryTarget = spinnerQueryTarget.getSelectedItemPosition();
+ querySession = spinnerQuerySession.getSelectedItemPosition();
+ tagFocus = (checkBoxTagFocus.isChecked() ? 1 : 0);
+ fastId = (checkBoxFastId.isChecked() ? 1 : 0);
+ invAlgoDynamic = (spinnerInvAlgo.getSelectedItemPosition() == 0 ? true : false);
+ retry = Integer.parseInt(editTextRetry.getText().toString());
+ profile = spinnerProfile.getSelectedItemPosition();
+ highCompression = (checkBoxHighCompression.isChecked() ? 1 : 0);
+ rflnagain = spinnerRflnaGain.getSelectedItemPosition();
+ iflnagain = spinnerIflnaGain.getSelectedItemPosition();
+ agcgain = spinnerAgcGain.getSelectedItemPosition();
+ settingUpdate();
+ } catch (Exception ex) {
+ Toast.makeText(MainActivity.mContext, R.string.toast_invalid_range, Toast.LENGTH_SHORT).show();
+ }
+ }
+ }
+
+ @Override
+ public void onDestroy() {
+ if (settingTask != null) settingTask.cancel(true);
+ if (MainActivity.csLibrary4A != null) MainActivity.csLibrary4A.setSameCheck(true);
+ mHandler.removeCallbacks(updateRunnable);
+ super.onDestroy();
+ }
+
+ boolean userVisibleHint = true;
+ @Override
+ public void setUserVisibleHint(boolean isVisibleToUser) {
+ MainActivity.csLibrary4A.appendToLog("isVisibleToUser = " + isVisibleToUser);
+ super.setUserVisibleHint(isVisibleToUser);
+ if(getUserVisibleHint()) {
+ if (userVisibleHint == false) {
+ userVisibleHint = true;
+ mHandler.post(updateRunnable);
+ }
+ } else {
+ userVisibleHint = false;
+ }
+ }
+
+ public SettingOperateFragment() {
+ super("SettingOperateFragment");
+ }
+
+ boolean updateRunning = false;
+ private final Runnable updateRunnable = new Runnable() {
+ @Override
+ public void run() {
+ int iValue;
+ long lValue;
+ boolean updating = false;
+
+ updateRunning = true;
+ if (MainActivity.csLibrary4A.mrfidToWriteSize() != 0) {
+ updating = true; MainActivity.csLibrary4A.appendToLog("updating 1");
+ }
+ else {
+ iPopulation = MainActivity.csLibrary4A.getPopulation();
+ if (iPopulation < 0) {
+ updating = true; MainActivity.csLibrary4A.appendToLog("updating 2");
+ }
+ else {
+ editTextPopulation.setText(String.valueOf(iPopulation));
+
+ byteFixedQValue = MainActivity.csLibrary4A.getQValue();
+ editTextStartQValue.setText(String.valueOf(byteFixedQValue));
+ if (MainActivity.csLibrary4A.getPopulation2Q(iPopulation) != byteFixedQValue) {
+ buttonOverride.setText(strRESET); overriding = true;
+ } else {
+ buttonOverride.setText(strOVERRIDE); overriding = false;
+ }
+ }
+ if (updating == false && textViewPortChannel != null) {
+ lValue = MainActivity.csLibrary4A.getAntennaSelect();
+ if (lValue < 0) {
+ updating = true; MainActivity.csLibrary4A.appendToLog("updating 4");
+ } else {
+ textViewPortChannel.setText(String.valueOf(lValue+1));
+ }
+ }
+ if (checkBoxPortEnable != null) checkBoxPortEnable.setChecked(MainActivity.csLibrary4A.getAntennaEnable());
+ if (updating == false) {
+ lValue = MainActivity.csLibrary4A.getPwrlevel();
+ if (lValue < 0) {
+ updating = true; MainActivity.csLibrary4A.appendToLog("updating 5");
+ } else {
+ editTextOperatePower.setText(String.valueOf(lValue));
+ }
+ }
+ if (updating == false && editTextPortDwell != null) {
+ lValue = MainActivity.csLibrary4A.getAntennaDwell();
+ if (lValue < 0) {
+ updating = true; MainActivity.csLibrary4A.appendToLog("updating 6");
+ } else {
+ editTextPortDwell.setText(String.valueOf(lValue));
+ }
+ }
+ if (editTextTagDelay != null) editTextTagDelay.setText(String.valueOf(MainActivity.csLibrary4A.getTagDelay()));
+ if (editTextIntraPkDelay != null) editTextIntraPkDelay.setText(String.valueOf(MainActivity.csLibrary4A.getIntraPkDelay()));
+ if (editTextDupDelay != null) editTextDupDelay.setText(String.valueOf(MainActivity.csLibrary4A.getDupDelay()));
+ if (updating == false) {
+ spinnerQueryTarget.setSelection(MainActivity.csLibrary4A.getQueryTarget());
+ }
+ if (updating == false) {
+ iValue = MainActivity.csLibrary4A.getQuerySession();
+ if (iValue < 0) {
+ updating = true; MainActivity.csLibrary4A.appendToLog("updating 7");
+ } else {
+ spinnerQuerySession.setSelection(iValue);
+ }
+ }
+ if (updating == false) {
+ iValue = MainActivity.csLibrary4A.getTagFocus();
+ if (iValue < 0) {
+ updating = true; MainActivity.csLibrary4A.appendToLog("updating 8");
+ }
+ else {
+ checkBoxTagFocus.setChecked(iValue > 0 ? true : false);
+ if (checkBoxTagFocus.isChecked()) settingBeforeTagFocus.store();
+ }
+ }
+ if (updating == false) {
+ iValue = MainActivity.csLibrary4A.getFastId();
+ if (iValue < 0) {
+ updating = true; MainActivity.csLibrary4A.appendToLog("updating 8");
+ }
+ else checkBoxFastId.setChecked(iValue > 0 ? true : false);
+ }
+ if (updating == false) {
+ spinnerInvAlgo.setSelection(MainActivity.csLibrary4A.getInvAlgo() ? 0 : 1);
+ }
+ if (updating == false) {
+ int iRetry = MainActivity.csLibrary4A.getRetryCount();
+ if (iRetry < 0) {
+ updating = true; MainActivity.csLibrary4A.appendToLog("updating 9");
+ }
+ else editTextRetry.setText(String.valueOf(iRetry));
+ }
+ if (updating == false) {
+ String[] strCountryList = MainActivity.csLibrary4A.getCountryList();
+ for (int i = 0; i < strCountryList.length; i++) MainActivity.csLibrary4A.appendToLog("updating: String " + i + " = " + strCountryList[i]);
+ String[] strChannelFrequencyList = MainActivity.csLibrary4A.getChannelFrequencyList();
+ //for (int i = 0; i < strChannelFrequencyList.length; i++) MainActivity.csLibrary4A.appendToLog("updating: String " + i + " = " + strChannelFrequencyList[i]);
+ if (strCountryList == null) {
+ updating = true; MainActivity.csLibrary4A.appendToLog("updating 10");
+ } else {
+ ArrayAdapter targetAdapter1 = new ArrayAdapter(getActivity(), R.layout.custom_spinner_layout, strCountryList);
+ targetAdapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+ spinnerRegulatoryRegion.setAdapter(targetAdapter1);
+ int countryNumber = MainActivity.csLibrary4A.getCountryNumberInList();
+ MainActivity.csLibrary4A.appendToLog("updating countryNumber = " + countryNumber);
+ if (countryNumber < 0 || countryNumber > strCountryList.length) spinnerRegulatoryRegion.setSelection(0);
+ else spinnerRegulatoryRegion.setSelection(countryNumber);
+ if (strCountryList.length == 1) spinnerRegulatoryRegion.setEnabled(false);
+ else spinnerRegulatoryRegion.setEnabled(true);
+
+ ArrayAdapter targetAdapter;
+ //if (MainActivity.csLibrary4A.getChannelHoppingDefault())
+ targetAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.frequencyOrder_options, R.layout.custom_spinner_layout);
+ //else targetAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.frequencyAgile_options, R.layout.custom_spinner_layout);
+ targetAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+ spinnerFrequencyOrder.setAdapter(targetAdapter);
+ spinnerFrequencyOrder.setSelection(MainActivity.csLibrary4A.getChannelHoppingStatus() ? 0 : 1);
+ if (MainActivity.csLibrary4A.getChannelHoppingStatus()) spinnerChannel.setEnabled(false);
+ else spinnerChannel.setEnabled(true);
+
+ ArrayAdapter targetAdapter2 = new ArrayAdapter(getActivity(), R.layout.custom_spinner_layout, strChannelFrequencyList);
+ targetAdapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+ spinnerChannel.setAdapter(targetAdapter2);
+ int channel = MainActivity.csLibrary4A.getChannel();
+ MainActivity.csLibrary4A.appendToLog("channel = " + channel);
+ if (channel < 0 || channel > strChannelFrequencyList.length) spinnerChannel.setSelection(0);
+ else spinnerChannel.setSelection(channel);
+ }
+ }
+ }
+ if (updating == false) {
+ iValue = MainActivity.csLibrary4A.getCurrentProfile();
+ if (iValue < 0) {
+ updating = true; MainActivity.csLibrary4A.appendToLog("updating 11");
+ } else {
+ spinnerProfile.setSelection(iValue);
+ }
+ }
+ if (updating == false) {
+ String strRssi = MainActivity.csLibrary4A.getEnvironmentalRSSI();
+ if (strRssi == null) {
+ updating = true; MainActivity.csLibrary4A.appendToLog("updating 12");
+ }
+ else textViewEnvironmentalRSSI.setText(strRssi);
+ }
+ if (updating == false) {
+ iValue = MainActivity.csLibrary4A.getHighCompression();
+ if (iValue < 0) {
+ updating = true; MainActivity.csLibrary4A.appendToLog("updating 13");
+ } else checkBoxHighCompression.setChecked(iValue == 0 ? false : true);
+ }
+ if (updating == false) {
+ iValue = MainActivity.csLibrary4A.getRflnaGain();
+ if (iValue < 0) {
+ updating = true; MainActivity.csLibrary4A.appendToLog("updating 14");
+ } else {
+ switch (iValue) {
+ case 2:
+ iValue = 1;
+ break;
+ case 3:
+ iValue = 2;
+ break;
+ case 0:
+ default:
+ iValue = 0;
+ break;
+ }
+ spinnerRflnaGain.setSelection(iValue);
+ }
+ }
+ if (updating == false) {
+ iValue = MainActivity.csLibrary4A.getIflnaGain();
+ if (iValue < 0) {
+ updating = true; MainActivity.csLibrary4A.appendToLog("updating 15");
+ } else {
+ switch (iValue) {
+ case 1:
+ iValue = 1;
+ break;
+ case 3:
+ iValue = 2;
+ break;
+ case 7:
+ iValue = 3;
+ break;
+ case 0:
+ default:
+ iValue = 0;
+ break;
+ }
+ spinnerIflnaGain.setSelection(iValue);
+ }
+ }
+ if (updating == false) {
+ iValue = MainActivity.csLibrary4A.getAgcGain();
+ if (iValue < 0) {
+ updating = true; MainActivity.csLibrary4A.appendToLog("updating 16");
+ } else {
+ switch (iValue) {
+ case 4:
+ iValue = 1;
+ break;
+ case 6:
+ iValue = 2;
+ break;
+ case 7:
+ iValue = 3;
+ break;
+ case 0:
+ default:
+ iValue = 0;
+ break;
+
+ }
+ spinnerAgcGain.setSelection(iValue);
+ }
+ }
+ if (updating) {
+ mHandler.postDelayed(updateRunnable, 500);
+ } else updateRunning = false;
+ }
+ };
+
+ void settingUpdate() {
+ boolean sameSetting = true;
+ boolean invalidRequest = false;
+ boolean changedChannel = false;
+
+ if (invalidRequest == false && (MainActivity.csLibrary4A.getCountryNumberInList() != countrySelect || sameCheck == false)) {
+ sameSetting = false; MainActivity.csLibrary4A.appendToLog("point 1");
+ if (MainActivity.csLibrary4A.setCountryInList(countrySelect) == false) invalidRequest = true;
+ }
+ if (invalidRequest == false && (MainActivity.csLibrary4A.getChannelHoppingStatus() != (channelOrder == 0 ? true : false) || sameCheck == false)) {
+ sameSetting = false; MainActivity.csLibrary4A.appendToLog("point 2");
+ if (MainActivity.csLibrary4A.setChannelHoppingStatus(channelOrder == 0 ? true : false) == false) invalidRequest = true;
+ else if (channelOrder > 0) spinnerChannel.setEnabled(true);
+ else spinnerChannel.setEnabled(false);
+ spinnerChannel.setSelection(MainActivity.csLibrary4A.getChannel()); MainActivity.csLibrary4A.appendToLog("1 channel = ");
+ }
+ if (invalidRequest == false && (MainActivity.csLibrary4A.getChannel() != channelSelect || sameCheck == false)) {
+ sameSetting = false; MainActivity.csLibrary4A.appendToLog("point 3");
+ if (channelSelect < MainActivity.csLibrary4A.FreqChnCnt()) {
+ if (MainActivity.csLibrary4A.setChannel(channelSelect) == false) invalidRequest = true;
+ } else {
+ invalidRequest = true;
+ }
+ }
+ if (false && invalidRequest == false && (MainActivity.csLibrary4A.getAntennaSelect() + 1 != channel || sameCheck == false)) {
+ sameSetting = false; MainActivity.csLibrary4A.appendToLog("point 4");
+ if (channel < channelMin || channel > channelMax) invalidRequest = true;
+ else if (MainActivity.csLibrary4A.setAntennaSelect(channel - 1) == false) invalidRequest = true;
+ else changedChannel = true;
+ }
+ if (invalidRequest == false && (MainActivity.csLibrary4A.getAntennaEnable() != portEnable || sameCheck == false || changedChannel)) {
+ sameSetting = false; MainActivity.csLibrary4A.appendToLog("point 5");
+ if (MainActivity.csLibrary4A.setAntennaEnable(portEnable) == false)
+ invalidRequest = true;
+ }
+ if (invalidRequest == false && (MainActivity.csLibrary4A.getPwrlevel() != powerLevel || sameCheck == false)) {
+ sameSetting = false; MainActivity.csLibrary4A.appendToLog("point 6");
+ if (powerLevel < powerLevelMin) invalidRequest = true;
+ else if (powerLevel > MainActivity.powerLevelMax) {
+ CustomPopupWindow customPopupWindow = new CustomPopupWindow(MainActivity.mContext);
+ customPopupWindow.popupStart("Power can only be set to 320 or below", false);
+ invalidRequest = true;
+ }
+ else if (MainActivity.csLibrary4A.setPowerLevel(powerLevel) == false) invalidRequest = true;
+ }
+ if ((invalidRequest == false && (MainActivity.csLibrary4A.getAntennaDwell() != dwellTime || sameCheck == false || changedChannel))) {
+ sameSetting = false; MainActivity.csLibrary4A.appendToLog("point 7");
+ if (dwellTime < dwellTimeMin || dwellTime > dwellTimeMax) invalidRequest = true;
+ else if (MainActivity.csLibrary4A.setAntennaDwell(dwellTime) == false) invalidRequest = true;
+ }
+ if ((invalidRequest == false && editTextTagDelay != null)) {
+ if (MainActivity.csLibrary4A.getTagDelay() != byteTagDelay || sameCheck == false) {
+ sameSetting = false; MainActivity.csLibrary4A.appendToLog("point 8");
+ if (byteTagDelay < byteTagDelayMin || byteTagDelay > byteTagDelayMax) invalidRequest = true;
+ else if (MainActivity.csLibrary4A.setTagDelay(byteTagDelay) == false)
+ invalidRequest = true;
+ }
+ }
+ if ((invalidRequest == false && editTextIntraPkDelay != null)) {
+ if (MainActivity.csLibrary4A.getIntraPkDelay() != byteIntraPkDelay || sameCheck == false) {
+ sameSetting = false; MainActivity.csLibrary4A.appendToLog("point 9A");
+ if (byteDupDelay < byteIntraPkDelayMin || byteIntraPkDelay > byteIntraPkDelayMax) invalidRequest = true;
+ else if (MainActivity.csLibrary4A.setIntraPkDelay(byteIntraPkDelay) == false)
+ invalidRequest = true;
+ }
+ }
+ if ((invalidRequest == false && editTextDupDelay != null)) {
+ if (MainActivity.csLibrary4A.getDupDelay() != byteDupDelay || sameCheck == false) {
+ sameSetting = false; MainActivity.csLibrary4A.appendToLog("point 9");
+ if (byteDupDelay < byteDupDelayMin || byteDupDelay > byteDupDelayMax) invalidRequest = true;
+ else if (MainActivity.csLibrary4A.setDupDelay(byteDupDelay) == false)
+ invalidRequest = true;
+ }
+ }
+
+ if (overriding) {
+ if (MainActivity.csLibrary4A.getQValue() != byteFixedQValue || sameCheck == false) {
+ sameSetting = false; MainActivity.csLibrary4A.appendToLog("point 9");
+ if (byteFixedQValue < byteFixedQValueMin || byteFixedQValue > byteFixedQValueMax) invalidRequest = true;
+ if (MainActivity.csLibrary4A.setQValue(byteFixedQValue) == false)
+ invalidRequest = true;
+ }
+ } else {
+ if (invalidRequest == false && (MainActivity.csLibrary4A.getPopulation() != iPopulation || MainActivity.csLibrary4A.getQValue() != byteFixedQValue || sameCheck == false)) {
+ sameSetting = false; MainActivity.csLibrary4A.appendToLog("point 10");
+ if (iPopulation < iPopulationMin || iPopulation > iPopulationMax) invalidRequest = true;
+ else if (MainActivity.csLibrary4A.setPopulation(iPopulation) == false) {
+ invalidRequest = true;
+ } else {
+ editTextStartQValue.setText(String.valueOf(MainActivity.csLibrary4A.getPopulation2Q(iPopulation)));
+ }
+ }
+ }
+ if ((MainActivity.csLibrary4A.getQueryTarget() != queryTarget
+ || MainActivity.csLibrary4A.getQuerySession() != querySession || sameCheck == false)) {
+ sameSetting = false; MainActivity.csLibrary4A.appendToLog("point 11");
+ if (MainActivity.csLibrary4A.setTagGroup(MainActivity.csLibrary4A.getQuerySelect(), querySession, queryTarget) == false)
+ invalidRequest = true;
+ }
+ if (MainActivity.csLibrary4A.getTagFocus() != tagFocus || sameCheck == false) {
+ sameSetting = false; MainActivity.csLibrary4A.appendToLog("point 12");
+ if (MainActivity.csLibrary4A.setTagFocus(tagFocus > 0 ? true : false) == false)
+ invalidRequest = true;
+ }
+ if (MainActivity.csLibrary4A.getFastId() != fastId || sameCheck == false) {
+ sameSetting = false; MainActivity.csLibrary4A.appendToLog("point 12");
+ if (MainActivity.csLibrary4A.setFastId(fastId > 0 ? true : false) == false)
+ invalidRequest = true;
+ }
+ if (invalidRequest == false) {
+ if (MainActivity.csLibrary4A.getInvAlgo() != invAlgoDynamic || sameCheck == false) {
+ sameSetting = false; MainActivity.csLibrary4A.appendToLog("point 13");
+ if (MainActivity.csLibrary4A.setInvAlgo(invAlgoDynamic) == false)
+ invalidRequest = true;
+ spinnerQueryTarget.setSelection(MainActivity.csLibrary4A.getQueryTarget());
+ }
+ }
+ if (invalidRequest == false) {
+ if (MainActivity.csLibrary4A.getRetryCount() != retry || sameCheck == false) {
+ sameSetting = false; MainActivity.csLibrary4A.appendToLog("point 14");
+ if (MainActivity.csLibrary4A.setRetryCount(retry) == false)
+ invalidRequest = true;
+ }
+ }
+ if (invalidRequest == false) {
+ if (MainActivity.csLibrary4A.getCurrentProfile() != profile || sameCheck == false) {
+ sameSetting = false; MainActivity.csLibrary4A.appendToLog("point 15 with profile = " + profile);
+ if (MainActivity.csLibrary4A.setCurrentLinkProfile(profile) == false)
+ invalidRequest = true;
+ }
+ }
+ if (invalidRequest == false) {
+ switch(rflnagain) {
+ case 1:
+ rflnagain = 2;
+ break;
+ case 2:
+ rflnagain = 3;
+ break;
+ case 0:
+ default:
+ rflnagain = 0;
+ break;
+ }
+ switch(iflnagain) {
+ case 1:
+ iflnagain = 1;
+ break;
+ case 2:
+ iflnagain = 3;
+ break;
+ case 3:
+ iflnagain = 7;
+ break;
+ case 0:
+ default:
+ iflnagain = 0;
+ break;
+ }
+ switch(agcgain) {
+ case 1:
+ agcgain = 4;
+ break;
+ case 2:
+ agcgain = 6;
+ break;
+ case 3:
+ agcgain = 7;
+ break;
+ case 0:
+ default:
+ agcgain = 0;
+ break;
+ }
+ if ((MainActivity.csLibrary4A.getHighCompression() != highCompression)
+ || (MainActivity.csLibrary4A.getRflnaGain() != rflnagain)
+ || (MainActivity.csLibrary4A.getIflnaGain() != iflnagain)
+ || (MainActivity.csLibrary4A.getAgcGain() != agcgain)
+ || sameCheck == false) {
+ sameSetting = false;
+ if (MainActivity.csLibrary4A.setRxGain(highCompression, rflnagain, iflnagain, agcgain) == false)
+ invalidRequest = true;
+ }
+ }
+ settingTask = new SettingTask((sameCheck ? button: button1), sameSetting, invalidRequest);
+ settingTask.execute();
+ MainActivity.csLibrary4A.saveSetting2File();
+ mHandler.post(updateRunnable);
+ }
+}
+
+
+
+package com.csl.cs710ademoapp.fragments;
+
+import android.app.AlertDialog;
+import android.app.Dialog;
+import android.content.DialogInterface;
+import android.os.Bundle;
+import android.view.View;
+import android.widget.ArrayAdapter;
+import android.widget.EditText;
+import android.widget.Spinner;
+
+import androidx.fragment.app.DialogFragment;
+
+import com.csl.cs710ademoapp.MainActivity;
+import com.csl.cs710ademoapp.R;
+
+public class SettingWedgeFragment extends DialogFragment {
+ EditText editTextPower, editTextPrefix, editTextSuffix;
+ Spinner spinnerDelimiter, spinnerOutput;
+
+ @Override
+ public Dialog onCreateDialog(Bundle savedInstanceState) {
+ View view = getActivity().getLayoutInflater().inflate(R.layout.fragment_directwedge_settings, null);
+
+ AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
+ builder.setTitle("Wedge Settings");
+ //builder.setMessage("simple wedge setttings");
+ builder.setView(view);
+ builder.setPositiveButton("Save", new DialogInterface.OnClickListener() {
+ public void onClick(DialogInterface dialog, int whichButton) {
+ String wedgePower = editTextPower.getText().toString();
+ try {
+ int iWedgePower = Integer.parseInt(wedgePower);
+ if (iWedgePower < 0) iWedgePower = 0;
+ else if (iWedgePower > 300) iWedgePower = 300;
+ editTextPower.setText(String.valueOf(iWedgePower));
+ MainActivity.csLibrary4A.setWedgePower(iWedgePower);
+ } catch (Exception ex) { }
+ MainActivity.csLibrary4A.setWedgePrefix(editTextPrefix.getText().toString());
+ MainActivity.csLibrary4A.setWedgeSuffix(editTextSuffix.getText().toString());
+ int wedgeDelimiter = 0x0A;
+ switch (spinnerDelimiter.getSelectedItemPosition()) {
+ default:
+ break;
+ case 1:
+ wedgeDelimiter = 0x09;
+ break;
+ case 2:
+ wedgeDelimiter = 0x2c;
+ break;
+ case 3:
+ wedgeDelimiter = 0x20;
+ break;
+ case 4:
+ wedgeDelimiter = -1;
+ break;
+ }
+ MainActivity.csLibrary4A.setWedgeDelimiter(wedgeDelimiter);
+ MainActivity.csLibrary4A.appendToLog("SettingWedgeFragment, onCreateDialog: wedgeDelimiter = " + MainActivity.csLibrary4A.getWedgeOutput());
+ MainActivity.csLibrary4A.setWedgeOutput(spinnerOutput.getSelectedItemPosition());
+ MainActivity.csLibrary4A.saveWedgeSetting2File();
+ getDialog().dismiss();
+ }
+ });
+ builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
+ public void onClick(DialogInterface dialog, int whichButton) {
+ getDialog().dismiss();
+ }
+ });
+
+ editTextPower = (EditText) view.findViewById(R.id.directWedgeSettingEditTextPower);
+ MainActivity.csLibrary4A.appendToLog("editTextPower is " + (editTextPower == null ? "null" : "valid"));
+ if (editTextPower != null) editTextPower.setText(String.valueOf(MainActivity.csLibrary4A.getWedgePower()));
+
+ editTextPrefix = (EditText) view.findViewById(R.id.directWedgeSettingEditTextPrefix);
+ MainActivity.csLibrary4A.appendToLog("editTextPrefix is " + (editTextPrefix == null ? "null" : "valid"));
+ if (editTextPrefix != null) editTextPrefix.setText(MainActivity.csLibrary4A.getWedgePrefix());
+
+ editTextSuffix = (EditText) view.findViewById(R.id.directWedgeSettingEditTextSuffix);
+ MainActivity.csLibrary4A.appendToLog("editTextSuffix is " + (editTextSuffix == null ? "null" : "valid"));
+ if (editTextSuffix != null) editTextSuffix.setText(MainActivity.csLibrary4A.getWedgeSuffix());
+
+ spinnerDelimiter = (Spinner) view.findViewById(R.id.directWedgeSettingSpinnerDelimiter);
+ MainActivity.csLibrary4A.appendToLog("spinnerDelimiter is " + (spinnerDelimiter == null ? "null" : "valid"));
+ ArrayAdapter targetAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.delimiter_options, R.layout.custom_spinner_layout);
+ MainActivity.csLibrary4A.appendToLog("targetAdapter is " + (targetAdapter == null ? "null" : "valid"));
+ targetAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+ int position = 0;
+ MainActivity.csLibrary4A.appendToLog("SettingWedgeFragment, onCreatDialog: wedgeDelimiter = " + MainActivity.csLibrary4A.getWedgeDelimiter());
+ switch (MainActivity.csLibrary4A.getWedgeDelimiter()) {
+ default:
+ position = 0;
+ break;
+ case 0x09:
+ position = 1;
+ break;
+ case 0x2C:
+ position = 2;
+ break;
+ case 0x20:
+ position = 3;
+ break;
+ case -1:
+ position = 4;
+ break;
+ }
+ MainActivity.csLibrary4A.appendToLog("position is " + position);
+ spinnerDelimiter.setAdapter(targetAdapter);
+ spinnerDelimiter.setSelection(position);
+
+ spinnerOutput = (Spinner) view.findViewById(R.id.directWedgeSettingSpinnerOutput);
+ MainActivity.csLibrary4A.appendToLog("spinnerOutput is " + (spinnerOutput == null ? "null" : "valid"));
+ ArrayAdapter targetAdapter1 = ArrayAdapter.createFromResource(getActivity(), R.array.wedgeOutput_options, R.layout.custom_spinner_layout);
+ MainActivity.csLibrary4A.appendToLog("targetAdapter1 is " + (targetAdapter1 == null ? "null" : "valid"));
+ targetAdapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+ int position1 = MainActivity.csLibrary4A.getWedgeOutput();
+ MainActivity.csLibrary4A.appendToLog("position1 is " + position1);
+ spinnerOutput.setAdapter(targetAdapter1);
+ spinnerOutput.setSelection(position1);
+
+ return builder.create();
+ }
+}
+
+
+
+package com.csl.cs710ademoapp.fragments;
+
+import static android.Manifest.permission.RECORD_AUDIO;
+import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
+
+import android.content.pm.PackageManager;
+import android.media.MediaPlayer;
+import android.media.MediaRecorder;
+import android.os.Bundle;
+import android.os.Environment;
+import android.os.Handler;
+import android.util.Log;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.Button;
+import android.widget.SeekBar;
+import android.widget.TextView;
+import android.widget.Toast;
+
+import androidx.appcompat.app.AppCompatActivity;
+import androidx.core.app.ActivityCompat;
+import androidx.core.content.ContextCompat;
+
+import com.csl.cs710ademoapp.MainActivity;
+import com.csl.cs710ademoapp.R;
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.text.SimpleDateFormat;
+
+public class Test1Fragment extends CommonFragment {
+ Button startbtn, stopbtn, playbtn, stopplay;
+ MediaRecorder mRecorder;
+ MediaPlayer mediaPlayer;
+ static final String LOG_TAG = "AudioRecording";
+ static String mFileName = null;
+ public static final int REQUEST_AUDIO_PERMISSION_CODE = 1;
+ Handler handler = new Handler();
+
+ TextView seekBarHint;
+ SeekBar seekBar;
+ boolean wasPlaying = false;
+
+ File file;
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ super.onCreateView(inflater, container, savedInstanceState, true);
+ return inflater.inflate(R.layout.fragment_test1, container, false);
+ }
+
+ @Override
+ public void onActivityCreated(Bundle savedInstanceState) {
+ super.onActivityCreated(savedInstanceState);
+
+ androidx.appcompat.app.ActionBar actionBar;
+ actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
+ actionBar.setIcon(R.drawable.dl_access);
+ actionBar.setTitle("Test");
+
+ startbtn = (Button) getActivity().findViewById(R.id.btnRecord);
+ stopbtn = (Button) getActivity().findViewById(R.id.btnStop);
+ playbtn = (Button) getActivity().findViewById(R.id.btnPlay);
+ stopplay = (Button) getActivity().findViewById(R.id.btnStopPlay);
+ stopbtn.setEnabled(false);
+ playbtn.setEnabled(false);
+ stopplay.setEnabled(false);
+ mFileName = Environment.getExternalStorageDirectory().getAbsolutePath();
+ mFileName += "/Download/cs710Java/";
+
+ seekBarHint = (TextView) getActivity().findViewById(R.id.textView);
+ seekBar = (SeekBar) getActivity().findViewById(R.id.seekbar);
+
+ startbtn.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if(CheckPermissions() == false) RequestPermissions();
+ else {
+ startbtn.setEnabled(false);
+ stopbtn.setEnabled(true);
+ playbtn.setEnabled(false);
+ stopplay.setEnabled(false);
+
+ mRecorder = new MediaRecorder();
+ mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
+ mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
+ mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
+ mFileName += "audio";
+ mFileName += new SimpleDateFormat("_yyMMdd_HHmmss").format(new java.util.Date());
+ Log.i("Hello2", "mFileName is " + mFileName );
+ mRecorder.setOutputFile(mFileName + ".3gp");
+ try {
+ mRecorder.prepare();
+ } catch (IOException e) {
+ Log.e(LOG_TAG, "prepare() failed");
+ }
+ mRecorder.start();
+ Toast.makeText(getActivity().getApplicationContext(), "Recording Started", Toast.LENGTH_LONG).show();
+
+ file = new File(getActivity().getFilesDir(), mFileName + ".txt");
+ try {
+ FileOutputStream stream = new FileOutputStream(file);
+ stream.write("Start of data\n".getBytes());
+ String outData = "preFilterData.maskbit";
+ stream.write(outData.getBytes());
+ stream.write("End of data\n".getBytes());
+ stream.close();
+ } catch (Exception ex) {
+ Log.i("Hello2", "Exception is " + ex.toString());
+ }
+
+ MainActivity.mSensorConnector.mLocationDevice.turnOn(true);
+ MainActivity.mSensorConnector.mSensorDevice.turnOn(true);
+ handler.post(runnableRecord);
+ }
+ }
+ });
+
+ stopbtn.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ startbtn.setEnabled(true);
+ stopbtn.setEnabled(false);
+ playbtn.setEnabled(true);
+ stopplay.setEnabled(true);
+ mRecorder.stop();
+ mRecorder.release();
+ mRecorder = null;
+ Toast.makeText(getActivity().getApplicationContext(), "Recording Stopped", Toast.LENGTH_LONG).show();
+
+ MainActivity.mSensorConnector.mLocationDevice.turnOn(false);
+ MainActivity.mSensorConnector.mSensorDevice.turnOn(false);
+ handler.removeCallbacks(runnableRecord);
+ }
+ });
+
+ playbtn.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ startbtn.setEnabled(true);
+ stopbtn.setEnabled(false);
+ playbtn.setEnabled(false);
+ stopplay.setEnabled(true);
+
+ if (mediaPlayer != null) {
+ try {
+ if (mediaPlayer.isPlaying()) {
+ clearMediaPlayer();
+ wasPlaying = true;
+ }
+ } catch (Exception ex) {
+ Log.i("Hello2", "Exception is " + ex.toString());
+ }
+ }
+ if (!wasPlaying) {
+ if (mediaPlayer == null) mediaPlayer = new MediaPlayer();
+ try {
+ mediaPlayer.setDataSource(mFileName);
+ mediaPlayer.prepare();
+ mediaPlayer.setLooping(false);
+ seekBar.setMax(mediaPlayer.getDuration());
+
+ mediaPlayer.start();
+ Toast.makeText(getActivity().getApplicationContext(), "Recording Started Playing", Toast.LENGTH_LONG).show();
+ handler.removeCallbacks(runnablePlay);
+ handler.post(runnablePlay);
+ } catch (IOException e) {
+ Log.e(LOG_TAG, "prepare() failed");
+ }
+ }
+ }
+ });
+
+ stopplay.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ clearMediaPlayer();
+ Toast.makeText(getActivity().getApplicationContext(),"Playing Audio Stopped", Toast.LENGTH_SHORT).show();
+ }
+ });
+
+ seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
+ @Override
+ public void onStartTrackingTouch(SeekBar seekBar) {
+ seekBarHint.setVisibility(View.VISIBLE);
+ }
+
+ @Override
+ public void onProgressChanged(SeekBar seekBar, int progress, boolean fromTouch) {
+ seekBarHint.setVisibility(View.VISIBLE);
+ int x = (int) Math.ceil(progress / 1000f);
+ if (x != 0 && mediaPlayer != null && !mediaPlayer.isPlaying()) {
+ clearMediaPlayer();
+ }
+ }
+
+ @Override
+ public void onStopTrackingTouch(SeekBar seekBar) {
+ if (mediaPlayer != null && mediaPlayer.isPlaying()) {
+ mediaPlayer.seekTo(seekBar.getProgress());
+ }
+ }
+ });
+ }
+
+ void clearMediaPlayer() {
+ if (mediaPlayer != null) {
+ mediaPlayer.stop();
+ mediaPlayer.release();
+ }
+ seekBar.setProgress(0);
+ startbtn.setEnabled(true);
+ stopbtn.setEnabled(false);
+ playbtn.setEnabled(true);
+ stopplay.setEnabled(false);
+ mediaPlayer = null;
+ }
+
+ @Override
+ public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
+ switch (requestCode) {
+ case REQUEST_AUDIO_PERMISSION_CODE:
+ if (grantResults.length> 0) {
+ boolean permissionToRecord = grantResults[0] == PackageManager.PERMISSION_GRANTED;
+ boolean permissionToStore = grantResults[1] == PackageManager.PERMISSION_GRANTED;
+ if (permissionToRecord && permissionToStore) {
+ Toast.makeText(getActivity().getApplicationContext(), "Permission Granted", Toast.LENGTH_LONG).show();
+ } else {
+ Toast.makeText(getActivity().getApplicationContext(),"Permission Denied",Toast.LENGTH_LONG).show();
+ }
+ }
+ break;
+ }
+ }
+
+ boolean CheckPermissions() {
+ int result = ContextCompat.checkSelfPermission(getActivity().getApplicationContext(), WRITE_EXTERNAL_STORAGE);
+ int result1 = ContextCompat.checkSelfPermission(getActivity().getApplicationContext(), RECORD_AUDIO);
+ Log.i("Hello2", "result = " + result + ", result1 = " + result1);
+ return result == PackageManager.PERMISSION_GRANTED && result1 == PackageManager.PERMISSION_GRANTED;
+ }
+
+ void RequestPermissions() {
+ ActivityCompat.requestPermissions(getActivity(), new String[]{RECORD_AUDIO, WRITE_EXTERNAL_STORAGE}, REQUEST_AUDIO_PERMISSION_CODE);
+ }
+
+
+ final Runnable runnableRecord = new Runnable() {
+ boolean DEBUG = false;
+ @Override
+ public void run() {
+ String stringLocation = MainActivity.mSensorConnector.mLocationDevice.getLocation();
+ String stringCompass = MainActivity.mSensorConnector.mSensorDevice.getEcompass();
+ Log.i("Hello2", "stringLocation = " + stringLocation + ", stringCompass = " + stringCompass);
+ handler.postDelayed(runnableRecord, 1000);
+ }
+ };
+
+ final Runnable runnablePlay = new Runnable() {
+ boolean DEBUG = false;
+ @Override
+ public void run() {
+ boolean bPlaying = false;
+ try {
+ if (mediaPlayer != null && mediaPlayer.isPlaying()) {
+ int currentPosition = mediaPlayer.getCurrentPosition();
+ int total = mediaPlayer.getDuration();
+ if (currentPosition < total) {
+ seekBar.setProgress(currentPosition);
+ bPlaying = true;
+ }
+ } else clearMediaPlayer();
+ } catch (Exception ex) {
+ Log.i("Hello2", "Runnable Exception: " + ex.toString());
+ }
+ if (bPlaying) handler.postDelayed(runnablePlay, 1000);
+ else clearMediaPlayer();
+ }
+ };
+
+ @Override
+ public void onDestroy() {
+ super.onDestroy();
+ }
+
+ public Test1Fragment() {
+ super("Test1Fragment");
+ }
+
+}
+
+
+
+package com.csl.cs710ademoapp.fragments;
+
+import android.os.Bundle;
+
+import androidx.appcompat.app.AppCompatActivity;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.Button;
+
+import com.csl.cs710ademoapp.MainActivity;
+import com.csl.cs710ademoapp.R;
+
+public class TestFragment extends CommonFragment {
+ private Button buttonRead;
+ private Button buttonWrite;
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ super.onCreateView(inflater, container, savedInstanceState, true);
+ return inflater.inflate(R.layout.fragment_test, container, false);
+ }
+
+ @Override
+ public void onActivityCreated(Bundle savedInstanceState) {
+ super.onActivityCreated(savedInstanceState);
+
+ androidx.appcompat.app.ActionBar actionBar;
+ actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
+ actionBar.setIcon(R.drawable.dl_access);
+ actionBar.setTitle("Test");
+
+ buttonRead = (Button) getActivity().findViewById(R.id.accessRWReadButton);
+ buttonWrite = (Button) getActivity().findViewById(R.id.accessRWWriteButton);
+ }
+
+ @Override
+ public void onDestroy() {
+ MainActivity.csLibrary4A.setSameCheck(true);
+ MainActivity.csLibrary4A.restoreAfterTagSelect();
+ super.onDestroy();
+ }
+
+ public TestFragment() {
+ super("TestFragment");
+ }
+}
+
+
+
+package com.csl.cs710ademoapp.fragments;
+
+import android.os.Bundle;
+import android.view.LayoutInflater;
+import android.view.MenuItem;
+import android.view.View;
+import android.view.ViewGroup;
+
+import androidx.appcompat.app.ActionBar;
+import androidx.appcompat.app.AppCompatActivity;
+import androidx.viewpager.widget.ViewPager;
+
+import com.csl.cs710ademoapp.MainActivity;
+import com.csl.cs710ademoapp.R;
+import com.csl.cslibrary4a.AdapterTab;
+import com.google.android.material.tabs.TabLayout;
+
+public class Ucode8Fragment extends CommonFragment {
+ private ActionBar actionBar;
+ private ViewPager viewPager;
+ AdapterTab adapter;
+
+ private String[] tabs = {"Configure", "Scan", "Security", "Untrace"};
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ super.onCreateView(inflater, container, savedInstanceState, true);
+ return inflater.inflate(R.layout.custom_tabbed_layout, container, false);
+ }
+
+ @Override
+ public boolean onOptionsItemSelected(MenuItem item) {
+ InventoryRfidiMultiFragment fragment = (InventoryRfidiMultiFragment) adapter.getItem(1);
+ if (item.getItemId() == R.id.menuAction_clear) {
+ fragment.clearTagsList();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_sortRssi) {
+ fragment.sortTagsListByRssi();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_sort) {
+ fragment.sortTagsList();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_save) {
+ fragment.saveTagsList();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_share) {
+ fragment.shareTagsList();
+ return true;
+ } else return super.onOptionsItemSelected(item);
+ }
+
+ @Override
+ public void onActivityCreated(Bundle savedInstanceState) {
+ super.onActivityCreated(savedInstanceState);
+
+ actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
+ actionBar.setIcon(R.drawable.dl_inv);
+ actionBar.setTitle(R.string.title_activity_ucode8);
+
+ TabLayout tabLayout = (TabLayout) getActivity().findViewById(R.id.OperationsTabLayout);
+
+ adapter = new AdapterTab(getActivity().getSupportFragmentManager(), tabs.length);
+ adapter.setFragment(0, new AccessUcode8Fragment());
+ adapter.setFragment(1, InventoryRfidiMultiFragment.newInstance(true, null, ""));
+ adapter.setFragment(2, new AccessUcodeFragment());
+ adapter.setFragment(3, new UtraceFragment());
+
+ viewPager = (ViewPager) getActivity().findViewById(R.id.OperationsPager);
+ viewPager.setAdapter(adapter);
+ viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
+
+ for (String tab_name : tabs) {
+ tabLayout.addTab(tabLayout.newTab().setText(tab_name));
+ }
+
+ tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
+ @Override
+ public void onTabSelected(TabLayout.Tab tab) {
+ viewPager.setCurrentItem(tab.getPosition());
+ }
+
+ @Override
+ public void onTabUnselected(TabLayout.Tab tab) {
+ }
+
+ @Override
+ public void onTabReselected(TabLayout.Tab tab) {
+ }
+ });
+ }
+
+ @Override
+ public void onPause() {
+ adapter.fragment0.onPause();
+ adapter.fragment1.onPause();
+ super.onPause();
+ }
+
+ @Override
+ public void onStop() {
+ adapter.fragment0.onStop();
+ adapter.fragment1.onStop();
+ super.onStop();
+ }
+
+ @Override
+ public void onDestroyView() {
+ adapter.fragment0.onDestroyView();
+ adapter.fragment1.onDestroyView();
+ super.onDestroyView();
+ }
+
+ @Override
+ public void onDestroy() {
+ adapter.fragment0.onDestroy();
+ adapter.fragment1.onDestroy();
+ MainActivity.csLibrary4A.setSelectCriteriaDisable(1);
+ MainActivity.csLibrary4A.restoreAfterTagSelect();
+ super.onDestroy();
+ }
+
+ @Override
+ public void onDetach() {
+ adapter.fragment0.onDetach();
+ adapter.fragment1.onDetach();
+ super.onDetach();
+ }
+
+ public Ucode8Fragment() {
+ super("Ucode8Fragment");
+ }
+}
+
+
+
+package com.csl.cs710ademoapp.fragments;
+
+import static com.csl.cslibrary4a.RfidReader.TagType.TAG_NXP_UCODEDNA;
+
+import android.os.Bundle;
+import android.view.LayoutInflater;
+import android.view.MenuItem;
+import android.view.View;
+import android.view.ViewGroup;
+
+import androidx.appcompat.app.ActionBar;
+import androidx.appcompat.app.AppCompatActivity;
+import androidx.viewpager.widget.ViewPager;
+
+import com.csl.cs710ademoapp.R;
+import com.csl.cslibrary4a.AdapterTab;
+import com.google.android.material.tabs.TabLayout;
+
+public class UcodeFragment extends CommonFragment {
+ private ActionBar actionBar;
+ private ViewPager viewPager;
+ AdapterTab adapter;
+
+ private String[] tabs = {"Scan", "Authenticate"};
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ super.onCreateView(inflater, container, savedInstanceState, true);
+ return inflater.inflate(R.layout.custom_tabbed_layout, container, false);
+ }
+
+ @Override
+ public boolean onOptionsItemSelected(MenuItem item) {
+ InventoryRfidiMultiFragment fragment = (InventoryRfidiMultiFragment) adapter.getItem(0);
+ if (item.getItemId() == R.id.menuAction_clear) {
+ fragment.clearTagsList();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_sortRssi) {
+ fragment.sortTagsListByRssi();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_sort) {
+ fragment.sortTagsList();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_save) {
+ fragment.saveTagsList();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_share) {
+ fragment.shareTagsList();
+ return true;
+ } else return super.onOptionsItemSelected(item);
+ }
+
+ @Override
+ public void onActivityCreated(Bundle savedInstanceState) {
+ super.onActivityCreated(savedInstanceState);
+
+ actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
+ actionBar.setIcon(R.drawable.dl_inv);
+ actionBar.setTitle(R.string.title_activity_ucodeDNA);
+
+ TabLayout tabLayout = (TabLayout) getActivity().findViewById(R.id.OperationsTabLayout);
+
+ adapter = new AdapterTab(getActivity().getSupportFragmentManager(), tabs.length);
+ adapter.setFragment(0, InventoryRfidiMultiFragment.newInstance(true, TAG_NXP_UCODEDNA, "E2C06"));
+ adapter.setFragment(1, new AccessUcodeFragment());
+
+
+ viewPager = (ViewPager) getActivity().findViewById(R.id.OperationsPager);
+ viewPager.setAdapter(adapter);
+ viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
+
+ for (String tab_name : tabs) {
+ tabLayout.addTab(tabLayout.newTab().setText(tab_name));
+ }
+
+ tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
+ @Override
+ public void onTabSelected(TabLayout.Tab tab) {
+ viewPager.setCurrentItem(tab.getPosition());
+ }
+
+ @Override
+ public void onTabUnselected(TabLayout.Tab tab) {
+ }
+
+ @Override
+ public void onTabReselected(TabLayout.Tab tab) {
+ }
+ });
+ }
+
+ @Override
+ public void onPause() {
+ adapter.fragment0.onPause();
+ adapter.fragment1.onPause();
+ super.onPause();
+ }
+
+ @Override
+ public void onStop() {
+ adapter.fragment0.onStop();
+ adapter.fragment1.onStop();
+ super.onStop();
+ }
+
+ @Override
+ public void onDestroyView() {
+ adapter.fragment0.onDestroyView();
+ adapter.fragment1.onDestroyView();
+ super.onDestroyView();
+ }
+
+ @Override
+ public void onDestroy() {
+ adapter.fragment0.onDestroy();
+ adapter.fragment1.onDestroy();
+ super.onDestroy();
+ }
+
+ @Override
+ public void onDetach() {
+ adapter.fragment0.onDetach();
+ adapter.fragment1.onDetach();
+ super.onDetach();
+ }
+
+ public UcodeFragment() {
+ super("UcodeFragment");
+ }
+}
+
+
+
+package com.csl.cs710ademoapp.fragments;
+
+import android.app.Activity;
+import android.os.AsyncTask;
+import android.os.Bundle;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.Button;
+import android.widget.CheckBox;
+import android.widget.CompoundButton;
+import android.widget.EditText;
+import android.widget.RadioButton;
+import android.widget.Spinner;
+import android.widget.TextView;
+import android.widget.Toast;
+
+import com.csl.cs710ademoapp.AccessTask;
+import com.csl.cs710ademoapp.MainActivity;
+import com.csl.cs710ademoapp.R;
+import com.csl.cs710ademoapp.SelectTag;
+import com.csl.cslibrary4a.ReaderDevice;
+import com.csl.cslibrary4a.RfidReaderChipData;
+
+public class UtraceFragment extends CommonFragment {
+ final boolean DEBUG = true;
+ SelectTag selectTag;
+ Spinner memoryBankSpinner;
+ EditText editTextRWTagID, editTextAccessRWAccPassword;
+ CheckBox checkBoxHideXpc, checkBoxHideEpc, checkBoxHideTid, checkBoxHideUser, checkBoxHideRange;
+ RadioButton radioButtonRangeToggle, radioButtonRangeReduced, radioButtonHideSomeTid, radioButtonHideAllTid;
+
+ EditText editTextEpcSize;
+ private Button buttonUntrace; String strUntraceButtonBackup;
+ private AccessTask accessTask;
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ super.onCreateView(inflater, container, savedInstanceState, false);
+ return inflater.inflate(R.layout.fragment_utrace, container, false);
+ }
+
+ @Override
+ public void onActivityCreated(Bundle savedInstanceState) {
+ super.onActivityCreated(savedInstanceState);
+
+ selectTag = new SelectTag((Activity)getActivity(), 2);
+
+ checkBoxHideXpc = (CheckBox) getActivity().findViewById(R.id.utraceAssertUXPC);
+ checkBoxHideEpc = (CheckBox) getActivity().findViewById(R.id.utraceHideEpc);
+ checkBoxHideEpc.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
+ @Override
+ public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
+ TextView textView = (TextView) getActivity().findViewById(R.id.utraceEpcLengthTitle);
+ if (isChecked) {
+ textView.setVisibility(View.VISIBLE);
+ editTextEpcSize.setVisibility(View.VISIBLE);
+ } else {
+ textView.setVisibility(View.INVISIBLE);
+ editTextEpcSize.setVisibility(View.INVISIBLE);
+ }
+ }
+ });
+ checkBoxHideTid = (CheckBox) getActivity().findViewById(R.id.utraceHideTid);
+ radioButtonHideSomeTid = (RadioButton) getActivity().findViewById(R.id.utraceHideSomeTid);
+ radioButtonHideAllTid = (RadioButton) getActivity().findViewById(R.id.utraceHideAllTid);
+ checkBoxHideTid.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
+ @Override
+ public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
+ RadioButton radioButton1 = (RadioButton) getActivity().findViewById(R.id.utraceHideSomeTid);
+ RadioButton radioButton2 = (RadioButton) getActivity().findViewById(R.id.utraceHideAllTid);
+ if (isChecked) {
+ radioButton1.setVisibility(View.VISIBLE);
+ radioButton2.setVisibility(View.VISIBLE);
+ } else {
+ radioButton1.setVisibility(View.INVISIBLE);
+ radioButton2.setVisibility(View.INVISIBLE);
+ }
+ }
+ });
+ checkBoxHideUser = (CheckBox) getActivity().findViewById(R.id.utraceHideUser);
+
+ checkBoxHideRange = (CheckBox) getActivity().findViewById(R.id.utraceHideRange);
+ radioButtonRangeToggle = (RadioButton) getActivity().findViewById(R.id.utraceRangeToggle);
+ radioButtonRangeReduced = (RadioButton) getActivity().findViewById(R.id.utraceRangeReduced);
+ checkBoxHideRange.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
+ @Override
+ public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
+ RadioButton radioButton1 = (RadioButton) getActivity().findViewById(R.id.utraceRangeToggle);
+ RadioButton radioButton2 = (RadioButton) getActivity().findViewById(R.id.utraceRangeReduced);
+ if (isChecked) {
+ radioButton1.setVisibility(View.VISIBLE);
+ radioButton2.setVisibility(View.VISIBLE);
+ } else {
+ radioButton1.setVisibility(View.INVISIBLE);
+ radioButton2.setVisibility(View.INVISIBLE);
+ }
+ }
+ });
+
+ editTextEpcSize = (EditText) getActivity().findViewById(R.id.utraceEpcLength);
+
+ selectTag.editTextAccessAntennaPower.setText(String.valueOf(300));
+
+ buttonUntrace = (Button) getActivity().findViewById(R.id.utraceUntraceButton);
+ buttonUntrace.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (MainActivity.csLibrary4A.isBleConnected() == false) {
+ Toast.makeText(MainActivity.mContext, R.string.toast_ble_not_connected, Toast.LENGTH_SHORT).show();
+ return;
+ } else if (MainActivity.csLibrary4A.isRfidFailure()) {
+ Toast.makeText(MainActivity.mContext, "Rfid is disabled", Toast.LENGTH_SHORT).show();
+ return;
+ }
+ startAccessTask();
+ }
+ });
+
+ MainActivity.csLibrary4A.appendToLog("going to setupTagID"); setupTagID();
+ MainActivity.csLibrary4A.setSameCheck(false);
+ }
+
+ @Override
+ public void onResume() {
+ super.onResume();
+ MainActivity.csLibrary4A.appendToLog("going to setupTagID"); setupTagID();
+ }
+
+ @Override
+ public void onDestroy() {
+ if (accessTask != null) accessTask.cancel(true);
+ super.onDestroy();
+ }
+
+ boolean userVisibleHint = false;
+ @Override
+ public void setUserVisibleHint(boolean isVisibleToUser) {
+ super.setUserVisibleHint(isVisibleToUser);
+ if(getUserVisibleHint()) {
+ MainActivity.csLibrary4A.appendToLog("going to setupTagID"); setupTagID();
+ userVisibleHint = true;
+ MainActivity.csLibrary4A.appendToLog("UtraceFragment is now VISIBLE");
+ } else {
+ userVisibleHint = false;
+ MainActivity.csLibrary4A.appendToLog("UtraceFragment is now INVISIBLE");
+ }
+ }
+
+ public UtraceFragment() {
+ super("UtraceFragment");
+ }
+
+ void setupTagID() {
+ MainActivity.csLibrary4A.appendToLog("selectTag 1 = " + (selectTag != null ? "Valid" : "Null"));
+ if (selectTag == null) return;
+ ReaderDevice tagSelected = MainActivity.tagSelected;
+ MainActivity.csLibrary4A.appendToLog("Start with tagSelected = " + (tagSelected == null ? "NULL" : (tagSelected.getSelected() + ", " + tagSelected.getAddress())));
+ boolean bSelected = false;
+ if (tagSelected != null) {
+ if (tagSelected.getSelected() == true) {
+ bSelected = true;
+ MainActivity.csLibrary4A.appendToLog("selectTag is " + (selectTag == null ? "NULL" : "valid"));
+ if (selectTag != null) MainActivity.csLibrary4A.appendToLog("selectTag.editTextTag is " + (selectTag.editTextTagID == null ? "NULL" : "valid"));
+ if (selectTag.editTextTagID != null) {
+ MainActivity.csLibrary4A.appendToLog("editTextRWTagID.setText " + tagSelected.getAddress());
+ selectTag.editTextTagID.setText(tagSelected.getAddress());
+ }
+
+ String stringDetail = tagSelected.getDetails();
+ int indexUser = stringDetail.indexOf("USER=");
+ if (indexUser != -1) {
+ String stringUser = stringDetail.substring(indexUser + 5);
+ MainActivity.csLibrary4A.appendToLog("stringUser = " + stringUser);
+
+ boolean bEnableBAPMode = false;
+ int number = Integer.valueOf(stringUser.substring(3, 4), 16);
+ if ((number % 2) == 1) bEnableBAPMode = true;
+// CheckBox checkBoxBAP = (CheckBox) getActivity().findViewById(R.id.coldChainEnableBAP);
+// checkBoxBAP.setChecked(bEnableBAPMode);
+ }
+ }
+ }
+ }
+
+ void startAccessTask() {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("startAccessTask()");
+ if (updating == false) {
+ updating = true;
+ mHandler.removeCallbacks(updateRunnable);
+ mHandler.post(updateRunnable);
+ }
+ }
+ boolean updating = false;
+ private final Runnable updateRunnable = new Runnable() {
+ @Override
+ public void run() {
+ boolean rerunRequest = false; boolean taskRequest = false;
+ if (accessTask == null) {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("updateRunnable(): NULL accessReadWriteTask");
+ taskRequest = true;
+ } else if (accessTask.getStatus() != AsyncTask.Status.FINISHED) {
+ rerunRequest = true;
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("updateRunnable(): accessReadWriteTask.getStatus() = " + accessTask.getStatus().toString());
+ } else {
+ taskRequest = true;
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("updateRunnable(): FINISHED accessReadWriteTask");
+ }
+ if (processResult()) { MainActivity.csLibrary4A.appendToLog("processResult is TRUE"); }
+ else if (taskRequest) {
+ int rangeValue = 0;
+ if (checkBoxHideRange.isChecked()) {
+ if (radioButtonRangeToggle.isChecked()) rangeValue = 1;
+ else if (radioButtonRangeReduced.isChecked()) rangeValue = 2;
+ }
+ int tidValue = 0;
+ if (checkBoxHideTid.isChecked()) {
+ if (radioButtonHideSomeTid.isChecked()) tidValue = 1;
+ else if (radioButtonHideAllTid.isChecked()) tidValue = 2;
+ }
+ int epcValue = 0;
+ epcValue = Integer.parseInt(editTextEpcSize.getText().toString());
+ if (epcValue < 0 || epcValue > 31) {
+ epcValue = 6; editTextEpcSize.setText("6");
+ }
+ boolean invalid = (MainActivity.csLibrary4A.setUntraceable(rangeValue, checkBoxHideUser.isChecked(), tidValue, epcValue, checkBoxHideEpc.isChecked(), checkBoxHideXpc.isChecked()) == false);
+ MainActivity.csLibrary4A.appendToLog("processTickItems, invalid = " + invalid);
+
+ Button button = buttonUntrace; int selectBank = selectTag.spinnerSelectBank.getSelectedItemPosition() + 1; MainActivity.csLibrary4A.appendToLog("selectBank = " + selectBank);
+ //if (strUntraceButtonBackup == null) strUntraceButtonBackup = buttonUntrace.getText().toString(); buttonUntrace.setText("Show"); button = buttonUntrace;
+ accessTask = new AccessTask(button, null, invalid, true,
+ selectTag.editTextTagID.getText().toString(), selectBank, (selectBank == 1 ? 32 : 0),
+ selectTag.editTextAccessPassword.getText().toString(), Integer.valueOf(selectTag.editTextAccessAntennaPower.getText().toString()), RfidReaderChipData.HostCommands.CMD_UNTRACEABLE,
+ 0, 0, true, false,
+ null, null, null, null, null);
+ accessTask.execute();
+ rerunRequest = true;
+ }
+ if (rerunRequest) {
+ mHandler.postDelayed(updateRunnable, 500);
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("updateRunnable(): Restart");
+ }
+ else updating = false;
+ MainActivity.csLibrary4A.appendToLog("updateRunnable(): Ending with updating = " + updating);
+ }
+ };
+
+ boolean processResult() {
+ String accessResult = null;
+ if (accessTask == null) return false;
+ else if (accessTask.getStatus() != AsyncTask.Status.FINISHED) return false;
+ else {
+ accessResult = accessTask.accessResult;
+ //if (strUntraceButtonBackup != null) buttonUntrace.setText(strUntraceButtonBackup); strUntraceButtonBackup = null;
+ accessTask = null;
+ return true;
+ }
+ }
+}
+
+
+
+package com.csl.cs710ademoapp;
+
+import android.graphics.Color;
+import android.text.Editable;
+import android.text.InputFilter;
+import android.text.TextWatcher;
+import android.widget.EditText;
+
+public class GenericTextWatcher implements TextWatcher {
+ EditText editText;
+ int maxLength;
+ InputFilter mInputFilter;
+
+ public GenericTextWatcher(EditText editText, int maxLength) {
+ this.editText = editText;
+ this.maxLength = maxLength;
+ mInputFilter = new InputFilter.LengthFilter(maxLength);
+ editText.setFilters(new InputFilter[] { mInputFilter });
+ }
+
+ public void afterTextChanged(Editable s) {
+ if (s.length() != 0 && s.length() < maxLength) {
+ editText.setTextColor(Color.RED);
+ } else
+ editText.setTextColor(Color.BLACK);
+ }
+ public void beforeTextChanged(CharSequence s, int start, int count, int after){}
+ public void onTextChanged(CharSequence s, int start, int before, int count){}
+}
+
+
+
+package com.csl.cs710ademoapp;
+
+import android.os.AsyncTask;
+import android.os.Handler;
+import android.widget.Button;
+import android.widget.EditText;
+import android.widget.TextView;
+import android.widget.Toast;
+
+import com.csl.cs710ademoapp.adapters.ReaderListAdapter;
+import com.csl.cslibrary4a.ReaderDevice;
+
+import java.util.ArrayList;
+
+public class InventoryBarcodeTask extends AsyncTask {
+ final boolean DEBUG = false, ALLOW_WEDGE = true;
+ public enum TaskCancelRReason {
+ NULL, INVALD_REQUEST, DESTORY, STOP, BUTTON_RELEASE, TIMEOUT
+ }
+ final private boolean bAdd2End = false;
+ final boolean endingRequest = false;
+
+ public TaskCancelRReason taskCancelReason;
+ int batteryCountInventory_old; long startTimeMillis, runTimeMillis;
+
+ private int total, allTotal;
+ private int yield = 0;
+ private long timeMillis;
+
+ boolean requestSound = false; boolean requestNewSound = false; boolean requestNewVibrate = false; long timeMillisNewVibrate;
+ long timeMillisSound = 0;
+ Handler handler = new Handler(); boolean bUseVibrateMode0 = false;
+
+ protected void onPreExecute() {
+ MainActivity.sharedObjects.runningInventoryBarcodeTask = true;
+ if (button != null) button.setText("Stop"); if (button1 != null) button1.setText("Stop");
+ total = 0; allTotal = 0; yield = 0;
+ if (tagsList != null) {
+ yield = tagsList.size();
+ for (int i = 0; i < yield; i++) {
+ allTotal += tagsList.get(i).getCount();
+ }
+ }
+// tagsList.clear();
+// readerListAdapter.notifyDataSetChanged();
+ timeMillis = 0; startTimeMillis = System.currentTimeMillis(); runTimeMillis = startTimeMillis;
+ taskCancelReason = TaskCancelRReason.NULL;
+ if (barcodeYieldView != null) barcodeYieldView.setText("");
+
+ MainActivity.csLibrary4A.barcodeInventory(true);
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("InventoryBarcodeFragment.InventoryRfidTask.onPreExecute()");
+ MainActivity.csLibrary4A.appendToLog("setVibrateOn A 3 with getInventoryVibrate as " + MainActivity.csLibrary4A.getInventoryVibrate() + ", bUseVibrateMode0 as " + bUseVibrateMode0);
+ if (MainActivity.csLibrary4A.getInventoryVibrate() && bUseVibrateMode0 == false) MainActivity.csLibrary4A.setVibrateOn(3);
+ }
+
+ @Override
+ protected String doInBackground(Void... a) {
+ while (MainActivity.csLibrary4A.isBleConnected() && isCancelled() == false) {
+ int batteryCount = MainActivity.csLibrary4A.getBatteryCount();
+ if (batteryCountInventory_old != batteryCount) {
+ batteryCountInventory_old = batteryCount;
+ publishProgress("VV");
+ }
+ if (System.currentTimeMillis() > runTimeMillis + 1000) {
+ runTimeMillis = System.currentTimeMillis();
+ publishProgress("WW");
+ }
+ if (System.currentTimeMillis() - timeMillisSound > 1000) {
+ timeMillisSound = System.currentTimeMillis();
+ requestSound = true;
+ }
+ byte[] onBarcodeEvent = MainActivity.csLibrary4A.onBarcodeEvent();
+ if (onBarcodeEvent != null) {
+ MainActivity.csLibrary4A.appendToLog("BarStream: onBarcodeEvent= " + MainActivity.csLibrary4A.byteArrayToString(onBarcodeEvent));
+ String stringBar = null;
+ if (true) stringBar = new String(onBarcodeEvent);
+ else if (onBarcodeEvent.length != 0) {
+ for (int i = 0; i < onBarcodeEvent.length; i++) {
+ String stringLetter = "";
+ if (false && onBarcodeEvent[i] == 0x0D) { if (false) stringLetter = ""; }
+ else if (false && onBarcodeEvent[i] == 0x0A) { if (false) stringLetter = ""; }
+ else {
+ byte[] arrayLetter = new byte[1];
+ arrayLetter[0] = onBarcodeEvent[i];
+ stringLetter = new String(arrayLetter);
+ if (stringLetter.length() == 0) MainActivity.csLibrary4A.appendToLog("Non-printable character = " + MainActivity.csLibrary4A.byteArrayToString(arrayLetter));
+ }
+ if (stringBar == null) stringBar = stringLetter;
+ else stringBar += stringLetter;
+ }
+ }
+ MainActivity.csLibrary4A.appendToLog("BarStream: onBarcodeEvent, stringBar= " + stringBar);
+ if (stringBar != null) { if (stringBar.length() != 0) { publishProgress(null, stringBar.trim()); } }
+ timeMillis = System.currentTimeMillis();
+ } else if (System.currentTimeMillis() - timeMillis > 300) { if (taskCancelReason != TaskCancelRReason.NULL) cancel(true); }
+ if (MainActivity.csLibrary4A.isBleConnected() == false) taskCancelReason = TaskCancelRReason.DESTORY;
+ }
+ return "End of Asynctask()";
+ }
+
+ @Override
+ protected void onProgressUpdate(String... output) {
+ if (output != null) {
+ if (output[0] != null) {
+ if (output[0].length() == 2) {
+ if (output[0].contains("WW")) {
+ long timePeriod = (System.currentTimeMillis() - startTimeMillis) / 1000;
+ if (timePeriod > 0)
+ if (barcodeRunTime != null) barcodeRunTime.setText(String.format("Run time: %d sec", timePeriod));
+ } else if (taskCancelReason == TaskCancelRReason.NULL) {
+ if (barcodeVoltageLevel != null) barcodeVoltageLevel.setText(MainActivity.csLibrary4A.getBatteryDisplay(true));
+ }
+ }
+ return;
+ }
+ if (registerBarValue != null) registerBarValue.setText(output[1]);
+ boolean match = false;
+ if (false || tagsList != null) {
+ MainActivity.csLibrary4A.appendToLog("BarMatch: Matching bdata = " + output[1]);
+ for (int i = 0; i < tagsList.size(); i++) {
+ String strInList = tagsList.get(i).getAddress();
+ if (output[1].length() == strInList.length() && output[1].indexOf(strInList) == 0) {
+ MainActivity.csLibrary4A.appendToLog("BarMatch: Matched stored bdata" + i + "= " + tagsList.get(i).getAddress());
+ ReaderDevice readerDevice = tagsList.get(i);
+ int count = readerDevice.getCount();
+ count++;
+ readerDevice.setCount(count);
+ tagsList.set(i, readerDevice);
+ match = true;
+ break;
+ } else MainActivity.csLibrary4A.appendToLog("BarMatch: NOT Matched stored bdata" + i + "= " + tagsList.get(i).getAddress());
+ }
+ }
+ if (match == false) {
+ if (ALLOW_WEDGE) MainActivity.sharedObjects.serviceArrayList.add(output[1]);
+ MainActivity.csLibrary4A.appendToLog(output[1] + " is added to MainActivity.shareObjects.serviceArrayList with size = " + MainActivity.sharedObjects.serviceArrayList.size());
+
+ ReaderDevice readerDevice = new ReaderDevice("", output[1], false, "", 1, 0);
+ if (tagsList != null) {
+ if (bAdd2End) tagsList.add(readerDevice);
+ else tagsList.add(0, readerDevice);
+ }
+ yield++;
+ if (barcodeYieldView != null) barcodeYieldView.setText("Unique:" + String.valueOf(yield));
+ requestNewSound = true; requestNewVibrate = true;
+ }
+ total++; allTotal++;
+ if (barcodeRateView != null) barcodeRateView.setText("Total:" + String.valueOf(allTotal));
+ if (readerListAdapter != null) readerListAdapter.notifyDataSetChanged();
+
+ if (playerN != null && playerO != null) {
+ if (requestSound && playerO.isPlaying() == false && playerN.isPlaying() == false) {
+ if (true) {
+ if (bStartBeepWaiting == false) {
+ bStartBeepWaiting = true;
+ handler.postDelayed(runnableStartBeep, 250);
+ }
+ if (MainActivity.csLibrary4A.getInventoryVibrate()) {
+ boolean validVibrate0 = false, validVibrate = false;
+ if (MainActivity.csLibrary4A.getVibrateModeSetting() == 0) {
+ if (requestNewVibrate) validVibrate0 = true;
+ } else validVibrate0 = true;
+ requestNewVibrate = false;
+
+ if (bUseVibrateMode0 && validVibrate0 && bStartVibrateWaiting == false) {
+ if (System.currentTimeMillis() - timeMillisNewVibrate > MainActivity.csLibrary4A.getVibrateWindow() * 1000 ) {
+ timeMillisNewVibrate = System.currentTimeMillis();
+ validVibrate = true;
+ }
+ }
+ if (validVibrate) {
+ MainActivity.csLibrary4A.appendToLog("setVibrateOn b 1");
+ MainActivity.csLibrary4A.setVibrateOn(1);
+ bStartVibrateWaiting = true;
+ handler.postDelayed(runnableStartVibrate, MainActivity.csLibrary4A.getVibrateTime());
+ }
+ }
+ } else {
+ requestSound = false;
+ if (requestNewSound) {
+ requestNewSound = false;
+ if (playerN != null) playerN.start();
+ } else {
+ if (playerO != null) playerO.start();
+ }
+ }
+ }
+ }
+ } else {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("InventoryBarcodeFragment with NULL data");
+ }
+ }
+
+ boolean bStartBeepWaiting = false;
+ Runnable runnableStartBeep = new Runnable() {
+ @Override
+ public void run() {
+ bStartBeepWaiting = false;
+ requestSound = false;
+ if (requestNewSound) {
+ requestNewSound = false;
+ playerN.start(); //playerN.setVolume(300, 300);
+ } else {
+ playerO.start(); //playerO.setVolume(30, 30);
+ }
+ }
+ };
+
+ boolean bStartVibrateWaiting = false;
+ Runnable runnableStartVibrate = new Runnable() {
+ @Override
+ public void run() {
+ bStartVibrateWaiting = false;
+ }
+ };
+
+ @Override
+ protected void onCancelled() {
+ super.onCancelled();
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("InventoryBarcodeFragment() onCancelled()");
+
+ DeviceConnectTask4InventoryEnding(taskCancelReason);
+ }
+
+ @Override
+ protected void onPostExecute(String result) {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("InventoryBarcodeFragment() onPostExecute(): " + result);
+
+ DeviceConnectTask4InventoryEnding(taskCancelReason);
+ }
+
+ private EditText registerBarValue;
+ private ArrayList tagsList;
+ private ReaderListAdapter readerListAdapter;
+ private TextView barcodeRunTime, barcodeVoltageLevel;
+ private TextView barcodeYieldView;
+ private Button button, button1; String textButton, btextButton1;
+ private TextView barcodeRateView;
+ private boolean noToast;
+ CustomMediaPlayer playerO, playerN;
+ public InventoryBarcodeTask() { }
+ public InventoryBarcodeTask(ArrayList tagsList, ReaderListAdapter readerListAdapter, EditText registerBarValue,
+ TextView barcodeRunTime, TextView barcodeVoltageLevel,
+ TextView barcodeYieldView, Button button, Button button1, TextView barcodeRateView, boolean noToast) {
+ this.registerBarValue = registerBarValue;
+ this.tagsList = tagsList;
+ this.readerListAdapter = readerListAdapter;
+ this.barcodeRunTime = barcodeRunTime;
+ this.barcodeVoltageLevel = barcodeVoltageLevel;
+ this.barcodeYieldView = barcodeYieldView;
+ this.button = button; textButton = button.getText().toString();
+ this.button1 = button1; if (button1 != null) btextButton1 = button1.getText().toString();
+ this.barcodeRateView = barcodeRateView;
+ this.noToast = noToast;
+
+ playerO = MainActivity.sharedObjects.playerO;
+ playerN = MainActivity.sharedObjects.playerN;
+ }
+
+ void DeviceConnectTask4InventoryEnding(TaskCancelRReason taskCancelRReason) {
+ if (readerListAdapter != null) readerListAdapter.notifyDataSetChanged();
+ MainActivity.csLibrary4A.barcodeInventory(false);
+ if (true) MainActivity.csLibrary4A.appendToLog("DeviceConnectTask4InventoryEnding(): sent setBarcodeOn(false)");
+ if (taskCancelReason == null) {
+ new Handler().postDelayed(new Runnable() {
+ @Override
+ public void run() {
+ if (noToast == false) Toast.makeText(MainActivity.mContext, R.string.toast_abort_by_END, Toast.LENGTH_SHORT).show();
+ button.setText(textButton);
+ if (button1 != null) button1.setText(btextButton1);
+ }
+ }, 5000);
+ } else {
+ if (endingRequest) {
+ switch (taskCancelReason) {
+ case STOP:
+ if (noToast == false)
+ Toast.makeText(MainActivity.mContext, R.string.toast_abort_by_STOP, Toast.LENGTH_SHORT).show();
+ break;
+ case BUTTON_RELEASE:
+ if (noToast == false)
+ Toast.makeText(MainActivity.mContext, R.string.toast_abort_by_BUTTON, Toast.LENGTH_SHORT).show();
+ break;
+ }
+ }
+ if (button != null) button.setText(textButton);
+ if (button1 != null) button1.setText(btextButton1);
+ }
+ MainActivity.sharedObjects.runningInventoryBarcodeTask = false;
+ MainActivity.csLibrary4A.appendToLog("setVibrateOn C 0");
+ MainActivity.csLibrary4A.setVibrateOn(0);
+ }
+}
+
+
+
+package com.csl.cs710ademoapp;
+
+import android.content.Context;
+import android.os.AsyncTask;
+import android.os.Handler;
+import android.widget.Button;
+import android.widget.TextView;
+import android.widget.Toast;
+
+import com.csl.cs710ademoapp.adapters.ReaderListAdapter;
+import com.csl.cslibrary4a.ReaderDevice;
+import com.csl.cslibrary4a.RfidReader;
+import com.csl.cslibrary4a.RfidReaderChipData;
+
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Date;
+
+public class InventoryRfidTask extends AsyncTask {
+ final boolean DEBUG = false; final boolean ALLOW_WEDGE = true; boolean ALLOW_RTSAVE = false;
+ public enum TaskCancelRReason {
+ NULL, INVALD_REQUEST, DESTORY, STOP, BUTTON_RELEASE, TIMEOUT, RFID_RESET, ERROR
+ }
+ final private boolean bAdd2End = false;
+ final boolean endingRequest = true;
+
+ Context context;
+ public TaskCancelRReason taskCancelReason;
+ public boolean bSgtinOnly = false, bProtectOnly;
+ private boolean invalidRequest;
+ boolean beepEnable;
+
+ private ArrayList tagsList;
+ private ReaderListAdapter readerListAdapter;
+ private TextView geigerTagRssiView;
+ private TextView rfidRunTime, geigerTagGotView, rfidVoltageLevel;
+ private TextView rfidYieldView, rfidRateView;
+ private Button button;
+
+ CustomMediaPlayer playerO, playerN; int requestSoundCount;
+
+ int extra1Bank = -1, extra2Bank = -1;
+ RfidReader.TagType tagType; String strMdid;
+
+ final boolean invalidDisplay = false;
+ private int total, allTotal;
+ private int yield, yield4RateCount, yieldRate;
+ double rssi = 0; int phase, chidx, data1_count, data2_count, data1_offset, data2_offset;
+ int port = -1; int portstatus; int backport1, backport2, codeSensor, codeRssi; float codeTempC; final int INVALID_CODEVALUE = -500; String brand;
+ long timeMillis, startTimeMillis, runTimeMillis;
+ long firstTime;
+ long lastTime;
+ boolean continousRequest = false;
+ int batteryCountInventory_old;
+
+ boolean requestSound = false; boolean requestNewSound = false; boolean requestNewVibrate = false; long timeMillisNewVibrate;
+ String strEpcOld = "";
+ private ArrayList rx000pkgDataArrary = new ArrayList();
+ private String endingMessaage;
+
+ SaveList2ExternalTask saveExternalTask;
+ boolean serverConnectValid = false;
+ Handler handler = new Handler(); boolean bValidVibrateNewAll = false; boolean bUseVibrateMode0 = false;
+
+ void inventoryHandler_setup() {
+ MainActivity.csLibrary4A.appendToLog("InventoryRfidTask.inventoryHandler_setup set runningInventoryRfidTask as true ");
+ MainActivity.sharedObjects.runningInventoryRfidTask = true;
+ total = 0; allTotal = 0; yield = 0;
+ if (tagsList != null) {
+ yield = tagsList.size();
+ for (int i = 0; i < yield; i++) {
+ allTotal += tagsList.get(i).getCount();
+ }
+ MainActivity.csLibrary4A.appendToLog("yield = " + yield + ", allTotal = " + allTotal);
+ }
+ MainActivity.csLibrary4A.clearInvalidata();
+
+ timeMillis = System.currentTimeMillis(); startTimeMillis = System.currentTimeMillis(); runTimeMillis = startTimeMillis;
+ firstTime = 0;
+ lastTime = 0;
+
+ if (rfidVoltageLevel != null) rfidVoltageLevel.setText("");
+ if (rfidYieldView != null) rfidYieldView.setText("");
+ if (rfidRateView != null) rfidRateView.setText("");
+
+ taskCancelReason = TaskCancelRReason.NULL;
+ if (invalidRequest) {
+ cancel(true);
+ taskCancelReason = TaskCancelRReason.INVALD_REQUEST;
+ Toast.makeText(MainActivity.mContext, "Invalid Request.", Toast.LENGTH_SHORT).show();
+ }
+ if (button != null) button.setText("Stop");
+ MainActivity.mSensorConnector.mLocationDevice.turnOn(true);
+ MainActivity.mSensorConnector.mSensorDevice.turnOn(true);
+ if (ALLOW_RTSAVE) {
+ saveExternalTask = new SaveList2ExternalTask(false);
+ if (saveExternalTask.openServer(false)) {
+ serverConnectValid = true;
+ MainActivity.csLibrary4A.appendToLog("openServer is done");
+ } else {
+ MainActivity.csLibrary4A.appendToLog("openServer has Exception");
+ }
+ }
+ MainActivity.csLibrary4A.appendToLog("serverConnectValid = " + serverConnectValid);
+
+
+ MainActivity.csLibrary4A.appendToLog("getInventoryVibrate = " + MainActivity.csLibrary4A.getInventoryVibrate()
+ + ", bUseVibrate0 = " + bUseVibrateMode0
+ + ", getVibrateModeSetting = " + MainActivity.csLibrary4A.getVibrateModeSetting()
+ );
+ if (MainActivity.csLibrary4A.getInventoryVibrate() && bUseVibrateMode0 == false && MainActivity.csLibrary4A.getVibrateModeSetting() == 1) bValidVibrateNewAll = true;
+ MainActivity.csLibrary4A.appendToLog("setVibrateOn d 2 with bValidVibrateNewAll = " + bValidVibrateNewAll);
+ if (bValidVibrateNewAll) MainActivity.csLibrary4A.setVibrateOn(2);
+ }
+
+ @Override
+ protected void onPreExecute() {
+ //inventoryHandler_setup();
+ }
+
+ byte[] notificationData;
+ @Override
+ protected String doInBackground(Void... a) {
+ boolean ending = false, triggerReleased = false; long triggerReleaseTime = 0;
+ RfidReaderChipData.Rx000pkgData rx000pkgData = null;
+ while (MainActivity.csLibrary4A.onRFIDEvent() != null) { } //clear up possible message before operation
+ while (MainActivity.csLibrary4A.isBleConnected() && isCancelled() == false && ending == false && MainActivity.csLibrary4A.isRfidFailure() == false) {
+ int batteryCount = MainActivity.csLibrary4A.getBatteryCount();
+ if (batteryCountInventory_old != batteryCount) {
+ batteryCountInventory_old = batteryCount;
+ publishProgress("VV");
+ }
+ if (System.currentTimeMillis() > runTimeMillis + 1000) {
+ runTimeMillis = System.currentTimeMillis();
+ publishProgress("WW");
+ }
+
+ notificationData = MainActivity.csLibrary4A.onNotificationEvent();
+ rx000pkgData = MainActivity.csLibrary4A.onRFIDEvent();
+ if (rx000pkgData != null && MainActivity.csLibrary4A.mrfidToWriteSize() == 0) {
+ if (rx000pkgData.responseType == null) {
+ publishProgress("null response");
+ } else if (rx000pkgData.responseType == RfidReaderChipData.HostCmdResponseTypes.TYPE_18K6C_INVENTORY) {
+ {
+ if (rx000pkgData.decodedError != null) publishProgress(rx000pkgData.decodedError);
+ else {
+ if (firstTime == 0) firstTime = rx000pkgData.decodedTime;
+ else lastTime = rx000pkgData.decodedTime;
+ rx000pkgDataArrary.add(rx000pkgData); publishProgress(null, "", "");
+ }
+ }
+ } else if (rx000pkgData.responseType == RfidReaderChipData.HostCmdResponseTypes.TYPE_18K6C_INVENTORY_COMPACT) {
+ {
+ if (rx000pkgData.decodedError != null) publishProgress(rx000pkgData.decodedError);
+ else {
+ if (firstTime == 0) firstTime = rx000pkgData.decodedTime;
+ rx000pkgDataArrary.add(rx000pkgData); publishProgress(null, "", "");
+ }
+ }
+ } else if (rx000pkgData.responseType == RfidReaderChipData.HostCmdResponseTypes.TYPE_ANTENNA_CYCLE_END) {
+ timeMillis = System.currentTimeMillis();
+ } else if (rx000pkgData.responseType == RfidReaderChipData.HostCmdResponseTypes.TYPE_COMMAND_ABORT_RETURN) {
+ MainActivity.csLibrary4A.appendToLog("AAA: Abort return is received !!!");
+ ending = true;
+ } else if (rx000pkgData.responseType == RfidReaderChipData.HostCmdResponseTypes.TYPE_COMMAND_END) {
+ if (rx000pkgData.decodedError != null) endingMessaage = rx000pkgData.decodedError;
+ if (continousRequest) {
+ MainActivity.csLibrary4A.batteryLevelRequest();
+ MainActivity.csLibrary4A.appendToLog("Debug_Compact: InventoryRfidTask.doInBackground");
+ MainActivity.csLibrary4A.startOperation(RfidReaderChipData.OperationTypes.TAG_INVENTORY_COMPACT);
+ } else ending = true;
+ }
+ } else if (false && notificationData != null) {
+ MainActivity.csLibrary4A.appendToLog("matched Error: resultError=" + MainActivity.csLibrary4A.byteArrayToString(notificationData));
+ publishProgress("P");
+ taskCancelReason = TaskCancelRReason.ERROR;
+ }
+ if (false) {
+ if (MainActivity.csLibrary4A.mrfidToWriteSize() != 0) timeMillis = System.currentTimeMillis();
+ } else {
+ //suspend the current thread up to 5 seconds until all the commands on the output buffer got sent out
+ long toCnt = System.currentTimeMillis();
+ if (MainActivity.csLibrary4A.mrfidToWriteSize() != 0) {
+ while (System.currentTimeMillis() - toCnt < 50000 && MainActivity.csLibrary4A.mrfidToWriteSize() != 0) {
+ try {
+ Thread.sleep(200);
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ }
+ MainActivity.csLibrary4A.appendToLog("InventoryRfidTask: send commands elapsed time: " + String.format("%d", System.currentTimeMillis() - toCnt));
+ timeMillis = System.currentTimeMillis();
+ }
+ }
+ if (System.currentTimeMillis() - timeMillis > 10000 && false) { //no tag timeout handling during inventory
+ if (true) taskCancelReason = TaskCancelRReason.TIMEOUT;
+ else {
+ timeMillisSound = System.currentTimeMillis();
+ requestSound = true;
+ }
+ }
+ if (triggerReleased == false && taskCancelReason == TaskCancelRReason.BUTTON_RELEASE) {
+ triggerReleased = true; triggerReleaseTime = System.currentTimeMillis();
+ //taskCancelReason = TaskCancelRReason.NULL;
+ MainActivity.csLibrary4A.appendToLog("AAA: release is triggered !!!");
+ }
+ if (taskCancelReason != TaskCancelRReason.NULL) {
+ MainActivity.csLibrary4A.abortOperation();
+ publishProgress("XX");
+ if (popRequest) publishProgress("P");
+ timeMillis = 0;
+ boolean endStatus = true;
+ cancel(true);
+ } else if (triggerReleased && (System.currentTimeMillis() > (triggerReleaseTime + 2000))) {
+ MainActivity.csLibrary4A.appendToLog("AAA: triggerRelease Timeout !!!");
+ taskCancelReason = TaskCancelRReason.BUTTON_RELEASE;
+ }
+ }
+ String stringReturn = "End of Asynctask()";
+ if (MainActivity.csLibrary4A.isBleConnected() == false) stringReturn = "isBleConnected is false";
+ else if (isCancelled()) stringReturn = "isCancelled is true";
+ else if (MainActivity.csLibrary4A.isRfidFailure()) stringReturn = "isRfidFailure is true";
+ else if (ending) stringReturn = (rx000pkgData == null ? "null ending" : (rx000pkgData.responseType.toString() + " ending"));
+ return stringReturn;
+ }
+
+ long firstTimeOld = 0, timeMillisSound = 0; int totalOld = 0;
+ @Override
+ protected void onProgressUpdate(String... output) {
+ if (false) MainActivity.csLibrary4A.appendToLog("InventoryRfidTask: output[0] = " + output[0]);
+ if (output[0] != null) {
+ if (output[0].length() == 1) inventoryHandler_endReason();
+ else if (output[0].length() == 2) {
+ if (output[0].contains("XX")) MainActivity.csLibrary4A.appendToLogView("CANCELLING: PostProgressUpdate sent abortOperation");
+ else if (output[0].contains("WW")) inventoryHandler_runtime();
+ else if (output[0].contains("VV")) inventoryHandler_voltage();
+ } else
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("InventoryRfidTask.InventoryRfidTask.onProgressUpdate(): " + output[0]);
+ } else tagHandler();
+ }
+
+ void inventoryHandler_endReason() {
+ String message;
+ switch (taskCancelReason) {
+ case STOP:
+ message = "Stop button pressed";
+ break;
+ case BUTTON_RELEASE:
+ message = "Trigger Released";
+ break;
+ case TIMEOUT:
+ message = "Time Out";
+ break;
+ case ERROR:
+ message = "Inventory Notification Error code A101: " + MainActivity.csLibrary4A.byteArrayToString(notificationData);
+ break;
+ default:
+ message = taskCancelReason.name();
+ break;
+ }
+ CustomPopupWindow customPopupWindow = new CustomPopupWindow(MainActivity.mContext);
+ customPopupWindow.popupStart(message, false);
+ }
+ void inventoryHandler_runtime() {
+ long timePeriod = (System.currentTimeMillis() - startTimeMillis) / 1000;
+ if (timePeriod > 0) {
+ if (rfidRunTime != null) rfidRunTime.setText(String.format("Run time: %d sec", timePeriod));
+ yieldRate = yield4RateCount; yield4RateCount = 0;
+ }
+ }
+ void inventoryHandler_voltage() {
+ if (rfidVoltageLevel != null) rfidVoltageLevel.setText(MainActivity.csLibrary4A.getBatteryDisplay(true));
+ }
+
+ boolean bGotTagRate = false;
+ void tagHandler() {
+ boolean DEBUG = false;
+ {
+ long currentTime = 0;
+ {
+ while (rx000pkgDataArrary.size() != 0) {
+ RfidReaderChipData.Rx000pkgData rx000pkgData = rx000pkgDataArrary.get(0);
+ rx000pkgDataArrary.remove(0);
+ if (rx000pkgData == null) {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("InventoryRfidTask: null rx000pkgData !!!");
+ continue;
+ };
+
+ boolean match = false;
+ boolean updated = false;
+ currentTime = rx000pkgData.decodedTime;
+ int iFlag = rx000pkgData.flags;
+ String strPc = MainActivity.csLibrary4A.byteArrayToString(rx000pkgData.decodedPc);
+ if (strPc.length() != 4) {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("InventoryRfidTask: !!! rx000pkgData.Pc length = " + strPc.length());
+ continue;
+ }
+ /*int extraLength = 0;
+ if (extra1Bank != -1 && rx000pkgData.decodedData1 != null) extraLength += rx000pkgData.decodedData1.length;
+ if (extra2Bank != -1 && rx000pkgData.decodedData2 != null) extraLength += rx000pkgData.decodedData2.length;
+ if (extraLength != 0) {
+ byte[] decodedEpcNew = new byte[rx000pkgData.decodedEpc.length - extraLength];
+ System.arraycopy(rx000pkgData.decodedEpc, 0, decodedEpcNew, 0, decodedEpcNew.length);
+ rx000pkgData.decodedEpc = decodedEpcNew;
+ }*/
+ MainActivity.csLibrary4A.appendToLog("ApData: decodedEpc = " + MainActivity.csLibrary4A.byteArrayToString(rx000pkgData.decodedEpc) + ", data1,2 = " + MainActivity.csLibrary4A.byteArrayToString(rx000pkgData.decodedData1) + ", " + MainActivity.csLibrary4A.byteArrayToString(rx000pkgData.decodedData2));
+ String strEpc = MainActivity.csLibrary4A.byteArrayToString(rx000pkgData.decodedEpc);
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("HelloC: decodePc = " + strPc + ", decodedEpc = " + strEpc + ", iFlags = " + String.format("%2X", iFlag));
+ portstatus = INVALID_CODEVALUE; backport1 = INVALID_CODEVALUE; backport2 = INVALID_CODEVALUE; codeSensor = INVALID_CODEVALUE; codeRssi = INVALID_CODEVALUE; codeTempC = INVALID_CODEVALUE; brand = null;
+ String strExtra2 = null; if (rx000pkgData.decodedData2 != null) strExtra2 = MainActivity.csLibrary4A.byteArrayToString(rx000pkgData.decodedData2);
+ if (strExtra2 != null && strMdid != null) {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("HelloK: strExtra2 = " + strExtra2 + ", strMdid = " + strMdid);
+ if (strMdid.contains("E200B0")) portstatus = Integer.parseInt(strExtra2.substring(3, 4), 16);
+ }
+ String strExtra1 = null; if (rx000pkgData.decodedData1 != null) {
+ strExtra1 = MainActivity.csLibrary4A.byteArrayToString(rx000pkgData.decodedData1);
+ if (strMdid != null && strExtra1 != null && strExtra2 != null) {
+ MainActivity.csLibrary4A.appendToLog("strExtra1 = " + strExtra1 + ", strExtra2 = " + strExtra2);
+ decodeMicronData(strExtra1, strExtra2);
+ }
+ }
+ String strAddresss = strEpc;
+ String strCrc16 = null; if (rx000pkgData.decodedCrc != null) strCrc16 = MainActivity.csLibrary4A.byteArrayToString(rx000pkgData.decodedCrc);
+
+ int extra1Bank = this.extra1Bank;
+ int data1_offset = this.data1_offset;
+
+ if (strMdid != null) {
+ if (tagType == RfidReader.TagType.TAG_CTESIUS /*strMdid.indexOf("E203510") == 0*/) {
+ if (strEpc.length() == 24 && strExtra2 != null) {
+ codeTempC = MainActivity.csLibrary4A.decodeCtesiusTemperature(strEpc.substring(16, 24), strExtra2);
+ strEpc = strEpc.substring(0, 16); strAddresss = strEpc;
+ }
+ } else if (tagType == RfidReader.TagType.TAG_ASYGN /*strMdid.indexOf("E283A") == 0*/) {
+ MainActivity.csLibrary4A.appendToLog("E283A is found with extra1Bank = " + extra1Bank + ", strExtra1 = " + strExtra1 + ", extra2Bank = " + extra2Bank + ", strExtra2 = " + strExtra2);
+ if (strExtra2 != null && strExtra2.length() >= 28) codeTempC = MainActivity.csLibrary4A.decodeAsygnTemperature(strExtra2);
+ }
+ }
+
+ boolean bFastId = false; boolean bTempId = false;
+ MainActivity.csLibrary4A.appendToLog("bFastId is false with MainActivity.mDid = " + MainActivity.mDid + ", getFastId = " + MainActivity.csLibrary4A.getFastId());
+ if (MainActivity.mDid != null) {
+ if (MainActivity.mDid.indexOf("E28011") == 0) {
+ int iValue = Integer.valueOf(MainActivity.mDid.substring("E28011".length()), 16);
+ MainActivity.csLibrary4A.appendToLog(String.format("iValue = 0x%02X", iValue));
+ if ((iValue & 0x20) != 0) {
+ bFastId = true; MainActivity.csLibrary4A.appendToLog("bFastId is true");
+ }
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("HelloK: iValue = " + String.format("%02X", iValue));
+ }
+ } else if (MainActivity.csLibrary4A.getFastId() > 0) {
+ bFastId = true; MainActivity.csLibrary4A.appendToLog("bFastId is true");
+ }
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("HelloK: strMdid = " + strMdid + ", MainMdid = " + MainActivity.mDid + ", bFastId = " + bFastId);
+
+ int iPc = Integer.parseInt(strPc, 16);
+ String strXpc = null; int iSensorData = ReaderDevice.INVALID_SENSORDATA; if ((iPc & 0x0200) != 0 && strEpc != null && strEpc.length() >= 8) {
+ MainActivity.csLibrary4A.appendToLog("strPc = " + strPc + ", strEpc = " + strEpc);
+ int iXpcw1 = Integer.parseInt(strEpc.substring(0, 4), 16);
+ if ((iXpcw1 & 0x8000) != 0) {
+ strXpc = strEpc.substring(0, 8);
+ strEpc = strEpc.substring(8); strAddresss = strEpc;
+ if (strMdid != null) {
+ if (strMdid.indexOf("E280B12") == 0) {
+ int iXpcw2 = Integer.parseInt(strXpc.substring(4, 8), 16);
+ if ((iXpcw1 & 0x8100) != 0 && (iXpcw2 & 0xF000) == 0) {
+ if ((iXpcw2 & 0x0C00) == 0x0C00) {
+ //iXpcw2 |= 0x200;
+ iSensorData = iXpcw2 & 0x1FF;
+ if ((iXpcw2 & 0x200) != 0) {
+ iSensorData ^= 0x1FF; iSensorData++; iSensorData = -iSensorData;
+ //MainActivity.csLibrary4A.appendToLog(String.format("Hello123: iXpcw2 = %04X, iSensorData = %d", iXpcw2, iSensorData ));
+ }
+ }
+ }
+ }
+ }
+ } else {
+ strXpc = strEpc.substring(0, 4);
+ strEpc = strEpc.substring(4); strAddresss = strEpc;
+ }
+ }
+
+ if (bFastId) {
+ String strEpc1 = null, strTid = null;
+ boolean bValidFastId = false;
+ if (strEpc.length() > 24) {
+ strEpc1 = strEpc.substring(0, strEpc.length() - 24);
+ strTid = strEpc.substring(strEpc.length() - 24, strEpc.length());
+ if (strTid.indexOf("E28011") == 0 || strTid.indexOf("E2C011") == 0 ) {
+ strEpc = strEpc1; strAddresss = strEpc;
+ strExtra2 = strTid;
+ extra2Bank = 2;
+ data2_offset = 0;
+ bValidFastId = true;
+ }
+ }
+ if (bValidFastId == false) return;
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("HelloK: Doing IMPINJ Inventory with strMdid = " + strMdid + ", strEpc1 = " + strEpc1 + ":, strTid = " + strTid);
+ } else if (MainActivity.mDid != null) {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("HelloK: MainActivity.mDid = " + MainActivity.mDid);
+ if (MainActivity.mDid.matches("E2806894B")) {
+ if (strEpc.length() >= 24) {
+ String strEpc1 = strEpc.substring(0, strEpc.length() - 24);
+ String strTid = strEpc.substring(strEpc.length() - 24, strEpc.length());
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("HelloK: matched E2806894B with strEpc = " + strEpc + ", strEpc1 = " + strEpc1 + ", strTid = " + strTid + ", strExtra1 = " + strExtra1);
+ boolean matched = true;
+ if (strExtra1 != null) {
+ if (!(strExtra1.length() == 8 && strTid.contains(strExtra1))) matched = false;
+ }
+ if (matched) {
+ strEpc = strEpc1;
+ strAddresss = strEpc;
+ strExtra2 = strTid;
+ extra2Bank = 2;
+ data2_offset = 0;
+ }
+ /*if (strTid.contains("E2806894") == false) {
+ MainActivity.csLibrary4A.appendToLog("HelloK: Skip the record without strExtra1 E2806894: " + strEpc);
+ return;
+ }*/
+ }
+ } else if (MainActivity.mDid.matches("E2806894C") || MainActivity.mDid.matches("E2806894d")) {
+ if (strEpc.length() >= 4) {
+ String strEpc1 = strEpc.substring(0, strEpc.length() - 4);
+ String strBrand = strEpc.substring(strEpc.length() - 4, strEpc.length());
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("HelloK: matched E2806894B with strEpc = " + strEpc + ", strEpc1 = " + strEpc1 + ", strBrand = " + strBrand + ", strExtra1 = " + strExtra1);
+ boolean matched = true;
+ if (strExtra1 != null || MainActivity.mDid.matches("E2806894d")) {
+ if (!(strExtra1 != null && strExtra1.length() == 8 && strExtra1.contains("E2806894"))) {
+ matched = false;
+ /*if (MainActivity.mDid.matches("E2806894d")) {
+ MainActivity.csLibrary4A.appendToLog("HelloK: Skip the record without strExtra1 E2806894: " + strEpc);
+ return;
+ }*/
+ }
+ }
+ if (matched) {
+ strEpc = strEpc1; strAddresss = strEpc;
+ brand = strBrand;
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("HelloK: brand 1 = " + brand + ", strEpc = " + strEpc);
+ }
+ }
+ }
+ }
+
+ if (DEBUG || true) MainActivity.csLibrary4A.appendToLog("strMdid = " + strMdid + ", strTidCompared = " + strMdid + ", MainActivity.mDid = " + MainActivity.mDid + ", strExtra1 = " + strExtra1 + ", strExtra2 = " + strExtra2);
+ if (strMdid != null) {
+ String strTidCompared = strMdid;
+ if (strTidCompared.indexOf("E28011") == 0) {
+ int iValue = Integer.valueOf(MainActivity.mDid.substring("E28011".length()), 16);
+ MainActivity.csLibrary4A.appendToLog(String.format("iValue = 0x%02X", iValue));
+ if ((iValue & 0x40) != 0) strTidCompared = "E2C011";
+ else if ((iValue & 0x80) != 0) strTidCompared = "E280117";
+ else strTidCompared = "E28011";
+ }
+ MainActivity.csLibrary4A.appendToLog("strTidCompared = " + strTidCompared);
+ if (strTidCompared.matches("E28011")) { }
+ else if (strTidCompared.matches("E2806894") && MainActivity.mDid.matches("E2806894C")) { }
+ else if (strTidCompared.matches("E281D")) { }
+ else if (strTidCompared.matches("E282402")) { }
+ else if (strTidCompared.matches("E282403")) { }
+ else if (strTidCompared.matches("E282405")) { }
+ else { //if (strMdid.matches("E280B0"))
+ boolean bMatched = false;
+ if (strExtra1 != null && strExtra1.indexOf(strTidCompared) == 0) {
+ bMatched = true; if (DEBUG) MainActivity.csLibrary4A.appendToLog("strExtra1 contains strTidCompared");
+ } else if (strExtra2 != null && strExtra2.indexOf(strTidCompared) == 0) {
+ bMatched = true; if (DEBUG) MainActivity.csLibrary4A.appendToLog("strEXTRA2 contains strTidCompared");
+ }
+ MainActivity.csLibrary4A.appendToLog("bMatched = " + bMatched);
+ if (bMatched == false) return;
+ }
+ }
+
+ rssi = rx000pkgData.decodedRssi;
+ phase = rx000pkgData.decodedPhase;
+ chidx = rx000pkgData.decodedChidx;
+ port = rx000pkgData.decodedPort;
+
+ timeMillis = System.currentTimeMillis();
+
+ double rssiGeiger = rssi;
+ if (MainActivity.csLibrary4A.getRssiDisplaySetting() != 0)
+ rssiGeiger -= MainActivity.csLibrary4A.dBuV_dBm_constant;
+ if (geigerTagRssiView != null)
+ geigerTagRssiView.setText(String.format("%.1f", rssiGeiger));
+ if (geigerTagGotView != null) geigerTagGotView.setText(strEpc);
+
+ if (tagsList == null) {
+ if (strEpc.matches(strEpcOld)) {
+ match = true;
+ updated = true;
+ }
+ } else if (readerListAdapter.getSelectDupElim()) {
+ ReaderDevice readerDevice = null;
+ int iMatchItem = -1;
+ if (false) {
+ int index = Collections.binarySearch(MainActivity.sharedObjects.tagsIndexList, new SharedObjects.TagsIndex(strAddresss, 0));
+ if (index >= 0) {
+ iMatchItem = MainActivity.sharedObjects.tagsIndexList.size() - 1 - MainActivity.sharedObjects.tagsIndexList.get(index).getPosition();
+ }
+ } else {
+ String strCompare = null;
+ if (extra1Bank == 2) {
+ strCompare = strExtra1; //MainActivity.csLibrary4A.appendToLog("1strExtra = " + strExtra1 + ", " + readerDevice.getTid() + ", " + readerDevice.getTid().matches(strCompare));
+ } else if (extra2Bank == 2) {
+ strCompare = strExtra2; //MainActivity.csLibrary4A.appendToLog("2strExtra = " + strExtra2 + ", " + readerDevice.getTid() + ", " + readerDevice.getTid().matches(strCompare));
+ }
+ for (int i = 0; i < tagsList.size(); i++) {
+ //MainActivity.csLibrary4A.appendToLog("strEpc = " + strEpc + ", tagsList.get(" + i + ").getAdddress = " + tagsList.get(i).getAddress());
+ if (strEpc == null || tagsList.get(i).getAddress() == null) { }
+ else if (strEpc.matches(tagsList.get(i).getAddress())) {
+ boolean bTidMatched = true;
+ if (strCompare != null && tagsList.get(i).getTid() != null) bTidMatched = tagsList.get(i).getTid().matches(strCompare);
+ if (bTidMatched) {
+ iMatchItem = i;
+ break;
+ }
+ }
+ }
+ }
+ MainActivity.csLibrary4A.appendToLog("Doing duplicate elimination with iMatchItem = " + iMatchItem);
+ if (iMatchItem >= 0) {
+ readerDevice = tagsList.get(iMatchItem);
+ int count = readerDevice.getCount();
+ count++;
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("HelloK: updated Epc = " + readerDevice.getAddress() + ", brand = " + brand);
+ readerDevice.setCount(count);
+ readerDevice.setXpc(strXpc);
+ readerDevice.setRssi(rssi);
+ readerDevice.setPhase(phase);
+ readerDevice.setChannel(chidx);
+ readerDevice.setPort(port);
+ readerDevice.setStatus(portstatus);
+ readerDevice.setBackport1((backport1));
+ readerDevice.setBackport2(backport2);
+ readerDevice.setCodeSensor(codeSensor);
+ readerDevice.setCodeRssi(codeRssi);
+ readerDevice.setBrand(brand);
+ readerDevice.setCodeTempC(codeTempC);
+ readerDevice.setSensorData(iSensorData);
+ if (strExtra1 != null) readerDevice.setExtra1(strExtra1, extra1Bank, data1_offset);
+ else if (readerDevice.getstrExtra1() != null) {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("HelloK: no null replacement of StrExtra1");
+ }
+ if (strExtra2 != null) readerDevice.setExtra2(strExtra2, extra2Bank, data2_offset);
+ else if (readerDevice.getstrExtra2() != null) {
+ MainActivity.csLibrary4A.appendToLog("HelloK: no null replacement of StrExtra2");
+ }
+ tagsList.set(iMatchItem, readerDevice);
+ match = true;
+ updated = true;
+ }
+ }
+ if (ALLOW_WEDGE) MainActivity.sharedObjects.serviceArrayList.add(strEpc);
+
+ boolean bAddDevice = true; String strValue = null;
+ MainActivity.csLibrary4A.appendToLog("bProtectOnly = " + bProtectOnly);
+ if (bSgtinOnly) {
+ strValue = MainActivity.csLibrary4A.getUpcSerial(strEpc);
+ MainActivity.csLibrary4A.appendToLog("bSgtinOnly = " + bSgtinOnly + ", strValue = " + (strValue == null ? "null" : strValue));
+ if (strValue == null) bAddDevice = false;
+ } else if (bProtectOnly) {
+ bAddDevice = false;
+ if (strExtra1 != null) {
+ strValue = strExtra1.substring(strExtra1.length() - 1);
+ int iValue = Integer.parseInt(strValue, 16);
+ MainActivity.csLibrary4A.appendToLog("bProtectOnly = " + bProtectOnly + ", strExtra1 = " + (strExtra1 == null ? "null" : strExtra1) + ", iValue = " + iValue);
+ if ((iValue & 0x02) != 0) bAddDevice = true;
+ } else MainActivity.csLibrary4A.appendToLog("NULL strExtra1");
+ }
+ if (bAddDevice == false) { }
+ else if (match == false) {
+ if (tagsList == null) {
+ strEpcOld = strEpc;
+ updated = true;
+ } else {
+ MainActivity.csLibrary4A.appendToLog("HelloK: New Epc = " + strEpc + ", brand = " + brand);
+ ReaderDevice readerDevice = new ReaderDevice("", strEpc, false, null,
+ strPc, strXpc, strCrc16, strMdid,
+ strExtra1, extra1Bank, data1_offset,
+ strExtra2, extra2Bank, data2_offset,
+ new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS").format(new Date()), new SimpleDateFormat("z").format(new Date()).replaceAll("GMT", ""),
+ MainActivity.mSensorConnector.mLocationDevice.getLocation(), MainActivity.mSensorConnector.mSensorDevice.getEcompass(),
+ 1, rssi, phase, chidx, port, portstatus, backport1, backport2, codeSensor, codeRssi, codeTempC, brand, iSensorData);
+ if (bSgtinOnly && strValue != null) readerDevice.setUpcSerial(strValue);
+ if (strMdid != null) {
+ if (strMdid.indexOf("E282402") == 0) readerDevice.setCodeSensorMax(0x1F);
+ else readerDevice.setCodeSensorMax(0x1FF);
+ }
+ if (bAdd2End) tagsList.add(readerDevice);
+ else tagsList.add(0, readerDevice);
+ SharedObjects.TagsIndex tagsIndex = new SharedObjects.TagsIndex(strAddresss, tagsList.size() - 1); MainActivity.sharedObjects.tagsIndexList.add(tagsIndex); Collections.sort(MainActivity.sharedObjects.tagsIndexList);
+ MainActivity.csLibrary4A.appendToLog("openServer: serverConnectValid is " + serverConnectValid);
+ if (serverConnectValid && ALLOW_RTSAVE && true) {
+ try {
+// saveExternalTask = new SaveList2ExternalTask();
+// saveExternalTask.openServer();
+ String msgOutput = saveExternalTask.createJSON(null, readerDevice).toString(); MainActivity.csLibrary4A.appendToLog("Json = " + msgOutput);
+ saveExternalTask.write2Server(msgOutput);
+ MainActivity.csLibrary4A.appendToLog("openServer: write2Server data = " + msgOutput);
+
+ // saveExternalTask.closeServer();
+ MainActivity.csLibrary4A.appendToLog("write2Server is done");
+ } catch (Exception ex) {
+ MainActivity.csLibrary4A.appendToLog("write2Server has Exception");
+ }
+ }
+ }
+ yield++; yield4RateCount++;
+ updated = true;
+ requestNewSound = true; requestNewVibrate = true;
+ requestSound = true;
+ }
+ if (updated && bAddDevice) {
+ total++;
+ allTotal++;
+ }
+ }
+ }
+ if (++requestSoundCount >= MainActivity.csLibrary4A.getBeepCount()) {
+ requestSoundCount = 0;
+ requestSound = true;
+ }
+ if (requestSound && requestNewSound) requestSoundCount = 0;
+ if (readerListAdapter != null) readerListAdapter.notifyDataSetChanged();
+ if (invalidDisplay) {
+ if (rfidYieldView != null) rfidYieldView.setText(String.valueOf(total) + "," + String.valueOf(MainActivity.csLibrary4A.getValidata()));
+ if (rfidRateView != null) rfidRateView.setText(String.valueOf(MainActivity.csLibrary4A.getInvalidata()) + "," + String.valueOf(MainActivity.csLibrary4A.getInvalidUpdata()));
+ } else {
+ String stringTemp = "Unique:" + String.valueOf(yield);
+ stringTemp += "\nTotal:" + String.valueOf(allTotal) + "\n";
+ if (rfidYieldView != null) rfidYieldView.setText(stringTemp);
+ if (total != 0 && currentTime - firstTimeOld > 500) {
+ if (firstTimeOld == 0) firstTimeOld = firstTime;
+ if (totalOld == 0) totalOld = total;
+
+ String strRate = "Error:" + String.valueOf(MainActivity.csLibrary4A.getInvalidata()) + "/";
+ if (true) {
+ float fErrorRate = (float) MainActivity.csLibrary4A.getInvalidata() / ((float) MainActivity.csLibrary4A.getValidata() + (float) MainActivity.csLibrary4A.getInvalidata()) * 100;
+ strRate += String.valueOf(MainActivity.csLibrary4A.getValidata()) + "/" + String.valueOf((int) fErrorRate) + "%";
+ } else if (true) {
+ strRate += String.valueOf(MainActivity.csLibrary4A.getInvalidUpdata()) + "/" + String.valueOf(MainActivity.csLibrary4A.getValidata());
+ }
+
+ strRate += "\nRate/New:";
+ if (firstTimeOld != 0) {
+ long tagRate = MainActivity.csLibrary4A.getTagRate();
+ long tagRate2 = -1;
+ if (currentTime > firstTimeOld) tagRate2 = totalOld * 1000 / (currentTime - firstTimeOld);
+ if (tagRate >= 0 || bGotTagRate) {
+ bGotTagRate = true;
+ if (true) strRate += (tagRate != -1 ? String.valueOf(tagRate) : "___");
+ else strRate += (tagRate != -1 ? String.valueOf(tagRate) : "___") + "/" + String.valueOf(tagRate2);
+ strRate += "/" + String.valueOf(yieldRate);
+ } else {
+ if (lastTime == 0) {
+ tagRate = MainActivity.csLibrary4A.getStreamInRate() / 17;
+ //strRate += "rAte";
+ } else if (currentTime > firstTimeOld) {
+ tagRate = totalOld * 1000 / (currentTime - firstTimeOld);
+ //strRate += "Rate";
+ }
+ strRate += String.valueOf(tagRate) + "/" + String.valueOf(yieldRate);
+ }
+ }
+
+ if (rfidRateView != null) rfidRateView.setText(strRate);
+ //if (lastTime - firstTime > 1000) {
+ firstTimeOld = currentTime;
+ totalOld = total;
+ total = 0;
+ //}
+ }
+ }
+ if (false) MainActivity.csLibrary4A.appendToLogView("playerN = " + (playerN == null ? "Null" : "Valid") + ", playerO = " + (playerO == null ? "Null" : "Valid"));
+ if (playerN != null && playerO != null) {
+ if (false) MainActivity.csLibrary4A.appendToLogView("requestSound = " + requestSound + ", bStartBeepWaiting = " + bStartBeepWaiting + ", Op=" + playerO.isPlaying() + ", Np=" + playerN.isPlaying());
+ if (requestSound && playerO.isPlaying() == false && playerN.isPlaying() == false) {
+ if (true) {
+ if (bStartBeepWaiting == false) {
+ bStartBeepWaiting = true;
+ if (false) MainActivity.csLibrary4A.appendToLogView("Going to play old song");
+ handler.postDelayed(runnableStartBeep, 250);
+ }
+ if (MainActivity.csLibrary4A.getInventoryVibrate()) {
+ boolean validVibrate0 = false, validVibrate = false;
+ if (MainActivity.csLibrary4A.getVibrateModeSetting() == 0) {
+ if (requestNewVibrate) validVibrate0 = true;
+ } else if (bValidVibrateNewAll == false) validVibrate0 = true;
+ requestNewVibrate = false;
+
+ if (validVibrate0) {
+ if (bStartVibrateWaiting == false) {
+ validVibrate = true;
+ } else if (bUseVibrateMode0 == false) {
+ handler.removeCallbacks(runnableStartVibrate); int timeout = MainActivity.csLibrary4A.getVibrateWindow() * 1000;
+ handler.postDelayed(runnableStartVibrate, MainActivity.csLibrary4A.getVibrateWindow() * 1000);
+ }
+ }
+
+ if (validVibrate) {
+ MainActivity.csLibrary4A.appendToLog("setVibrateOn E with bUseVibrateMode0 as " + bUseVibrateMode0);
+ if (bUseVibrateMode0) MainActivity.csLibrary4A.setVibrateOn(1);
+ else MainActivity.csLibrary4A.setVibrateOn(2);
+ bStartVibrateWaiting = true; int timeout = MainActivity.csLibrary4A.getVibrateWindow() * 1000;
+ handler.postDelayed(runnableStartVibrate, MainActivity.csLibrary4A.getVibrateWindow() * 1000);
+ }
+ }
+ } else {
+ requestSound = false;
+ if (requestNewSound) {
+ requestNewSound = false;
+ playerN.start();
+ } else {
+ playerO.start();
+ }
+ }
+ }
+ }
+ }
+ }
+
+ boolean bStartBeepWaiting = false;
+ Runnable runnableStartBeep = new Runnable() {
+ @Override
+ public void run() {
+ if (false) MainActivity.csLibrary4A.appendToLogView("Playing old song");
+ bStartBeepWaiting = false;
+ requestSound = false;
+ if (requestNewSound) {
+ requestNewSound = false;
+ playerN.start(); //playerN.setVolume(300, 300);
+ } else {
+ playerO.start(); //playerO.setVolume(30, 30);
+ }
+ }
+ };
+
+ boolean bStartVibrateWaiting = false;
+ Runnable runnableStartVibrate = new Runnable() {
+ @Override
+ public void run() {
+ bStartVibrateWaiting = false;
+ MainActivity.csLibrary4A.appendToLog("setVibrateOn F1 with bUseVibrateMode0 as " + bUseVibrateMode0);
+ if (bUseVibrateMode0 == false) MainActivity.csLibrary4A.setVibrateOn(0);
+ }
+ };
+
+ @Override
+ protected void onCancelled() {
+ super.onCancelled();
+ if (DEBUG || true) MainActivity.csLibrary4A.appendToLogView("InventoryRfidTask.InventoryRfidTask.onCancelled()");
+
+ DeviceConnectTask4InventoryEnding(taskCancelReason);
+ }
+
+ @Override
+ protected void onPostExecute(String result) {
+ if (DEBUG || true) MainActivity.csLibrary4A.appendToLogView("InventoryRfidTask.InventoryRfidTask.onPostExecute(): " + result);
+
+ DeviceConnectTask4InventoryEnding(taskCancelReason);
+ }
+
+ public InventoryRfidTask() {
+ inventoryHandler_setup();
+ }
+ public InventoryRfidTask(Context context, int extra1Bank, int extra2Bank, int data1_count, int data2_count, int data1_offset, int data2_offset,
+ boolean invalidRequest, boolean beepEnable,
+ ArrayList tagsList, ReaderListAdapter readerListAdapter, TextView geigerTagRssiView,
+ RfidReader.TagType tagType, String strMdid,
+ TextView rfidRunTime, TextView geigerTagGotView, TextView rfidVoltageLevel,
+ TextView rfidYieldView, Button button, TextView rfidRateView) {
+ this.context = context;
+ this.extra1Bank = extra1Bank;
+ this.extra2Bank = extra2Bank;
+ this.data1_count = data1_count;
+ this.data2_count = data2_count;
+ this.data1_offset = data1_offset;
+ this.data2_offset = data2_offset;
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("data1_count = " + data1_count + ", data2_count = " + data2_count + ", extra1Bank = " + extra1Bank + ", extra2Bank = " + extra2Bank);
+
+ this.invalidRequest = invalidRequest;
+
+ this.geigerTagRssiView = geigerTagRssiView;
+ this.tagsList = tagsList;
+ this.readerListAdapter = readerListAdapter;
+ this.tagType = tagType;
+ this.strMdid = strMdid; MainActivity.csLibrary4A.appendToLog("HelloK: strMdid = " + strMdid);
+
+ this.rfidRunTime = rfidRunTime;
+ this.geigerTagGotView = geigerTagGotView;
+ this.rfidVoltageLevel = rfidVoltageLevel;
+ this.rfidYieldView = rfidYieldView;
+ this.button = button;
+ this.rfidRateView = rfidRateView;
+ this.beepEnable = beepEnable;
+
+ MainActivity.csLibrary4A.appendToLogView("going to create playerO and playerN with beepEnable = " + beepEnable);
+ if (tagsList != null && readerListAdapter != null && beepEnable) {
+ playerO = MainActivity.sharedObjects.playerO;
+ playerN = MainActivity.sharedObjects.playerN;
+ MainActivity.csLibrary4A.appendToLogView("playerO and playerN is created");
+ }
+ inventoryHandler_setup();
+ }
+
+ boolean popRequest = false; Toast mytoast;
+ void DeviceConnectTask4InventoryEnding(TaskCancelRReason taskCancelReason) {
+ MainActivity.csLibrary4A.appendToLogView("CANCELLING: TaskEnding sent abortOperation again with taskCancelReason = " + taskCancelReason.toString());
+ MainActivity.csLibrary4A.abortOperation(); //added in case previous command end is received with inventory stopped
+ MainActivity.csLibrary4A.appendToLog("serverConnectValid = " + serverConnectValid);
+ if (serverConnectValid && ALLOW_RTSAVE) {
+ if (saveExternalTask.closeServer()) MainActivity.csLibrary4A.appendToLog("closeServer is done");
+ else MainActivity.csLibrary4A.appendToLog("closeServer has Exception");
+ }
+ MainActivity.csLibrary4A.appendToLog("INVENDING: Ending with endingRequest = " + endingRequest);
+ if (MainActivity.mContext == null) return;
+ if (readerListAdapter != null) readerListAdapter.notifyDataSetChanged();
+ if (mytoast != null) mytoast.cancel();
+ if (endingRequest) {
+ switch (taskCancelReason) {
+ case NULL:
+ mytoast = Toast.makeText(MainActivity.mContext, R.string.toast_abort_by_END, Toast.LENGTH_SHORT);
+ break;
+ case STOP:
+ mytoast = Toast.makeText(MainActivity.mContext, R.string.toast_abort_by_STOP, Toast.LENGTH_SHORT);
+ break;
+ case BUTTON_RELEASE:
+ if (false) mytoast = Toast.makeText(MainActivity.mContext, R.string.toast_abort_by_BUTTON, Toast.LENGTH_SHORT);
+ break;
+ case TIMEOUT:
+ mytoast = Toast.makeText(MainActivity.mContext, R.string.toast_abort_by_TIMEOUT, Toast.LENGTH_SHORT);
+ break;
+ case RFID_RESET:
+ mytoast = Toast.makeText(MainActivity.mContext, R.string.toast_abort_by_RFIDRESET, Toast.LENGTH_SHORT);
+ break;
+ case INVALD_REQUEST:
+ mytoast = Toast.makeText(MainActivity.mContext, R.string.toast_invalid_sendHostRequest, Toast.LENGTH_SHORT);
+ break;
+ default:
+ mytoast = Toast.makeText(MainActivity.mContext, ("Finish reason as " + taskCancelReason.toString()), Toast.LENGTH_SHORT);
+ break;
+ }
+ MainActivity.csLibrary4A.appendToLog("INVENDING: Toasting");
+ if (mytoast != null) mytoast.show();
+ }
+ if (button != null) button.setText("Start");
+ MainActivity.csLibrary4A.appendToLog("InventoryRfidTask.DeviceConnectTask4InventoryEnding set runningInventoryRfidTask as false ");
+ MainActivity.sharedObjects.runningInventoryRfidTask = false;
+ if (endingMessaage != null) {
+ CustomPopupWindow customPopupWindow = new CustomPopupWindow(MainActivity.mContext);
+ customPopupWindow.popupStart(endingMessaage, false);
+ }
+ MainActivity.mSensorConnector.mLocationDevice.turnOn(false);
+ MainActivity.mSensorConnector.mSensorDevice.turnOn(false);
+ MainActivity.csLibrary4A.appendToLog("setVibrateOn F 0");
+ MainActivity.csLibrary4A.setVibrateOn(0);
+ }
+
+ String decodeMicronData(String strActData, String strCalData) {
+ int iTag35 = -1;
+ if (strMdid.contains("E282402")) iTag35 = 2;
+ else if (strMdid.contains("E282403")) iTag35 = 3;
+ else if (strMdid.contains("E282405")) iTag35 = 5;
+ if (iTag35 < 2) return "";
+
+ if (iTag35 == 5) {
+ backport1 = Integer.parseInt(strActData.substring(0, 4), 16); backport2 = Integer.parseInt(strActData.substring(4, 8), 16);
+ MainActivity.csLibrary4A.appendToLog("backport1 = " + backport1 + ", backport2 = " + backport2);
+ strActData = strActData.substring(8);
+ }
+ int iSensorCode = Integer.parseInt(strActData.substring(0,4), 16); iSensorCode &= 0x1FF; if (iTag35 == 2) iSensorCode &= 0x1F; codeSensor = iSensorCode;
+ int iRssi;
+ String strRetValue = "";
+ if (iTag35 == 2) {
+ iRssi = Integer.parseInt(strCalData.substring(0,4), 16); iRssi &= 0x1F; codeRssi = iRssi;
+ } else if (iTag35 == 3) {
+ iRssi = Integer.parseInt(strActData.substring(4,8), 16); iRssi &= 0x1F; codeRssi = iRssi;
+
+ if (true) {
+ if (strActData.length() < 8) return null;
+ codeTempC = MainActivity.csLibrary4A.decodeMicronTemperature(iTag35, strActData.substring(8, 12), strCalData);
+ } else {
+ int calCode1, calTemp1, calCode2, calTemp2, calVer = -1;
+ if (strCalData == null) return null;
+ if (strCalData.length() < 16) return null;
+ int crc = Integer.parseInt(strCalData.substring(0, 4), 16);
+ calCode1 = Integer.parseInt(strCalData.substring(4, 7), 16);
+ calTemp1 = Integer.parseInt(strCalData.substring(7, 10), 16);
+ calTemp1 >>= 1;
+ calCode2 = Integer.parseInt(strCalData.substring(9, 13), 16);
+ calCode2 >>= 1;
+ calCode2 &= 0xFFF;
+ calTemp2 = Integer.parseInt(strCalData.substring(12, 16), 16);
+ calTemp2 >>= 2;
+ calTemp2 &= 0x7FF;
+ calVer = Integer.parseInt(strCalData.substring(15, 16), 16);
+ calVer &= 0x3;
+
+ if (strActData == null) return null;
+ if (strActData.length() < 8) return null;
+
+ float fTemperature = Integer.parseInt(strActData.substring(8, 12), 16);
+ fTemperature = ((float) calTemp2 - (float) calTemp1) * (fTemperature - (float) calCode1);
+ fTemperature /= ((float) (calCode2) - (float) calCode1);
+ fTemperature += (float) calTemp1;
+ fTemperature -= 800;
+ fTemperature /= 10;
+ codeTempC = fTemperature;
+ }
+ } else if (iTag35 == 5) {
+ iRssi = Integer.parseInt(strActData.substring(4,8), 16); iRssi &= 0x1F; codeRssi = iRssi;
+
+ if (true) {
+ codeTempC = MainActivity.csLibrary4A.decodeMicronTemperature(iTag35, strActData.substring(8, 12), strCalData);
+ } else {
+ int iTemp;
+ float calCode2 = Integer.parseInt(strCalData.substring(0, 4), 16);
+ calCode2 /= 16;
+ iTemp = Integer.parseInt(strCalData.substring(4, 8), 16);
+ iTemp &= 0x7FF;
+ float calTemp2 = iTemp;
+ calTemp2 -= 600;
+ calTemp2 /= 10;
+ float calCode1 = Integer.parseInt(strCalData.substring(8, 12), 16);
+ calCode1 /= 16;
+ iTemp = Integer.parseInt(strCalData.substring(12, 16), 16);
+ iTemp &= 0x7FF;
+ float calTemp1 = iTemp;
+ calTemp1 -= 600;
+ calTemp1 /= 10;
+
+ float fTemperature = Integer.parseInt(strActData.substring(8, 12), 16);
+ fTemperature -= calCode1;
+ fTemperature *= (calTemp2 - calTemp1);
+ fTemperature /= (calCode2 - calCode1);
+ fTemperature += calTemp1;
+ codeTempC = fTemperature;
+ }
+ }
+ return "";
+ }
+}
+
+
+
+package com.csl.cs710ademoapp;
+
+import static com.csl.cslibrary4a.RfidReader.TagType.TAG_ALIEN;
+import static com.csl.cslibrary4a.RfidReader.TagType.TAG_ASYGN;
+import static com.csl.cslibrary4a.RfidReader.TagType.TAG_CTESIUS;
+import static com.csl.cslibrary4a.RfidReader.TagType.TAG_EM_BAP;
+
+import android.content.Context;
+import android.content.Intent;
+import android.net.Uri;
+import android.os.Bundle;
+import android.os.Handler;
+import android.util.Log;
+import android.view.Gravity;
+import android.view.View;
+import android.widget.AdapterView;
+import android.widget.ListView;
+import android.widget.TextView;
+import android.widget.Toast;
+
+import androidx.activity.EdgeToEdge;
+import androidx.appcompat.app.AppCompatActivity;
+import androidx.drawerlayout.widget.DrawerLayout;
+import androidx.fragment.app.Fragment;
+import androidx.fragment.app.FragmentManager;
+
+import com.csl.cs710ademoapp.DrawerListContent.DrawerPositions;
+import com.csl.cs710ademoapp.adapters.DrawerListAdapter;
+import com.csl.cs710ademoapp.fragments.AboutFragment;
+import com.csl.cs710ademoapp.fragments.AccessReadWriteFragment;
+import com.csl.cs710ademoapp.fragments.AccessReadWriteUserFragment;
+import com.csl.cs710ademoapp.fragments.AccessRegisterFragment;
+import com.csl.cs710ademoapp.fragments.AccessSecurityFragment;
+import com.csl.cs710ademoapp.fragments.AuraSenseFragment;
+import com.csl.cs710ademoapp.fragments.AxzonSelectorFragment;
+import com.csl.cs710ademoapp.fragments.ColdChainFragment;
+import com.csl.cs710ademoapp.fragments.ConnectionFragment;
+import com.csl.cs710ademoapp.fragments.DirectWedgeFragment;
+import com.csl.cs710ademoapp.fragments.FdmicroFragment;
+import com.csl.cs710ademoapp.fragments.HomeFragment;
+import com.csl.cs710ademoapp.fragments.HomeSpecialFragment;
+import com.csl.cs710ademoapp.fragments.ImpinjFragment;
+import com.csl.cs710ademoapp.fragments.ImpinjM775Fragment;
+import com.csl.cs710ademoapp.fragments.InventoryFragment;
+import com.csl.cs710ademoapp.fragments.InventoryRfidSearchFragment;
+import com.csl.cs710ademoapp.fragments.InventoryRfidSimpleFragment;
+import com.csl.cs710ademoapp.fragments.InventoryRfidiMultiFragment;
+import com.csl.cs710ademoapp.fragments.KilowayFragment;
+import com.csl.cs710ademoapp.fragments.LongjingFragment;
+import com.csl.cs710ademoapp.fragments.SettingFilterFragment;
+import com.csl.cs710ademoapp.fragments.SettingFragment;
+import com.csl.cs710ademoapp.fragments.TestFragment;
+import com.csl.cs710ademoapp.fragments.Ucode8Fragment;
+import com.csl.cs710ademoapp.fragments.UcodeFragment;
+import com.csl.cslibrary4a.CsLibrary4A;
+import com.csl.cslibrary4a.ReaderDevice;
+import com.csl.cslibrary4a.RfidReader;
+
+public class MainActivity extends AppCompatActivity {
+ final boolean DEBUG = false; final String TAG = "Hello";
+ public static boolean foregroundServiceEnable = false;
+ public static boolean activityActive = false;
+ public static DrawerPositions drawerPositionsDefault = DrawerPositions.MAIN;
+ public static int powerLevelMax = 320;
+
+ //Tag to identify the currently displayed fragment
+ Fragment fragment = null;
+ protected static final String TAG_CONTENT_FRAGMENT = "ContentFragment";
+ public static boolean isHomeFragment = false;
+
+ public static TextView mLogView;
+ private DrawerLayout mDrawerLayout;
+ private ListView mDrawerList;
+ private CharSequence mTitle;
+
+ public static Context mContext;
+ public static CsLibrary4A csLibrary4A;
+ public static SharedObjects sharedObjects;
+ public static SensorConnector mSensorConnector;
+ public static ReaderDevice tagSelected;
+
+ Handler mHandler = new Handler();
+
+ public static String mDid; public static int selectHold; public static int selectFor;
+ public static RfidReader.TagType tagType;
+ public static class Config {
+ public String configPassword, configPower, config0, config1, config2, config3;
+ };
+ public static Config config = new Config();
+
+ @Override
+ protected void onCreate(Bundle savedInstanceState) {
+ if (DEBUG) {
+ if (savedInstanceState == null) Log.i(TAG, "MainActivity.onCreate: NULL savedInstanceState");
+ else Log.i(TAG, "MainActivity.onCreate: VALID savedInstanceState");
+ }
+ Log.i("Hello", "PackageName is " + getPackageName());
+ if (getPackageName().matches("com.csl.updwedgeservice")) setContentView(R.layout.activity_main1);
+ else setContentView(R.layout.activity_main);
+
+ mTitle = getTitle();
+ mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
+ mDrawerList = (ListView) findViewById(R.id.left_drawer);
+
+ mLogView = (TextView) findViewById(R.id.log_view);
+
+ // set up the drawer's list view with items and click listener
+ mDrawerList.setAdapter(new DrawerListAdapter(this, R.layout.drawer_list_item, DrawerListContent.ITEMS));
+ mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
+
+ mContext = this;
+ sharedObjects = new SharedObjects(mContext);
+ csLibrary4A = new CsLibrary4A(mContext, mLogView);
+ mSensorConnector = new SensorConnector(mContext);
+
+ EdgeToEdge.enable(this);
+ super.onCreate(savedInstanceState);
+ if (savedInstanceState == null) selectItem(drawerPositionsDefault);
+ if (true) Log.i(TAG, "MainActivity.onCreate.onCreate: END");
+
+ getSupportActionBar().hide();
+ }
+
+ @Override
+ protected void onRestart() {
+ super.onRestart();
+ MainActivity.csLibrary4A.connect(null);
+ if (DEBUG) csLibrary4A.appendToLog("MainActivity.onRestart()");
+ }
+
+ @Override
+ protected void onStart() {
+ super.onStart();
+ if (DEBUG) csLibrary4A.appendToLog("MainActivity.onStart()");
+ }
+
+ @Override
+ protected void onResume() {
+ super.onResume();
+ activityActive = true; wedged = false;
+ if (DEBUG) csLibrary4A.appendToLog("MainActivity.onResume()");
+ }
+
+ @Override
+ protected void onPause() {
+ if (DEBUG) csLibrary4A.appendToLog("MainActivity.onPause()");
+ activityActive = false;
+ super.onPause();
+ }
+
+ @Override
+ protected void onStop() {
+ if (DEBUG) csLibrary4A.appendToLog("MainActivity.onStop()");
+ super.onStop();
+ }
+
+ @Override
+ protected void onDestroy() {
+ if (DEBUG) csLibrary4A.appendToLog("MainActivity.onDestroy()");
+ if (true) { csLibrary4A.disconnect(true); }
+ csLibrary4A = null;
+ super.onDestroy();
+ }
+
+ boolean configureDisplaying = false;
+ Toast configureToast;
+ private final Runnable configureRunnable = new Runnable() {
+ @Override
+ public void run() {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("AAA: mrfidToWriteSize = " + csLibrary4A.mrfidToWriteSize());
+ if (csLibrary4A.mrfidToWriteSize() != 0) {
+ MainActivity.csLibrary4A.mrfidToWritePrint();
+ configureDisplaying = true;
+ mHandler.postDelayed(configureRunnable, 500);
+ } else {
+ configureDisplaying = false;
+ progressDialog.dismiss();
+ }
+ }
+ };
+
+ CustomProgressDialog progressDialog;
+ private void selectItem(DrawerPositions position) {
+ if (DEBUG) Log.i(TAG, "MainActivity.selectItem: position = " + position);
+ if (position != DrawerPositions.MAIN
+ && position != DrawerPositions.SPECIAL
+ && position != DrawerPositions.ABOUT
+ && position != DrawerPositions.CONNECT
+ && position != DrawerPositions.DIRECTWEDGE && csLibrary4A.isBleConnected() == false) {
+ Toast.makeText(MainActivity.mContext, "Bluetooth Disconnected. Please Connect.", Toast.LENGTH_SHORT).show();
+ return;
+ }
+ switch (position) {
+ case MAIN:
+ fragment = new HomeFragment();
+ break;
+ case SPECIAL:
+ fragment = new HomeSpecialFragment();
+ break;
+
+ case ABOUT:
+ //fragment = new Test1Fragment();
+ fragment = new AboutFragment();
+ break;
+ case CONNECT:
+ fragment = new ConnectionFragment();
+ break;
+ case INVENTORY:
+ fragment = new InventoryFragment();
+ break;
+ case SEARCH:
+ fragment = new InventoryRfidSearchFragment(false);
+ break;
+ case MULTIBANK:
+ fragment = InventoryRfidiMultiFragment.newInstance(true, null, null);
+ break;
+ case SIMINVENTORY:
+ fragment = InventoryRfidSimpleFragment.newInstance(false, null);
+ break;
+ case SETTING:
+ fragment = new SettingFragment();
+ break;
+ case FILTER:
+ fragment = new SettingFilterFragment();
+ break;
+ case READWRITE:
+ fragment = new AccessReadWriteFragment();
+ break;
+ case SECURITY:
+ fragment = new AccessSecurityFragment();
+ break;
+
+ case IMPINVENTORY:
+ fragment = new ImpinjFragment();
+ break;
+ case IMP775:
+ fragment = new ImpinjM775Fragment();
+ break;
+ case ALIEN:
+ fragment = InventoryRfidiMultiFragment.newInstance(true, TAG_ALIEN, "E2003");
+ break;
+ case UCODE8:
+ fragment = new Ucode8Fragment();
+ break;
+ case UCODEDNA:
+ fragment = new UcodeFragment();
+ break;
+ case BAPCARD:
+ fragment = InventoryRfidiMultiFragment.newInstance(true, TAG_EM_BAP, "E200B0");
+ break;
+ case COLDCHAIN:
+ fragment = new ColdChainFragment();
+ break;
+ case AURASENSE:
+ fragment = new AuraSenseFragment();
+ break;
+ case KILOWAY:
+ fragment = new KilowayFragment();
+ break;
+ case LONGJING:
+ fragment = new LongjingFragment();
+ break;
+ case AXZON:
+ fragment = AxzonSelectorFragment.newInstance(true);
+ break;
+ case RFMICRON:
+ fragment = AxzonSelectorFragment.newInstance(false);
+ break;
+ case FDMICRO:
+ fragment = new FdmicroFragment();
+ break;
+ case CTESIUS:
+ fragment = InventoryRfidiMultiFragment.newInstance(true, TAG_CTESIUS, "E203510");
+ break;
+ case ASYGNTAG:
+ fragment = InventoryRfidiMultiFragment.newInstance(true, TAG_ASYGN, "E283A");
+ break;
+
+ case REGISTER:
+ fragment = new AccessRegisterFragment();
+ break;
+ case READWRITEUSER:
+ fragment = new AccessReadWriteUserFragment();
+ break;
+ case WEDGE:
+ case DIRECTWEDGE:
+ fragment = new DirectWedgeFragment();
+ break;
+ case BLANK:
+ fragment = new TestFragment();
+ break;
+ }
+
+ FragmentManager fragmentManager = getSupportFragmentManager();
+
+ if (position == drawerPositionsDefault) {
+ //Pop the back stack since we want to maintain only one level of the back stack
+ //Don't add the transaction to back stack since we are navigating to the first fragment
+ //being displayed and adding the same to the backstack will result in redundancy
+ fragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
+ fragmentManager.beginTransaction().replace(R.id.content_frame, fragment, TAG_CONTENT_FRAGMENT).commit();
+ } else {
+ //Pop the back stack since we want to maintain only one level of the back stack
+ //Add the transaction to the back stack since we want the state to be preserved in the back stack
+ //fragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
+ fragmentManager.beginTransaction().replace(R.id.content_frame, fragment, TAG_CONTENT_FRAGMENT).addToBackStack(null).commit();
+ }
+ mDrawerLayout.closeDrawer(mDrawerList);
+ }
+
+ @Override
+ public void setTitle(CharSequence title) {
+ mTitle = title;
+ getSupportActionBar().setTitle(mTitle);
+ }
+
+ @Override
+ public void onBackPressed() {
+ if (drawerPositionsDefault != DrawerPositions.MAIN) return;
+ mDrawerList.setItemChecked(0, true);
+ Fragment fragment = getSupportFragmentManager().findFragmentByTag(TAG_CONTENT_FRAGMENT);
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("MainActivity super.onBackPressed");
+ super.onBackPressed();
+ }
+
+ public static boolean permissionRequesting;
+ @Override
+ public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("permissionRequesting: requestCode = " + requestCode + ", permissions is " + (permissions == null ? "null" : "valid") + ", grantResults is " + (grantResults == null ? "null" : "valid") );
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("permissionRequesting: permissions[" + permissions.length + "] = " + (permissions != null && permissions.length > 0 ? permissions[0] : ""));
+ if (grantResults != null && grantResults.length != 0) {
+ boolean bNegative = false;
+ for (int i = 0; i < grantResults.length; i++) {
+ if (grantResults[i] < 0) bNegative = true;
+ if (DEBUG) csLibrary4A.appendToLog("permissionRequesting: grantResults[" + i + "] = " + grantResults[i] );
+ }
+ if (bNegative) {
+ Toast toast = Toast.makeText(this, R.string.toast_permission_not_granted, Toast.LENGTH_SHORT);
+ if (false) toast.setGravity(Gravity.TOP | Gravity.RIGHT, 100, 200);
+ toast.show();
+ }
+ }
+ super.onRequestPermissionsResult(requestCode, permissions, grantResults);
+ permissionRequesting = false;
+ }
+
+ public void sfnClicked(View view) {
+ selectItem(DrawerPositions.SPECIAL);
+ }
+
+ public void privacyClicked(View view) {
+ Intent intent = new Intent();
+ intent.setAction(Intent.ACTION_VIEW);
+ intent.addCategory(Intent.CATEGORY_BROWSABLE);
+ intent.setData(Uri.parse("https://www.convergence.com.hk/apps-privacy-policy"));
+ startActivity(intent);
+ }
+
+ public void aboutClicked(View view) { selectItem(DrawerPositions.ABOUT); }
+ public void connectClicked(View view) { selectItem(DrawerPositions.CONNECT); }
+ public void invClicked(View view) { selectItem(DrawerPositions.INVENTORY); }
+ public void locateClicked(View view) {
+ selectItem(DrawerPositions.SEARCH);
+ }
+ public void multiBankClicked(View view) { selectItem(DrawerPositions.MULTIBANK); }
+ public void settClicked(View view) {
+ selectItem(DrawerPositions.SETTING);
+ }
+ public void filterClicked(View view) {
+ selectItem(DrawerPositions.FILTER);
+ }
+ public void rrClicked(View view) {
+ selectItem(DrawerPositions.READWRITE);
+ }
+ public void rrUserClicked(View view) { selectItem(DrawerPositions.READWRITEUSER); }
+
+ public void accessClicked(View view) {
+ selectItem(DrawerPositions.SECURITY);
+ }
+
+ public void impInventoryClicked(View view) { selectItem(DrawerPositions.IMPINVENTORY); }
+ public void m775Clicked(View view) { selectItem(DrawerPositions.IMP775); }
+ public void alienClicked(View view) { selectItem(DrawerPositions.ALIEN); }
+ public void uCode8Clicked(View view) { selectItem(DrawerPositions.UCODE8); }
+ public void uCodeClicked(View view) { selectItem(DrawerPositions.UCODEDNA); }
+ public void bapCardClicked(View view) { selectItem(DrawerPositions.BAPCARD); }
+ public void coldChainClicked(View view) { selectItem(DrawerPositions.COLDCHAIN); }
+ public void aurasenseClicked(View view) { selectItem(DrawerPositions.AURASENSE); }
+ public void kilowayClicked(View view) { selectItem(DrawerPositions.KILOWAY); }
+ public void longjingClicked(View view) { selectItem(DrawerPositions.LONGJING); }
+ public void axzonClicked(View view) { selectItem(DrawerPositions.AXZON); }
+ public void rfMicronClicked(View view) { selectItem(DrawerPositions.RFMICRON); }
+ public void fdmicroClicked(View view) { selectItem(DrawerPositions.FDMICRO); }
+ public void ctesiusClicked(View view) { selectItem(DrawerPositions.CTESIUS); }
+ public void asygnClicked(View view) { selectItem(DrawerPositions.ASYGNTAG); }
+
+ public void regClicked(View view) { selectItem(DrawerPositions.REGISTER); }
+ public static boolean wedged = false;
+ public void wedgeClicked(View view) {
+ if (false) {
+ wedged = true;
+ Intent i = new Intent(Intent.ACTION_MAIN);
+ i.addCategory(Intent.CATEGORY_HOME);
+ startActivity(i);
+ } else selectItem(DrawerPositions.WEDGE);
+ }
+ public void directWedgeClicked(View view) {
+ selectItem(DrawerPositions.DIRECTWEDGE);
+ }
+
+ public void simpleInventoryClicked(View view) { selectItem(DrawerPositions.SIMINVENTORY); }
+
+ public void blankClicked(View view) { if (false) selectItem(DrawerPositions.BLANK); }
+
+ // The click listener for ListView in the navigation drawer
+ private class DrawerItemClickListener implements ListView.OnItemClickListener {
+ @Override
+ public void onItemClick(AdapterView> parent, View view, int position, long id) {
+ if (DEBUG) Log.i(TAG, "MainActivity.onItemClick: position = " + position + ", id = " + id);
+ selectItem(DrawerPositions.toDrawerPosition(position));
+ }
+ }
+
+ @Override
+ protected void onNewIntent(Intent intent) {
+ super.onNewIntent(intent);
+ if (DEBUG) csLibrary4A.appendToLog("onNewIntent !!! intent.getAction = " + intent.getAction());
+ readFromIntent(intent);
+ }
+ private void readFromIntent(Intent intent) {
+ if (DEBUG) csLibrary4A.appendToLog("onNewIntent !!! readFromIntent entry");
+ String action = intent.getAction();
+ }
+}
+
+
+
+package com.csl.cs710ademoapp;
+
+import static android.Manifest.permission.BLUETOOTH_CONNECT;
+import static android.Manifest.permission.BLUETOOTH_SCAN;
+import static com.csl.cs710ademoapp.MainActivity.mContext;
+import static com.csl.cs710ademoapp.MyForegroundService.ForegroundServiceState.CLOUDCONNECT;
+import static com.csl.cs710ademoapp.MyForegroundService.ForegroundServiceState.CONNECT;
+import static com.csl.cs710ademoapp.MyForegroundService.ForegroundServiceState.CONNECTED;
+import static com.csl.cs710ademoapp.MyForegroundService.ForegroundServiceState.INVENTORY;
+import static com.csl.cs710ademoapp.MyForegroundService.ForegroundServiceState.NULL;
+import static com.csl.cs710ademoapp.MyForegroundService.ForegroundServiceState.SCAN;
+import static com.csl.cs710ademoapp.MyForegroundService.ForegroundServiceState.WAIT;
+
+import android.app.Notification;
+import android.app.NotificationChannel;
+import android.app.NotificationManager;
+import android.app.PendingIntent;
+import android.app.Service;
+import android.content.Intent;
+import android.content.pm.PackageManager;
+import android.content.pm.ServiceInfo;
+import android.os.Binder;
+import android.os.Build;
+import android.os.Handler;
+import android.os.IBinder;
+import android.util.Log;
+import android.widget.Toast;
+
+import androidx.annotation.Nullable;
+import androidx.core.app.ActivityCompat;
+import androidx.core.app.NotificationCompat;
+
+import com.csl.cs710ademoapp.fragments.AboutFragment;
+import com.csl.cslibrary4a.BluetoothGatt;
+import com.csl.cslibrary4a.ReaderDevice;
+import com.csl.cslibrary4a.RfidReaderChipData;
+
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.List;
+import java.util.Random;
+
+public class MyForegroundService extends Service {
+ boolean DEBUG = false;
+ String TAG = "Hello";
+ Handler mHandler = new Handler();
+ public static final String CHANNEL_ID = "ForegroundServiceChannelA";
+ public static final int SERVICE_ID = 1;
+ NotificationManager notificationManager;
+ NotificationCompat.Builder notificationCompatBuilder;
+ ReaderDevice readerDevice;
+ SaveList2ExternalTask saveExternalTask; boolean isHttpServerOpened;
+ MyMqttClient myMqttClient;
+ ArrayList epcArrayList = new ArrayList();
+ ArrayList readerDeviceArrayList = new ArrayList<>();
+ long startTimeMillis, inventoryStartTimeMillis = 0;
+ int iConnectingCount = 0;
+
+ private final IBinder binder = new LocalBinder();
+ public class LocalBinder extends Binder {
+ MyForegroundService getService() {
+ // Return this instance of LocalService so clients can call public methods.
+ return MyForegroundService.this;
+ }
+ }
+
+ @Override
+ public void onCreate() {
+ super.onCreate();
+ mHandler.post(serviceRunnable);
+ }
+
+ @Override
+ public int onStartCommand(Intent intent, int flags, int startId) {
+ //String input = intent.getStringExtra("inputExtra");
+ if (MainActivity.csLibrary4A != null) Log.i(TAG, "MyForegroundService onStartCommand: csLibrary4A is created");
+ else Log.i(TAG, "MyForegroundService onStartCommand: null csLibrary4A");
+ Log.i(TAG, "MyForegroundService: onStartCommand");
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
+ Log.i(TAG, "MyForegroundService: createNotificationChannel");
+ NotificationChannel serviceChannel = new NotificationChannel(
+ CHANNEL_ID,
+ "Foreground Service Channel",
+ NotificationManager.IMPORTANCE_LOW
+ );
+ notificationManager = (NotificationManager) getSystemService(NotificationManager.class); //NotificationManager.class); //NOTIFICATION_SERVICE
+ List list = notificationManager.getNotificationChannels(); Log.i(TAG, "MyForegroundService onStartComand: getNotificationChannels.size = " + list.size());
+ notificationManager.createNotificationChannel(serviceChannel);
+ list = notificationManager.getNotificationChannels(); Log.i(TAG, "MyForegroundService onStartCommand: after createNotificationChannel, getNotificationChannels.size = " + list.size());
+ }
+
+ Intent notificationIntent = new Intent(this, AboutFragment.class);
+ //notificationIntent.setFlags((Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK));
+ PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, notificationIntent, PendingIntent.FLAG_IMMUTABLE);
+ notificationCompatBuilder = new NotificationCompat.Builder(this, CHANNEL_ID)
+ .setContentTitle("Cs710Reader Foreground Service")
+ .setSmallIcon(R.drawable.csl_logo_230510);
+ //.setPriority(NotificationCompat.PRIORITY_DEFAULT)
+ //.setContentIntent(pendingIntent)
+ //.setAutoCancel(true)
+ //.build();
+ Notification notification = updateNotification("MyForegroundService starts");
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
+ startForeground(SERVICE_ID, notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_LOCATION);
+ } else {
+ startForeground(SERVICE_ID, notification);
+ }
+
+ thread = new Thread(
+ new Runnable() {
+ @Override
+ public void run() {
+ while (true) {
+ int iRandom = getRandomNumber();
+ String strMessage = iRandom + ", ";
+ if (MainActivity.csLibrary4A == null) {
+ strMessage += "Cannot connect. Please restart App";
+ foregroundServiceState = NULL;
+ } else
+ {
+ ForegroundServiceState foregroundServiceStateOld = foregroundServiceState;
+ if (foregroundServiceState == NULL) {
+ strMessage += "ServiceState = " + foregroundServiceState.toString();
+ foregroundServiceState = WAIT;
+ } else if (foregroundServiceState == WAIT) {
+ strMessage += "Wait to enable Foreground Service";
+ if (isForegroundEnable()) {
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { //that is android 12 or above
+ if (ActivityCompat.checkSelfPermission(mContext, BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED
+ || ActivityCompat.checkSelfPermission(mContext, BLUETOOTH_SCAN) != PackageManager.PERMISSION_GRANTED) {
+ Log.i(TAG, "runnableStart: CANNOT start scanLeDevice as BLUETOOTH_CONNECT && BLUETOOTH_SCAN is NOT yet permitted");
+ } else if (MainActivity.csLibrary4A.isBleConnected()) {
+ foregroundServiceState = CONNECTED;
+ Log.i(TAG, "going to CONNECTED");
+ } else if (MainActivity.activityActive == false) {
+ Log.i(TAG, "runnableStartService: BLUETOOTH_CONNECT and BLUETOOTH_SCAN and (ACCESS_FINE_LOCATION or ACCESS_COARSE_LOCATION) is permitted");
+ } else {
+ Log.i(TAG, "Start ScanLeDevice");
+ MainActivity.csLibrary4A.scanLeDevice(true);
+ foregroundServiceState = SCAN;
+ }
+ }
+ }
+ } else if (foregroundServiceState == SCAN) {
+ strMessage += "Scanning reader";
+ if (MainActivity.csLibrary4A.isBleConnected()) {
+ foregroundServiceState = CONNECTED;
+ } else if (isForegroundEnable()) {
+ BluetoothGatt.CsScanData csScanData = null;
+ while (true) {
+ csScanData = MainActivity.csLibrary4A.getNewDeviceScanned();
+ Log.i(TAG, "cs108ScanData is " + (csScanData == null ? "null" : "valid") + ", foregroundReader = " + MainActivity.csLibrary4A.getForegroundReader());
+ if (csScanData == null) break;
+ strMessage += ("\n" + csScanData.device.getAddress());
+ if (csScanData.device.getAddress().matches(MainActivity.csLibrary4A.getForegroundReader())) { //"84:C6:92:9D:DD:52")) {
+ readerDevice = new ReaderDevice(csScanData.device.getName(), csScanData.device.getAddress(), false, "", 1, csScanData.rssi, csScanData.serviceUUID2p2);
+ String strInfo = "";
+ if (csScanData.device.getBondState() == 12) {
+ strInfo += "BOND_BONDED\n";
+ }
+ readerDevice.setDetails(strInfo + "scanRecord=" + MainActivity.csLibrary4A.byteArrayToString(csScanData.scanRecord));
+
+ MainActivity.csLibrary4A.scanLeDevice(false);
+ MainActivity.csLibrary4A.connect(readerDevice);
+ foregroundServiceState = CONNECT;
+ iConnectingCount = 0;
+ break;
+ }
+ }
+ if (foregroundServiceState != CONNECT && csScanData != null)
+ strMessage += ("\n" + csScanData.device.getAddress());
+ } else {
+ Log.i(TAG, "Stop ScanLeDevice");
+ MainActivity.csLibrary4A.scanLeDevice(false);
+ foregroundServiceState = NULL;
+ }
+ } else if (foregroundServiceState == CONNECT) {
+ strMessage += "Connecting Reader";
+ if (MainActivity.csLibrary4A.isBleConnected()) {
+ readerDevice.setConnected(true);
+ readerDevice.setSelected(true);
+ MainActivity.sharedObjects.readersList.add(readerDevice);
+ foregroundServiceState = CONNECTED;
+ } else if (++iConnectingCount > 10) {
+ MainActivity.csLibrary4A.disconnect(false);
+ foregroundServiceState = NULL;
+ }
+ } else if (foregroundServiceState == CLOUDCONNECT) {
+ strMessage += "Connecting MQTT Server";
+ if (!MainActivity.csLibrary4A.isBleConnected())
+ foregroundServiceState = CONNECTED;
+ else if (!isForegroundEnable())
+ foregroundServiceState = CONNECTED;
+ if (false && MainActivity.csLibrary4A.getInventoryCloudSave() == 1) {
+ saveExternalTask = new SaveList2ExternalTask(false);
+ Log.i(TAG, "Server: new saveExternalTask");
+ isHttpServerOpened = saveExternalTask.openServer(false);
+ Log.i(TAG, "Server: openServer is " + isHttpServerOpened);
+ foregroundServiceState = CONNECTED;
+ } else if (MainActivity.csLibrary4A.getInventoryCloudSave() == 2) {
+ if (myMqttClient != null && myMqttClient.isMqttServerConnected) {
+ Log.i(TAG, "MyForegroundService: Connecting MQTT 1");
+ foregroundServiceState = CONNECTED;
+ } else {
+ Log.i(TAG, "MyForegroundService: Connecting MQTT 2");
+ myMqttClient = new MyMqttClient(getApplicationContext());
+ myMqttClient.connect(null);
+ }
+ } else foregroundServiceState = NULL;
+ } else if (foregroundServiceState == CONNECTED) {
+ strMessage += "Connected";
+ if (MainActivity.csLibrary4A.isBleConnected()) {
+ if (isForegroundEnable()) {
+ boolean bStartInventory = false;
+ if (MainActivity.csLibrary4A.getInventoryCloudSave() == 1) {
+ if (false && !isHttpServerOpened) {
+ Log.i(TAG, "Server: going to CloudConnect");
+ foregroundServiceState = CLOUDCONNECT;
+ } else if (MainActivity.csLibrary4A.getTriggerButtonStatus()) {
+ strMessage += ("\n" + "H pressed trigger");
+ bStartInventory = true;
+ } else strMessage += ("\n" + "H released trigger");
+ } else if (MainActivity.csLibrary4A.getInventoryCloudSave() == 2
+ && MainActivity.csLibrary4A.getServerMqttLocation().length() > 0 && MainActivity.csLibrary4A.getTopicMqtt().length() > 0) {
+ if (myMqttClient == null || !myMqttClient.isMqttServerConnected)
+ foregroundServiceState = CLOUDCONNECT;
+ else if (MainActivity.csLibrary4A.getTriggerButtonStatus()) {
+ strMessage += (" with trigger pressed");
+ bStartInventory = true;
+ } else strMessage += (" with trigger released");
+ }
+ if (bStartInventory) {
+ Log.i(TAG, "Debug_Compact: MyForegroundService.onStartCommand");
+ MainActivity.csLibrary4A.startOperation(RfidReaderChipData.OperationTypes.TAG_INVENTORY_COMPACT);
+ Log.i(TAG, "Server:sss startOperation");
+ inventoryStartTimeMillis = System.currentTimeMillis();
+ foregroundServiceState = INVENTORY;
+ }
+ }
+ if (false) Log.i(TAG, "isForegroundEnable = " + isForegroundEnable()
+ + ", getInventoryCloudSave = " + MainActivity.csLibrary4A.getInventoryCloudSave()
+ + ", getServerMqttLocation = " + MainActivity.csLibrary4A.getServerMqttLocation()
+ + ", getTopicMqtt = " + MainActivity.csLibrary4A.getTopicMqtt());
+ } else {
+ Log.i(TAG, "Disconnecting");
+ MainActivity.csLibrary4A.disconnect(false);
+ if (isHttpServerOpened) {
+ if (saveExternalTask.closeServer())
+ Log.i(TAG, "Server: closeServer success");
+ else Log.i(TAG, "Server: closeServer failure");
+ isHttpServerOpened = false;
+ }
+ if (myMqttClient != null) myMqttClient.disconnect(null);
+ foregroundServiceState = NULL;
+ }
+ } else if (foregroundServiceState == INVENTORY) {
+ strMessage += "Doing inventory ";
+ Log.i(TAG, "inventory: isBleConnected = " + MainActivity.csLibrary4A.isBleConnected());
+ Log.i(TAG, "inventory: myMqttClient = " + (myMqttClient == null ? "null" : myMqttClient.isMqttServerConnected));
+ if (!MainActivity.csLibrary4A.isBleConnected())
+ foregroundServiceState = CONNECTED;
+// else if (csLibrary4A.getInventoryCloudSave() == 2 && (myMqttClient == null || !myMqttClient.isMqttServerConnected)) foregroundServiceState = CONNECTED;
+ else {
+ long timePeriod = System.currentTimeMillis() - startTimeMillis;
+ if (timePeriod > MainActivity.csLibrary4A.getForegroundDupElim() * 1000L) {
+ startTimeMillis = System.currentTimeMillis();
+ Log.i(TAG, "Foreground removes strEpcList of size " + epcArrayList.size());
+ epcArrayList.clear();
+ }
+ timePeriod = System.currentTimeMillis() - inventoryStartTimeMillis;
+ if (MainActivity.csLibrary4A.getInventoryCloudSave() == 2)
+ timePeriod = 0;
+ if (isForegroundEnable() && MainActivity.csLibrary4A.getTriggerButtonStatus() && timePeriod < 2000L) {
+ RfidReaderChipData.Rx000pkgData rx000pkgData = null, rx000pkgData1 = null;
+ while (MainActivity.csLibrary4A.getTriggerButtonStatus()) {
+ rx000pkgData = MainActivity.csLibrary4A.onRFIDEvent();
+ Log.i(TAG, "rx000pkgData is " + (rx000pkgData == null ? "null" : "valid") +
+ ", rx000pkgData1 is " + (rx000pkgData1 == null ? "null" : "valid"));
+ if (rx000pkgData == null) {
+ if (rx000pkgData1 == null)
+ strMessage += ("\n NO Tag is found");
+ break;
+ } else {
+ rx000pkgData1 = rx000pkgData;
+ String strEpc = MainActivity.csLibrary4A.byteArrayToString(rx000pkgData1.decodedEpc);
+ if (strEpc == null || strEpc.length() <= 0)
+ rx000pkgData1 = null;
+ else {
+ boolean match = false;
+ for (int i = 0; i < epcArrayList.size(); i++) {
+ if (strEpc.matches(epcArrayList.get(i))) {
+ match = true;
+ Log.i(TAG, "Foreground matches tag " + strEpc);
+ break;
+ }
+ }
+ if (!match) epcArrayList.add(strEpc);
+ else rx000pkgData1 = null;
+ }
+ if (rx000pkgData1 != null) {
+ Log.i(TAG, "Server: getInventoryCloudSave = " + MainActivity.csLibrary4A.getInventoryCloudSave());
+ if (MainActivity.csLibrary4A.getInventoryCloudSave() == 1) {
+ ReaderDevice readerDevice1 = new ReaderDevice("", MainActivity.csLibrary4A.byteArrayToString(rx000pkgData1.decodedEpc), false, null,
+ MainActivity.csLibrary4A.byteArrayToString(rx000pkgData1.decodedPc), null, MainActivity.csLibrary4A.byteArrayToString(rx000pkgData1.decodedCrc), null,
+ null, -1, -1,
+ null, -1, -1,
+ new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS").format(new Date()), new SimpleDateFormat("z").format(new Date()).replaceAll("GMT", ""),
+ MainActivity.mSensorConnector.mLocationDevice.getLocation(), MainActivity.mSensorConnector.mSensorDevice.getEcompass(),
+ 1, rx000pkgData1.decodedRssi, rx000pkgData1.decodedPhase, rx000pkgData1.decodedChidx, rx000pkgData1.decodedPort, -1, -1, -1, -1, -1, -1, null, -1);
+
+ readerDeviceArrayList.add(readerDevice1);
+ } else if (MainActivity.csLibrary4A.getInventoryCloudSave() == 2) {
+ myMqttClient.publish(MainActivity.csLibrary4A.byteArrayToString(rx000pkgData1.decodedEpc));
+ }
+ }
+ }
+ }
+ if (rx000pkgData1 != null)
+ strMessage += ("\n " + MainActivity.csLibrary4A.byteArrayToString(rx000pkgData1.decodedEpc));
+ } else { //isForegroundEnable() && csLibrary4A.getTriggerButtonStatus() && timePeriod
+ Log.i(TAG, "Server:sss abortOperation with isForegroundEnable = " + isForegroundEnable()
+ + ", getTriggerButtonStatus = " + MainActivity.csLibrary4A.getTriggerButtonStatus() + ", timePeriod = " + timePeriod + ", ");
+ MainActivity.csLibrary4A.abortOperation();
+ while (true) {
+ RfidReaderChipData.Rx000pkgData rx000pkgData = MainActivity.csLibrary4A.onRFIDEvent();
+ if (rx000pkgData == null) break;
+ }
+ if (readerDeviceArrayList.size() != 0) {
+ saveExternalTask = new SaveList2ExternalTask(false);
+ Log.i(TAG, "Server: new saveExternalTask");
+ isHttpServerOpened = saveExternalTask.openServer(false);
+ Log.i(TAG, "Server: openServer is " + isHttpServerOpened);
+ String messageStr = saveExternalTask.createJSON(readerDeviceArrayList, null).toString();
+ Log.i(TAG, "Server: Json = " + messageStr);
+ saveExternalTask.write2Server(messageStr);
+ Log.i(TAG, "Server: write2Server success");
+ if (saveExternalTask.closeServer())
+ Log.i(TAG, "Server: closeServer success");
+ else Log.i(TAG, "Server: closeServer failure");
+ }
+ foregroundServiceState = CONNECTED;
+ }
+ }
+ }
+ if (foregroundServiceState != foregroundServiceStateOld) {
+ strMessage += (", New ServiceState = " + foregroundServiceState.toString());
+ }
+ MainActivity.csLibrary4A.batteryLevelRequest(); //dummy reader access
+ }
+
+ updateNotification(strMessage);
+ try {
+ int iTime = 2000;
+ if (foregroundServiceState == INVENTORY) iTime = 100;
+ Thread.sleep(iTime);
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ }
+ }
+ }
+ );
+ thread.start();
+
+ // Builds the notification and issues it.
+ //do heavy work on a background thread
+ //stopSelf();
+ return super.onStartCommand(intent, flags, startId); //return START_NOT_STICKY;
+ }
+
+ @Override
+ public void onDestroy() {
+ Log.i(TAG, "MyForegroundService: onDestroy");
+ mHandler.removeCallbacks(serviceRunnable);
+ if (MainActivity.csLibrary4A != null) {
+ MainActivity.csLibrary4A.disconnect(false);
+ Log.i(TAG, "MyForegroundService: onDestroy 0");
+ }
+ thread.stop();
+ stopSelf();
+ super.onDestroy();
+ }
+
+ @Nullable
+ @Override
+ public IBinder onBind(Intent intent) {
+ Log.i(TAG, "MyForegroundService: onBind");
+ return binder; // null;
+ }
+
+ @Override
+ public void onTaskRemoved(Intent rootIntent) {
+ Log.i(TAG, "MyForegroundService: onTaskRemoved");
+ System.out.println("onTaskRemoved called");
+ super.onTaskRemoved(rootIntent);
+ //do something you want
+ //stop service
+ thread.stop();
+ this.stopSelf();
+ }
+
+ Thread thread = null;
+ Notification updateNotification(String string) {
+ if (DEBUG) Log.i(TAG, "MyForegroundService.updateNotification: " + string);
+ notificationCompatBuilder.setContentText(string);
+ Notification notification = notificationCompatBuilder.build();
+ notificationManager.notify(1, notification);
+ return notification;
+ }
+
+ int batteryCount_old; String strBatteryLow_old;
+ Runnable serviceRunnable = new Runnable() {
+ @Override
+ public void run() {
+ if (DEBUG) Log.i(TAG, "MyForegroundService.serviceRunnable starts");
+ mHandler.postDelayed(serviceRunnable, 2000);
+ if (!MainActivity.activityActive && MainActivity.csLibrary4A != null && MainActivity.csLibrary4A.isBleConnected()) {
+ int batteryCount = MainActivity.csLibrary4A.getBatteryCount();
+ String strBatteryLow = MainActivity.csLibrary4A.isBatteryLow();
+ if (DEBUG) Log.i(TAG, "MyForegroundService.serviceRunnable: batteryCount = " + batteryCount + ", batteryCount_old = " + batteryCount_old);
+ if (batteryCount_old != batteryCount) {
+ batteryCount_old = batteryCount;
+ if (strBatteryLow == null || strBatteryLow_old == null)
+ strBatteryLow_old = strBatteryLow;
+ else if (!strBatteryLow.matches(strBatteryLow_old))
+ strBatteryLow_old = strBatteryLow;
+ }
+ if (strBatteryLow != null) {
+ if (false) Log.i(TAG, "CustomIME Debug 112");
+ Toast.makeText(mContext,
+ "Battery Low: " + strBatteryLow + "% Battery Life Left",
+ Toast.LENGTH_SHORT).show();
+ }
+ }
+ }
+ };
+
+ final Random mGenerator = new Random();
+ int getRandomNumber() {
+ return mGenerator.nextInt(100);
+ }
+
+ boolean isForegroundEnable() {
+ if (MainActivity.csLibrary4A == null) return false;
+ if (DEBUG) Log.i(TAG, "MyForegroundService.isForegroundEnable: isHomeFragment = " + MainActivity.isHomeFragment + ", getForegroundReader = " + MainActivity.csLibrary4A.getForegroundReader());
+ return (MainActivity.isHomeFragment && MainActivity.csLibrary4A.getForegroundReader().length() != 0);
+ }
+
+ enum ForegroundServiceState {
+ NULL, WAIT, SCAN, CONNECT, CLOUDCONNECT, CONNECTED, INVENTORY, DISCONNECT
+ }
+ ForegroundServiceState foregroundServiceState = NULL;
+}
+
+
+
+package com.csl.cs710ademoapp;
+
+import android.content.Context;
+import android.util.Log;
+import android.view.View;
+
+import org.eclipse.paho.client.mqttv3.IMqttActionListener;
+import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
+import org.eclipse.paho.client.mqttv3.IMqttToken;
+import org.eclipse.paho.client.mqttv3.MqttCallback;
+import org.eclipse.paho.client.mqttv3.MqttClient;
+import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
+import org.eclipse.paho.client.mqttv3.MqttMessage;
+
+import info.mqtt.android.service.Ack;
+import info.mqtt.android.service.MqttAndroidClient;
+
+public class MyMqttClient {
+ final boolean DEBUG = false; final String TAG = "Hello";
+ boolean isMqttServerConnected = false;
+ Context context;
+ public MyMqttClient(Context context) {
+ this.context = context;
+
+ ///This here are the mqtt broker informations
+ String clientId = MqttClient.generateClientId();
+ Log.i(TAG, "MQTT: clientId is " + (clientId == null ? "null" : clientId));
+ //String serverMqttLocation = "tcp://192.168.25.153:1883";
+ //String serverMqttLocation = "tcp://localhost:1883";
+ String serverMqttLocation = "tcp://" + MainActivity.csLibrary4A.getServerMqttLocation() + ":1883";
+ Log.i(TAG, "MQTT: serverLocation is " + serverMqttLocation);
+ client = new MqttAndroidClient(context, serverMqttLocation, clientId, Ack.AUTO_ACK);
+ Log.i(TAG, "MQTT: client is " + (client == null ? "null" : "valid"));
+
+ if (true) {
+ MqttConnectOptions options = new MqttConnectOptions();
+ //options.setUserName("narada");
+ //options.setPassword("narada146551".toCharArray());
+ //options.setPassword("narada683796".toCharArray());
+ options.setKeepAliveInterval(60);//seconds
+ options.setCleanSession(true);
+ options.setAutomaticReconnect(true);
+ }
+
+ /*if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
+ ContextCompat.registerReceiver(this, mMessageReceiver,
+ new IntentFilter(AppConstants.INTENT_FILTERS.DASHBOARD_MESSAGE),RECEIVER_NOT_EXPORTED);
+ }else {
+ ContextCompat.registerReceiver(this, mMessageReceiver,
+ new IntentFilter(AppConstants.INTENT_FILTERS.DASHBOARD_MESSAGE));
+ }*/
+
+ client.setCallback(new MqttCallback() {
+ @Override
+ public void connectionLost(Throwable cause) {
+ Log.i(TAG, "MQTT: client.setCallback connectionLost");
+ isMqttServerConnected = false;
+ }
+
+ @Override
+ public void messageArrived(String topic, MqttMessage message) throws Exception {
+ Log.i(TAG, "MQTT: client.setCallback messageArrived");
+ }
+
+ @Override
+ public void deliveryComplete(IMqttDeliveryToken token) {
+ Log.i(TAG, "MQTT: client.setCallback deliveryComplete");
+ }
+ });
+ }
+ MqttAndroidClient client;
+ public void connect(View v) {
+ try {
+ IMqttToken token = client.connect();
+ token.setActionCallback(new IMqttActionListener() {
+ @Override
+ public void onSuccess(IMqttToken asyncActionToken) {
+ Log.i(TAG, "MQTT: client.connect.setActionCallback onSuccess");
+ //Toast.makeText(MainActivity.this,"connected!!",Toast.LENGTH_LONG).show();
+ subscribe();
+ isMqttServerConnected = true;
+ }
+
+ @Override
+ public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
+ Log.i(TAG, "MQTT: client.connect.setActionCallback onFailure");
+ //Toast.makeText(MainActivity.this,"connection failed!!",Toast.LENGTH_LONG).show();
+ }
+ });
+ } catch (Exception e) {
+ Log.i(TAG, "MQTT: conn Exception: " + e.toString());
+ }
+ }
+ public void disconnect(View v) {
+ try {
+ IMqttToken token = client.disconnect();
+ token.setActionCallback(new IMqttActionListener() {
+ @Override
+ public void onSuccess(IMqttToken asyncActionToken) {
+ isMqttServerConnected = false;
+ Log.i(TAG, "MQTT: client.disconnect.setActionCallback onSuccess");
+ //Toast.makeText(MainActivity.this,"Disconnected!!",Toast.LENGTH_LONG).show();
+ }
+
+ @Override
+ public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
+ Log.i(TAG, "MQTT: client.disconnect.setActionCallback onFailure");
+ //Toast.makeText(MainActivity.this,"Could not diconnect!!",Toast.LENGTH_LONG).show();
+ }
+ });
+ } catch (Exception e) {
+ Log.i(TAG, "MQTT: disconn Exception: " + e.toString());
+ }
+ }
+ private void subscribe() {
+ try{
+ client.subscribe("event",0);
+ Log.i(TAG, "MQTT: client.subscribe");
+ } catch (Exception e){
+ Log.i(TAG, "MQTT: setSubscription Exception: " + e.toString());
+ }
+ }
+ public void publish(String message) {
+ String topic = MainActivity.csLibrary4A.getTopicMqtt();
+ //String message = "the payload 11";
+ try {
+ client.publish(topic, message.getBytes(),0,false);
+ Log.i(TAG, "MQTT: client.publish");
+ //Toast.makeText(this,"Published Message",Toast.LENGTH_SHORT).show();
+ } catch (Exception e) {
+ Log.i(TAG, "MQTT: published Exception: " + e.toString());
+ }
+ }
+}
+
+
+
+package com.csl.cs710ademoapp;
+
+import static android.content.Context.WIFI_SERVICE;
+import static com.csl.cs710ademoapp.MainActivity.csLibrary4A;
+import static com.csl.cs710ademoapp.MainActivity.mContext;
+
+import android.bluetooth.BluetoothAdapter;
+import android.media.MediaScannerConnection;
+import android.net.wifi.WifiManager;
+import android.os.AsyncTask;
+import android.os.Build;
+import android.os.Environment;
+import android.provider.Settings;
+import android.util.Log;
+
+import com.csl.cslibrary4a.ReaderDevice;
+import com.csl.cslibrary4a.RfidReaderChipData;
+
+import org.json.JSONArray;
+import org.json.JSONObject;
+
+import java.io.BufferedReader;
+import java.io.DataOutputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.InputStreamReader;
+import java.io.OutputStream;
+import java.net.DatagramPacket;
+import java.net.DatagramSocket;
+import java.net.HttpURLConnection;
+import java.net.InetAddress;
+import java.net.NetworkInterface;
+import java.net.URL;
+import java.security.SecureRandom;
+import java.security.cert.CertificateException;
+import java.security.cert.X509Certificate;
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Date;
+import java.util.List;
+
+import javax.net.ssl.HostnameVerifier;
+import javax.net.ssl.HttpsURLConnection;
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.TrustManager;
+import javax.net.ssl.X509TrustManager;
+
+public class SaveList2ExternalTask extends AsyncTask {
+ public String messageStr;
+ String resultDisplay = "";
+ public String errorDisplay;
+ ArrayList tagsList; ReaderDevice tagDevice1;
+ CustomPopupWindow customPopupWindow;
+ boolean savedFile = false;
+ int fileFormat = 0;
+
+ public String url = null, strBearer = null;
+ HttpURLConnection con;
+ String stringBluetoothMAC, stringWifiMac;
+
+ public SaveList2ExternalTask(ArrayList tagsList) {
+ this.tagsList = tagsList;
+
+ stringBluetoothMAC = BluetoothAdapter.getDefaultAdapter().getAddress().replaceAll(":", "");
+ csLibrary4A.appendToLog("stringBluetoothMac from getMacAddress = " + stringBluetoothMAC);
+ if (Build.VERSION.SDK_INT > Build.VERSION_CODES.S) { }
+ else if (stringBluetoothMAC.contains("020000000000")) {
+ final String SECURE_SETTINGS_BLUETOOTH_ADDRESS = "bluetooth_address";
+ String macAddress = Settings.Secure.getString(mContext.getContentResolver(), SECURE_SETTINGS_BLUETOOTH_ADDRESS); //Not OK in android 8, >= 32
+ csLibrary4A.appendToLog("stringBluetoothMac from Settings.Secure.getString = " + macAddress);
+ stringBluetoothMAC = macAddress;
+ }
+
+ stringWifiMac = ((WifiManager) MainActivity.mContext.getSystemService(WIFI_SERVICE)).getConnectionInfo().getMacAddress().replaceAll(":", "");
+ csLibrary4A.appendToLog("stringWifMac from getMacAddress = " + stringWifiMac);
+ if (stringWifiMac.contains("020000000000")) {
+ try {
+ List all = Collections.list(NetworkInterface.getNetworkInterfaces());
+ for (NetworkInterface nif : all) {
+ csLibrary4A.appendToLog("nif.getName = " + nif.getName() + ", macByts = " + csLibrary4A.byteArrayToString(nif.getHardwareAddress()));
+ }
+
+ WifiManager wifiMan = (WifiManager) mContext.getSystemService(WIFI_SERVICE);
+ int wifiState = wifiMan.getWifiState();
+ //wifiMan.setWifiEnabled(true);
+ File fl = new File("/sys/class/net/wlan0/address");
+ FileInputStream fin = new FileInputStream(fl); //Not Ok in Amdroid 11
+ StringBuilder builder = new StringBuilder();
+ int ch;
+ while ((ch = fin.read()) != -1) {
+ builder.append((char) ch);
+ }
+ String fileMAC = builder.toString();
+ csLibrary4A.appendToLog("getName: file content = " + fileMAC);
+ fin.close();
+
+ stringWifiMac = fileMAC;
+ //boolean enabled = WifiManager.WIFI_STATE_ENABLED == wifiState;
+ //wifiMan.setWifiEnabled(enabled);
+ } catch (Exception ex) {
+ csLibrary4A.appendToLog("Exception : " + ex.getCause());
+ }
+ }
+ }
+ boolean bImpinjServer = false;
+ public SaveList2ExternalTask(boolean bImpinjServer) {
+ csLibrary4A.appendToLog("bImpinjServer = " + bImpinjServer);
+ this.bImpinjServer = bImpinjServer;
+ }
+
+ @Override
+ protected void onPreExecute() {
+ if (!bImpinjServer) {
+ if (tagsList == null) cancel(true);
+ if (MainActivity.csLibrary4A.getSavingFormatSetting() == 0)
+ messageStr = createJSON(tagsList, null).toString();
+ else messageStr = createCSV(tagsList, null);
+ resultDisplay = save2File(messageStr, true);
+ }
+ customPopupWindow = new CustomPopupWindow(mContext);
+ csLibrary4A.appendToLog("SaveList2ExternalTask: resultDisplay = " + resultDisplay);
+ if (resultDisplay == null) resultDisplay = "";
+ else {
+ resultDisplay += "\n";
+ savedFile = true;
+ customPopupWindow.popupStart(resultDisplay + "Connecting server. Please wait.", true);
+ csLibrary4A.appendToLog("SaveList2ExternalTask: popupStart is done");
+ }
+ }
+
+ protected String doInBackground(Void... params) {
+ Log.i("Hello", "bImpinjServer: doInBackground starts");
+ if (MainActivity.csLibrary4A.isBleConnected() == false) {
+ resultDisplay += "Error in sending data to server as the reader is not connected";
+ return null;
+ } else if (MainActivity.csLibrary4A.getSaveCloudEnable() == false && bImpinjServer == false) {
+ resultDisplay += "No saving to cloud as it is disabled";
+ return null;
+ }
+ try {
+ if (true) {
+ csLibrary4A.appendToLog("bImpinjServer: doInBackground starts doing");
+ openServer(bImpinjServer); csLibrary4A.appendToLog("bImpinjServer: doInBackground after openServer");
+ write2Server(messageStr); csLibrary4A.appendToLog("bImpinjServer: doInBackground after write2Server");
+ closeServer(); csLibrary4A.appendToLog("bImpinjServer: doInBackground after closeServer");
+ } else if (true) {
+ String serverAddress = "192.168.25.119:21";
+ String addressPort[];
+ InetAddress serverAddr = null;
+ int serverPort = 0;
+ boolean validLocation = false;
+ if (serverAddress != null) {
+ addressPort = serverAddress.trim().split(":");
+ if (addressPort.length == 2) {
+ try {
+ serverAddr = InetAddress.getByName(addressPort[0]);
+ serverPort = Integer.decode(addressPort[1]);
+ validLocation = true;
+ } catch (Exception ex) { }
+ }
+ }
+ if (validLocation == false) resultDisplay += "Error in creating server location from " + csLibrary4A.getServerLocation() + " !!!";
+ else {
+ DatagramSocket udpSocket = new DatagramSocket();
+ byte[] buf = messageStr.getBytes();
+ DatagramPacket packet = new DatagramPacket(buf, buf.length, serverAddr, serverPort);
+ udpSocket.send(packet);
+ resultDisplay += "Success in sending data to " + csLibrary4A.getServerLocation();
+ }
+ }
+ } catch (Exception e) {
+ errorDisplay += ": " + e.getMessage() + "\n";
+ }
+ if (errorDisplay != null) resultDisplay += "Error in sending data to server " + (url != null ? url : "") + " with " + errorDisplay;
+ while (MainActivity.permissionRequesting) { }
+ return null;
+ }
+ protected void onProgressUpdate(Void... output) { }
+ protected void onCancelled() { }
+ protected void onPostExecute(String output) {
+ if (savedFile == false) resultDisplay += "\n" + save2File(messageStr, false);
+ customPopupWindow.popupWindow.dismiss();
+ csLibrary4A.appendToLog("bImpinjServer = " + bImpinjServer + ", responseCode = " + responseCode + ", resultDisplay = " + resultDisplay);
+ if (resultDisplay != null && resultDisplay.length() != 0) {
+ if (!bImpinjServer || responseCode != 200) customPopupWindow.popupStart(resultDisplay, false);
+ }
+ }
+
+ public String createStrEpcList() {
+ String stringOutput = "";
+ if (tagsList != null) {
+ for (int i = 0; i < tagsList.size(); i++) {
+ ReaderDevice tagDevice = tagsList.get(i);
+ if (tagDevice.getAddress() != null) stringOutput += tagDevice.getAddress() + "\n";
+ }
+ }
+ return stringOutput;
+ }
+
+ int sequenceNumber;
+ public JSONObject createJSON(ArrayList tagsList0, ReaderDevice tagDevice0) {
+ JSONObject object = new JSONObject();
+ try {
+ object.put("sequenceNumber", sequenceNumber++);
+
+ if (tagsList0 != null || tagDevice0 != null) {
+ JSONArray jsonArray = new JSONArray();
+ int i = 1; if (tagsList0 != null) i = tagsList0.size();
+ object.put("numberOfTags", i);
+ while (--i >= 0) {
+ ReaderDevice tagDevice;
+ if (tagsList0 != null) tagDevice = tagsList0.get(i);
+ else tagDevice = tagDevice0;
+
+ String accessPassword = null, killPassword = null, pcData = null, epcData = null, resBankData = null, epcBankData = null, tidBankData = null, userBankData = null;
+ String timeOfRead = null, timeZone = null, location = null, compass = null;
+ int phase = -1, channel = -1;
+ if (tagDevice != null) {
+ pcData = tagDevice.getPc();
+ epcData = tagDevice.getAddress();
+ resBankData = tagDevice.getRes();
+ epcBankData = tagDevice.getEpc();
+ tidBankData = tagDevice.getTid();
+ userBankData = tagDevice.getUser();
+ timeOfRead = tagDevice.getTimeOfRead();
+ timeZone = tagDevice.getTimeZone();
+ location = tagDevice.getLocation();
+ compass = tagDevice.getCompass();
+ phase = tagDevice.getPhase();
+ channel = tagDevice.getChannel();
+ }
+
+ JSONObject objectTag = new JSONObject();
+
+ objectTag.put("accessPassword", accessPassword);
+ objectTag.put("killPassword", killPassword);
+
+ objectTag.put("pc", pcData);
+ objectTag.put("epc", epcData);
+
+ objectTag.put("resBank", resBankData);
+ objectTag.put("epcBank", epcBankData);
+ objectTag.put("tidBank", tidBankData);
+ objectTag.put("userBank", userBankData);
+ if (phase != -1) objectTag.put("phase", phase);
+ if (channel != -1) objectTag.put("channel", channel);
+
+ objectTag.put("timeOfRead", timeOfRead);
+ objectTag.put("timeZone", timeZone);
+ objectTag.put("locationOfRead", location);
+ objectTag.put("eCompass", compass);
+
+ objectTag.put("antennaPort", "0");
+ jsonArray.put(objectTag);
+ }
+ object.put("tags", jsonArray);
+ }
+
+ object.put("userDescription","this is example tag data");
+
+ object.put("rfidReaderName", MainActivity.csLibrary4A.getBluetoothICFirmwareName());
+ object.put("rfidReaderSerialNumber", MainActivity.csLibrary4A.getHostProcessorICSerialNumber());
+ object.put("rfidReaderInternalSerialNumber", MainActivity.csLibrary4A.getRadioSerial());
+
+ object.put("smartPhoneName", Build.MODEL);
+ String strPhoneSerial = Build.SERIAL;
+ object.put("smartPhoneSerialNumber", strPhoneSerial);
+ object.put("smartPhoneBluetoothMACAddress", stringBluetoothMAC);
+ object.put("smartPhoneWiFiMACAddress", stringWifiMac);
+
+ object.put("smartPhoneUUID", null);
+ object.put("pcName", null);
+ object.put("pcEthernetMACAddress", null);
+ object.put("pcWiFiMACAddress", null);
+
+ object.put("operatorId","Generic Operator");
+ object.put("operatorSiteId","Generic Site");
+ } catch (Exception ex) { }
+ return object;
+ }
+
+ public String createCSV(ArrayList tagsList0, ReaderDevice tagDevice0) {
+ String object = "";
+ int csvColumnSelect = MainActivity.csLibrary4A.getCsvColumnSelectSetting();
+ try {
+ if (tagsList0 != null || tagDevice0 != null) {
+ JSONArray jsonArray = new JSONArray();
+ int i = 1; if (tagsList0 != null) i = tagsList0.size();
+ if (true) {
+ String objectTag;
+ objectTag = "PC,";
+ objectTag += "EPC,";
+ if ((csvColumnSelect & (0x01 << RfidReaderChipData.CsvColumn.RESERVE_BANK.ordinal())) != 0) objectTag += "Reserve Bank,";
+ if ((csvColumnSelect & (0x01 << RfidReaderChipData.CsvColumn.EPC_BANK.ordinal())) != 0) objectTag += "EPC Bank,";
+ if ((csvColumnSelect & (0x01 << RfidReaderChipData.CsvColumn.TID_BANK.ordinal())) != 0) objectTag += "TID Bank,";
+ if ((csvColumnSelect & (0x01 << RfidReaderChipData.CsvColumn.USER_BANK.ordinal())) != 0) objectTag += "User Bank,";
+ if ((csvColumnSelect & (0x01 << RfidReaderChipData.CsvColumn.PHASE.ordinal())) != 0) objectTag += "Phase,";
+ if ((csvColumnSelect & (0x01 << RfidReaderChipData.CsvColumn.CHANNEL.ordinal())) != 0) objectTag += "Channel,";
+ if ((csvColumnSelect & (0x01 << RfidReaderChipData.CsvColumn.TIME.ordinal())) != 0) objectTag += "Time Of Read,";
+ if ((csvColumnSelect & (0x01 << RfidReaderChipData.CsvColumn.TIMEZONE.ordinal())) != 0) objectTag += "Time Zone,";
+ if ((csvColumnSelect & (0x01 << RfidReaderChipData.CsvColumn.LOCATION.ordinal())) != 0) objectTag += "location Of Read Latitude, Location of Read Longitude, ";
+ if ((csvColumnSelect & (0x01 << RfidReaderChipData.CsvColumn.DIRECTION.ordinal())) != 0) objectTag += "eCompass";
+ objectTag += "\n";
+ object += objectTag;
+ }
+
+ while (--i >= 0) {
+ ReaderDevice tagDevice;
+ if (tagsList0 != null) tagDevice = tagsList0.get(i);
+ else tagDevice = tagDevice0;
+
+ String accessPassword = null, killPassword = null, pcData = null, epcData = null, resBankData = null, epcBankData = null, tidBankData = null, userBankData = null;
+ String timeOfRead = null, timeZone = null, location = null, compass = null;
+ int phase = -1, channel = -1;
+ if (tagDevice != null) {
+ pcData = tagDevice.getPc();
+ epcData = tagDevice.getAddress();
+ resBankData = tagDevice.getRes();
+ epcBankData = tagDevice.getEpc();
+ tidBankData = tagDevice.getTid();
+ userBankData = tagDevice.getUser();
+ timeOfRead = tagDevice.getTimeOfRead(); MainActivity.csLibrary4A.appendToLog("timeOfRead = " + timeOfRead );
+ if (false) {
+ int index = timeOfRead.indexOf(".");
+ if (index >= 0) {
+ String string1 = timeOfRead.substring(0, index);
+ timeOfRead = string1;
+ MainActivity.csLibrary4A.appendToLog("index = " + index + ", revised timeOfRead = " + timeOfRead );
+ }
+ }
+ timeZone = tagDevice.getTimeZone();
+ location = tagDevice.getLocation();
+ compass = tagDevice.getCompass();
+ phase = tagDevice.getPhase();
+ channel = tagDevice.getChannel();
+ }
+
+ String objectTag;
+ objectTag = String.format("=\"%s\",", pcData);
+ objectTag += String.format("=\"%s\",", epcData);
+
+ if ((csvColumnSelect & (0x01 << RfidReaderChipData.CsvColumn.RESERVE_BANK.ordinal())) != 0) objectTag += String.format("=\"%s\",", resBankData);
+ if ((csvColumnSelect & (0x01 << RfidReaderChipData.CsvColumn.EPC_BANK.ordinal())) != 0) objectTag += String.format("=\"%s\",", epcBankData);
+ if ((csvColumnSelect & (0x01 << RfidReaderChipData.CsvColumn.TID_BANK.ordinal())) != 0) objectTag += String.format("=\"%s\",", tidBankData);
+ if ((csvColumnSelect & (0x01 << RfidReaderChipData.CsvColumn.USER_BANK.ordinal())) != 0) objectTag += String.format("=\"%s\",", userBankData);
+ if ((csvColumnSelect & (0x01 << RfidReaderChipData.CsvColumn.PHASE.ordinal())) != 0) objectTag += String.format("%d,", phase);
+ if ((csvColumnSelect & (0x01 << RfidReaderChipData.CsvColumn.CHANNEL.ordinal())) != 0) objectTag += String.format("%d,", channel);
+ if ((csvColumnSelect & (0x01 << RfidReaderChipData.CsvColumn.TIME.ordinal())) != 0) objectTag += String.format("=\"%s\",", timeOfRead);
+ if ((csvColumnSelect & (0x01 << RfidReaderChipData.CsvColumn.TIMEZONE.ordinal())) != 0) objectTag += String.format("%s,", timeZone);
+ if ((csvColumnSelect & (0x01 << RfidReaderChipData.CsvColumn.LOCATION.ordinal())) != 0) objectTag += String.format("%s,", location);
+ if ((csvColumnSelect & (0x01 << RfidReaderChipData.CsvColumn.DIRECTION.ordinal())) != 0)objectTag += String.format("%s", compass);
+ objectTag += "\n";
+ object += objectTag;
+ }
+
+ if ((csvColumnSelect & (0x01 << RfidReaderChipData.CsvColumn.OTHERS.ordinal())) != 0) {
+ object += "\nUser Description,this is example tag data\n";
+
+ object += String.format("RFID Reader Name,=\"%s\"\n", MainActivity.csLibrary4A.getBluetoothICFirmwareName());
+ object += String.format("RFID Reader Serial Number,=\"%s\"\n", MainActivity.csLibrary4A.getHostProcessorICSerialNumber());
+ object += String.format("RFID Reader Radio Serial Number,=\"%s\"\n", MainActivity.csLibrary4A.getRadioSerial());
+ if (true) {
+ object += String.format("RFID Reader Barcode Serial Number,=\"%s\"\n", MainActivity.csLibrary4A.getBarcodeSerial());
+ object += String.format("RFID Reader Bluetooth MAC address,=\"%s\"\n", MainActivity.csLibrary4A.getBluetoothDeviceAddress());
+ }
+ object += String.format("Smart Phone Name,=\"%s\"\n", Build.MODEL);
+ }
+ }
+ } catch (Exception ex) { }
+ return object;
+ }
+
+ public String save2File(String messageStr, boolean requestPermission) {
+ String resultDisplay = "";
+ if (MainActivity.csLibrary4A.getSaveFileEnable() == false) return "No saving file as it is disabled";
+ boolean writeExtPermission = true;
+/*
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
+ if (mContext.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
+ csLibrary4A.appendToLog("WRITE_EXTERNAL_STORAGE Permission is required !!!");
+ writeExtPermission = false;
+ if (requestPermission) {
+ csLibrary4A.appendToLog("requestPermissions WRITE_EXTERNAL_STORAGE 1");
+ MainActivity.permissionRequesting = true; requestPermissions((Activity) mContext, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
+ if (false) Toast.makeText(mContext, R.string.toast_permission_not_granted, Toast.LENGTH_SHORT).show();
+ return null;
+ }
+ } else csLibrary4A.appendToLog("WRITE_EXTERNAL_STORAGE Permission is GRANTED !!!");
+ }
+*/
+ errorDisplay = null;
+ if (writeExtPermission == false) {
+ errorDisplay = "denied WRITE_EXTERNAL_STORAGE Permission !!!";
+ } else if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) == false) errorDisplay = "Error in mouting external storage !!!";
+ else {
+ String strDir = "csReaderJava";
+ File path = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + Environment.DIRECTORY_DOWNLOADS + "/" + strDir);
+ if (path.exists() == false) path.mkdirs();
+ if (path.exists() == false) errorDisplay = "Error in making directory !!!";
+ else {
+ String dateTime = new SimpleDateFormat("yyMMdd_HHmmss").format(new Date());
+ String fileName = strDir + "_" + dateTime + (csLibrary4A.getSavingFormatSetting() == 0 ? ".txt" : ".csv");
+ File file = new File(path, fileName);
+ if (file == null) errorDisplay = "Error in making directory !!!";
+ else {
+ try {
+ errorDisplay = "Error in FileOutputStream()";
+ FileOutputStream outputStream = new FileOutputStream(file);
+ errorDisplay = "Error in write()";
+ outputStream.write(messageStr.getBytes());
+ errorDisplay = "Error in close()"; outputStream.close();
+ MediaScannerConnection.scanFile(mContext, new String[]{file.getAbsolutePath()}, null, null);
+ resultDisplay = "Success in saving data to Download/" + strDir + "/" + fileName;
+ errorDisplay = null;
+ } catch (Exception ex) {
+ errorDisplay += ex.getMessage();
+ }
+ }
+ }
+ }
+ if (errorDisplay != null) return "Error in saving file with " + errorDisplay;
+ return resultDisplay;
+ }
+
+ public boolean openServer(boolean bImpinjServer) {
+ boolean bValue = true;
+ try {
+ if (false) {
+ url = "https://";
+ url += "192.168.25.21:";
+ url += "29090/WebServiceRESTs/1.0/req/";
+ } else if (false) url = "http://ptsv2.com/t/10i1t-1519143332/post";
+ else if (bImpinjServer) {
+ } //url = "https://h9tqczg9-7275.asse.devtunnels.ms/api/Auth/login"; //"https://142.251.220.110"; //
+ else url = csLibrary4A.getServerLocation();
+ MainActivity.csLibrary4A.appendToLog("nnn 1: url is " + url);
+
+ errorDisplay = "Error in SSLContext.getInstance()";
+ SSLContext sc = SSLContext.getInstance("TLSv1.2");
+ MainActivity.csLibrary4A.appendToLog("nnn 2: SSLContext sc is " + (sc == null ? "null" : "valid"));
+ errorDisplay = "Error in SSLContext.init()";
+ sc.init(null, new TrustManager[]{
+ new X509TrustManager() {
+ @Override
+ public void checkClientTrusted(X509Certificate[] certs, String authType) throws CertificateException {
+ throw new UnsupportedOperationException("TrustManager.checkClientTrusted: Not supported yet."); //To change body of generated methods, choose Tools | Templates.
+ }
+
+ @Override
+ public void checkServerTrusted(X509Certificate[] certs, String authType) throws CertificateException {
+ }
+
+ @Override
+ public X509Certificate[] getAcceptedIssuers() {
+ return null;
+ }
+ }
+ }, new SecureRandom());
+ MainActivity.csLibrary4A.appendToLog("nnn 3: SSLContext sc.init is Okay");
+ if (true) {
+ errorDisplay = "Error in setDefaultSSLSocketFactory()";
+ MainActivity.csLibrary4A.appendToLog("nnn 4: sc.getSocketFactory is " + (sc.getSocketFactory() == null ? "null" : "valid"));
+ HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
+ MainActivity.csLibrary4A.appendToLog("nnn 5: HttpsURLConnection.setDefaultSSLSocketFactory is Okay");
+ errorDisplay = "Error in setDefaultHostnameVerifier()";
+ HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
+ @Override
+ public boolean verify(String hostname, javax.net.ssl.SSLSession sslSession) {
+ return true;
+ }
+ });
+ MainActivity.csLibrary4A.appendToLog("nnn 6: HttpsURLConnection.setDefaultHostnameVerifier is Okay");
+ }
+ HttpsURLConnection.setFollowRedirects(false);
+ MainActivity.csLibrary4A.appendToLog("nnn 7: HttpsURLConnection.setFollowRedirects is Okay");
+
+ errorDisplay = "Error in URL()";
+ URL obj = new URL(url);
+ MainActivity.csLibrary4A.appendToLog("nnn 8: URL(obj) is " + (obj != null ? "valid" : "NULL") + " with url = " + url);
+ errorDisplay = "Error in openConnection()";
+ boolean isHttps = false;
+ if (url.length() >= 6) {
+ if (url.substring(0, 6).matches("https:")) isHttps = true;
+ }
+ con = (HttpURLConnection) obj.openConnection();
+ MainActivity.csLibrary4A.appendToLog("nnn 9: HttpURLConnection obj.openConnection is " + (con == null ? "null" : "valid"));
+ if (isHttps) {
+ con = (HttpsURLConnection) obj.openConnection();
+ MainActivity.csLibrary4A.appendToLog("nnn 10: HttpsURLConnection obj.openConnection is " + (con == null ? "null" : "valid"));
+ }
+ errorDisplay = "Error in setConnectTimeout()";
+ con.setConnectTimeout(MainActivity.csLibrary4A.getServerTimeout() * 1000);
+ MainActivity.csLibrary4A.appendToLog("nnn 11: con.setConnectTimeout is Okay");
+ errorDisplay = "Error in setRequestMethod()";
+ con.setRequestMethod("POST");
+ MainActivity.csLibrary4A.appendToLog("nnn 12: con.setRequestMethod is Okay");
+ //errorDisplay = "Error in setRequestProperty(User-Agent)"; con.setRequestProperty("User-Agent", "Mozilla/5.0");
+ //errorDisplay = "Error in setRequestProperty(text/plain)"; con.setRequestProperty("text/plain", "text/plain");
+ //errorDisplay = "Error in setRequestProperty(Accept-Language)"; con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
+ MainActivity.csLibrary4A.appendToLog("nnn 13: authenticate in url position : " + url.indexOf("authenticate"));
+ if (url.indexOf("authenticate") >= 0) {
+ String string = strBearer;
+ MainActivity.csLibrary4A.appendToLog("nnn 14: Authorization value = " + string);
+ errorDisplay = "Error in setRequestProperty(Authorization)";
+ con.setRequestProperty("Authorization", string);
+ MainActivity.csLibrary4A.appendToLog("nnn 15 : con.setRequestProperty is Okay");
+ }
+ errorDisplay = "Error in setRequestProperty(Content)";
+ con.setRequestProperty("Content-Type", "application/json); //; charset=utf8");
+ MainActivity.csLibrary4A.appendToLog("nnn 16: con.setRequestProperty is Okay");
+ errorDisplay = "Error in setDoOutput()";
+ con.setDoOutput(true);
+ MainActivity.csLibrary4A.appendToLog("nnn 17: con.setDoOutput is Okay");
+ errorDisplay = "Error in setDoInput()";
+ con.setDoInput(true);
+ MainActivity.csLibrary4A.appendToLog("nnn 18: Finished openServer");
+ } catch (Exception ex) {
+ MainActivity.csLibrary4A.appendToLog("openServer Exception: " + ex.getMessage());
+ bValue = false;
+ }
+ return bValue;
+ }
+
+ boolean serverWritten = false;
+ public void write2Server(String messageStr0) {
+ csLibrary4A.appendToLog("messageStr0 = " + messageStr0);
+ try {
+ //InputStream is = con.getInputStream(); DataInputStream ir = new DataInputStream(is);
+ errorDisplay = "Error in getOutputStream()"; OutputStream os = con.getOutputStream();
+ errorDisplay = "Error in DataOutputStream()"; DataOutputStream wr = new DataOutputStream(os);
+
+ errorDisplay = "Error in writeBytes()"; wr.writeBytes(messageStr0);
+
+ errorDisplay = "Error in flush()"; wr.flush();
+ errorDisplay = "Error in close(wr)"; wr.close();
+ errorDisplay = "Error in close(os)"; os.close();
+ serverWritten = true;
+ //csLibrary4A.appendToLog("inputStream = " + ir.readUTF());
+ MainActivity.csLibrary4A.appendToLog("nnn 19: finished write2Server");
+ } catch (Exception ex) {
+ MainActivity.csLibrary4A.appendToLog("nnn 20: errorDisplay = " + errorDisplay + ", exception = " + ex.getMessage());
+ }
+ }
+
+ public int responseCode; public String response = null;
+ public boolean closeServer() {
+ boolean bValue = true;
+ if (serverWritten) {
+ try {
+ errorDisplay = "Error in getResponseCode()";
+ responseCode = con.getResponseCode();
+ //MainActivity.csLibrary4A.appendToLog("errorDisplay = " + errorDisplay);
+ MainActivity.csLibrary4A.appendToLog("responseCode = " + responseCode);
+ if (responseCode != 200)
+ errorDisplay = "Error in response code = " + responseCode;
+ else {
+ BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
+ //MainActivity.csLibrary4A.appendToLog("errorDisplay = " + errorDisplay);
+ String inputLine;
+ response = "";
+ while ((inputLine = in.readLine()) != null) {
+ response += inputLine;
+ }
+ in.close();
+ //MainActivity.csLibrary4A.appendToLog("errorDisplay = " + errorDisplay);
+ resultDisplay += "Success in sending data to server with response = " + response;
+ MainActivity.csLibrary4A.appendToLog("response = " + response);
+ errorDisplay = null;
+ }
+ } catch (Exception ex) {
+ bValue = false;
+ }
+ }
+ con.disconnect();
+ return bValue;
+ }
+}
+
+
+
+package com.csl.cs710ademoapp;
+
+import android.app.Activity;
+import android.view.View;
+import android.widget.AdapterView;
+import android.widget.ArrayAdapter;
+import android.widget.EditText;
+import android.widget.Spinner;
+import android.widget.TableRow;
+
+import static com.csl.cs710ademoapp.MainActivity.tagSelected;
+
+public class SelectTag {
+ public EditText editTextTagID, editTextSelectOffset, editTextAccessPassword, editTextAccessAntennaPower;
+ public Spinner spinnerSelectBank;
+ public TableRow tableRowSelectMemoryBank, tableRowSelectPassword;
+
+ public SelectTag(Activity activity, int index) {
+ if (index == 2) tableRowSelectMemoryBank = (TableRow) activity.findViewById(R.id.selectMemoryBankRow2);
+ else if (index == 1) tableRowSelectMemoryBank = (TableRow) activity.findViewById(R.id.selectMemoryBankRow1);
+ else tableRowSelectMemoryBank = (TableRow) activity.findViewById(R.id.selectMemoryBankRow);
+ if (index == 2) tableRowSelectPassword = (TableRow) activity.findViewById(R.id.selectPasswordRow2);
+ else if (index == 1) tableRowSelectPassword = (TableRow) activity.findViewById(R.id.selectPasswordRow1);
+ else tableRowSelectPassword = (TableRow) activity.findViewById(R.id.selectPasswordRow);
+
+ if (index == 2) editTextTagID = (EditText) activity.findViewById(R.id.selectTagID2);
+ else if (index == 1) editTextTagID = (EditText) activity.findViewById(R.id.selectTagID1);
+ else editTextTagID = (EditText) activity.findViewById(R.id.selectTagID);
+ if (index == 2) editTextSelectOffset = (EditText) activity.findViewById(R.id.selectMemoryOffset2);
+ else if (index == 1) editTextSelectOffset = (EditText) activity.findViewById(R.id.selectMemoryOffset1);
+ else editTextSelectOffset = (EditText) activity.findViewById(R.id.selectMemoryOffset);
+ //editTextRWSelectOffset.setVisibility(View.VISIBLE);
+
+ if (index == 2) spinnerSelectBank = (Spinner) activity.findViewById(R.id.selectMemoryBank2);
+ else if (index == 1) spinnerSelectBank = (Spinner) activity.findViewById(R.id.selectMemoryBank1);
+ else spinnerSelectBank = (Spinner) activity.findViewById(R.id.selectMemoryBank);
+ ArrayAdapter targetAdapter = ArrayAdapter.createFromResource(activity, R.array.read_memoryBank_options, R.layout.custom_spinner_layout);
+ targetAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+ spinnerSelectBank.setAdapter(targetAdapter);
+ spinnerSelectBank.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
+ @Override
+ public void onItemSelected(AdapterView> parent, View view, int position, long id) {
+ setBankSelected(position);
+ }
+
+ @Override
+ public void onNothingSelected(AdapterView> parent) {
+
+ }
+ });
+
+ if (index == 2) editTextAccessPassword = (EditText) activity.findViewById(R.id.selectPasswordValue2);
+ else if (index == 1) editTextAccessPassword = (EditText) activity.findViewById(R.id.selectPasswordValue1);
+ else editTextAccessPassword = (EditText) activity.findViewById(R.id.selectPasswordValue);
+ editTextAccessPassword.addTextChangedListener(new GenericTextWatcher(editTextAccessPassword, 8));
+ editTextAccessPassword.setText("00000000");
+
+ if (index == 2) editTextAccessAntennaPower = (EditText) activity.findViewById(R.id.selectAntennaPower2);
+ else if (index == 1) editTextAccessAntennaPower = (EditText) activity.findViewById(R.id.selectAntennaPower1);
+ else editTextAccessAntennaPower = (EditText) activity.findViewById(R.id.selectAntennaPower);
+ editTextAccessAntennaPower.setText(String.valueOf(300));
+ }
+
+ public void updateBankSelected() {
+ setBankSelected(-1);
+ }
+ void setBankSelected(int position) {
+ if (position < 0 || position > 2) position = spinnerSelectBank.getSelectedItemPosition();
+ switch (position) {
+ case 0: //if EPC
+ if (tagSelected != null) editTextTagID.setText(tagSelected.getAddress());
+ editTextSelectOffset.setText("32");
+ break;
+ case 1:
+ if (tagSelected != null) { if (tagSelected.getTid() != null) editTextTagID.setText(tagSelected.getTid()); }
+ editTextSelectOffset.setText("0");
+ break;
+ case 2:
+ if (tagSelected != null) { if (tagSelected.getUser() != null) editTextTagID.setText(tagSelected.getUser()); }
+ editTextSelectOffset.setText("0");
+ break;
+ default:
+ break;
+ }
+ }
+}
+
+
+
+package com.csl.cs710ademoapp;
+
+import android.Manifest;
+import android.content.Context;
+import android.content.pm.PackageManager;
+import android.hardware.Sensor;
+import android.hardware.SensorEvent;
+import android.hardware.SensorEventListener;
+import android.hardware.SensorManager;
+import android.location.Location;
+import android.location.LocationListener;
+import android.location.LocationManager;
+import android.os.Bundle;
+import androidx.core.app.ActivityCompat;
+import android.widget.Toast;
+
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import java.util.List;
+
+import static android.content.Context.LOCATION_SERVICE;
+import static android.content.Context.SENSOR_SERVICE;
+
+public class SensorConnector {
+ final boolean DEBUG = false;
+
+ public String getTimeStamp() {
+ SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
+ return sdf.format(new Date());
+ }
+
+ public LocationDevice mLocationDevice;
+ public SensorDevice mSensorDevice;
+
+ private Sensor mAccelerometer;
+ private Sensor mMagnetometer;
+
+ SensorConnector(Context context) {
+ mLocationDevice = new LocationDevice(context);
+ mSensorDevice = new SensorDevice(context);
+ }
+
+ public class LocationDevice {
+ private Context mContext;
+ private LocationManager locationManager;
+ private Location location;
+
+ public String getLocation() {
+ if (location != null) {
+ return Location.convert(location.getLatitude(), Location.FORMAT_DEGREES) + ", " + Location.convert(location.getLongitude(), Location.FORMAT_DEGREES);
+ } else {
+ return "";
+ }
+ }
+
+ private boolean onStatus = false;
+
+ LocationDevice(Context context) {
+ mContext = context;
+
+ PackageManager mPackageManager;
+ mPackageManager = (PackageManager) context.getPackageManager();
+ if (!(mPackageManager.hasSystemFeature(PackageManager.FEATURE_LOCATION))) {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("there is NO Feature_Location");
+ Toast.makeText(context.getApplicationContext(), "there is NO LOCATION_FEATURE in this phone !!! Please use another phone.", Toast.LENGTH_LONG).show();
+ } else locationManager = (LocationManager) context.getSystemService(LOCATION_SERVICE);
+ }
+
+ public void turnOn(boolean onStatus) {
+ if (locationManager != null) {
+ if (true) MainActivity.csLibrary4A.appendToLog("permission.ACCESS_FINE_LOCATION = " + ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION));
+ if (true) MainActivity.csLibrary4A.appendToLog("permission.ACCESS_COARSE_LOCATION = " + ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION));
+ if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
+ Toast.makeText(mContext.getApplicationContext(), "LOCATION_FEATURE permission is NOT GRANTED in this phone !!! Please go to Phone Setup and enable Location Services and Relaunch.", Toast.LENGTH_SHORT).show();
+ } else if (onStatus && this.onStatus == false) {
+ this.onStatus = onStatus;
+ if (true) MainActivity.csLibrary4A.appendToLog("LocationDevice.setRfidOn(): ON with LocationManager: ON");
+ if (true) MainActivity.csLibrary4A.appendToLog("LocationManager.PASSIVE_PROVIDER = " + LocationManager.PASSIVE_PROVIDER);
+ location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
+// locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, locationListener);
+ if (true) locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0, locationListener); //not working in iData2S phone
+ } else if (onStatus == false && this.onStatus) {
+ this.onStatus = onStatus;
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("LocationDevice.setRfidOn(): OFF");
+ locationManager.removeUpdates(locationListener);
+ }
+ }
+ }
+
+ private LocationListener locationListener = new LocationListener() {
+ @Override
+ public void onLocationChanged(Location location) {
+ if (true) MainActivity.csLibrary4A.appendToLog("onLocationChanged(): " + location.getProvider());
+ location = location;
+ }
+
+ @Override
+ public void onStatusChanged(String provider, int status, Bundle extras) {
+ }
+
+ @Override
+ public void onProviderEnabled(String provider) {
+ }
+
+ @Override
+ public void onProviderDisabled(String provider) {
+ }
+ };
+ }
+
+ public class SensorDevice {
+ private Context mContext;
+ private SensorManager mSensorManager;
+ private float[] mOrientation = new float[3];
+
+ public String getEcompass() {
+ String s0, s1, s2;
+ synchronized (mOrientation) {
+ float azimuthInRadians = mOrientation[0];
+ if (azimuthInRadians == 0) return null;
+ float azimuthInDegress = (float) (Math.toDegrees(azimuthInRadians) + 360) % 360;
+ s0 = String.format("%.1f", azimuthInDegress);
+ }
+ return s0; // + ", " + s1 + ", " + s2;
+ }
+
+ private boolean onStatus = false;
+
+ SensorDevice(Context context) {
+ mContext = context;
+
+ mSensorManager = (SensorManager) mContext.getSystemService(SENSOR_SERVICE);
+ List deviceSensors = mSensorManager.getSensorList(Sensor.TYPE_ALL);
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("SensorDevice(): List of sensors");
+ for (int i = 0; i < deviceSensors.size(); i++) {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog(deviceSensors.get(i).getType() + "," + deviceSensors.get(i).getName());
+ }
+ }
+
+ public void turnOn(boolean onStatus) {
+ if (onStatus && this.onStatus == false) {
+ Sensor mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
+ Sensor mMagnetometer = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
+ if (mSensorManager.registerListener(sensorEventListener, mAccelerometer, SensorManager.SENSOR_DELAY_UI) == false) {
+ Toast.makeText(mContext.getApplicationContext(), "ACCELEROMETER is NOT supported in this phone !!! Please use another phone.", Toast.LENGTH_LONG).show();
+ mAccelerometer = null;
+ }
+ if (mSensorManager.registerListener(sensorEventListener, mMagnetometer, SensorManager.SENSOR_DELAY_UI) == false) {
+ if (false) Toast.makeText(mContext.getApplicationContext(), "MAGNETOMETER is NOT supported in this phone !!! Please use another phone.", Toast.LENGTH_LONG).show();
+ mMagnetometer = null;
+ }
+ if (mAccelerometer == null || mMagnetometer == null) {
+ mSensorManager.unregisterListener(sensorEventListener);
+ } else {
+ this.onStatus = onStatus;
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("SensorDevice.setRfidOn(): ON");
+ }
+ } else if (this.onStatus && onStatus == false) {
+ this.onStatus = onStatus;
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("SensorDevice.setRfidOn(): OFF");
+ mSensorManager.unregisterListener(sensorEventListener);
+ }
+ }
+
+ private SensorEventListener sensorEventListener = new SensorEventListener() {
+ private float[] mLastAccelerometer = new float[3];
+ private boolean mLastAccelerometerSet = false;
+ private float[] mLastMagnetometer = new float[3];
+ private boolean mLastMagnetometerSet = false;
+
+ private float[] mR = new float[9];
+
+ @Override
+ public void onSensorChanged(SensorEvent event) {
+ if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
+ if (event.values.length == mLastAccelerometer.length) {
+ System.arraycopy(event.values, 0, mLastAccelerometer, 0, mLastAccelerometer.length);
+ mLastAccelerometerSet = true;
+// appendToLog("onSensorChanged(): updated mAccelerometer");
+ } else {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("onSensorChanged(): mAccelerometer: " + event.values.length);
+ }
+ } else if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
+ if (event.values.length == mLastMagnetometer.length) {
+ System.arraycopy(event.values, 0, mLastMagnetometer, 0, event.values.length);
+ mLastMagnetometerSet = true;
+// appendToLog("onSensorChanged(): updated mMagnetometer");
+ } else {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("onSensorChanged(): mMagnetometer: " + event.values.length);
+ }
+ } else {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("onSensorChanged(): " + event.sensor.getType() + "," + event.sensor.getName());
+ }
+
+ if (mLastAccelerometerSet && mLastMagnetometerSet) {
+ SensorManager.getRotationMatrix(mR, null, mLastAccelerometer, mLastMagnetometer);
+ synchronized (mOrientation) {
+ SensorManager.getOrientation(mR, mOrientation);
+ }
+ mLastAccelerometerSet = false;
+ mLastMagnetometerSet = false;
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("onSensorChanged(): updated mOrientation with mOrientation=" + mOrientation[0]);
+ }
+ }
+
+ @Override
+ public void onAccuracyChanged(Sensor sensor, int accuracy) {
+ }
+ };
+ }
+}
+
+
+
+package com.csl.cs710ademoapp;
+
+import android.os.AsyncTask;
+import android.view.View;
+import android.widget.Button;
+import android.widget.Toast;
+
+public class SettingTask extends AsyncTask {
+ final boolean DEBUG = false;
+ private enum TaskCancelRReason {
+ SAME_SETTING, INVALD_REQUEST, TIMEOUT
+ }
+ private TaskCancelRReason taskCancelReason;
+
+ Button button;
+ boolean sameSetting = false;
+ boolean invalidRequest = false;
+
+ public SettingTask(Button button, boolean sameSetting, boolean invalidRequest) {
+ button.setVisibility(View.INVISIBLE);
+ this.button = button;
+ this.sameSetting = sameSetting;
+ this.invalidRequest = invalidRequest;
+ }
+
+ @Override
+ protected void onPreExecute() {
+ if (sameSetting) {
+ taskCancelReason = TaskCancelRReason.SAME_SETTING;
+ cancel(true);
+ } else if (invalidRequest) {
+ taskCancelReason = TaskCancelRReason.INVALD_REQUEST;
+ cancel(true);
+ }
+ }
+
+ @Override
+ protected String doInBackground(Void... a) {
+ long timeMillis = System.currentTimeMillis();
+ int writeSize = MainActivity.csLibrary4A.mrfidToWriteSize();
+ while (true) {
+ int writeSizeN = MainActivity.csLibrary4A.mrfidToWriteSize();
+ if (writeSizeN == 0) break;
+ if (writeSizeN < writeSize) {
+ writeSize = writeSizeN;
+ timeMillis = System.currentTimeMillis();
+ } else if (System.currentTimeMillis() - timeMillis > 5000) {
+ taskCancelReason = TaskCancelRReason.TIMEOUT;
+ cancel(true);
+ }
+ }
+ return "End of Asynctask()";
+ }
+
+ @Override
+ protected void onProgressUpdate(String... output) { }
+
+ @Override
+ protected void onCancelled() {
+ super.onCancelled();
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("Setting0Fragment.SettingTask.onCancelled()");
+ if (taskCancelReason != null) {
+ switch (taskCancelReason) {
+ case SAME_SETTING:
+ Toast.makeText(MainActivity.mContext, R.string.toast_same_setting, Toast.LENGTH_SHORT).show();
+ break;
+ case INVALD_REQUEST:
+ Toast.makeText(MainActivity.mContext, R.string.toast_invalid_sendHostRequest, Toast.LENGTH_SHORT).show();
+ break;
+ case TIMEOUT:
+ Toast.makeText(MainActivity.mContext, R.string.toast_abort_by_TIMEOUT, Toast.LENGTH_SHORT).show();
+ break;
+ }
+ }
+ button.setVisibility(View.VISIBLE);
+ }
+
+ @Override
+ protected void onPostExecute(String result) {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("Setting0Fragment.SettingTask.onPostExecute(): " + result);
+
+ Toast.makeText(MainActivity.mContext, R.string.toast_saved, Toast.LENGTH_SHORT).show();
+ button.setVisibility(View.VISIBLE);
+ }
+}
+
+
+
+package com.csl.cs710ademoapp;
+
+import android.content.Context;
+
+import androidx.annotation.Keep;
+import androidx.annotation.NonNull;
+
+import com.csl.cslibrary4a.ReaderDevice;
+
+import java.util.ArrayList;
+
+public class SharedObjects {
+ public static class TagsIndex implements Comparable {
+ private String address;
+ private int position;
+
+ @Keep
+ public TagsIndex(String address, int position) {
+ this.address = address;
+ this.position = position;
+ }
+
+ @Keep public String getAddress() {
+ return address;
+ }
+ @Keep public int getPosition() {
+ return position;
+ }
+
+ @Override
+ public int compareTo(@NonNull TagsIndex tagsIndex) {
+ return address.compareTo(tagsIndex.address);
+ }
+ }
+
+ Context context;
+
+ public ArrayList readersList = new ArrayList();
+ public String connectedBleAddressOld = "";
+ public boolean versionWarningShown = false;
+ public int batteryWarningShown = 0;
+
+ public boolean runningInventoryRfidTask = false;
+ public ArrayList tagsList = new ArrayList<>();
+ public ArrayList tagsIndexList = new ArrayList<>();
+ public ArrayList serviceArrayList = new ArrayList();
+
+ public boolean runningInventoryBarcodeTask = false;
+ public ArrayList barsList = new ArrayList<>();
+
+ public CustomMediaPlayer playerO, playerN, playerL;
+
+ public SharedObjects(Context context) {
+ this.context = context;
+ playerO = new CustomMediaPlayer(context, "beeplow.mp3");
+ playerN = new CustomMediaPlayer(context, "beephigh.mp3");
+ playerL = new CustomMediaPlayer(context, "beep3s1khz.wav");
+ }
+}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ #00529c
+ #07274a
+ #FFFFFF
+
+
+
+
+
+
+
+
+ 8dp
+
+
+
+
+
+
+
+
+
+
+ 18sp
+
+
+
+
+ 32sp
+ 15sp
+ 10dp
+ 10dp
+ 10dp
+ 10dp
+ 5dp
+ 2dp
+ 4dp
+ 8dp
+
+
+
+
+
+
+
+ English (US)
+
+ CSL Wedge
+ CS710S Java
+ CS108 Java
+ CSL Data Wedge
+ CSL Java Simple Wedge
+ CSL Java Wedge
+ CS108 Java Wedge
+
+
+ CSL Wedge
+ CSL Java Reader
+ Convergence Systems
+
+ Special Functions
+
+ About
+ Connect
+ Inventory
+ Geiger search
+ Multibank
+ Settings
+ Filters
+ Read / Write
+ Security
+
+ Impinj
+ ImpinJ M775
+ ImpinJ Autotune
+ NXP UCODE 8
+ UCODE DNA
+ BAP
+ Cold Chain
+ Aura-sense
+
+ Select Tag Type
+ Configuration
+ Axzon
+ Magnus
+
+ FM13DT160
+ CTESIUS
+ KX2005X-BL
+ EL-N2ESL
+
+ Register tag
+ Long Read / Write
+ Simple Inventory
+
+
+
+ - Unchanged
+ - Unlock
+ - Permanent Unlock
+ - Lock
+ - Permanent Lock
+
+
+
+
+
+
+
+ - Reser
+ - EPC
+ - TID
+ - User
+
+
+
+ - EPC
+ - TID
+ - User
+
+
+
+ - EPC
+ - User
+
+
+
+ - SGTIN - Serialized Global Trade Item Number
+ - SSCC - Serial Shipping Container Code
+ - SGLN - Serialized Global Location Number
+ - GRAI - Global Returnable Asset Identifier
+ - GIAI - Global Individual Asset Identifier
+ - GSRN - Global Service Relation Number, Recipient
+ - GSRNP - Global Service Relation Number, Provider
+ - GDTI - Global Document Type Identifier
+ - CPI - Component Part Identifier
+ - SGCN - Serialized Globald Coupon Number
+
+
+
+ - No change
+ - Barcode before writing
+ - add 1 after writing
+
+
+
+ - Read/Write Memory
+ - Auth
+ - Get Temperature
+ - Start/Stop Logging
+ - Read/Write Reg
+ - Deep Sleep
+ - Op Mode Check
+ - Initial Regfile
+ - Led Ctrl
+
+
+
+ - user area
+ - unlock
+ - stop logging
+
+
+
+ - temperature
+ - battery voltage
+ - external voltage
+ - external pressure sensore voltage
+
+
+
+ - Hex
+ - Bit
+
+
+
+ - NB_RSSI value filtering
+ - RSSI value filtering
+
+
+
+ - NB_RSSI/RSSI "<"= threshold 1
+ - NB_RSSI/RSSI >= threshold 1
+ - NB_RSSI/RSSI == threshold 1
+ - NB_RSSI/RSSI "<"= threshold 2 and >= threshold 1
+ - NB_RSSI/RSSI "<"= threshold 1 and >= threshold 2
+
+
+
+ - NB_RSSI/RSSI "<"= threshold 1
+ - NB_RSSI/RSSI >= threshold 1
+
+
+
+ - Match(assert SL), else(deassert SL)
+ - Match(assert SL), else(do nothing)
+ - Match(do nothing), else(deassert SL)
+ - Match(invert SL), else(do nothing)
+ - Match(deassert SL), else(assert SL)
+ - Match(deassert SL), else(do nothing)
+ - Match(do nothing), else(assert SL)
+ - Match(do nothing), else(invert SL)
+
+
+
+ - Match(inventory A), else(set inventory B)
+ - Match(inventory A), else(do nothing)
+ - Match(do nothing), else(inventory B)
+ - Match(toggle AB), else(do nothing)
+ - Match(inventory B), else(inventory A)
+ - Match(inventory B), else(do nothing)
+ - Match(do nothing), else(inventory A)
+ - Match(do nothing), else(toggle AB)
+
+
+
+ - Inventoried S0
+ - Inventoried S1
+ - Inventoried S2
+ - Inventoried S3
+ - SL
+
+
+
+ - Voltage
+ - Percentage
+
+
+
+ - dBuV
+ - dBm
+
+
+
+ - New
+ - All
+
+
+
+ - JSON
+ - CSV
+
+
+
+ - Frequency hopping
+ - Fixed channel
+
+
+
+ - Frequency agile
+ - Fixed channel
+
+
+
+ - hide none
+ - hide some
+ - hide all
+
+
+
+ - A
+ - B
+ - Toggle A/B
+
+
+
+ - S0
+ - S1
+ - S2
+ - S3
+
+
+
+ - Dynamic
+ - Fixed
+
+
+
+ - 0
+ - 1
+ - 2
+ - 3
+
+
+
+ - 1 dB
+ - 7 dB
+ - 13 dB
+
+
+
+ - 24 dB
+ - 18 dB
+ - 12 dB
+ - 6 dB
+
+
+
+ - -12 dB
+ - -6 dB
+ - 0 dB
+ - 6 dB
+
+
+
+ - All
+ - All
+ - ~SL
+ - SL
+
+
+
+
+ - second
+ - minute
+ - hour
+ - sample interval
+
+
+
+
+ - second
+ - minute
+ - hour
+ - 5 minutes
+
+
+
+
+ - disable
+ - enable
+
+
+
+ - disable
+ - enable
+
+
+
+ - CS8300
+ - CS8304 Cold Chain
+ - Avery Maxdura
+
+
+
+ - All
+ - S2
+ - S3
+ - Xerxes
+
+
+
+ - code
+ - humidity
+
+
+
+ - \u2103
+ - \u2109
+
+
+
+ - All
+ - S2
+ - S3
+
+
+
+ - temperature
+ - snsor
+
+
+
+ - New line(0x0A)
+ - Tab(0x09)
+ - Comma(0x2C)
+ - Space(0x20)
+ - None
+
+
+
+ - RFID in EPC
+ - RFID in Sgtin-96
+ - Barcode
+
+
+
+ - M775
+ - M780/M781
+ - M830/M850
+ - M770
+ - M730/M750
+ - Monza R6-A/B
+ - Monza R6-P
+ - Monza X8K
+ - Others
+
+
+
+ - ucode 8
+ - ucode dna
+ - Others
+
+
+
+ - em4152 aura-sense
+ - em4325 custom cold-chain
+ - CS9010 BAP
+ - Others
+
+
+
+
+
+
+
+
+
+ No Device Found
+ No Tag Found
+ No BarCode Found
+
+
+ Available Readers
+
+
+
+
+ Bluetooth is Not Connected, Please Connect
+ Updating data. Please wait.
+ Finishing tag data upload
+ Finish as STOP is pressed
+ Finish as BUTTON is released
+ Finish as TIMEOUT
+ Finish as RFID RESET
+ Finish as COMMAND END is received
+ SUCCESS
+ FAILURE
+ BLE is connected
+ Setup problem after connection. Disconnect
+ Invalid Range. Operation is cancelled.
+ Invalid sendHostRequest. Operation is cancelled.
+ Same setting. Need no update. Operation is cancelled.
+ Saved new setting.
+ Please select reader first
+ "Permissions are not granted. Please allow them in system setting."
+
+
+ START
+ Tag Pattern
+ Password
+ Password
+ Memory Bank
+ READ
+ READ KEY
+ WRITE
+ WRITE KEY
+ Reserved Memory
+ Offset
+ Size
+ Kill PW
+ Access PW
+ EPC
+ PC
+ EPC
+ XPC
+ EPC Memory
+ TID Memory
+ User Memory
+ Tone
+ Threshold =
+ Profile(0-3)
+ Antenna cycle(0-65535)
+ Antenna dwell(0-65535ms)
+ Antenna power(0-300)
+ Battery Display
+ Query target
+ Query algorithm
+ Start Q(0-15)
+ Q Value(0-15)
+ Maximum Q(0-15)
+ Minimum Q(0-15)
+ Retry(0-255)
+ Run til zero
+ Mask data
+ KILL
+ SAVE
+ Bit Offset (decimal)
+ Index
+ Target
+ Action
+ Enable Filter
+ match on ~EPC (not EPC)
+ Convergence Systems Limited
+ Application Version
+ Library Version
+ Time stamp
+ GPS location
+ E-Compass
+ Bluetooth device address
+ Bluetooth Rssi level
+ Rfid module status
+ Barcode module status
+ Drawer Item
+ Read/Write
+ Inventory
+ Register Tag
+ Settings
+ Geiger Search
+ Filters
+ Press to Scan/Connect Reader
+ Security
+ Special Functions
+
+ Inventory\n
+ Configuration\n
+ Geiger Search\n
+
+ Longjing EL-N2ESL\nCS6861
+ EL-N2ESL CS6861
+
+ Unable to connect device
+ :
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ android.nfc.tech.Ndef
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+package com.csl.cslibrary4a;
+
+import androidx.fragment.app.Fragment;
+import androidx.fragment.app.FragmentManager;
+import androidx.fragment.app.FragmentStatePagerAdapter;
+import androidx.viewpager.widget.PagerAdapter;
+
+public class AdapterTab extends FragmentStatePagerAdapter {
+ private int iNumOfTabs;
+ public Fragment fragment0, fragment1, fragment2, fragment3, fragment4 = null;
+
+ public AdapterTab(FragmentManager fm, int iNumOfTabs) {
+ super(fm);
+ this.iNumOfTabs = iNumOfTabs;
+ }
+
+ @Override
+ public Fragment getItem(int index) {
+ Fragment fragment = null;
+ switch (index) {
+ case 0:
+ fragment = fragment0;
+ break;
+ case 1:
+ fragment = fragment1;
+ break;
+ case 2:
+ fragment = fragment2;
+ break;
+ case 3:
+ fragment = fragment3;
+ break;
+ case 4:
+ fragment = fragment4;
+ break;
+ default:
+ break;
+ }
+ return fragment;
+ }
+
+ @Override
+ public int getCount() {
+ return iNumOfTabs;
+ }
+
+ @Override
+ public int getItemPosition(Object object) {
+ return PagerAdapter.POSITION_NONE;
+ }
+
+ public void setFragment(int index, Fragment fragment) {
+ switch (index) {
+ case 0:
+ fragment0 = fragment;
+ break;
+ case 1:
+ fragment1 = fragment;
+ break;
+ case 2:
+ fragment2 = fragment;
+ break;
+ case 3:
+ fragment3 = fragment;
+ break;
+ case 4:
+ fragment4 = fragment;
+ break;
+ default:
+ break;
+ }
+ }
+}
+
+
+
+package com.csl.cslibrary4a;
+
+import java.security.InvalidKeyException;
+import java.security.Key;
+import java.security.NoSuchAlgorithmException;
+
+import javax.crypto.*;
+import javax.crypto.spec.IvParameterSpec;
+import javax.crypto.spec.SecretKeySpec;
+
+public class AesCmac {
+ private static final byte CONSTANT = (byte) 0x87;
+ private static final int BLOCK_SIZE = 16;
+
+ private int macLength;
+ private Cipher aesCipher;
+
+ private byte[] buffer;
+ private int bufferCount;
+
+ private byte[] k1;
+ private byte[] k2;
+
+ public AesCmac() throws NoSuchAlgorithmException {
+ this(BLOCK_SIZE);
+ }
+
+ public AesCmac(int length) throws NoSuchAlgorithmException {
+ if (length > BLOCK_SIZE) {
+ throw new NoSuchAlgorithmException("AES CMAC maximum length is " + BLOCK_SIZE);
+ }
+
+ try {
+ macLength = length;
+ aesCipher = Cipher.getInstance("AES/CBC/NOPADDING");
+ buffer = new byte[BLOCK_SIZE];
+ } catch (NoSuchPaddingException nspe) {
+ nspe.printStackTrace();
+ }
+ }
+
+ private byte[] doubleSubKey(byte[] k) {
+ byte[] ret = new byte[k.length];
+
+ boolean firstBitSet = ((k[0]&0x80) != 0);
+ for (int i=0; i 0) {
+ System.arraycopy(data, 0, buffer, bufferCount, BLOCK_SIZE-bufferCount);
+ try {
+ aesCipher.update(buffer, 0, BLOCK_SIZE, buffer, 0);
+ } catch (ShortBufferException sbe) {}
+ currentOffset += BLOCK_SIZE-bufferCount;
+ bufferCount = 0;
+ }
+
+ // Transform all the full blocks in data
+ while (currentOffset+BLOCK_SIZE < data.length) {
+ try {
+ aesCipher.update(data, currentOffset, BLOCK_SIZE, buffer, 0);
+ } catch (ShortBufferException sbe) {}
+ currentOffset += BLOCK_SIZE;
+ }
+
+ // Save the leftover bytes to buffer
+ if (currentOffset != data.length) {
+ System.arraycopy(data, currentOffset, buffer, 0, data.length-currentOffset);
+ bufferCount = data.length-currentOffset;
+ }
+ }
+
+ public final byte[] doFinal() {
+ byte[] subKey = k1;
+ if (bufferCount < BLOCK_SIZE) {
+ // Add padding and XOR with k2 instead
+ buffer[bufferCount] = (byte) 0x80;
+ for (int i=bufferCount+1; i
+
+
+package com.csl.cslibrary4a;
+
+import android.content.Context;
+import android.widget.TextView;
+import android.widget.Toast;
+
+import java.util.ArrayList;
+
+public class BarcodeConnector {
+ boolean DEBUG_PKDATA;
+ public boolean userDebugEnableDefault = false;
+ public boolean userDebugEnable = userDebugEnableDefault;
+
+ Context context; Utility utility;
+ public BarcodeConnector(Context context, Utility utility) {
+ this.context = context;
+ this.utility = utility;
+ }
+ private String byteArrayToString(byte[] packet) { return utility.byteArrayToString(packet); }
+ private boolean compareArray(byte[] array1, byte[] array2, int length) { return utility.compareByteArray(array1, array2, length); }
+ private void appendToLog(String s) { utility.appendToLog(s); }
+ private void appendToLogView(String s) { utility.appendToLogView(s); }
+
+ public enum BarcodePayloadEvents {
+ BARCODE_NULL,
+ BARCODE_POWER_ON, BARCODE_POWER_OFF, BARCODE_SCAN_START, BARCODE_COMMAND, BARCODE_VIBRATE_ON, BARCODE_VIBRATE_OFF,
+ BARCODE_DATA_READ, BARCODE_GOOD_READ,
+ }
+ public static class CsReaderBarcodeData {
+ public boolean waitUplinkResponse = false;
+ boolean downlinkResponsed = false;
+ public BarcodePayloadEvents barcodePayloadEvent;
+ public byte[] dataValues;
+ }
+
+ private boolean onStatus = false; public boolean getOnStatus() { return onStatus; }
+ private boolean vibrateStatus = false; boolean getVibrateStatus() { return vibrateStatus; }
+
+ public interface BarcodeConnectorCallback {
+ boolean callbackMethod(byte[] dataValues, CsReaderBarcodeData csReaderBarcodeData);
+ }
+ public BarcodeConnectorCallback barcodeConnectorCallback = null;
+
+ public ArrayList barcodeToWrite = new ArrayList<>();
+ public ArrayList mBarcodeToRead = new ArrayList<>();
+
+ private boolean arrayTypeSet(byte[] dataBuf, int pos, BarcodePayloadEvents event) {
+ boolean validEvent = false;
+ switch (event) {
+ case BARCODE_POWER_ON:
+ validEvent = true;
+ break;
+ case BARCODE_POWER_OFF:
+ dataBuf[pos] = 1;
+ validEvent = true;
+ break;
+ case BARCODE_SCAN_START:
+ dataBuf[pos] = 2;
+ validEvent = true;
+ break;
+ case BARCODE_COMMAND:
+ dataBuf[pos] = 3;
+ validEvent = true;
+ break;
+ case BARCODE_VIBRATE_ON:
+ dataBuf[pos] = 4;
+ validEvent = true;
+ break;
+ case BARCODE_VIBRATE_OFF:
+ dataBuf[pos] = 5;
+ validEvent = true;
+ break;
+ }
+ return validEvent;
+ }
+ private byte[] writeBarcode(CsReaderBarcodeData data, boolean usbConnection) {
+ boolean DEBUG = false;
+ int datalength = 0;
+ if (data.dataValues != null) datalength = data.dataValues.length;
+ byte[] dataOutRef = new byte[] { (byte) 0xA7, (byte) 0xB3, 2, (byte) 0x6A, (byte) 0x82, (byte) 0x37, 0, 0, (byte) 0x90, 0};
+ if (usbConnection) dataOutRef[1] = (byte) 0xE6;
+
+ byte[] dataOut = new byte[10 + datalength];
+ if (datalength != 0) {
+ System.arraycopy(data.dataValues, 0, dataOut, 10, datalength);
+ dataOutRef[2] += datalength;
+ }
+ System.arraycopy(dataOutRef, 0, dataOut, 0, dataOutRef.length);
+
+ if (arrayTypeSet(dataOut, 9, data.barcodePayloadEvent)) {
+ if (DEBUG) {
+ appendToLog("BarStreamOut: " + byteArrayToString(dataOut));
+ appendToLogView("BOut: " + byteArrayToString(dataOut));
+ }
+ if (DEBUG_PKDATA) appendToLog(String.format("PkData: write Barcode.%s.%s with mBarcodeDevice.sendDataToWriteSent = %d", data.barcodePayloadEvent.toString(), byteArrayToString(data.dataValues), sendDataToWriteSent));
+ if (sendDataToWriteSent != 0) appendToLog("!!! mBarcodeDevice.sendDataToWriteSent = " + sendDataToWriteSent);
+ return dataOut;
+ }
+ return null;
+ }
+ public int barcodePowerOnTimeOut = 0;
+ public boolean isMatchBarcodeToWrite(ConnectorData connectorData) {
+ boolean match = false, DEBUG = false;
+ if (barcodeToWrite.size() != 0 && connectorData.dataValues[0] == (byte)0x90) {
+ if (DEBUG) appendToLog("csReadData = " + byteArrayToString(connectorData.dataValues));
+ //if (DEBUG) appendToLog("tempDisconnect: icsModel = " + bluetoothConnector.getCsModel() + ", barcodeToWrite.size = " + barcodeToWrite.size());
+ if (barcodeToWrite.size() != 0) if (DEBUG) appendToLog("barcodeToWrite(0) = " + barcodeToWrite.get(0).barcodePayloadEvent.toString() + "," + byteArrayToString(barcodeToWrite.get(0).dataValues));
+ byte[] dataInCompare = new byte[]{(byte) 0x90, 0};
+ if (arrayTypeSet(dataInCompare, 1, barcodeToWrite.get(0).barcodePayloadEvent) && (connectorData.dataValues.length == dataInCompare.length + 1)) {
+ if (match = compareArray(connectorData.dataValues, dataInCompare, dataInCompare.length)) {
+ boolean bprocessed = false;
+ byte[] data1 = new byte[connectorData.dataValues.length - 2]; System.arraycopy(connectorData.dataValues, 2, data1, 0, data1.length);
+ if (DEBUG_PKDATA) appendToLog("PkData: matched Barcode.Reply with payload = " + byteArrayToString(connectorData.dataValues) + " for writeData Barcode." + barcodeToWrite.get(0).barcodePayloadEvent.toString());
+ if (connectorData.dataValues[2] != 0) {
+ if (DEBUG) appendToLog("Barcode.reply data is found with error");
+ } else if (true) { //testing bluetoothConnector.getCsModel() == 108) {
+ if (barcodeToWrite.get(0).barcodePayloadEvent == BarcodePayloadEvents.BARCODE_POWER_ON) {
+ barcodePowerOnTimeOut = 1000;
+ if (DEBUG) appendToLog("tempDisconnect: BARCODE_POWER_ON");
+ onStatus = true;
+ if (DEBUG_PKDATA | connectorData.dataValues[2] != 0) appendToLog("PkData: matched Barcode.Reply.PowerOn with result = " + connectorData.dataValues[2] + " and onStatus = " + onStatus);
+ bprocessed = true;
+ } else if (barcodeToWrite.get(0).barcodePayloadEvent == BarcodePayloadEvents.BARCODE_POWER_OFF) {
+ if (DEBUG) appendToLog("tempDisconnect: BARCODE_POWER_OFF");
+ onStatus = false;
+ if (DEBUG_PKDATA | connectorData.dataValues[2] != 0) appendToLog("PkData: matched Barcode.Reply.PowerOff with result = " + connectorData.dataValues[2] + " and onStatus = " + onStatus);
+ bprocessed = true;
+ } else if (barcodeToWrite.get(0).barcodePayloadEvent == BarcodePayloadEvents.BARCODE_VIBRATE_ON) {
+ vibrateStatus = true;
+ if (DEBUG_PKDATA | connectorData.dataValues[2] != 0) appendToLog("PkData: matched Barcode.Reply.VibrateOn with result = " + connectorData.dataValues[2] + " and vibrateStatus = " + vibrateStatus);
+ bprocessed = true;
+ } else if (barcodeToWrite.get(0).barcodePayloadEvent == BarcodePayloadEvents.BARCODE_VIBRATE_OFF) {
+ vibrateStatus = false;
+ if (DEBUG_PKDATA | connectorData.dataValues[2] != 0) appendToLog("PkData: matched Barcode.Reply.VibrateOff with result = " + connectorData.dataValues[2] + " and vibrateStatus = " + vibrateStatus);
+ bprocessed = true;
+ } else if (barcodeToWrite.get(0).barcodePayloadEvent == BarcodePayloadEvents.BARCODE_COMMAND) {
+ barcodePowerOnTimeOut = 500;
+ if (DEBUG_PKDATA | connectorData.dataValues[2] != 0) appendToLog("PkData: matched Barcode.Reply.Command with result = " + connectorData.dataValues[2] + " and barcodePowerOnTimeOut = " + barcodePowerOnTimeOut);
+ bprocessed = true;
+ } else {
+ bprocessed = true;
+ if (DEBUG_PKDATA) appendToLog("matched Barcode.Other.Reply data is found.");
+ }
+
+ CsReaderBarcodeData csReaderBarcodeData = barcodeToWrite.get(0);
+ if (csReaderBarcodeData.waitUplinkResponse) {
+ csReaderBarcodeData.downlinkResponsed = true; iOkCount = 0;
+ barcodeToWrite.set(0, csReaderBarcodeData);
+ if (DEBUG_PKDATA) appendToLog("PkData: barcodeToWrite.downlinkResponsed is set and waiting uplink data");
+ utility.writeDebug2File("Up31 " + barcodeToWrite.get(0).barcodePayloadEvent.toString() + ", " + byteArrayToString(data1));
+ return true;
+ }
+ } else {
+ barcodeFailure = true;
+ appendToLog("Not matched Barcode.Reply");
+ }
+ String string = "Up31 " + (bprocessed ? "" : "Unprocessed, ") + barcodeToWrite.get(0).barcodePayloadEvent.toString() + ", " + byteArrayToString(data1);
+ utility.writeDebug2File(string);
+ barcodeToWrite.remove(0); sendDataToWriteSent = 0; mDataToWriteRemoved = true; appendToLog("barcodeToWrite remove0 with length = " + barcodeToWrite.size());
+ if (DEBUG_PKDATA) appendToLog("PkData: new barcodeToWrite size = " + barcodeToWrite.size());
+ }
+ }
+ }
+ return match;
+ }
+
+ public int sendDataToWriteSent = 0; public boolean mDataToWriteRemoved = false;
+ public boolean barcodeFailure = false;
+ public byte[] sendBarcodeToWrite(boolean usbConnection) {
+ boolean DEBUG = false;
+ /*if (barcodePowerOnTimeOut != 0) {
+ if (DEBUG) appendToLog("barcodePowerOnTimeOut = " + barcodePowerOnTimeOut + ", barcodeToWrite.size() = " + barcodeToWrite.size());
+ return false;
+ }
+ if (barcodeToWrite.size() != 0) {*/
+ //if (DEBUG) appendToLog("barcodeToWrite.size = " + barcodeToWrite.size());
+ //appendToLog("testing 3"); appendToLog("testing 4");
+ //if (false) { //testing isBleConnected() == false) {
+ // barcodeToWrite.clear();
+ //} else if (false) { //testing System.currentTimeMillis() - btSendTime > btSendTimeOut) {
+ BarcodePayloadEvents barcodePayloadEvents = barcodeToWrite.get(0).barcodePayloadEvent;
+ //if (DEBUG) appendToLog("barcodePayloadEvents = " + barcodePayloadEvents.toString());
+ boolean isBarcodeData = false;
+ if (barcodePayloadEvents == BarcodePayloadEvents.BARCODE_SCAN_START || barcodePayloadEvents == BarcodePayloadEvents.BARCODE_COMMAND) isBarcodeData = true;
+ //appendToLog("BarcodePayloadEvents = " + barcodePayloadEvents.toString() + ", barcodeFailure = " + barcodeFailure + ", isBarcodeData = " + isBarcodeData + ", sendDataToWriteSent = " + sendDataToWriteSent);
+ if (barcodeFailure && isBarcodeData) {
+ barcodeToWrite.remove(0); sendDataToWriteSent = 0; mDataToWriteRemoved = true; appendToLog("barcodeToWrite remove0 with length = " + barcodeToWrite.size());
+ } else if (sendDataToWriteSent >= 5 && isBarcodeData) {
+ int oldSize = barcodeToWrite.size();
+ barcodeToWrite.remove(0); sendDataToWriteSent = 0; mDataToWriteRemoved = true; appendToLog("barcodeToWrite remove0 with length = " + barcodeToWrite.size());
+ if (DEBUG) appendToLog("Removed after sending count-out with oldSize = " + oldSize + ", updated barcodeToWrite.size() = " + barcodeToWrite.size());
+ if (DEBUG) appendToLog("Removed after sending count-out.");
+ String string = "Problem in sending data to Barcode Module. Removed data sending after count-out";
+ if (userDebugEnable) Toast.makeText(context, string, Toast.LENGTH_SHORT).show();
+ else appendToLogView(string);
+ //appendToLog("testing 5"); //testing if (bluetoothConnector.getCsModel() == 108) Toast.makeText(context, "No barcode present on Reader", Toast.LENGTH_LONG).show();
+ barcodeFailure = true; // disconnect(false);
+ } else {
+ if (DEBUG) appendToLog("size = " + barcodeToWrite.size() + ", PayloadEvents = " + barcodeToWrite.get(0).barcodePayloadEvent.toString());
+ sendDataToWriteSent++;
+ return writeBarcode(barcodeToWrite.get(0), usbConnection);
+ /*if (retValue) {
+ sendDataToWriteSent++;
+ mDataToWriteRemoved = false;
+ } else {
+ //if (DEBUG) appendToLogView("failure to send " + barcodeToWrite.get(0).barcodePayloadEvent.toString());
+ barcodeToWrite.remove(0); sendDataToWriteSent = 0; mDataToWriteRemoved = true; appendToLog("barcodeToWrite remove0 with length = " + barcodeToWrite.size());
+ }
+ return true;*/
+ }
+ //}
+ //}
+ return null;
+ }
+
+ int iOkCount = 0;
+ public boolean isBarcodeToRead(ConnectorData connectorData) {
+ boolean found = false, DEBUG = false;
+
+ if (connectorData.dataValues[0] == (byte) 0x91) {
+ if (DEBUG_PKDATA) appendToLog("PkData: found Barcode.Uplink with payload = " + byteArrayToString(connectorData.dataValues));
+ CsReaderBarcodeData csReaderBarcodeData = new CsReaderBarcodeData();
+ switch (connectorData.dataValues[1]) {
+ case 0:
+ csReaderBarcodeData.barcodePayloadEvent = BarcodePayloadEvents.BARCODE_DATA_READ;
+ byte[] dataValues = new byte[connectorData.dataValues.length - 2];
+ System.arraycopy(connectorData.dataValues, 2, dataValues, 0, dataValues.length);
+ if (DEBUG_PKDATA) appendToLog("PkData: found Barcode.Uplink.DataRead with payload = " + byteArrayToString(dataValues));
+ //commandType = null;
+ if (barcodeToWrite.size() > 0) {
+ if (barcodeToWrite.get(0).downlinkResponsed) {
+ if (barcodeConnectorCallback != null) found = barcodeConnectorCallback.callbackMethod(dataValues, csReaderBarcodeData);
+ break;
+ }
+ }
+ /*for (int i=0; false && commandType == null && i < dataValues.length; i++) {
+ if (dataValues[i] == 0x28 || dataValues[i] == 0x29 // ( )
+ || dataValues[i] == 0x5B || dataValues[i] == 0x5D || dataValues[i] == 0x5C
+ || dataValues[i] == 0x7B || dataValues[i] == 0x7D
+ ) dataValues[i] = 0x20;
+ }*/
+ csReaderBarcodeData.dataValues = dataValues;
+ mBarcodeToRead.add(csReaderBarcodeData);
+ if (DEBUG_PKDATA) appendToLog("PkData: uplink data Barcode.DataRead." + byteArrayToString(dataValues) + " is added to mBarcodeToRead");
+ found = true;
+ break;
+ case 1:
+ if (DEBUG) appendToLog("BarStream: matched Barcode.good data is found");
+ csReaderBarcodeData.barcodePayloadEvent = BarcodePayloadEvents.BARCODE_GOOD_READ;
+ csReaderBarcodeData.dataValues = null;
+ mBarcodeToRead.add(csReaderBarcodeData);
+ if (DEBUG_PKDATA) appendToLog("PkData: uplink data Barcode.GoodRead is added to mBarcodeToRead");
+ found = true;
+ break;
+ }
+ }
+ if (found && DEBUG) appendToLog("found Barcode.read data = " + byteArrayToString(connectorData.dataValues));
+ return found;
+ }
+}
+
+
+
+package com.csl.cslibrary4a;
+
+import android.content.Context;
+import android.widget.TextView;
+
+import androidx.annotation.Keep;
+
+import java.util.Arrays;
+
+public class BarcodeNewland {
+ public enum BarcodeCommandTypes {
+ COMMAND_COMMON, COMMAND_SETTING, COMMAND_QUERY
+ }
+ BarcodeCommandTypes commandType;
+
+ Context context; Utility utility; BarcodeConnector barcodeConnector; boolean barcode2TriggerMode;
+ public BarcodeNewland(Context context, Utility utility, BarcodeConnector barcodeConnector, boolean barcode2TriggerMode) {
+ this.context = context;
+ this.barcodeConnector = barcodeConnector;
+ this.barcode2TriggerMode = barcode2TriggerMode;
+ this.utility = utility;
+ }
+
+ void appendToLog(String s) { utility.appendToLog(s); }
+ String byteArrayToString(byte[] packet) { return utility.byteArrayToString(packet); }
+
+ public boolean barcodeSendCommand(byte[] barcodeCommandData) {
+ BarcodeConnector.CsReaderBarcodeData csReaderBarcodeData = new BarcodeConnector.CsReaderBarcodeData();
+ csReaderBarcodeData.barcodePayloadEvent = BarcodeConnector.BarcodePayloadEvents.BARCODE_COMMAND;
+ csReaderBarcodeData.waitUplinkResponse = true;
+ csReaderBarcodeData.dataValues = barcodeCommandData;
+ barcodeConnector.barcodeToWrite.add(csReaderBarcodeData); appendToLog("barcodeToWrite added with size = " + barcodeConnector.barcodeToWrite.size());
+ if (utility.DEBUG_PKDATA) {
+ //if (barcodeCommandData[0] == 'n')
+ appendToLog("PkData: add " + csReaderBarcodeData.barcodePayloadEvent.toString() + "." + byteArrayToString(csReaderBarcodeData.dataValues) + " to barcodeToWrite with length = " + barcodeConnector.barcodeToWrite.size());
+ }
+ return true;
+ }
+
+ public byte bBarcodeTriggerMode = (byte)0xff;
+ //public boolean barcode2TriggerModeDefault = true, barcode2TriggerMode = barcode2TriggerModeDefault;
+ boolean barcodeReadTriggerStart() {
+ BarcodeConnector.CsReaderBarcodeData csReaderBarcodeData = new BarcodeConnector.CsReaderBarcodeData();
+ csReaderBarcodeData.barcodePayloadEvent = BarcodeConnector.BarcodePayloadEvents.BARCODE_SCAN_START;
+ csReaderBarcodeData.waitUplinkResponse = false;
+ barcode2TriggerMode = false;
+ boolean bValue = barcodeConnector.barcodeToWrite.add(csReaderBarcodeData); appendToLog("barcodeToWrite added with size = " + barcodeConnector.barcodeToWrite.size());
+ appendToLog("add " + csReaderBarcodeData.barcodePayloadEvent.toString() + " to barcodeToWrite with length = " + barcodeConnector.barcodeToWrite.size());
+ return bValue;
+ }
+ public boolean barcodeSendCommandTrigger() {
+ boolean retValue = true;
+ barcode2TriggerMode = true; bBarcodeTriggerMode = 0x30; if (false) appendToLog("Set trigger reading mode to TRIGGER");
+ if (retValue) retValue = barcodeSendCommand("nls0006010;".getBytes());
+ if (retValue) retValue = barcodeSendCommand("nls0302000;".getBytes());
+ if (retValue) retValue = barcodeSendCommand("nls0313000=3000;nls0313010=1000;nls0313040=1000;nls0302000;nls0007010;".getBytes());
+ if (retValue) retValue = barcodeSendCommand("nls0001150;nls0006000;".getBytes());
+ return retValue;
+ }
+
+ public byte[] prefixRef = { 0x02, 0x00, 0x07, 0x10, 0x17, 0x13 };
+ public byte[] suffixRef = { 0x05, 0x01, 0x11, 0x16, 0x03, 0x04 };
+ public boolean barcodeSendCommandSetPreSuffix() {
+ boolean retValue = true;
+ appendToLog("BarStream: BarcodePrefix BarcodeSuffix are SET");
+ if (retValue) retValue = barcodeSendCommand("nls0006010;".getBytes());
+ if (retValue) retValue = barcodeSendCommand("nls0311010;".getBytes());
+ if (retValue) retValue = barcodeSendCommand("nls0317040;".getBytes());
+ if (retValue) retValue = barcodeSendCommand("nls0305010;".getBytes());
+ String string = "nls0300000=0x" + byteArrayToString(prefixRef) + ";"; appendToLog("Set Prefix string = " + string);
+ if (retValue) retValue = barcodeSendCommand(string.getBytes());
+ if (retValue) retValue = barcodeSendCommand("nls0306010;".getBytes());
+ string = "nls0301000=0x" + byteArrayToString(suffixRef) + ";"; appendToLog("Set Suffix string = " + string);
+ if (retValue) retValue = barcodeSendCommand(string.getBytes());
+ if (retValue) retValue = barcodeSendCommand("nls0308030;".getBytes());
+ if (retValue) retValue = barcodeSendCommand("nls0307010;".getBytes());
+ if (retValue) retValue = barcodeSendCommand("nls0309010;nls0310010;".getBytes()); //enable terminator, set terminator as 0x0D
+ if (retValue) retValue = barcodeSendCommand("nls0502110;".getBytes());
+ if (retValue) barcodeSendCommand("nls0001150;nls0006000;".getBytes());
+ if (retValue) {
+ bytesBarcodePrefix = prefixRef;
+ bytesBarcodeSuffix = suffixRef;
+ }
+ return retValue;
+ }
+
+ public boolean barcodeSendCommandResetPreSuffix() {
+ boolean retValue = true;
+ if (retValue) barcodeSendCommand("nls0006010;".getBytes());
+ if (retValue) barcodeSendCommand("nls0311000;".getBytes());
+ if (retValue) retValue = barcodeSendCommand("nls0300000=;".getBytes());
+ if (retValue) retValue = barcodeSendCommand("nls0301000=;".getBytes());
+ if (retValue) barcodeSendCommand("nls0006000;".getBytes());
+ if (retValue) {
+ bytesBarcodePrefix = null;
+ bytesBarcodeSuffix = null;
+ }
+ return retValue;
+ }
+
+ boolean barcodeSendCommandLoadUserDefault() {
+ boolean retValue = barcodeSendCommand("nls0006010;".getBytes());
+ if (retValue) retValue = barcodeSendCommand("nls0001160;".getBytes());
+ if (retValue) retValue = barcodeSendCommand("nls0006000;".getBytes());
+ return retValue;
+ }
+
+ public boolean barcodeSendCommandConinuous() {
+ boolean retValue = barcodeSendCommand("nls0006010;".getBytes());
+ if (retValue) retValue = barcodeSendCommand("nls0302020;".getBytes());
+ if (retValue) retValue = barcodeSendCommand("nls0006000;".getBytes());
+ return retValue;
+ }
+
+ boolean barcodeSendQuerySystem() {
+ byte[] datatt = new byte[] { 0x7E, 0x01, 0x30, 0x30, 0x30, 0x30, 0x40, 0x5F, 0x5F, 0x5F, 0x3F, 0x3B, 0x03 };
+ barcodeSendCommand(datatt);
+
+ byte[] datat = new byte[] { 0x7E, 0x01,
+ 0x30, 0x30, 0x30, 0x30,
+ 0x40, 0x51, 0x52, 0x59, 0x53, 0x59, 0x53, 0x2C, 0x50, 0x44, 0x4E, 0x2C, 0x50, 0x53, 0x4E, 0x3B,
+ 0X03 };
+// return barcodeSendQuery(datat);
+ return barcodeSendCommand(datat);
+ }
+ public boolean barcodeSendCommandItf14Cksum() {
+ return barcodeSendCommand("nls0006010;nls0405100;nls0006000".getBytes());
+ }
+
+ boolean barcodeSendQuery(byte[] data) {
+ byte bytelrc = (byte)0xff;
+ for (int i = 2; i < data.length - 1; i++) {
+ bytelrc ^= data[i];
+ }
+ if (false) appendToLog(String.format("BarStream: bytelrc = %02X, last = %02X", (byte)bytelrc, data[data.length-1]));
+ data[data.length-1] = bytelrc;
+ return barcodeSendCommand(data);
+ }
+
+ boolean barcodeSendQueryVersion() {
+ byte[] data = new byte[] { 0x7E, 0x00,
+ 0x00, 0x02,
+ 0x33, 0x47,
+ 0 };
+ return barcodeSendQuery(data);
+ }
+
+ public String getBarcodeVersion() {
+ String strValue = getVersion();
+ if (strValue == null) barcodeSendQueryVersion();
+ return strValue;
+ }
+
+ boolean barcodeSendQueryESN() {
+ byte[] datat = new byte[] { 0x7E, 0x00,
+ 0x00, 0x05,
+ 0x33, 0x48, 0x30, 0x32, 0x30,
+ (byte)0xb2 };
+ return barcodeSendQuery(datat);
+ }
+
+ public String getBarcodeESN() {
+ String strValue = getESN();
+ if (strValue == null) barcodeSendQueryESN();
+ return strValue;
+ }
+
+ boolean barcodeSendQuerySerialNumber() {
+ byte[] datat = new byte[] { 0x7E, 0x00,
+ 0x00, 0x05,
+ 0x33, 0x48, 0x30, 0x33, 0x30,
+ (byte)0xb2 };
+ return barcodeSendQuery(datat);
+ }
+ public String getBarcodeSerial() {
+ String strValue = getSerialNumber();
+ if (strValue == null) barcodeSendQuerySerialNumber();
+ return strValue;
+ }
+
+ boolean barcodeSendQueryDate() {
+ byte[] datat = new byte[] { 0x7E, 0x00,
+ 0x00, 0x05,
+ 0x33, 0x48, 0x30, 0x34, 0x30,
+ (byte)0xb2 };
+ return barcodeSendQuery(datat);
+ }
+ public String getBarcodeDate() {
+ String strValue = getDate();
+ if (strValue == null) barcodeSendQueryDate();
+ String strValue1 = getBarcodeESN();
+ if (strValue1 != null && strValue1.length() != 0) strValue += (", " + strValue1);
+ return strValue;
+ }
+ public boolean barcodeSendQuerySelfPreSuffix() {
+ byte[] data = new byte[] { 0x7E, 0x00,
+ 0x00, 0x02,
+ 0x33, 0x37,
+ (byte)0xf9 };
+ return barcodeSendQuery(data);
+ }
+ public boolean barcodeSendQueryReadingMode() {
+ byte[] data = new byte[] { 0x7E, 0x00,
+ 0x00, 0x05,
+ 0x33, 0x44, 0x30, 0x30, 0x30,
+ (byte)0xbd };
+ return barcodeSendQuery(data);
+ }
+ public boolean barcodeSendQueryPrefixOrder() {
+ byte[] data = new byte[] { 0x7E, 0x00,
+ 0x00, 0x02,
+ 0x33, 0x42,
+ 0 };
+ return barcodeSendQuery(data);
+ }
+ public boolean barcodeSendQueryEnable2dBarCodes() {
+ byte[] data = new byte[] { 0x7E, 0x00,
+ 0x00, 0x02,
+ 0x33, 0x33,
+ 0 };
+ return barcodeSendQuery(data);
+ }
+ public boolean barcodeSendQueryDelayTimeOfEachReading() {
+ byte[] data = new byte[] { 0x7E, 0x00,
+ 0x00, 0x05,
+ 0x33, 0x44, 0x30, 0x33, 0x30,
+ 0 };
+ return barcodeSendQuery(data);
+ }
+ public boolean barcodeSendQueryNoDuplicateReading() {
+ byte[] data = new byte[] { 0x7E, 0x00,
+ 0x00, 0x05,
+ 0x33, 0x44, 0x30, 0x33, 0x31,
+ 0 };
+ return barcodeSendQuery(data);
+ }
+
+ @Keep public void getBarcodePreSuffix() {
+ if (getPrefix() == null || getSuffix() == null) barcodeSendQuerySelfPreSuffix();
+ }
+
+ public String strVersion, strESN, strSerialNumber, strDate;
+ public String getVersion() { return strVersion; }
+ public String getESN() { return strESN; }
+ public String getSerialNumber() { return strSerialNumber; }
+ public String getDate() { return strDate; }
+ public byte[] bytesBarcodePrefix = null;
+ public byte[] bytesBarcodeSuffix = null;
+ public byte[] getPrefix() { return bytesBarcodePrefix; }
+ public byte[] getSuffix() { return bytesBarcodeSuffix; }
+ public boolean checkPreSuffix(byte[] prefix1, byte[] suffix1) {
+ boolean result = false;
+ if (prefix1 != null && bytesBarcodePrefix != null && suffix1 != null && bytesBarcodeSuffix != null) {
+ result = Arrays.equals(prefix1, bytesBarcodePrefix);
+ if (result) result = Arrays.equals(suffix1, bytesBarcodeSuffix);
+ }
+ return result;
+ }
+ public boolean decodeBarcodeUplinkData(byte[] dataValues, BarcodeConnector.CsReaderBarcodeData csReaderBarcodeData) {
+ appendToLog("decodeBarcodeUplinkData starts");
+ boolean found = false, DEBUG = false;
+ int count = 0; boolean matched = true;
+ if (barcodeConnector.barcodeToWrite.get(0).dataValues[0] == 0x1b) {
+ commandType = BarcodeCommandTypes.COMMAND_COMMON;
+ count = 1;
+ if (DEBUG) appendToLog("0x1b, Common response with count = " + count);
+ } else if (barcodeConnector.barcodeToWrite.get(0).dataValues[0] == 0x7E) {
+ if (DEBUG) appendToLog("0x7E, Barcode response with 0x7E barcodeToWrite.get(0).dataValues[0] and response data = " + byteArrayToString(dataValues));
+ matched = true;
+ commandType = BarcodeCommandTypes.COMMAND_QUERY;
+ int index = 0;
+ while (dataValues.length - index >= 5 + 1) {
+ if (dataValues[index+0] == 2 && dataValues[index+1] == 0 && dataValues[index+4] == 0x34) {
+ int length = dataValues[index+2] * 256 + dataValues[index+3];
+ if (dataValues.length - index >= length + 4 + 1) {
+ matched = true;
+ byte[] bytes = new byte[length-1];
+ System.arraycopy(dataValues, index + 5, bytes, 0, bytes.length);
+ byte[] requestBytes = new byte[barcodeConnector.barcodeToWrite.get(0).dataValues.length - 6];
+ System.arraycopy(barcodeConnector.barcodeToWrite.get(0).dataValues, 5, requestBytes, 0, requestBytes.length);
+ if (utility.DEBUG_PKDATA) appendToLog("PkData: found Barcode.Uplink.DataRead.QueryResponse with payload data1 = " + byteArrayToString(bytes) + " for QueryInput data1 = " + byteArrayToString(requestBytes));
+ if (barcodeConnector.barcodeToWrite.get(0).dataValues[5] == 0x37 && length >= 5) {
+ matched = true;
+ int prefixLength = dataValues[index+6];
+ int suffixLength = 0;
+ if (dataValues.length - index >= 5 + 2 + prefixLength + 2 + 1) {
+ suffixLength = dataValues[index + 6 + prefixLength + 2];
+ }
+ if (dataValues.length - index >= 5 + 2 + prefixLength + 2 + suffixLength + 1) {
+ bytesBarcodePrefix = null;
+ bytesBarcodeSuffix = null;
+ if (dataValues[index+5] == 1) {
+ bytesBarcodePrefix = new byte[prefixLength];
+ System.arraycopy(dataValues, index + 7, bytesBarcodePrefix, 0, bytesBarcodePrefix.length);
+ }
+ if (dataValues[index + 6 + prefixLength + 1] == 1) {
+ bytesBarcodeSuffix = new byte[suffixLength];
+ System.arraycopy(dataValues, index + 7 + prefixLength + 2, bytesBarcodeSuffix, 0, bytesBarcodeSuffix.length);
+ }
+ if (DEBUG) appendToLog("BarStream: BarcodePrefix = " + byteArrayToString(bytesBarcodePrefix) + ", BarcodeSuffix = " + byteArrayToString(bytesBarcodeSuffix));
+ }
+ if (utility.DEBUG_PKDATA) appendToLog("PkData: Barcode.Uplink.DataRead.QueryResponse.SelfPrefix_SelfSuffix is processed as Barcode Prefix = " + byteArrayToString(bytesBarcodePrefix) + ", Suffix = " + byteArrayToString(bytesBarcodeSuffix));
+ } else if (barcodeConnector.barcodeToWrite.get(0).dataValues[5] == 0x47 && length > 1) {
+ if (DEBUG) appendToLog("versionNumber is detected with length = " + length);
+ matched = true;
+ byte[] byteVersion = new byte[length - 1];
+ System.arraycopy(dataValues, index + 5, byteVersion, 0, byteVersion.length);
+ String versionNumber;
+ try {
+ versionNumber = new String(byteVersion, "UTF-8");
+ } catch (Exception e) {
+ versionNumber = null;
+ }
+ strVersion = versionNumber;
+ if (utility.DEBUG_PKDATA) appendToLog("PkData: uplink data " + byteArrayToString(byteVersion) + " is processsed as version = " + versionNumber);
+ } else if (barcodeConnector.barcodeToWrite.get(0).dataValues[5] == 0x48 && length >= 5) {
+ if (dataValues[index+5] == barcodeConnector.barcodeToWrite.get(0).dataValues[6] && dataValues[index+6] == barcodeConnector.barcodeToWrite.get(0).dataValues[7]) {
+ matched = true; //for ESN, S/N or Date
+ byte[] byteSN = new byte[length - 3];
+ System.arraycopy(dataValues, index + 7, byteSN, 0, byteSN.length);
+ String serialNumber;
+ try {
+ serialNumber = new String(byteSN, "UTF-8");
+ int snLength = Integer.parseInt(serialNumber.substring(0, 2));
+ if (DEBUG)
+ appendToLog("BarStream: serialNumber = " + serialNumber + ", snLength = " + snLength + ", serialNumber.length = " + serialNumber.length());
+ if (snLength + 2 == serialNumber.length()) {
+ serialNumber = serialNumber.substring(2);
+ } else serialNumber = null;
+ } catch (Exception e) {
+ serialNumber = null;
+ }
+ if (false) appendToLog("debug index = " + index + ", " + byteArrayToString(dataValues));
+ String strResponseType = "";
+ if (dataValues[index+6] == (byte)0x32) {
+ strESN = serialNumber;
+ strResponseType = "EquipmentSerialNumber";
+ } else if (dataValues[index+6] == (byte)0x33) {
+ strSerialNumber = serialNumber;
+ strResponseType = "SerialNumber";
+ } else if (dataValues[index+6] == (byte)0x34) {
+ strDate = serialNumber;
+ strResponseType = "DataCode";
+ }
+ if (false) appendToLog("strResponseType = " + strResponseType);
+ if (utility.DEBUG_PKDATA) appendToLog(String.format("PkData: Barcode.Uplink.DataRead.QueryResponse.%s is processed as %s[%s]", strResponseType, byteArrayToString(byteSN).substring(4), serialNumber));
+ } else appendToLog("Barcode.Uplink.DataRead.QueryResponse has mis-matched values");
+ } else if (barcodeConnector.barcodeToWrite.get(0).dataValues[5] == 0x44 && length >= 3) {
+ if (DEBUG) appendToLog("BarStream: dataValue = " + byteArrayToString(dataValues) + ", writeDataValue = " + byteArrayToString(barcodeConnector.barcodeToWrite.get(0).dataValues));
+ if (dataValues[index+5] == barcodeConnector.barcodeToWrite.get(0).dataValues[6] && dataValues[index+6] == barcodeConnector.barcodeToWrite.get(0).dataValues[7]) {
+ matched = true;
+ if (barcodeConnector.barcodeToWrite.get(0).dataValues[6] == 0x30 && barcodeConnector.barcodeToWrite.get(0).dataValues[7] == 0x30 && barcodeConnector.barcodeToWrite.get(0).dataValues[8] == 0x30) {
+ bBarcodeTriggerMode = dataValues[7];
+ String strModeType = "";
+ if (dataValues[index+7] == 0x30) strModeType = "trigger";
+ else if (dataValues[index+7] == 0x31) strModeType = "auto_Scan";
+ else if (dataValues[index+7] == 0x32) strModeType = "continue_Scan";
+ else if (dataValues[index+7] == 0x33) strModeType = "batch_Scan";
+ if (utility.DEBUG_PKDATA) appendToLog(String.format("PkData: Barcode.Uplink.DataRead.QueryResponse.ReadingMode is processed as last 0x%X[%s]", dataValues[index+7], strModeType));
+ } else appendToLog("Barcode.Uplink.DataRead.QueryResponse has mis-matched values");
+ } else appendToLog("Barcode.Uplink.DataRead.QueryResponse has mis-matched values");
+ } else appendToLog("Barcode.Uplink.DataRead.QueryResponse has mis-matched values");
+ index += (length + 5);
+ } else break;
+ } else index++;
+ }
+ if (matched) { if (DEBUG) appendToLog("Matched Query response"); }
+ else { if (DEBUG) appendToLog("Mis-matched Query response"); }
+ } else {
+ if (DEBUG) appendToLog("BarStream: Barcode response with barcodeToWrite.get(0).dataValues[0] = Others");
+ String strData = null;
+ try {
+ strData = new String(barcodeConnector.barcodeToWrite.get(0).dataValues, "UTF-8");
+ } catch (Exception ex) {
+ strData = "";
+ }
+ String findStr = "nls";
+ int lastIndex = 0;
+ while (lastIndex != -1) {
+ lastIndex = strData.indexOf(findStr, lastIndex);
+ if (lastIndex != -1) {
+ count++;
+ lastIndex += findStr.length();
+ }
+ }
+ if (DEBUG) appendToLog("Setting strData = " + strData + ", count = " + count);
+ }
+ if (count != 0) {
+ if (false) appendToLog("dataValues.length = " + dataValues.length + ", okCount = " + barcodeConnector.iOkCount + ", count = " + count + " for barcodeToWrite data = " + byteArrayToString(barcodeConnector.barcodeToWrite.get(0).dataValues));
+ matched = false; boolean foundOk = false;
+ for (int k = 0; k < dataValues.length; k++) {
+ boolean match06 = false;
+ if (dataValues[k] == 0x06 || dataValues[k] == 0x15) { match06 = true; if (++barcodeConnector.iOkCount == count) matched = true; }
+ if (match06 == false) break;
+ foundOk = true; found = true;
+ }
+ if (false) appendToLog("00 matcched = " + matched);
+ if (matched) { if (utility.DEBUG_PKDATA) appendToLog("PkData: Barcode.Uplink.DataRead." + byteArrayToString(dataValues) + " is processed with matched = " + matched + ", OkCount = " + barcodeConnector.iOkCount + ", expected count = " + count + " for " + byteArrayToString(barcodeConnector.barcodeToWrite.get(0).dataValues)); }
+ else if (foundOk) { if (utility.DEBUG_PKDATA) appendToLog("PkData: Barcode.Uplink.DataRead." + byteArrayToString(dataValues) + " is processed with matched = " + matched + ", but OkCount = " + barcodeConnector.iOkCount + ", expected count = " + count + " for " + byteArrayToString(barcodeConnector.barcodeToWrite.get(0).dataValues)); }
+ else {
+ barcodeConnector.mBarcodeToRead.add(csReaderBarcodeData);
+ if (utility.DEBUG_PKDATA) appendToLog("PkData: uplink data Barcode.DataRead." + byteArrayToString(csReaderBarcodeData.dataValues) + " is added to mBarcodeToRead");
+ }
+ }
+ if (matched) {
+ found = true;
+ barcodeConnector.barcodeToWrite.remove(0); barcodeConnector.sendDataToWriteSent = 0; barcodeConnector.mDataToWriteRemoved = true; appendToLog("barcodeToWrite remove0 with length = " + barcodeConnector.barcodeToWrite.size());
+ if (utility.DEBUG_PKDATA) appendToLog("PkData: new barcodeToWrite size = " + barcodeConnector.barcodeToWrite.size());
+ }
+ appendToLog("decodeBarcodeUplinkData found = " + found);
+ return found;
+ }
+}
+
+
+
+package com.csl.cslibrary4a;
+
+import android.content.Context;
+import android.widget.TextView;
+import android.widget.Toast;
+
+import java.util.ArrayList;
+
+public class BluetoothConnector {
+ boolean DEBUG_PKDATA;
+ final boolean DEBUG = false;
+// public boolean userDebugEnableDefault = false;
+// public boolean userDebugEnable = userDebugEnableDefault;
+
+ Context context; Utility utility; boolean userDebugEnable;
+ public BluetoothConnector(Context context, Utility utility, boolean userDebugEnable) {
+ this.context = context;
+ this.utility = utility; DEBUG_PKDATA = utility.DEBUG_PKDATA;
+ this.userDebugEnable = userDebugEnable;
+ }
+ private String byteArrayToString(byte[] packet) { return utility.byteArrayToString(packet); }
+ private boolean compareArray(byte[] array1, byte[] array2, int length) { return utility.compareByteArray(array1, array2, length); }
+ private void appendToLog(String s) { utility.appendToLog(s); }
+ private void appendToLogView(String s) { utility.appendToLogView(s); }
+
+ private int icsModel = -1;
+ public int getCsModel() {
+ if (false) appendToLog("icsModel = " + icsModel);
+ return icsModel;
+ }
+
+ public enum BluetoothIcPayloadEvents {
+ BLUETOOTH_GET_VERSION, BLUETOOTH_SET_DEVICE_NAME, BLUETOOTH_GET_DEVICE_NAME, BLUETOOTH_FORCE_BT_DISCONNECT
+ }
+
+ public class BluetoothIcData {
+ public BluetoothIcPayloadEvents bluetoothIcPayloadEvent;
+ public byte[] dataValues;
+ }
+
+ private byte[] mBluetoothIcVersion = new byte[]{-1, -1, -1};
+ private boolean mBluetoothIcVersionUpdated = false;
+ public String getBluetoothIcVersion() {
+ boolean DEBUG = false;
+ if (mBluetoothIcVersionUpdated == false) {
+ if (DEBUG) appendToLog("mBluetoothIcVersionUpdated is false");
+ boolean repeatRequest = false;
+ if (bluetoothIcToWrite.size() != 0) {
+ if (bluetoothIcToWrite.get(bluetoothIcToWrite.size() - 1).bluetoothIcPayloadEvent == BluetoothIcPayloadEvents.BLUETOOTH_GET_VERSION) {
+ repeatRequest = true;
+ }
+ }
+ if (repeatRequest == false) {
+ BluetoothIcData cs108BluetoothIcData = new BluetoothIcData();
+ cs108BluetoothIcData.bluetoothIcPayloadEvent = BluetoothIcPayloadEvents.BLUETOOTH_GET_VERSION;
+ bluetoothIcToWrite.add(cs108BluetoothIcData);
+ if (DEBUG_PKDATA) appendToLog("add " + cs108BluetoothIcData.bluetoothIcPayloadEvent.toString() + " to mBluetoothIcToWrite with length = " + bluetoothIcToWrite.size());
+ }
+ return "";
+ } else {
+ String retValue = String.valueOf(mBluetoothIcVersion[0]) + "." + String.valueOf(mBluetoothIcVersion[1]) + "." + String.valueOf(mBluetoothIcVersion[2]);
+ if (DEBUG) appendToLog("mBluetoothIcVersionUpdated is true with data = " + byteArrayToString(mBluetoothIcVersion) + ", icsModel = " + icsModel);
+ return retValue;
+ }
+ }
+
+ public byte[] deviceName = null;
+ public String getBluetoothIcName() {
+ boolean DEBBUG = false;
+ if (DEBBUG) appendToLog("3 deviceName = " + (deviceName == null ? "null" : byteArrayToString(deviceName)));
+ if (deviceName == null) {
+ boolean repeatRequest = false;
+ if (DEBBUG) appendToLog("3A mBluetoothIcToWrite.size = " + bluetoothIcToWrite.size());
+ if (bluetoothIcToWrite.size() != 0) {
+ if (bluetoothIcToWrite.get(bluetoothIcToWrite.size() - 1).bluetoothIcPayloadEvent == BluetoothIcPayloadEvents.BLUETOOTH_GET_DEVICE_NAME) {
+ repeatRequest = true;
+ }
+ }
+ if (DEBBUG) appendToLog("3b repeatRequest = " + repeatRequest);
+ if (repeatRequest == false) {
+ BluetoothIcData cs108BluetoothIcData = new BluetoothIcData();
+ cs108BluetoothIcData.bluetoothIcPayloadEvent = BluetoothIcPayloadEvents.BLUETOOTH_GET_DEVICE_NAME;
+ bluetoothIcToWrite.add(cs108BluetoothIcData);
+ if (DEBUG_PKDATA) appendToLog("add " + cs108BluetoothIcData.bluetoothIcPayloadEvent.toString() + " to mBluetoothIcToWrite with length = " + bluetoothIcToWrite.size());
+ }
+ return "";
+ } else {
+ return new String(deviceName).trim();
+ }
+ }
+ public boolean setBluetoothIcName(String name) {
+ if (name == null) return false;
+ if (name.length() == 0) return false;
+ if (name.length() > 20) return false;
+ BluetoothIcData cs108BluetoothIcData = new BluetoothIcData();
+ cs108BluetoothIcData.bluetoothIcPayloadEvent = BluetoothIcPayloadEvents.BLUETOOTH_SET_DEVICE_NAME;
+ if (DEBUG) appendToLog("deviceName.length = " + deviceName.length + ", name.getBytes = " + byteArrayToString(name.getBytes()));
+ cs108BluetoothIcData.dataValues = name.getBytes();
+ if (bluetoothIcToWrite.add(cs108BluetoothIcData) == false) return false;
+ deviceName = name.getBytes();
+ return true;
+ }
+
+ public boolean forceBTdisconnect() {
+ BluetoothIcData cs108BluetoothIcData = new BluetoothIcData();
+ cs108BluetoothIcData.bluetoothIcPayloadEvent = BluetoothIcPayloadEvents.BLUETOOTH_FORCE_BT_DISCONNECT;
+ if (bluetoothIcToWrite.add(cs108BluetoothIcData) == false) return false;
+ return true;
+ }
+
+ public ArrayList bluetoothIcToWrite = new ArrayList<>();
+ private ArrayList mBluetoothIcToRead = new ArrayList<>();
+
+ private boolean arrayTypeSet(byte[] dataBuf, int pos, BluetoothIcPayloadEvents event) {
+ boolean validEvent = false;
+ switch (event) {
+ case BLUETOOTH_GET_VERSION:
+ validEvent = true;
+ break;
+ case BLUETOOTH_SET_DEVICE_NAME:
+ dataBuf[pos] = 3;
+ validEvent = true;
+ break;
+ case BLUETOOTH_GET_DEVICE_NAME:
+ dataBuf[pos] = 4;
+ validEvent = true;
+ break;
+ case BLUETOOTH_FORCE_BT_DISCONNECT:
+ dataBuf[pos] = 5;
+ validEvent = true;
+ break;
+ }
+ return validEvent;
+ }
+
+ private byte[] writeBluetoothIc(BluetoothIcData data, boolean usbConnection) {
+ boolean DEBUG = false;
+ int datalength = 0;
+ if (DEBUG) appendToLog("data.bluetoothIcPayloadEvent=" + data.bluetoothIcPayloadEvent.toString() + ", data.dataValues=" + byteArrayToString(data.dataValues));
+ if (data.dataValues != null) datalength = data.dataValues.length;
+ byte[] dataOutRef = new byte[]{(byte) 0xA7, (byte) 0xB3, 2, (byte) 0x5F, (byte) 0x82, (byte) 0x37, 0, 0, (byte) 0xC0, 0};
+ if (usbConnection) dataOutRef[1] = (byte) 0xE6;
+ byte[] dataOut = new byte[10 + datalength];
+ if (datalength != 0) {
+ System.arraycopy(data.dataValues, 0, dataOut, 10, datalength);
+ dataOutRef[2] += datalength;
+ }
+ System.arraycopy(dataOutRef, 0, dataOut, 0, dataOutRef.length);
+ if (DEBUG) appendToLog("dataOut=" + byteArrayToString(dataOut));
+ if (arrayTypeSet(dataOut, 9, data.bluetoothIcPayloadEvent)) {
+ if (data.bluetoothIcPayloadEvent == BluetoothIcPayloadEvents.BLUETOOTH_SET_DEVICE_NAME && data.dataValues.length < 21) {
+ byte[] dataOut1 = new byte[10+21];
+ System.arraycopy(dataOut, 0, dataOut1, 0, dataOut.length);
+ dataOut1[2] = 23;
+ dataOut = dataOut1;
+ }
+ if (DEBUG) appendToLog(byteArrayToString(dataOut));
+ return dataOut;
+ }
+ return null;
+ }
+
+ public boolean isMatchBluetoothIcToWrite(ConnectorData connectorData) {
+ boolean match = false;
+ if (bluetoothIcToWrite.size() != 0 && connectorData.dataValues[0] == (byte)0xC0) {
+ byte[] dataInCompare = new byte[]{(byte) 0xC0, 0};
+ if (arrayTypeSet(dataInCompare, 1, bluetoothIcToWrite.get(0).bluetoothIcPayloadEvent) && (connectorData.dataValues.length >= dataInCompare.length + 1)) {
+ if (match = compareArray(connectorData.dataValues, dataInCompare, dataInCompare.length)) {
+ boolean bprocessed = false;
+ byte[] data1 = new byte[connectorData.dataValues.length - 2]; System.arraycopy(connectorData.dataValues, 2, data1, 0, data1.length);
+ if (DEBUG_PKDATA) appendToLog("PkData: matched BluetoothIc.Reply with payload = " + byteArrayToString(connectorData.dataValues) + " for writeData BluetoothIc." + bluetoothIcToWrite.get(0).bluetoothIcPayloadEvent.toString());
+ if (bluetoothIcToWrite.get(0).bluetoothIcPayloadEvent == BluetoothIcPayloadEvents.BLUETOOTH_GET_VERSION) {
+ if (connectorData.dataValues.length > 2) {
+ int length = mBluetoothIcVersion.length;
+ if (connectorData.dataValues.length - 2 < length) length = connectorData.dataValues.length - 2;
+ System.arraycopy(connectorData.dataValues, 2, mBluetoothIcVersion, 0, length);
+ if (mBluetoothIcVersion[0] == 3) icsModel = 463;
+ else if (mBluetoothIcVersion[0] == 1) icsModel = 108;
+ mBluetoothIcVersionUpdated = true;
+ if (DEBUG) appendToLog("mBluetoothIcVersionUpdated is true");
+ bprocessed = true;
+ }
+ if (DEBUG_PKDATA) appendToLog("PkData: matched BluetoothIc.Reply.GetVersion with version = " + byteArrayToString(mBluetoothIcVersion));
+ } else if (bluetoothIcToWrite.get(0).bluetoothIcPayloadEvent == BluetoothIcPayloadEvents.BLUETOOTH_GET_DEVICE_NAME) {
+ if (connectorData.dataValues.length > 2) {
+ byte[] deviceName1 = new byte[connectorData.dataValues.length - 2];
+ System.arraycopy(connectorData.dataValues, 2, deviceName1, 0, connectorData.dataValues.length - 2);
+ deviceName = deviceName1;
+ bprocessed = true;
+ }
+ if (DEBUG_PKDATA) appendToLog("PkData: matched mBluetoothIc.GetDeviceName.Reply data is found with name=" + byteArrayToString(deviceName) + ", dataValues.length=" + connectorData.dataValues.length + ", deviceName.length=" + deviceName.length);
+ } else {
+ bprocessed = true;
+ if (DEBUG) appendToLog("matched mBluetoothIc.Other.Reply data is found.");
+ }
+ String string = "Up3 " + (bprocessed ? "" : "Unprocessed, ") + bluetoothIcToWrite.get(0).bluetoothIcPayloadEvent.toString() + ", " + byteArrayToString(data1);
+ utility.writeDebug2File(string);
+ bluetoothIcToWrite.remove(0); sendDataToWriteSent = 0;
+ if (DEBUG_PKDATA) appendToLog("PkData: new mBluetoothIcToWrite size = " + bluetoothIcToWrite.size());
+ }
+ }
+ }
+ return match;
+ }
+
+ public int sendDataToWriteSent = 0;
+ boolean bluetoothFailure = false;
+ public byte[] sendBluetoothIcToWrite(boolean usbConnection) {
+ if (bluetoothFailure) {
+ bluetoothIcToWrite.remove(0); sendDataToWriteSent = 0;
+ } else if (sendDataToWriteSent >= 5) {
+ int oldSize = bluetoothIcToWrite.size();
+ bluetoothIcToWrite.remove(0); sendDataToWriteSent = 0;
+ if (DEBUG) appendToLog("Removed after sending count-out with oldSize = " + oldSize + ", updated mBluetoothIcToWrite.size() = " + bluetoothIcToWrite.size());
+ if (DEBUG) appendToLog("Removed after sending count-out.");
+ String string = "Problem in sending data to Bluetooth Module. Removed data sending after count-out";
+ if (userDebugEnable) Toast.makeText(context, string, Toast.LENGTH_SHORT).show();
+ else appendToLogView(string);
+ bluetoothFailure = true;
+ } else {
+ if (DEBUG) appendToLog("size = " + bluetoothIcToWrite.size() + ", PayloadEvents = " + bluetoothIcToWrite.get(0).bluetoothIcPayloadEvent.toString());
+ sendDataToWriteSent++;
+ return writeBluetoothIc(bluetoothIcToWrite.get(0), usbConnection);
+ }
+ return null;
+ }
+
+ void addBluetoothToWrite(BluetoothIcData cs108BluetoothIcData) {
+ boolean repeatRequest = false;
+ if (bluetoothIcToWrite.size() != 0) {
+ BluetoothIcData cs108BluetoothIcData1 = bluetoothIcToWrite.get(bluetoothIcToWrite.size() - 1);
+ if (cs108BluetoothIcData.bluetoothIcPayloadEvent == cs108BluetoothIcData1.bluetoothIcPayloadEvent) {
+ if (cs108BluetoothIcData.dataValues == null && cs108BluetoothIcData1.dataValues == null) {
+ repeatRequest = true;
+ } else if (cs108BluetoothIcData.dataValues != null && cs108BluetoothIcData1.dataValues != null) {
+ if (cs108BluetoothIcData.dataValues.length == cs108BluetoothIcData1.dataValues.length) {
+ if (compareArray(cs108BluetoothIcData.dataValues, cs108BluetoothIcData1.dataValues, cs108BluetoothIcData.dataValues.length)) {
+ repeatRequest = true;
+ }
+ }
+ }
+ }
+ }
+ if (repeatRequest == false) {
+ bluetoothIcToWrite.add(cs108BluetoothIcData);
+ appendToLog("2b GET_DEVICE_NAME");
+ if (DEBUG_PKDATA) appendToLog("add " + cs108BluetoothIcData.bluetoothIcPayloadEvent.toString() + " to mBluetoothIcToWrite with length = " + bluetoothIcToWrite.size());
+ }
+ }
+}
+
+
+
+package com.csl.cslibrary4a;
+
+import android.Manifest;
+import android.bluetooth.BluetoothAdapter;
+import android.bluetooth.BluetoothDevice;
+import android.bluetooth.BluetoothGattCallback;
+import android.bluetooth.BluetoothGattCharacteristic;
+import android.bluetooth.BluetoothGattDescriptor;
+import android.bluetooth.BluetoothGattService;
+import android.bluetooth.BluetoothManager;
+import android.bluetooth.BluetoothProfile;
+import android.bluetooth.le.BluetoothLeScanner;
+import android.bluetooth.le.ScanCallback;
+import android.content.Context;
+import android.content.pm.PackageManager;
+import android.location.LocationManager;
+import android.os.Build;
+import android.os.Handler;
+
+import androidx.core.app.ActivityCompat;
+
+import android.util.Log;
+import android.widget.PopupWindow;
+
+import java.lang.reflect.Method;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Set;
+import java.util.UUID;
+
+import static android.content.Context.LOCATION_SERVICE;
+
+public class BluetoothGatt extends BluetoothGattCallback {
+ boolean DEBUG_PKDATA, DEBUG_APDATA;
+ final boolean DEBUG = true, DEBUG_BTOP = false;
+ static final String TAG = "Hello";
+
+ private Handler mHandler = new Handler();
+
+ private ReaderDevice readerDeviceConnected;
+ public ReaderDevice getReaderDeviceConnected() {
+ return readerDeviceConnected;
+ }
+
+ public BluetoothManager bluetoothManager;
+ public BluetoothAdapter bluetoothAdapter;
+ public android.bluetooth.BluetoothGatt bluetoothGatt;
+ private BluetoothLeScanner bluetoothLeScanner;
+
+ public int bluetoothConnectionState;
+ public boolean isConnected() { return bluetoothConnectionState == BluetoothProfile.STATE_CONNECTED && mReaderStreamOutCharacteristic != null; }
+
+ private boolean scanning = false;
+ public boolean isScanning() { return scanning; }
+
+ int serviceUUID2p1 = 0;
+ public void setServiceUUIDType(int serviceUUID2p1) { this.serviceUUID2p1 = serviceUUID2p1; }
+
+ private final UUID UUID_READER_STREAM_OUT_CHARACTERISTIC = UUID.fromString("00009900-0000-1000-8000-00805f9b34fb");
+ private final UUID UUID_READER_STREAM_IN_CHARACTERISTIC = UUID.fromString("00009901-0000-1000-8000-00805f9b34fb");
+
+ private int mRssi;
+ public int getRssi() { return mRssi; }
+
+ private boolean characteristicListRead = false;
+
+ public boolean isCharacteristicListRead() {
+ return characteristicListRead;
+ }
+
+ public BluetoothGattCharacteristic mReaderStreamOutCharacteristic;
+ private BluetoothGattCharacteristic mReaderStreamInCharacteristic;
+ private long mStreamWriteCount, mStreamWriteCountOld;
+ private boolean _readCharacteristic_in_progress;
+ private boolean _writeCharacteristic_in_progress;
+ private ArrayList mBluetoothGattCharacteristicToRead = new ArrayList<>();
+
+ private final int STREAM_IN_BUFFER_MAX = 0x100000; //0xC00; //0x800; //0x400;
+ private byte[] streamInBuffer = new byte[STREAM_IN_BUFFER_MAX];
+ private int streamInBufferHead, streamInBufferTail;
+ private int streamInBufferSize = 0;
+
+ public int getStreamInBufferSize() {
+ return streamInBufferSize;
+ }
+
+ private long streamInOverflowTime = 0;
+
+ public long getStreamInOverflowTime() {
+ return streamInOverflowTime;
+ }
+
+ private int streamInBytesMissing = 0;
+
+ public int getStreamInBytesMissing() {
+ int missingByte = streamInBytesMissing;
+ streamInBytesMissing = 0;
+ return missingByte;
+ }
+
+ private int streamInTotalCounter = 0;
+
+ public int getStreamInTotalCounter() {
+ return streamInTotalCounter;
+ }
+
+ private int streamInAddCounter = 0;
+
+ public int getStreamInAddCounter() {
+ return streamInAddCounter;
+ }
+
+ private long streamInAddTime = 0;
+
+ public long getStreamInAddTime() {
+ return streamInAddTime;
+ }
+
+ private boolean connectionHSpeed = true;
+
+ public boolean getConnectionHSpeedA() {
+ return connectionHSpeed;
+ }
+
+ public boolean setConnectionHSpeedA(boolean connectionHSpeed) {
+ this.connectionHSpeed = connectionHSpeed;
+ return true;
+ }
+
+ @Override
+ public void onConnectionStateChange(android.bluetooth.BluetoothGatt gatt, int status, int newState) {
+ boolean DEBUG = false;
+ super.onConnectionStateChange(gatt, status, newState);
+ if (utility.DEBUG_CONNECT) appendToLog("newState = " + newState);
+ if (gatt != bluetoothGatt) {
+ if (DEBUG) appendToLog("abcc mismatched mBluetoothGatt = " + (gatt != bluetoothGatt) + ", status = " + status);
+ } else {
+ bluetoothConnectionState = newState;
+ switch (newState) {
+ case BluetoothProfile.STATE_DISCONNECTED:
+ if (utility.DEBUG_CONNECT) appendToLog("state=Disconnected with status = " + status);
+ if (disconnectRunning == false) {
+ if (DEBUG) appendToLog("disconnect b");
+ disconnect();
+ }
+ break;
+
+ case BluetoothProfile.STATE_CONNECTED:
+ if (utility.DEBUG_CONNECT) appendToLog("state=Connected with status = " + status);
+ if (disconnectRunning) {
+ if (DEBUG) appendToLog("abcc disconnectRunning !!!");
+ break;
+ }
+ mStreamWriteCount = mStreamWriteCountOld = 0;
+ _readCharacteristic_in_progress = _writeCharacteristic_in_progress = false;
+ if (bDiscoverStarted) {
+ if (DEBUG) appendToLog("abc discovery has been started before");
+ break;
+ }
+ if (utility.DEBUG_CONNECT) appendToLog("Start discoverServices");
+ if (discoverServices()) {
+ bDiscoverStarted = true;
+ if (utility.DEBUG_CONNECT) appendToLog("state=Connected. discoverServices starts with status = " + status);
+ } else {
+ if (DEBUG) appendToLog("state=Connected. discoverServices FAIL");
+ }
+ utility.setReferenceTimeMs();
+ mHandler.removeCallbacks(mReadRssiRunnable);
+ mHandler.post(mReadRssiRunnable);
+ break;
+ default:
+ if (DEBUG) appendToLog("state=" + newState);
+ break;
+ }
+ }
+ }
+
+ public boolean bDiscoverStarted = false;
+
+ @Override
+ public void onServicesDiscovered(android.bluetooth.BluetoothGatt gatt, int status) {
+ boolean DEBUG = false;
+ super.onServicesDiscovered(gatt, status);
+ if (gatt != bluetoothGatt) {
+ if (DEBUG) appendToLog("INVALID mBluetoothGatt");
+ } else if (status != android.bluetooth.BluetoothGatt.GATT_SUCCESS) {
+ if (DEBUG) appendToLog("status=" + status + ". restart discoverServices");
+ discoverServices();
+ } else {
+ UUID UUID_READER_SERVICE = UUID.fromString("0000" + strReaderServiceUUID + "-0000-1000-8000-00805f9b34fb");
+ mReaderStreamOutCharacteristic = getCharacteristic(UUID_READER_SERVICE, UUID_READER_STREAM_OUT_CHARACTERISTIC);
+ mReaderStreamInCharacteristic = getCharacteristic(UUID_READER_SERVICE, UUID_READER_STREAM_IN_CHARACTERISTIC);
+ if (DEBUG_BTOP) appendToLog("mReaderStreamOutCharacteristic flag = " + mReaderStreamOutCharacteristic.getProperties());
+ if (DEBUG_BTOP) appendToLog("mReaderStreamInCharacteristic flag = " + mReaderStreamInCharacteristic.getProperties());
+ if (mReaderStreamInCharacteristic == null || mReaderStreamOutCharacteristic == null) {
+ if (DEBUG_BTOP) appendToLog("restart discoverServices");
+ discoverServices();
+ return;
+ }
+
+ if (checkSelfPermissionBLUETOOTH() == false) return;
+ if (!bluetoothGatt.setCharacteristicNotification(mReaderStreamInCharacteristic, true)) {
+ if (DEBUG) appendToLog("setCharacteristicNotification() FAIL");
+ } else {
+ int mtu_requested = 255;
+ boolean bValue = gatt.requestMtu(mtu_requested);
+ if (DEBUG_BTOP) appendToLog("requestMtu[" + mtu_requested + "] with result=" + bValue);
+
+ if (DEBUG_BTOP) appendToLog("characteristicListRead = " + characteristicListRead);
+ if (characteristicListRead == false) {
+ if (DEBUG) appendToLog("with services");
+ mBluetoothGattCharacteristicToRead.clear();
+ List ss = bluetoothGatt.getServices();
+ for (BluetoothGattService service : ss) {
+ String uuid = service.getUuid().toString().substring(4, 8); //substring(0, 8)
+ List cc = service.getCharacteristics();
+ for (BluetoothGattCharacteristic characteristic : cc) {
+ String characteristicUuid = characteristic.getUuid().toString().substring(4, 8); //substring(0, 8)
+ int properties = characteristic.getProperties();
+ boolean do_something = false;
+ if ((properties & BluetoothGattCharacteristic.PROPERTY_READ) > 0) {
+ if (DEBUG)
+ appendToLog("service=" + uuid + ", characteristic=" + characteristicUuid + ", property=read");
+ mBluetoothGattCharacteristicToRead.add(characteristic);
+ do_something = true;
+ }
+ if ((properties & BluetoothGattCharacteristic.PROPERTY_WRITE) > 0) {
+ if (DEBUG)
+ appendToLog("service=" + uuid + ", characteristic=" + characteristicUuid + ", property=write");
+ do_something = true;
+ }
+ if ((properties & BluetoothGattCharacteristic.PROPERTY_NOTIFY) > 0) {
+ if (DEBUG)
+ appendToLog("service=" + uuid + ", characteristic=" + characteristicUuid + ", property=notify");
+ do_something = true;
+ }
+ if (!do_something) {
+ if (DEBUG)
+ appendToLog("service=" + uuid + ", characteristic=" + characteristicUuid + ", property=" + String.format("%X ", properties));
+ }
+ }
+ }
+ if (true) mBluetoothGattCharacteristicToRead.clear();
+ mHandler.removeCallbacks(mReadCharacteristicRunnable);
+ if (DEBUG) appendToLog("starts in onServicesDiscovered");
+ mHandler.postDelayed(mReadCharacteristicRunnable, 500);
+ }
+ }
+ }
+ }
+
+ @Override
+ public void onReadRemoteRssi(android.bluetooth.BluetoothGatt gatt, int rssi, int status) {
+ boolean DEBUG = false;
+ super.onReadRemoteRssi(gatt, rssi, status);
+ if (gatt != bluetoothGatt) {
+ if (DEBUG) utility.appendToLogRunnable("onReadRemoteRssi: INVALID mBluetoothGatt");
+ } else if (status != android.bluetooth.BluetoothGatt.GATT_SUCCESS) {
+ if (DEBUG) utility.appendToLogRunnable("onReadRemoteRssi: NOT GATT_SUCCESS");
+ } else {
+ if (DEBUG_BTOP) utility.appendToLogRunnable("onReadRemoteRssi: rssi=" + rssi);
+ mRssi = rssi;
+ }
+ }
+
+ private final Runnable mReadRssiRunnable = new Runnable() {
+ boolean DEBUG = false;
+ @Override
+ public void run() {
+ if (checkSelfPermissionBLUETOOTH() == false) return;
+ if (bluetoothGatt == null) {
+ if (DEBUG) appendToLog("mReadRssiRunnable: readRemoteRssi with null mBluetoothGatt");
+ return;
+ } else if (bluetoothGatt.readRemoteRssi()) {
+ if (DEBUG_BTOP) appendToLog("mReadRssiRunnable: readRemoteRssi starts");
+ } else {
+ if (DEBUG) appendToLog("mReadRssiRunnable: readRemoteRssi FAIL");
+ }
+ }
+ };
+
+ @Override
+ public void onDescriptorWrite(android.bluetooth.BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
+ super.onDescriptorWrite(gatt, descriptor, status);
+ if (gatt != bluetoothGatt) {
+ if (DEBUG) appendToLog("INVALID mBluetoothGatt");
+ } else if (status != android.bluetooth.BluetoothGatt.GATT_SUCCESS) {
+ if (DEBUG) appendToLog("status=" + status);
+ } else {
+ if (DEBUG) appendToLog("descriptor=" + descriptor.getUuid().toString().substring(4, 8));
+ }
+ }
+
+ private boolean writeDescriptor(BluetoothGattDescriptor descriptor, byte[] value) {
+ descriptor.setValue(value);
+ if (checkSelfPermissionBLUETOOTH() == false) return false;
+ if (!bluetoothGatt.writeDescriptor(descriptor))
+ return false;
+ return true;
+ }
+
+ @Override
+ public void onDescriptorRead(android.bluetooth.BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
+ super.onDescriptorRead(gatt, descriptor, status);
+ if (gatt != bluetoothGatt) {
+ if (DEBUG) utility.appendToLogRunnable("onDescriptorRead(): INVALID mBluetoothGatt");
+ } else if (status != android.bluetooth.BluetoothGatt.GATT_SUCCESS) {
+ if (DEBUG) utility.appendToLogRunnable("onDescriptorRead(): status=" + status);
+ } else {
+ if (DEBUG) utility.appendToLogRunnable("onDescriptorRead(): descriptor=" + descriptor.getUuid().toString().substring(4, 8));
+ }
+ }
+
+ @Override
+ public void onCharacteristicRead(android.bluetooth.BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
+ super.onCharacteristicRead(gatt, characteristic, status);
+ if (gatt != bluetoothGatt) {
+ if (DEBUG) appendToLog("INVALID mBluetoothGatt");
+ } else if (status != android.bluetooth.BluetoothGatt.GATT_SUCCESS) {
+ if (DEBUG) appendToLog("status=" + status);
+ } else {
+ _readCharacteristic_in_progress = false;
+
+ final String serviceUuidd = characteristic.getService().getUuid().toString().substring(4, 8);
+ final String characteristicUuid = characteristic.getUuid().toString().substring(4, 8);
+ final byte[] v = characteristic.getValue();
+ final long t = utility.getReferencedCurrentTimeMs();
+ mHandler.removeCallbacks(mReadCharacteristicRunnable);
+ StringBuilder stringBuilder = new StringBuilder();
+ if (v != null && v.length > 0) {
+ stringBuilder.ensureCapacity(v.length * 3);
+ for (byte b : v)
+ stringBuilder.append(String.format("%02X ", b));
+ }
+ if (DEBUG) appendToLog(serviceUuidd + ", " + characteristicUuid + " = " + stringBuilder.toString() + " = " + new String(v));
+ if (DEBUG) appendToLog("starts in onCharacteristicRead");
+ mReadCharacteristicRunnable.run();
+ }
+ }
+
+ private final Runnable mReadCharacteristicRunnable = new Runnable() {
+ @Override
+ public void run() {
+ if (mBluetoothGattCharacteristicToRead.size() == 0) {
+ if (DEBUG) appendToLog("mReadCharacteristicRunnable(): read finish");
+ characteristicListRead = true;
+ } else if (isBleBusy()) {
+ if (DEBUG) appendToLog("mReadCharacteristicRunnable(): PortBusy");
+ mHandler.postDelayed(mReadCharacteristicRunnable, 100);
+ } else if (readCharacteristic(mBluetoothGattCharacteristicToRead.get(0)) == false) {
+ if (DEBUG) appendToLog("mReadCharacteristicRunnable(): Read FAIL");
+ mHandler.postDelayed(mReadCharacteristicRunnable, 100);
+ } else {
+ mBluetoothGattCharacteristicToRead.remove(0);
+ if (DEBUG) appendToLog("mReadCharacteristicRunnable(): starts in mReadCharacteristicRunnable");
+ mHandler.postDelayed(mReadCharacteristicRunnable, 10000);
+ }
+ }
+ };
+
+ private boolean readCharacteristic(BluetoothGattCharacteristic characteristic) {
+ if (checkSelfPermissionBLUETOOTH() == false) return false;
+ if (bluetoothGatt.readCharacteristic(characteristic)) {
+ _readCharacteristic_in_progress = true;
+ return true;
+ }
+ return false;
+ }
+
+ @Override
+ public void onCharacteristicWrite(android.bluetooth.BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
+ boolean DEBUG = false;
+ super.onCharacteristicWrite(gatt, characteristic, status);
+ if (gatt != bluetoothGatt) {
+ if (DEBUG) appendToLog("INVALID mBluetoothGatt");
+ } else if (status != android.bluetooth.BluetoothGatt.GATT_SUCCESS) {
+ onCharacteristicWriteFailue++;
+ if (DEBUG) appendToLog("status=" + status);
+ } else {
+ onCharacteristicWriteFailue = 0;
+ if (DEBUG) appendToLog("characteristic=" + characteristic.getUuid().toString().substring(4, 8) + ", sent " + (mStreamWriteCount - mStreamWriteCountOld) + " bytes");
+ _writeCharacteristic_in_progress = false;
+ }
+ }
+
+ private int writeBleFailure = 0;
+ private int onCharacteristicWriteFailue = 0;
+ public boolean writeBleStreamOut(byte[] value) {
+ if (bluetoothGatt == null) {
+ if (DEBUG) appendToLog("ERROR with NULL mBluetoothGatt");
+ } else if (mReaderStreamOutCharacteristic == null) {
+ if (DEBUG) appendToLog("ERROR with NULL mReaderStreamOutCharacteristic");
+ } else if (isBleBusy() || characteristicListRead == false) {
+ if (true) appendToLog("isBleBusy() = " + isBleBusy() + ", characteristicListRead = " + characteristicListRead);
+ } else {
+ mReaderStreamOutCharacteristic.setValue(value);
+ if (checkSelfPermissionBLUETOOTH() == false) return false;
+ boolean bValue = bluetoothGatt.writeCharacteristic(mReaderStreamOutCharacteristic);
+ if (bValue == false) writeBleFailure++;
+ else {
+ writeBleFailure = 0;
+ if (utility.DEBUG_BTDATA || true) appendToLogView("BtDataOut: " + byteArrayToString(value));
+ writeDebug2File("Down " + byteArrayToString(value));
+ _writeCharacteristic_in_progress = true;
+ mStreamWriteCountOld = mStreamWriteCount;
+ mStreamWriteCount += value.length;
+ return true;
+ }
+ if (false && (writeBleFailure != 0 || onCharacteristicWriteFailue != 0)) {
+ appendToLogView("failure in writeCharacteristic(" + byteArrayToString(value) + "), writeBleFailure = " + writeBleFailure + ", onCharacteristicWriteFailue = " + onCharacteristicWriteFailue);
+ if (writeBleFailure > 5 || onCharacteristicWriteFailue > 5) {
+ appendToLogView("writeBleFailure is too much. start disconnect !!!");
+ appendToLog("disconnect C");
+ disconnect(); //mReaderStreamOutCharacteristic = null;
+ }
+ }
+ }
+ return false;
+ }
+
+ private boolean streamInRequest = false;
+ @Override
+ public void onCharacteristicChanged(android.bluetooth.BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
+ super.onCharacteristicChanged(gatt, characteristic);
+ if (gatt != bluetoothGatt) {
+ utility.writeDebug2File("Up1 Error, mismatched gatt");
+ if (DEBUG) {
+ byte[] v = characteristic.getValue();
+ utility.appendToLogRunnable("onCharacteristicChanged(): INVALID mBluetoothGatt, with address = " + gatt.getDevice().getAddress() + ", values =" + byteArrayToString(v));
+ }
+ } else if (!characteristic.equals(mReaderStreamInCharacteristic)) {
+ utility.writeDebug2File("Up1 Error, mismatched characteristic");
+ if (DEBUG) utility.appendToLogRunnable("onCharacteristicChanged(): characteristic is not ReaderSteamIn");
+ } else if (bluetoothConnectionState == BluetoothProfile.STATE_DISCONNECTED) {
+ utility.writeDebug2File("Up1 Error, disconnected bluetoothConnectionState");
+ streamInBufferHead = 0;
+ streamInBufferTail = 0;
+ streamInBufferSize = 0;
+ } else {
+ byte[] v = characteristic.getValue();
+ if (false) utility.appendToLogRunnable("onCharacteristicChanged(): VALID mBluetoothGatt, values =" + byteArrayToString(v));
+ synchronized (arrayListStreamIn) {
+ if (v.length != 0) {
+ streamInTotalCounter++;
+ }
+ if (streamInBufferReseting) {
+ if (DEBUG) utility.appendToLogRunnable("onCharacteristicChanged(): RESET.");
+ streamInBufferReseting = false;
+ streamInBufferSize = 0;
+ streamInBytesMissing = 0;
+ }
+ if (streamInBufferSize + v.length > streamInBuffer.length) {
+ utility.writeDebug2File("Up1 Error, insufficient buffer. missed " + byteArrayToString(v));
+ Log.i(TAG, ".Hello: missing data = " + byteArrayToString(v));
+ if (streamInBytesMissing == 0) {
+ streamInOverflowTime = utility.getReferencedCurrentTimeMs();
+ }
+ streamInBytesMissing += v.length;
+ } else {
+ if (true) utility.writeDebug2File("Up1 " + byteArrayToString(v));
+ if (utility.DEBUG_BTDATA) Log.i(TAG, "BtDataIn= " + byteArrayToString(v));
+ if (isStreamInBufferRing) {
+ streamInBufferPush(v, 0, v.length);
+ } else {
+ System.arraycopy(v, 0, streamInBuffer, streamInBufferSize, v.length);
+ }
+ streamInBufferSize += v.length;
+ streamInAddCounter++;
+ streamInAddTime = utility.getReferencedCurrentTimeMs();
+ if (streamInRequest == false) {
+ streamInRequest = true;
+ //appendToLog("post runnableProcessStreamInData after onCharacteristicChanged");
+ mHandler.removeCallbacks(runnableProcessStreamInData); mHandler.post(runnableProcessStreamInData);
+ }
+ }
+ }
+ }
+ }
+
+ private boolean streamInBufferReseting = false;
+ void setStreamInBufferReseting() { streamInBufferReseting = true; }
+
+ void processStreamInData() {
+ if (connectorCallback != null) connectorCallback.callbackMethod();
+ }
+
+ public interface ConnectorCallback {
+ void callbackMethod();
+ }
+ public ConnectorCallback connectorCallback = null;
+
+ private int intervalProcessBleStreamInData = 100; //50;
+ public int getIntervalProcessBleStreamInData() { return intervalProcessBleStreamInData; }
+ public final Runnable runnableProcessStreamInData = new Runnable() {
+ @Override
+ public void run() {
+ streamInRequest = false;
+ processStreamInData();
+ //appendToLog("post runnableProcessStreamInData within runnableProcessStreamInData");
+ mHandler.postDelayed(runnableProcessStreamInData, intervalProcessBleStreamInData);
+ }
+ };
+
+ @Override
+ public void onMtuChanged(android.bluetooth.BluetoothGatt gatt, int mtu, int status) {
+ super.onMtuChanged(gatt, mtu, status);
+ Log.i(TAG, "onMtuChanged starts");
+ if (gatt != bluetoothGatt) {
+ if (DEBUG) utility.appendToLogRunnable("onMtuChanged: INVALID mBluetoothGatt");
+ } else if (status != android.bluetooth.BluetoothGatt.GATT_SUCCESS) {
+ if (DEBUG) utility.appendToLogRunnable("onMtuChanged: status=" + status);
+ } else {
+ if (DEBUG_BTOP) utility.appendToLogRunnable("onMtuChanged: mtu=" + mtu);
+ }
+ }
+
+ @Override
+ public void onReliableWriteCompleted(android.bluetooth.BluetoothGatt gatt, int status) {
+ super.onReliableWriteCompleted(gatt, status);
+ if (gatt != bluetoothGatt) {
+ if (true) utility.appendToLogRunnable("INVALID mBluetoothGatt");
+ } else {
+ if (true) utility.appendToLogRunnable("onReliableWriteCompleted(): status=" + status);
+ //mBluetoothGatt.abortReliableWrite();
+ }
+ }
+
+ private Context context; Utility utility; String strReaderServiceUUID; //private Activity activity;
+ public BluetoothGatt(Context context, Utility utility, String strReaderServiceUUID) {
+ boolean DEBUG = false;
+ this.context = context; //activity = (Activity) mContext;
+ this.strReaderServiceUUID = strReaderServiceUUID;
+ this.utility = utility; DEBUG_PKDATA = utility.DEBUG_PKDATA; DEBUG_APDATA = utility.DEBUG_APDATA;
+
+// BluetoothConfigManager mConfigManager;
+// mConfigManager = BluetoothConfigManager.getInstance();
+// appendToLog("BluetoothConfigManager.getIoCapability = " + mConfigManager.getIoCapability());
+
+ PackageManager mPackageManager = this.context.getPackageManager();
+ if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
+ bluetoothManager = (BluetoothManager) this.context.getSystemService(Context.BLUETOOTH_SERVICE);
+ bluetoothAdapter = bluetoothManager.getAdapter();
+ if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
+ boolean isBle5 = bluetoothAdapter.isLeCodedPhySupported();
+ boolean isAdvertising5 = bluetoothAdapter.isLeExtendedAdvertisingSupported();
+ if (DEBUG) appendToLog("isBle5 = " + isBle5 + ", isAdvertising5 = " + isAdvertising5);
+ }
+ } else {
+ bluetoothAdapter = null;
+ if (DEBUG) appendToLog("NO BLUETOOTH_LE");
+ }
+
+ if (DEBUG) {
+ LocationManager locationManager = (LocationManager) this.context.getSystemService(LOCATION_SERVICE);
+ if (ActivityCompat.checkSelfPermission(this.context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) appendToLog("permitted ACCESS_FINE_LOCATION");
+ if (ActivityCompat.checkSelfPermission(this.context, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) appendToLog("permitted ACCESS_COARSE_LOCATION");
+
+ List stringProviderList = locationManager.getAllProviders();
+ for (String stringProvider : stringProviderList)
+ appendToLog("Provider = " + stringProvider);
+ if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER))
+ appendToLog("ProviderEnabled GPS_PROVIDER");
+ if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER))
+ appendToLog("ProviderEnabled NETWORK_PROVIDER");
+ if (locationManager.isProviderEnabled(LocationManager.PASSIVE_PROVIDER))
+ appendToLog("ProviderEnabled PASSIVE_PROVIDER");
+ }
+ }
+
+ private PopupWindow popupWindow;
+ private boolean /*bleEnableRequestShown0 = false, */bleEnableRequestShown = false;
+ private boolean isLocationAccepted = false;
+ boolean bAlerting = false; //CustomAlertDialog appdialog;
+ public boolean scanDevice(boolean enable, BluetoothAdapter.LeScanCallback mLeScanCallback, ScanCallback mScanCallBack) {
+ boolean DEBUG = false;
+ if (DEBUG) appendToLog("BluetoothGatt.scanDevice: StreamOut: enable = " + enable);
+ boolean result = false;
+ boolean locationReady = true;
+ if (enable && isConnected()) return true;
+ if (enable == false && isScanning() == false) return true;
+
+ if (enable) {
+ LocationManager locationManager = (LocationManager) context.getSystemService(LOCATION_SERVICE);
+ if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) == false && locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER) == false)
+ isLocationAccepted = false;
+ }
+ if (DEBUG || utility.DEBUG_SCAN) appendToLog("BluetoothGatt.scanLeDevice: isLocationAccepted = " + isLocationAccepted + ", bAlerting = " + bAlerting + ", bleEnableRequestShown = " + bleEnableRequestShown);
+ /*if (false && isLocationAccepted == false) {
+ if (bAlerting == false && bleEnableRequestShown0 == false) {
+ bAlerting = true;
+ if (DEBUG) appendToLog("StreamOut: new AlertDialog");
+ popupAlert();
+ }
+ return false;
+ }*/
+/*
+ if (DEBUG) appendToLog("StreamOut: Passed AlertDialog");
+ if (enable && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
+ if (DEBUG) appendToLog("Checking permission and grant !!!");
+ LocationManager locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
+ if (DEBUG_SCAN) appendToLog("locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) = " + locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER));
+ if (DEBUG_SCAN) appendToLog("locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER) = " + locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER));
+ if (DEBUG_SCAN) appendToLog("ActivityCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_FINE_LOCATION) = " + ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION));
+ if (DEBUG_SCAN) appendToLog("ActivityCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_COARSE_LOCATION) = " + ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION));
+ if (false && locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) == false && locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER) == false) {
+ boolean isShowing = false;
+ if (popupWindow != null) isShowing = popupWindow.isShowing();
+ if (isShowing == false) {
+ LayoutInflater layoutInflater = (LayoutInflater) mContext.getSystemService(LAYOUT_INFLATER_SERVICE);
+ View popupView = layoutInflater.inflate(R.layout.popup, null);
+ popupWindow = new PopupWindow(popupView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
+ popupWindow.showAtLocation(popupView, Gravity.CENTER, 0, 0);
+ TextView textViewDismiss = (TextView) popupView.findViewById(R.id.dismissMessage);
+ textViewDismiss.setText("Android OS 6.0+ requires to enable location service to find the nearby BLE devices");
+ Button btnDismiss = (Button) popupView.findViewById(R.id.dismiss);
+ if (DEBUG) appendToLog("Setting grant");
+ btnDismiss.setOnClickListener(new Button.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ popupWindow.dismiss();
+ if (DEBUG) appendToLog("Set GRANT");
+ Intent intent1 = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
+ mContext.startActivity(intent1);
+ }
+ });
+ }
+ return false;
+ } else if (
+ (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) == false
+ && locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER) == false)
+ || (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
+ && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)) {
+ if (true) {
+ if (bAlerting || bleEnableRequestShown0) return false;
+ bAlerting = true;
+ popupAlert();
+ return false;
+ }
+ }
+ }
+*/
+ if (isBLUETOOTH_CONNECTinvalid()) return false;
+
+ if (locationReady == false) {
+ if (DEBUG) appendToLog("BluetoothGatt.scanLeDevice: AccessCoarseLocatin is NOT granted");
+ } else if (bluetoothAdapter == null) {
+ if (DEBUG) appendToLog("BluetoothGatt.scanLeDevice: scanLeDevice(" + enable + ") with NULL mBluetoothAdapter");
+/* } else if (!bluetoothAdapter.isEnabled()) {
+ if (DEBUG) appendToLog("StreamOut: bleEnableRequestShown = " + bleEnableRequestShown);
+ if (bleEnableRequestShown == false) {
+ if (true) appendToLog("scanLeDevice(" + enable + ") with DISABLED mBluetoothAdapter");
+ Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
+ activity.startActivityForResult(enableBtIntent, 1);
+ if (DEBUG) appendToLog("StreamOut: bleEnableRequestShown is set");
+ bleEnableRequestShown = true; mHandler.postDelayed(mRquestAllowRunnable, 60000);
+ }
+*/
+ } else {
+ bleEnableRequestShown = false;
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
+ bluetoothLeScanner = bluetoothAdapter.getBluetoothLeScanner();
+ if (bluetoothLeScanner == null) {
+ if (DEBUG) appendToLog("BluetoothGatt.scanLeDevice: scanLeDevice(" + enable + ") with NULL BluetoothLeScanner");
+ return false;
+ }
+ }
+ if (enable == false) {
+ if (true) appendToLog("BluetoothGatt.scanLeDevice: scanLeDevice(" + enable + ") with mScanCallBack is " + (mScanCallBack != null ? "VALID" : "INVALID"));
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
+ if (mScanCallBack != null) bluetoothLeScanner.stopScan(mScanCallBack);
+ } else {
+ if (mLeScanCallback != null) bluetoothAdapter.stopLeScan(mLeScanCallback);
+ }
+ scanning = false; result = true;
+ } else {
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
+ if (true) appendToLog("BluetoothGatt.scanLeDevice: scanLeDevice(" + enable + "): START with mleScanner. ActivityCompat.checkSelfPermission(activity, Manifest.permission.BLUETOOTH_SCAN) = " + ActivityCompat.checkSelfPermission(context, Manifest.permission.BLUETOOTH_SCAN));
+ if (isBLUETOOTH_CONNECTinvalid()) return false;
+ else bluetoothLeScanner.startScan(mScanCallBack);
+ } else {
+ if (true) appendToLog("BluetoothGatt.scanLeDevice: scanLeDevice(" + enable + "): START with mBluetoothAdapter");
+ bluetoothAdapter.startLeScan(mLeScanCallback);
+ }
+ scanning = true; result = true;
+ }
+ }
+ return result;
+ }
+
+ private final Runnable mRquestAllowRunnable = new Runnable() {
+ @Override
+ public void run() {
+ //bleEnableRequestShown0 = false;
+ bleEnableRequestShown = false;
+ }
+ };
+/*
+ void popupAlert() {
+ appdialog = new CustomAlertDialog();
+ appdialog.Confirm(activity, "Use your location",
+ "This app collects location data in the background. In terms of the features using this location data in the background, this App collects location data when it is reading RFID tag in all inventory pages. The purpose of this is to correlate the RFID tag with the actual GNSS(GPS) location of the tag. In other words, this is to track the physical location of the logistics item tagged with the RFID tag.",
+ "No thanks", "Turn on",
+ new Runnable() {
+ @Override
+ public void run() {
+ isLocationAccepted = true;
+ appendToLog("StreamOut: This from FALSE proc");
+ if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
+// && ActivityCompat.checkSelfPermission(activity, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED
+ && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
+ appendToLog("requestPermissions ACCESS_FINE_LOCATION 123");
+ requestPermissions(activity, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 123);
+ if (false) Toast.makeText(mContext, R.string.toast_permission_not_granted, Toast.LENGTH_SHORT).show();
+ }
+ {
+ LocationManager locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
+ if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) == false && locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER) == false) {
+ appendToLog("StreamOut: start activity ACTION_LOCATION_SOURCE_SETTINGS");
+ Intent intent1 = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
+ mContext.startActivity(intent1);
+ }
+ }
+ bleEnableRequestShown0 = true; mHandler.postDelayed(mRquestAllowRunnable, 60000);
+ bAlerting = false;
+ }
+ },
+ new Runnable() {
+ @Override
+ public void run() {
+ appendToLog("StreamOut: This from FALSE proc");
+ bAlerting = false;
+ bleEnableRequestShown0 = true; mHandler.postDelayed(mRquestAllowRunnable, 60000);
+ }
+ });
+ }
+
+ BroadcastReceiver myReceiver = new BroadcastReceiver() {
+ @Override
+ public void onReceive(Context context, Intent intent) {
+ String action = intent.getAction();
+ appendToLog("action = " + action);
+ if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {
+ BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
+ if (device.getBondState() == BluetoothDevice.BOND_BONDED) {
+ // CONNECT
+ }
+ } else if (BluetoothDevice.ACTION_FOUND.equals(action)) {
+ BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
+ // Discover new device
+ }
+ }
+ };
+*/
+ public boolean connect(ReaderDevice readerDevice) {
+ boolean DEBUG = false;
+ if (DEBUG) appendToLog("abcc: start connecting " + readerDevice.getName());
+ if (readerDevice == null) {
+ if (DEBUG) appendToLog("with NULL readerDevice");
+ } else {
+ String address = readerDevice.getAddress();
+ if (bluetoothAdapter == null) {
+ if (DEBUG) appendToLog("connect[" + address + "] with NULL mBluetoothAdapter");
+ } else if (!bluetoothAdapter.isEnabled()) {
+ if (DEBUG) appendToLog("connect[" + address + "] with DISABLED mBluetoothAdapter");
+ } else {
+ utility.debugFileSetup(); utility.debugFileEnable(true);
+ utility.setReferenceTimeMs();
+ if (utility.DEBUG_CONNECT) appendToLog("connect[" + address + "]: connectGatt starts");
+ bluetoothConnectionState = -1;
+ if (checkSelfPermissionBLUETOOTH() == false) return false;
+ bluetoothGatt = bluetoothAdapter.getRemoteDevice(address).connectGatt(context, false, this);
+ if (bluetoothGatt != null) mBluetoothGattActive = true;
+ if (false && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
+ if (true) {
+ bluetoothGatt.requestConnectionPriority(android.bluetooth.BluetoothGatt.CONNECTION_PRIORITY_HIGH);
+ if (DEBUG) appendToLog("Stream Set to HIGH");
+ }
+ else {
+ bluetoothGatt.requestConnectionPriority(android.bluetooth.BluetoothGatt.CONNECTION_PRIORITY_BALANCED);
+ if (DEBUG) appendToLog("Stream Set to BALANCED");
+ }
+ }
+ readerDeviceConnected = readerDevice;
+ characteristicListRead = true; //skip in case there is problem in completing reading characteristic features, causing endless reading 0706 and 0C02
+ appendToLog("post runnableProcessStreamInData after connect");
+ mHandler.removeCallbacks(runnableProcessStreamInData); mHandler.post(runnableProcessStreamInData);
+ return true;
+ }
+ }
+ return false;
+ }
+
+ public void disconnect() {
+ appendToLog("abcc: start disconnect ");
+ if (bluetoothGatt == null) {
+ if (DEBUG) appendToLog("NULL mBluetoothGatt");
+ } else {
+ utility.debugFileClose();
+ mReaderStreamOutCharacteristic = null;
+ mHandler.removeCallbacks(mDisconnectRunnable);
+ mHandler.post(mDisconnectRunnable); disconnectRunning = true;
+ if (DEBUG) appendToLog("abcc done and start mDisconnectRunnable");
+ appendToLog("post runnableProcessStreamInData after disconnect");
+ mHandler.removeCallbacks(runnableProcessStreamInData);
+ }
+ }
+ boolean mBluetoothGattActive = false;
+ boolean forcedDisconnect1() {
+ mHandler.removeCallbacks(mReadRssiRunnable);
+ mHandler.removeCallbacks(mReadCharacteristicRunnable);
+ if (bluetoothGatt != null) {
+ if (mBluetoothGattActive) {
+ appendToLog("abcc mDisconnectRunnable(): close mBluetoothGatt");
+ if (checkSelfPermissionBLUETOOTH() == false) return false;
+ bluetoothGatt.close();
+ mBluetoothGattActive = false;
+ } else {
+ appendToLog("abcc mDisconnectRunnable(): Null mBluetoothGatt");
+ bluetoothGatt = null;
+ return true;
+ }
+ }
+ return false;
+ //mBluetoothConnectionState = -1;
+ }
+
+ private boolean disconnectRunning = false;
+ public BluetoothDevice bluetoothDeviceConnectOld;
+ private final Runnable mDisconnectRunnable = new Runnable() {
+ @Override
+ public void run() {
+ boolean done = false;
+ int bGattConnection = -1;
+ if (checkSelfPermissionBLUETOOTH() == false) return;
+ if (bluetoothDeviceConnectOld != null) bGattConnection = bluetoothManager.getConnectionState(bluetoothDeviceConnectOld, BluetoothProfile.GATT);
+ if (DEBUG) appendToLog("abcc DisconnectRunnable(): disconnect with mBluetoothConnectionState = " + bluetoothConnectionState + ", gattConnection = " + bGattConnection);
+ if (bluetoothConnectionState < 0) {
+ appendToLog("abcc DisconnectRunnable(): start mBluetoothGatt.disconnect");
+ bluetoothGatt.disconnect();
+ bluetoothConnectionState = BluetoothProfile.STATE_DISCONNECTED;
+ } else if (bluetoothConnectionState != BluetoothProfile.STATE_DISCONNECTED) {
+ appendToLog("abcc 2 DisconnectRunnable(): start mBluetoothGatt.disconnect");
+ if (checkSelfPermissionBLUETOOTH()) {
+ bluetoothGatt.disconnect(); //forcedDisconnect(true);
+ bluetoothConnectionState = BluetoothProfile.STATE_DISCONNECTED;
+ }
+ } else if (forcedDisconnect1()) {
+ if (DEBUG) appendToLog("abcc mDisconnectRunnable(): END");
+ disconnectRunning = false;
+ if (false) bluetoothAdapter.disable();
+ done = true;
+ }
+ if (done == false) mHandler.postDelayed(mDisconnectRunnable, 100);
+ }
+ };
+
+ boolean isBleBusy() {
+ return bluetoothConnectionState != BluetoothProfile.STATE_CONNECTED || _readCharacteristic_in_progress /*|| _writeCharacteristic_in_progress*/;
+ }
+
+ private BluetoothGattCharacteristic getCharacteristic(UUID service, UUID characteristic) {
+ BluetoothGattService s = bluetoothGatt.getService(service);
+ if (s == null)
+ return null;
+ BluetoothGattCharacteristic c = s.getCharacteristic(characteristic);
+ return c;
+ }
+
+ private long streamInDataMilliSecond;
+ public long getStreamInDataMilliSecond() { return streamInDataMilliSecond; }
+ public int readSteamIn(byte[] buffer, int byteOffset, int byteCount) {
+ synchronized (arrayListStreamIn) {
+ if (0 == streamInBufferSize) return 0;
+
+ if (isArrayListStreamInBuffering) {
+ int byteGot = 0;
+ int length1 = arrayListStreamIn.get(0).data.length;
+ if (arrayListStreamIn.size() != 0 && buffer.length - byteOffset > length1) {
+ System.arraycopy(arrayListStreamIn.get(0).data, 0, buffer, byteOffset, length1);
+ streamInDataMilliSecond = arrayListStreamIn.get(0).milliseconds;
+ arrayListStreamIn.remove(0);
+ byteOffset += length1;
+ byteGot += length1;
+ }
+ byteCount = byteGot;
+ } else {
+ if (byteCount > streamInBufferSize)
+ byteCount = streamInBufferSize;
+ if (byteOffset + byteCount > buffer.length) {
+ byteCount = buffer.length - byteOffset;
+ }
+ if (byteCount <= 0) return 0;
+
+ if (isStreamInBufferRing) {
+ streamInBufferPull(buffer, byteOffset, byteCount);
+ } else {
+ System.arraycopy(streamInBuffer, 0, buffer, byteOffset, byteCount);
+ System.arraycopy(streamInBuffer, byteCount, streamInBuffer, 0, streamInBufferSize - byteCount);
+ }
+ }
+ streamInBufferSize -= byteCount;
+ return byteCount;
+ }
+ }
+
+ private int totalTemp, totalReceived;
+ private long firstTime, totalTime; public long getStreamInRate() {
+ if (totalTime == 0 || totalReceived == 0) return 0;
+ return totalReceived * 1000 / totalTime;
+ }
+
+ private class StreamInData {
+ byte[] data;
+ long milliseconds;
+ }
+ private ArrayList arrayListStreamIn = new ArrayList(); private boolean isArrayListStreamInBuffering = true;
+ private boolean isStreamInBufferRing = true;
+ private void streamInBufferPush(byte[] inData, int inDataOffset, int length) {
+ int length1 = streamInBuffer.length - streamInBufferTail;
+ int totalCopy = 0;
+ if (isArrayListStreamInBuffering) {
+ StreamInData streamInData = new StreamInData();
+ streamInData.data = inData;
+ streamInData.milliseconds = System.currentTimeMillis();
+ arrayListStreamIn.add(streamInData);
+ totalCopy = length;
+ } else {
+ if (length > length1) {
+ totalCopy = length1;
+ System.arraycopy(inData, inDataOffset, streamInBuffer, streamInBufferTail, length1);
+ length -= length1;
+ inDataOffset += length1;
+ streamInBufferTail = 0;
+ }
+ if (length != 0) {
+ totalCopy += length;
+ System.arraycopy(inData, inDataOffset, streamInBuffer, streamInBufferTail, length);
+ streamInBufferTail += length;
+ }
+ }
+ if (totalCopy != 0) {
+ totalTemp += totalCopy;
+ long timeDifference = System.currentTimeMillis() - firstTime;
+ if (totalTemp > 17 && timeDifference > 1000) {
+ totalReceived = totalTemp;
+ totalTime = timeDifference;
+ //appendToLog("BtDataIn: totalReceived = " + totalReceived + ", totalTime = " + totalTime);
+ firstTime = System.currentTimeMillis();
+ totalTemp = 0;
+ }
+ }
+ }
+ private void streamInBufferPull(byte[] buffer, int byteOffset, int length) {
+ synchronized (arrayListStreamIn) {
+ int length1 = streamInBuffer.length - streamInBufferHead;
+ if (length > length1) {
+ System.arraycopy(streamInBuffer, streamInBufferHead, buffer, byteOffset, length1);
+ length -= length1;
+ byteOffset += length1;
+ streamInBufferHead = 0;
+ }
+ if (length != 0) {
+ System.arraycopy(streamInBuffer, streamInBufferHead, buffer, byteOffset, length);
+ streamInBufferHead += length;
+ }}
+ }
+
+ public boolean isBLUETOOTH_CONNECTinvalid() {
+ boolean bValue = false;
+/*
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S && (
+ ActivityCompat.checkSelfPermission(mContext, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED || ActivityCompat.checkSelfPermission(mContext, Manifest.permission.BLUETOOTH_SCAN) != PackageManager.PERMISSION_GRANTED
+ )) {
+ appendToLog("requestPermissions BLUETOOTH_CONNECT & BLUETOOTH_CONNECT 123");
+ requestPermissions(activity, new String[] {
+ Manifest.permission.BLUETOOTH_SCAN,
+ Manifest.permission.BLUETOOTH_CONNECT
+ }, 123);
+ if (false) Toast.makeText(mContext, R.string.toast_permission_not_granted, Toast.LENGTH_SHORT).show();
+ bValue = true;
+ }
+ //appendToLog("isBLUETOOTH_CONNECTinvalid returns " + bValue);
+*/
+ return bValue;
+ }
+
+ String byteArray2DisplayString(byte[] byteData) { return utility.byteArray2DisplayString(byteData); }
+ String byteArrayToString(byte[] packet) { return utility.byteArrayToString(packet); }
+ int byteArrayToInt(byte[] bytes) { return utility.byteArrayToInt(bytes); }
+ void appendToLog(String s) { utility.appendToLog(s); }
+ void appendToLogView(String s) { utility.appendToLogView(s); }
+ void writeDebug2File(String stringDebug) { utility.writeDebug2File(stringDebug); }
+ boolean compareArray(byte[] array1, byte[] array2, int length) { return utility.compareByteArray(array1, array2, length); }
+ void debugFileEnable(boolean enable) { utility.debugFileEnable(enable); }
+ String getlast3digitVersion(String str) { return utility.getlast3digitVersion(str); }
+ public boolean isVersionGreaterEqual(String version, int majorVersion, int minorVersion, int buildVersion) { return utility.isVersionGreaterEqual(version, majorVersion, minorVersion, buildVersion); }
+ double get2BytesOfRssi(byte[] bytes, int index) { return utility.get2BytesOfRssi(bytes, index); }
+
+ int getConnectionState(BluetoothDevice bluetoothDevice) {
+ if (checkSelfPermissionBLUETOOTH() == false) return -1;
+
+ return bluetoothManager.getConnectionState(bluetoothDevice, BluetoothProfile.GATT);
+ }
+
+ boolean discoverServices() {
+ if (checkSelfPermissionBLUETOOTH() == false) return false;
+ return bluetoothGatt.discoverServices();
+ }
+ boolean checkSelfPermissionBLUETOOTH() {
+ boolean bValue = false;
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
+ if (ActivityCompat.checkSelfPermission(context, Manifest.permission.BLUETOOTH_CONNECT) == PackageManager.PERMISSION_GRANTED) bValue = true;
+ } else if (ActivityCompat.checkSelfPermission(context.getApplicationContext(), Manifest.permission.BLUETOOTH) == PackageManager.PERMISSION_GRANTED) bValue = true;
+ if (false) Log.i("Hello3", "checkSelfPermissionBLUETOOTH bValue = " + bValue);
+ return bValue;
+ }
+
+ public static class CsScanData {
+ public BluetoothDevice device; public String name, address;
+ public int rssi;
+ public byte[] scanRecord;
+ public ArrayList decoded_scanRecord;
+ public int serviceUUID2p2;
+
+ public CsScanData(BluetoothDevice device, int rssi, byte[] scanRecord) {
+ this.device = device;
+ this.rssi = rssi;
+ this.scanRecord = scanRecord;
+ decoded_scanRecord = new ArrayList();
+ }
+ CsScanData(String name, String address, int rssi, byte[] scanRecord) {
+ this.device = device; this.name = name; this.address = address;
+ this.rssi = rssi;
+ this.scanRecord = scanRecord;
+ }
+ public BluetoothDevice getDevice() { return device; }
+ public String getName() {
+ return name;
+ }
+ public String getAddress() {
+ return address;
+ }
+ public byte[] getScanRecord() { return scanRecord; }
+ }
+
+ public void removeBond(ReaderDevice readerDevice) {
+ if (readerDevice == null) readerDevice = readerDeviceConnected;
+ if (readerDevice != null) {
+ BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
+ if (ActivityCompat.checkSelfPermission(context, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
+ appendToLog("BluetoothGatt.removeBond, Fragment: BLUETOOTH_CONNECT is not permitted");
+ // TODO: Consider calling
+ // ActivityCompat#requestPermissions
+ // here to request the missing permissions, and then overriding
+ // public void onRequestPermissionsResult(int requestCode, String[] permissions,
+ // int[] grantResults)
+ // to handle the case where the user grants the permission. See the documentation
+ // for ActivityCompat#requestPermissions for more details.
+ return;
+ }
+ Set bluetoothDevices = bluetoothAdapter.getBondedDevices();
+ appendToLog("BluetoothGatt.removeBond, Fragment: bluetoothDevices size = " + bluetoothDevices.size());
+ int i = 0;
+ for (BluetoothDevice bluetoothDevice : bluetoothDevices) {
+ appendToLog("BluetoothGatt.removeBond, Fragment: " + i + ", Address = " + bluetoothDevice.getAddress());
+ appendToLog("BluetoothGatt.removeBond, Fragment: readerDevice is " + (readerDevice == null ? "null" : "valid")
+ + ", bluetoothDevice is " + (bluetoothDevice == null ? "null" : "valid"));
+ if (readerDevice.getAddress().matches(bluetoothDevice.getAddress())) {
+ appendToLog("BluetoothGatt.removeBond, Fragment: matched address");
+ if (false) {
+ //bluetoothDevices.re
+ } else {
+ removeBond(bluetoothDevice);
+ }
+ appendToLog("BluetoothGatt.removeBond, Fragment: break");
+ break;
+ }
+ }
+ }
+ }
+
+ public void removeBond(BluetoothDevice bluetoothDevice) {
+ try {
+ if (true) {
+ //Method m = bluetoothDevice.getClass().getMethod("disconnect", (Class[]) null);
+ //m.invoke(bluetoothDevice, (Object[]) null);
+ Method m = bluetoothDevice.getClass().getMethod("removeBond", (Class[]) null);
+ m.invoke(bluetoothDevice, (Object[]) null);
+
+ appendToLog("BluetoothGatt.removeBond, Fragment: start to wait 2000ms");
+ Thread.sleep(1000); //1000 milliseconds is one second.
+ appendToLog("BluetoothGatt.removeBond, Fragment: end of timeout");
+ } else {
+ Method m = bluetoothDevice.getClass().getMethod("createBond", (Class[]) null);
+ m.invoke(bluetoothDevice, (Object[]) null);
+ }
+ } catch (Exception e) {
+ appendToLog("BluetoothGatt.removeBond, Fragment: exception " + e.toString());
+ e.printStackTrace();
+ }
+ }
+}
+
+
+
+package com.csl.cslibrary4a;
+
+public class ConnectorData {
+ public enum ConnectorTypes {
+ RFID, BARCODE, NOTIFICATION, SILICONLAB, BLUETOOTH, OTHER
+ }
+ public ConnectorTypes connectorTypes;
+ public byte[] dataValues;
+ public boolean invalidSequence;
+ public long milliseconds;
+}
+
+
+
+package com.csl.cslibrary4a;
+
+import android.content.Context;
+import android.widget.TextView;
+import android.widget.Toast;
+
+import java.util.ArrayList;
+
+public class ControllerConnector {
+ final boolean DEBUG = false;
+ boolean userDebugEnableDefault = false, userDebugEnable = userDebugEnableDefault;
+
+ Context context; Utility utility;
+ public ControllerConnector(Context context, Utility utility) {
+ this.context = context;
+ this.utility = utility;
+ }
+ private String byteArrayToString(byte[] packet) { return utility.byteArrayToString(packet); }
+ private boolean compareArray(byte[] array1, byte[] array2, int length) { return utility.compareByteArray(array1, array2, length); }
+ private void appendToLog(String s) { utility.appendToLog(s); }
+ private void appendToLogView(String s) { utility.appendToLogView(s); }
+
+ private int icsModel = -1;
+ int getCsModel() {
+ if (false) appendToLog("icsModel = " + icsModel);
+ return icsModel;
+ }
+
+ public enum ControllerPayloadEvents {
+ CONTROLLER_GET_VERSION, CONTROLLER_GET_SERIALNUMBER, CONTROLLER_GET_MODELNAME, CONTROLLER_RESET
+ }
+
+ class ControllerReadData {
+ ControllerPayloadEvents controllerPayloadEvents;
+ byte[] dataValues;
+ }
+
+ private byte[] controllerVersion = new byte[]{-1, -1, -1};
+
+ public String getVersion() {
+ boolean DEBUG = false;
+ if (controllerVersion[0] == -1) {
+ boolean repeatRequest = false;
+ if (controllerToWrite.size() != 0) {
+ if (controllerToWrite.get(controllerToWrite.size() - 1) == ControllerPayloadEvents.CONTROLLER_GET_VERSION) {
+ repeatRequest = true;
+ }
+ }
+ if (repeatRequest == false) {
+ controllerToWrite.add(ControllerPayloadEvents.CONTROLLER_GET_VERSION);
+ if (utility.DEBUG_PKDATA || DEBUG) appendToLog("PkData: add GET_VERSION to controllerWrite with length = " + controllerToWrite.size());
+ }
+ return "";
+ } else {
+ if (DEBUG) appendToLog("controllerVersion = " + byteArrayToString(controllerVersion));
+ String string = String.valueOf(controllerVersion[0]) + "." + String.valueOf(controllerVersion[1]) + "." + String.valueOf(controllerVersion[2]);
+ if (DEBUG) appendToLog("controllerVersion string = " + string);
+ return string;
+ }
+ }
+
+ private byte[] serialNumber = null;
+ public String getSerialNumber() {
+ if (serialNumber == null) {
+ boolean repeatRequest = false;
+ if (controllerToWrite.size() != 0) {
+ if (controllerToWrite.get(controllerToWrite.size() - 1) == ControllerPayloadEvents.CONTROLLER_GET_SERIALNUMBER) {
+ repeatRequest = true;
+ }
+ }
+ if (repeatRequest == false) {
+ controllerToWrite.add(ControllerPayloadEvents.CONTROLLER_GET_SERIALNUMBER);
+ if (utility.DEBUG_PKDATA) appendToLog("PkData: add GET_SERIALNUMBER to controllerToWrite with length = " + controllerToWrite.size());
+ }
+ return "";
+ } else {
+ byte[] bytes = new byte[serialNumber.length];
+ System.arraycopy(serialNumber, 0, bytes, 0, serialNumber.length);
+ if (bytes.length == 16) {
+ if (bytes[15] == 0) {
+ bytes[15] = serialNumber[14];
+ bytes[14] = serialNumber[13];
+ bytes[13] = 0;
+ }
+ for (int i = 13; i < 16; i++) {
+ if (bytes[i] == 0) bytes[i] = 0x30;
+ }
+ }
+ if (false) appendToLog("serialNumber = " + byteArrayToString(serialNumber) + ", revised = " + byteArrayToString(bytes));
+ String string = utility.byteArray2DisplayString(bytes);
+ if (string == null || string.length() == 0) {
+ string = byteArrayToString(bytes);
+ if (string.length() > 16) string = string.substring(0, 16);
+ }
+ if (false) appendToLog("string = " + string + " from serial " + byteArrayToString(serialNumber) + ", revised = " + byteArrayToString(bytes));
+ return string;
+ }
+ }
+
+ private byte[] modelName = null;
+ public String getModelName() {
+ if (false) appendToLog("modelName = " + byteArrayToString(modelName));
+ String strValue = null;
+ if (modelName == null) {
+ boolean repeatRequest = false;
+ if (controllerToWrite.size() != 0) {
+ if (controllerToWrite.get(controllerToWrite.size() - 1) == ControllerPayloadEvents.CONTROLLER_GET_MODELNAME) {
+ repeatRequest = true;
+ }
+ }
+ if (repeatRequest == false) {
+ controllerToWrite.add(ControllerPayloadEvents.CONTROLLER_GET_MODELNAME);
+ if (false) appendToLog("PkData: add GET_MODELNAME to controllerWrite with length = " + controllerToWrite.size());
+ }
+ } else {
+ strValue = utility.byteArray2DisplayString(modelName);
+ if (false) appendToLog("strValue 0 = " + strValue);
+ if (strValue == null || strValue.length() == 0) {
+ strValue = byteArrayToString(modelName).substring(0, 5);
+ }
+ }
+ if (false) appendToLog("strValue = " + strValue);
+ return strValue;
+ }
+
+ boolean resetSiliconLab() {
+ boolean bRetValue = false;
+ bRetValue = controllerToWrite.add(ControllerConnector.ControllerPayloadEvents.CONTROLLER_RESET);
+ appendToLog("add RESET to mSiliconLabIcWrite with length = " + controllerToWrite.size());
+ //mRfidDevice.setInventoring(false);
+ return bRetValue;
+ }
+
+ public ArrayList controllerToWrite = new ArrayList<>();
+
+ private boolean arrayTypeSet(byte[] dataBuf, int pos, ControllerPayloadEvents event) {
+ boolean validEvent = false;
+ switch (event) {
+ case CONTROLLER_GET_VERSION:
+ validEvent = true;
+ break;
+ case CONTROLLER_GET_SERIALNUMBER:
+ dataBuf[pos] = 4;
+ validEvent = true;
+ break;
+ case CONTROLLER_GET_MODELNAME:
+ dataBuf[pos] = 6;
+ validEvent = true;
+ break;
+ case CONTROLLER_RESET:
+ dataBuf[pos] = 12;
+ validEvent = true;
+ break;
+ }
+ return validEvent;
+ }
+
+ private byte[] writeController(ControllerPayloadEvents event, boolean usbConnection) {
+ boolean DEBUG = false;
+ byte[] dataOut = null;
+ if (event == ControllerPayloadEvents.CONTROLLER_GET_VERSION) {
+ dataOut = new byte[]{(byte) 0xA7, (byte) 0xB3, 2, (byte) 0xE8, (byte) 0x82, (byte) 0x37, 0, 0, (byte) 0xB0, 0};
+ } else if (event == ControllerPayloadEvents.CONTROLLER_GET_SERIALNUMBER) {
+ dataOut = new byte[]{(byte) 0xA7, (byte) 0xB3, 3, (byte) 0xE8, (byte) 0x82, (byte) 0x37, 0, 0, (byte) 0xB0, 4, 0};
+ } else if (event == ControllerPayloadEvents.CONTROLLER_GET_MODELNAME) {
+ dataOut = new byte[]{(byte) 0xA7, (byte) 0xB3, 2, (byte) 0xE8, (byte) 0x82, (byte) 0x37, 0, 0, (byte) 0xB0, 6};
+ } else if (event == ControllerPayloadEvents.CONTROLLER_RESET) {
+ dataOut = new byte[]{(byte) 0xA7, (byte) 0xB3, 2, (byte) 0xE8, (byte) 0x82, (byte) 0x37, 0, 0, (byte) 0xB0, 12};
+ }
+ if (usbConnection && dataOut != null) dataOut[1] = (byte) 0xE6;
+ if (DEBUG) appendToLog(byteArrayToString(dataOut) + " for " + event.toString());
+ return dataOut;
+ }
+
+ public boolean isMatchControllerToWrite(ConnectorData connectorData) {
+ boolean match = false;
+ if (controllerToWrite.size() != 0 && connectorData.dataValues[0] == (byte)0xB0) {
+ byte[] dataInCompare = new byte[]{(byte) 0xB0, 0};
+ if (arrayTypeSet(dataInCompare, 1, controllerToWrite.get(0)) && (connectorData.dataValues.length >= dataInCompare.length + 1)) {
+ if (match = compareArray(connectorData.dataValues, dataInCompare, dataInCompare.length)) {
+ if (utility.DEBUG_PKDATA) appendToLog("PkData: matched Controller.Reply with payload = " + byteArrayToString(connectorData.dataValues) + " for writeData.Controller." + controllerToWrite.get(0).toString());
+ if (controllerToWrite.get(0) == ControllerPayloadEvents.CONTROLLER_GET_VERSION) {
+ if (connectorData.dataValues.length >= 2 + controllerVersion.length) {
+ System.arraycopy(connectorData.dataValues, 2, controllerVersion, 0, controllerVersion.length);
+ if (utility.DEBUG_PKDATA) appendToLog("PkData: matched Controller.Reply.GetVersion with version = " + byteArrayToString(controllerVersion));
+ }
+ } else if (controllerToWrite.get(0) == ControllerPayloadEvents.CONTROLLER_GET_SERIALNUMBER) {
+ int length = connectorData.dataValues.length - 2;
+ serialNumber = new byte[length];
+ System.arraycopy(connectorData.dataValues, 2, serialNumber, 0, length);
+ if (utility.DEBUG_PKDATA) appendToLog("PkData: matched Controller.Reply.GetSerialNumber with serialNumber = " + byteArrayToString(serialNumber));
+ } else if (controllerToWrite.get(0) == ControllerPayloadEvents.CONTROLLER_GET_MODELNAME) {
+ int length = connectorData.dataValues.length - 2;
+ modelName = new byte[length];
+ System.arraycopy(connectorData.dataValues, 2, modelName, 0, length);
+ if (utility.DEBUG_PKDATA) appendToLog("PkData: matched controller.GetModelName.reply with modelName = " + byteArrayToString(modelName));
+ } else if (controllerToWrite.get(0) == ControllerPayloadEvents.CONTROLLER_RESET) {
+ if (connectorData.dataValues[2] != 0) {
+ appendToLog("Controller RESET is found with error");
+ } else appendToLog("matched Controller.reply data is found");
+ } else {
+ appendToLog("matched controller.Other.reply data is found.");
+ }
+ controllerToWrite.remove(0); sendDataToWriteSent = 0;
+ if (utility.DEBUG_PKDATA) appendToLog("PkData: new controllerToWrite size = " + controllerToWrite.size());
+
+ }
+ }
+ }
+ return match;
+ }
+
+ public int sendDataToWriteSent = 0;
+ boolean controllerFailure = false;
+ public byte[] sendControllerToWrite(boolean usbConnection) {
+ if (controllerFailure) {
+ controllerToWrite.remove(0); sendDataToWriteSent = 0;
+ } else if (sendDataToWriteSent >= 5) {
+ int oldSize = controllerToWrite.size();
+ controllerToWrite.remove(0); sendDataToWriteSent = 0;
+ if (DEBUG) appendToLog("Removed after sending count-out with oldSize = " + oldSize + ", updated controllerToWrite.size() = " + controllerToWrite.size());
+ if (DEBUG) appendToLog("Removed after sending count-out.");
+ String string = "Problem in sending data to Controller Module. Removed data sending after count-out";
+ if (userDebugEnable) Toast.makeText(context, string, Toast.LENGTH_SHORT).show();
+ else appendToLogView(string);
+ controllerFailure = true; // disconnect(false);
+ } else {
+ if (DEBUG) appendToLog("size = " + controllerToWrite.size());
+ sendDataToWriteSent++;
+ return writeController(controllerToWrite.get(0), usbConnection);
+ }
+ return null;
+ }
+}
+
+
+
+package com.csl.cslibrary4a;
+
+import android.bluetooth.BluetoothProfile;
+import android.content.Context;
+import android.os.Handler;
+import android.widget.TextView;
+
+import com.csl.cslibrary4a.RfidReader.RegionCodes;
+
+import java.io.File;
+import java.util.ArrayList;
+import java.util.List;
+
+public class Cs108Library4A {
+ final boolean DEBUG = false;
+ final boolean DEBUG_FILE = false;
+ private Handler mHandler = new Handler();
+
+ Context context;
+ CsReaderConnector csReaderConnector; Utility utility;
+ boolean DEBUG_CONNECT, DEBUG_SCAN;
+ BluetoothGatt bluetoothGatt;
+ BarcodeNewland barcodeNewland; BarcodeConnector barcodeConnector;
+ NotificationConnector notificationConnector;
+ ControllerConnector controllerConnector;
+ BluetoothConnector bluetoothConnector;
+ public Cs108Library4A(Context context, TextView mLogView) {
+ this.context = context;
+ utility = new Utility(context, mLogView);
+ csReaderConnector = new CsReaderConnector(context, mLogView, utility, true); csReaderConnector.setScanType(0x01);
+ bluetoothGatt = csReaderConnector.bluetoothGatt; DEBUG_CONNECT = utility.DEBUG_CONNECT; DEBUG_SCAN = utility.DEBUG_SCAN;
+/*
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
+ mScanCallback = new ScanCallback() {
+ @Override
+ public void onBatchScanResults(List results) {
+ if (DEBUG) appendToLog("onBatchScanResults()");
+ }
+
+ @Override
+ public void onScanFailed(int errorCode) {
+ if (DEBUG) appendToLog("onScanFailed()");
+ }
+
+ @Override
+ public void onScanResult(int callbackType, ScanResult result) {
+ boolean DEBUG = false;
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
+ BluetoothGatt.CsScanData scanResultA = new BluetoothGatt.CsScanData(result.getDevice(), result.getRssi(), result.getScanRecord().getBytes());
+ boolean found98 = true;
+ if (true) found98 = check9800(scanResultA);
+ if (DEBUG) appendToLog("found98 = " + found98 + ", mScanResultList 0 = " + (mScanResultList != null ? "VALID" : "NULL"));
+ if (mScanResultList != null && found98) {
+ scanResultA.serviceUUID2p2 = check9800_serviceUUID2p1;
+ mScanResultList.add(scanResultA);
+ if (DEBUG) appendToLog("mScanResultList 0 = " + mScanResultList.size());
+ }
+ }
+ }
+ };
+ } else {
+ mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
+ @Override
+ public void onLeScan(final BluetoothDevice device, final int rssi, final byte[] scanRecord) {
+ if (true) appendToLog("onLeScan()");
+ BluetoothGatt.CsScanData scanResultA = new BluetoothGatt.CsScanData(device, rssi, scanRecord);
+ boolean found98 = true;
+ if (true) found98 = check9800(scanResultA);
+ appendToLog("found98 = " + found98 + ", mScanResultList 1 = " + (mScanResultList != null ? "VALID" : "NULL"));
+ if (mScanResultList != null && found98) {
+ scanResultA.serviceUUID2p2 = check9800_serviceUUID2p1;
+ mScanResultList.add(scanResultA);
+ appendToLog("mScanResultList 1 = " + mScanResultList.size());
+ }
+ }
+ };
+ }
+*/
+ File path = context.getFilesDir();
+ File[] fileArray = path.listFiles();
+ boolean deleteFiles = false;
+ if (true || DEBUG)
+ appendToLog("Number of file in data storage sub-directory = " + fileArray.length);
+ boolean bProfileInstalledFound = false;
+ for (int i = 0; i < fileArray.length; i++) {
+ String fileName = fileArray[i].toString();
+ if (true) appendToLog("Stored file (" + i + ") = " + fileName);
+ if (fileName.contains("profileInstalled") || fileName.contains("profileinstaller")) {
+ bProfileInstalledFound = true;
+ appendToLog("Found profileInstalled or profileinstaller file");
+ }
+ File file = new File(fileName);
+ if (deleteFiles) file.delete();
+ }
+ if (!bProfileInstalledFound) {
+ for (int i = 0; i < fileArray.length; i++) {
+ String fileName = fileArray[i].toString();
+ File file = new File(fileName);
+ file.delete();
+ appendToLog("Deleted " + fileName);
+ }
+ }
+ }
+ public String getlibraryVersion() {
+ String version = BuildConfig.VERSION_NAME;
+ //int iVersion = Integer.parseInt(version) + 10;
+ version = "15.0"; //+ String.valueOf(iVersion);
+ appendToLog("version = " + version);
+ return utility.getCombinedVersion(version);
+ }
+ public String checkVersion() {
+ return csReaderConnector.checkVersion();
+ }
+
+ //============ utility ============
+ public String byteArrayToString(byte[] packet) {
+ return utility.byteArrayToString(packet);
+ }
+ public void appendToLog(String s) {
+ utility.appendToLog(s);
+ }
+ public void appendToLogView(String s) {
+ utility.appendToLogView(s);
+ }
+ public String strFloat16toFloat32(String strData) {
+ return utility.strFloat16toFloat32(strData);
+ }
+ public String str2float16(String strData) {
+ return utility.str2float16(strData);
+ }
+ public float decodeCtesiusTemperature(String strActData, String strCalData) {
+ return utility.decodeCtesiusTemperature(strActData, strCalData);
+ }
+ public float decodeMicronTemperature(int iTag35, String strActData, String strCalData) {
+ return utility.decodeMicronTemperature(iTag35, strActData, strCalData);
+ }
+ public float decodeAsygnTemperature(String string) {
+ return utility.decodeAsygnTemperature(string);
+ }
+ public String temperatureC2F(String strValue) {
+ return utility.temperatureC2F(strValue);
+ }
+ public String temperatureF2C(String strValue) {
+ return utility.temperatureF2C(strValue);
+ }
+ public String getUpcSerial(String strEpc) {
+ return utility.getUpcSerial(strEpc);
+ }
+ public String getUpcSerialDetail(String strUpcSerial) {
+ return utility.getUpcSerialDetail(strUpcSerial);
+ }
+ public String getEpc4upcSerial(Utility.EpcClass epcClass, String filter, String companyPrefix, String itemReference, String serialNumber) {
+ return utility.getEpc4upcSerial(epcClass, filter, companyPrefix, itemReference, serialNumber);
+ }
+ public boolean checkHostProcessorVersion(String version, int majorVersion, int minorVersion, int buildVersion) {
+ return utility.checkHostProcessorVersion(version, majorVersion, minorVersion, buildVersion);
+ }
+
+ //============ android bluetooth ============
+ ArrayList mScanResultList = new ArrayList<>();
+ int check9800_serviceUUID2p1 = 0;
+ boolean bleConnection = false;
+ ReaderDevice readerDeviceConnect;
+ boolean bNeedReconnect = false;
+ int iConnectStateTimer = 0;
+/*
+ boolean check9800(BluetoothGatt.CsScanData scanResultA) {
+ boolean found98 = false, DEBUG = false;
+ if (DEBUG) appendToLog("decoded data size = " + scanResultA.decoded_scanRecord.size());
+ int iNewADLength = 0;
+ byte[] newAD = new byte[0];
+ int iNewADIndex = 0;
+ check9800_serviceUUID2p1 = -1;
+ if (bluetoothGatt.isBLUETOOTH_CONNECTinvalid()) return true;
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S && ActivityCompat.checkSelfPermission(context, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED)
+ return true;
+ String strTemp = scanResultA.getDevice().getName();
+ if (strTemp != null && DEBUG)
+ appendToLog("Found name = " + strTemp + ", length = " + String.valueOf(strTemp.length()));
+ for (byte bdata : scanResultA.getScanRecord()) {
+ if (iNewADIndex >= iNewADLength && iNewADLength != 0) {
+ scanResultA.decoded_scanRecord.add(newAD);
+ iNewADIndex = 0;
+ iNewADLength = 0;
+ if (DEBUG)
+ appendToLog("Size = " + scanResultA.decoded_scanRecord.size() + ", " + byteArrayToString(newAD));
+ }
+ if (iNewADLength == 0) {
+ iNewADLength = bdata;
+ newAD = new byte[iNewADLength];
+ iNewADIndex = 0;
+ } else newAD[iNewADIndex++] = bdata;
+ }
+ if (DEBUG) appendToLog("decoded data size = " + scanResultA.decoded_scanRecord.size());
+ for (int i = 0; i < scanResultA.decoded_scanRecord.size(); i++) {
+ byte[] currentAD = scanResultA.decoded_scanRecord.get(i);
+ if (DEBUG) appendToLog("Processing decoded data = " + byteArrayToString(currentAD));
+ if (currentAD[0] == 2) {
+ if (DEBUG) appendToLog("Processing UUIDs");
+ if ((currentAD[1] == 0) && currentAD[2] == (byte) 0x98) {
+ if (DEBUG) appendToLog("Found 9800");
+ found98 = true;
+ check9800_serviceUUID2p1 = currentAD[1];
+ if (DEBUG) appendToLog("serviceUD1D2p1 = " + check9800_serviceUUID2p1);
+ break;
+ }
+ }
+ }
+ if (found98 == false && DEBUG)
+ appendToLog("No 9800: with scanData = " + byteArrayToString(scanResultA.getScanRecord()));
+ else if (DEBUG_SCAN)
+ appendToLog("Cs108Library4A, Found 9800: with scanData = " + byteArrayToString(scanResultA.getScanRecord()));
+ return found98;
+ }
+*/
+ boolean connect1(ReaderDevice readerDevice) {
+ boolean DEBUG = true;
+ if (DEBUG || DEBUG_CONNECT)
+ appendToLog("Debug_Connect, Cs108Library4A.Connect1: with " + (readerDevice == null ? "null" : "valid") + " readerDevice, " + (readerDeviceConnect == null ? "null" : "valid" + "readerDeviceConnect"));
+ if (readerDevice == null && readerDeviceConnect != null) readerDevice = readerDeviceConnect;
+ boolean result = false;
+ if (readerDevice != null) {
+ bNeedReconnect = false;
+ iConnectStateTimer = 0;
+ bluetoothGatt.bDiscoverStarted = false;
+ bluetoothGatt.setServiceUUIDType(readerDevice.getServiceUUID2p1());
+ appendToLog("Cs108Library4A.connect1 is going to connect");
+ result = csReaderConnector.connect(readerDevice);
+ }
+ if (DEBUG || DEBUG_CONNECT) appendToLog("Debug_Connect, Cs108Library4A.connect1: Result = " + result);
+ return result;
+ }
+ final Runnable connectRunnable = new Runnable() {
+ boolean DEBUG = true;
+
+ @Override
+ public void run() {
+ if (DEBUG || DEBUG_CONNECT) {
+ appendToLog("Debug_Connect, Cs108Library4A.connectRunnable: isBleScanning = " + isBleScanning());
+ appendToLog("Debug_Connect, Cs108Library4A.connectRunnable: bNeedReconnect = " + bNeedReconnect);
+ appendToLog("Debug_Connect, Cs108Library4A.connectRunnable: deviceFinderConnectState = " + csReaderConnector.deviceFinder.deviceFinderConnectState);
+ appendToLog("Debug_Connect, Cs108Library4A.connectRunnable: bluetoothConnectionState = " + bluetoothGatt.bluetoothConnectionState) ;
+ }
+ if (isBleScanning()) {
+ if (DEBUG) appendToLog("Cs108Library4A.connectRunnable: still scanning. Stop scanning first");
+ scanLeDevice(false);
+ } else if (bNeedReconnect) {
+ if (bluetoothGatt.bluetoothGatt != null) {
+ if (DEBUG) appendToLog("Cs108Library4A.connectRunnable: mBluetoothGatt is null before connect. disconnect first");
+ csReaderConnector.disconnect();
+ } else if (readerDeviceConnect == null) {
+ if (DEBUG) appendToLog("Cs108Library4A.connectRunnable: exit with null readerDeviceConnect");
+ return;
+ } else if (bluetoothGatt.bluetoothGatt == null) {
+ if (DEBUG || DEBUG_CONNECT) appendToLog("Debug_Connect, Cs108Library4A.connectRunnable: connect1 starts");
+ connect1(null);
+ bNeedReconnect = false;
+ }
+ } else if (csReaderConnector.deviceFinder.deviceFinderConnectState) return;
+ else if (bluetoothGatt.bluetoothConnectionState == BluetoothProfile.STATE_DISCONNECTED) { //mReaderStreamOutCharacteristic valid around 1500ms
+ iConnectStateTimer = 0;
+ if (DEBUG)
+ appendToLog("Cs108Library4A.connectRunnable: disconnect as disconnected connectionState is received");
+ bNeedReconnect = true;
+ //if (true || bluetoothGatt.bluetoothGatt != null) {
+ //if (DEBUG) appendToLog("Cs108Library4A.connectRunnable: disconnect F");
+ csReaderConnector.disconnect();
+ //}
+ } else if (bluetoothGatt.mReaderStreamOutCharacteristic == null) {
+ if (DEBUG_CONNECT)
+ appendToLog("Debug_Connect, Cs108Library4A.connectRunnable: wait as not yet discovery, with iConnectStateTimer = " + iConnectStateTimer);
+ if (++iConnectStateTimer > 10) {
+ }
+ } else {
+ if (DEBUG_CONNECT) appendToLog("Debug_Connect, Cs108Library4A.connectRunnable: end of ConnectRunnable");
+ return;
+ }
+ mHandler.postDelayed(connectRunnable, 500);
+ }
+ };
+ final Runnable disconnectRunnable = new Runnable() {
+ @Override
+ public void run() {
+ if (barcodeConnector == null) return;
+ appendToLog("abcc disconnectRunnable with barcodeToWrite.size = " + barcodeConnector.barcodeToWrite.size());
+ if (barcodeConnector.barcodeToWrite.size() != 0)
+ mHandler.postDelayed(disconnectRunnable, 100);
+ else {
+ appendToLog("disconnect G");
+ csReaderConnector.disconnect();
+ }
+ }
+ };
+ public boolean isBleScanning() {
+ return bluetoothGatt.isScanning();
+ }
+ public boolean scanLeDevice(boolean enable) {
+ boolean DEBUG = true;
+ if (enable) mHandler.removeCallbacks(connectRunnable);
+
+ if (DEBUG || DEBUG_SCAN) appendToLog("Cs108Library.scanLeDevice[" + enable + "]");
+ if (bluetoothGatt.bluetoothDeviceConnectOld != null) {
+ if (DEBUG) appendToLog("Cs108Library.scanLeDevice: bluetoothDeviceConnectOld connection state = " + bluetoothGatt.bluetoothManager.getConnectionState(bluetoothGatt.bluetoothDeviceConnectOld, BluetoothProfile.GATT));
+ }
+ if (enable && csReaderConnector.deviceFinder != null) csReaderConnector.deviceFinder.scanDevice(enable);
+ boolean bValue = bluetoothGatt.scanDevice(enable, csReaderConnector.mLeScanCallback, csReaderConnector.mScanCallback);
+ if (DEBUG || DEBUG_SCAN) appendToLog("Cs108Library.scanLeDevice: isScanning = " + isBleScanning());
+ return bValue;
+ }
+ public BluetoothGatt.CsScanData getNewDeviceScanned() {
+ return csReaderConnector.getNewDeviceScanned();
+/*
+ if (mScanResultList.size() != 0) {
+ if (DEBUG_SCAN) appendToLog("mScanResultList.size() = " + mScanResultList.size());
+ BluetoothGatt.CsScanData csScanData = mScanResultList.get(0); mScanResultList.remove(0);
+ return csScanData;
+ } else return null;
+*/
+ }
+ public String getBluetoothDeviceAddress() {
+ if (bluetoothGatt.getReaderDeviceConnected() == null) return null;
+ return bluetoothGatt.getReaderDeviceConnected().getAddress();
+ }
+ public String getBluetoothDeviceName() {
+ if (bluetoothGatt.getReaderDeviceConnected() == null) return null;
+ return bluetoothGatt.getReaderDeviceConnected().getName();
+ }
+ public boolean isBleConnected() {
+ boolean DEBUG = true;
+ boolean bleConnectionNew = csReaderConnector.isConnected();
+ if (DEBUG) appendToLog("Cs108Library4A.isBleConnected: bleConnectionNew = " + bleConnectionNew);
+ if (bleConnectionNew) {
+ if (bleConnection == false) {
+ bleConnection = bleConnectionNew;
+ if (DEBUG || DEBUG_CONNECT) appendToLog("Debug_Connect, Cs108Library4A.isBleConnected: Newly connected");
+
+ csReaderConnector.csConnectorDataInit();
+ barcodeNewland = csReaderConnector.barcodeNewland;
+ barcodeConnector = csReaderConnector.barcodeConnector;
+ notificationConnector = csReaderConnector.notificationConnector;
+ controllerConnector = csReaderConnector.controllerConnector;
+ bluetoothConnector = csReaderConnector.bluetoothConnector;
+
+ setRfidOn(true);
+ setBarcodeOn(true);
+ hostProcessorICGetFirmwareVersion();
+ getBluetoothICFirmwareVersion();
+ csReaderConnector.rfidReader.channelOrderType = -1;
+ {
+ // getBarcodePreSuffix();
+ // getBarcodeReadingMode();
+ // getBarcodeSerial();
+ //getBarcodeNoDuplicateReading();
+ //getBarcodeDelayTimeOfEachReading();
+ //getBarcodeEnable2dBarCodes();
+ //getBarcodePrefixOrder();
+ //getBarcodeVersion();
+ //barcodeSendCommandLoadUserDefault();
+ //barcodeSendQuerySystem();
+ // barcodeNewland.barcodeSendCommandItf14Cksum();
+
+ notificationConnector.setBatteryAutoReport(true); //0xA003
+ }
+ //abortOperation();
+ //getHostProcessorICSerialNumber(); //0xb004 (but access Oem as bluetooth version is not got)
+ getMacVer();
+ if (false) { //following two instructions seems not used
+ int iValue = csReaderConnector.rfidReader.getDiagnosticConfiguration();
+ if (DEBUG) appendToLog("Cs108Library4A.isBleConnected: diagnostic data = " + iValue);
+ macWrite(0xC08, 0x100);
+ }
+ csReaderConnector.rfidReader.regionCode = null;
+ getModelNumber();
+ getCountryCode();
+ {
+ getFreqModifyCode();
+ csReaderConnector.rfidReader.getSpecialCountryVersion();
+ }
+ //getSerialNumber();
+ getQueryTarget();
+ csReaderConnector.rfidReader.getImpinjExtension();
+ csReaderConnector.rfidReader.getInvAlgoInChip();
+ csReaderConnector.rfidReader.getFreqChannelConfig();
+ if (DEBUG_CONNECT || DEBUG) appendToLog("Debug_Connect, Cs108Library4A.isBleConnected: Start checkVersionRunnable");
+ mHandler.postDelayed(checkVersionRunnable, 500);
+
+ if (csReaderConnector.settingData.strForegroundReader.trim().length() != 0) {
+ csReaderConnector.settingData.strForegroundReader = bluetoothGatt.getReaderDeviceConnected().getAddress();
+ }
+ csReaderConnector.settingData.saveForegroundSetting2File();
+ } else if (csReaderConnector.rfidReader == null) {
+ bleConnection = false;
+ appendToLog("Cs108Library4A.isBleConnnected: csReaderConnector.rfidReader is NULL");
+ } else if (csReaderConnector.rfidReader.bFirmware_reset_before) {
+ csReaderConnector.rfidReader.bFirmware_reset_before = false;
+ mHandler.postDelayed(reinitaliseDataRunnable, 500);
+ }
+ } else if (bleConnection) {
+ barcodeNewland = null; barcodeConnector = null;
+ notificationConnector = null;
+ controllerConnector = null;
+ bluetoothConnector = null;
+ bleConnection = bleConnectionNew;
+ if (DEBUG) appendToLog("Cs108Library4A.isBleConnnected: Newly disconnected");
+ }
+ return(bleConnection);
+ }
+ public void connect(ReaderDevice readerDevice) {
+ if (isBleConnected()) return;
+ if (bluetoothGatt.bluetoothGatt != null) csReaderConnector.disconnect();
+ if (readerDevice != null) readerDeviceConnect = readerDevice;
+ mHandler.removeCallbacks(connectRunnable);
+ bNeedReconnect = true; mHandler.post(connectRunnable);
+ if (true || DEBUG_CONNECT) appendToLog("Debug_Connect: Cs108Library4A.connect Start ConnectRunnable");
+ }
+ public void disconnect(boolean tempDisconnect) {
+ appendToLog("abcc tempDisconnect: getBarcodeOnStatus = " + (getBarcodeOnStatus() ? "on" : "off"));
+ if (DEBUG) appendToLog("tempDisconnect = " + tempDisconnect);
+ mHandler.removeCallbacks(checkVersionRunnable);
+ mHandler.removeCallbacks(runnableToggleConnection);
+ if (getBarcodeOnStatus()) {
+ appendToLog("tempDisconnect: setBarcodeOn(false)");
+ if (barcodeConnector.barcodeToWrite.size() != 0) {
+ appendToLog("going to disconnectRunnable with remaining barcodeToWrite.size = " + barcodeConnector.barcodeToWrite.size() + ", data = " + byteArrayToString(barcodeConnector.barcodeToWrite.get(0).dataValues));
+ }
+ barcodeConnector.barcodeToWrite.clear(); appendToLog("barcodeToWrite is clear");
+ setBarcodeOn(false);
+ setRfidOn(false);
+ } else appendToLog("tempDisconnect: getBarcodeOnStatus is false");
+ mHandler.postDelayed(disconnectRunnable, 100);
+ appendToLog("done with tempDisconnect = " + tempDisconnect);
+ if (tempDisconnect == false) {
+ mHandler.removeCallbacks(connectRunnable);
+ bluetoothGatt.bluetoothDeviceConnectOld = null;
+ if (readerDeviceConnect != null) bluetoothGatt.bluetoothDeviceConnectOld = bluetoothGatt.bluetoothAdapter.getRemoteDevice(readerDeviceConnect.getAddress());
+ readerDeviceConnect = null;
+ }
+ }
+ public boolean forceBTdisconnect() {
+ return bluetoothConnector.forceBTdisconnect();
+ }
+ public int getRssi() {
+ return bluetoothGatt.getRssi();
+ }
+ boolean getConnectionHSpeed() {
+ return bluetoothGatt.getConnectionHSpeedA();
+ }
+ boolean setConnectionHSpeed(boolean on) {
+ return bluetoothGatt.setConnectionHSpeedA(on);
+ }
+ public long getStreamInRate() {
+ return csReaderConnector.getStreamInRate();
+ }
+ public int get98XX() {
+ return 0;
+ }
+
+ //============ Rfid ============
+ //============ Rfid ============
+ //============ Rfid ============
+
+ boolean setInvAlgoNoSave(boolean dynamicAlgo) {
+ return csReaderConnector.rfidReader.setInvAlgoNoSave(dynamicAlgo);
+ }
+ boolean setInvAlgo1(boolean dynamicAlgo) {
+ return csReaderConnector.rfidReader.setInvAlgo1(dynamicAlgo);
+ }
+ public String getAuthMatchData() {
+ return csReaderConnector.rfidReader.getAuthMatchData();
+ }
+ public boolean setAuthMatchData(String mask) {
+ return csReaderConnector.rfidReader.setAuthMatchData(mask);
+ }
+ public int getStartQValue() {
+ return csReaderConnector.rfidReader.getStartQValue();
+ }
+ public int getMaxQValue() {
+ return csReaderConnector.rfidReader.getMaxQValue();
+ }
+ public int getMinQValue() {
+ return csReaderConnector.rfidReader.getMinQValue();
+ }
+ public boolean setDynamicQParms(int startQValue, int minQValue, int maxQValue, int retryCount) {
+ return csReaderConnector.rfidReader.setDynamicQParms(startQValue, minQValue, maxQValue, retryCount);
+ }
+ public int getFixedQValue() {
+ return csReaderConnector.rfidReader.getFixedQValue();
+ }
+ public int getFixedRetryCount() {
+ return csReaderConnector.rfidReader.getFixedRetryCount();
+ }
+ public boolean getRepeatUnitNoTags() {
+ return csReaderConnector.rfidReader.getRepeatUnitNoTags();
+ }
+ public boolean setFixedQParms(int qValue, int retryCount, boolean repeatUnitNoTags) {
+ return csReaderConnector.rfidReader.setFixedQParms(qValue, retryCount, repeatUnitNoTags);
+ }
+ RegionCodes[] getRegionList() {
+ return csReaderConnector.rfidReader.getRegionList();
+ }
+ boolean toggledConnection = false;
+ Runnable runnableToggleConnection = new Runnable() {
+ boolean DEBUG = true;
+ @Override
+ public void run() {
+ if (DEBUG) appendToLog("Cs108Library4A.runnableToggleConnection: toggledConnection = " + toggledConnection + ", isBleConnected() = " + isBleConnected());
+ if (isBleConnected() == false) toggledConnection = true;
+ if (toggledConnection) {
+ if (isBleConnected() == false) {
+ if (connect1(null) == false) return;
+ } else return;
+ } else { appendToLog("Cs108Library4A.runnableToggleConnection: disconnect H"); csReaderConnector.disconnect(); appendToLog("done"); }
+ mHandler.postDelayed(runnableToggleConnection, 500);
+ }
+ };
+ public boolean getChannelHoppingDefault() {
+ return csReaderConnector.rfidReader.getChannelHoppingDefault();
+ }
+ int getCountryCode() {
+ return csReaderConnector.rfidReader.getCountryCode();
+ }
+ int getFreqModifyCode() {
+ return csReaderConnector.rfidReader.getFreqModifyCode();
+ }
+ public boolean getRfidOnStatus() {
+ return csReaderConnector.rfidReader.getRfidOnStatus();
+ }
+ public boolean isRfidFailure() {
+ //appendToLog("BtDataOut: isRfidFailure rfidReader is " + (csReaderConnector.rfidReader == null ? "null" : csReaderConnector.rfidReader.isRfidFailure()));
+ if (csReaderConnector.rfidReader == null) return false;
+ return csReaderConnector.rfidReader.isRfidFailure();
+ }
+ public void setReaderDefault() {
+ csReaderConnector.rfidReader.setReaderDefault();
+ String string = bluetoothGatt.getReaderDeviceConnected().getAddress();
+ string = string.replaceAll("[^a-zA-Z0-9]","");
+ string = string.substring(string.length()-6, string.length());
+ setBluetoothICFirmwareName("CS108Reader" + string);
+ //getlibraryVersion()
+ if (false) {
+ setCountryInList(csReaderConnector.rfidReader.countryInListDefault);
+ setChannel(0);
+
+ //getAntennaPower(0)
+ //getPopulation()
+ //getQuerySession()
+ //getQueryTarget()
+ setTagFocus(false);
+ setFastId(false);
+ //getInvAlgo()
+ //\\getRetryCount()
+ //getCurrentProfile() + "\n"));
+ //\\getRxGain() + "\n"));
+ }
+ //getBluetoothICFirmwareName() + "\n");
+ setTagDelay(csReaderConnector.rfidReader.tagDelaySettingDefault);
+ setCycleDelay((long)0);
+ setIntraPkDelay((byte)4);
+ setDupDelay((byte)0);
+
+ setBatteryDisplaySetting(csReaderConnector.settingData.batteryDisplaySelectDefault);
+ setRssiDisplaySetting(csReaderConnector.settingData.rssiDisplaySelectDefault);
+ setTriggerReporting(csReaderConnector.settingData.triggerReportingDefault);
+ setTriggerReportingCount(csReaderConnector.settingData.triggerReportingCountSettingDefault);
+ setInventoryBeep(csReaderConnector.settingData.inventoryBeepDefault);
+ setBeepCount(csReaderConnector.settingData.beepCountSettingDefault);
+ setInventoryVibrate(csReaderConnector.settingData.inventoryVibrateDefault);
+ setVibrateTime(csReaderConnector.settingData.vibrateTimeSettingDefault);
+ setVibrateModeSetting(csReaderConnector.settingData.vibrateModeSelectDefault);
+ setVibrateWindow(csReaderConnector.settingData.vibrateWindowSettingDefault);
+
+ setSavingFormatSetting(csReaderConnector.settingData.savingFormatSelectDefault);
+ setCsvColumnSelectSetting(csReaderConnector.settingData.csvColumnSelectDefault);
+ setSaveFileEnable(csReaderConnector.settingData.saveFileEnableDefault);
+ setSaveCloudEnable(csReaderConnector.settingData.saveCloudEnableDefault);
+ setSaveNewCloudEnable(csReaderConnector.settingData.saveNewCloudEnableDefault);
+ setSaveAllCloudEnable(csReaderConnector.settingData.saveAllCloudEnableDefault);
+ setServerLocation(csReaderConnector.settingData.serverLocationDefault);
+ setServerTimeout(csReaderConnector.settingData.serverTimeoutDefault);
+ csReaderConnector.settingData.barcode2TriggerMode = csReaderConnector.settingData.barcode2TriggerModeDefault;
+
+ setUserDebugEnable(csReaderConnector.settingData.userDebugEnableDefault);
+ csReaderConnector.settingData.preFilterData = null;
+ }
+ public String getMacVer() {
+ appendToLog("Cs108Library4A.getMacVer");
+ return csReaderConnector.rfidReader.getMacVer();
+ }
+ public String getRadioSerial() {
+ return csReaderConnector.rfidReader.getRadioSerial();
+ }
+ public String getRadioBoardVersion() {
+ return csReaderConnector.rfidReader.getRadioBoardVersion();
+ }
+ public int getPortNumber() {
+ if (bluetoothConnector.getCsModel() == 463) return 4;
+ else return 1;
+ }
+ public int getAntennaSelect() {
+ return csReaderConnector.rfidReader.getAntennaSelect();
+ }
+ public boolean setAntennaSelect(int number) {
+ return csReaderConnector.rfidReader.setAntennaSelect(number);
+ }
+ public boolean getAntennaEnable() {
+ return csReaderConnector.rfidReader.getAntennaEnable();
+ }
+ public boolean setAntennaEnable(boolean enable) {
+ return csReaderConnector.rfidReader.setAntennaEnable(enable);
+ }
+ public long getAntennaDwell() {
+ return csReaderConnector.rfidReader.getAntennaDwell();
+ }
+ public boolean setAntennaDwell(long antennaDwell) {
+ return csReaderConnector.rfidReader.setAntennaDwell(antennaDwell);
+ }
+ public long getPwrlevel() {
+ return csReaderConnector.rfidReader.getPwrlevel();
+ }
+ public boolean setPowerLevel(long pwrlevel) {
+ return csReaderConnector.rfidReader.setPowerLevel(pwrlevel);
+ }
+ public int getQueryTarget() {
+ return csReaderConnector.rfidReader.getQueryTarget();
+ }
+ public int getQuerySession() {
+ return csReaderConnector.rfidReader.getQuerySession();
+ }
+ public int getQuerySelect() {
+ return csReaderConnector.rfidReader.getQuerySelect();
+ }
+ public boolean setTagGroup(int sL, int session, int target1) {
+ return csReaderConnector.rfidReader.setTagGroup(sL, session, target1);
+ }
+ public int getTagFocus() {
+ return csReaderConnector.rfidReader.getTagFocus();
+ }
+ public boolean setTagFocus(boolean tagFocusNew) {
+ return csReaderConnector.rfidReader.setTagFocus(tagFocusNew);
+ }
+ public int getFastId() {
+ return csReaderConnector.rfidReader.getFastId();
+ }
+ public boolean setFastId(boolean fastIdNew) {
+ appendToLog("bFastId: setFastId[" + fastIdNew);
+ return csReaderConnector.rfidReader.setFastId(fastIdNew);
+ }
+ public boolean getInvAlgo() {
+ return csReaderConnector.rfidReader.getInvAlgo();
+ }
+ public boolean setInvAlgo(boolean dynamicAlgo) {
+ return csReaderConnector.rfidReader.setInvAlgo(dynamicAlgo);
+ }
+ public List getProfileList() {
+ return csReaderConnector.rfidReader.getProfileList();
+ }
+ public int getCurrentProfile() {
+ return csReaderConnector.rfidReader.getCurrentProfile();
+ }
+ public boolean setBasicCurrentLinkProfile() {
+ return csReaderConnector.rfidReader.setBasicCurrentLinkProfile();
+ }
+ public boolean setCurrentLinkProfile(int profile) {
+ return csReaderConnector.rfidReader.setCurrentLinkProfile(profile);
+ }
+ public void resetEnvironmentalRSSI() {
+ csReaderConnector.rfidReader.resetEnvironmentalRSSI();
+ }
+ public String getEnvironmentalRSSI() {
+ return csReaderConnector.rfidReader.getEnvironmentalRSSI();
+ }
+ public int getHighCompression() {
+ return csReaderConnector.rfidReader.getHighCompression();
+ }
+ public int getRflnaGain() {
+ return csReaderConnector.rfidReader.getRflnaGain();
+ }
+ public int getIflnaGain() {
+ return csReaderConnector.rfidReader.getIflnaGain();
+ }
+ public int getAgcGain() {
+ return csReaderConnector.rfidReader.getAgcGain();
+ }
+ public int getRxGain() {
+ return csReaderConnector.rfidReader.getRxGain();
+ }
+ public boolean setRxGain(int highCompression, int rflnagain, int iflnagain, int agcgain) {
+ return csReaderConnector.rfidReader.setRxGain(highCompression, rflnagain, iflnagain, agcgain);
+ }
+ public boolean setRxGain(int rxGain) {
+ return csReaderConnector.rfidReader.setRxGain(rxGain);
+ }
+ public int FreqChnCnt() {
+ return csReaderConnector.rfidReader.FreqChnCnt(csReaderConnector.rfidReader.regionCode);
+ }
+ public double getLogicalChannel2PhysicalFreq(int channel) {
+ return csReaderConnector.rfidReader.getLogicalChannel2PhysicalFreq(channel);
+ }
+ public byte getTagDelay() {
+ return csReaderConnector.rfidReader.getTagDelay();
+ }
+ public boolean setTagDelay(byte tagDelay) {
+ return csReaderConnector.rfidReader.setTagDelay(tagDelay);
+ }
+ public byte getIntraPkDelay() {
+ return csReaderConnector.rfidReader.getIntraPkDelay();
+ }
+ public boolean setIntraPkDelay(byte intraPkDelay) {
+ return csReaderConnector.rfidReader.setIntraPkDelay(intraPkDelay);
+ }
+ public byte getDupDelay() {
+ return csReaderConnector.rfidReader.getDupDelay();
+ }
+ public boolean setDupDelay(byte dupElim) {
+ return csReaderConnector.rfidReader.setDupDelay(dupElim);
+ }
+ public long getCycleDelay() {
+ return csReaderConnector.rfidReader.getCycleDelay();
+ }
+ public boolean setCycleDelay(long cycleDelay) {
+ return csReaderConnector.rfidReader.setCycleDelay(cycleDelay);
+ }
+ public void getAuthenticateReplyLength() {
+ csReaderConnector.rfidReader.getAuthenticateReplyLength();
+ }
+ public boolean setTamConfiguration(boolean header, String matchData) {
+ return csReaderConnector.rfidReader.setTamConfiguration(header, matchData);
+ }
+ public boolean setTam1Configuration(int keyId, String matchData) {
+ return csReaderConnector.rfidReader.setTam1Configuration(keyId, matchData);
+ }
+ public boolean setTam2Configuration(int keyId, String matchData, int profile, int offset, int blockId, int protMode) {
+ return csReaderConnector.rfidReader.setTam2Configuration(keyId, matchData, profile, offset, blockId, protMode);
+ }
+ public int getUntraceableEpcLength() {
+ return csReaderConnector.rfidReader.getUntraceableEpcLength();
+ }
+ public boolean setUntraceable(boolean bHideEpc, int ishowEpcSize, int iHideTid, boolean bHideUser, boolean bHideRange) {
+ return csReaderConnector.rfidReader.setUntraceable(bHideEpc, ishowEpcSize, iHideTid, bHideUser, bHideRange);
+ }
+ public boolean setUntraceable(int range, boolean user, int tid, int epcLength, boolean epc, boolean uxpc) {
+ return csReaderConnector.rfidReader.setUntraceable(range, user, tid, epcLength, epc, uxpc);
+ }
+ public boolean setAuthenticateConfiguration() {
+ return csReaderConnector.rfidReader.setAuthenticateConfiguration();
+ }
+ public int getRetryCount() {
+ return csReaderConnector.rfidReader.getRetryCount();
+ }
+ public boolean setRetryCount(int retryCount) {
+ return csReaderConnector.rfidReader.setRetryCount(retryCount);
+ }
+ public int getInvSelectIndex() {
+ return csReaderConnector.rfidReader.getInvSelectIndex();
+ }
+ public boolean getSelectEnable() {
+ return csReaderConnector.rfidReader.getSelectEnable();
+ }
+ public int getSelectTarget() {
+ return csReaderConnector.rfidReader.getSelectTarget();
+ }
+ public int getSelectAction() {
+ return csReaderConnector.rfidReader.getSelectAction();
+ }
+ public int getSelectMaskBank() {
+ return csReaderConnector.rfidReader.getSelectMaskBank();
+ }
+ public int getSelectMaskOffset() {
+ return csReaderConnector.rfidReader.getSelectMaskOffset();
+ }
+ public String getSelectMaskData() {
+ return csReaderConnector.rfidReader.getSelectMaskData();
+ }
+ public boolean setInvSelectIndex(int invSelect) {
+ return csReaderConnector.rfidReader.setInvSelectIndex(invSelect);
+ }
+ public boolean setSelectCriteriaDisable(int index) {
+ if (utility.DEBUG_SELECT) appendToLog("Debug_Select: Cs108Library4A.setSelectCriteriaDisable[" + index + "] goes to setSelectCriteriaDisable");
+ return csReaderConnector.rfidReader.setSelectCriteriaDisable(index);
+ }
+ int findFirstEmptySelect() {
+ return csReaderConnector.rfidReader.findFirstEmptySelect();
+ }
+ public boolean setSelectCriteria(int index, boolean enable, int target, int action, int bank, int offset, String mask, boolean maskbit) {
+ return csReaderConnector.rfidReader.setSelectCriteria(index, enable, target, action, bank, offset, mask, maskbit);
+ }
+ public boolean setSelectCriteria(int index, boolean enable, int target, int action, int delay, int bank, int offset, String mask) {
+ return csReaderConnector.rfidReader.setSelectCriteria(index, enable, target, action, delay, bank, offset, mask);
+ }
+ public boolean getRssiFilterEnable() {
+ return csReaderConnector.rfidReader.getRssiFilterEnable();
+ }
+ public int getRssiFilterType() {
+ return csReaderConnector.rfidReader.getRssiFilterType();
+ }
+ public int getRssiFilterOption() {
+ return csReaderConnector.rfidReader.getRssiFilterOption();
+ }
+ public boolean setRssiFilterConfig(boolean enable, int rssiFilterType, int rssiFilterOption) {
+ return csReaderConnector.rfidReader.setRssiFilterConfig(enable, rssiFilterType, rssiFilterOption);
+ }
+ public double getRssiFilterThreshold1() {
+ return csReaderConnector.rfidReader.getRssiFilterThreshold1();
+ }
+ public double getRssiFilterThreshold2() {
+ return csReaderConnector.rfidReader.getRssiFilterThreshold2();
+ }
+ public boolean setRssiFilterThreshold(double rssiFilterThreshold1, double rssiFilterThreshold2) {
+ return csReaderConnector.rfidReader.setRssiFilterThreshold(rssiFilterThreshold1, rssiFilterThreshold2);
+ }
+ public long getRssiFilterCount() {
+ return csReaderConnector.rfidReader.getRssiFilterCount();
+ }
+ public boolean setRssiFilterCount(long rssiFilterCount) {
+ return csReaderConnector.rfidReader.setRssiFilterCount(rssiFilterCount);
+ }
+ public boolean getInvMatchEnable() {
+ return csReaderConnector.rfidReader.getInvMatchEnable();
+ }
+ public boolean getInvMatchType() {
+ return csReaderConnector.rfidReader.getInvMatchType();
+ }
+ public int getInvMatchOffset() {
+ return csReaderConnector.rfidReader.getInvMatchOffset();
+ }
+ public String getInvMatchData() {
+ return csReaderConnector.rfidReader.getInvMatchData();
+ }
+ public boolean setPostMatchCriteria(boolean enable, boolean target, int offset, String mask) {
+ return csReaderConnector.rfidReader.setPostMatchCriteria(enable, target, offset, mask);
+ }
+ public int mrfidToWriteSize() {
+ if (isBleConnected() == false) return -1;
+ if (csReaderConnector.rfidReader == null) return -1;
+ return csReaderConnector.rfidReader.rfidToWriteSize();
+ }
+ public void mrfidToWritePrint() {
+ if (true) { csReaderConnector.rfidReader.rfidToWriteSize(); return; }
+ for (int i = 0; i < csReaderConnector.rfidReader.mRfidToWrite.size(); i++) {
+ appendToLog(byteArrayToString(csReaderConnector.rfidReader.mRfidToWrite.get(i).dataValues));
+ }
+ }
+ public long getTagRate() {
+ return csReaderConnector.rfidReader.getTagRate();
+ }
+ public boolean startOperation(RfidReaderChipData.OperationTypes operationTypes) {
+ return csReaderConnector.rfidReader.startOperation(operationTypes);
+ }
+ public boolean abortOperation() {
+ return csReaderConnector.rfidReader.abortOperation();
+ }
+ public void restoreAfterTagSelect() {
+ if (!isBleConnected()) return;
+ if (utility.DEBUG_SELECT) appendToLog("Debug_Select: Cs108Library4A.restoreAfterTagSelect goes to setSelectCriteriaDisable");
+ setSelectCriteriaDisable(0); setSelectCriteriaDisable(1); setSelectCriteriaDisable(2);
+ loadSetting1File();
+ setAccessCount(0);
+ setRx000AccessPassword("00000000");
+ if (checkHostProcessorVersion(getMacVer(), 2, 6, 8)) {
+ setMatchRep(0);
+ setTagDelay(csReaderConnector.rfidReader.tagDelaySetting);
+ setCycleDelay(csReaderConnector.rfidReader.cycleDelaySetting);
+ setInvModeCompact(true);
+ }
+ if (csReaderConnector.rfidReader.postMatchDataChanged) {
+ csReaderConnector.rfidReader.postMatchDataChanged = false;
+ setPostMatchCriteria(csReaderConnector.rfidReader.postMatchDataOld.enable, csReaderConnector.rfidReader.postMatchDataOld.target, csReaderConnector.rfidReader.postMatchDataOld.offset, csReaderConnector.rfidReader.postMatchDataOld.mask);
+ appendToLog("PowerLevel");
+ setPowerLevel(csReaderConnector.rfidReader.postMatchDataOld.pwrlevel);
+ appendToLog("writeBleStreamOut: invAlgo = " + csReaderConnector.rfidReader.postMatchDataOld.invAlgo); setInvAlgo1(csReaderConnector.rfidReader.postMatchDataOld.invAlgo);
+ setQValue1(csReaderConnector.rfidReader.postMatchDataOld.qValue);
+ }
+ }
+ public boolean setSelectedTagByTID(String strTagId, long pwrlevel) {
+ return csReaderConnector.rfidReader.setSelectedTagByTID(strTagId, pwrlevel);
+ }
+ public boolean setSelectedTag(String strTagId, int selectBank, long pwrlevel) {
+ return csReaderConnector.rfidReader.setSelectedTag(strTagId, selectBank, pwrlevel);
+ }
+ public boolean setSelectedTag(boolean selectOne, String selectMask, int selectBank, int selectOffset, long pwrlevel, int qValue, int matchRep) {
+ return csReaderConnector.rfidReader.setSelectedTag4Access(selectOne, selectMask, selectBank, selectOffset, pwrlevel, qValue, matchRep);
+ }
+ public boolean setMatchRep(int matchRep) {
+ if (utility.DEBUG_INVCFG) appendToLog("Debug_InvCfg: Cs108Library4A.setMatchRep goes to setMatchRep with matchRep = " + matchRep);
+ return csReaderConnector.rfidReader.setMatchRep(matchRep);
+ }
+ public String[] getCountryList() {
+ return csReaderConnector.rfidReader.getCountryList();
+ }
+ public int getCountryNumberInList() {
+ return csReaderConnector.rfidReader.countryInList;
+ }
+ public boolean setCountryInList(int countryInList) {
+ return csReaderConnector.rfidReader.setCountryInList(countryInList);
+ }
+ public boolean getChannelHoppingStatus() {
+ return csReaderConnector.rfidReader.getChannelHoppingStatus();
+ }
+ public boolean setChannelHoppingStatus(boolean channelOrderHopping) {
+ return csReaderConnector.rfidReader.setChannelHoppingStatus(channelOrderHopping);
+ }
+ public String[] getChannelFrequencyList() {
+ return csReaderConnector.rfidReader.getChannelFrequencyList();
+ }
+ public int getChannel() {
+ return csReaderConnector.settingData.channel;
+ }
+ public boolean setChannel(int channelSelect) {
+ return csReaderConnector.rfidReader.setChannel(channelSelect);
+ }
+ public byte getPopulation2Q(int population) {
+ return csReaderConnector.rfidReader.getPopulation2Q(population);
+ }
+ public int getPopulation() {
+ return csReaderConnector.rfidReader.getPopulation();
+ }
+ public boolean setPopulation(int population) {
+ return csReaderConnector.rfidReader.setPopulation(population);
+ }
+ public byte getQValue() {
+ return csReaderConnector.rfidReader.qValueSetting;
+ }
+ public boolean setQValue(byte byteValue) {
+ return csReaderConnector.rfidReader.setQValue(byteValue);
+ }
+ int getQValue1() {
+ return csReaderConnector.rfidReader.getQValue();
+ }
+ boolean setQValue1(int iValue) {
+ return csReaderConnector.rfidReader.setQValue1(iValue);
+ }
+ public RfidReaderChipData.Rx000pkgData onRFIDEvent() {
+ return csReaderConnector.rfidReader.onRFIDEvent();
+ }
+ public String getModelNumber() {
+ return csReaderConnector.rfidReader.getModelNumber(getModelName());
+ }
+ public boolean setRx000KillPassword(String password) {
+ return csReaderConnector.rfidReader.setRx000KillPassword(password);
+ }
+ public boolean setRx000AccessPassword(String password) {
+ return csReaderConnector.rfidReader.setRx000AccessPassword(password);
+ }
+ public boolean setAccessRetry(boolean accessVerfiy, int accessRetry) {
+ return csReaderConnector.rfidReader.setAccessRetry(accessVerfiy, accessRetry);
+ }
+ public boolean setInvModeCompact(boolean invModeCompact) {
+ if (utility.DEBUG_COMPACT) appendToLog("Debug_Compact: Cs108Library4A.setInvModeCompact goes to setInvModeCompact");
+ return csReaderConnector.rfidReader.setInvModeCompact(invModeCompact);
+ }
+ public boolean setAccessLockAction(int accessLockAction, int accessLockMask) {
+ return csReaderConnector.rfidReader.setAccessLockAction(accessLockAction, accessLockMask);
+ }
+ public boolean setAccessBank(int accessBank) {
+ return csReaderConnector.rfidReader.setAccessBank(accessBank);
+ }
+ public boolean setAccessBank(int accessBank, int accessBank2) {
+ return csReaderConnector.rfidReader.setAccessBank(accessBank, accessBank2);
+ }
+ public boolean setAccessOffset(int accessOffset) {
+ return csReaderConnector.rfidReader.setAccessOffset(accessOffset);
+ }
+ public boolean setAccessOffset(int accessOffset, int accessOffset2) {
+ return csReaderConnector.rfidReader.setAccessOffset(accessOffset, accessOffset2);
+ }
+ public boolean setAccessCount(int accessCount) {
+ return csReaderConnector.rfidReader.setAccessCount(accessCount);
+ }
+ public boolean setAccessCount(int accessCount, int accessCount2) {
+ return csReaderConnector.rfidReader.setAccessCount(accessCount, accessCount2);
+ }
+ public boolean setAccessWriteData(String dataInput) {
+ return csReaderConnector.rfidReader.setAccessWriteData(dataInput);
+ }
+ public boolean setResReadNoReply(boolean resReadNoReply) {
+ return false;
+ }
+ public boolean setTagRead(int tagRead) {
+ return csReaderConnector.rfidReader.setTagRead(tagRead);
+ }
+ public boolean setInvBrandId(boolean invBrandId) {
+ return csReaderConnector.rfidReader.setInvBrandId(invBrandId);
+ }
+ public boolean setInvAuthenticate(boolean invAuthenticate) {
+ return csReaderConnector.rfidReader.setInvAuthenticate(invAuthenticate);
+ }
+ public boolean sendHostRegRequestHST_CMD(RfidReaderChipData.HostCommands hostCommand) {
+ if (checkHostProcessorVersion(getMacVer(), 2, 6, 8)) setInvModeCompact(false);
+ return csReaderConnector.rfidReader.sendHostRegRequestHST_CMD(hostCommand);
+ }
+ public boolean setPwrManagementMode(boolean bLowPowerStandby) {
+ if (isBleConnected() == false) return false;
+ return csReaderConnector.rfidReader.setPwrManagementMode(bLowPowerStandby);
+ }
+ public void macWrite(int address, long value) {
+ csReaderConnector.rfidReader.macWrite(address, value);
+ }
+ public void set_fdCmdCfg(int value) {
+ csReaderConnector.rfidReader.set_fdRegAddr(value);
+ }
+ public void set_fdRegAddr(int addr) {
+ csReaderConnector.rfidReader.set_fdRegAddr(addr);
+ }
+ public void set_fdWrite(int addr, long value) {
+ csReaderConnector.rfidReader.set_fdWrite(addr, value);
+ }
+ public void set_fdPwd(int value) {
+ csReaderConnector.rfidReader.set_fdPwd(value);
+ }
+ public void set_fdBlockAddr4GetTemperature(int addr) {
+ csReaderConnector.rfidReader.set_fdBlockAddr4GetTemperature(addr);
+ }
+ public void set_fdReadMem(int addr, long len) {
+ csReaderConnector.rfidReader.set_fdReadMem(addr, len);
+ }
+ public void set_fdWriteMem(int addr, int len, long value) {
+ csReaderConnector.rfidReader.set_fdWriteMem(addr, len, value);
+ }
+ public void setImpinJExtension(boolean tagFocus, boolean fastId) {
+ csReaderConnector.rfidReader.setImpinJExtension(tagFocus, fastId);
+ }
+
+ //============ Barcode ============
+ public void getBarcodePreSuffix() {
+ barcodeNewland.getBarcodePreSuffix();
+ }
+ public void getBarcodeReadingMode() {
+ barcodeNewland.barcodeSendQueryReadingMode();
+ }
+ void getBarcodeEnable2dBarCodes() {
+ barcodeNewland.barcodeSendQueryEnable2dBarCodes();
+ }
+ void getBarcodePrefixOrder() {
+ barcodeNewland.barcodeSendQueryPrefixOrder();
+ }
+ void getBarcodeDelayTimeOfEachReading() {
+ barcodeNewland.barcodeSendQueryDelayTimeOfEachReading();
+ }
+ void getBarcodeNoDuplicateReading() {
+ barcodeNewland.barcodeSendQueryNoDuplicateReading();
+ }
+
+ public boolean isBarcodeFailure() {
+ if (barcodeConnector == null) return false;
+ return barcodeConnector.barcodeFailure;
+ }
+ public String getBarcodeDate() {
+ return barcodeNewland.getBarcodeDate();
+ }
+ public boolean getBarcodeOnStatus() {
+ if (barcodeConnector == null) return false;
+ return barcodeConnector.getOnStatus();
+ }
+ public boolean setBarcodeOn(boolean on) {
+ boolean retValue;
+ BarcodeConnector.CsReaderBarcodeData csReaderBarcodeData = new BarcodeConnector.CsReaderBarcodeData();
+ if (on) csReaderBarcodeData.barcodePayloadEvent = BarcodeConnector.BarcodePayloadEvents.BARCODE_POWER_ON;
+ else csReaderBarcodeData.barcodePayloadEvent = BarcodeConnector.BarcodePayloadEvents.BARCODE_POWER_OFF;
+ csReaderBarcodeData.waitUplinkResponse = false;
+ retValue = barcodeConnector.barcodeToWrite.add(csReaderBarcodeData); appendToLog("barcodeToWrite added with size = " + barcodeConnector.barcodeToWrite.size());
+ if (DEBUG_FILE) appendToLog("add " + csReaderBarcodeData.barcodePayloadEvent.toString() + " to barcodeToWrite with length = " + barcodeConnector.barcodeToWrite.size());
+ boolean continuousAfterOn = false;
+ if (retValue && on && continuousAfterOn) {
+ if (checkHostProcessorVersion(getBluetoothICFirmwareVersion(), 1, 0, 2)) {
+ if (DEBUG) appendToLog("to barcodeSendCommandConinuous()");
+ retValue = barcodeNewland.barcodeSendCommandConinuous();
+ } else retValue = false;
+ }
+ if (DEBUG) appendToLog("barcodeToWrite size = " + barcodeConnector.barcodeToWrite.size());
+ return retValue;
+ }
+ int iModeSet = -1, iVibratieTimeSet = -1;
+ public boolean setVibrateOn(int mode) {
+ boolean retValue;
+ if (true) appendToLog("setVibrateOn with mode = " + mode + ", and isInventoring = " + csReaderConnector.rfidReader.isInventoring());
+ if (csReaderConnector.rfidReader.isInventoring()) return false;
+ BarcodeConnector.CsReaderBarcodeData csReaderBarcodeData = new BarcodeConnector.CsReaderBarcodeData();
+ if (mode > 0) csReaderBarcodeData.barcodePayloadEvent = BarcodeConnector.BarcodePayloadEvents.BARCODE_VIBRATE_ON;
+ else csReaderBarcodeData.barcodePayloadEvent = BarcodeConnector.BarcodePayloadEvents.BARCODE_VIBRATE_OFF;
+ csReaderBarcodeData.waitUplinkResponse = false;
+ if (iModeSet == mode && iVibratieTimeSet == getVibrateTime()) {
+ appendToLog("writeBleStreamOut: A7B3: Skip saving vibration data");
+ return true;
+ }
+ if (mode > 0) {
+ byte[] barcodeCommandData = new byte[3];
+ barcodeCommandData[0] = (byte) (mode - 1);
+ barcodeCommandData[1] = (byte) (getVibrateTime() / 256);
+ barcodeCommandData[2] = (byte) (getVibrateTime() % 256);
+ csReaderBarcodeData.dataValues = barcodeCommandData;
+ }
+ retValue = barcodeConnector.barcodeToWrite.add(csReaderBarcodeData); appendToLog("barcodeToWrite added with size = " + barcodeConnector.barcodeToWrite.size());
+ if (DEBUG) appendToLog("barcodeToWrite size = " + barcodeConnector.barcodeToWrite.size());
+ if (retValue) {
+ iModeSet = mode; iVibratieTimeSet = getVibrateTime();
+ }
+ return retValue;
+ }
+ public boolean getInventoryVibrate() {
+ return csReaderConnector.settingData.inventoryVibrate;
+ }
+ public boolean setInventoryVibrate(boolean inventoryVibrate) {
+ boolean DEBUG = false;
+ if (DEBUG) appendToLog("this.inventoryVibrate = " + csReaderConnector.settingData.inventoryVibrate + ", inventoryVibrate = " + inventoryVibrate);
+ csReaderConnector.settingData.inventoryVibrate = inventoryVibrate;
+ if (DEBUG) appendToLog("this.inventoryVibrate = " + csReaderConnector.settingData.inventoryVibrate + ", inventoryVibrate = " + inventoryVibrate);
+ return true;
+ }
+ public int getVibrateTime() {
+ return csReaderConnector.settingData.vibrateTimeSetting;
+ }
+ public boolean setVibrateTime(int vibrateTime) {
+ csReaderConnector.settingData.vibrateTimeSetting = vibrateTime;
+ return true;
+ }
+ public int getVibrateWindow() {
+ return csReaderConnector.settingData.vibrateWindowSetting;
+ }
+ public boolean setVibrateWindow(int vibrateWindow) {
+ csReaderConnector.settingData.vibrateWindowSetting = vibrateWindow;
+ return true;
+ }
+ public boolean barcodeSendCommandTrigger() {
+ return barcodeNewland.barcodeSendCommandTrigger();
+ }
+ public boolean barcodeSendCommandSetPreSuffix() {
+ return barcodeNewland.barcodeSendCommandSetPreSuffix();
+ }
+ public boolean barcodeSendCommandResetPreSuffix() {
+ return barcodeNewland.barcodeSendCommandResetPreSuffix();
+ }
+ public boolean barcodeSendCommandConinuous() {
+ return barcodeNewland.barcodeSendCommandConinuous();
+ }
+ public String getBarcodeVersion() {
+ return barcodeNewland.getBarcodeVersion();
+ }
+ public String getBarcodeSerial() {
+ return barcodeNewland.getBarcodeSerial();
+ }
+ boolean barcodeAutoStarted = false;
+ public boolean barcodeInventory(boolean start) {
+ boolean result = true;
+ appendToLog("TTestPoint 0: " + start);
+ if (start) {
+ barcodeConnector.mBarcodeToRead.clear(); barcodeDataStore = null;
+ if (getBarcodeOnStatus() == false) { result = setBarcodeOn(true); appendToLog("TTestPoint 1"); }
+ if (csReaderConnector.settingData.barcode2TriggerMode && result) {
+ if (getTriggerButtonStatus() && notificationConnector.getAutoBarStartSTop()) { appendToLog("TTestPoint 2"); barcodeAutoStarted = true; result = true; }
+ else { appendToLog("TTestPoint 3"); result = barcodeNewland.barcodeSendCommand(new byte[]{0x1b, 0x33}); }
+ } else appendToLog("TTestPoint 4");
+ appendToLog("TTestPoint 5");
+ } else {
+ appendToLog("getBarcodeOnStatus = " + getBarcodeOnStatus() + ", result = " + result);
+ if (csReaderConnector.settingData.barcode2TriggerMode == false) { appendToLog("TTestPoint 6"); result = setBarcodeOn(false); }
+ else if (getBarcodeOnStatus() == false && result) { appendToLog("TTestPoint 7"); result = setBarcodeOn(true); }
+ appendToLog("barcode2TriggerMode = " + csReaderConnector.settingData.barcode2TriggerMode + ", result = " + result + ", barcodeAutoStarted = " + barcodeAutoStarted);
+ if (csReaderConnector.settingData.barcode2TriggerMode && result) {
+ if (barcodeAutoStarted && result) { appendToLog("TTestPoint 8"); barcodeAutoStarted = false; result = true; }
+ else { appendToLog("TTestPoint 9"); result = barcodeNewland.barcodeSendCommand(new byte[] { 0x1b, 0x30 }); }
+ } else appendToLog("TTestPoint 10");
+ }
+ return result;
+ }
+ byte[] barcodeDataStore = null; long timeBarcodeData;
+ public byte[] onBarcodeEvent() {
+ byte[] barcodeData = null;
+ if (barcodeConnector.mBarcodeToRead.size() != 0) {
+ BarcodeConnector.CsReaderBarcodeData csReaderBarcodeData = barcodeConnector.mBarcodeToRead.get(0);
+ barcodeConnector.mBarcodeToRead.remove(0);
+ if (csReaderBarcodeData != null) {
+ if (csReaderBarcodeData.barcodePayloadEvent == BarcodeConnector.BarcodePayloadEvents.BARCODE_GOOD_READ) {
+ if (false) barcodeData = "".getBytes();
+ } else if (csReaderBarcodeData.barcodePayloadEvent == BarcodeConnector.BarcodePayloadEvents.BARCODE_DATA_READ) {
+ barcodeData = csReaderBarcodeData.dataValues;
+ }
+ }
+ }
+
+ byte[] barcodeCombined = null;
+ if (false) barcodeCombined = barcodeData;
+ else if (barcodeData != null) {
+ appendToLog("BarStream: barcodeData = " + byteArrayToString(barcodeData) + ", barcodeDataStore = " + byteArrayToString(barcodeDataStore));
+ int barcodeDataStoreIndex = 0;
+ int length = barcodeData.length;
+ if (barcodeDataStore != null) {
+ barcodeDataStoreIndex = barcodeDataStore.length;
+ length += barcodeDataStoreIndex;
+ }
+ barcodeCombined = new byte[length];
+ if (barcodeDataStore != null)
+ System.arraycopy(barcodeDataStore, 0, barcodeCombined, 0, barcodeDataStore.length);
+ System.arraycopy(barcodeData, 0, barcodeCombined, barcodeDataStoreIndex, barcodeData.length);
+ barcodeDataStore = barcodeCombined;
+ timeBarcodeData = System.currentTimeMillis();
+ barcodeCombined = new byte[0];
+ }
+ if (barcodeDataStore != null) {
+ barcodeCombined = new byte[barcodeDataStore.length];
+ System.arraycopy(barcodeDataStore, 0, barcodeCombined, 0, barcodeCombined.length);
+
+ if (System.currentTimeMillis() - timeBarcodeData < 300) barcodeCombined = null;
+ else barcodeDataStore = null;
+ }
+ if (barcodeCombined != null && barcodeNewland.getPrefix() != null && barcodeNewland.getSuffix() != null) {
+ if (barcodeCombined.length == 0) barcodeCombined = null;
+ else {
+ byte[] prefixExpected = barcodeNewland.getPrefix(); boolean prefixFound = false;
+ byte[] suffixExpected = barcodeNewland.getSuffix(); boolean suffixFound = false;
+ int codeTypeLength = 4;
+ appendToLog("BarStream: barcodeCombined = " + byteArrayToString(barcodeCombined) + ", Expected Prefix = " + byteArrayToString(prefixExpected) + ", Expected Suffix = " + byteArrayToString(suffixExpected));
+ if (barcodeCombined.length > prefixExpected.length + suffixExpected.length + codeTypeLength) {
+ int i = 0;
+ for (; i <= barcodeCombined.length - prefixExpected.length - suffixExpected.length; i++) {
+ int j = 0;
+ for (; j < prefixExpected.length; j++) {
+ if (barcodeCombined[i+j] != prefixExpected[j]) break;
+ }
+ if (j == prefixExpected.length) { prefixFound = true; break; }
+ }
+ int k = i + prefixExpected.length;
+ for (; k <= barcodeCombined.length - suffixExpected.length; k++) {
+ int j = 0;
+ for (; j < suffixExpected.length; j++) {
+ if (barcodeCombined[k+j] != suffixExpected[j]) break;
+ }
+ if (j == suffixExpected.length) { suffixFound = true; break; }
+ }
+ appendToLog("BarStream: iPrefix = " + i + ", iSuffix = " + k + ", with prefixFound = " + prefixFound + ", suffixFound = " + suffixFound);
+ if (prefixFound && suffixFound) {
+ byte[] barcodeCombinedNew = new byte[k - i - prefixExpected.length - codeTypeLength];
+ System.arraycopy(barcodeCombined, i + prefixExpected.length + codeTypeLength, barcodeCombinedNew, 0, barcodeCombinedNew.length);
+ barcodeCombined = barcodeCombinedNew;
+ appendToLog("BarStream: barcodeCombinedNew = " + byteArrayToString(barcodeCombinedNew));
+
+ if (true) {
+ byte[] prefixExpected1 = {0x5B, 0x29, 0x3E, 0x1E};
+ prefixFound = false;
+ byte[] suffixExpected1 = {0x1E, 0x04};
+ suffixFound = false;
+ appendToLog("BarStream: barcodeCombined = " + byteArrayToString(barcodeCombined) + ", Expected Prefix = " + byteArrayToString(prefixExpected1) + ", Expected Suffix = " + byteArrayToString(suffixExpected1));
+ if (barcodeCombined.length > prefixExpected1.length + suffixExpected1.length) {
+ i = 0;
+ for (; i <= barcodeCombined.length - prefixExpected1.length - suffixExpected1.length; i++) {
+ int j = 0;
+ for (; j < prefixExpected1.length; j++) {
+ if (barcodeCombined[i + j] != prefixExpected1[j]) break;
+ }
+ if (j == prefixExpected1.length) {
+ prefixFound = true;
+ break;
+ }
+ }
+ k = i + prefixExpected1.length;
+ for (; k <= barcodeCombined.length - suffixExpected1.length; k++) {
+ int j = 0;
+ for (; j < suffixExpected1.length; j++) {
+ if (barcodeCombined[k + j] != suffixExpected1[j]) break;
+ }
+ if (j == suffixExpected1.length) {
+ suffixFound = true;
+ break;
+ }
+ }
+ appendToLog("BarStream: iPrefix = " + i + ", iSuffix = " + k + ", with prefixFound = " + prefixFound + ", suffixFound = " + suffixFound);
+ if (prefixFound && suffixFound) {
+ barcodeCombinedNew = new byte[k - i - prefixExpected1.length];
+ System.arraycopy(barcodeCombined, i + prefixExpected1.length, barcodeCombinedNew, 0, barcodeCombinedNew.length);
+ barcodeCombined = barcodeCombinedNew;
+ appendToLog("BarStream: barcodeCombinedNew = " + byteArrayToString(barcodeCombinedNew));
+ }
+ }
+ }
+ }
+ } else barcodeCombined = null;
+ }
+ }
+ return barcodeCombined;
+ }
+
+ //============ Android General ============
+ public void setSameCheck(boolean sameCheck1) {
+ if (csReaderConnector.sameCheck == sameCheck1) return;
+ if (false) appendToLog("new sameCheck = " + sameCheck1 + ", with old sameCheck = " + csReaderConnector.sameCheck);
+ csReaderConnector.sameCheck = sameCheck1; //sameCheck = false;
+ }
+
+ public int getBeepCount() {
+ return csReaderConnector.settingData.beepCountSetting;
+ }
+ public boolean setBeepCount(int beepCount) {
+ csReaderConnector.settingData.beepCountSetting = beepCount;
+ return true;
+ }
+
+ public boolean getInventoryBeep() {
+ return csReaderConnector.settingData.inventoryBeep;
+ }
+ public boolean setInventoryBeep(boolean inventoryBeep) {
+ csReaderConnector.settingData.inventoryBeep = inventoryBeep;
+ return true;
+ }
+
+ public boolean getSaveFileEnable() {
+ return csReaderConnector.settingData.saveFileEnable;
+ }
+ public boolean setSaveFileEnable(boolean saveFileEnable) {
+ appendToLog("this.saveFileEnable = " + csReaderConnector.settingData.saveFileEnable + ", saveFileEnable = " + saveFileEnable);
+ csReaderConnector.settingData.saveFileEnable = saveFileEnable;
+ appendToLog("this.saveFileEnable = " + csReaderConnector.settingData.saveFileEnable + ", saveFileEnable = " + saveFileEnable);
+ return true;
+ }
+ public boolean getSaveCloudEnable() {
+ return csReaderConnector.settingData.saveCloudEnable;
+ }
+ public boolean setSaveCloudEnable(boolean saveCloudEnable) {
+ csReaderConnector.settingData.saveCloudEnable = saveCloudEnable;
+ return true;
+ }
+ public boolean getSaveNewCloudEnable() {
+ return csReaderConnector.settingData.saveNewCloudEnable;
+ }
+ public boolean setSaveNewCloudEnable(boolean saveNewCloudEnable) {
+ csReaderConnector.settingData.saveNewCloudEnable = saveNewCloudEnable;
+ return true;
+ }
+ public boolean getSaveAllCloudEnable() {
+ return csReaderConnector.settingData.saveAllCloudEnable;
+ }
+ public boolean setSaveAllCloudEnable(boolean saveAllCloudEnable) {
+ csReaderConnector.settingData.saveAllCloudEnable = saveAllCloudEnable;
+ return true;
+ }
+ public boolean getUserDebugEnable() {
+ boolean bValue = csReaderConnector.settingData.userDebugEnable; appendToLog("bValue = " + bValue); return bValue;
+ }
+ public boolean setUserDebugEnable(boolean userDebugEnable) {
+ appendToLog("new userDebug = " + userDebugEnable);
+ csReaderConnector.settingData.userDebugEnable = userDebugEnable;
+ return true;
+ }
+ public String getForegroundReader() {
+ return csReaderConnector.settingData.strForegroundReader;
+ }
+ public boolean getForegroundServiceEnable() {
+ String string = csReaderConnector.settingData.strForegroundReader;
+ return (string.trim().length() == 0 ? false : true);
+ }
+ public boolean setForegroundServiceEnable(boolean bForegroundService) {
+ if (bForegroundService) csReaderConnector.settingData.strForegroundReader = csReaderConnector.bluetoothGatt.getReaderDeviceConnected().getAddress();
+ else csReaderConnector.settingData.strForegroundReader = "";
+ return true;
+ }
+ public String getServerLocation() {
+ return csReaderConnector.settingData.serverLocation;
+ }
+ public boolean setServerLocation(String serverLocation) {
+ csReaderConnector.settingData.serverLocation = serverLocation;
+ return true;
+ }
+ public int getServerTimeout() {
+ return csReaderConnector.settingData.serverTimeout;
+ }
+ public boolean setServerTimeout(int serverTimeout) {
+ csReaderConnector.settingData.serverTimeout = serverTimeout;
+ return true;
+ }
+ public String getServerMqttLocation() {
+ return csReaderConnector.settingData.serverMqttLocation;
+ }
+ public boolean setServerMqttLocation(String serverLocation) {
+ csReaderConnector.settingData.serverMqttLocation = serverLocation;
+ return true;
+ }
+ public String getTopicMqtt() {
+ return csReaderConnector.settingData.topicMqtt;
+ }
+ public boolean setTopicMqtt(String topicMqtt) {
+ csReaderConnector.settingData.topicMqtt = topicMqtt;
+ return true;
+ }
+ public int getForegroundDupElim() {
+ return csReaderConnector.settingData.iForegroundDupElim;
+ }
+ public boolean setForegroundDupElim(int iForegroundDupElim) {
+ csReaderConnector.settingData.iForegroundDupElim = iForegroundDupElim;
+ return true;
+ }
+ public int getInventoryCloudSave() {
+ return csReaderConnector.settingData.inventoryCloudSave;
+ }
+ public boolean setInventoryCloudSave(int inventoryCloudSave) {
+ csReaderConnector.settingData.inventoryCloudSave = inventoryCloudSave;
+ return true;
+ }
+ public String getServerImpinjLocation() {
+ return csReaderConnector.settingData.serverImpinjLocation;
+ }
+ public boolean setServerImpinjLocation(String serverImpinjLocation) {
+ csReaderConnector.settingData.serverImpinjLocation = serverImpinjLocation;
+ return true;
+ }
+ public String getServerImpinjName() {
+ appendToLog("serverImpinjName = " + csReaderConnector.settingData.serverImpinjName);
+ return csReaderConnector.settingData.serverImpinjName;
+ }
+ public boolean setServerImpinjName(String serverImpinjName) {
+ csReaderConnector.settingData.serverImpinjName = serverImpinjName;
+ appendToLog("serverImpinjName = " + serverImpinjName);
+ return true;
+ }
+ public String getServerImpinjPassword() {
+ return csReaderConnector.settingData.serverImpinjPassword;
+ }
+ public boolean setServerImpinjPassword(String serverImpinjPassword) {
+ csReaderConnector.settingData.serverImpinjPassword = serverImpinjPassword;
+ return true;
+ }
+ public int getBatteryDisplaySetting() {
+ return csReaderConnector.settingData.batteryDisplaySelect;
+ }
+ public boolean setBatteryDisplaySetting(int batteryDisplaySelect) {
+ return csReaderConnector.settingData.setBatteryDisplaySetting(batteryDisplaySelect);
+ }
+ public double dBuV_dBm_constant = RfidReader.dBuV_dBm_constant; //106.98;
+ public int getRssiDisplaySetting() {
+ return csReaderConnector.settingData.rssiDisplaySelect;
+ }
+ public boolean setRssiDisplaySetting(int rssiDisplaySelect) {
+ return csReaderConnector.settingData.setRssiDisplaySetting(rssiDisplaySelect);
+ }
+ public int getVibrateModeSetting() {
+ return csReaderConnector.settingData.vibrateModeSelect;
+ }
+ public boolean setVibrateModeSetting(int vibrateModeSelect) {
+ if (vibrateModeSelect < 0 || vibrateModeSelect > 1) return false;
+ csReaderConnector.settingData.vibrateModeSelect = vibrateModeSelect;
+ return true;
+ }
+ public int getSavingFormatSetting() {
+ return csReaderConnector.settingData.savingFormatSelect;
+ }
+ public boolean setSavingFormatSetting(int savingFormatSelect) {
+ if (false) appendToLog("savingFormatSelect = " + savingFormatSelect);
+ if (savingFormatSelect < 0 || savingFormatSelect > 1) return false;
+ csReaderConnector.settingData.savingFormatSelect = savingFormatSelect;
+ return true;
+ }
+ public int getCsvColumnSelectSetting() {
+ return csReaderConnector.settingData.csvColumnSelect;
+ }
+ public boolean setCsvColumnSelectSetting(int csvColumnSelect) {
+ csReaderConnector.settingData.csvColumnSelect = csvColumnSelect;
+ return true;
+ }
+ public String getWedgeDeviceName() {
+ return csReaderConnector.settingData.wedgeDeviceName;
+ }
+ public String getWedgeDeviceAddress() {
+ return csReaderConnector.settingData.wedgeDeviceAddress;
+ }
+ public int getWedgeDeviceUUID2p1() {
+ return csReaderConnector.settingData.wedgeDeviceUUID2p1;
+ }
+ public int getWedgePower() {
+ return csReaderConnector.settingData.wedgePower;
+ }
+ public String getWedgePrefix() {
+ return csReaderConnector.settingData.wedgePrefix;
+ }
+ public String getWedgeSuffix() {
+ return csReaderConnector.settingData.wedgeSuffix;
+ }
+ public int getWedgeDelimiter() {
+ return csReaderConnector.settingData.wedgeDelimiter;
+ }
+ public int getWedgeOutput() {
+ return csReaderConnector.settingData.wedgeOutput;
+ }
+ public void setWedgeDeviceName(String wedgeDeviceName) {
+ csReaderConnector.settingData.wedgeDeviceName = wedgeDeviceName;
+ }
+ public void setWedgeDeviceAddress(String wedgeDeviceAddress) {
+ csReaderConnector.settingData.wedgeDeviceAddress = wedgeDeviceAddress;
+ }
+ public void setWedgeDeviceUUID2p1(int wedgeDeviceUUID2p1) {
+ csReaderConnector.settingData.wedgeDeviceUUID2p1 = wedgeDeviceUUID2p1;;
+ }
+ public void setWedgePower(int iPower) {
+ csReaderConnector.settingData.wedgePower = iPower;
+ }
+ public void setWedgePrefix(String string) {
+ csReaderConnector.settingData.wedgePrefix = string;
+ }
+ public void setWedgeSuffix(String string) {
+ csReaderConnector.settingData.wedgeSuffix = string;
+ }
+ public void setWedgeDelimiter(int iValue) {
+ csReaderConnector.settingData.wedgeDelimiter = iValue;
+ }
+ public void setWedgeOutput(int iOutput) {
+ csReaderConnector.settingData.wedgeOutput = iOutput;
+ }
+ public void saveWedgeSetting2File() {
+ csReaderConnector.settingData.saveWedgeSetting2File();
+ }
+
+ //============ Bluetooth ============
+ public String getBluetoothICFirmwareVersion() {
+ return bluetoothConnector.getBluetoothIcVersion();
+ }
+ public String getBluetoothICFirmwareName() {
+ return bluetoothConnector.getBluetoothIcName();
+ }
+ public boolean setBluetoothICFirmwareName(String name) {
+ return bluetoothConnector.setBluetoothIcName(name);
+ }
+
+ //============ Controller ============
+ public String hostProcessorICGetFirmwareVersion() {
+ return controllerConnector.getVersion();
+ }
+ public String getHostProcessorICSerialNumber() {
+ String str;
+ if (bluetoothConnector.getCsModel() != 463) str = controllerConnector.getSerialNumber();
+ else str = csReaderConnector.rfidReader.getProductSerialNumber();
+ if (str != null) {
+ if (str.length() > 13) return str.substring(0, 13);
+ }
+ return null;
+ }
+ public String getHostProcessorICBoardVersion() {
+ String str;
+ if (bluetoothConnector.getCsModel() != 463) str = controllerConnector.getSerialNumber();
+ else str = csReaderConnector.rfidReader.getProductSerialNumber();
+ if (false) appendToLog("str = " + str);
+ if (str != null) {
+ if (str.length() == 16) {
+ String strOut = "";
+ if (str.substring(13, 14).matches("0") == false) strOut = str.substring(13, 14);
+ strOut += (strOut.length() != 0 ? "." : "") + str.substring(14, 15);
+ if (str.substring(15, 16).matches("0") == false || strOut.length() < 3) strOut += (strOut.length() < 3 ? "." : "") + str.substring(15, 16);
+ if (false) appendToLog("getBoardVersion 1 = " + str);
+ return strOut;
+ }
+ }
+ return null;
+ }
+
+ //============ Controller notification ============
+ int iBatteryCount;
+ int getBatteryValue2Percent(float floatValue) {
+ boolean DEBUG = false;
+ if (DEBUG) appendToLog("getHostProcessorICBoardVersion = " + getHostProcessorICBoardVersion() + ", strVersionMBoard = " + strVersionMBoard);
+ if (false || checkHostProcessorVersion(getHostProcessorICBoardVersion(), Integer.parseInt(strMBoardVersions[0].trim()), Integer.parseInt(strMBoardVersions[1].trim()), 0)) {
+ final float[] fValueStbyRef = {
+ (float) 4.212, (float) 4.175, (float) 4.154, (float) 4.133, (float) 4.112,
+ (float) 4.085, (float) 4.069, (float) 4.054, (float) 4.032, (float) 4.011,
+ (float) 3.990, (float) 3.969, (float) 3.953, (float) 3.937, (float) 3.922,
+ (float) 3.901, (float) 3.885, (float) 3.869, (float) 3.853, (float) 3.837,
+ (float) 3.821, (float) 3.806, (float) 3.790, (float) 3.774, (float) 3.769,
+ (float) 3.763, (float) 3.758, (float) 3.753, (float) 3.747, (float) 3.742,
+ (float) 3.732, (float) 3.721, (float) 3.705, (float) 3.684, (float) 3.668,
+ (float) 3.652, (float) 3.642, (float) 3.626, (float) 3.615, (float) 3.605,
+ (float) 3.594, (float) 3.584, (float) 3.568, (float) 3.557, (float) 3.542,
+ (float) 3.531, (float) 3.510, (float) 3.494, (float) 3.473, (float) 3.457,
+ (float) 3.436, (float) 3.410, (float) 3.362, (float) 3.235, (float) 2.987,
+ (float) 2.982
+ };
+ final float[] fPercentStbyRef = {
+ (float) 100, (float) 98, (float) 96, (float) 95, (float) 93,
+ (float) 91, (float) 89, (float) 87, (float) 85, (float) 84,
+ (float) 82, (float) 80, (float) 78, (float) 76, (float) 75,
+ (float) 73, (float) 71, (float) 69, (float) 67, (float) 65,
+ (float) 64, (float) 62, (float) 60, (float) 58, (float) 56,
+ (float) 55, (float) 53, (float) 51, (float) 49, (float) 47,
+ (float) 45, (float) 44, (float) 42, (float) 40, (float) 38,
+ (float) 36, (float) 35, (float) 33, (float) 31, (float) 29,
+ (float) 27, (float) 25, (float) 24, (float) 22, (float) 20,
+ (float) 18, (float) 16, (float) 15, (float) 13, (float) 11,
+ (float) 9, (float) 7, (float) 5, (float) 4, (float) 2,
+ (float) 0
+ };
+ final float[] fValueRunRef = {
+ (float) 4.106, (float) 4.017, (float) 3.98 , (float) 3.937, (float) 3.895,
+ (float) 3.853, (float) 3.816, (float) 3.779, (float) 3.742, (float) 3.711,
+ (float) 3.679, (float) 3.658, (float) 3.637, (float) 3.626, (float) 3.61 ,
+ (float) 3.584, (float) 3.547, (float) 3.515, (float) 3.484, (float) 3.457,
+ (float) 3.431, (float) 3.399, (float) 3.362, (float) 3.32 , (float) 3.251,
+ (float) 3.135
+ };
+ final float[] fPercentRunRef = {
+ (float) 100, (float) 96, (float) 92, (float) 88, (float) 84,
+ (float) 80, (float) 76, (float) 72, (float) 67, (float) 63,
+ (float) 59, (float) 55, (float) 51, (float) 47, (float) 43,
+ (float) 39, (float) 35, (float) 31, (float) 27, (float) 23,
+ (float) 19, (float) 15, (float) 11, (float) 7, (float) 2,
+ (float) 0
+ };
+ float[] fValueRef = fValueStbyRef;
+ float[] fPercentRef = fPercentStbyRef;
+
+ if (true && iBatteryCount != getBatteryCount()) {
+ iBatteryCount = getBatteryCount();
+ iBatteryNewCurveDelay++;
+ }
+ if (csReaderConnector.rfidReader.mRfidToWrite.size() != 0) iBatteryNewCurveDelay = 0;
+ else if (csReaderConnector.rfidReader.isInventoring()) {
+ if (bUsingInventoryBatteryCurve == false) { if (iBatteryNewCurveDelay > 1) { iBatteryNewCurveDelay = 0; bUsingInventoryBatteryCurve = true; } }
+ else iBatteryNewCurveDelay = 0;
+ } else if (bUsingInventoryBatteryCurve) { if (iBatteryNewCurveDelay > 2) { iBatteryNewCurveDelay = 0; bUsingInventoryBatteryCurve = false; } }
+ else iBatteryNewCurveDelay = 0;
+
+ if (bUsingInventoryBatteryCurve) {
+ fValueRef = fValueRunRef;
+ fPercentRef = fPercentRunRef;
+ }
+ if (DEBUG) appendToLog("NEW Percentage cureve is USED with bUsingInventoryBatteryCurve = " + bUsingInventoryBatteryCurve + ", iBatteryNewCurveDelay = " + iBatteryNewCurveDelay);
+
+ int index = 0;
+ while (index < fValueRef.length) {
+ if (floatValue > fValueRef[index]) break;
+ index++;
+ }
+ if (DEBUG) appendToLog("Index = " + index);
+ if (index == 0) return 100;
+ if (index == fValueRef.length) return 0;
+ float value = ((fValueRef[index - 1] - floatValue) / (fValueRef[index - 1] - fValueRef[index]));
+ if (true) {
+ value *= (fPercentRef[index -1] - fPercentRef[index]);
+ value = fPercentRef[index - 1] - value;
+ } else {
+ value += (float) (index - 1);
+ value /= (float) (fValueRef.length - 1);
+ value *= 100;
+ value = 100 - value;
+ }
+ value += 0.5;
+ int iValue = (int) (value);
+ if (iBatteryNewCurveDelay != 0) iValue = iBatteryPercentOld;
+ else if (bUsingInventoryBatteryCurve && floatValue <= fBatteryValueOld && iValue >= iBatteryPercentOld) iValue = iBatteryPercentOld;
+ fBatteryValueOld = floatValue; iBatteryPercentOld = iValue;
+ return iValue;
+ } else {
+ if (DEBUG) appendToLog("OLD Percentage cureve is USED");
+ if (floatValue >= 4) return 100;
+ else if (floatValue < 3.4) return 0;
+ else {
+ float result = (float) 166.67 * floatValue - (float) 566.67;
+ return (int) result;
+ }
+ }
+ }
+ public int getBatteryLevel() {
+ return csReaderConnector.getBatteryLevel();
+ }
+ public boolean setAutoTriggerReporting(byte timeSecond) {
+ return notificationConnector.setAutoTriggerReporting(timeSecond);
+ }
+ public boolean getAutoBarStartSTop() {
+ return notificationConnector.getAutoBarStartStopStatus();
+ }
+
+ public boolean batteryLevelRequest() {
+ if (csReaderConnector.rfidReader == null) return false;
+ if (notificationConnector == null) return false;
+ if (csReaderConnector.rfidReader.isInventoring()) {
+ appendToLog("Skip batteryLevelREquest as inventoring !!!");
+ return true;
+ }
+ if (mrfidToWriteSize() != 0) return false;
+ return notificationConnector.batteryLevelRequest();
+ }
+ public boolean setAutoBarStartSTop(boolean enable) {
+ return notificationConnector.setAutoBarStartSTop(enable);
+ }
+ public boolean getTriggerReporting() {
+ return csReaderConnector.settingData.triggerReporting;
+ }
+ public boolean setTriggerReporting(boolean triggerReporting) {
+ return notificationConnector.setTriggerReporting(triggerReporting);
+ }
+ public final int iNO_SUCH_SETTING = 10000;
+ public short getTriggerReportingCount() {
+ boolean bValue = false;
+ if (getcsModel() != 463) bValue = checkHostProcessorVersion(hostProcessorICGetFirmwareVersion(), 1, 0, 16);
+ if (bValue == false) return iNO_SUCH_SETTING; else
+ return csReaderConnector.settingData.triggerReportingCountSetting;
+ }
+ public boolean setTriggerReportingCount(short triggerReportingCount) {
+ return notificationConnector.setTriggerReportingCount(triggerReportingCount);
+ }
+ public String getBatteryDisplay(boolean voltageDisplay) {
+ float floatValue = (float) getBatteryLevel() / 1000;
+ if (floatValue == 0) return " ";
+ String retString = null;
+ if (voltageDisplay || (getBatteryDisplaySetting() == 0)) retString = String.format("%.3f V", floatValue);
+ else retString = (String.format("%d", getBatteryValue2Percent(floatValue)) + "%");
+ if (voltageDisplay == false) retString += String.format("\r\n P=%d", getPwrlevel());
+ return retString;
+ }
+ String strVersionMBoard = "1.8"; String[] strMBoardVersions = strVersionMBoard.split("\\.");
+ int iBatteryNewCurveDelay; boolean bUsingInventoryBatteryCurve = false; float fBatteryValueOld; int iBatteryPercentOld;
+ public String isBatteryLow() {
+ boolean batterylow = false;
+ int iValue = getBatteryLevel();
+ if (iValue == 0) return null;
+ float fValue = (float) iValue / 1000;
+ int iPercent = getBatteryValue2Percent(fValue);
+ if (checkHostProcessorVersion(getHostProcessorICBoardVersion(), Integer.parseInt(strMBoardVersions[0].trim()), Integer.parseInt(strMBoardVersions[1].trim()), 0)) {
+ if (true) {
+ if (csReaderConnector.rfidReader.isInventoring()) {
+ if (fValue < 3.520) batterylow = true;
+ } else if (bUsingInventoryBatteryCurve == false) {
+ if (fValue < 3.626) batterylow = true;
+ }
+ } else if (iPercent <= 20) batterylow = true;
+ } else if (true) {
+ if (csReaderConnector.rfidReader.isInventoring()) {
+ if (fValue < 3.45) batterylow = true;
+ } else if (bUsingInventoryBatteryCurve == false) {
+ if (fValue < 3.6) batterylow = true;
+ }
+ } else if (iPercent <= 8) batterylow = true;
+ if (batterylow) return String.valueOf(iPercent);
+ return null;
+ }
+ public int getBatteryCount() {
+ return csReaderConnector.csConnectorData.getVoltageCnt();
+ }
+ public boolean getTriggerButtonStatus() {
+ return notificationConnector.getTriggerStatus();
+ }
+ public int getTriggerCount() {
+ return csReaderConnector.csConnectorData.getTriggerCount();
+ }
+ //public interface NotificationListener { void onChange(); }
+ public void setNotificationListener(NotificationConnector.NotificationListener listener) {
+ notificationConnector.setNotificationListener0(listener);
+ }
+ public byte[] onNotificationEvent() {
+ byte[] notificationData = null;
+ if (notificationConnector == null) {
+ appendToLog("notificationConnector is null");
+ return null;
+ }
+ if (notificationConnector.notificationToRead.size() != 0) {
+ NotificationConnector.CsReaderNotificationData csReaderNotificationData = notificationConnector.notificationToRead.get(0);
+ notificationConnector.notificationToRead.remove(0);
+ if (csReaderNotificationData != null) notificationData = csReaderNotificationData.dataValues;
+ }
+ return notificationData;
+ }
+
+ //============ to be modified ============
+ String getModelName() {
+ return csReaderConnector.getModelName();
+ }
+ public String getSerialNumber() {
+ return csReaderConnector.rfidReader.getSerialNumber();
+ }
+ public boolean setRfidOn(boolean onStatus) {
+ return csReaderConnector.rfidReader.turnOn(onStatus);
+ }
+ private final Runnable reinitaliseDataRunnable = new Runnable() {
+ @Override
+ public void run() {
+ appendToLog("reset before: reinitaliseDataRunnable starts with inventoring=" + csReaderConnector.rfidReader.isInventoring() + ", mrfidToWriteSize=" + mrfidToWriteSize());
+ if (csReaderConnector.rfidReader.isInventoring() || mrfidToWriteSize() != 0) {
+ mHandler.removeCallbacks(reinitaliseDataRunnable);
+ mHandler.postDelayed(reinitaliseDataRunnable, 500);
+ } else {
+ if (DEBUG_CONNECT) appendToLog("Debug_Connect: Cs108Library4A.reinitaliseDataRunnable Start checkVersionRunnable");
+ mHandler.postDelayed(checkVersionRunnable, 500);
+ }
+ }
+ };
+ private final Runnable checkVersionRunnable = new Runnable() {
+ boolean DEBUG = false;
+ @Override
+ public void run() {
+ if (DEBUG_CONNECT || true) appendToLog("Debug_Connect: Cs108Library4A.checkVersionRunnable with mrfidToWriteSize = " + mrfidToWriteSize());
+ if (mrfidToWriteSize() > 0) {
+ mHandler.removeCallbacks(checkVersionRunnable);
+ mHandler.postDelayed(checkVersionRunnable, 500);
+ } else {
+ //setSameCheck(false);
+ setAccessCount(0); //appendToLog("btDataOut: setAccessCount as 0");
+ notificationConnector.setVersion(hostProcessorICGetFirmwareVersion());
+ if (false && isBarcodeFailure() == false) {
+ if (DEBUG) appendToLog("checkVersionRunnable: Checkpoint 2");
+ if (barcodeNewland.checkPreSuffix(barcodeNewland.prefixRef, barcodeNewland.suffixRef) == false) barcodeNewland.barcodeSendCommandSetPreSuffix();
+ if (barcodeNewland.bBarcodeTriggerMode != 0x30) barcodeNewland.barcodeSendCommandTrigger();
+ notificationConnector.getAutoRFIDAbort(); notificationConnector.getAutoBarStartSTop(); //setAutoRFIDAbort(false); setAutoBarStartSTop(true);
+ }
+ setAntennaCycle(0xffff);
+ if (true) {
+ if (bluetoothConnector.getCsModel() == 463) {
+ if (DEBUG_CONNECT) appendToLog("Debug_Connect: Cs108Library4A.checkVersionRunnable 4");
+ setAntennaDwell(2000);
+ setAntennaInvCount(0);
+ } else {
+ if (DEBUG_CONNECT) appendToLog("Debug_Connect: Cs108Library4A.checkVersionRunnable 5");
+ setAntennaDwell(0);
+ setAntennaInvCount(0xfffffffeL);
+ }
+ }
+ csReaderConnector.settingData.loadWedgeSettingFile();
+ if (loadSetting1File()) loadSetting1File();
+ if (DEBUG_CONNECT) appendToLog("Debug_Connect: Cs108Library4A.checkVersionRunnable with macVersion [" + getMacVer());
+ if (checkHostProcessorVersion(getMacVer(), 2, 6, 8)) {
+ setTagDelay(csReaderConnector.rfidReader.tagDelaySetting);
+ setCycleDelay(csReaderConnector.rfidReader.cycleDelaySetting);
+ setInvModeCompact(true);
+ } else {
+ setTagDelay(csReaderConnector.rfidReader.tagDelayDefaultNormalSetting);
+ setCycleDelay(csReaderConnector.rfidReader.cycleDelaySetting);
+ }
+ csReaderConnector.rfidReader.setDiagnosticConfiguration(true);
+ if (DEBUG_CONNECT) appendToLog("Debug_Connect: Cs108Library4A.checkVersionRunnable ends with mRfidToWrite.size = " + csReaderConnector.rfidReader.mRfidToWrite.size());
+ //setSameCheck(true);
+ }
+ }
+ };
+
+ boolean loadSetting1File() {
+ return csReaderConnector.settingData.loadSettingFile(bluetoothGatt.getReaderDeviceConnected().getAddress(), getlibraryVersion(), getChannelHoppingStatus(), getCurrentProfile());
+ }
+ public void saveSetting2File() {
+ csReaderConnector.settingData.saveSetting2File(getlibraryVersion(), getChannelHoppingStatus(), getCurrentProfile());
+ }
+
+ public int getcsModel() {
+ return bluetoothConnector.getCsModel();
+ }
+ public int getAntennaCycle() {
+ return csReaderConnector.rfidReader.getAntennaCycle();
+ }
+ public boolean setAntennaCycle(int antennaCycle) {
+ return csReaderConnector.rfidReader.setAntennaCycle(antennaCycle);
+ }
+ public boolean setAntennaInvCount(long antennaInvCount) {
+ return csReaderConnector.rfidReader.setAntennaInvCount(antennaInvCount);
+ }
+
+ public void clearInvalidata() {
+ csReaderConnector.clearInvalidata();
+ }
+ public int getInvalidata() {
+ return csReaderConnector.invalidata;
+ }
+ public int getInvalidUpdata() {
+ return csReaderConnector.invalidUpdata;
+ }
+ public int getValidata() {
+ return csReaderConnector.validata;
+ }
+
+ public int setSelectData(RfidReader.TagType tagType, String mDid, boolean bNeedSelectedTagByTID, String stringProtectPassword, int selectFor, int selectHold) {
+ return csReaderConnector.rfidReader.setSelectData4Inventory(tagType, mDid, bNeedSelectedTagByTID, stringProtectPassword, selectFor, selectHold);
+ }
+ public int setOtherInventoryData(RfidReader.TagType tagType, String mDid) {
+ return -1;
+ }
+}
+
+
+
+package com.csl.cslibrary4a;
+
+import android.bluetooth.BluetoothAdapter;
+import android.bluetooth.BluetoothProfile;
+import android.bluetooth.le.ScanCallback;
+import android.content.Context;
+import android.os.Handler;
+import android.widget.TextView;
+
+import com.csl.cslibrary4a.RfidReader.RegionCodes;
+
+import java.io.File;
+import java.util.ArrayList;
+import java.util.List;
+
+public class Cs710Library4A {
+ final boolean DEBUG = false;
+ final boolean DEBUG_FILE = false;
+ private Handler mHandler = new Handler();
+ BluetoothAdapter.LeScanCallback mLeScanCallback = null;
+ ScanCallback mScanCallback = null;
+
+ Context context;
+ CsReaderConnector csReaderConnector; Utility utility;
+ boolean DEBUG_CONNECT, DEBUG_SCAN;
+ BluetoothGatt bluetoothGatt;
+ BarcodeNewland barcodeNewland; BarcodeConnector barcodeConnector;
+ NotificationConnector notificationConnector;
+ ControllerConnector controllerConnector;
+ BluetoothConnector bluetoothConnector;
+ TextView mLogView = null;
+
+ void setCsReaderConnectorCombo() { csReaderConnector.setScanType(0x03); }
+ public Cs710Library4A(Context context, TextView mLogView) {
+ this.context = context;
+ this.mLogView = mLogView;
+ utility = new Utility(context, mLogView);
+ csReaderConnector = new CsReaderConnector(context, mLogView, utility, false); csReaderConnector.setScanType(0x02);
+ bluetoothGatt = csReaderConnector.bluetoothGatt; DEBUG_CONNECT = utility.DEBUG_CONNECT; DEBUG_SCAN = utility.DEBUG_SCAN;
+/*
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
+ mScanCallback = new ScanCallback() {
+ @Override
+ public void onBatchScanResults(List results) {
+ if (DEBUG) appendToLog("onBatchScanResults()");
+ }
+
+ @Override
+ public void onScanFailed(int errorCode) {
+ if (DEBUG) appendToLog("onScanFailed()");
+ }
+
+ @Override
+ public void onScanResult(int callbackType, ScanResult result) {
+ boolean DEBUG = false;
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
+ BluetoothGatt.CsScanData scanResultA = new BluetoothGatt.CsScanData(result.getDevice(), result.getRssi(), result.getScanRecord().getBytes());
+ boolean found98 = true;
+ if (true) found98 = check9800(scanResultA);
+ if (DEBUG) appendToLog("found98 = " + found98 + ", mScanResultList 0 = " + (mScanResultList != null ? "VALID" : "NULL"));
+ if (mScanResultList != null && found98) {
+ scanResultA.serviceUUID2p2 = check9800_serviceUUID2p1;
+ mScanResultList.add(scanResultA);
+ if (DEBUG) appendToLog("mScanResultList 0 = " + mScanResultList.size());
+ }
+ }
+ }
+ };
+ } else {
+ mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
+ @Override
+ public void onLeScan(final BluetoothDevice device, final int rssi, final byte[] scanRecord) {
+ if (true) appendToLog("onLeScan()");
+ BluetoothGatt.CsScanData scanResultA = new BluetoothGatt.CsScanData(device, rssi, scanRecord);
+ boolean found98 = true;
+ if (true) found98 = check9800(scanResultA);
+ appendToLog("found98 = " + found98 + ", mScanResultList 1 = " + (mScanResultList != null ? "VALID" : "NULL"));
+ if (mScanResultList != null && found98) {
+ scanResultA.serviceUUID2p2 = check9800_serviceUUID2p1;
+ mScanResultList.add(scanResultA);
+ appendToLog("mScanResultList 1 = " + mScanResultList.size());
+ }
+ }
+ };
+ }
+*/
+ File path = context.getFilesDir();
+ File[] fileArray = path.listFiles();
+ boolean deleteFiles = false;
+ if (true || DEBUG)
+ appendToLog("Number of file in data storage sub-directory = " + fileArray.length);
+ boolean bProfileInstalledFound = false;
+ for (int i = 0; i < fileArray.length; i++) {
+ String fileName = fileArray[i].toString();
+ if (true) appendToLog("Stored file (" + i + ") = " + fileName);
+ if (fileName.contains("profileInstalled") || fileName.contains("profileinstaller")) {
+ bProfileInstalledFound = true;
+ appendToLog("Found profileInstalled or profileinstaller file");
+ }
+ File file = new File(fileName);
+ if (deleteFiles) file.delete();
+ }
+ if (!bProfileInstalledFound) {
+ for (int i = 0; i < fileArray.length; i++) {
+ String fileName = fileArray[i].toString();
+ File file = new File(fileName);
+ file.delete();
+ appendToLog("Deleted " + fileName);
+ }
+ }
+ }
+ public String getlibraryVersion() {
+ String version = BuildConfig.VERSION_NAME;
+ //int iVersion = Integer.parseInt(version) + 10;
+ version = "15.0"; //+ String.valueOf(iVersion);
+ appendToLog("version = " + version);
+ return utility.getCombinedVersion(version);
+ }
+ public String checkVersion() {
+ return csReaderConnector.checkVersion();
+ }
+
+ //============ utility ============
+ public String byteArrayToString(byte[] packet) {
+ return utility.byteArrayToString(packet);
+ }
+ public void appendToLog(String s) {
+ utility.appendToLog(s);
+ }
+ public void appendToLogView(String s) {
+ utility.appendToLogView(s);
+ }
+ public String strFloat16toFloat32(String strData) {
+ return utility.strFloat16toFloat32(strData);
+ }
+ public String str2float16(String strData) {
+ return utility.str2float16(strData);
+ }
+ public float decodeCtesiusTemperature(String strActData, String strCalData) {
+ return utility.decodeCtesiusTemperature(strActData, strCalData);
+ }
+ public float decodeMicronTemperature(int iTag35, String strActData, String strCalData) {
+ return utility.decodeMicronTemperature(iTag35, strActData, strCalData);
+ }
+ public float decodeAsygnTemperature(String string) {
+ return utility.decodeAsygnTemperature(string);
+ }
+ public String temperatureC2F(String strValue) {
+ return utility.temperatureC2F(strValue);
+ }
+ public String temperatureF2C(String strValue) {
+ return utility.temperatureF2C(strValue);
+ }
+ public String getUpcSerial(String strEpc) {
+ return utility.getUpcSerial(strEpc);
+ }
+ public String getUpcSerialDetail(String strUpcSerial) {
+ return utility.getUpcSerialDetail(strUpcSerial);
+ }
+ public String getEpc4upcSerial(Utility.EpcClass epcClass, String filter, String companyPrefix, String itemReference, String serialNumber) {
+ return utility.getEpc4upcSerial(epcClass, filter, companyPrefix, itemReference, serialNumber);
+ }
+ public boolean checkHostProcessorVersion(String version, int majorVersion, int minorVersion, int buildVersion) {
+ return utility.checkHostProcessorVersion(version, majorVersion, minorVersion, buildVersion);
+ }
+
+ //============ android bluetooth ============
+ ArrayList mScanResultList = new ArrayList<>();
+ int check9800_serviceUUID2p1 = 0;
+ boolean deviceConnection = false;
+ ReaderDevice readerDeviceConnect;
+ boolean bNeedReconnect = false;
+ int iConnectStateTimer = 0;
+/*
+ boolean check9800(BluetoothGatt.CsScanData scanResultA) {
+ boolean found98 = false, DEBUG = false;
+ if (DEBUG) appendToLog("decoded data size = " + scanResultA.decoded_scanRecord.size());
+ int iNewADLength = 0;
+ byte[] newAD = new byte[0];
+ int iNewADIndex = 0;
+ check9800_serviceUUID2p1 = -1;
+ if (bluetoothGatt.isBLUETOOTH_CONNECTinvalid()) return true;
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S && ActivityCompat.checkSelfPermission(context, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED)
+ return true;
+ String strTemp = scanResultA.getDevice().getName();
+ if (strTemp != null && DEBUG)
+ appendToLog("Found name = " + strTemp + ", length = " + String.valueOf(strTemp.length()));
+ for (byte bdata : scanResultA.getScanRecord()) {
+ if (iNewADIndex >= iNewADLength && iNewADLength != 0) {
+ scanResultA.decoded_scanRecord.add(newAD);
+ iNewADIndex = 0;
+ iNewADLength = 0;
+ if (DEBUG)
+ appendToLog("Size = " + scanResultA.decoded_scanRecord.size() + ", " + byteArrayToString(newAD));
+ }
+ if (iNewADLength == 0) {
+ iNewADLength = bdata;
+ newAD = new byte[iNewADLength];
+ iNewADIndex = 0;
+ } else newAD[iNewADIndex++] = bdata;
+ }
+ if (DEBUG) appendToLog("decoded data size = " + scanResultA.decoded_scanRecord.size());
+ for (int i = 0; i < scanResultA.decoded_scanRecord.size(); i++) {
+ byte[] currentAD = scanResultA.decoded_scanRecord.get(i);
+ if (DEBUG) appendToLog("Processing decoded data = " + byteArrayToString(currentAD));
+ if (currentAD[0] == 2) {
+ if (DEBUG) appendToLog("Processing UUIDs 02");
+ if ((currentAD[1] == 2) && currentAD[2] == (byte) 0x98) {
+ if (DEBUG) appendToLog("Found 9802");
+ found98 = true;
+ check9800_serviceUUID2p1 = currentAD[1];
+ if (DEBUG) appendToLog("serviceUD1D2p1 = " + check9800_serviceUUID2p1);
+ break;
+ }
+ }
+ }
+ if (found98 == false && DEBUG)
+ appendToLog("No 9800: with scanData = " + byteArrayToString(scanResultA.getScanRecord()));
+ else if (DEBUG_SCAN)
+ appendToLog("Cs710Library4A, Found 9800: with scanData = " + byteArrayToString(scanResultA.getScanRecord()));
+ return found98;
+ }
+*/
+ boolean connect1(ReaderDevice readerDevice) {
+ boolean DEBUG = true;
+ if (DEBUG || DEBUG_CONNECT)
+ appendToLog("Debug_Connect: Cs710Library4A.Connect1 with " + (readerDevice == null ? "null" : "valid") + " readerDevice, " + (readerDeviceConnect == null ? "null" : "valid") + " readerDeviceConnect");
+ if (readerDevice == null && readerDeviceConnect != null) readerDevice = readerDeviceConnect;
+ boolean result = false;
+ if (readerDevice != null) {
+ bNeedReconnect = false;
+ iConnectStateTimer = 0;
+ bluetoothGatt.bDiscoverStarted = false;
+ if (DEBUG) appendToLog("connect1: going to connectBle with " + (readerDevice == null ? "null" : "valid"));
+ bluetoothGatt.setServiceUUIDType(readerDevice.getServiceUUID2p1());
+ appendToLog("Cs710Library4A.connect1 is going to connect");
+ result = csReaderConnector.connect(readerDevice);
+ }
+ if (DEBUG || DEBUG_CONNECT) appendToLog("Debug_Connect: Cs710Library4A.connect1 Result = " + result);
+ return result;
+ }
+ final Runnable connectRunnable = new Runnable() {
+ boolean DEBUG = true;
+
+ @Override
+ public void run() {
+ if (DEBUG || DEBUG_CONNECT) {
+ appendToLog("Debug_Connect: Cs710Library4A.connectRunnable: isBleScanning = " + isBleScanning());
+ appendToLog("Debug_Connect: Cs710Library4A.connectRunnable: bNeedReconnect = " + bNeedReconnect);
+ appendToLog("Debug_Connect, Cs108Library4A.connectRunnable: usbConnectState = " + (csReaderConnector.usbConnector == null ? "null" : csReaderConnector.usbConnector.usbConnectionState));
+ appendToLog("Debug_Connect: Cs710Library4A.connectRunnable: bluetoothConnectionState = " + bluetoothGatt.bluetoothConnectionState);
+ }
+ if (isBleScanning()) {
+ if (DEBUG) appendToLog("Cs710Library4A.connectRunnable: still scanning. Stop scanning first");
+ scanLeDevice(false);
+ } else if (bNeedReconnect) {
+ if (bluetoothGatt.bluetoothGatt != null) {
+ if (DEBUG) appendToLog("Cs710Library4A.connectRunnable: mBluetoothGatt is null before connect. disconnect first");
+ csReaderConnector.disconnect();
+ } else if (readerDeviceConnect == null) {
+ if (DEBUG) appendToLog("Cs710Library4A.connectRunnable: exit with null readerDeviceConnect");
+ return;
+ } else if (bluetoothGatt.bluetoothGatt == null) {
+ if (DEBUG || DEBUG_CONNECT) appendToLog("Debug_Connect, Cs710Library4A.connectRunnable: connect1 starts");
+ connect1(null);
+ bNeedReconnect = false;
+ }
+ } else if (csReaderConnector.usbConnector != null && csReaderConnector.usbConnector.usbConnectionState) return;
+ else if (bluetoothGatt.bluetoothConnectionState == BluetoothProfile.STATE_DISCONNECTED) { //mReaderStreamOutCharacteristic valid around 1500ms
+ iConnectStateTimer = 0;
+ if (DEBUG)
+ appendToLog("Cs710Library4A.connectRunnable: disconnect as disconnected connectionState is received");
+ bNeedReconnect = true;
+ if (DEBUG)
+ appendToLog("Cs710Library4A.connectRunnable: bluetoothGatt is " + (bluetoothGatt.bluetoothGatt != null ? "valid" : "null"));
+ if (bluetoothGatt.bluetoothGatt != null) {
+ if (DEBUG) appendToLog("Cs710Library4A.connectRunnable: disconnect F");
+ csReaderConnector.disconnect();
+ }
+ } else if (bluetoothGatt.mReaderStreamOutCharacteristic == null) {
+ if (DEBUG_CONNECT)
+ appendToLog("Debug_Connect, Cs710Library4A.connectRunnable: wait as not yet discovery, with iConnectStateTimer = " + iConnectStateTimer);
+ if (++iConnectStateTimer > 10) {
+ }
+ } else {
+ if (DEBUG_CONNECT) appendToLog("Debug_Connect, Cs710Library4A.connectRunnable: end of ConnectRunnable");
+ return;
+ }
+ mHandler.postDelayed(connectRunnable, 500);
+ }
+ };
+ final Runnable disconnectRunnable = new Runnable() {
+ @Override
+ public void run() {
+ if (barcodeConnector == null) return;
+ appendToLog("abcc disconnectRunnable with barcodeToWrite.size = " + barcodeConnector.barcodeToWrite.size());
+ if (barcodeConnector.barcodeToWrite.size() != 0)
+ mHandler.postDelayed(disconnectRunnable, 100);
+ else {
+ appendToLog("disconnect G");
+ csReaderConnector.disconnect();
+ }
+ }
+ };
+ public boolean isBleScanning() {
+ return bluetoothGatt.isScanning();
+ }
+ public boolean scanLeDevice(boolean enable) {
+ boolean DEBUG = true;
+ if (enable) mHandler.removeCallbacks(connectRunnable);
+
+ if (DEBUG || DEBUG_SCAN) appendToLog("Cs710Library4A.scanLeDevice[" + enable + "]");
+ if (bluetoothGatt.bluetoothDeviceConnectOld != null) {
+ if (DEBUG) appendToLog("Cs710Library4A.scanLeDevice: bluetoothDeviceConnectOld connection state = " + bluetoothGatt.bluetoothManager.getConnectionState(bluetoothGatt.bluetoothDeviceConnectOld, BluetoothProfile.GATT));
+ }
+ if (enable && csReaderConnector.usbConnector != null) csReaderConnector.usbConnector.scanDevice(enable);
+ boolean bValue = bluetoothGatt.scanDevice(enable, csReaderConnector.mLeScanCallback, csReaderConnector.mScanCallback);
+ if (DEBUG || DEBUG_SCAN) appendToLog("Cs710Library4A.scanLeDevice: isScanning = " + isBleScanning());
+ return bValue;
+ }
+ public BluetoothGatt.CsScanData getNewDeviceScanned() {
+ return csReaderConnector.getNewDeviceScanned();
+/*
+ if (mScanResultList.size() != 0) {
+ if (DEBUG_SCAN) appendToLog("mScanResultList.size() = " + mScanResultList.size());
+ BluetoothGatt.CsScanData csScanData = mScanResultList.get(0); mScanResultList.remove(0);
+ return csScanData;
+ } else return null;
+*/
+ }
+ public String getBluetoothDeviceAddress() {
+ if (bluetoothGatt.getReaderDeviceConnected() == null) return null;
+ return bluetoothGatt.getReaderDeviceConnected().getAddress();
+ }
+ public String getBluetoothDeviceName() {
+ if (bluetoothGatt.getReaderDeviceConnected() == null) return null;
+ return bluetoothGatt.getReaderDeviceConnected().getName();
+ }
+ public boolean isBleConnected() {
+ boolean DEBUG = false;
+ boolean deviceConnectionNew = csReaderConnector.isConnected();
+ if (DEBUG && false) appendToLog("Cs710Library4A.isBleConnected: ConnectionNew = " + deviceConnectionNew + ", connection = " + deviceConnection);
+ if (DEBUG && false) appendToLog("Cs710Library4A.isBleConnected: rfidReader is " + (csReaderConnector.rfidReader == null ? "null" : "valid"));
+ if (DEBUG && csReaderConnector.rfidReader != null) appendToLog("Cs710Library4A.isBleConnected: bFirmware_reset_before is " + csReaderConnector.rfidReader.bFirmware_reset_before);
+ if (deviceConnectionNew) {
+ if (deviceConnection == false) {
+ deviceConnection = deviceConnectionNew;
+ if (DEBUG || DEBUG_CONNECT) appendToLog("Debug_Connect, Cs710Library4A.isBleConnected: Newly connected");
+
+ csReaderConnector.csConnectorDataInit();
+ barcodeNewland = csReaderConnector.barcodeNewland;
+ barcodeConnector = csReaderConnector.barcodeConnector;
+ notificationConnector = csReaderConnector.notificationConnector;
+ controllerConnector = csReaderConnector.controllerConnector;
+ bluetoothConnector = csReaderConnector.bluetoothConnector;
+
+ setRfidOn(true);
+ setBarcodeOn(true);
+ //hostProcessorICGetFirmwareVersion();
+ getBluetoothICFirmwareVersion();
+ csReaderConnector.rfidReader.channelOrderType = -1;
+ {
+ // getBarcodePreSuffix();
+ // getBarcodeReadingMode();
+ // getBarcodeSerial();
+ //getBarcodeNoDuplicateReading();
+ //getBarcodeDelayTimeOfEachReading();
+ //getBarcodeEnable2dBarCodes();
+ //getBarcodePrefixOrder();
+ //getBarcodeVersion();
+ //barcodeSendCommandLoadUserDefault();
+ //barcodeSendQuerySystem();
+ // barcodeNewland.barcodeSendCommandItf14Cksum();
+
+ notificationConnector.setBatteryAutoReport(true); //0xA003
+ }
+ abortOperation();
+ //getHostProcessorICSerialNumber(); //0xb004 (but access Oem as bluetooth version is not got)
+ getMacVer();
+ csReaderConnector.rfidReader.getReaderDefault();
+ csReaderConnector.rfidReader.regionCode = null;
+ getModelNumber();
+ getCountryCode();
+ //getSerialNumber();
+ getQueryTarget();
+ csReaderConnector.rfidReader.getImpinjExtension();
+ csReaderConnector.rfidReader.getInvAlgoInChip();
+ if (DEBUG || DEBUG_CONNECT) appendToLog("Debug_Connect, Cs710Library4A.isBleConnected: Start checkVersionRunnable");
+ mHandler.postDelayed(checkVersionRunnable, 500);
+
+ if (csReaderConnector.settingData.strForegroundReader.trim().length() != 0) {
+ csReaderConnector.settingData.strForegroundReader = bluetoothGatt.getReaderDeviceConnected().getAddress();
+ }
+ csReaderConnector.settingData.saveForegroundSetting2File();
+ } else if (csReaderConnector.rfidReader == null) {
+ deviceConnection = false;
+ appendToLog("Cs710Library4A.isBleConnected: csReaderConnector.rfidReader is NULL");
+ } else if (csReaderConnector.rfidReader.bFirmware_reset_before) {
+ csReaderConnector.rfidReader.bFirmware_reset_before = false;
+ mHandler.postDelayed(reinitaliseDataRunnable, 500);
+ }
+ } else if (deviceConnection) {
+ barcodeNewland = null; barcodeConnector = null;
+ notificationConnector = null;
+ controllerConnector = null;
+ bluetoothConnector = null;
+ deviceConnection = deviceConnectionNew;
+ if (DEBUG) appendToLog("Cs710Library4A.isBleConnected: Newly disconnected");
+ }
+ return(deviceConnection);
+ }
+ public void connect(ReaderDevice readerDevice) {
+ if (isBleConnected()) return;
+ if (bluetoothGatt.bluetoothGatt != null) csReaderConnector.disconnect();
+ if (readerDevice != null) readerDeviceConnect = readerDevice;
+ mHandler.removeCallbacks(connectRunnable);
+ bNeedReconnect = true; mHandler.post(connectRunnable);
+ if (DEBUG_CONNECT) appendToLog("Debug_Connect: Cs710Library4A.connect Start ConnectRunnable");
+ }
+ public void disconnect(boolean tempDisconnect) {
+ appendToLog("abcc tempDisconnect: getBarcodeOnStatus = " + (getBarcodeOnStatus() ? "on" : "off"));
+ if (DEBUG) appendToLog("tempDisconnect = " + tempDisconnect);
+ mHandler.removeCallbacks(checkVersionRunnable);
+ mHandler.removeCallbacks(runnableToggleConnection);
+ if (getBarcodeOnStatus()) {
+ appendToLog("tempDisconnect: setBarcodeOn(false)");
+ if (barcodeConnector.barcodeToWrite.size() != 0) {
+ appendToLog("going to disconnectRunnable with remaining barcodeToWrite.size = " + barcodeConnector.barcodeToWrite.size() + ", data = " + byteArrayToString(barcodeConnector.barcodeToWrite.get(0).dataValues));
+ }
+ barcodeConnector.barcodeToWrite.clear(); appendToLog("barcodeToWrite is clear");
+ setBarcodeOn(false);
+ setRfidOn(false);
+ } else appendToLog("tempDisconnect: getBarcodeOnStatus is false");
+ mHandler.postDelayed(disconnectRunnable, 100);
+ appendToLog("done with tempDisconnect = " + tempDisconnect);
+ if (tempDisconnect == false) {
+ mHandler.removeCallbacks(connectRunnable);
+ bluetoothGatt.bluetoothDeviceConnectOld = null;
+ if (readerDeviceConnect != null) bluetoothGatt.bluetoothDeviceConnectOld = bluetoothGatt.bluetoothAdapter.getRemoteDevice(readerDeviceConnect.getAddress());
+ readerDeviceConnect = null;
+ }
+ }
+ public boolean forceBTdisconnect() {
+ return bluetoothConnector.forceBTdisconnect();
+ }
+ public int getRssi() {
+ return bluetoothGatt.getRssi();
+ }
+ boolean getConnectionHSpeed() {
+ return bluetoothGatt.getConnectionHSpeedA();
+ }
+ boolean setConnectionHSpeed(boolean on) {
+ return bluetoothGatt.setConnectionHSpeedA(on);
+ }
+ public long getStreamInRate() {
+ return csReaderConnector.getStreamInRate();
+ }
+ public int get98XX() {
+ return 2;
+ }
+
+ //============ Rfid ============
+ //============ Rfid ============
+ //============ Rfid ============
+
+ boolean setInvAlgoNoSave(boolean dynamicAlgo) {
+ return csReaderConnector.rfidReader.setInvAlgoNoSave(dynamicAlgo);
+ }
+ boolean setInvAlgo1(boolean dynamicAlgo) {
+ return csReaderConnector.rfidReader.setInvAlgo1(dynamicAlgo);
+ }
+ public String getAuthMatchData() {
+ return csReaderConnector.rfidReader.getAuthMatchData();
+ }
+ public boolean setAuthMatchData(String mask) {
+ return csReaderConnector.rfidReader.setAuthMatchData(mask);
+ }
+ public int getStartQValue() {
+ return csReaderConnector.rfidReader.getStartQValue();
+ }
+ public int getMaxQValue() {
+ return csReaderConnector.rfidReader.getMaxQValue();
+ }
+ public int getMinQValue() {
+ return csReaderConnector.rfidReader.getMinQValue();
+ }
+ public boolean setDynamicQParms(int startQValue, int minQValue, int maxQValue, int retryCount) {
+ return csReaderConnector.rfidReader.setDynamicQParms(startQValue, minQValue, maxQValue, retryCount);
+ }
+ public int getFixedQValue() {
+ return csReaderConnector.rfidReader.getFixedQValue();
+ }
+ public int getFixedRetryCount() {
+ return csReaderConnector.rfidReader.getFixedRetryCount();
+ }
+ public boolean getRepeatUnitNoTags() {
+ return csReaderConnector.rfidReader.getRepeatUnitNoTags();
+ }
+ public boolean setFixedQParms(int qValue, int retryCount, boolean repeatUnitNoTags) {
+ return csReaderConnector.rfidReader.setFixedQParms(qValue, retryCount, repeatUnitNoTags);
+ }
+ RegionCodes[] getRegionList() {
+ return csReaderConnector.rfidReader.getRegionList();
+ }
+ boolean toggledConnection = false;
+ Runnable runnableToggleConnection = new Runnable() {
+ @Override
+ public void run() {
+ if (DEBUG) appendToLog("runnableToggleConnection(): toggledConnection = " + toggledConnection + ", isBleConnected() = " + isBleConnected());
+ if (isBleConnected() == false) toggledConnection = true;
+ if (toggledConnection) {
+ if (isBleConnected() == false) {
+ if (connect1(null) == false) return;
+ } else return;
+ } else { appendToLog("disconnect H"); csReaderConnector.disconnect(); appendToLog("done"); }
+ mHandler.postDelayed(runnableToggleConnection, 500);
+ }
+ };
+ public boolean getChannelHoppingDefault() {
+ return csReaderConnector.rfidReader.getChannelHoppingDefault();
+ }
+ int getCountryCode() {
+ return csReaderConnector.rfidReader.getCountryCode();
+ }
+ int getFreqModifyCode() {
+ return csReaderConnector.rfidReader.getFreqModifyCode();
+ }
+ public boolean getRfidOnStatus() {
+ return csReaderConnector.rfidReader.getRfidOnStatus();
+ }
+ public boolean isRfidFailure() {
+ //appendToLog("BtDataOut: isRfidFailure rfidReader is " + (csReaderConnector.rfidReader == null ? "null" : csReaderConnector.rfidReader.isRfidFailure()));
+ if (csReaderConnector.rfidReader == null) return false;
+ return csReaderConnector.rfidReader.isRfidFailure();
+ }
+ public void setReaderDefault() {
+ csReaderConnector.rfidReader.setReaderDefault();
+ String string = bluetoothGatt.getReaderDeviceConnected().getAddress();
+ string = string.replaceAll("[^a-zA-Z0-9]","");
+ string = string.substring(string.length()-6, string.length());
+ setBluetoothICFirmwareName("CS710Sreader" + string);
+ //getlibraryVersion()
+ if (false) {
+ setCountryInList(csReaderConnector.rfidReader.countryInListDefault);
+ setChannel(0);
+
+ //getAntennaPower(0)
+ //getPopulation()
+ //getQuerySession()
+ //getQueryTarget()
+ setTagFocus(false);
+ setFastId(false);
+ //getInvAlgo()
+ //\\getRetryCount()
+ //getCurrentProfile() + "\n"));
+ //\\getRxGain() + "\n"));
+ }
+ //getBluetoothICFirmwareName() + "\n");
+ setTagDelay(csReaderConnector.rfidReader.tagDelaySettingDefault);
+ setCycleDelay((long)0);
+ setIntraPkDelay((byte)4);
+ setDupDelay((byte)0);
+
+ setBatteryDisplaySetting(csReaderConnector.settingData.batteryDisplaySelectDefault);
+ setRssiDisplaySetting(csReaderConnector.settingData.rssiDisplaySelectDefault);
+ setTriggerReporting(csReaderConnector.settingData.triggerReportingDefault);
+ setTriggerReportingCount(csReaderConnector.settingData.triggerReportingCountSettingDefault);
+ setInventoryBeep(csReaderConnector.settingData.inventoryBeepDefault);
+ setBeepCount(csReaderConnector.settingData.beepCountSettingDefault);
+ setInventoryVibrate(csReaderConnector.settingData.inventoryVibrateDefault);
+ setVibrateTime(csReaderConnector.settingData.vibrateTimeSettingDefault);
+ setVibrateModeSetting(csReaderConnector.settingData.vibrateModeSelectDefault);
+ setVibrateWindow(csReaderConnector.settingData.vibrateWindowSettingDefault);
+
+ setSavingFormatSetting(csReaderConnector.settingData.savingFormatSelectDefault);
+ setCsvColumnSelectSetting(csReaderConnector.settingData.csvColumnSelectDefault);
+ setSaveFileEnable(csReaderConnector.settingData.saveFileEnableDefault);
+ setSaveCloudEnable(csReaderConnector.settingData.saveCloudEnableDefault);
+ setSaveNewCloudEnable(csReaderConnector.settingData.saveNewCloudEnableDefault);
+ setSaveAllCloudEnable(csReaderConnector.settingData.saveAllCloudEnableDefault);
+ setServerLocation(csReaderConnector.settingData.serverLocationDefault);
+ setServerTimeout(csReaderConnector.settingData.serverTimeoutDefault);
+ csReaderConnector.settingData.barcode2TriggerMode = csReaderConnector.settingData.barcode2TriggerModeDefault;
+
+ setUserDebugEnable(csReaderConnector.settingData.userDebugEnableDefault);
+ csReaderConnector.settingData.preFilterData = null;
+ }
+ public String getMacVer() {
+ appendToLog("Cs710Library4A.getMacVer");
+ return csReaderConnector.rfidReader.getMacVer();
+ }
+ public String getRadioSerial() {
+ return csReaderConnector.rfidReader.getRadioSerial();
+ }
+ public String getRadioBoardVersion() {
+ return csReaderConnector.rfidReader.getRadioBoardVersion();
+ }
+ public int getPortNumber() {
+ if (bluetoothConnector.getCsModel() == 463) return 4;
+ else return 1;
+ }
+ public int getAntennaSelect() {
+ return csReaderConnector.rfidReader.getAntennaSelect();
+ }
+ public boolean setAntennaSelect(int number) {
+ return csReaderConnector.rfidReader.setAntennaSelect(number);
+ }
+ public boolean getAntennaEnable() {
+ return csReaderConnector.rfidReader.getAntennaEnable();
+ }
+ public boolean setAntennaEnable(boolean enable) {
+ return csReaderConnector.rfidReader.setAntennaEnable(enable);
+ }
+ public long getAntennaDwell() {
+ return csReaderConnector.rfidReader.getAntennaDwell();
+ }
+ public boolean setAntennaDwell(long antennaDwell) {
+ return csReaderConnector.rfidReader.setAntennaDwell(antennaDwell);
+ }
+ public long getPwrlevel() {
+ return csReaderConnector.rfidReader.getPwrlevel();
+ }
+ public boolean setPowerLevel(long pwrlevel) {
+ return csReaderConnector.rfidReader.setPowerLevel(pwrlevel);
+ }
+ public int getQueryTarget() {
+ return csReaderConnector.rfidReader.getQueryTarget();
+ }
+ public int getQuerySession() {
+ return csReaderConnector.rfidReader.getQuerySession();
+ }
+ public int getQuerySelect() {
+ return csReaderConnector.rfidReader.getQuerySelect();
+ }
+ public boolean setTagGroup(int sL, int session, int target1) {
+ return csReaderConnector.rfidReader.setTagGroup(sL, session, target1);
+ }
+ public int getTagFocus() {
+ return csReaderConnector.rfidReader.getTagFocus();
+ }
+ public boolean setTagFocus(boolean tagFocusNew) {
+ return csReaderConnector.rfidReader.setTagFocus(tagFocusNew);
+ }
+ public int getFastId() {
+ return csReaderConnector.rfidReader.getFastId();
+ }
+ public boolean setFastId(boolean fastIdNew) {
+ appendToLog("bFastId: setFastId[" + fastIdNew);
+ return csReaderConnector.rfidReader.setFastId(fastIdNew);
+ }
+ public boolean getInvAlgo() {
+ return csReaderConnector.rfidReader.getInvAlgo();
+ }
+ public boolean setInvAlgo(boolean dynamicAlgo) {
+ return csReaderConnector.rfidReader.setInvAlgo(dynamicAlgo);
+ }
+ public List getProfileList() {
+ return csReaderConnector.rfidReader.getProfileList();
+ }
+ public int getCurrentProfile() {
+ return csReaderConnector.rfidReader.getCurrentProfile();
+ }
+ public boolean setBasicCurrentLinkProfile() {
+ return csReaderConnector.rfidReader.setBasicCurrentLinkProfile();
+ }
+ public boolean setCurrentLinkProfile(int profile) {
+ return csReaderConnector.rfidReader.setCurrentLinkProfile(profile);
+ }
+ public void resetEnvironmentalRSSI() {
+ csReaderConnector.rfidReader.resetEnvironmentalRSSI();
+ }
+ public String getEnvironmentalRSSI() {
+ return csReaderConnector.rfidReader.getEnvironmentalRSSI();
+ }
+ public int getHighCompression() {
+ return csReaderConnector.rfidReader.getHighCompression();
+ }
+ public int getRflnaGain() {
+ return csReaderConnector.rfidReader.getRflnaGain();
+ }
+ public int getIflnaGain() {
+ return csReaderConnector.rfidReader.getIflnaGain();
+ }
+ public int getAgcGain() {
+ return csReaderConnector.rfidReader.getAgcGain();
+ }
+ public int getRxGain() {
+ return csReaderConnector.rfidReader.getRxGain();
+ }
+ public boolean setRxGain(int highCompression, int rflnagain, int iflnagain, int agcgain) {
+ return csReaderConnector.rfidReader.setRxGain(highCompression, rflnagain, iflnagain, agcgain);
+ }
+ public boolean setRxGain(int rxGain) {
+ return csReaderConnector.rfidReader.setRxGain(rxGain);
+ }
+ public int FreqChnCnt() {
+ return csReaderConnector.rfidReader.FreqChnCnt(csReaderConnector.rfidReader.regionCode);
+ }
+ public double getLogicalChannel2PhysicalFreq(int channel) {
+ return csReaderConnector.rfidReader.getLogicalChannel2PhysicalFreq(channel);
+ }
+ public byte getTagDelay() {
+ return csReaderConnector.rfidReader.getTagDelay();
+ }
+ public boolean setTagDelay(byte tagDelay) {
+ return csReaderConnector.rfidReader.setTagDelay(tagDelay);
+ }
+ public byte getIntraPkDelay() {
+ return csReaderConnector.rfidReader.getIntraPkDelay();
+ }
+ public boolean setIntraPkDelay(byte intraPkDelay) {
+ return csReaderConnector.rfidReader.setIntraPkDelay(intraPkDelay);
+ }
+ public byte getDupDelay() {
+ return csReaderConnector.rfidReader.getDupDelay();
+ }
+ public boolean setDupDelay(byte dupElim) {
+ return csReaderConnector.rfidReader.setDupDelay(dupElim);
+ }
+ public long getCycleDelay() {
+ return csReaderConnector.rfidReader.getCycleDelay();
+ }
+ public boolean setCycleDelay(long cycleDelay) {
+ return csReaderConnector.rfidReader.setCycleDelay(cycleDelay);
+ }
+ public void getAuthenticateReplyLength() {
+ csReaderConnector.rfidReader.getAuthenticateReplyLength();
+ }
+ public boolean setTamConfiguration(boolean header, String matchData) {
+ return csReaderConnector.rfidReader.setTamConfiguration(header, matchData);
+ }
+ public boolean setTam1Configuration(int keyId, String matchData) {
+ return csReaderConnector.rfidReader.setTam1Configuration(keyId, matchData);
+ }
+ public boolean setTam2Configuration(int keyId, String matchData, int profile, int offset, int blockId, int protMode) {
+ return csReaderConnector.rfidReader.setTam2Configuration(keyId, matchData, profile, offset, blockId, protMode);
+ }
+ public int getUntraceableEpcLength() {
+ return csReaderConnector.rfidReader.getUntraceableEpcLength();
+ }
+ public boolean setUntraceable(boolean bHideEpc, int ishowEpcSize, int iHideTid, boolean bHideUser, boolean bHideRange) {
+ return csReaderConnector.rfidReader.setUntraceable(bHideEpc, ishowEpcSize, iHideTid, bHideUser, bHideRange);
+ }
+ public boolean setUntraceable(int range, boolean user, int tid, int epcLength, boolean epc, boolean uxpc) {
+ return csReaderConnector.rfidReader.setUntraceable(range, user, tid, epcLength, epc, uxpc);
+ }
+ public boolean setAuthenticateConfiguration() {
+ return csReaderConnector.rfidReader.setAuthenticateConfiguration();
+ }
+ public int getRetryCount() {
+ return csReaderConnector.rfidReader.getRetryCount();
+ }
+ public boolean setRetryCount(int retryCount) {
+ return csReaderConnector.rfidReader.setRetryCount(retryCount);
+ }
+ public int getInvSelectIndex() {
+ return csReaderConnector.rfidReader.getInvSelectIndex();
+ }
+ public boolean getSelectEnable() {
+ return csReaderConnector.rfidReader.getSelectEnable();
+ }
+ public int getSelectTarget() {
+ return csReaderConnector.rfidReader.getSelectTarget();
+ }
+ public int getSelectAction() {
+ return csReaderConnector.rfidReader.getSelectAction();
+ }
+ public int getSelectMaskBank() {
+ return csReaderConnector.rfidReader.getSelectMaskBank();
+ }
+ public int getSelectMaskOffset() {
+ return csReaderConnector.rfidReader.getSelectMaskOffset();
+ }
+ public String getSelectMaskData() {
+ return csReaderConnector.rfidReader.getSelectMaskData();
+ }
+ public boolean setInvSelectIndex(int invSelect) {
+ return csReaderConnector.rfidReader.setInvSelectIndex(invSelect);
+ }
+ public boolean setSelectCriteriaDisable(int index) {
+ if (utility.DEBUG_SELECT) appendToLog("Debug_Select: Cs710Library4A.setSelectCriteriaDisable[" + index + "] goes to setSelectCriteriaDisable");
+ return csReaderConnector.rfidReader.setSelectCriteriaDisable(index);
+ }
+ int findFirstEmptySelect() {
+ return csReaderConnector.rfidReader.findFirstEmptySelect();
+ }
+ public boolean setSelectCriteria(int index, boolean enable, int target, int action, int bank, int offset, String mask, boolean maskbit) {
+ return csReaderConnector.rfidReader.setSelectCriteria(index, enable, target, action, bank, offset, mask, maskbit);
+ }
+ public boolean setSelectCriteria(int index, boolean enable, int target, int action, int delay, int bank, int offset, String mask) {
+ return csReaderConnector.rfidReader.setSelectCriteria(index, enable, target, action, delay, bank, offset, mask);
+ }
+ public boolean getRssiFilterEnable() {
+ return csReaderConnector.rfidReader.getRssiFilterEnable();
+ }
+ public int getRssiFilterType() {
+ return csReaderConnector.rfidReader.getRssiFilterType();
+ }
+ public int getRssiFilterOption() {
+ return csReaderConnector.rfidReader.getRssiFilterOption();
+ }
+ public boolean setRssiFilterConfig(boolean enable, int rssiFilterType, int rssiFilterOption) {
+ return csReaderConnector.rfidReader.setRssiFilterConfig(enable, rssiFilterType, rssiFilterOption);
+ }
+ public double getRssiFilterThreshold1() {
+ return csReaderConnector.rfidReader.getRssiFilterThreshold1();
+ }
+ public double getRssiFilterThreshold2() {
+ return csReaderConnector.rfidReader.getRssiFilterThreshold2();
+ }
+ public boolean setRssiFilterThreshold(double rssiFilterThreshold1, double rssiFilterThreshold2) {
+ return csReaderConnector.rfidReader.setRssiFilterThreshold(rssiFilterThreshold1, rssiFilterThreshold2);
+ }
+ public long getRssiFilterCount() {
+ return csReaderConnector.rfidReader.getRssiFilterCount();
+ }
+ public boolean setRssiFilterCount(long rssiFilterCount) {
+ return csReaderConnector.rfidReader.setRssiFilterCount(rssiFilterCount);
+ }
+ public boolean getInvMatchEnable() {
+ return csReaderConnector.rfidReader.getInvMatchEnable();
+ }
+ public boolean getInvMatchType() {
+ return csReaderConnector.rfidReader.getInvMatchType();
+ }
+ public int getInvMatchOffset() {
+ return csReaderConnector.rfidReader.getInvMatchOffset();
+ }
+ public String getInvMatchData() {
+ return csReaderConnector.rfidReader.getInvMatchData();
+ }
+ public boolean setPostMatchCriteria(boolean enable, boolean target, int offset, String mask) {
+ return csReaderConnector.rfidReader.setPostMatchCriteria(enable, target, offset, mask);
+ }
+ public int mrfidToWriteSize() {
+ if (isBleConnected() == false) return -1;
+ if (csReaderConnector.rfidReader == null) return -1;
+ return csReaderConnector.rfidReader.rfidToWriteSize();
+ }
+ public void mrfidToWritePrint() {
+ if (true) { csReaderConnector.rfidReader.rfidToWriteSize(); return; }
+ for (int i = 0; i < csReaderConnector.rfidReader.mRfidToWrite.size(); i++) {
+ appendToLog(byteArrayToString(csReaderConnector.rfidReader.mRfidToWrite.get(i).dataValues));
+ }
+ }
+ public long getTagRate() {
+ return csReaderConnector.rfidReader.getTagRate();
+ }
+ public boolean startOperation(RfidReaderChipData.OperationTypes operationTypes) {
+ return csReaderConnector.rfidReader.startOperation(operationTypes);
+ }
+ public boolean abortOperation() {
+ return csReaderConnector.rfidReader.abortOperation();
+ }
+ public void restoreAfterTagSelect() {
+ if (!isBleConnected()) return;
+ if (utility.DEBUG_SELECT) appendToLog("Debug_Select: Cs710Library4A.restoreAfterTagSelect goes to setSelectCriteriaDisable");
+ setSelectCriteriaDisable(0); setSelectCriteriaDisable(1); setSelectCriteriaDisable(2);
+ loadSetting1File();
+ setAccessCount(0);
+ setRx000AccessPassword("00000000");
+ if (true) {
+ setMatchRep(0);
+ setTagDelay(csReaderConnector.rfidReader.tagDelaySetting);
+ setCycleDelay(csReaderConnector.rfidReader.cycleDelaySetting);
+ setInvModeCompact(true);
+ }
+ if (csReaderConnector.rfidReader.postMatchDataChanged) {
+ csReaderConnector.rfidReader.postMatchDataChanged = false;
+ setPostMatchCriteria(csReaderConnector.rfidReader.postMatchDataOld.enable, csReaderConnector.rfidReader.postMatchDataOld.target, csReaderConnector.rfidReader.postMatchDataOld.offset, csReaderConnector.rfidReader.postMatchDataOld.mask);
+ appendToLog("PowerLevel");
+ setPowerLevel(csReaderConnector.rfidReader.postMatchDataOld.pwrlevel);
+ appendToLog("writeBleStreamOut: invAlgo = " + csReaderConnector.rfidReader.postMatchDataOld.invAlgo); setInvAlgo1(csReaderConnector.rfidReader.postMatchDataOld.invAlgo);
+ setQValue1(csReaderConnector.rfidReader.postMatchDataOld.qValue);
+ }
+ }
+ public boolean setSelectedTagByTID(String strTagId, long pwrlevel) {
+ return csReaderConnector.rfidReader.setSelectedTagByTID(strTagId, pwrlevel);
+ }
+ public boolean setSelectedTag(String strTagId, int selectBank, long pwrlevel) {
+ return csReaderConnector.rfidReader.setSelectedTag(strTagId, selectBank, pwrlevel);
+ }
+ public boolean setSelectedTag(String selectMask, int selectBank, int selectOffset, long pwrlevel, int qValue, int matchRep) {
+ return csReaderConnector.rfidReader.setSelectedTag4Access(false, selectMask, selectBank, selectOffset, pwrlevel, qValue, matchRep);
+ }
+ public boolean setMatchRep(int matchRep) {
+ if (utility.DEBUG_INVCFG) appendToLog("Debug_InvCfg: Cs710Library4A.setMatchRep goes to setMatchRep with matchRep = " + matchRep);
+ return csReaderConnector.rfidReader.setMatchRep(matchRep);
+ }
+ public String[] getCountryList() {
+ return csReaderConnector.rfidReader.getCountryList();
+ }
+ public int getCountryNumberInList() {
+ return csReaderConnector.rfidReader.countryInList;
+ }
+ public boolean setCountryInList(int countryInList) {
+ return csReaderConnector.rfidReader.setCountryInList(countryInList);
+ }
+ public boolean getChannelHoppingStatus() {
+ return csReaderConnector.rfidReader.getChannelHoppingStatus();
+ }
+ public boolean setChannelHoppingStatus(boolean channelOrderHopping) {
+ return csReaderConnector.rfidReader.setChannelHoppingStatus(channelOrderHopping);
+ }
+ public String[] getChannelFrequencyList() {
+ return csReaderConnector.rfidReader.getChannelFrequencyList();
+ }
+ public int getChannel() {
+ return csReaderConnector.settingData.channel;
+ }
+ public boolean setChannel(int channelSelect) {
+ return csReaderConnector.rfidReader.setChannel(channelSelect);
+ }
+ public byte getPopulation2Q(int population) {
+ return csReaderConnector.rfidReader.getPopulation2Q(population);
+ }
+ public int getPopulation() {
+ return csReaderConnector.rfidReader.getPopulation();
+ }
+ public boolean setPopulation(int population) {
+ return csReaderConnector.rfidReader.setPopulation(population);
+ }
+ public byte getQValue() {
+ return csReaderConnector.rfidReader.qValueSetting;
+ }
+ public boolean setQValue(byte byteValue) {
+ return csReaderConnector.rfidReader.setQValue(byteValue);
+ }
+ int getQValue1() {
+ return csReaderConnector.rfidReader.getQValue();
+ }
+ boolean setQValue1(int iValue) {
+ return csReaderConnector.rfidReader.setQValue1(iValue);
+ }
+ public RfidReaderChipData.Rx000pkgData onRFIDEvent() {
+ return csReaderConnector.rfidReader.onRFIDEvent();
+ }
+ public String getModelNumber() {
+ return csReaderConnector.rfidReader.getModelNumber(getModelName());
+ }
+ public boolean setRx000KillPassword(String password) {
+ return csReaderConnector.rfidReader.setRx000KillPassword(password);
+ }
+ public boolean setRx000AccessPassword(String password) {
+ return csReaderConnector.rfidReader.setRx000AccessPassword(password);
+ }
+ public boolean setAccessRetry(boolean accessVerfiy, int accessRetry) {
+ return csReaderConnector.rfidReader.setAccessRetry(accessVerfiy, accessRetry);
+ }
+ public boolean setInvModeCompact(boolean invModeCompact) {
+ if (utility.DEBUG_COMPACT) appendToLog("Debug_Compact: Cs710Library4A.setInvModeCompact goes to setInvModeCompact");
+ return csReaderConnector.rfidReader.setInvModeCompact(invModeCompact);
+ }
+ public boolean setAccessLockAction(int accessLockAction, int accessLockMask) {
+ return csReaderConnector.rfidReader.setAccessLockAction(accessLockAction, accessLockMask);
+ }
+ public boolean setAccessBank(int accessBank) {
+ return csReaderConnector.rfidReader.setAccessBank(accessBank);
+ }
+ public boolean setAccessBank(int accessBank, int accessBank2) {
+ return csReaderConnector.rfidReader.setAccessBank(accessBank, accessBank2);
+ }
+ public boolean setAccessOffset(int accessOffset) {
+ return csReaderConnector.rfidReader.setAccessOffset(accessOffset);
+ }
+ public boolean setAccessOffset(int accessOffset, int accessOffset2) {
+ return csReaderConnector.rfidReader.setAccessOffset(accessOffset, accessOffset2);
+ }
+ public boolean setAccessCount(int accessCount) {
+ return csReaderConnector.rfidReader.setAccessCount(accessCount);
+ }
+ public boolean setAccessCount(int accessCount, int accessCount2) {
+ return csReaderConnector.rfidReader.setAccessCount(accessCount, accessCount2);
+ }
+ public boolean setAccessWriteData(String dataInput) {
+ return csReaderConnector.rfidReader.setAccessWriteData(dataInput);
+ }
+ public boolean setResReadNoReply(boolean resReadNoReply) {
+ return csReaderConnector.rfidReader.setResReadNoReply(resReadNoReply);
+ }
+ public boolean setTagRead(int tagRead) {
+ return csReaderConnector.rfidReader.setTagRead(tagRead);
+ }
+ public boolean setInvBrandId(boolean invBrandId) {
+ return csReaderConnector.rfidReader.setInvBrandId(invBrandId);
+ }
+ public boolean setInvAuthenticate(boolean invAuthenticate) {
+ return csReaderConnector.rfidReader.setInvAuthenticate(invAuthenticate);
+ }
+ public boolean sendHostRegRequestHST_CMD(RfidReaderChipData.HostCommands hostCommand) {
+ if (true) setInvModeCompact(false);
+ return csReaderConnector.rfidReader.sendHostRegRequestHST_CMD(hostCommand);
+ }
+ public boolean setPwrManagementMode(boolean bLowPowerStandby) {
+ if (isBleConnected() == false) return false;
+ return csReaderConnector.rfidReader.setPwrManagementMode(bLowPowerStandby);
+ }
+ public void macWrite(int address, long value) {
+ csReaderConnector.rfidReader.macWrite(address, value);
+ }
+ public void set_fdCmdCfg(int value) {
+ csReaderConnector.rfidReader.set_fdRegAddr(value);
+ }
+ public void set_fdRegAddr(int addr) {
+ csReaderConnector.rfidReader.set_fdRegAddr(addr);
+ }
+ public void set_fdWrite(int addr, long value) {
+ csReaderConnector.rfidReader.set_fdWrite(addr, value);
+ }
+ public void set_fdPwd(int value) {
+ csReaderConnector.rfidReader.set_fdPwd(value);
+ }
+ public void set_fdBlockAddr4GetTemperature(int addr) {
+ csReaderConnector.rfidReader.set_fdBlockAddr4GetTemperature(addr);
+ }
+ public void set_fdReadMem(int addr, long len) {
+ csReaderConnector.rfidReader.set_fdReadMem(addr, len);
+ }
+ public void set_fdWriteMem(int addr, int len, long value) {
+ csReaderConnector.rfidReader.set_fdWriteMem(addr, len, value);
+ }
+ public void setImpinJExtension(boolean tagFocus, boolean fastId) {
+ csReaderConnector.rfidReader.setImpinJExtension(tagFocus, fastId);
+ }
+
+ //============ Barcode ============
+ public void getBarcodePreSuffix() {
+ barcodeNewland.getBarcodePreSuffix();
+ }
+ public void getBarcodeReadingMode() {
+ barcodeNewland.barcodeSendQueryReadingMode();
+ }
+ void getBarcodeEnable2dBarCodes() {
+ barcodeNewland.barcodeSendQueryEnable2dBarCodes();
+ }
+ void getBarcodePrefixOrder() {
+ barcodeNewland.barcodeSendQueryPrefixOrder();
+ }
+ void getBarcodeDelayTimeOfEachReading() {
+ barcodeNewland.barcodeSendQueryDelayTimeOfEachReading();
+ }
+ void getBarcodeNoDuplicateReading() {
+ barcodeNewland.barcodeSendQueryNoDuplicateReading();
+ }
+
+ public boolean isBarcodeFailure() {
+ if (barcodeConnector == null) return false;
+ return barcodeConnector.barcodeFailure;
+ }
+ public String getBarcodeDate() {
+ return barcodeNewland.getBarcodeDate();
+ }
+ public boolean getBarcodeOnStatus() {
+ if (barcodeConnector == null) return false;
+ return barcodeConnector.getOnStatus();
+ }
+ public boolean setBarcodeOn(boolean on) {
+ boolean retValue;
+ BarcodeConnector.CsReaderBarcodeData csReaderBarcodeData = new BarcodeConnector.CsReaderBarcodeData();
+ if (on) csReaderBarcodeData.barcodePayloadEvent = BarcodeConnector.BarcodePayloadEvents.BARCODE_POWER_ON;
+ else csReaderBarcodeData.barcodePayloadEvent = BarcodeConnector.BarcodePayloadEvents.BARCODE_POWER_OFF;
+ csReaderBarcodeData.waitUplinkResponse = false;
+ retValue = barcodeConnector.barcodeToWrite.add(csReaderBarcodeData); appendToLog("barcodeToWrite added with size = " + barcodeConnector.barcodeToWrite.size());
+ if (DEBUG_FILE) appendToLog("add " + csReaderBarcodeData.barcodePayloadEvent.toString() + " to barcodeToWrite with length = " + barcodeConnector.barcodeToWrite.size());
+ boolean continuousAfterOn = false;
+ if (retValue && on && continuousAfterOn) {
+ if (checkHostProcessorVersion(getBluetoothICFirmwareVersion(), 1, 0, 2)) {
+ if (DEBUG) appendToLog("to barcodeSendCommandConinuous()");
+ retValue = barcodeNewland.barcodeSendCommandConinuous();
+ } else retValue = false;
+ }
+ if (DEBUG) appendToLog("barcodeToWrite size = " + barcodeConnector.barcodeToWrite.size());
+ return retValue;
+ }
+ int iModeSet = -1, iVibratieTimeSet = -1;
+ public boolean setVibrateOn(int mode) {
+ boolean retValue;
+ if (true) appendToLog("setVibrateOn with mode = " + mode + ", and isInventoring = " + csReaderConnector.rfidReader.isInventoring());
+ if (csReaderConnector.rfidReader.isInventoring()) return false;
+ BarcodeConnector.CsReaderBarcodeData csReaderBarcodeData = new BarcodeConnector.CsReaderBarcodeData();
+ if (mode > 0) csReaderBarcodeData.barcodePayloadEvent = BarcodeConnector.BarcodePayloadEvents.BARCODE_VIBRATE_ON;
+ else csReaderBarcodeData.barcodePayloadEvent = BarcodeConnector.BarcodePayloadEvents.BARCODE_VIBRATE_OFF;
+ csReaderBarcodeData.waitUplinkResponse = false;
+ if (iModeSet == mode && iVibratieTimeSet == getVibrateTime()) {
+ appendToLog("writeBleStreamOut: A7B3: Skip saving vibration data");
+ return true;
+ }
+ if (mode > 0) {
+ byte[] barcodeCommandData = new byte[3];
+ barcodeCommandData[0] = (byte) (mode - 1);
+ barcodeCommandData[1] = (byte) (getVibrateTime() / 256);
+ barcodeCommandData[2] = (byte) (getVibrateTime() % 256);
+ csReaderBarcodeData.dataValues = barcodeCommandData;
+ }
+ retValue = barcodeConnector.barcodeToWrite.add(csReaderBarcodeData); appendToLog("barcodeToWrite added with size = " + barcodeConnector.barcodeToWrite.size());
+ if (DEBUG) appendToLog("barcodeToWrite size = " + barcodeConnector.barcodeToWrite.size());
+ if (retValue) {
+ iModeSet = mode; iVibratieTimeSet = getVibrateTime();
+ }
+ return retValue;
+ }
+ public boolean getInventoryVibrate() {
+ return csReaderConnector.settingData.inventoryVibrate;
+ }
+ public boolean setInventoryVibrate(boolean inventoryVibrate) {
+ boolean DEBUG = false;
+ if (DEBUG) appendToLog("this.inventoryVibrate = " + csReaderConnector.settingData.inventoryVibrate + ", inventoryVibrate = " + inventoryVibrate);
+ csReaderConnector.settingData.inventoryVibrate = inventoryVibrate;
+ if (DEBUG) appendToLog("this.inventoryVibrate = " + csReaderConnector.settingData.inventoryVibrate + ", inventoryVibrate = " + inventoryVibrate);
+ return true;
+ }
+ public int getVibrateTime() {
+ return csReaderConnector.settingData.vibrateTimeSetting;
+ }
+ public boolean setVibrateTime(int vibrateTime) {
+ csReaderConnector.settingData.vibrateTimeSetting = vibrateTime;
+ return true;
+ }
+ public int getVibrateWindow() {
+ return csReaderConnector.settingData.vibrateWindowSetting;
+ }
+ public boolean setVibrateWindow(int vibrateWindow) {
+ csReaderConnector.settingData.vibrateWindowSetting = vibrateWindow;
+ return true;
+ }
+ public boolean barcodeSendCommandTrigger() {
+ return barcodeNewland.barcodeSendCommandTrigger();
+ }
+ public boolean barcodeSendCommandSetPreSuffix() {
+ return barcodeNewland.barcodeSendCommandSetPreSuffix();
+ }
+ public boolean barcodeSendCommandResetPreSuffix() {
+ return barcodeNewland.barcodeSendCommandResetPreSuffix();
+ }
+ public boolean barcodeSendCommandConinuous() {
+ return barcodeNewland.barcodeSendCommandConinuous();
+ }
+ public String getBarcodeVersion() {
+ return barcodeNewland.getBarcodeVersion();
+ }
+ public String getBarcodeSerial() {
+ return barcodeNewland.getBarcodeSerial();
+ }
+ boolean barcodeAutoStarted = false;
+ public boolean barcodeInventory(boolean start) {
+ boolean result = true;
+ appendToLog("TTestPoint 0: " + start);
+ if (start) {
+ barcodeConnector.mBarcodeToRead.clear(); barcodeDataStore = null;
+ if (getBarcodeOnStatus() == false) { result = setBarcodeOn(true); appendToLog("TTestPoint 1"); }
+ if (csReaderConnector.settingData.barcode2TriggerMode && result) {
+ if (getTriggerButtonStatus() && notificationConnector.getAutoBarStartSTop()) { appendToLog("TTestPoint 2"); barcodeAutoStarted = true; result = true; }
+ else { appendToLog("TTestPoint 3"); result = barcodeNewland.barcodeSendCommand(new byte[]{0x1b, 0x33}); }
+ } else appendToLog("TTestPoint 4");
+ appendToLog("TTestPoint 5");
+ } else {
+ appendToLog("getBarcodeOnStatus = " + getBarcodeOnStatus() + ", result = " + result);
+ if (csReaderConnector.settingData.barcode2TriggerMode == false) { appendToLog("TTestPoint 6"); result = setBarcodeOn(false); }
+ else if (getBarcodeOnStatus() == false && result) { appendToLog("TTestPoint 7"); result = setBarcodeOn(true); }
+ appendToLog("barcode2TriggerMode = " + csReaderConnector.settingData.barcode2TriggerMode + ", result = " + result + ", barcodeAutoStarted = " + barcodeAutoStarted);
+ if (csReaderConnector.settingData.barcode2TriggerMode && result) {
+ if (barcodeAutoStarted && result) { appendToLog("TTestPoint 8"); barcodeAutoStarted = false; result = true; }
+ else { appendToLog("TTestPoint 9"); result = barcodeNewland.barcodeSendCommand(new byte[] { 0x1b, 0x30 }); }
+ } else appendToLog("TTestPoint 10");
+ }
+ return result;
+ }
+ byte[] barcodeDataStore = null; long timeBarcodeData;
+ public byte[] onBarcodeEvent() {
+ byte[] barcodeData = null;
+ if (barcodeConnector.mBarcodeToRead.size() != 0) {
+ BarcodeConnector.CsReaderBarcodeData csReaderBarcodeData = barcodeConnector.mBarcodeToRead.get(0);
+ barcodeConnector.mBarcodeToRead.remove(0);
+ if (csReaderBarcodeData != null) {
+ if (csReaderBarcodeData.barcodePayloadEvent == BarcodeConnector.BarcodePayloadEvents.BARCODE_GOOD_READ) {
+ if (false) barcodeData = "".getBytes();
+ } else if (csReaderBarcodeData.barcodePayloadEvent == BarcodeConnector.BarcodePayloadEvents.BARCODE_DATA_READ) {
+ barcodeData = csReaderBarcodeData.dataValues;
+ }
+ }
+ }
+
+ byte[] barcodeCombined = null;
+ if (false) barcodeCombined = barcodeData;
+ else if (barcodeData != null) {
+ appendToLog("BarStream: barcodeData = " + byteArrayToString(barcodeData) + ", barcodeDataStore = " + byteArrayToString(barcodeDataStore));
+ int barcodeDataStoreIndex = 0;
+ int length = barcodeData.length;
+ if (barcodeDataStore != null) {
+ barcodeDataStoreIndex = barcodeDataStore.length;
+ length += barcodeDataStoreIndex;
+ }
+ barcodeCombined = new byte[length];
+ if (barcodeDataStore != null)
+ System.arraycopy(barcodeDataStore, 0, barcodeCombined, 0, barcodeDataStore.length);
+ System.arraycopy(barcodeData, 0, barcodeCombined, barcodeDataStoreIndex, barcodeData.length);
+ barcodeDataStore = barcodeCombined;
+ timeBarcodeData = System.currentTimeMillis();
+ barcodeCombined = new byte[0];
+ }
+ if (barcodeDataStore != null) {
+ barcodeCombined = new byte[barcodeDataStore.length];
+ System.arraycopy(barcodeDataStore, 0, barcodeCombined, 0, barcodeCombined.length);
+
+ if (System.currentTimeMillis() - timeBarcodeData < 300) barcodeCombined = null;
+ else barcodeDataStore = null;
+ }
+ if (barcodeCombined != null && barcodeNewland.getPrefix() != null && barcodeNewland.getSuffix() != null) {
+ if (barcodeCombined.length == 0) barcodeCombined = null;
+ else {
+ byte[] prefixExpected = barcodeNewland.getPrefix(); boolean prefixFound = false;
+ byte[] suffixExpected = barcodeNewland.getSuffix(); boolean suffixFound = false;
+ int codeTypeLength = 4;
+ appendToLog("BarStream: barcodeCombined = " + byteArrayToString(barcodeCombined) + ", Expected Prefix = " + byteArrayToString(prefixExpected) + ", Expected Suffix = " + byteArrayToString(suffixExpected));
+ if (barcodeCombined.length > prefixExpected.length + suffixExpected.length + codeTypeLength) {
+ int i = 0;
+ for (; i <= barcodeCombined.length - prefixExpected.length - suffixExpected.length; i++) {
+ int j = 0;
+ for (; j < prefixExpected.length; j++) {
+ if (barcodeCombined[i+j] != prefixExpected[j]) break;
+ }
+ if (j == prefixExpected.length) { prefixFound = true; break; }
+ }
+ int k = i + prefixExpected.length;
+ for (; k <= barcodeCombined.length - suffixExpected.length; k++) {
+ int j = 0;
+ for (; j < suffixExpected.length; j++) {
+ if (barcodeCombined[k+j] != suffixExpected[j]) break;
+ }
+ if (j == suffixExpected.length) { suffixFound = true; break; }
+ }
+ appendToLog("BarStream: iPrefix = " + i + ", iSuffix = " + k + ", with prefixFound = " + prefixFound + ", suffixFound = " + suffixFound);
+ if (prefixFound && suffixFound) {
+ byte[] barcodeCombinedNew = new byte[k - i - prefixExpected.length - codeTypeLength];
+ System.arraycopy(barcodeCombined, i + prefixExpected.length + codeTypeLength, barcodeCombinedNew, 0, barcodeCombinedNew.length);
+ barcodeCombined = barcodeCombinedNew;
+ appendToLog("BarStream: barcodeCombinedNew = " + byteArrayToString(barcodeCombinedNew));
+
+ if (true) {
+ byte[] prefixExpected1 = {0x5B, 0x29, 0x3E, 0x1E};
+ prefixFound = false;
+ byte[] suffixExpected1 = {0x1E, 0x04};
+ suffixFound = false;
+ appendToLog("BarStream: barcodeCombined = " + byteArrayToString(barcodeCombined) + ", Expected Prefix = " + byteArrayToString(prefixExpected1) + ", Expected Suffix = " + byteArrayToString(suffixExpected1));
+ if (barcodeCombined.length > prefixExpected1.length + suffixExpected1.length) {
+ i = 0;
+ for (; i <= barcodeCombined.length - prefixExpected1.length - suffixExpected1.length; i++) {
+ int j = 0;
+ for (; j < prefixExpected1.length; j++) {
+ if (barcodeCombined[i + j] != prefixExpected1[j]) break;
+ }
+ if (j == prefixExpected1.length) {
+ prefixFound = true;
+ break;
+ }
+ }
+ k = i + prefixExpected1.length;
+ for (; k <= barcodeCombined.length - suffixExpected1.length; k++) {
+ int j = 0;
+ for (; j < suffixExpected1.length; j++) {
+ if (barcodeCombined[k + j] != suffixExpected1[j]) break;
+ }
+ if (j == suffixExpected1.length) {
+ suffixFound = true;
+ break;
+ }
+ }
+ appendToLog("BarStream: iPrefix = " + i + ", iSuffix = " + k + ", with prefixFound = " + prefixFound + ", suffixFound = " + suffixFound);
+ if (prefixFound && suffixFound) {
+ barcodeCombinedNew = new byte[k - i - prefixExpected1.length];
+ System.arraycopy(barcodeCombined, i + prefixExpected1.length, barcodeCombinedNew, 0, barcodeCombinedNew.length);
+ barcodeCombined = barcodeCombinedNew;
+ appendToLog("BarStream: barcodeCombinedNew = " + byteArrayToString(barcodeCombinedNew));
+ }
+ }
+ }
+ }
+ } else barcodeCombined = null;
+ }
+ }
+ return barcodeCombined;
+ }
+
+ //============ Android General ============
+ public void setSameCheck(boolean sameCheck1) {
+ if (csReaderConnector.sameCheck == sameCheck1) return;
+ if (false) appendToLog("new sameCheck = " + sameCheck1 + ", with old sameCheck = " + csReaderConnector.sameCheck);
+ csReaderConnector.sameCheck = sameCheck1; //sameCheck = false;
+ }
+
+ public int getBeepCount() {
+ return csReaderConnector.settingData.beepCountSetting;
+ }
+ public boolean setBeepCount(int beepCount) {
+ csReaderConnector.settingData.beepCountSetting = beepCount;
+ return true;
+ }
+
+ public boolean getInventoryBeep() {
+ return csReaderConnector.settingData.inventoryBeep;
+ }
+ public boolean setInventoryBeep(boolean inventoryBeep) {
+ csReaderConnector.settingData.inventoryBeep = inventoryBeep;
+ return true;
+ }
+
+ public boolean getSaveFileEnable() {
+ return csReaderConnector.settingData.saveFileEnable;
+ }
+ public boolean setSaveFileEnable(boolean saveFileEnable) {
+ appendToLog("this.saveFileEnable = " + csReaderConnector.settingData.saveFileEnable + ", saveFileEnable = " + saveFileEnable);
+ csReaderConnector.settingData.saveFileEnable = saveFileEnable;
+ appendToLog("this.saveFileEnable = " + csReaderConnector.settingData.saveFileEnable + ", saveFileEnable = " + saveFileEnable);
+ return true;
+ }
+ public boolean getSaveCloudEnable() {
+ return csReaderConnector.settingData.saveCloudEnable;
+ }
+ public boolean setSaveCloudEnable(boolean saveCloudEnable) {
+ csReaderConnector.settingData.saveCloudEnable = saveCloudEnable;
+ return true;
+ }
+ public boolean getSaveNewCloudEnable() {
+ return csReaderConnector.settingData.saveNewCloudEnable;
+ }
+ public boolean setSaveNewCloudEnable(boolean saveNewCloudEnable) {
+ csReaderConnector.settingData.saveNewCloudEnable = saveNewCloudEnable;
+ return true;
+ }
+ public boolean getSaveAllCloudEnable() {
+ return csReaderConnector.settingData.saveAllCloudEnable;
+ }
+ public boolean setSaveAllCloudEnable(boolean saveAllCloudEnable) {
+ csReaderConnector.settingData.saveAllCloudEnable = saveAllCloudEnable;
+ return true;
+ }
+ public boolean getUserDebugEnable() {
+ boolean bValue = csReaderConnector.settingData.userDebugEnable; appendToLog("bValue = " + bValue); return bValue;
+ }
+ public boolean setUserDebugEnable(boolean userDebugEnable) {
+ appendToLog("new userDebug = " + userDebugEnable);
+ csReaderConnector.settingData.userDebugEnable = userDebugEnable;
+ return true;
+ }
+ public String getForegroundReader() {
+ return csReaderConnector.settingData.strForegroundReader;
+ }
+ public boolean getForegroundServiceEnable() {
+ String string = csReaderConnector.settingData.strForegroundReader;
+ return (string.trim().length() == 0 ? false : true);
+ }
+ public boolean setForegroundServiceEnable(boolean bForegroundService) {
+ if (bForegroundService) csReaderConnector.settingData.strForegroundReader = csReaderConnector.bluetoothGatt.getReaderDeviceConnected().getAddress();
+ else csReaderConnector.settingData.strForegroundReader = "";
+ return true;
+ }
+ public String getServerLocation() {
+ return csReaderConnector.settingData.serverLocation;
+ }
+ public boolean setServerLocation(String serverLocation) {
+ csReaderConnector.settingData.serverLocation = serverLocation;
+ return true;
+ }
+ public int getServerTimeout() {
+ return csReaderConnector.settingData.serverTimeout;
+ }
+ public boolean setServerTimeout(int serverTimeout) {
+ csReaderConnector.settingData.serverTimeout = serverTimeout;
+ return true;
+ }
+ public String getServerMqttLocation() {
+ return csReaderConnector.settingData.serverMqttLocation;
+ }
+ public boolean setServerMqttLocation(String serverLocation) {
+ csReaderConnector.settingData.serverMqttLocation = serverLocation;
+ return true;
+ }
+ public String getTopicMqtt() {
+ return csReaderConnector.settingData.topicMqtt;
+ }
+ public boolean setTopicMqtt(String topicMqtt) {
+ csReaderConnector.settingData.topicMqtt = topicMqtt;
+ return true;
+ }
+ public int getForegroundDupElim() {
+ return csReaderConnector.settingData.iForegroundDupElim;
+ }
+ public boolean setForegroundDupElim(int iForegroundDupElim) {
+ csReaderConnector.settingData.iForegroundDupElim = iForegroundDupElim;
+ return true;
+ }
+ public int getInventoryCloudSave() {
+ return csReaderConnector.settingData.inventoryCloudSave;
+ }
+ public boolean setInventoryCloudSave(int inventoryCloudSave) {
+ csReaderConnector.settingData.inventoryCloudSave = inventoryCloudSave;
+ return true;
+ }
+ public String getServerImpinjLocation() {
+ return csReaderConnector.settingData.serverImpinjLocation;
+ }
+ public boolean setServerImpinjLocation(String serverImpinjLocation) {
+ csReaderConnector.settingData.serverImpinjLocation = serverImpinjLocation;
+ return true;
+ }
+ public String getServerImpinjName() {
+ appendToLog("serverImpinjName = " + csReaderConnector.settingData.serverImpinjName);
+ return csReaderConnector.settingData.serverImpinjName;
+ }
+ public boolean setServerImpinjName(String serverImpinjName) {
+ csReaderConnector.settingData.serverImpinjName = serverImpinjName;
+ appendToLog("serverImpinjName = " + serverImpinjName);
+ return true;
+ }
+ public String getServerImpinjPassword() {
+ return csReaderConnector.settingData.serverImpinjPassword;
+ }
+ public boolean setServerImpinjPassword(String serverImpinjPassword) {
+ csReaderConnector.settingData.serverImpinjPassword = serverImpinjPassword;
+ return true;
+ }
+ public int getBatteryDisplaySetting() {
+ return csReaderConnector.settingData.batteryDisplaySelect;
+ }
+ public boolean setBatteryDisplaySetting(int batteryDisplaySelect) {
+ return csReaderConnector.settingData.setBatteryDisplaySetting(batteryDisplaySelect);
+ }
+ public double dBuV_dBm_constant = RfidReader.dBuV_dBm_constant; //106.98;
+ public int getRssiDisplaySetting() {
+ return csReaderConnector.settingData.rssiDisplaySelect;
+ }
+ public boolean setRssiDisplaySetting(int rssiDisplaySelect) {
+ return csReaderConnector.settingData.setRssiDisplaySetting(rssiDisplaySelect);
+ }
+ public int getVibrateModeSetting() {
+ return csReaderConnector.settingData.vibrateModeSelect;
+ }
+ public boolean setVibrateModeSetting(int vibrateModeSelect) {
+ if (vibrateModeSelect < 0 || vibrateModeSelect > 1) return false;
+ csReaderConnector.settingData.vibrateModeSelect = vibrateModeSelect;
+ return true;
+ }
+ public int getSavingFormatSetting() {
+ return csReaderConnector.settingData.savingFormatSelect;
+ }
+ public boolean setSavingFormatSetting(int savingFormatSelect) {
+ if (false) appendToLog("savingFormatSelect = " + savingFormatSelect);
+ if (savingFormatSelect < 0 || savingFormatSelect > 1) return false;
+ csReaderConnector.settingData.savingFormatSelect = savingFormatSelect;
+ return true;
+ }
+ public int getCsvColumnSelectSetting() {
+ return csReaderConnector.settingData.csvColumnSelect;
+ }
+ public boolean setCsvColumnSelectSetting(int csvColumnSelect) {
+ csReaderConnector.settingData.csvColumnSelect = csvColumnSelect;
+ return true;
+ }
+ public String getWedgeDeviceName() {
+ return csReaderConnector.settingData.wedgeDeviceName;
+ }
+ public String getWedgeDeviceAddress() {
+ return csReaderConnector.settingData.wedgeDeviceAddress;
+ }
+ public int getWedgeDeviceUUID2p1() {
+ return csReaderConnector.settingData.wedgeDeviceUUID2p1;
+ }
+ public int getWedgePower() {
+ return csReaderConnector.settingData.wedgePower;
+ }
+ public String getWedgePrefix() {
+ return csReaderConnector.settingData.wedgePrefix;
+ }
+ public String getWedgeSuffix() {
+ return csReaderConnector.settingData.wedgeSuffix;
+ }
+ public int getWedgeDelimiter() {
+ return csReaderConnector.settingData.wedgeDelimiter;
+ }
+ public int getWedgeOutput() {
+ return csReaderConnector.settingData.wedgeOutput;
+ }
+ public void setWedgeDeviceName(String wedgeDeviceName) {
+ csReaderConnector.settingData.wedgeDeviceName = wedgeDeviceName;
+ }
+ public void setWedgeDeviceAddress(String wedgeDeviceAddress) {
+ csReaderConnector.settingData.wedgeDeviceAddress = wedgeDeviceAddress;
+ }
+ public void setWedgeDeviceUUID2p1(int wedgeDeviceUUID2p1) {
+ csReaderConnector.settingData.wedgeDeviceUUID2p1 = wedgeDeviceUUID2p1;;
+ }
+ public void setWedgePower(int iPower) {
+ csReaderConnector.settingData.wedgePower = iPower;
+ }
+ public void setWedgePrefix(String string) {
+ csReaderConnector.settingData.wedgePrefix = string;
+ }
+ public void setWedgeSuffix(String string) {
+ csReaderConnector.settingData.wedgeSuffix = string;
+ }
+ public void setWedgeDelimiter(int iValue) {
+ csReaderConnector.settingData.wedgeDelimiter = iValue;
+ }
+ public void setWedgeOutput(int iOutput) {
+ csReaderConnector.settingData.wedgeOutput = iOutput;
+ }
+ public void saveWedgeSetting2File() {
+ csReaderConnector.settingData.saveWedgeSetting2File();
+ }
+
+ //============ Bluetooth ============
+ public String getBluetoothICFirmwareVersion() {
+ return bluetoothConnector.getBluetoothIcVersion();
+ }
+ public String getBluetoothICFirmwareName() {
+ return bluetoothConnector.getBluetoothIcName();
+ }
+ public boolean setBluetoothICFirmwareName(String name) {
+ return bluetoothConnector.setBluetoothIcName(name);
+ }
+
+ //============ Controller ============
+ public String hostProcessorICGetFirmwareVersion() {
+ return controllerConnector.getVersion();
+ }
+ public String getHostProcessorICSerialNumber() {
+ String str;
+ if (bluetoothConnector.getCsModel() != 463) str = controllerConnector.getSerialNumber();
+ else str = csReaderConnector.rfidReader.getProductSerialNumber();
+ if (str != null) {
+ if (str.length() >= 16) return str.substring(0, 16);
+ }
+ return null;
+ }
+ public String getHostProcessorICBoardVersion() {
+ String str;
+ if (bluetoothConnector.getCsModel() != 463) str = controllerConnector.getSerialNumber();
+ else str = csReaderConnector.rfidReader.getProductSerialNumber();
+ if (false) appendToLog("str = " + str);
+ if (str == null) return null;
+ if (str.length() < 16+4) return null;
+ str = str.substring(16);
+ if (true) {
+ String string = "";
+ if (str.length() >= 1) string = str.substring(0,1);
+ if (str.length() >= 3) string += ("." + str.substring(1, 3));
+ if (str.length() >= 4) string += ("." + str.substring(3, 4));
+
+ if (false) {
+ if (str.length() >= 5) string += (", " + str.substring(4, 5));
+ if (str.length() >= 7) string += ("." + str.substring(5, 7));
+ if (str.length() >= 8) string += ("." + str.substring(7, 8));
+ }
+ str = string;
+ }
+ return str;
+ }
+
+ //============ Controller notification ============
+ int iBatteryCount;
+ int getBatteryValue2Percent(float floatValue) {
+ boolean DEBUG = false;
+ if (DEBUG) appendToLog("getHostProcessorICBoardVersion = " + getHostProcessorICBoardVersion() + ", strVersionMBoard = " + strVersionMBoard);
+ if (false || checkHostProcessorVersion(getHostProcessorICBoardVersion(), Integer.parseInt(strMBoardVersions[0].trim()), Integer.parseInt(strMBoardVersions[1].trim()), 0)) {
+ final float[] fValueStbyRef = {
+ (float) 4.212, (float) 4.175, (float) 4.154, (float) 4.133, (float) 4.112,
+ (float) 4.085, (float) 4.069, (float) 4.054, (float) 4.032, (float) 4.011,
+ (float) 3.990, (float) 3.969, (float) 3.953, (float) 3.937, (float) 3.922,
+ (float) 3.901, (float) 3.885, (float) 3.869, (float) 3.853, (float) 3.837,
+ (float) 3.821, (float) 3.806, (float) 3.790, (float) 3.774, (float) 3.769,
+ (float) 3.763, (float) 3.758, (float) 3.753, (float) 3.747, (float) 3.742,
+ (float) 3.732, (float) 3.721, (float) 3.705, (float) 3.684, (float) 3.668,
+ (float) 3.652, (float) 3.642, (float) 3.626, (float) 3.615, (float) 3.605,
+ (float) 3.594, (float) 3.584, (float) 3.568, (float) 3.557, (float) 3.542,
+ (float) 3.531, (float) 3.510, (float) 3.494, (float) 3.473, (float) 3.457,
+ (float) 3.436, (float) 3.410, (float) 3.362, (float) 3.235, (float) 2.987,
+ (float) 2.982
+ };
+ final float[] fPercentStbyRef = {
+ (float) 100, (float) 98, (float) 96, (float) 95, (float) 93,
+ (float) 91, (float) 89, (float) 87, (float) 85, (float) 84,
+ (float) 82, (float) 80, (float) 78, (float) 76, (float) 75,
+ (float) 73, (float) 71, (float) 69, (float) 67, (float) 65,
+ (float) 64, (float) 62, (float) 60, (float) 58, (float) 56,
+ (float) 55, (float) 53, (float) 51, (float) 49, (float) 47,
+ (float) 45, (float) 44, (float) 42, (float) 40, (float) 38,
+ (float) 36, (float) 35, (float) 33, (float) 31, (float) 29,
+ (float) 27, (float) 25, (float) 24, (float) 22, (float) 20,
+ (float) 18, (float) 16, (float) 15, (float) 13, (float) 11,
+ (float) 9, (float) 7, (float) 5, (float) 4, (float) 2,
+ (float) 0
+ };
+ final float[] fValueRunRef = {
+ (float) 4.106, (float) 4.017, (float) 3.98 , (float) 3.937, (float) 3.895,
+ (float) 3.853, (float) 3.816, (float) 3.779, (float) 3.742, (float) 3.711,
+ (float) 3.679, (float) 3.658, (float) 3.637, (float) 3.626, (float) 3.61 ,
+ (float) 3.584, (float) 3.547, (float) 3.515, (float) 3.484, (float) 3.457,
+ (float) 3.431, (float) 3.399, (float) 3.362, (float) 3.32 , (float) 3.251,
+ (float) 3.135
+ };
+ final float[] fPercentRunRef = {
+ (float) 100, (float) 96, (float) 92, (float) 88, (float) 84,
+ (float) 80, (float) 76, (float) 72, (float) 67, (float) 63,
+ (float) 59, (float) 55, (float) 51, (float) 47, (float) 43,
+ (float) 39, (float) 35, (float) 31, (float) 27, (float) 23,
+ (float) 19, (float) 15, (float) 11, (float) 7, (float) 2,
+ (float) 0
+ };
+ float[] fValueRef = fValueStbyRef;
+ float[] fPercentRef = fPercentStbyRef;
+
+ if (true && iBatteryCount != getBatteryCount()) {
+ iBatteryCount = getBatteryCount();
+ iBatteryNewCurveDelay++;
+ }
+ if (csReaderConnector.rfidReader.mRfidToWrite.size() != 0) iBatteryNewCurveDelay = 0;
+ else if (csReaderConnector.rfidReader.isInventoring()) {
+ if (bUsingInventoryBatteryCurve == false) { if (iBatteryNewCurveDelay > 1) { iBatteryNewCurveDelay = 0; bUsingInventoryBatteryCurve = true; } }
+ else iBatteryNewCurveDelay = 0;
+ } else if (bUsingInventoryBatteryCurve) { if (iBatteryNewCurveDelay > 2) { iBatteryNewCurveDelay = 0; bUsingInventoryBatteryCurve = false; } }
+ else iBatteryNewCurveDelay = 0;
+
+ if (bUsingInventoryBatteryCurve) {
+ fValueRef = fValueRunRef;
+ fPercentRef = fPercentRunRef;
+ }
+ if (DEBUG) appendToLog("NEW Percentage cureve is USED with bUsingInventoryBatteryCurve = " + bUsingInventoryBatteryCurve + ", iBatteryNewCurveDelay = " + iBatteryNewCurveDelay);
+
+ int index = 0;
+ while (index < fValueRef.length) {
+ if (floatValue > fValueRef[index]) break;
+ index++;
+ }
+ if (DEBUG) appendToLog("Index = " + index);
+ if (index == 0) return 100;
+ if (index == fValueRef.length) return 0;
+ float value = ((fValueRef[index - 1] - floatValue) / (fValueRef[index - 1] - fValueRef[index]));
+ if (true) {
+ value *= (fPercentRef[index -1] - fPercentRef[index]);
+ value = fPercentRef[index - 1] - value;
+ } else {
+ value += (float) (index - 1);
+ value /= (float) (fValueRef.length - 1);
+ value *= 100;
+ value = 100 - value;
+ }
+ value += 0.5;
+ int iValue = (int) (value);
+ if (iBatteryNewCurveDelay != 0) iValue = iBatteryPercentOld;
+ else if (bUsingInventoryBatteryCurve && floatValue <= fBatteryValueOld && iValue >= iBatteryPercentOld) iValue = iBatteryPercentOld;
+ fBatteryValueOld = floatValue; iBatteryPercentOld = iValue;
+ return iValue;
+ } else {
+ if (DEBUG) appendToLog("OLD Percentage cureve is USED");
+ if (floatValue >= 4) return 100;
+ else if (floatValue < 3.4) return 0;
+ else {
+ float result = (float) 166.67 * floatValue - (float) 566.67;
+ return (int) result;
+ }
+ }
+ }
+ public int getBatteryLevel() {
+ return csReaderConnector.getBatteryLevel();
+ }
+ public boolean setAutoTriggerReporting(byte timeSecond) {
+ return notificationConnector.setAutoTriggerReporting(timeSecond);
+ }
+ public boolean getAutoBarStartSTop() {
+ return notificationConnector.getAutoBarStartStopStatus();
+ }
+
+ public boolean batteryLevelRequest() {
+ if (csReaderConnector.rfidReader == null) return false;
+ if (notificationConnector == null) return false;
+ if (csReaderConnector.rfidReader.isInventoring()) {
+ appendToLog("Skip batteryLevelREquest as inventoring !!!");
+ return true;
+ }
+ if (mrfidToWriteSize() != 0) return false;
+ return notificationConnector.batteryLevelRequest();
+ }
+ public boolean setAutoBarStartSTop(boolean enable) {
+ return notificationConnector.setAutoBarStartSTop(enable);
+ }
+ public boolean getTriggerReporting() {
+ return csReaderConnector.settingData.triggerReporting;
+ }
+ public boolean setTriggerReporting(boolean triggerReporting) {
+ return notificationConnector.setTriggerReporting(triggerReporting);
+ }
+ public final int iNO_SUCH_SETTING = 10000;
+ public short getTriggerReportingCount() {
+ boolean bValue = false;
+ if (getcsModel() != 463) bValue = checkHostProcessorVersion(hostProcessorICGetFirmwareVersion(), 1, 0, 16);
+ if (bValue == false) return iNO_SUCH_SETTING; else
+ return csReaderConnector.settingData.triggerReportingCountSetting;
+ }
+ public boolean setTriggerReportingCount(short triggerReportingCount) {
+ return notificationConnector.setTriggerReportingCount(triggerReportingCount);
+ }
+ public String getBatteryDisplay(boolean voltageDisplay) {
+ float floatValue = (float) getBatteryLevel() / 1000;
+ if (floatValue == 0) return " ";
+ String retString = null;
+ if (voltageDisplay || (getBatteryDisplaySetting() == 0)) retString = String.format("%.3f V", floatValue);
+ else retString = (String.format("%d", getBatteryValue2Percent(floatValue)) + "%");
+ if (voltageDisplay == false) retString += String.format("\r\n P=%d", getPwrlevel());
+ return retString;
+ }
+ String strVersionMBoard = "1.8"; String[] strMBoardVersions = strVersionMBoard.split("\\.");
+ int iBatteryNewCurveDelay; boolean bUsingInventoryBatteryCurve = false; float fBatteryValueOld; int iBatteryPercentOld;
+ public String isBatteryLow() {
+ boolean batterylow = false;
+ int iValue = getBatteryLevel();
+ if (iValue == 0) return null;
+ float fValue = (float) iValue / 1000;
+ int iPercent = getBatteryValue2Percent(fValue);
+ if (checkHostProcessorVersion(getHostProcessorICBoardVersion(), Integer.parseInt(strMBoardVersions[0].trim()), Integer.parseInt(strMBoardVersions[1].trim()), 0)) {
+ if (true) {
+ if (csReaderConnector.rfidReader.isInventoring()) {
+ if (fValue < 3.520) batterylow = true;
+ } else if (bUsingInventoryBatteryCurve == false) {
+ if (fValue < 3.626) batterylow = true;
+ }
+ } else if (iPercent <= 20) batterylow = true;
+ } else if (true) {
+ if (csReaderConnector.rfidReader.isInventoring()) {
+ if (fValue < 3.45) batterylow = true;
+ } else if (bUsingInventoryBatteryCurve == false) {
+ if (fValue < 3.6) batterylow = true;
+ }
+ } else if (iPercent <= 8) batterylow = true;
+ if (batterylow) return String.valueOf(iPercent);
+ return null;
+ }
+ public int getBatteryCount() {
+ return csReaderConnector.csConnectorData.getVoltageCnt();
+ }
+ public boolean getTriggerButtonStatus() {
+ return notificationConnector.getTriggerStatus();
+ }
+ public int getTriggerCount() {
+ return csReaderConnector.csConnectorData.getTriggerCount();
+ }
+ //public interface NotificationListener { void onChange(); }
+ public void setNotificationListener(NotificationConnector.NotificationListener listener) {
+ notificationConnector.setNotificationListener0(listener);
+ }
+ public byte[] onNotificationEvent() {
+ byte[] notificationData = null;
+ if (notificationConnector == null) {
+ appendToLog("notificationConnector is null");
+ return null;
+ }
+ if (notificationConnector.notificationToRead.size() != 0) {
+ NotificationConnector.CsReaderNotificationData csReaderNotificationData = notificationConnector.notificationToRead.get(0);
+ notificationConnector.notificationToRead.remove(0);
+ if (csReaderNotificationData != null) notificationData = csReaderNotificationData.dataValues;
+ }
+ return notificationData;
+ }
+
+ //============ to be modified ============
+ String getModelName() {
+ return csReaderConnector.getModelName();
+ }
+ public String getSerialNumber() {
+ return csReaderConnector.rfidReader.getSerialNumber();
+ }
+ public boolean setRfidOn(boolean onStatus) {
+ return csReaderConnector.rfidReader.turnOn(onStatus);
+ }
+ private final Runnable reinitaliseDataRunnable = new Runnable() {
+ @Override
+ public void run() {
+ appendToLog("reset before: reinitaliseDataRunnable starts with inventoring=" + csReaderConnector.rfidReader.isInventoring() + ", mrfidToWriteSize=" + mrfidToWriteSize());
+ if (csReaderConnector.rfidReader.isInventoring() || mrfidToWriteSize() != 0) {
+ mHandler.removeCallbacks(reinitaliseDataRunnable);
+ mHandler.postDelayed(reinitaliseDataRunnable, 500);
+ } else {
+ if (DEBUG_CONNECT) appendToLog("Debug_Connect: Cs710Library4A.reinitaliseDataRunnable Start checkVersionRunnable");
+ mHandler.postDelayed(checkVersionRunnable, 500);
+ }
+ }
+ };
+ private final Runnable checkVersionRunnable = new Runnable() {
+ boolean DEBUG = false;
+ @Override
+ public void run() {
+ if (DEBUG_CONNECT) appendToLog("Debug_Connect: Cs710Library4A.checkVersionRunnable with mrfidToWriteSize = " + mrfidToWriteSize());
+ if (csReaderConnector.rfidReader == null || barcodeNewland == null || csReaderConnector.rfidReader.mRfidToWrite.size() != 0) {
+ mHandler.removeCallbacks(checkVersionRunnable);
+ mHandler.postDelayed(checkVersionRunnable, 500);
+ } else {
+ //bluetoothGatt.removeBond(null);
+ setSameCheck(false);
+ if (DEBUG_CONNECT) appendToLog("Debug_Connect: Cs710Library4A.checkVersionRunnable with BarcodeFailure = " + isBarcodeFailure()); ///
+ if (false && isBarcodeFailure() == false) {
+ if (DEBUG_CONNECT) appendToLog("Debug_Connect: Cs710Library4A.checkVersionRunnable"); ///5
+ if (barcodeNewland.checkPreSuffix(barcodeNewland.prefixRef, barcodeNewland.suffixRef) == false) barcodeNewland.barcodeSendCommandSetPreSuffix();
+ if (barcodeNewland.bBarcodeTriggerMode != 0x30) barcodeNewland.barcodeSendCommandTrigger();
+ notificationConnector.getAutoRFIDAbort(); notificationConnector.getAutoBarStartSTop(); //setAutoRFIDAbort(false); setAutoBarStartSTop(true);
+ }
+ setAntennaCycle(0xffff);
+ if (false) {
+ if (bluetoothConnector.getCsModel() == 463) {
+ if (DEBUG_CONNECT) appendToLog("Debug_Connect: Cs710Library4A.checkVersionRunnable 4");
+ setAntennaDwell(2000);
+ setAntennaInvCount(0);
+ } else {
+ if (DEBUG_CONNECT) appendToLog("Debug_Connect: Cs710Library4A.checkVersionRunnable 5");
+ setAntennaDwell(0);
+ setAntennaInvCount(0xfffffffeL);
+ }
+ }
+ csReaderConnector.settingData.loadWedgeSettingFile();
+ if (loadSetting1File()) loadSetting1File();
+ appendToLog("Cs710Library4A.checkVersionRunnable, getMacVer");
+ if (DEBUG_CONNECT) appendToLog("Debug_Connect: Cs710Library4A.checkVersionRunnable with macVersion = " + getMacVer());
+ if (true) {
+ setTagDelay(csReaderConnector.rfidReader.tagDelaySetting);
+ setCycleDelay(csReaderConnector.rfidReader.cycleDelaySetting);
+ setInvModeCompact(true);
+ } else {
+ setTagDelay(csReaderConnector.rfidReader.tagDelayDefaultNormalSetting);
+ setCycleDelay(csReaderConnector.rfidReader.cycleDelaySetting);
+ }
+ if (DEBUG_CONNECT) appendToLog("Debug_Connect: Cs710Library4A.checkVersionRunnable ends with mRfidToWrite.size = " + csReaderConnector.rfidReader.mRfidToWrite.size());
+ setSameCheck(true);
+ }
+ }
+ };
+
+ boolean loadSetting1File() {
+ String stringMacAddress = null;
+ appendToLog("Cs710Library4A.loadSetting1File, loadSettingFile: starts with bluetoothGatt is " + (bluetoothGatt == null ? "null" : "valid"));
+ if (bluetoothGatt != null) {
+ appendToLog("Cs710Library4A.loadSetting1File, loadSettingFile: bluetoothConnectionState = " + bluetoothGatt.bluetoothConnectionState);
+ appendToLog("Cs710Library4A.loadSetting1File, loadSettingFile: starts with bluetoothGatt.getmBluetoothDevice is " + (bluetoothGatt.getReaderDeviceConnected() == null ? "null" : "valid"));
+ if (bluetoothGatt.getReaderDeviceConnected() != null) stringMacAddress = bluetoothGatt.getReaderDeviceConnected().getAddress();
+ }
+ if (stringMacAddress == null) {
+ appendToLog("Cs710Library4A.loadSetting1File, loadSettingFile: starts with usbConnector is " + (csReaderConnector.usbConnector == null ? "null" : "valid"));
+ if (csReaderConnector.usbConnector != null) {
+ appendToLog("Cs710Library4A.loadSetting1File, loadSettingFile: usbConnectionState = " + csReaderConnector.usbConnector.usbConnectionState);
+ stringMacAddress = readerDeviceConnect.getAddress();
+ }
+ }
+ appendToLog("Cs710Library4A.loadSetting1File, loadSettingFile: stringMacAddress = " + stringMacAddress);
+ return csReaderConnector.settingData.loadSettingFile(stringMacAddress, getlibraryVersion(), getChannelHoppingStatus(), getCurrentProfile());
+ }
+ public void saveSetting2File() {
+ csReaderConnector.settingData.saveSetting2File(getlibraryVersion(), getChannelHoppingStatus(), getCurrentProfile());
+ }
+
+ public int getcsModel() {
+ return bluetoothConnector.getCsModel();
+ }
+ public int getAntennaCycle() {
+ return csReaderConnector.rfidReader.getAntennaCycle();
+ }
+ public boolean setAntennaCycle(int antennaCycle) {
+ return csReaderConnector.rfidReader.setAntennaCycle(antennaCycle);
+ }
+ public boolean setAntennaInvCount(long antennaInvCount) {
+ return csReaderConnector.rfidReader.setAntennaInvCount(antennaInvCount);
+ }
+
+ public void clearInvalidata() {
+ csReaderConnector.clearInvalidata();
+ }
+ public int getInvalidata() {
+ return csReaderConnector.invalidata;
+ }
+ public int getInvalidUpdata() {
+ return csReaderConnector.invalidUpdata;
+ }
+ public int getValidata() {
+ return csReaderConnector.validata;
+ }
+
+ public int setSelectData(RfidReader.TagType tagType, String mDid, boolean bNeedSelectedTagByTID, String stringProtectPassword, int selectFor, int selectHold) {
+ return csReaderConnector.rfidReader.setSelectData4Inventory(tagType, mDid, bNeedSelectedTagByTID, stringProtectPassword, selectFor, selectHold);
+ }
+ public int setOtherInventoryData(RfidReader.TagType tagType, String mDid) {
+ if (tagType == RfidReader.TagType.TAG_ASYGN) { //mDid.matches("E283A")) {
+ long iValue = csReaderConnector.rfidReader.getAntennaDwell();
+ if (iValue == 0) {
+ csReaderConnector.rfidReader.setAntennaDwell(2000);
+ }
+ }
+ return -1;
+ }
+}
+
+
+
+package com.csl.cslibrary4a;
+
+import static android.bluetooth.BluetoothClass.Service.LE_AUDIO;
+import static android.bluetooth.BluetoothClass.Service.LIMITED_DISCOVERABILITY;
+import static android.bluetooth.BluetoothDevice.BOND_BONDED;
+import static android.bluetooth.BluetoothDevice.BOND_BONDING;
+import static android.bluetooth.BluetoothDevice.BOND_NONE;
+import static android.bluetooth.BluetoothDevice.DEVICE_TYPE_CLASSIC;
+import static android.bluetooth.BluetoothDevice.DEVICE_TYPE_DUAL;
+import static android.bluetooth.BluetoothDevice.DEVICE_TYPE_LE;
+import static android.bluetooth.BluetoothDevice.DEVICE_TYPE_UNKNOWN;
+import static android.bluetooth.BluetoothProfile.GATT;
+
+import android.Manifest;
+import android.bluetooth.BluetoothAdapter;
+import android.bluetooth.BluetoothClass;
+import android.bluetooth.BluetoothDevice;
+import android.bluetooth.BluetoothGattCallback;
+import android.bluetooth.BluetoothGattCharacteristic;
+import android.bluetooth.BluetoothGattService;
+import android.bluetooth.BluetoothManager;
+import android.content.Context;
+import android.content.pm.PackageManager;
+import android.os.Build;
+import android.os.ParcelUuid;
+import android.util.Log;
+import android.widget.TextView;
+
+import androidx.core.app.ActivityCompat;
+
+import java.lang.reflect.Method;
+import java.util.List;
+import java.util.Set;
+
+public class CsLibrary4A {
+ boolean DEBUG = false, DEBUG2 = false;
+ String stringVersion = "18.0";
+ Utility utility;
+ Cs710Library4A cs710Library4A;
+ Cs108Library4A cs108Library4A;
+ Context context; TextView textViewLog;
+
+ public CsLibrary4A(Context context, TextView textViewLog) {
+ this.context = context;
+ this.textViewLog = textViewLog;
+ cs710Library4A = new Cs710Library4A(context, textViewLog); utility = cs710Library4A.utility;
+ cs710Library4A.setCsReaderConnectorCombo();
+ //cs108Library4A = new Cs108Library4A(context, textViewLog);
+ stringNOTCONNECT = " is called before Connection !!!";
+ dBuV_dBm_constant = RfidReader.dBuV_dBm_constant;
+ iNO_SUCH_SETTING = cs710Library4A.iNO_SUCH_SETTING;
+ }
+ public String getlibraryVersion() {
+ if (DEBUG) Log.i("Hello2", "getlibraryVersion");
+ String string710 = cs710Library4A.getlibraryVersion(); appendToLog("string710 = " + string710);
+ int iPos0 = string710.indexOf(".");
+ int iPos1 = string710.substring(iPos0 + 1).indexOf(".");
+ String string108 = (cs108Library4A != null ? cs108Library4A.getlibraryVersion() : string710); appendToLog("string108 = " + string108);
+ int iPos2 = string108.indexOf(".");
+ int iPos3 = string108.substring(iPos2 + 1).indexOf(".");
+ return stringVersion + "-" + string710.substring(iPos0 + iPos1 + 2) + "-" + string108.substring(iPos2 + iPos3 + 2);
+ }
+ public String checkVersion() {
+ if (DEBUG) Log.i("Hello2", "checkVersion");
+ if (isCs108Connected()) return cs108Library4A.checkVersion();
+ else if (isCs710Connected()) return cs710Library4A.checkVersion();
+ else Log.i("Hello2", "checkVersion" + stringNOTCONNECT);
+ return null;
+ }
+
+ //============ utility ============
+ public String byteArrayToString(byte[] packet) {
+ return utility.byteArrayToString(packet);
+ }
+ public void appendToLog(String s) {
+ utility.appendToLog(s);
+ }
+ public void appendToLogView(String s) {
+ utility.appendToLogView(s);
+ }
+ public String strFloat16toFloat32(String strData) {
+ return utility.strFloat16toFloat32(strData);
+ }
+ public String str2float16(String strData) {
+ return utility.str2float16(strData);
+ }
+ public float decodeCtesiusTemperature(String strActData, String strCalData) {
+ return utility.decodeCtesiusTemperature(strActData, strCalData);
+ }
+ public float decodeMicronTemperature(int iTag35, String strActData, String strCalData) {
+ return utility.decodeMicronTemperature(iTag35, strActData, strCalData);
+ }
+ public float decodeAsygnTemperature(String string) {
+ return utility.decodeAsygnTemperature(string);
+ }
+ public String temperatureC2F(String strValue) {
+ return utility.temperatureC2F(strValue);
+ }
+ public String temperatureF2C(String strValue) {
+ return utility.temperatureF2C(strValue);
+ }
+ public String getUpcSerial(String strEpc) {
+ return utility.getUpcSerial(strEpc);
+ }
+ public String getUpcSerialDetail(String strUpcSerial) {
+ return utility.getUpcSerialDetail(strUpcSerial);
+ }
+ public String getEpc4upcSerial(Utility.EpcClass epcClass, String filter, String companyPrefix, String itemReference, String serialNumber) {
+ return utility.getEpc4upcSerial(epcClass, filter, companyPrefix, itemReference, serialNumber);
+ }
+ public boolean checkHostProcessorVersion(String version, int majorVersion, int minorVersion, int buildVersion) {
+ return utility.checkHostProcessorVersion(version, majorVersion, minorVersion, buildVersion);
+ }
+
+ //============ android bluetooth ============
+ public boolean isBleScanning() {
+ if (DEBUG) Log.i("Hello2", "isBleScanning");
+ boolean bValue = false, bValue1 = false, bValue7 = false;
+ bValue1 = (cs108Library4A != null && cs108Library4A.isBleScanning());
+ bValue7 = cs710Library4A.isBleScanning();
+ if (bValue1 || bValue7) bValue = true;
+ return bValue;
+ }
+ public boolean scanLeDevice(final boolean enable) {
+ boolean bValue = false, bValue1 = false, bValue7 = false, DEBUG = true;
+ if (DEBUG) appendToLog("CsLibrary.scanLeDevice[" + enable + "]");
+
+ BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
+ if (bluetoothAdapter == null) {
+ appendToLog("CsLibrary.scanLeDevice: bluetoothAdapter is null");
+ // device doesn't support bluetooth
+ } else {
+ appendToLog("CsLibrary.scanLeDevice: bluetoothAdapter is valid");
+/*
+ if(!bluetoothAdapter.isEnabled()) {
+ Intent enableAdapter;
+ enableAdapter = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
+ startActivityForResult(enableAdapter, 0);
+ }
+*/
+ // Do whatever you want to do with your bluetoothAdapter
+ if (ActivityCompat.checkSelfPermission(context, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
+ // TODO: Consider calling
+ // ActivityCompat#requestPermissions
+ // here to request the missing permissions, and then overriding
+ // public void onRequestPermissionsResult(int requestCode, String[] permissions,
+ // int[] grantResults)
+ // to handle the case where the user grants the permission. See the documentation
+ // for ActivityCompat#requestPermissions for more details.
+ appendToLog("CsLibrary.scanLeDevice: bluetoothConnect permission is not granted");
+ } else {
+ appendToLog("CsLibrary.scanLeDevice: bluetoothConnect permission is granted");
+
+ BluetoothManager bluetoothManager = (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE);
+ //List bluetoothDevices = bluetoothManager.getConnectedDevices(GATT);
+ Set bluetoothDevices = bluetoothAdapter.getBondedDevices();
+ appendToLog("CsLibrary.scanLeDevice: bluetoothDevices size = " + bluetoothDevices.size());
+ int i = 0;
+ for (BluetoothDevice bluetoothDevice : bluetoothDevices) {
+ appendToLog("CsLibrary.scanLeDevice: " + i + ", Name = " + bluetoothDevice.getName());
+ appendToLog("CsLibrary.scanLeDevice: " + i + ", Address = " + bluetoothDevice.getAddress());
+ String string = "CsLibrary.scanLeDevice: " + i + ", Type = " + bluetoothDevice.getType();
+ switch (bluetoothDevice.getType()) {
+ case DEVICE_TYPE_CLASSIC:
+ string += " Classic - BR/EDR device";
+ break;
+ case DEVICE_TYPE_LE:
+ string += " Low Energy - LE only device";
+ break;
+ case DEVICE_TYPE_DUAL:
+ string += " Dual Mode - BR/EDR/LE device";
+ break;
+ default:
+ case DEVICE_TYPE_UNKNOWN:
+ string += " Unknown device";
+ break;
+ }
+ appendToLog(string);
+ appendToLog("CsLibrary.scanLeDevice: " + i + ", bluetoothClass = " + bluetoothDevice.getBluetoothClass().toString());
+ int iDeviceClass = bluetoothDevice.getBluetoothClass().getDeviceClass();
+ int iDeviceClassService = iDeviceClass >> 13;
+ int iDeviceClassMajor = (iDeviceClass & 0x1F00) >> 8;
+ int iDeviceClassMinor = (iDeviceClass & 0xFF) >> 2;
+ appendToLog("CsLibrary.scanLeDevice: " + i + ", bluetoothClass = " + String.format("%X", iDeviceClass)
+ + ", " + String.format("%X", iDeviceClassService)
+ + ", " + String.format("%X", iDeviceClassMajor)
+ + ", " + String.format("%X", iDeviceClassMinor));
+ appendToLog("CsLibrary.scanLeDevice: " + i + ", doesClassMatch[Profile_HID] = " + bluetoothDevice.getBluetoothClass().doesClassMatch(BluetoothClass.PROFILE_HID));
+ appendToLog("CsLibrary.scanLeDevice: " + i + ", doesClassMatch[Profile_HEADSET] = " + bluetoothDevice.getBluetoothClass().doesClassMatch(BluetoothClass.PROFILE_HEADSET));
+ appendToLog("CsLibrary.scanLeDevice: " + i + ", doesClassMatch[Profile_A2DP] = " + bluetoothDevice.getBluetoothClass().doesClassMatch(BluetoothClass.PROFILE_A2DP));
+ appendToLog("CsLibrary.scanLeDevice: " + i + ", hasService[LIMITED_DISCOVERABILITY] = " + bluetoothDevice.getBluetoothClass().hasService(LIMITED_DISCOVERABILITY));
+ appendToLog("CsLibrary.scanLeDevice: " + i + ", hasService[LE_AUDIO] = " + bluetoothDevice.getBluetoothClass().hasService(LE_AUDIO));
+ appendToLog("CsLibrary.scanLeDevice: " + i + ", describeContents = " + bluetoothDevice.describeContents());
+ boolean connected = false;
+ try {
+ Method m = bluetoothDevice.getClass().getMethod("isConnected", (Class[]) null);
+ connected = (boolean) m.invoke(bluetoothDevice, (Object[]) null);
+ } catch (Exception ex) {
+ appendToLog("CsLibrary.scanLeDevice: Exception " + ex.toString());
+ }
+ appendToLog("CsLibrary.scanLeDevice: " + i + ", connected = " + connected);
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.VANILLA_ICE_CREAM) {
+ appendToLog("CsLibrary.scanLeDevice: " + i + ", AddressType = " + bluetoothDevice.getAddressType());
+ }
+ string = "CsLibrary.scanLeDevice: " + i + ", BondState = ";
+ switch (bluetoothDevice.getBondState()) {
+ case BOND_NONE:
+ string += "None";
+ break;
+ case BOND_BONDING:
+ string += "Bonding";
+ break;
+ case BOND_BONDED:
+ string += "Bonded";
+ break;
+ default:
+ string += "Unknown";
+ break;
+ }
+ appendToLog(string);
+ ParcelUuid[] parcelUuids = bluetoothDevice.getUuids();
+ appendToLog("CsLibrary.scanLeDevice: " + i + ", Uuids.size = " + (parcelUuids == null ? "null" : parcelUuids.length));
+ for (int k = 0; parcelUuids != null && k < parcelUuids.length; k++) {
+ String string0 = "", string1 = "", string2 = parcelUuids[k].toString();
+ String string3 = string2.split("-")[0];
+ appendToLog("CsLibrary.scanLeDevice: string3 = " + string3);
+ int iString2 = 0;
+ if (string3.substring(0, 4).matches("0000")) iString2 = Integer.parseInt(string3, 16);
+ if (iString2 >= 0x1000 && iString2 < 0x1410) string0 = "SDP ";
+ else if (iString2 >= 0x1800 && iString2 < 0x1860) string0 = "GATT ";
+ if (iString2 == 0x1101) string1 = "Serial Port, ";
+ else if (iString2 == 0x110b) string1 = "Audio Sink, ";
+ else if (iString2 == 0x110e) string1 = "A/V Remote Control, ";
+ else if (iString2 == 0x1124) string1 = "HID, ";
+ else if (iString2 == 0x180f) string1 = "Battery, ";
+ else if (iString2 == 0x1812) {
+ string1 = "Human Interface Device, ";
+/*
+ UUID UUID_READER_SERVICE = UUID.fromString(string2);
+ BluetoothGattService s = bluetoothGatt.getService(service);
+ mReaderStreamOutCharacteristic = getCharacteristic(UUID_READER_SERVICE, UUID_READER_STREAM_OUT_CHARACTERISTIC);
+ mReaderStreamInCharacteristic = getCharacteristic(UUID_READER_SERVICE, UUID_READER_STREAM_IN_CHARACTERISTIC);
+*/
+ }
+ appendToLog("CsLibrary.scanLeDevice: " + i + "," + k + ", " + string0 + "Service Class: " + string1 + string2);
+ }
+
+ if (false) {
+ android.bluetooth.BluetoothGatt bluetoothGatt = bluetoothDevice.connectGatt(context, false, new BluetoothGattCallback() {
+ @Override
+ public void onCharacteristicChanged(android.bluetooth.BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
+ appendToLog("CsLibrary.scanLeDevice: onCharacteristicChanged");
+ super.onCharacteristicChanged(gatt, characteristic);
+ }
+ });
+ appendToLog("CsLibrary.scanLeDevice: " + i + ", connectGatt is " + (bluetoothGatt != null ? "valid" : "false"));
+ if (bluetoothGatt != null) {
+ List bluetoothGattServices = bluetoothGatt.getServices();
+ appendToLog("CsLibrary.scanLeDevice: " + i + ", bluetoothGattServices size is " + bluetoothGattServices.size());
+ for (int a = 0; a < bluetoothGattServices.size(); a++) {
+ appendToLog("CsLibrary.scanLeDevice: " + i + "," + a + " bluetoothGattService is " + bluetoothGattServices.get(a).toString());
+ }
+ }
+ }
+
+ String stringClassCode = bluetoothDevice.getBluetoothClass().toString().toUpperCase();
+ if (connected && (stringClassCode.matches("1F00") || stringClassCode.matches("540"))) {
+ if (false) {
+ BluetoothGatt.CsScanData scanResultA = new BluetoothGatt.CsScanData(bluetoothDevice, 0, null);
+ scanResultA.serviceUUID2p2 = 6;
+ cs710Library4A.csReaderConnector.mScanResultList.add(scanResultA);
+ appendToLog("CsLibrary.scanLeDevice: mScanResultList.size = " + cs710Library4A.mScanResultList.size());
+ } else {
+ cs710Library4A.bluetoothGatt.removeBond(bluetoothDevice);
+ }
+ }
+ i++;
+ }
+ }
+ }
+
+ bValue1 = (cs108Library4A != null && cs108Library4A.scanLeDevice(enable));
+ bValue7 = cs710Library4A.scanLeDevice(enable);
+ if (bValue1 || bValue7) bValue = true;
+ return bValue;
+ }
+ public BluetoothGatt.CsScanData getNewDeviceScanned() {
+ if (DEBUG2) Log.i("Hello2", "getNewDeviceScanned");
+ BluetoothGatt.CsScanData csScanData1;
+ BluetoothGatt.CsScanData csScanData7 = cs710Library4A.getNewDeviceScanned();
+ BluetoothGatt.CsScanData csScanData = null;
+ if (csScanData7 == null) {
+ csScanData1 = (cs108Library4A == null ? null : cs108Library4A.getNewDeviceScanned());
+ if (true) csScanData = csScanData1;
+ else if (csScanData1 != null) {
+ csScanData = new BluetoothGatt.CsScanData(csScanData1.getDevice(), csScanData1.rssi, csScanData1.getScanRecord());
+ csScanData.serviceUUID2p2 = csScanData1.serviceUUID2p2;
+ }
+ } else if (true) {
+ csScanData = csScanData7;
+ } else {
+ csScanData = new BluetoothGatt.CsScanData(csScanData7.getDevice(), csScanData7.rssi, csScanData7.getScanRecord());
+ csScanData.serviceUUID2p2 = csScanData7.serviceUUID2p2;
+ }
+ if (csScanData != null) {
+ //appendToLog("DeviceFinder, CsLibrary4A.getNewDeviceScanned: csScanData.getAddress is " + csScanData.getAddress());
+ }
+ if (csScanData != null) appendToLog("found982 with name = " + csScanData.name + ", device.name = " + csScanData.device.getName());
+ return csScanData;
+ }
+ public String getBluetoothDeviceAddress() {
+ if (DEBUG) Log.i("Hello2", "getBluetoothDeviceAddress");
+ if (isCs108Connected()) return cs108Library4A.getBluetoothDeviceAddress();
+ else if (isCs710Connected()) return cs710Library4A.getBluetoothDeviceAddress();
+ else Log.i("Hello2", "getBluetoothDeviceAddress" + stringNOTCONNECT);
+ return null;
+ }
+ public String getBluetoothDeviceName() {
+ if (DEBUG) Log.i("Hello2", "getBluetoothDeviceName");
+ if (isCs108Connected()) return cs108Library4A.getBluetoothDeviceName();
+ else if (isCs710Connected()) return cs710Library4A.getBluetoothDeviceName();
+ else Log.i("Hello2", "getBluetoothDeviceName" + stringNOTCONNECT);
+ return null;
+ }
+ public boolean isBleConnected() {
+ boolean bValue = false, DEBUG = true;
+ if (DEBUG && false) Log.i("Hello2", "CsLibrary4A.isBleConnected");
+ if (isCs108Connected()) {
+ bValue = cs108Library4A.isBleConnected();
+ if (bValue == false) bConnectStatus = 0;
+ } else if (isCs710Connected()) {
+ bValue = cs710Library4A.isBleConnected();
+ if (bValue == false) bConnectStatus = 0;
+ } else {
+ bValue = cs710Library4A.isBleConnected();
+ if (bValue) bConnectStatus = 7;
+ else {
+ bValue = (cs108Library4A != null && cs108Library4A.isBleConnected());
+ if (bValue) bConnectStatus = 1;
+ else bConnectStatus = 0;
+ }
+ }
+ return bValue;
+ }
+ public void connect(ReaderDevice readerDevice) {
+ if (DEBUG || true) Log.i("Hello", "CsLibrary4A.connect: readerDevice is " + (readerDevice != null ? "valid" : "null") + ", iServiceUuidConnectedBefore = " + iServiceUuidConnectedBefore);
+ cs710Library4A.bluetoothGatt.removeBond(readerDevice);
+ int iServiceUuid = -1;
+ if (readerDevice == null) iServiceUuid = iServiceUuidConnectedBefore;
+ else iServiceUuid = readerDevice.getServiceUUID2p1();
+ Log.i("Hello", "CsLibrary4A.connect: iServiceUuid = " + iServiceUuid);
+ if (iServiceUuid == 0 || iServiceUuid == 1 || iServiceUuid == 4) {
+ if (true) {
+ appendToLog("CsLibrary4A.connect: going to connect cs108");
+ if (cs108Library4A == null) cs108Library4A = new Cs108Library4A(context, textViewLog);
+ cs108Library4A.connect(readerDevice); iServiceUuidConnectedBefore = 0;
+ } else {
+ if (true) {
+ cs108Library4A.connect(readerDevice);
+ iServiceUuidConnectedBefore = 0;
+ } else {
+ ReaderDevice readerDevice1 = null;
+ if (readerDevice != null) readerDevice1 = new ReaderDevice(
+ readerDevice.getName(), readerDevice.getAddress(), readerDevice.getSelected(),
+ readerDevice.getDetails(), readerDevice.getCount(), readerDevice.getRssi(),
+ readerDevice.getServiceUUID2p1());
+ cs108Library4A.connect(readerDevice1);
+ iServiceUuidConnectedBefore = 0;
+ }
+ }
+ } else if (iServiceUuid == 2 || iServiceUuid == 3 || iServiceUuid == 5 || iServiceUuid == 6) {
+ appendToLog("CsLibrary4A.connect: going to connect cs710");
+ cs710Library4A.connect(readerDevice); iServiceUuidConnectedBefore = 2;
+ } else appendToLog("CsLibrary4A.connect: invalid serviceUUID = " + (readerDevice == null ? "null" : readerDevice.getServiceUUID2p1()));
+ }
+ public void disconnect(boolean tempDisconnect) {
+ //appendToLog("CsLibrary4A.disconnect, Fragment: Starts");
+ //ReaderDevice readerDevice = null;
+ //if (isCs108Connected() && cs108Library4A != null) readerDevice = cs108Library4A.readerDeviceConnect;
+ //else if (isCs710Connected() && cs710Library4A != null) readerDevice = cs710Library4A.readerDeviceConnect;
+ //cs710Library4A.bluetoothGatt.removeBond(readerDevice);
+
+ if (isCs108Connected()) cs108Library4A.disconnect(tempDisconnect);
+ else if (isCs710Connected()) cs710Library4A.disconnect(tempDisconnect);
+ }
+ public boolean forceBTdisconnect() {
+ if (DEBUG) Log.i("Hello2", "forceBTdisconnect");
+ if (isCs108Connected()) return cs108Library4A.forceBTdisconnect();
+ else if (isCs710Connected()) return cs710Library4A.forceBTdisconnect();
+ else Log.i("Hello2", "forceBTdisconnect" + stringNOTCONNECT);
+ return false;
+ }
+ public int getRssi() {
+ if (DEBUG) Log.i("Hello2", "getRssi");
+ if (isCs108Connected()) return cs108Library4A.getRssi();
+ else if (isCs710Connected()) return cs710Library4A.getRssi();
+ else Log.i("Hello2", "getRssi" + stringNOTCONNECT);
+ return -1;
+ } //411
+ public long getStreamInRate() {
+ if (DEBUG) Log.i("Hello2", "getStreamInRate");
+ if (isCs108Connected()) return cs108Library4A.getStreamInRate();
+ else if (isCs710Connected()) return cs710Library4A.getStreamInRate();
+ else Log.i("Hello2", "getStreamInRate" + stringNOTCONNECT);
+ return -1;
+ }
+ public int get98XX() {
+ if (DEBUG) Log.i("Hello2", "get98XX");
+ if (isCs108Connected()) return cs108Library4A.get98XX();
+ else if (isCs710Connected()) return cs710Library4A.get98XX();
+ else Log.i("Hello2", "get98XX" + stringNOTCONNECT);
+ return -1;
+ }
+
+
+ //============ Rfid ============
+ public String getAuthMatchData() {
+ if (DEBUG) Log.i("Hello2", "getAuthMatchData");
+ if (isCs108Connected()) return cs108Library4A.getAuthMatchData();
+ else if (isCs710Connected()) return cs710Library4A.getAuthMatchData();
+ else Log.i("Hello2", "getAuthMatchData" + stringNOTCONNECT);
+ return null;
+ }
+ public boolean setAuthMatchData(String mask) {
+ if (DEBUG) Log.i("Hello2", "setAuthMatchData");
+ if (isCs108Connected()) return cs108Library4A.setAuthMatchData(mask);
+ else if (isCs710Connected()) return cs710Library4A.setAuthMatchData(mask);
+ else Log.i("Hello2", "setAuthMatchData" + stringNOTCONNECT);
+ return false;
+ }
+ public int getStartQValue() {
+ if (DEBUG) Log.i("Hello2", "getStartQValue");
+ if (isCs108Connected()) return cs108Library4A.getStartQValue();
+ else if (isCs710Connected()) return cs710Library4A.getStartQValue();
+ else Log.i("Hello2", "getStartQValue" + stringNOTCONNECT);
+ return -1;
+ }
+ public int getMaxQValue() {
+ if (DEBUG) Log.i("Hello2", "getMaxQValue");
+ if (isCs108Connected()) return cs108Library4A.getMaxQValue();
+ else if (isCs710Connected()) return cs710Library4A.getMaxQValue();
+ else Log.i("Hello2", "getMaxQValue" + stringNOTCONNECT);
+ return -1;
+ }
+ public int getMinQValue() {
+ if (DEBUG) Log.i("Hello2", "getMinQValue");
+ if (isCs108Connected()) return cs108Library4A.getMinQValue();
+ else if (isCs710Connected()) return cs710Library4A.getMinQValue();
+ else Log.i("Hello2", "getMinQValue" + stringNOTCONNECT);
+ return -1;
+ }
+ public boolean setDynamicQParms(int startQValue, int minQValue, int maxQValue, int retryCount) {
+ if (DEBUG) Log.i("Hello2", "setDynamicQParms");
+ if (isCs108Connected()) return cs108Library4A.setDynamicQParms(startQValue, minQValue, maxQValue, retryCount);
+ else if (isCs710Connected()) return cs710Library4A.setDynamicQParms(startQValue, minQValue, maxQValue, retryCount);
+ else Log.i("Hello2", "setDynamicQParms" + stringNOTCONNECT);
+ return false;
+ }
+ public int getFixedQValue() {
+ if (DEBUG) Log.i("Hello2", "getFixedQValue");
+ if (isCs108Connected()) return cs108Library4A.getFixedQValue();
+ else if (isCs710Connected()) return cs710Library4A.getFixedQValue();
+ else Log.i("Hello2", "getFixedQValue" + stringNOTCONNECT);
+ return -1;
+ }
+ public int getFixedRetryCount() {
+ if (DEBUG) Log.i("Hello2", "getFixedRetryCount");
+ if (isCs108Connected()) return cs108Library4A.getFixedRetryCount();
+ else if (isCs710Connected()) return cs710Library4A.getFixedRetryCount();
+ else Log.i("Hello2", "getFixedRetryCount" + stringNOTCONNECT);
+ return -1;
+ }
+ public boolean getRepeatUnitNoTags() {
+ if (DEBUG) Log.i("Hello2", "getRepeatUnitNoTags");
+ if (isCs108Connected()) return cs108Library4A.getRepeatUnitNoTags();
+ else if (isCs710Connected()) return cs710Library4A.getRepeatUnitNoTags();
+ else Log.i("Hello2", "getRepeatUnitNoTags" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean setFixedQParms(int qValue, int retryCount, boolean repeatUnitNoTags) {
+ if (DEBUG) Log.i("Hello2", "setFixedQParms");
+ if (isCs108Connected()) return cs108Library4A.setFixedQParms(qValue, retryCount, repeatUnitNoTags);
+ else if (isCs710Connected()) return cs710Library4A.setFixedQParms(qValue, retryCount, repeatUnitNoTags);
+ else Log.i("Hello2", "setFixedQParms" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean getChannelHoppingDefault() {
+ if (DEBUG) Log.i("Hello2", "getChannelHoppingDefault");
+ if (isCs108Connected()) return cs108Library4A.getChannelHoppingDefault();
+ else if (isCs710Connected()) return cs710Library4A.getChannelHoppingDefault();
+ else Log.i("Hello2", "getChannelHoppingDefault" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean getRfidOnStatus() {
+ if (DEBUG) Log.i("Hello2", "getRfidOnStatus");
+ if (isCs108Connected()) return cs108Library4A.getRfidOnStatus();
+ else if (isCs710Connected()) return cs710Library4A.getRfidOnStatus();
+ else Log.i("Hello2", "getRfidOnStatus" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean isRfidFailure() {
+ if (DEBUG2) Log.i("Hello2", "isRfidFailure");
+ if (isCs108Connected()) return cs108Library4A.isRfidFailure();
+ else if (isCs710Connected()) return cs710Library4A.isRfidFailure();
+ return false;
+ }
+ public void setReaderDefault() {
+ if (DEBUG) Log.i("Hello2", "setReaderDefault");
+ if (isCs108Connected()) cs108Library4A.setReaderDefault();
+ else if (isCs710Connected()) cs710Library4A.setReaderDefault();
+ else Log.i("Hello2", "setReaderDefault" + stringNOTCONNECT);
+ }
+ public String getMacVer() {
+ if (DEBUG) Log.i("Hello2", "getMacVer");
+ appendToLog("CsLibrary4A.getMacVer");
+ if (isCs108Connected()) return cs108Library4A.getMacVer();
+ else if (isCs710Connected()) return cs710Library4A.getMacVer();
+ else Log.i("Hello2", "getMacVer" + stringNOTCONNECT);
+ return null;
+ }
+ public String getRadioSerial() {
+ if (DEBUG) Log.i("Hello2", "getRadioSerial");
+ if (isCs108Connected()) return cs108Library4A.getRadioSerial();
+ else if (isCs710Connected()) return cs710Library4A.getRadioSerial();
+ else Log.i("Hello2", "getRadioSerial" + stringNOTCONNECT);
+ return null;
+ }
+ public String getRadioBoardVersion() {
+ if (DEBUG) Log.i("Hello2", "getRadioBoardVersion");
+ if (isCs108Connected()) return cs108Library4A.getRadioBoardVersion();
+ else if (isCs710Connected()) return cs710Library4A.getRadioBoardVersion();
+ else Log.i("Hello2", "getRadioBoardVersion" + stringNOTCONNECT);
+ return null;
+ }
+ public int getPortNumber() {
+ if (DEBUG) Log.i("Hello2", "getPortNumber");
+ if (isCs108Connected()) return cs108Library4A.getPortNumber();
+ else if (isCs710Connected()) return cs710Library4A.getPortNumber();
+ else Log.i("Hello2", "getPortNumber" + stringNOTCONNECT);
+ return -1;
+ }
+ public int getAntennaSelect() {
+ if (DEBUG) Log.i("Hello2", "getAntennaSelect");
+ if (isCs108Connected()) return cs108Library4A.getAntennaSelect();
+ else if (isCs710Connected()) return cs710Library4A.getAntennaSelect();
+ else Log.i("Hello2", "getAntennaSelect" + stringNOTCONNECT);
+ return -1;
+ }
+ public boolean setAntennaSelect(int number) {
+ if (DEBUG) Log.i("Hello2", "setAntennaSelect");
+ if (isCs108Connected()) return cs108Library4A.setAntennaSelect(number);
+ else if (isCs710Connected()) return cs710Library4A.setAntennaSelect(number);
+ else Log.i("Hello2", "setAntennaSelect" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean getAntennaEnable() {
+ if (DEBUG) Log.i("Hello2", "getAntennaEnable");
+ if (isCs108Connected()) return cs108Library4A.getAntennaEnable();
+ else if (isCs710Connected()) return cs710Library4A.getAntennaEnable();
+ else Log.i("Hello2", "getAntennaEnable" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean setAntennaEnable(boolean enable) {
+ if (DEBUG) Log.i("Hello2", "setAntennaEnable");
+ if (isCs108Connected()) return cs108Library4A.setAntennaEnable(enable);
+ else if (isCs710Connected()) return cs710Library4A.setAntennaEnable(enable);
+ else Log.i("Hello2", "setAntennaEnable" + stringNOTCONNECT);
+ return false;
+ }
+ public long getAntennaDwell() {
+ if (DEBUG) Log.i("Hello2", "getAntennaDwell");
+ if (isCs108Connected()) return cs108Library4A.getAntennaDwell();
+ else if (isCs710Connected()) return cs710Library4A.getAntennaDwell();
+ else Log.i("Hello2", "getAntennaDwell" + stringNOTCONNECT);
+ return -1;
+ }
+ public boolean setAntennaDwell(long antennaDwell) {
+ if (DEBUG) Log.i("Hello2", "setAntennaDwell");
+ if (isCs108Connected()) return cs108Library4A.setAntennaDwell(antennaDwell);
+ else if (isCs710Connected()) return cs710Library4A.setAntennaDwell(antennaDwell);
+ else Log.i("Hello2", "setAntennaDwell" + stringNOTCONNECT);
+ return false;
+ }
+ public long getPwrlevel() {
+ if (DEBUG) Log.i("Hello2", "getPwrlevel");
+ if (isCs108Connected()) return cs108Library4A.getPwrlevel();
+ else if (isCs710Connected()) return cs710Library4A.getPwrlevel();
+ else Log.i("Hello2", "getPwrlevel" + stringNOTCONNECT);
+ return -1;
+ }
+ public boolean setPowerLevel(long pwrlevel) {
+ if (DEBUG) Log.i("Hello2", "setPowerLevel");
+ if (isCs108Connected()) return cs108Library4A.setPowerLevel(pwrlevel);
+ else if (isCs710Connected()) return cs710Library4A.setPowerLevel(pwrlevel);
+ else Log.i("Hello2", "setPowerLevel" + stringNOTCONNECT);
+ return false;
+ }
+ public int getQueryTarget() {
+ if (DEBUG) Log.i("Hello2", "getQueryTarget");
+ if (isCs108Connected()) return cs108Library4A.getQueryTarget();
+ else if (isCs710Connected()) return cs710Library4A.getQueryTarget();
+ else Log.i("Hello2", "getQueryTarget" + stringNOTCONNECT);
+ return -1;
+ }
+ public int getQuerySession() {
+ if (DEBUG) Log.i("Hello2", "getQuerySession");
+ if (isCs108Connected()) return cs108Library4A.getQuerySession();
+ else if (isCs710Connected()) return cs710Library4A.getQuerySession();
+ else Log.i("Hello2", "getQuerySession" + stringNOTCONNECT);
+ return -1;
+ }
+ public int getQuerySelect() {
+ if (DEBUG) Log.i("Hello2", "getQuerySelect");
+ if (isCs108Connected()) return cs108Library4A.getQuerySelect();
+ else if (isCs710Connected()) return cs710Library4A.getQuerySelect();
+ else Log.i("Hello2", "getQuerySelect" + stringNOTCONNECT);
+ return -1;
+ }
+ public boolean setTagGroup(int sL, int session, int target1) {
+ if (DEBUG) Log.i("Hello2", "setTagGroup");
+ if (isCs108Connected()) return cs108Library4A.setTagGroup(sL, session, target1);
+ else if (isCs710Connected()) return cs710Library4A.setTagGroup(sL, session, target1);
+ else Log.i("Hello2", "setTagGroup" + stringNOTCONNECT);
+ return false;
+ }
+ public int getTagFocus() {
+ if (DEBUG) Log.i("Hello2", "getTagFocus");
+ if (isCs108Connected()) return cs108Library4A.getTagFocus();
+ else if (isCs710Connected()) return cs710Library4A.getTagFocus();
+ else Log.i("Hello2", "getTagFocus" + stringNOTCONNECT);
+ return -1;
+ }
+ public boolean setTagFocus(boolean tagFocusNew) {
+ if (DEBUG) Log.i("Hello2", "setTagFocus");
+ if (isCs108Connected()) return cs108Library4A.setTagFocus(tagFocusNew);
+ else if (isCs710Connected()) return cs710Library4A.setTagFocus(tagFocusNew);
+ else Log.i("Hello2", "setTagFocus" + stringNOTCONNECT);
+ return false;
+ }
+ public int getFastId() {
+ if (DEBUG) Log.i("Hello2", "getFastId");
+ if (isCs108Connected()) return cs108Library4A.getFastId();
+ else if (isCs710Connected()) return cs710Library4A.getFastId();
+ else Log.i("Hello2", "getFastId" + stringNOTCONNECT);
+ return -1;
+ }
+ public boolean setFastId(boolean fastIdNew) {
+ if (DEBUG) Log.i("Hello2", "setFastId");
+ if (isCs108Connected()) return cs108Library4A.setFastId(fastIdNew);
+ else if (isCs710Connected()) return cs710Library4A.setFastId(fastIdNew);
+ else Log.i("Hello2", "setFastId" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean getInvAlgo() {
+ if (DEBUG) Log.i("Hello2", "getInvAlgo");
+ if (isCs108Connected()) return cs108Library4A.getInvAlgo();
+ else if (isCs710Connected()) return cs710Library4A.getInvAlgo();
+ else Log.i("Hello2", "getInvAlgo" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean setInvAlgo(boolean dynamicAlgo) {
+ if (DEBUG) Log.i("Hello2", "setInvAlgo");
+ if (isCs108Connected()) return cs108Library4A.setInvAlgo(dynamicAlgo);
+ else if (isCs710Connected()) return cs710Library4A.setInvAlgo(dynamicAlgo);
+ else Log.i("Hello2", "setInvAlgo" + stringNOTCONNECT);
+ return false;
+ }
+ public List getProfileList() {
+ if (DEBUG) Log.i("Hello2", "getProfileList");
+ if (isCs108Connected()) return cs108Library4A.getProfileList();
+ else if (isCs710Connected()) return cs710Library4A.getProfileList();
+ else Log.i("Hello2", "getProfileList" + stringNOTCONNECT);
+ return null;
+ }
+ public int getCurrentProfile() {
+ if (DEBUG) Log.i("Hello2", "getCurrentProfile");
+ if (isCs108Connected()) return cs108Library4A.getCurrentProfile();
+ else if (isCs710Connected()) return cs710Library4A.getCurrentProfile();
+ else Log.i("Hello2", "getCurrentProfile" + stringNOTCONNECT);
+ return -1;
+ }
+ public boolean setBasicCurrentLinkProfile() {
+ if (DEBUG) Log.i("Hello2", "setBasicCurrentLinkProfile");
+ if (isCs108Connected()) return true;
+ else if (isCs710Connected()) return cs710Library4A.setBasicCurrentLinkProfile();
+ else Log.i("Hello2", "setBasicCurrentLinkProfile" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean setCurrentLinkProfile(int profile) {
+ if (DEBUG) Log.i("Hello2", "setCurrentLinkProfile to " + profile);
+ if (isCs108Connected()) return cs108Library4A.setCurrentLinkProfile(profile);
+ else if (isCs710Connected()) return cs710Library4A.setCurrentLinkProfile(profile);
+ else Log.i("Hello2", "setCurrentLinkProfile" + stringNOTCONNECT);
+ return false;
+ }
+ public void resetEnvironmentalRSSI() {
+ if (DEBUG) Log.i("Hello2", "resetEnvironmentalRSSI");
+ if (isCs108Connected()) cs108Library4A.resetEnvironmentalRSSI();
+ else if (isCs710Connected()) cs710Library4A.resetEnvironmentalRSSI();
+ else Log.i("Hello2", "resetEnvironmentalRSSI" + stringNOTCONNECT);
+ }
+ public String getEnvironmentalRSSI() {
+ if (DEBUG) Log.i("Hello2", "getEnvironmentalRSSI");
+ if (isCs108Connected()) return cs108Library4A.getEnvironmentalRSSI();
+ else if (isCs710Connected()) return cs710Library4A.getEnvironmentalRSSI();
+ else Log.i("Hello2", "getEnvironmentalRSSI" + stringNOTCONNECT);
+ return null;
+ }
+ public int getHighCompression() {
+ if (DEBUG) Log.i("Hello2", "getHighCompression");
+ if (isCs108Connected()) return cs108Library4A.getHighCompression();
+ else if (isCs710Connected()) return cs710Library4A.getHighCompression();
+ else Log.i("Hello2", "getHighCompression" + stringNOTCONNECT);
+ return -1;
+ }
+ public int getRflnaGain() {
+ if (DEBUG) Log.i("Hello2", "getRflnaGain");
+ if (isCs108Connected()) return cs108Library4A.getRflnaGain();
+ else if (isCs710Connected()) return cs710Library4A.getRflnaGain();
+ else Log.i("Hello2", "getRflnaGain" + stringNOTCONNECT);
+ return -1;
+ }
+ public int getIflnaGain() {
+ if (DEBUG) Log.i("Hello2", "getIflnaGain");
+ if (isCs108Connected()) return cs108Library4A.getIflnaGain();
+ else if (isCs710Connected()) return cs710Library4A.getIflnaGain();
+ else Log.i("Hello2", "getIflnaGain" + stringNOTCONNECT);
+ return -1;
+ }
+ public int getAgcGain() {
+ if (DEBUG) Log.i("Hello2", "getAgcGain");
+ if (isCs108Connected()) return cs108Library4A.getAgcGain();
+ else if (isCs710Connected()) return cs710Library4A.getAgcGain();
+ else Log.i("Hello2", "getAgcGain" + stringNOTCONNECT);
+ return -1;
+ }
+ public int getRxGain() {
+ if (DEBUG) Log.i("Hello2", "getRxGain");
+ if (isCs108Connected()) return cs108Library4A.getRxGain();
+ else if (isCs710Connected()) return cs710Library4A.getRxGain();
+ else Log.i("Hello2", "getRxGain" + stringNOTCONNECT);
+ return -1;
+ }
+ public boolean setRxGain(int highCompression, int rflnagain, int iflnagain, int agcgain) {
+ if (DEBUG) Log.i("Hello2", "setRxGain");
+ if (isCs108Connected()) return cs108Library4A.setRxGain(highCompression, rflnagain, iflnagain, agcgain);
+ else if (isCs710Connected()) return cs710Library4A.setRxGain(highCompression, rflnagain, iflnagain, agcgain);
+ else Log.i("Hello2", "setRxGain" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean setRxGain(int rxGain) {
+ if (DEBUG) Log.i("Hello2", "setRxGain");
+ if (isCs108Connected()) return cs108Library4A.setRxGain(rxGain);
+ else if (isCs710Connected()) return cs710Library4A.setRxGain(rxGain);
+ else Log.i("Hello2", "setRxGain" + stringNOTCONNECT);
+ return false;
+ }
+ public int FreqChnCnt() {
+ if (DEBUG) Log.i("Hello2", "FreqChnCnt");
+ if (isCs108Connected()) return cs108Library4A.FreqChnCnt();
+ else if (isCs710Connected()) return cs710Library4A.FreqChnCnt();
+ else Log.i("Hello2", "FreqChnCnt" + stringNOTCONNECT);
+ return -1;
+ }
+ public double getLogicalChannel2PhysicalFreq(int channel) {
+ if (DEBUG) Log.i("Hello2", "getLogicalChannel2PhysicalFreq");
+ if (isCs108Connected()) return cs108Library4A.getLogicalChannel2PhysicalFreq(channel);
+ else if (isCs710Connected()) return cs710Library4A.getLogicalChannel2PhysicalFreq(channel);
+ else Log.i("Hello2", "getLogicalChannel2PhysicalFreq" + stringNOTCONNECT);
+ return -1;
+ }
+ public byte getTagDelay() {
+ if (DEBUG) Log.i("Hello2", "getTagDelay");
+ if (isCs108Connected()) return cs108Library4A.getTagDelay();
+ else if (isCs710Connected()) return cs710Library4A.getTagDelay();
+ else Log.i("Hello2", "getTagDelay" + stringNOTCONNECT);
+ return -1;
+ }
+ public boolean setTagDelay(byte tagDelay) {
+ if (DEBUG) Log.i("Hello2", "setTagDelay");
+ if (isCs108Connected()) return cs108Library4A.setTagDelay(tagDelay);
+ else if (isCs710Connected()) return cs710Library4A.setTagDelay(tagDelay);
+ else Log.i("Hello2", "setTagDelay" + stringNOTCONNECT);
+ return false;
+ }
+ public byte getIntraPkDelay() {
+ if (DEBUG) Log.i("Hello2", "getIntraPkDelay");
+ if (isCs108Connected()) return cs108Library4A.getIntraPkDelay();
+ else if (isCs710Connected()) return cs710Library4A.getIntraPkDelay();
+ else Log.i("Hello2", "getIntraPkDelay" + stringNOTCONNECT);
+ return -1;
+ }
+ public boolean setIntraPkDelay(byte intraPkDelay) {
+ if (DEBUG) Log.i("Hello2", "setIntraPkDelay");
+ if (isCs108Connected()) return cs108Library4A.setIntraPkDelay(intraPkDelay);
+ else if (isCs710Connected()) return cs710Library4A.setIntraPkDelay(intraPkDelay);
+ else Log.i("Hello2", "setIntraPkDelay" + stringNOTCONNECT);
+ return false;
+ }
+ public byte getDupDelay() {
+ if (DEBUG) Log.i("Hello2", "getDupDelay");
+ if (isCs108Connected()) return cs108Library4A.getDupDelay();
+ else if (isCs710Connected()) return cs710Library4A.getDupDelay();
+ else Log.i("Hello2", "getDupDelay" + stringNOTCONNECT);
+ return -1;
+ }
+ public boolean setDupDelay(byte dupElim) {
+ if (DEBUG) Log.i("Hello2", "setDupDelay");
+ if (isCs108Connected()) return cs108Library4A.setDupDelay(dupElim);
+ else if (isCs710Connected()) return cs710Library4A.setDupDelay(dupElim);
+ else Log.i("Hello2", "setDupDelay" + stringNOTCONNECT);
+ return false;
+ }
+ public long getCycleDelay() {
+ if (DEBUG) Log.i("Hello2", "getCycleDelay");
+ if (isCs108Connected()) return cs108Library4A.getCycleDelay();
+ else if (isCs710Connected()) return cs710Library4A.getCycleDelay();
+ else Log.i("Hello2", "getCycleDelay" + stringNOTCONNECT);
+ return -1;
+ }
+ public boolean setCycleDelay(long cycleDelay) {
+ if (DEBUG) Log.i("Hello2", "setCycleDelay");
+ if (isCs108Connected()) return cs108Library4A.setCycleDelay(cycleDelay);
+ else if (isCs710Connected()) return cs710Library4A.setCycleDelay(cycleDelay);
+ return false;
+ }
+ public void getAuthenticateReplyLength() {
+ if (DEBUG) Log.i("Hello2", "getAuthenticateReplyLength");
+ if (isCs108Connected()) cs108Library4A.getAuthenticateReplyLength();
+ else if (isCs710Connected()) cs710Library4A.getAuthenticateReplyLength();
+ else Log.i("Hello2", "getAuthenticateReplyLength" + stringNOTCONNECT);
+ }
+ public boolean setTamConfiguration(boolean header, String matchData) {
+ if (DEBUG | true) Log.i("Hello2", "setTamConfiguration with header = " + header + ", matchData = " + matchData);
+ if (isCs108Connected()) return cs108Library4A.setTamConfiguration(header, matchData);
+ else if (isCs710Connected()) return cs710Library4A.setTamConfiguration(header, matchData);
+ else Log.i("Hello2", "setTam1Configuration");
+ return false;
+ }
+ public boolean setTam1Configuration(int keyId, String matchData) {
+ if (DEBUG | true) Log.i("Hello2", "setTam1Configuration with KeyId = " + keyId + ", matchData = " + matchData);
+ if (isCs108Connected()) return cs108Library4A.setTam1Configuration(keyId, matchData);
+ else if (isCs710Connected()) return cs710Library4A.setTam1Configuration(keyId, matchData);
+ else Log.i("Hello2", "setTam1Configuration");
+ return false;
+ }
+ public boolean setTam2Configuration(int keyId, String matchData, int profile, int offset, int blockId, int protMode) {
+ if (DEBUG) Log.i("Hello2", "setTam2Configuration");
+ if (isCs108Connected()) return cs108Library4A.setTam2Configuration(keyId, matchData, profile, offset, blockId, protMode);
+ else if (isCs710Connected()) return cs710Library4A.setTam2Configuration(keyId, matchData, profile, offset, blockId, protMode);
+ else Log.i("Hello2", "setTam2Configuration");
+ return false;
+ }
+ public int getUntraceableEpcLength() {
+ if (DEBUG) Log.i("Hello2", "getUntraceableEpcLength");
+ if (isCs108Connected()) return cs108Library4A.getUntraceableEpcLength();
+ else if (isCs710Connected()) return cs710Library4A.getUntraceableEpcLength();
+ else Log.i("Hello2", "getUntraceableEpcLength" + stringNOTCONNECT);
+ return -1;
+ }
+ public boolean setUntraceable(boolean bHideEpc, int ishowEpcSize, int iHideTid, boolean bHideUser, boolean bHideRange) {
+ Log.i("Hello2", "setUntraceable 1");
+ return false;
+ }
+ public boolean setUntraceable(int range, boolean user, int tid, int epcLength, boolean epc, boolean uxpc) {
+ if (DEBUG) Log.i("Hello2", "setUntraceable");
+ if (isCs108Connected()) return cs108Library4A.setUntraceable(range, user, tid, epcLength, epc, uxpc);
+ else if (isCs710Connected()) return false;
+ else Log.i("Hello2", "setUntraceable" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean setAuthenticateConfiguration() {
+ if (DEBUG) Log.i("Hello2", "setAuthenticateConfiguration");
+ if (isCs108Connected()) return cs108Library4A.setAuthenticateConfiguration();
+ else if (isCs710Connected()) return cs710Library4A.setAuthenticateConfiguration();
+ else Log.i("Hello2", "setAuthenticateConfiguration" + stringNOTCONNECT);
+ return false;
+ }
+ public int getRetryCount() {
+ if (DEBUG) Log.i("Hello2", "getRetryCount");
+ if (isCs108Connected()) return cs108Library4A.getRetryCount();
+ else if (isCs710Connected()) return cs710Library4A.getRetryCount();
+ else Log.i("Hello2", "getRetryCount" + stringNOTCONNECT);
+ return -1;
+ }
+ public boolean setRetryCount(int retryCount) {
+ if (DEBUG) Log.i("Hello2", "setRetryCount");
+ if (isCs108Connected()) return cs108Library4A.setRetryCount(retryCount);
+ else if (isCs710Connected()) return cs710Library4A.setRetryCount(retryCount);
+ else Log.i("Hello2", "setRetryCount" + stringNOTCONNECT);
+ return false;
+ }
+ public int getInvSelectIndex() {
+ if (DEBUG) Log.i("Hello2", "getInvSelectIndex");
+ if (isCs108Connected()) return cs108Library4A.getInvSelectIndex();
+ else if (isCs710Connected()) return cs710Library4A.getInvSelectIndex();
+ else Log.i("Hello2", "getInvSelectIndex" + stringNOTCONNECT);
+ return -1;
+ } //2286
+ public boolean getSelectEnable() {
+ if (DEBUG) Log.i("Hello2", "getSelectEnable");
+ if (isCs108Connected()) return cs108Library4A.getSelectEnable();
+ else if (isCs710Connected()) return cs710Library4A.getSelectEnable();
+ else Log.i("Hello2", "getSelectEnable" + stringNOTCONNECT);
+ return false;
+ }
+ public int getSelectTarget() {
+ if (DEBUG) Log.i("Hello2", "getSelectTarget");
+ if (isCs108Connected()) return cs108Library4A.getSelectTarget();
+ else if (isCs710Connected()) return cs710Library4A.getSelectTarget();
+ else Log.i("Hello2", "getSelectTarget" + stringNOTCONNECT);
+ return -1;
+ }
+ public int getSelectAction() {
+ if (DEBUG) Log.i("Hello2", "getSelectAction");
+ if (isCs108Connected()) return cs108Library4A.getSelectAction();
+ else if (isCs710Connected()) return cs710Library4A.getSelectAction();
+ else Log.i("Hello2", "getSelectAction" + stringNOTCONNECT);
+ return -1;
+ }
+ public int getSelectMaskBank() {
+ if (DEBUG) Log.i("Hello2", "getSelectMaskBank");
+ if (isCs108Connected()) return cs108Library4A.getSelectMaskBank();
+ else if (isCs710Connected()) return cs710Library4A.getSelectMaskBank();
+ else Log.i("Hello2", "getSelectMaskBank" + stringNOTCONNECT);
+ return -1;
+ }
+ public int getSelectMaskOffset() {
+ if (DEBUG) Log.i("Hello2", "getSelectMaskOffset");
+ if (isCs108Connected()) return cs108Library4A.getSelectMaskOffset();
+ else if (isCs710Connected()) return cs710Library4A.getSelectMaskOffset();
+ else Log.i("Hello2", "getSelectMaskOffset" + stringNOTCONNECT);
+ return -1;
+ }
+ public String getSelectMaskData() {
+ if (DEBUG) Log.i("Hello2", "getSelectMaskData");
+ if (isCs108Connected()) return cs108Library4A.getSelectMaskData();
+ else if (isCs710Connected()) return cs710Library4A.getSelectMaskData();
+ else Log.i("Hello2", "getSelectMaskData" + stringNOTCONNECT);
+ return null;
+ }
+ public boolean setInvSelectIndex(int invSelect) {
+ if (DEBUG) Log.i("Hello2", "setInvSelectIndex");
+ if (isCs108Connected()) return cs108Library4A.setInvSelectIndex(invSelect);
+ else if (isCs710Connected()) return cs710Library4A.setInvSelectIndex(invSelect);
+ else Log.i("Hello2", "setInvSelectIndex" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean setSelectCriteriaDisable(int index) {
+ if (DEBUG || true) appendToLog("csLibrary4A: setSelectCriteria Disable with index = " + index);
+ if (isCs108Connected()) return cs108Library4A.setSelectCriteriaDisable(index);
+ else if (isCs710Connected()) return cs710Library4A.setSelectCriteriaDisable(index);
+ else Log.i("Hello2", "setSelectCriteriaDisable" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean setSelectCriteria(int index, boolean enable, int target, int action, int bank, int offset, String mask, boolean maskbit) {
+ appendToLog("csLibrary4A: setSelectCriteria 1 with index = " + index + ", enable = " + enable + ", target = " + target + ", action = " + action + ", bank = " + bank + ", offset = " + offset + ", mask = " + mask + ", maskbit = " + maskbit);
+ if (isCs108Connected()) return cs108Library4A.setSelectCriteria(index, enable, target, action, bank, offset, mask, maskbit);
+ else if (isCs710Connected()) return cs710Library4A.setSelectCriteria(index, enable, target, action, bank, offset, mask, maskbit);
+ else Log.i("Hello2", "setSelectCriteria 1" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean setSelectCriteria(int index, boolean enable, int target, int action, int delay, int bank, int offset, String mask) {
+ appendToLog("csLibrary4A: setSelectCriteria 2 with index = " + index + ", enable = " + enable + ", target = " + target + ", action = " + action + ", delay = " + delay + ", bank = " + bank + ", offset = " + offset + ", mask = " + mask);
+ if (isCs108Connected()) return cs108Library4A.setSelectCriteria(index, enable, target, action, delay, bank, offset, mask);
+ else if (isCs710Connected()) return cs710Library4A.setSelectCriteria(index, enable, target, action, delay, bank, offset, mask);
+ else Log.i("Hello2", "setSelectCriteria" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean getRssiFilterEnable() {
+ if (DEBUG) Log.i("Hello2", "getRssiFilterEnable");
+ if (isCs108Connected()) return cs108Library4A.getRssiFilterEnable();
+ else if (isCs710Connected()) return cs710Library4A.getRssiFilterEnable();
+ else Log.i("Hello2", "getRssiFilterEnable" + stringNOTCONNECT);
+ return false;
+ }
+ public int getRssiFilterType() {
+ if (DEBUG) Log.i("Hello2", "getRssiFilterType");
+ if (isCs108Connected()) return cs108Library4A.getRssiFilterType();
+ else if (isCs710Connected()) return cs710Library4A.getRssiFilterType();
+ else Log.i("Hello2", "getRssiFilterType" + stringNOTCONNECT);
+ return -1;
+ }
+ public int getRssiFilterOption() {
+ if (DEBUG) Log.i("Hello2", "getRssiFilterOption");
+ if (isCs108Connected()) return cs108Library4A.getRssiFilterOption();
+ else if (isCs710Connected()) return cs710Library4A.getRssiFilterOption();
+ return -1;
+ }
+ public boolean setRssiFilterConfig(boolean enable, int rssiFilterType, int rssiFilterOption) {
+ if (DEBUG) Log.i("Hello2", "setRssiFilterConfig");
+ if (isCs108Connected()) return cs108Library4A.setRssiFilterConfig(enable, rssiFilterType, rssiFilterOption);
+ else if (isCs710Connected()) return cs710Library4A.setRssiFilterConfig(enable, rssiFilterType, rssiFilterOption);
+ else Log.i("Hello2", "setRssiFilterConfig" + stringNOTCONNECT);
+ return false;
+ }
+ public double getRssiFilterThreshold1() {
+ if (DEBUG) Log.i("Hello2", "getRssiFilterThreshold1");
+ if (isCs108Connected()) return cs108Library4A.getRssiFilterThreshold1();
+ else if (isCs710Connected()) return cs710Library4A.getRssiFilterThreshold1();
+ else Log.i("Hello2", "getRssiFilterThreshold1" + stringNOTCONNECT);
+ return -1;
+ }
+ public double getRssiFilterThreshold2() {
+ if (DEBUG) Log.i("Hello2", "getRssiFilterThreshold2");
+ if (isCs108Connected()) return cs108Library4A.getRssiFilterThreshold2();
+ else if (isCs710Connected()) return cs710Library4A.getRssiFilterThreshold2();
+ else Log.i("Hello2", "getRssiFilterThreshold2" + stringNOTCONNECT);
+ return -1;
+ }
+ public boolean setRssiFilterThreshold(double rssiFilterThreshold1, double rssiFilterThreshold2) {
+ if (DEBUG) Log.i("Hello2", "setRssiFilterThreshold");
+ if (isCs108Connected()) return cs108Library4A.setRssiFilterThreshold(rssiFilterThreshold1, rssiFilterThreshold2);
+ else if (isCs710Connected()) return cs710Library4A.setRssiFilterThreshold(rssiFilterThreshold1, rssiFilterThreshold2);
+ else Log.i("Hello2", "setRssiFilterThreshold" + stringNOTCONNECT);
+ return false;
+ }
+ public long getRssiFilterCount() {
+ if (DEBUG) Log.i("Hello2", "getRssiFilterCount");
+ if (isCs108Connected()) return cs108Library4A.getRssiFilterCount();
+ else if (isCs710Connected()) return cs710Library4A.getRssiFilterCount();
+ else Log.i("Hello2", "getRssiFilterCount" + stringNOTCONNECT);
+ return -1;
+ }
+ public boolean setRssiFilterCount(long rssiFilterCount) {
+ Log.i("Hello2", "setRssiFilterCount");
+ return false;
+ }
+ public boolean getInvMatchEnable() {
+ if (DEBUG) Log.i("Hello2", "getInvMatchEnable");
+ if (isCs108Connected()) return cs108Library4A.getInvMatchEnable();
+ else if (isCs710Connected()) return cs710Library4A.getInvMatchEnable();
+ else Log.i("Hello2", "getInvMatchEnable" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean getInvMatchType() {
+ if (DEBUG) Log.i("Hello2", "getInvMatchType");
+ if (isCs108Connected()) return cs108Library4A.getInvMatchType();
+ else if (isCs710Connected()) return cs710Library4A.getInvMatchType();
+ else Log.i("Hello2", "getInvMatchType" + stringNOTCONNECT);
+ return false;
+ }
+ public int getInvMatchOffset() {
+ if (DEBUG) Log.i("Hello2", "getInvMatchOffset");
+ if (isCs108Connected()) return cs108Library4A.getInvMatchOffset();
+ else if (isCs710Connected()) return cs710Library4A.getInvMatchOffset();
+ else Log.i("Hello2", "getInvMatchOffset" + stringNOTCONNECT);
+ return -1;
+ }
+ public String getInvMatchData() {
+ if (DEBUG) Log.i("Hello2", "getInvMatchData");
+ if (isCs108Connected()) return cs108Library4A.getInvMatchData();
+ else if (isCs710Connected()) return cs710Library4A.getInvMatchData();
+ else Log.i("Hello2", "getInvMatchData" + stringNOTCONNECT);
+ return null;
+ }
+ public boolean setPostMatchCriteria(boolean enable, boolean target, int offset, String mask) {
+ if (DEBUG) Log.i("Hello2", "setPostMatchCriteria");
+ if (isCs108Connected()) return cs108Library4A.setPostMatchCriteria(enable, target, offset, mask);
+ else if (isCs710Connected()) return cs710Library4A.setPostMatchCriteria(enable, target, offset, mask);
+ else Log.i("Hello2", "setPostMatchCriteria" + stringNOTCONNECT);
+ return false;
+ }
+ public int mrfidToWriteSize() {
+ if (DEBUG2) Log.i("Hello2", "mrfidToWriteSize");
+ if (isCs108Connected()) return cs108Library4A.mrfidToWriteSize();
+ else if (isCs710Connected()) return cs710Library4A.mrfidToWriteSize();
+ else Log.i("Hello2", "mrfidToWriteSize" + stringNOTCONNECT);
+ return -1;
+ }
+ public void mrfidToWritePrint() {
+ Log.i("Hello2", "mrfidToWritePrint");
+ }
+ public long getTagRate() {
+ if (DEBUG) Log.i("Hello2", "getTagRate");
+ if (isCs108Connected()) return cs108Library4A.getTagRate();
+ else if (isCs710Connected()) return cs710Library4A.getTagRate();
+ else Log.i("Hello2", "getTagRate" + stringNOTCONNECT);
+ return -1;
+ }
+ public boolean startOperation(RfidReaderChipData.OperationTypes operationTypes) {
+ if (DEBUG) Log.i("Hello2", "startOperation");
+ if (isCs108Connected()) {
+ return cs108Library4A.startOperation(operationTypes);
+ } else if (isCs710Connected()) {
+ return cs710Library4A.startOperation(operationTypes);
+ }
+ else Log.i("Hello2", "startOperation" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean abortOperation() {
+ if (DEBUG) Log.i("Hello2", "abortOperation");
+ if (isCs108Connected()) return cs108Library4A.abortOperation();
+ else if (isCs710Connected()) return cs710Library4A.abortOperation();
+ else Log.i("Hello2", "abortOperation" + stringNOTCONNECT);
+ return false;
+ }
+ public void restoreAfterTagSelect() {
+ if (DEBUG | true) Log.i("Hello2", "restoreAfterTagSelect");
+ if (isCs108Connected()) cs108Library4A.restoreAfterTagSelect();
+ else if (isCs710Connected()) cs710Library4A.restoreAfterTagSelect();
+ else Log.i("Hello2", "restoreAfterTagSelect" + stringNOTCONNECT);
+ }
+ public boolean setSelectedTagByTID(String strTagId, long pwrlevel) {
+ appendToLog("csLibrary4A: setSelectCriteria setSelectedByTID strTagId = " + strTagId + ", pwrlevel = " + pwrlevel);
+ if (isCs108Connected()) return cs108Library4A.setSelectedTagByTID(strTagId, pwrlevel);
+ else if (isCs710Connected()) return cs710Library4A.setSelectedTagByTID(strTagId, pwrlevel);
+ else Log.i("Hello2", "setSelectedTagByTID" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean setSelectedTag(String strTagId, int selectBank, long pwrlevel) {
+ if (DEBUG) Log.i("Hello2", "setSelectedTag 1");
+ if (isCs108Connected()) return cs108Library4A.setSelectedTag(strTagId, selectBank, pwrlevel);
+ else if (isCs710Connected()) return cs710Library4A.setSelectedTag(strTagId, selectBank, pwrlevel);
+ else Log.i("Hello2", "setSelectedTag 1" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean setSelectedTag(boolean selectOne, String selectMask, int selectBank, int selectOffset, long pwrlevel, int qValue, int matchRep) {
+ appendToLog("csLibraryA: setSelectCriteria strTagId = " + selectMask + ", selectBank = " + selectBank + ", selectOffset = " + selectOffset + ", pwrlevel = " + pwrlevel + ", qValue = " + qValue + ", matchRep = " + matchRep);
+ if (isCs108Connected()) return cs108Library4A.setSelectedTag(selectOne, selectMask, selectBank, selectOffset, pwrlevel, qValue, matchRep);
+ else if (isCs710Connected()) return cs710Library4A.setSelectedTag(selectMask, selectBank, selectOffset, pwrlevel, qValue, matchRep);
+ else Log.i("Hello2", "setSelectedTag 2" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean setMatchRep(int matchRep) {
+ if (DEBUG) Log.i("Hello2", "setMatchRep");
+ if (isCs108Connected()) return cs108Library4A.setMatchRep(matchRep);
+ else if (isCs710Connected()) return cs710Library4A.setMatchRep(matchRep);
+ else Log.i("Hello2", "setMatchRep" + stringNOTCONNECT);
+ return false;
+ }
+ public String[] getCountryList() {
+ if (DEBUG) Log.i("Hello2", "getCountryList");
+ if (isCs108Connected()) return cs108Library4A.getCountryList();
+ else if (isCs710Connected()) return cs710Library4A.getCountryList();
+ else Log.i("Hello2", "getCountryList" + stringNOTCONNECT);
+ return null;
+ }
+ public int getCountryNumberInList() {
+ if (DEBUG) Log.i("Hello2", "getCountryNumberInList");
+ if (isCs108Connected()) return cs108Library4A.getCountryNumberInList();
+ else if (isCs710Connected()) return cs710Library4A.getCountryNumberInList();
+ else Log.i("Hello2", "getCountryNumberInList" + stringNOTCONNECT);
+ return -1;
+ }
+ public boolean setCountryInList(int countryInList) {
+ if (DEBUG || true) Log.i("Hello2", "setCountryInList");
+ if (isCs108Connected()) return cs108Library4A.setCountryInList(countryInList);
+ else if (isCs710Connected()) return cs710Library4A.setCountryInList(countryInList);
+ else Log.i("Hello2", "setCountryInList" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean getChannelHoppingStatus() {
+ if (DEBUG) Log.i("Hello2", "getChannelHoppingStatus");
+ if (isCs108Connected()) return cs108Library4A.getChannelHoppingStatus();
+ else if (isCs710Connected()) return cs710Library4A.getChannelHoppingStatus();
+ else Log.i("Hello2", "getChannelHoppingStatus" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean setChannelHoppingStatus(boolean channelOrderHopping) {
+ Log.i("Hello2", "setChannelHoppingStatus");
+ return false;
+ }
+ public String[] getChannelFrequencyList() {
+ if (isCs108Connected()) return cs108Library4A.getChannelFrequencyList();
+ else if (isCs710Connected()) return cs710Library4A.getChannelFrequencyList();
+ else Log.i("Hello2", "getChannelFrequencyList" + stringNOTCONNECT);
+ return null;
+ }
+ public int getChannel() {
+ if (DEBUG) Log.i("Hello2", "getChannel");
+ if (isCs108Connected()) return cs108Library4A.getChannel();
+ else if (isCs710Connected()) return cs710Library4A.getChannel();
+ else Log.i("Hello2", "getChannel" + stringNOTCONNECT);
+ return -1;
+ }
+ public boolean setChannel(int channelSelect) {
+ if (DEBUG) Log.i("Hello2", "setChannel");
+ if (isCs108Connected()) return cs108Library4A.setChannel(channelSelect);
+ else if (isCs710Connected()) return cs710Library4A.setChannel(channelSelect);
+ else Log.i("Hello2", "setChannel" + stringNOTCONNECT);
+ return false;
+ }
+ public byte getPopulation2Q(int population) {
+ if (DEBUG) Log.i("Hello2", "getPopulation2Q");
+ if (isCs108Connected()) return cs108Library4A.getPopulation2Q(population);
+ else if (isCs710Connected()) return cs710Library4A.getPopulation2Q(population);
+ else Log.i("Hello2", "getPopulation2Q" + stringNOTCONNECT);
+ return -1;
+ }
+ public int getPopulation() {
+ if (DEBUG) Log.i("Hello2", "getPopulation");
+ if (isCs108Connected()) return cs108Library4A.getPopulation();
+ else if (isCs710Connected()) return cs710Library4A.getPopulation();
+ else Log.i("Hello2", "getPopulation" + stringNOTCONNECT);
+ return -1;
+ } //3348
+ public boolean setPopulation(int population) {
+ if (DEBUG || true) Log.i("Hello2", "setPopulation " + population);
+ if (isCs108Connected()) return cs108Library4A.setPopulation(population);
+ else if (isCs710Connected()) return cs710Library4A.setPopulation(population);
+ else Log.i("Hello2", "setPopulation" + stringNOTCONNECT);
+ return false;
+ }
+ public byte getQValue() {
+ if (DEBUG) Log.i("Hello2", "getQValue");
+ if (isCs108Connected()) return cs108Library4A.getQValue();
+ else if (isCs710Connected()) return cs710Library4A.getQValue();
+ else Log.i("Hello2", "getQValue" + stringNOTCONNECT);
+ return -1;
+ }
+ public boolean setQValue(byte byteValue) {
+ if (DEBUG) Log.i("Hello2", "setQValue");
+ if (isCs108Connected()) return cs108Library4A.setQValue(byteValue);
+ else if (isCs710Connected()) return cs710Library4A.setQValue(byteValue);
+ else Log.i("Hello2", "setQValue" + stringNOTCONNECT);
+ return false;
+ }
+ public RfidReaderChipData.Rx000pkgData onRFIDEvent() {
+ if (DEBUG2) Log.i("Hello2", "onRFIDEvent");
+ if (isCs108Connected()) {
+ RfidReaderChipData.Rx000pkgData rx000pkgData = null;
+ RfidReaderChipData.Rx000pkgData rx000pkgData1 = cs108Library4A.onRFIDEvent();
+ if (rx000pkgData1 != null) {
+ rx000pkgData = new RfidReaderChipData.Rx000pkgData();
+ switch (rx000pkgData1.responseType) {
+ case TYPE_18K6C_INVENTORY_COMPACT:
+ rx000pkgData.responseType = RfidReaderChipData.HostCmdResponseTypes.TYPE_18K6C_INVENTORY_COMPACT;
+ break;
+ case TYPE_18K6C_INVENTORY:
+ rx000pkgData.responseType = RfidReaderChipData.HostCmdResponseTypes.TYPE_18K6C_INVENTORY;
+ break;
+ case TYPE_COMMAND_ABORT_RETURN:
+ rx000pkgData.responseType = RfidReaderChipData.HostCmdResponseTypes.TYPE_COMMAND_ABORT_RETURN;
+ break;
+ case TYPE_COMMAND_END:
+ rx000pkgData.responseType = RfidReaderChipData.HostCmdResponseTypes.TYPE_COMMAND_END;
+ break;
+ case TYPE_18K6C_TAG_ACCESS:
+ rx000pkgData.responseType = RfidReaderChipData.HostCmdResponseTypes.TYPE_18K6C_TAG_ACCESS;
+ break;
+ default:
+ Log.i("Hello2", "onRFIDEvent: responseType = " + rx000pkgData1.responseType.toString());
+ }
+ rx000pkgData.flags = rx000pkgData1.flags;
+ rx000pkgData.dataValues = rx000pkgData1.dataValues;
+ rx000pkgData.decodedTime = rx000pkgData1.decodedTime;
+ rx000pkgData.decodedRssi = rx000pkgData1.decodedRssi;
+ rx000pkgData.decodedPhase = rx000pkgData1.decodedPhase;
+ rx000pkgData.decodedChidx = rx000pkgData1.decodedChidx;
+ rx000pkgData.decodedPort = rx000pkgData1.decodedPort;
+ rx000pkgData.decodedPc = rx000pkgData1.decodedPc;
+ rx000pkgData.decodedEpc = rx000pkgData1.decodedEpc;
+ rx000pkgData.decodedCrc = rx000pkgData1.decodedCrc;
+ rx000pkgData.decodedData1 = rx000pkgData1.decodedData1;
+ rx000pkgData.decodedData2 = rx000pkgData1.decodedData2;
+ rx000pkgData.decodedResult = rx000pkgData1.decodedResult;
+ rx000pkgData.decodedError = rx000pkgData1.decodedError;
+ }
+ return rx000pkgData;
+ } else if (isCs710Connected()) {
+ RfidReaderChipData.Rx000pkgData rx000pkgData = null;
+ RfidReaderChipData.Rx000pkgData rx000pkgData1 = cs710Library4A.onRFIDEvent();
+ if (rx000pkgData1 != null) {
+ rx000pkgData = new RfidReaderChipData.Rx000pkgData();
+ switch (rx000pkgData1.responseType) {
+ case TYPE_18K6C_INVENTORY_COMPACT:
+ rx000pkgData.responseType = RfidReaderChipData.HostCmdResponseTypes.TYPE_18K6C_INVENTORY_COMPACT;
+ break;
+ case TYPE_18K6C_INVENTORY:
+ rx000pkgData.responseType = RfidReaderChipData.HostCmdResponseTypes.TYPE_18K6C_INVENTORY;
+ break;
+ case TYPE_COMMAND_ABORT_RETURN:
+ rx000pkgData.responseType = RfidReaderChipData.HostCmdResponseTypes.TYPE_COMMAND_ABORT_RETURN;
+ break;
+ case TYPE_COMMAND_END:
+ rx000pkgData.responseType = RfidReaderChipData.HostCmdResponseTypes.TYPE_COMMAND_END;
+ break;
+ case TYPE_18K6C_TAG_ACCESS:
+ rx000pkgData.responseType = RfidReaderChipData.HostCmdResponseTypes.TYPE_18K6C_TAG_ACCESS;
+ break;
+ default:
+ Log.i("Hello2", "onRFIDEvent: responseType = " + rx000pkgData1.responseType.toString());
+ }
+ rx000pkgData.flags = rx000pkgData1.flags;
+ rx000pkgData.dataValues = rx000pkgData1.dataValues;
+ rx000pkgData.decodedTime = rx000pkgData1.decodedTime;
+ rx000pkgData.decodedRssi = rx000pkgData1.decodedRssi;
+ rx000pkgData.decodedPhase = rx000pkgData1.decodedPhase;
+ rx000pkgData.decodedChidx = rx000pkgData1.decodedChidx;
+ rx000pkgData.decodedPort = rx000pkgData1.decodedPort;
+ rx000pkgData.decodedPc = rx000pkgData1.decodedPc;
+ rx000pkgData.decodedEpc = rx000pkgData1.decodedEpc;
+ rx000pkgData.decodedCrc = rx000pkgData1.decodedCrc;
+ rx000pkgData.decodedData1 = rx000pkgData1.decodedData1;
+ rx000pkgData.decodedData2 = rx000pkgData1.decodedData2;
+ rx000pkgData.decodedResult = rx000pkgData1.decodedResult;
+ rx000pkgData.decodedError = rx000pkgData1.decodedError;
+ }
+ if (rx000pkgData != null) appendToLog("response0 = " + rx000pkgData.responseType.toString() + ", " + byteArrayToString(rx000pkgData.dataValues));
+ return rx000pkgData;
+ }
+ else Log.i("Hello2", "onRFIDEvent" + stringNOTCONNECT);
+ return null;
+ }
+ public String getModelNumber() {
+ if (DEBUG) Log.i("Hello2", "getModelNumber");
+ if (isCs108Connected()) return cs108Library4A.getModelNumber();
+ else if (isCs710Connected()) return cs710Library4A.getModelNumber();
+ else Log.i("Hello2", "getModelNumber" + stringNOTCONNECT);
+ return null;
+ }
+ public boolean setRx000KillPassword(String password) {
+ if (DEBUG) Log.i("Hello2", "setRx000KillPassword");
+ if (isCs108Connected()) return cs108Library4A.setRx000KillPassword(password);
+ else if (isCs710Connected()) return cs710Library4A.setRx000KillPassword(password);
+ else Log.i("Hello2", "setRx000KillPassword" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean setRx000AccessPassword(String password) {
+ if (DEBUG) Log.i("Hello2", "setRx000AccessPassword");
+ if (isCs108Connected()) return cs108Library4A.setRx000AccessPassword(password);
+ else if (isCs710Connected()) return cs710Library4A.setRx000AccessPassword(password);
+ else Log.i("Hello2", "setRx000AccessPassword" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean setAccessRetry(boolean accessVerfiy, int accessRetry) {
+ if (DEBUG) Log.i("Hello2", "setAccessRetry");
+ if (isCs108Connected()) return cs108Library4A.setAccessRetry(accessVerfiy, accessRetry);
+ else if (isCs710Connected()) return cs710Library4A.setAccessRetry(accessVerfiy, accessRetry);
+ else Log.i("Hello2", "setAccessRetry" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean setInvModeCompact(boolean invModeCompact) {
+ if (DEBUG) Log.i("Hello2", "setInvModeCompact");
+ if (isCs108Connected()) return cs108Library4A.setInvModeCompact(invModeCompact);
+ else if (isCs710Connected()) return cs710Library4A.setInvModeCompact(invModeCompact);
+ else Log.i("Hello2", "setInvModeCompact" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean setAccessLockAction(int accessLockAction, int accessLockMask) {
+ if (DEBUG) Log.i("Hello2", "setAccessLockAction");
+ if (isCs108Connected()) return cs108Library4A.setAccessLockAction(accessLockAction, accessLockMask);
+ else if (isCs710Connected()) return cs710Library4A.setAccessLockAction(accessLockAction, accessLockMask);
+ else Log.i("Hello2", "setAccessLockAction" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean setAccessBank(int accessBank) {
+ if (DEBUG) Log.i("Hello2", "setAccessBank 1");
+ if (isCs108Connected()) return cs108Library4A.setAccessBank(accessBank);
+ else if (isCs710Connected()) return cs710Library4A.setAccessBank(accessBank);
+ else Log.i("Hello2", "setAccessBank 1" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean setAccessBank(int accessBank, int accessBank2) {
+ if (DEBUG) Log.i("Hello2", "setAccessBank 2");
+ if (isCs108Connected()) return cs108Library4A.setAccessBank(accessBank, accessBank2);
+ else if (isCs710Connected()) return cs710Library4A.setAccessBank(accessBank, accessBank2);
+ else Log.i("Hello2", "setAccessBank 2" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean setAccessOffset(int accessOffset) {
+ if (DEBUG) Log.i("Hello2", "setAccessOffset 1");
+ if (isCs108Connected()) return cs108Library4A.setAccessOffset(accessOffset);
+ else if (isCs710Connected()) return cs710Library4A.setAccessOffset(accessOffset);
+ else Log.i("Hello2", "setAccessOffset 1" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean setAccessOffset(int accessOffset, int accessOffset2) {
+ if (DEBUG) Log.i("Hello2", "setAccessOffset 2");
+ if (isCs108Connected()) return cs108Library4A.setAccessOffset(accessOffset, accessOffset2);
+ else if (isCs710Connected()) return cs710Library4A.setAccessOffset(accessOffset, accessOffset2);
+ else Log.i("Hello2", "setAccessOffset 2" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean setAccessCount(int accessCount) {
+ if (DEBUG) Log.i("Hello2", "setAccessCount 1");
+ if (isCs108Connected()) return cs108Library4A.setAccessCount(accessCount);
+ else if (isCs710Connected()) return cs710Library4A.setAccessCount(accessCount);
+ else Log.i("Hello2", "setAccessCount 1" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean setAccessCount(int accessCount, int accessCount2) {
+ if (DEBUG) Log.i("Hello2", "setAccessCount 2");
+ if (isCs108Connected()) return cs108Library4A.setAccessCount(accessCount, accessCount2);
+ else if (isCs710Connected()) return cs710Library4A.setAccessCount(accessCount, accessCount2);
+ else Log.i("Hello2", "setAccessCount 2" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean setAccessWriteData(String dataInput) {
+ if (DEBUG) Log.i("Hello2", "setAccessWriteData");
+ if (isCs108Connected()) return cs108Library4A.setAccessWriteData(dataInput);
+ else if (isCs710Connected()) return cs710Library4A.setAccessWriteData(dataInput);
+ else Log.i("Hello2", "setAccessWriteData" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean setResReadNoReply(boolean resReadNoReply) {
+ if (DEBUG) Log.i("Hello2", "setResReadNoReply");
+ if (isCs108Connected()) return false;
+ else if (isCs710Connected()) return cs710Library4A.setResReadNoReply(resReadNoReply);
+ else Log.i("Hello2", "setResReadNoReply" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean setTagRead(int tagRead) {
+ if (DEBUG) Log.i("Hello2", "setTagRead");
+ if (isCs108Connected()) return cs108Library4A.setTagRead(tagRead);
+ else if (isCs710Connected()) return cs710Library4A.setTagRead(tagRead);
+ else Log.i("Hello2", "setTagRead" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean setInvBrandId(boolean invBrandId) {
+ if (DEBUG) Log.i("Hello2", "setInvBrandId");
+ if (isCs108Connected()) return cs108Library4A.setInvBrandId(invBrandId);
+ else if (isCs710Connected()) return cs710Library4A.setInvBrandId(invBrandId);
+ else Log.i("Hello2", "setInvBrandId" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean setInvAuthenticate(boolean invAuthenticate) {
+ if (DEBUG) Log.i("Hello2", "setInvBrandId");
+ if (isCs108Connected()) return cs108Library4A.setInvAuthenticate(invAuthenticate);
+ else if (isCs710Connected()) return cs710Library4A.setInvAuthenticate(invAuthenticate);
+ else Log.i("Hello2", "setInvAuthenticate" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean sendHostRegRequestHST_CMD(RfidReaderChipData.HostCommands hostCommand) {
+ if (DEBUG | true) Log.i("Hello2", "sendHostRegRequestHST_CMD with hostCommand = " + hostCommand.toString());
+ if (isCs108Connected()) {
+ RfidReaderChipData.HostCommands hostCommands1 = null;
+ switch (hostCommand) {
+ case CMD_18K6CREAD:
+ hostCommands1 = RfidReaderChipData.HostCommands.CMD_18K6CREAD;
+ break;
+ case CMD_18K6CWRITE:
+ hostCommands1 = RfidReaderChipData.HostCommands.CMD_18K6CWRITE;
+ break;
+ case CMD_18K6CLOCK:
+ hostCommands1 = RfidReaderChipData.HostCommands.CMD_18K6CLOCK;
+ break;
+ case CMD_18K6CKILL:
+ hostCommands1 = RfidReaderChipData.HostCommands.CMD_18K6CKILL;
+ break;
+ case CMD_18K6CAUTHENTICATE:
+ hostCommands1 = RfidReaderChipData.HostCommands.CMD_18K6CAUTHENTICATE;
+ break;
+ case CMD_UNTRACEABLE:
+ hostCommands1 = RfidReaderChipData.HostCommands.CMD_UNTRACEABLE;
+ break;
+ case CMD_GETSENSORDATA:
+ hostCommands1 = RfidReaderChipData.HostCommands.CMD_GETSENSORDATA;
+ break;
+ case CMD_FDM_RDMEM:
+ hostCommands1 = RfidReaderChipData.HostCommands.CMD_FDM_RDMEM;
+ break;
+ case CMD_FDM_WRMEM:
+ hostCommands1 = RfidReaderChipData.HostCommands.CMD_FDM_WRMEM;
+ break;
+ case CMD_FDM_AUTH:
+ hostCommands1 = RfidReaderChipData.HostCommands.CMD_FDM_AUTH;
+ break;
+ case CMD_FDM_GET_TEMPERATURE:
+ hostCommands1 = RfidReaderChipData.HostCommands.CMD_FDM_GET_TEMPERATURE;
+ break;
+ case CMD_FDM_START_LOGGING:
+ hostCommands1 = RfidReaderChipData.HostCommands.CMD_FDM_START_LOGGING;
+ break;
+ case CMD_FDM_STOP_LOGGING:
+ hostCommands1 = RfidReaderChipData.HostCommands.CMD_FDM_STOP_LOGGING;
+ break;
+ case CMD_FDM_WRREG:
+ hostCommands1 = RfidReaderChipData.HostCommands.CMD_FDM_WRREG;
+ break;
+ case CMD_FDM_RDREG:
+ hostCommands1 = RfidReaderChipData.HostCommands.CMD_FDM_RDREG;
+ break;
+ case CMD_FDM_DEEP_SLEEP:
+ hostCommands1 = RfidReaderChipData.HostCommands.CMD_FDM_DEEP_SLEEP;
+ break;
+ case CMD_FDM_OPMODE_CHECK:
+ hostCommands1 = RfidReaderChipData.HostCommands.CMD_FDM_OPMODE_CHECK;
+ break;
+ case CMD_FDM_INIT_REGFILE:
+ hostCommands1 = RfidReaderChipData.HostCommands.CMD_FDM_INIT_REGFILE;
+ break;
+ case CMD_FDM_LED_CTRL:
+ hostCommands1 = RfidReaderChipData.HostCommands.CMD_FDM_LED_CTRL;
+ break;
+ default:
+ Log.i("Hello2", "Skip sendHostRegRequestHST_CMD: hostCommand = " + hostCommand.toString());
+ break;
+ }
+ if (hostCommands1 == null) return false;
+ else return cs108Library4A.sendHostRegRequestHST_CMD(hostCommands1);
+ } else if (isCs710Connected()) {
+ RfidReaderChipData.HostCommands hostCommands1 = null;
+ switch (hostCommand) {
+ case CMD_18K6CREAD:
+ hostCommands1 = RfidReaderChipData.HostCommands.CMD_18K6CREAD;
+ break;
+ case CMD_18K6CWRITE:
+ hostCommands1 = RfidReaderChipData.HostCommands.CMD_18K6CWRITE;
+ break;
+ case CMD_18K6CLOCK:
+ hostCommands1 = RfidReaderChipData.HostCommands.CMD_18K6CLOCK;
+ break;
+ case CMD_18K6CKILL:
+ hostCommands1 = RfidReaderChipData.HostCommands.CMD_18K6CKILL;
+ break;
+ case CMD_18K6CAUTHENTICATE:
+ hostCommands1 = RfidReaderChipData.HostCommands.CMD_18K6CAUTHENTICATE;
+ break;
+ case CMD_UNTRACEABLE:
+ hostCommands1 = RfidReaderChipData.HostCommands.CMD_UNTRACEABLE;
+ break;
+ case CMD_GETSENSORDATA:
+ hostCommands1 = RfidReaderChipData.HostCommands.CMD_GETSENSORDATA;
+ default:
+ Log.i("Hello2", "sendHostRegRequestHST_CMD: hostCommand = " + hostCommand.toString());
+ break;
+ }
+ if (hostCommands1 == null) return false;
+ return cs710Library4A.sendHostRegRequestHST_CMD(hostCommands1);
+ }
+ else Log.i("Hello2", "sendHostRegRequestHST_CMD" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean setPwrManagementMode(boolean bLowPowerStandby) {
+ if (DEBUG) Log.i("Hello2", "setPwrManagementMode");
+ if (isCs108Connected()) return cs108Library4A.setPwrManagementMode(bLowPowerStandby);
+ else if (isCs710Connected()) return cs710Library4A.setPwrManagementMode(bLowPowerStandby);
+ return false;
+ }
+ public void macWrite(int address, long value) {
+ if (DEBUG) Log.i("Hello2", "macWrite");
+ if (isCs108Connected()) cs108Library4A.macWrite(address, value);
+ else if (isCs710Connected()) { }
+ }
+ public void set_fdCmdCfg(int value) {
+ if (DEBUG) Log.i("Hello2", "set_fdCmdCfg");
+ if (isCs108Connected()) cs108Library4A.set_fdCmdCfg(value);
+ else if (isCs710Connected()) { }
+ }
+ public void set_fdRegAddr(int addr) {
+ if (DEBUG) Log.i("Hello2", "set_fdRegAddr");
+ if (isCs108Connected()) cs108Library4A.set_fdRegAddr(addr);
+ else if (isCs710Connected()) { }
+ }
+ public void set_fdWrite(int addr, long value) {
+ if (DEBUG) Log.i("Hello2", "set_fdWrite");
+ if (isCs108Connected()) cs108Library4A.set_fdWrite(addr, value);
+ else if (isCs710Connected()) { }
+ }
+ public void set_fdPwd(int value) {
+ if (DEBUG) Log.i("Hello2", "set_fdPwd");
+ if (isCs108Connected()) cs108Library4A.set_fdPwd(value);
+ else if (isCs710Connected()) { }
+ }
+ public void set_fdBlockAddr4GetTemperature(int addr) {
+ if (DEBUG) Log.i("Hello2", "set_fdBlockAddr4GetTemperature");
+ if (isCs108Connected()) cs108Library4A.set_fdBlockAddr4GetTemperature(addr);
+ else if (isCs710Connected()) { }
+ }
+ public void set_fdReadMem(int addr, long len) {
+ if (DEBUG) Log.i("Hello2", "set_fdReadMem");
+ if (isCs108Connected()) cs108Library4A.set_fdReadMem(addr, len);
+ else if (isCs710Connected()) { }
+ }
+ public void set_fdWriteMem(int addr, int len, long value) {
+ if (DEBUG) Log.i("Hello2", "set_fdWriteMem");
+ if (isCs108Connected()) cs108Library4A.set_fdWriteMem(addr, len, value);
+ else if (isCs710Connected()) { }
+ }
+ public void setImpinJExtension(boolean tagFocus, boolean fastId) {
+ if (DEBUG) Log.i("Hello2", "setImpinJExtension with tagFocus = " + tagFocus + ", fastId = " + fastId);
+ if (isCs108Connected()) cs108Library4A.setImpinJExtension(tagFocus, fastId);
+ else if (isCs710Connected()) cs710Library4A.setImpinJExtension(tagFocus, fastId);
+ else Log.i("Hello2", "setImpinJExtension" + stringNOTCONNECT);
+ }
+
+ //============ Barcode ============
+ public void getBarcodePreSuffix() {
+ if (DEBUG) Log.i("Hello2", "getBarcodePreSuffix");
+ if (isCs108Connected()) cs108Library4A.getBarcodePreSuffix();
+ else if (isCs710Connected()) cs710Library4A.getBarcodePreSuffix();
+ else Log.i("Hello2", "getBarcodePreSuffix" + stringNOTCONNECT);
+ }
+ public void getBarcodeReadingMode() {
+ if (DEBUG) Log.i("Hello2", "getBarcodeReadingMode");
+ if (isCs108Connected()) cs108Library4A.getBarcodeReadingMode();
+ else if (isCs710Connected()) cs710Library4A.getBarcodeReadingMode();
+ else Log.i("Hello2", "getBarcodeReadingMode" + stringNOTCONNECT);
+ }
+ public boolean isBarcodeFailure() {
+ if (DEBUG) Log.i("Hello2", "isBarcodeFailure");
+ if (isCs108Connected()) return cs108Library4A.isBarcodeFailure();
+ else if (isCs710Connected()) return cs710Library4A.isBarcodeFailure();
+ else Log.i("Hello2", "isBarcodeFailure" + stringNOTCONNECT);
+ return false;
+ }
+ public String getBarcodeDate() {
+ if (DEBUG) Log.i("Hello2", "getBarcodeDate");
+ if (isCs108Connected()) return cs108Library4A.getBarcodeDate();
+ else if (isCs710Connected()) return cs710Library4A.getBarcodeDate();
+ else Log.i("Hello2", "getBarcodeDate" + stringNOTCONNECT);
+ return null;
+ }
+ public boolean getBarcodeOnStatus() {
+ if (DEBUG) Log.i("Hello2", "getBarcodeOnStatus");
+ if (isCs108Connected()) return cs108Library4A.getBarcodeOnStatus();
+ else if (isCs710Connected()) return cs710Library4A.getBarcodeOnStatus();
+ else Log.i("Hello2", "getBarcodeOnStatus" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean setBarcodeOn(boolean on) {
+ if (DEBUG) Log.i("Hello2", "setBarcodeOn");
+ if (isCs108Connected()) return cs108Library4A.setBarcodeOn(on);
+ else if (isCs710Connected()) return cs710Library4A.setBarcodeOn(on);
+ else Log.i("Hello2", "setBarcodeOn" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean setVibrateOn(int mode) {
+ if (DEBUG || true) Log.i("Hello2", "setVibrateOn with mode = " + mode);
+ if (isCs108Connected()) return cs108Library4A.setVibrateOn(mode);
+ else if (isCs710Connected()) return cs710Library4A.setVibrateOn(mode);
+ else Log.i("Hello2", "setVibrateOn" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean getInventoryVibrate() {
+ if (DEBUG) Log.i("Hello2", "getInventoryVibrate");
+ if (isCs108Connected()) return cs108Library4A.getInventoryVibrate();
+ else if (isCs710Connected()) return cs710Library4A.getInventoryVibrate();
+ else Log.i("Hello2", "getInventoryVibrate" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean setInventoryVibrate(boolean inventoryVibrate) {
+ if (DEBUG) Log.i("Hello2", "setInventoryVibrate");
+ if (isCs108Connected()) return cs108Library4A.setInventoryVibrate(inventoryVibrate);
+ else if (isCs710Connected()) return cs710Library4A.setInventoryVibrate(inventoryVibrate);
+ else Log.i("Hello2", "setInventoryVibrate" + stringNOTCONNECT);
+ return false;
+ }
+ public int getVibrateTime() {
+ if (DEBUG) Log.i("Hello2", "getVibrateTime");
+ if (isCs108Connected()) return cs108Library4A.getVibrateTime();
+ else if (isCs710Connected()) return cs710Library4A.getVibrateTime();
+ else Log.i("Hello2", "getVibrateTime" + stringNOTCONNECT);
+ return -1;
+ }
+ public boolean setVibrateTime(int vibrateTime) {
+ if (DEBUG) Log.i("Hello2", "setVibrateTime");
+ if (isCs108Connected()) return cs108Library4A.setVibrateTime(vibrateTime);
+ else if (isCs710Connected()) return cs710Library4A.setVibrateTime(vibrateTime);
+ else Log.i("Hello2", "setVibrateTime" + stringNOTCONNECT);
+ return false;
+ }
+ public int getVibrateWindow() {
+ if (DEBUG) Log.i("Hello2", "getVibrateWindow");
+ if (isCs108Connected()) return cs108Library4A.getVibrateWindow();
+ else if (isCs710Connected()) return cs710Library4A.getVibrateWindow();
+ else Log.i("Hello2", "getVibrateWindow" + stringNOTCONNECT);
+ return -1;
+ }
+ public boolean setVibrateWindow(int vibrateWindow) {
+ if (DEBUG) Log.i("Hello2", "setVibrateWindow");
+ if (isCs108Connected()) return cs108Library4A.setVibrateWindow(vibrateWindow);
+ else if (isCs710Connected()) return cs710Library4A.setVibrateWindow(vibrateWindow);
+ else Log.i("Hello2", "setVibrateWindow" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean barcodeSendCommandTrigger() {
+ if (DEBUG) Log.i("Hello2", "barcodeSendCommandTrigger");
+ if (isCs108Connected()) return cs108Library4A.barcodeSendCommandTrigger();
+ else if (isCs710Connected()) return cs710Library4A.barcodeSendCommandTrigger();
+ else Log.i("Hello2", "barcodeSendCommandTrigger" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean barcodeSendCommandSetPreSuffix() {
+ if (DEBUG) Log.i("Hello2", "barcodeSendCommandSetPreSuffix");
+ if (isCs108Connected()) return cs108Library4A.barcodeSendCommandSetPreSuffix();
+ else if (isCs710Connected()) return cs710Library4A.barcodeSendCommandSetPreSuffix();
+ else Log.i("Hello2", "barcodeSendCommandSetPreSuffix" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean barcodeSendCommandResetPreSuffix() {
+ if (DEBUG) Log.i("Hello2", "barcodeSendCommandResetPreSuffix");
+ if (isCs108Connected()) return cs108Library4A.barcodeSendCommandResetPreSuffix();
+ else if (isCs710Connected()) return cs710Library4A.barcodeSendCommandResetPreSuffix();
+ else Log.i("Hello2", "barcodeSendCommandResetPreSuffix" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean barcodeSendCommandConinuous() {
+ if (DEBUG) Log.i("Hello2", "barcodeSendCommandConinuous");
+ if (isCs108Connected()) return cs108Library4A.barcodeSendCommandConinuous();
+ else if (isCs710Connected()) return cs710Library4A.barcodeSendCommandConinuous();
+ else Log.i("Hello2", "barcodeSendCommandConinuous" + stringNOTCONNECT);
+ return false;
+ }
+ public String getBarcodeVersion() {
+ if (DEBUG) Log.i("Hello2", "getBarcodeVersion");
+ if (isCs108Connected()) return cs108Library4A.getBarcodeVersion();
+ else if (isCs710Connected()) return cs710Library4A.getBarcodeVersion();
+ else Log.i("Hello2", "getBarcodeVersion" + stringNOTCONNECT);
+ return null;
+ }
+ public String getBarcodeSerial() {
+ if (DEBUG) Log.i("Hello2", "getBarcodeSerial");
+ if (isCs108Connected()) return cs108Library4A.getBarcodeSerial();
+ else if (isCs710Connected()) return cs710Library4A.getBarcodeSerial();
+ else Log.i("Hello2", "getBarcodeSerial" + stringNOTCONNECT);
+ return null;
+ }
+ public boolean barcodeInventory(boolean start) {
+ if (DEBUG) Log.i("Hello2", "barcodeInventory");
+ if (isCs108Connected()) return cs108Library4A.barcodeInventory(start);
+ else if (isCs710Connected()) return cs710Library4A.barcodeInventory(start);
+ else Log.i("Hello2", "barcodeInventory" + stringNOTCONNECT);
+ return false;
+ }
+ public byte[] onBarcodeEvent() {
+ if (DEBUG) Log.i("Hello2", "onBarcodeEvent");
+ if (isCs108Connected()) return cs108Library4A.onBarcodeEvent();
+ else if (isCs710Connected()) return cs710Library4A.onBarcodeEvent();
+ else Log.i("Hello2", "onBarcodeEvent" + stringNOTCONNECT);
+ return null;
+ }
+
+ //============ Android General ============
+ public void setSameCheck(boolean sameCheck1) {
+ if (DEBUG) Log.i("Hello2", "setSameCheck");
+ if (isCs108Connected()) cs108Library4A.setSameCheck(sameCheck1);
+ else if (isCs710Connected()) cs710Library4A.setSameCheck(sameCheck1);
+ else Log.i("Hello2", "setSameCheck" + stringNOTCONNECT);
+ }
+ public void saveSetting2File() {
+ if (DEBUG) Log.i("Hello2", "saveSetting2File");
+ if (isCs108Connected()) cs108Library4A.saveSetting2File();
+ else if (isCs710Connected()) cs710Library4A.saveSetting2File();
+ else Log.i("Hello2", "saveSetting2File" + stringNOTCONNECT);
+ }
+ public int getBeepCount() {
+ if (DEBUG) Log.i("Hello2", "getBeepCount");
+ if (isCs108Connected()) return cs108Library4A.getBeepCount();
+ else if (isCs710Connected()) return cs710Library4A.getBeepCount();
+ else Log.i("Hello2", "getBeepCount" + stringNOTCONNECT);
+ return -1;
+ }
+ public boolean setBeepCount(int beepCount) {
+ if (DEBUG) Log.i("Hello2", "setBeepCount");
+ if (isCs108Connected()) return cs108Library4A.setBeepCount(beepCount);
+ else if (isCs710Connected()) return cs710Library4A.setBeepCount(beepCount);
+ else Log.i("Hello2", "setBeepCount" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean getInventoryBeep() {
+ if (DEBUG) Log.i("Hello2", "getInventoryBeep");
+ if (isCs108Connected()) return cs108Library4A.getInventoryBeep();
+ else if (isCs710Connected()) return cs710Library4A.getInventoryBeep();
+ else Log.i("Hello2", "getInventoryBeep" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean setInventoryBeep(boolean inventoryBeep) {
+ if (DEBUG) Log.i("Hello2", "setInventoryBeep");
+ if (isCs108Connected()) return cs108Library4A.setInventoryBeep(inventoryBeep);
+ else if (isCs710Connected()) return cs710Library4A.setInventoryBeep(inventoryBeep);
+ else Log.i("Hello2", "setInventoryBeep" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean getSaveFileEnable() {
+ if (DEBUG) Log.i("Hello2", "getSaveFileEnable");
+ if (isCs108Connected()) return cs108Library4A.getSaveFileEnable();
+ else if (isCs710Connected()) return cs710Library4A.getSaveFileEnable();
+ else Log.i("Hello2", "getSaveFileEnable" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean setSaveFileEnable(boolean saveFileEnable) {
+ if (DEBUG) Log.i("Hello2", "setSaveFileEnable");
+ if (isCs108Connected()) return cs108Library4A.setSaveFileEnable(saveFileEnable);
+ else if (isCs710Connected()) return cs710Library4A.setSaveFileEnable(saveFileEnable);
+ else Log.i("Hello2", "setSaveFileEnable" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean getSaveCloudEnable() {
+ if (DEBUG) Log.i("Hello2", "getSaveCloudEnable");
+ if (isCs108Connected()) return cs108Library4A.getSaveCloudEnable();
+ else if (isCs710Connected()) return cs710Library4A.getSaveCloudEnable();
+ else Log.i("Hello2", "getSaveCloudEnable" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean setSaveCloudEnable(boolean saveCloudEnable) {
+ if (DEBUG) Log.i("Hello2", "setSaveCloudEnable");
+ if (isCs108Connected()) return cs108Library4A.setSaveCloudEnable(saveCloudEnable);
+ else if (isCs710Connected()) return cs710Library4A.setSaveCloudEnable(saveCloudEnable);
+ else Log.i("Hello2", "setSaveCloudEnable" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean getSaveNewCloudEnable() {
+ if (DEBUG) Log.i("Hello2", "getSaveNewCloudEnable");
+ if (isCs108Connected()) return cs108Library4A.getSaveNewCloudEnable();
+ else if (isCs710Connected()) return cs710Library4A.getSaveNewCloudEnable();
+ else Log.i("Hello2", "getSaveNewCloudEnable" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean setSaveNewCloudEnable(boolean saveNewCloudEnable) {
+ Log.i("Hello2", "setSaveNewCloudEnable");
+ return false;
+ }
+ public boolean getSaveAllCloudEnable() {
+ if (DEBUG) Log.i("Hello2", "getSaveAllCloudEnable");
+ if (isCs108Connected()) return cs108Library4A.getSaveAllCloudEnable();
+ else if (isCs710Connected()) return cs710Library4A.getSaveAllCloudEnable();
+ else Log.i("Hello2", "getSaveAllCloudEnable" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean setSaveAllCloudEnable(boolean saveAllCloudEnable) {
+ Log.i("Hello2", "setSaveAllCloudEnable");
+ return false;
+ }
+ public boolean getUserDebugEnable() {
+ if (DEBUG) Log.i("Hello2", "getUserDebugEnable");
+ if (isCs108Connected()) return cs108Library4A.getUserDebugEnable();
+ else if (isCs710Connected()) return cs710Library4A.getUserDebugEnable();
+ else Log.i("Hello2", "getUserDebugEnable" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean setUserDebugEnable(boolean userDebugEnable) {
+ if (DEBUG) Log.i("Hello2", "setUserDebugEnable");
+ if (isCs108Connected()) return cs108Library4A.setUserDebugEnable(userDebugEnable);
+ else if (isCs710Connected()) return cs710Library4A.setUserDebugEnable(userDebugEnable);
+ else Log.i("Hello2", "getUserDebugEnable" + stringNOTCONNECT);
+ return false;
+ }
+ public String getForegroundReader() {
+ String string = null;
+ if (isCs710Connected()) string = cs710Library4A.getForegroundReader().trim();
+ else string = (cs108Library4A == null ? null : cs108Library4A.getForegroundReader().trim());
+ return string;
+ }
+ public boolean getForegroundServiceEnable() {
+ if (DEBUG) Log.i("Hello2", "getForegroundEnable");
+ if (isCs108Connected()) return cs108Library4A.getForegroundServiceEnable();
+ else if (isCs710Connected()) return cs710Library4A.getForegroundServiceEnable();
+ else Log.i("Hello2", "getForegroundEnable" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean setForegroundServiceEnable(boolean forgroundServiceEnable) {
+ if (DEBUG) Log.i("Hello2", "setForegroundServiceEnable");
+ if (isCs108Connected()) return cs108Library4A.setForegroundServiceEnable(forgroundServiceEnable);
+ else if (isCs710Connected()) return cs710Library4A.setForegroundServiceEnable(forgroundServiceEnable);
+ else Log.i("Hello2", "setForegroundServiceEnable" + stringNOTCONNECT);
+ return false;
+ }
+ public String getServerLocation() {
+ if (DEBUG) Log.i("Hello2", "getServerLocation");
+ if (isCs108Connected()) return cs108Library4A.getServerLocation();
+ else if (isCs710Connected()) return cs710Library4A.getServerLocation();
+ else Log.i("Hello2", "getServerLocation" + stringNOTCONNECT);
+ return null;
+ }
+ public boolean setServerLocation(String serverLocation) {
+ if (DEBUG) Log.i("Hello2", "setServerLocation");
+ if (isCs108Connected()) return cs108Library4A.setServerLocation(serverLocation);
+ else if (isCs710Connected()) return cs710Library4A.setServerLocation(serverLocation);
+ else Log.i("Hello2", "setServerLocation" + stringNOTCONNECT);
+ return false;
+ }
+ public int getServerTimeout() {
+ if (DEBUG) Log.i("Hello2", "getServerTimeout");
+ if (isCs108Connected()) return cs108Library4A.getServerTimeout();
+ else if (isCs710Connected()) return cs710Library4A.getServerTimeout();
+ else Log.i("Hello2", "getServerTimeout" + stringNOTCONNECT);
+ return -1;
+ }
+ public boolean setServerTimeout(int serverTimeout) {
+ if (DEBUG) Log.i("Hello2", "setServerTimeout");
+ if (isCs108Connected()) return cs108Library4A.setServerTimeout(serverTimeout);
+ else if (isCs710Connected()) return cs710Library4A.setServerTimeout(serverTimeout);
+ else Log.i("Hello2", "setServerTimeout" + stringNOTCONNECT);
+ return false;
+ }
+ public String getServerMqttLocation() {
+ if (DEBUG) Log.i("Hello2", "getServerMqttLocation");
+ if (isCs108Connected()) return cs108Library4A.getServerMqttLocation();
+ else if (isCs710Connected()) return cs710Library4A.getServerMqttLocation();
+ else Log.i("Hello2", "getServerMqttLocation" + stringNOTCONNECT);
+ return null;
+ }
+ public boolean setServerMqttLocation(String serverLocation) {
+ if (DEBUG) Log.i("Hello2", "setServerMqttLocation");
+ if (isCs108Connected()) return cs108Library4A.setServerMqttLocation(serverLocation);
+ else if (isCs710Connected()) return cs710Library4A.setServerMqttLocation(serverLocation);
+ else Log.i("Hello2", "setServerMqttLocation" + stringNOTCONNECT);
+ return false;
+ }
+ public String getTopicMqtt() {
+ if (DEBUG) Log.i("Hello2", "getServerTopicMqtt");
+ if (isCs108Connected()) return cs108Library4A.getTopicMqtt();
+ else if (isCs710Connected()) return cs710Library4A.getTopicMqtt();
+ else Log.i("Hello2", "getServerTopicMqtt" + stringNOTCONNECT);
+ return null;
+ }
+ public boolean setTopicMqtt(String topic) {
+ if (DEBUG) Log.i("Hello2", "setServerTopicMqtt");
+ if (isCs108Connected()) return cs108Library4A.setTopicMqtt(topic);
+ else if (isCs710Connected()) return cs710Library4A.setTopicMqtt(topic);
+ else Log.i("Hello2", "setServerTopicMqtt" + stringNOTCONNECT);
+ return false;
+ }
+ public int getForegroundDupElim() {
+ if (DEBUG) Log.i("Hello2", "getForegroundDupElim");
+ if (isCs108Connected()) return cs108Library4A.getForegroundDupElim();
+ else if (isCs710Connected()) return cs710Library4A.getForegroundDupElim();
+ else Log.i("Hello2", "getForegroundDupElim" + stringNOTCONNECT);
+ return -1;
+ }
+ public boolean setForegroundDupElim(int iForegroundDupElim) {
+ if (DEBUG) Log.i("Hello2", "setForegroundDupElim");
+ if (isCs108Connected()) return cs108Library4A.setForegroundDupElim(iForegroundDupElim);
+ else if (isCs710Connected()) return cs710Library4A.setForegroundDupElim(iForegroundDupElim);
+ else Log.i("Hello2", "setForegroundDupElim" + stringNOTCONNECT);
+ return false;
+ }
+ public int getInventoryCloudSave() {
+ if (DEBUG) Log.i("Hello2", "getInventoryCloudSave");
+ if (isCs108Connected()) return cs108Library4A.getInventoryCloudSave();
+ else if (isCs710Connected()) return cs710Library4A.getInventoryCloudSave();
+ else Log.i("Hello2", "getInventoryCloudSave" + stringNOTCONNECT);
+ return -1;
+ }
+ public boolean setInventoryCloudSave(int inventoryCloudSave) {
+ if (DEBUG) Log.i("Hello2", "setInventoryCloudSave");
+ if (isCs108Connected()) return cs108Library4A.setInventoryCloudSave(inventoryCloudSave);
+ else if (isCs710Connected()) return cs710Library4A.setInventoryCloudSave(inventoryCloudSave);
+ else Log.i("Hello2", "setInventoryCloudSave" + stringNOTCONNECT);
+ return false;
+ }
+ public String getServerImpinjLocation() {
+ if (DEBUG) Log.i("Hello2", "getServerImpinjLocation");
+ if (isCs108Connected()) return cs108Library4A.getServerImpinjLocation();
+ else if (isCs710Connected()) return cs710Library4A.getServerImpinjLocation();
+ else Log.i("Hello2", "getServerImpinjLocation" + stringNOTCONNECT);
+ return null;
+ }
+ public boolean setServerImpinjLocation(String serverImpinjLocation) {
+ if (DEBUG) Log.i("Hello2", "setServerImpinjLocation");
+ if (isCs108Connected()) return cs108Library4A.setServerImpinjLocation(serverImpinjLocation);
+ else if (isCs710Connected()) return cs710Library4A.setServerImpinjLocation(serverImpinjLocation);
+ else Log.i("Hello2", "setServerImpinjLocation" + stringNOTCONNECT);
+ return false;
+ }
+ public String getServerImpinjName() {
+ if (DEBUG) Log.i("Hello2", "getServerImpinjName");
+ if (isCs108Connected()) return cs108Library4A.getServerImpinjName();
+ else if (isCs710Connected()) return cs710Library4A.getServerImpinjName();
+ else Log.i("Hello2", "getServerImpinjName" + stringNOTCONNECT);
+ return null;
+ }
+ public boolean setServerImpinjName(String serverImpinjName) {
+ if (DEBUG) Log.i("Hello2", "setServerImpinjName");
+ if (isCs108Connected()) return cs108Library4A.setServerImpinjName(serverImpinjName);
+ else if (isCs710Connected()) return cs710Library4A.setServerImpinjName(serverImpinjName);
+ else Log.i("Hello2", "setServerImpinjName" + stringNOTCONNECT);
+ return false;
+ }
+ public String getServerImpinjPassword() {
+ if (DEBUG) Log.i("Hello2", "getServerImpinjPassword");
+ if (isCs108Connected()) return cs108Library4A.getServerImpinjPassword();
+ else if (isCs710Connected()) return cs710Library4A.getServerImpinjPassword();
+ else Log.i("Hello2", "getServerImpinjPassword" + stringNOTCONNECT);
+ return null;
+ }
+ public boolean setServerImpinjPassword(String serverImpinjPassword) {
+ if (DEBUG) Log.i("Hello2", "setServerImpinjPassword");
+ if (isCs108Connected()) return cs108Library4A.setServerImpinjPassword(serverImpinjPassword);
+ else if (isCs710Connected()) return cs710Library4A.setServerImpinjPassword(serverImpinjPassword);
+ else Log.i("Hello2", "setServerImpinjPassword" + stringNOTCONNECT);
+ return false;
+ }
+
+ public int getBatteryDisplaySetting() {
+ if (DEBUG) Log.i("Hello2", "getBatteryDisplaySetting");
+ if (isCs108Connected()) return cs108Library4A.getBatteryDisplaySetting();
+ else if (isCs710Connected()) return cs710Library4A.getBatteryDisplaySetting();
+ else Log.i("Hello2", "getBatteryDisplaySetting" + stringNOTCONNECT);
+ return -1;
+ }
+ public boolean setBatteryDisplaySetting(int batteryDisplaySelect) {
+ if (DEBUG) Log.i("Hello2", "setBatteryDisplaySetting");
+ if (isCs108Connected()) return cs108Library4A.setBatteryDisplaySetting(batteryDisplaySelect);
+ else if (isCs710Connected()) return cs710Library4A.setBatteryDisplaySetting(batteryDisplaySelect);
+ else Log.i("Hello2", "setBatteryDisplaySetting" + stringNOTCONNECT);
+ return false;
+ }
+ public double dBuV_dBm_constant = RfidReader.dBuV_dBm_constant; //106.98;
+ public int getRssiDisplaySetting() {
+ if (DEBUG) Log.i("Hello2", "getRssiDisplaySetting");
+ if (isCs108Connected()) return cs108Library4A.getRssiDisplaySetting();
+ else if (isCs710Connected()) return cs710Library4A.getRssiDisplaySetting();
+ return 0;
+ }
+ public boolean setRssiDisplaySetting(int rssiDisplaySelect) {
+ if (DEBUG) Log.i("Hello2", "setRssiDisplaySetting");
+ if (isCs108Connected()) return cs108Library4A.setRssiDisplaySetting(rssiDisplaySelect);
+ else if (isCs710Connected()) return cs710Library4A.setRssiDisplaySetting(rssiDisplaySelect);
+ else Log.i("Hello2", "setRssiDisplaySetting" + stringNOTCONNECT);
+ return false;
+ }
+ public int getVibrateModeSetting() {
+ if (DEBUG) Log.i("Hello2", "getVibrateModeSetting");
+ if (isCs108Connected()) return cs108Library4A.getVibrateModeSetting();
+ else if (isCs710Connected()) return cs710Library4A.getVibrateModeSetting();
+ else Log.i("Hello2", "getVibrateModeSetting" + stringNOTCONNECT);
+ return -1;
+ }
+ public boolean setVibrateModeSetting(int vibrateModeSelect) {
+ if (DEBUG) Log.i("Hello2", "setVibrateModeSetting");
+ if (isCs108Connected()) return cs108Library4A.setVibrateModeSetting(vibrateModeSelect);
+ else if (isCs710Connected()) return cs710Library4A.setVibrateModeSetting(vibrateModeSelect);
+ else Log.i("Hello2", "setVibrateModeSetting" + stringNOTCONNECT);
+ return false;
+ }
+ public int getSavingFormatSetting() {
+ if (DEBUG) Log.i("Hello2", "getSavingFormatSetting");
+ if (isCs108Connected()) return cs108Library4A.getSavingFormatSetting();
+ else if (isCs710Connected()) return cs710Library4A.getSavingFormatSetting();
+ else Log.i("Hello2", "getSavingFormatSetting" + stringNOTCONNECT);
+ return -1;
+ }
+ public boolean setSavingFormatSetting(int savingFormatSelect) {
+ if (DEBUG) Log.i("Hello2", "setSavingFormatSetting");
+ if (isCs108Connected()) return cs108Library4A.setSavingFormatSetting(savingFormatSelect);
+ else if (isCs710Connected()) return cs710Library4A.setSavingFormatSetting(savingFormatSelect);
+ else Log.i("Hello2", "setSavingFormatSetting" + stringNOTCONNECT);
+ return false;
+ }
+ public int getCsvColumnSelectSetting() {
+ if (DEBUG) Log.i("Hello2", "getCsvColumnSelectSetting");
+ if (isCs108Connected()) return cs108Library4A.getCsvColumnSelectSetting();
+ else if (isCs710Connected()) return cs710Library4A.getCsvColumnSelectSetting();
+ else Log.i("Hello2", "getCsvColumnSelectSetting" + stringNOTCONNECT);
+ return -1;
+ }
+ public boolean setCsvColumnSelectSetting(int csvColumnSelect) {
+ if (DEBUG) Log.i("Hello2", "setCsvColumnSelectSetting");
+ if (isCs108Connected()) return cs108Library4A.setCsvColumnSelectSetting(csvColumnSelect);
+ else if (isCs710Connected()) return cs710Library4A.setCsvColumnSelectSetting(csvColumnSelect);
+ else Log.i("Hello2", "setCsvColumnSelectSetting" + stringNOTCONNECT);
+ return false;
+ }
+ public String getWedgeDeviceName() {
+ if (isCs108Connected()) return cs108Library4A.getWedgeDeviceName();
+ else return cs710Library4A.getWedgeDeviceName();
+ }
+ public String getWedgeDeviceAddress() {
+ if (isCs108Connected()) return cs108Library4A.getWedgeDeviceAddress();
+ else return cs710Library4A.getWedgeDeviceAddress();
+ }
+ public int getWedgeDeviceUUID2p1() {
+ if (isCs108Connected()) return cs108Library4A.getWedgeDeviceUUID2p1();
+ else return cs710Library4A.getWedgeDeviceUUID2p1();
+ }
+ public int getWedgePower() {
+ if (isCs108Connected()) return cs108Library4A.getWedgePower();
+ else return cs710Library4A.getWedgePower();
+ }
+ public String getWedgePrefix() {
+ if (isCs108Connected()) return cs108Library4A.getWedgePrefix();
+ else return cs710Library4A.getWedgePrefix();
+ }
+ public String getWedgeSuffix() {
+ if (isCs108Connected()) return cs108Library4A.getWedgeSuffix();
+ else return cs710Library4A.getWedgeSuffix();
+ }
+ public int getWedgeDelimiter() {
+ if (isCs108Connected()) return cs108Library4A.getWedgeDelimiter();
+ else return cs710Library4A.getWedgeDelimiter();
+ }
+ public int getWedgeOutput() {
+ if (isCs108Connected()) return cs108Library4A.getWedgeOutput();
+ else return cs710Library4A.getWedgeOutput();
+ }
+ public void setWedgeDeviceName(String wedgeDeviceName) {
+ if (isCs108Connected()) cs108Library4A.setWedgeDeviceName(wedgeDeviceName);
+ else cs710Library4A.setWedgeDeviceName(wedgeDeviceName);
+ }
+ public void setWedgeDeviceAddress(String wedgeDeviceAddress) {
+ if (isCs108Connected()) cs108Library4A.setWedgeDeviceAddress(wedgeDeviceAddress);
+ else cs710Library4A.setWedgeDeviceAddress(wedgeDeviceAddress);
+ }
+ public void setWedgeDeviceUUID2p1(int wedgeDeviceUUID2p1) {
+ if (isCs108Connected()) cs108Library4A.setWedgeDeviceUUID2p1(wedgeDeviceUUID2p1);
+ else cs710Library4A.setWedgeDeviceUUID2p1(wedgeDeviceUUID2p1);
+ }
+ public void setWedgePower(int iPower) {
+ if (isCs108Connected()) cs108Library4A.setWedgePower(iPower);
+ else cs710Library4A.setWedgePower(iPower);
+ }
+ public void setWedgePrefix(String string) {
+ if (isCs108Connected()) cs108Library4A.setWedgePrefix(string);
+ else cs710Library4A.setWedgePrefix(string);
+ }
+ public void setWedgeSuffix(String string) {
+ if (isCs108Connected()) cs108Library4A.setWedgeSuffix(string);
+ else cs710Library4A.setWedgeSuffix(string);
+ }
+ public void setWedgeDelimiter(int iValue) {
+ if (isCs108Connected()) cs108Library4A.setWedgeDelimiter(iValue);
+ else cs710Library4A.setWedgeDelimiter(iValue);
+ }
+ public void setWedgeOutput(int iOutput) {
+ if (isCs108Connected()) cs108Library4A.setWedgeOutput(iOutput);
+ else cs710Library4A.setWedgeOutput(iOutput);
+ }
+ public void saveWedgeSetting2File() {
+ if (isCs108Connected()) cs108Library4A.saveWedgeSetting2File();
+ else cs710Library4A.saveWedgeSetting2File();
+ }
+
+ //============ Bluetooth ============
+ public String getBluetoothICFirmwareVersion() {
+ if (DEBUG) Log.i("Hello2", "getBluetoothICFirmwareVersion");
+ if (isCs108Connected()) return cs108Library4A.getBluetoothICFirmwareVersion();
+ else if (isCs710Connected()) return cs710Library4A.getBluetoothICFirmwareVersion();
+ else Log.i("Hello2", "getBluetoothICFirmwareVersion" + stringNOTCONNECT);
+ return null;
+ }
+ public String getBluetoothICFirmwareName() {
+ if (DEBUG) Log.i("Hello2", "getBluetoothICFirmwareName");
+ if (isCs108Connected()) return cs108Library4A.getBluetoothICFirmwareName();
+ else if (isCs710Connected()) return cs710Library4A.getBluetoothICFirmwareName();
+ else Log.i("Hello2", "getBluetoothICFirmwareName" + stringNOTCONNECT);
+ return null;
+ }
+ public boolean setBluetoothICFirmwareName(String name) {
+ if (DEBUG) Log.i("Hello2", "setBluetoothICFirmwareName");
+ if (isCs108Connected()) return cs108Library4A.setBluetoothICFirmwareName(name);
+ else if (isCs710Connected()) return cs710Library4A.setBluetoothICFirmwareName(name);
+ else Log.i("Hello2", "setBluetoothICFirmwareName" + stringNOTCONNECT);
+ return false;
+ }
+
+ //============ Controller ============
+ public String hostProcessorICGetFirmwareVersion() {
+ if (DEBUG) Log.i("Hello2", "hostProcessorICGetFirmwareVersion");
+ if (isCs108Connected()) return cs108Library4A.hostProcessorICGetFirmwareVersion();
+ else if (isCs710Connected()) return cs710Library4A.hostProcessorICGetFirmwareVersion();
+ else Log.i("Hello2", "hostProcessorICGetFirmwareVersion" + stringNOTCONNECT);
+ return null;
+ }
+ public String getHostProcessorICSerialNumber() {
+ if (DEBUG) Log.i("Hello2", "getHostProcessorICSerialNumber");
+ if (isCs108Connected()) return cs108Library4A.getHostProcessorICSerialNumber();
+ else if (isCs710Connected()) return cs710Library4A.getHostProcessorICSerialNumber();
+ else Log.i("Hello2", "getHostProcessorICSerialNumber" + stringNOTCONNECT);
+ return null;
+ }
+ public String getHostProcessorICBoardVersion() {
+ if (DEBUG) Log.i("Hello2", "getHostProcessorICBoardVersion");
+ if (isCs108Connected()) return cs108Library4A.getHostProcessorICBoardVersion();
+ else if (isCs710Connected()) return cs710Library4A.getHostProcessorICBoardVersion();
+ else Log.i("Hello2", "getHostProcessorICBoardVersion" + stringNOTCONNECT);
+ return null;
+ }
+
+ //============ Controller notification ============
+ public int getBatteryLevel() {
+ if (DEBUG) Log.i("Hello2", "getBatteryLevel");
+ if (isCs108Connected()) return cs108Library4A.getBatteryLevel();
+ else if (isCs710Connected()) return cs710Library4A.getBatteryLevel();
+ else Log.i("Hello2", "getBatteryLevel" + stringNOTCONNECT);
+ return -1;
+ }
+ public boolean setAutoTriggerReporting(byte timeSecond) {
+ if (DEBUG) Log.i("Hello2", "setAutoTriggerReporting");
+ if (isCs108Connected()) return cs108Library4A.setAutoTriggerReporting(timeSecond);
+ else if (isCs710Connected()) return cs710Library4A.setAutoTriggerReporting(timeSecond);
+ else Log.i("Hello2", "setAutoTriggerReporting" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean getAutoBarStartSTop() {
+ if (DEBUG) Log.i("Hello2", "getAutoBarStartSTop");
+ if (isCs108Connected()) return cs108Library4A.getAutoBarStartSTop();
+ else if (isCs710Connected()) return cs710Library4A.getAutoBarStartSTop();
+ else Log.i("Hello2", "getAutoBarStartSTop" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean batteryLevelRequest() {
+ if (DEBUG) Log.i("Hello2", "batteryLevelRequest");
+ if (isCs108Connected()) return cs108Library4A.batteryLevelRequest();
+ else if (isCs710Connected()) return cs710Library4A.batteryLevelRequest();
+ else Log.i("Hello2", "batteryLevelRequest" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean setAutoBarStartSTop(boolean enable) {
+ if (DEBUG) Log.i("Hello2", "setAutoBarStartSTop");
+ if (isCs108Connected()) return cs108Library4A.setAutoBarStartSTop(enable);
+ else if (isCs710Connected()) return cs710Library4A.setAutoBarStartSTop(enable);
+ else Log.i("Hello2", "setAutoBarStartSTop" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean getTriggerReporting() {
+ if (DEBUG) Log.i("Hello2", "getTriggerReporting");
+ if (isCs108Connected()) cs108Library4A.getTriggerReporting();
+ else if (isCs710Connected()) cs710Library4A.getTriggerReporting();
+ else Log.i("Hello2", "getTriggerReporting" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean setTriggerReporting(boolean triggerReporting) {
+ if (DEBUG) Log.i("Hello2", "setTriggerReporting");
+ if (isCs108Connected()) return cs108Library4A.setTriggerReporting(triggerReporting);
+ else if (isCs710Connected()) return cs710Library4A.setTriggerReporting(triggerReporting);
+ else Log.i("Hello2", "setTriggerReporting" + stringNOTCONNECT);
+ return false;
+ }
+ public int iNO_SUCH_SETTING = -1;
+ public short getTriggerReportingCount() {
+ if (DEBUG) Log.i("Hello2", "getTriggerReportingCount");
+ if (isCs108Connected()) return cs108Library4A.getTriggerReportingCount();
+ else if (isCs710Connected()) return cs710Library4A.getTriggerReportingCount();
+ else Log.i("Hello2", "getTriggerReportingCount" + stringNOTCONNECT);
+ return 5;
+ }
+ public boolean setTriggerReportingCount(short triggerReportingCount) {
+ if (DEBUG) Log.i("Hello2", "setTriggerReportingCount");
+ if (isCs108Connected()) return cs108Library4A.setTriggerReportingCount(triggerReportingCount);
+ else if (isCs710Connected()) return cs710Library4A.setTriggerReportingCount(triggerReportingCount);
+ else Log.i("Hello2", "setTriggerReportingCount" + stringNOTCONNECT);
+ return false;
+ }
+ public String getBatteryDisplay(boolean voltageDisplay) {
+ if (DEBUG) Log.i("Hello2", "getBatteryDisplay");
+ if (isCs108Connected()) return cs108Library4A.getBatteryDisplay(voltageDisplay);
+ else if (isCs710Connected()) return cs710Library4A.getBatteryDisplay(voltageDisplay);
+ else Log.i("Hello2", "getBatteryDisplay is called befoe connection !!!");
+ return null;
+ }
+ String stringNOTCONNECT;
+ public String isBatteryLow() {
+ if (DEBUG) Log.i("Hello2", "isBatteryLow");
+ if (isCs108Connected()) return cs108Library4A.isBatteryLow();
+ else if (isCs710Connected()) return cs710Library4A.isBatteryLow();
+ else Log.i("Hello2", "isBatteryLow" + stringNOTCONNECT);
+ return null;
+ }
+ public int getBatteryCount() {
+ if (DEBUG2) Log.i("Hello2", "getBatteryCount");
+ if (isCs108Connected()) return cs108Library4A.getBatteryCount();
+ else if (isCs710Connected()) return cs710Library4A.getBatteryCount();
+ else Log.i("Hello2", "getBatteryCount" + stringNOTCONNECT);
+ return -1;
+ }
+ public boolean getTriggerButtonStatus() {
+ if (DEBUG2) Log.i("Hello2", "getTriggerButtonStatus");
+ if (isCs108Connected()) return cs108Library4A.getTriggerButtonStatus();
+ else if (isCs710Connected()) return cs710Library4A.getTriggerButtonStatus();
+ else Log.i("Hello2", "getTriggerButtonStatus" + stringNOTCONNECT);
+ return false;
+ }
+ public int getTriggerCount() {
+ if (DEBUG2) Log.i("Hello2", "getTriggerCount");
+ if (isCs108Connected()) return cs108Library4A.getTriggerCount();
+ else if (isCs710Connected()) return cs710Library4A.getTriggerCount();
+ else Log.i("Hello2", "getTriggerCount" + stringNOTCONNECT);
+ return -1;
+ }
+ //public interface NotificationListener { void onChange(); }
+ public void setNotificationListener(NotificationConnector.NotificationListener listener) {
+ if (DEBUG) Log.i("Hello2", "setNotificationListener");
+ if (isCs108Connected()) {
+ cs108Library4A.setNotificationListener(new NotificationConnector.NotificationListener() {
+ @Override
+ public void onChange() {
+ listener.onChange();
+ }
+ });
+ } else if (isCs710Connected()) {
+ cs710Library4A.setNotificationListener(new NotificationConnector.NotificationListener() {
+ @Override
+ public void onChange() {
+ listener.onChange();
+ }
+ });
+ }
+ else Log.i("Hello2", "setNotificationListener" + stringNOTCONNECT);
+ }
+ public byte[] onNotificationEvent() {
+ if (DEBUG2) Log.i("Hello2", "onNotificationEvent");
+ if (isCs108Connected()) return cs108Library4A.onNotificationEvent();
+ else if (isCs710Connected()) return cs710Library4A.onNotificationEvent();
+ else Log.i("Hello2", "onNotificationEvent" + stringNOTCONNECT);
+ return null;
+ }
+
+ //============ to be modified ============
+ public String getSerialNumber() {
+ if (DEBUG2) Log.i("Hello2", "getSerialNumber");
+ if (isCs108Connected()) return cs108Library4A.getSerialNumber();
+ else if (isCs710Connected()) return cs710Library4A.getSerialNumber();
+ else Log.i("Hello2", "getSerialNumber" + stringNOTCONNECT);
+ return null;
+ }
+ public boolean setRfidOn(boolean onStatus) {
+ if (DEBUG2) Log.i("Hello2", "setRfidOn");
+ if (isCs108Connected()) return cs108Library4A.setRfidOn(onStatus);
+ else if (isCs710Connected()) return cs710Library4A.setRfidOn(onStatus);
+ else Log.i("Hello2", "setRfidOn" + stringNOTCONNECT);
+ return false;
+ }
+ public int getcsModel() {
+ if (DEBUG2) Log.i("Hello2", "getcsModel");
+ if (isCs108Connected()) return cs108Library4A.getcsModel();
+ else if (isCs710Connected()) return cs710Library4A.getcsModel();
+ else Log.i("Hello2", "getcsModel" + stringNOTCONNECT);
+ return -1;
+ }
+ public int getAntennaCycle() {
+ if (DEBUG2) Log.i("Hello2", "getAntennaCycle");
+ if (isCs108Connected()) return cs108Library4A.getAntennaCycle();
+ else if (isCs710Connected()) return cs710Library4A.getAntennaCycle();
+ else Log.i("Hello2", "getAntennaCycle" + stringNOTCONNECT);
+ return -1;
+ }
+ public boolean setAntennaCycle(int antennaCycle) {
+ if (DEBUG2) Log.i("Hello2", "setAntennaCycle");
+ if (isCs108Connected()) return cs108Library4A.setAntennaCycle(antennaCycle);
+ else if (isCs710Connected()) return cs710Library4A.setAntennaCycle(antennaCycle);
+ else Log.i("Hello2", "setAntennaCycle" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean setAntennaInvCount(long antennaInvCount) {
+ if (DEBUG2) Log.i("Hello2", "setAntennaInvCount");
+ if (isCs108Connected()) return cs108Library4A.setAntennaInvCount(antennaInvCount);
+ else if (isCs710Connected()) return cs710Library4A.setAntennaInvCount(antennaInvCount);
+ else Log.i("Hello2", "setAntennaInvCount" + stringNOTCONNECT);
+ return false;
+ }
+ public void clearInvalidata() {
+ if (DEBUG2) Log.i("Hello2", "clearInvalidata");
+ if (isCs108Connected()) cs108Library4A.clearInvalidata();
+ else if (isCs710Connected()) cs710Library4A.clearInvalidata();
+ else Log.i("Hello2", "clearInvalidata" + stringNOTCONNECT);
+ }
+ public int getInvalidata() {
+ if (DEBUG2) Log.i("Hello2", "getInvalidata");
+ if (isCs108Connected()) return cs108Library4A.getInvalidata();
+ else if (isCs710Connected()) return cs710Library4A.getInvalidata();
+ else Log.i("Hello2", "getInvalidata" + stringNOTCONNECT);
+ return -1;
+ }
+ public int getInvalidUpdata() {
+ if (DEBUG2) Log.i("Hello2", "getInvalidUpdata");
+ if (isCs108Connected()) return cs108Library4A.getInvalidUpdata();
+ else if (isCs710Connected()) return cs710Library4A.getInvalidUpdata();
+ else Log.i("Hello2", "getInvalidUpdata" + stringNOTCONNECT);
+ return -1;
+ }
+ public int getValidata() {
+ if (DEBUG2) Log.i("Hello2", "getValidata");
+ if (isCs108Connected()) return cs108Library4A.getValidata();
+ else if (isCs710Connected()) return cs710Library4A.getValidata();
+ else Log.i("Hello2", "getValidata" + stringNOTCONNECT);
+ return -1;
+ }
+
+ //============ not public ============
+ int bConnectStatus = 0;
+ int iServiceUuidConnectedBefore = -1;
+ private boolean isCs108Connected() { return (bConnectStatus == 1); }
+ private boolean isCs710Connected() { return (bConnectStatus == 7); }
+
+ public int setSelectData(RfidReader.TagType tagType, String mDid, boolean bNeedSelectedTagByTID, String stringProtectPassword, int selectFor, int selectHold) {
+ if (DEBUG2) Log.i("Hello2", "setSelectData");
+ if (isCs108Connected()) return cs108Library4A.setSelectData(tagType, mDid, bNeedSelectedTagByTID, stringProtectPassword, selectFor, selectHold);
+ else if (isCs710Connected()) return cs710Library4A.setSelectData(tagType, mDid, bNeedSelectedTagByTID, stringProtectPassword, selectFor, selectHold);
+ else Log.i("Hello2", "setSelectData" + stringNOTCONNECT);
+ return -1;
+ }
+ public int setOtherInventoryData(RfidReader.TagType tagType, String mDid) {
+ if (DEBUG2) Log.i("Hello2", "setOtherInventoryData");
+ //appendToLog("BtDataOut: tagType = " + (tagType == null ? "null" : tagType.toString()) + ", mDid = " + mDid);
+ if (isCs108Connected()) return cs108Library4A.setOtherInventoryData(tagType, mDid);
+ else if (isCs710Connected()) return cs710Library4A.setOtherInventoryData(tagType, mDid);
+ else Log.i("Hello2", "setOtherInventoryData" + stringNOTCONNECT);
+ return -1;
+ }
+}
+
+
+
+package com.csl.cslibrary4a;
+
+import android.Manifest;
+import android.bluetooth.BluetoothAdapter;
+import android.bluetooth.BluetoothDevice;
+import android.bluetooth.le.ScanCallback;
+import android.content.Context;
+import android.content.pm.PackageManager;
+import android.os.Build;
+import android.os.Handler;
+import android.widget.TextView;
+
+import java.nio.charset.StandardCharsets;
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Date;
+import java.util.List;
+
+import android.bluetooth.le.ScanResult;
+
+import androidx.core.app.ActivityCompat;
+
+public class CsReaderConnector {
+ final boolean appendToLogViewDisable = false;
+ final boolean DEBUG = false; final boolean DEBUGTHREAD = false;
+ boolean DEBUG_CONNECT, DEBUG_SCAN;
+ boolean DEBUG_APDATA;
+ public boolean sameCheck = true;
+
+ String byteArrayToString(byte[] packet) { return utility.byteArrayToString(packet); }
+ void appendToLog(String s) { utility.appendToLog(s); }
+ public boolean connect(ReaderDevice readerDevice) {
+ boolean result = false, DEBUG = true;
+ if (DEBUG) appendToLog("csReaderConnector.connect: readerDevice is " + (readerDevice == null ? "null" : "valid"));
+ int iNumberColon = readerDevice.getAddress().split(":").length;
+ int iNumberDot = readerDevice.getAddress().split("\\.").length;
+ if (DEBUG) appendToLog("csReaderConnector.connect with split[:].length = " + iNumberColon + ", split[.].length = " + iNumberDot);
+ if (DEBUG || DEBUG_CONNECT) appendToLog("csReaderConnector.connect(" + readerDevice.getAddress() + ")");
+ if (iNumberColon == 6 && iNumberDot == 4) { result = deviceFinder.connect(readerDevice); } //for http
+ else if (iNumberColon == 1 && iNumberDot == 1) { result = usbConnector.connect(readerDevice); } //for usb
+ else if (iNumberColon == 6 && iNumberDot == 1) result = bluetoothGatt.connect(readerDevice); //for bluetooth
+ if (result) writeDataCount = 0;
+ return result;
+ }
+
+ public boolean isConnected() {
+ if (bluetoothGatt.isConnected()) return true;
+ if (usbConnector != null && usbConnector.isConnected()) return true;
+ return false;
+ }
+
+ public void disconnect() {
+ bluetoothGatt.disconnect();
+ appendToLog("abcc done");
+ if (rfidConnector != null) {
+ rfidConnector.mRfidToWrite.clear(); appendToLog("BtDataOut: mRfidToWrite.clear 1");
+ }
+ if (rfidReader != null) rfidReader.mRx000ToWrite.clear();
+ }
+
+ public long getStreamInRate() { return bluetoothGatt.getStreamInRate(); }
+
+ int writeDataCount; int btSendTimeOut = 0; long btSendTime = 0; int BTSENDDELAY = 20;
+ boolean writeData(byte[] buffer, int timeout) {
+ if (rfidReader.isInventoring()) {
+ utility.appendToLogView("BtData: isInventoring is true when writeData " + byteArrayToString(buffer));
+ }
+ boolean result = false;
+ if (usbConnector != null && usbConnector.isConnected()) {
+ appendToLog("CsReaderConnector.writeData, UsbData: going to writeStreamOut with " + byteArrayToString(buffer));
+ result = usbConnector.writeStreamOut(buffer);
+ }
+ else result = bluetoothGatt.writeBleStreamOut(buffer);
+ if (!result) appendToLog("!!! failure to writeData with previous btSendTimeout = " + btSendTimeOut + ", btSendTime = " + btSendTime);
+ if (true) {
+ btSendTime = System.currentTimeMillis();
+ btSendTimeOut = timeout + BTSENDDELAY;
+ utility.appendToLog("csReaderConnector.writeData: UsbConnector: btSendTimeOut 0 = " + btSendTimeOut);
+ if ((usbConnector != null && !usbConnector.isConnected()) && !bluetoothGatt.isCharacteristicListRead()) btSendTimeOut += 3000;
+ utility.appendToLog("csReaderConnector.writeData: UsbConnector: btSendTimeOut 1 = " + btSendTimeOut);
+ }
+ utility.appendToLog("csReaderConnector.writeData: UsbConnector: result = " + result);
+ return result;
+ }
+
+ int[] crc_lookup_table = new int[]{
+ 0x0000, 0x1189, 0x2312, 0x329b, 0x4624, 0x57ad, 0x6536, 0x74bf,
+ 0x8c48, 0x9dc1, 0xaf5a, 0xbed3, 0xca6c, 0xdbe5, 0xe97e, 0xf8f7,
+ 0x1081, 0x0108, 0x3393, 0x221a, 0x56a5, 0x472c, 0x75b7, 0x643e,
+ 0x9cc9, 0x8d40, 0xbfdb, 0xae52, 0xdaed, 0xcb64, 0xf9ff, 0xe876,
+ 0x2102, 0x308b, 0x0210, 0x1399, 0x6726, 0x76af, 0x4434, 0x55bd,
+ 0xad4a, 0xbcc3, 0x8e58, 0x9fd1, 0xeb6e, 0xfae7, 0xc87c, 0xd9f5,
+ 0x3183, 0x200a, 0x1291, 0x0318, 0x77a7, 0x662e, 0x54b5, 0x453c,
+ 0xbdcb, 0xac42, 0x9ed9, 0x8f50, 0xfbef, 0xea66, 0xd8fd, 0xc974,
+ 0x4204, 0x538d, 0x6116, 0x709f, 0x0420, 0x15a9, 0x2732, 0x36bb,
+ 0xce4c, 0xdfc5, 0xed5e, 0xfcd7, 0x8868, 0x99e1, 0xab7a, 0xbaf3,
+ 0x5285, 0x430c, 0x7197, 0x601e, 0x14a1, 0x0528, 0x37b3, 0x263a,
+ 0xdecd, 0xcf44, 0xfddf, 0xec56, 0x98e9, 0x8960, 0xbbfb, 0xaa72,
+ 0x6306, 0x728f, 0x4014, 0x519d, 0x2522, 0x34ab, 0x0630, 0x17b9,
+ 0xef4e, 0xfec7, 0xcc5c, 0xddd5, 0xa96a, 0xb8e3, 0x8a78, 0x9bf1,
+ 0x7387, 0x620e, 0x5095, 0x411c, 0x35a3, 0x242a, 0x16b1, 0x0738,
+ 0xffcf, 0xee46, 0xdcdd, 0xcd54, 0xb9eb, 0xa862, 0x9af9, 0x8b70,
+ 0x8408, 0x9581, 0xa71a, 0xb693, 0xc22c, 0xd3a5, 0xe13e, 0xf0b7,
+ 0x0840, 0x19c9, 0x2b52, 0x3adb, 0x4e64, 0x5fed, 0x6d76, 0x7cff,
+ 0x9489, 0x8500, 0xb79b, 0xa612, 0xd2ad, 0xc324, 0xf1bf, 0xe036,
+ 0x18c1, 0x0948, 0x3bd3, 0x2a5a, 0x5ee5, 0x4f6c, 0x7df7, 0x6c7e,
+ 0xa50a, 0xb483, 0x8618, 0x9791, 0xe32e, 0xf2a7, 0xc03c, 0xd1b5,
+ 0x2942, 0x38cb, 0x0a50, 0x1bd9, 0x6f66, 0x7eef, 0x4c74, 0x5dfd,
+ 0xb58b, 0xa402, 0x9699, 0x8710, 0xf3af, 0xe226, 0xd0bd, 0xc134,
+ 0x39c3, 0x284a, 0x1ad1, 0x0b58, 0x7fe7, 0x6e6e, 0x5cf5, 0x4d7c,
+ 0xc60c, 0xd785, 0xe51e, 0xf497, 0x8028, 0x91a1, 0xa33a, 0xb2b3,
+ 0x4a44, 0x5bcd, 0x6956, 0x78df, 0x0c60, 0x1de9, 0x2f72, 0x3efb,
+ 0xd68d, 0xc704, 0xf59f, 0xe416, 0x90a9, 0x8120, 0xb3bb, 0xa232,
+ 0x5ac5, 0x4b4c, 0x79d7, 0x685e, 0x1ce1, 0x0d68, 0x3ff3, 0x2e7a,
+ 0xe70e, 0xf687, 0xc41c, 0xd595, 0xa12a, 0xb0a3, 0x8238, 0x93b1,
+ 0x6b46, 0x7acf, 0x4854, 0x59dd, 0x2d62, 0x3ceb, 0x0e70, 0x1ff9,
+ 0xf78f, 0xe606, 0xd49d, 0xc514, 0xb1ab, 0xa022, 0x92b9, 0x8330,
+ 0x7bc7, 0x6a4e, 0x58d5, 0x495c, 0x3de3, 0x2c6a, 0x1ef1, 0x0f78};
+
+ boolean dataRead = false; int dataReadDisplayCount = 0; boolean mCs108DataReadRequest = false;
+ int inventoryLength = 0;
+ int iSequenceNumber; boolean bDifferentSequence = false, bFirstSequence = true;
+ public int invalidata, invalidUpdata, validata;
+ public void clearInvalidata() {
+ invalidata = 0;
+ invalidUpdata = 0;
+ validata = 0;
+ }
+ //boolean dataInBufferResetting;
+
+ void processStreamInData() {
+ final boolean DEBUG = false;
+ int cs108DataReadStartOld = 0;
+ int cs108DataReadStart = 0;
+ boolean validHeader = false;
+
+ if (DEBUG) appendToLog("CsReaderConnector.processStreamInData: starts with cs108DataLeft " + (cs108DataLeft == null ? "null" : "valid"));
+ if (cs108DataLeft == null) return;
+ /*if (false && dataInBufferResetting) {
+ if (utility.DEBUG_FMDATA) appendToLog("FmData: RESET.");
+ dataInBufferResetting = false;
+ cs108DataLeftOffset = 0;
+ connectorDataList.clear();
+ }*/
+ if (DEBUG) appendToLog("CsReaderConnector.processStreamInData: " + (usbConnector == null ? "null" : (usbConnector.isConnected() ? "connected" : "not connected")) + " usbConnector");
+ int iStreamInBufferSize = ((usbConnector == null || !usbConnector.isConnected()) ? bluetoothGatt.getStreamInBufferSize() : usbConnector.getStreamInBufferSize());
+ if (DEBUG) appendToLog("CsReaderConnector.processStreamInData: iStreamInBufferSize = " + iStreamInBufferSize);
+ //boolean bFirst = true;
+ long lTime = System.currentTimeMillis();
+ boolean bLooping = false;
+ while (((usbConnector == null || !usbConnector.isConnected()) ? bluetoothGatt.getStreamInBufferSize() : usbConnector.getStreamInBufferSize()) != 0) {
+ if (DEBUG) appendToLog("CsReaderConnector.processStreamInData: while loop starts");
+ if (utility.DEBUG_FMDATA && bLooping == false) appendToLog("FmData: Enter loop with cs108DataLeftOffset=" + cs108DataLeftOffset + ", streamInBufferSize=" + iStreamInBufferSize);
+ bLooping = true;
+
+ if ((usbConnector == null || !usbConnector.isConnected()) && (System.currentTimeMillis() - lTime > (bluetoothGatt.getIntervalProcessBleStreamInData()/2))) {
+ appendToLog("CsReaderConnector.processStreamInData: timeout");
+ utility.writeDebug2File("Up2 " + bluetoothGatt.getIntervalProcessBleStreamInData()/2 + "ms Timeout");
+ utility.appendToLogView("FmData: Timeout !!!");
+ break;
+ }
+
+ if (usbConnector != null && !usbConnector.isConnected()) {
+ appendToLog("CsReaderConnector.processStreamInData: going to bluetoothGatt.getStreamInOverflowTime");
+ long streamInOverflowTime = bluetoothGatt.getStreamInOverflowTime();
+ int streamInMissing = bluetoothGatt.getStreamInBytesMissing();
+ if (streamInMissing != 0)
+ utility.appendToLogView("FmData: processCs108DataIn(" + bluetoothGatt.getStreamInTotalCounter() + ", " + bluetoothGatt.getStreamInAddCounter() + "): len=0, getStreamInOverflowTime()=" + streamInOverflowTime + ", MissBytes=" + streamInMissing + ", Offset=" + cs108DataLeftOffset);
+ }
+ if (DEBUG) appendToLog("CsReaderConnector.processStreamInData: going to readData");
+ int len = readData(cs108DataLeft, cs108DataLeftOffset, cs108DataLeft.length);
+ if (DEBUG) appendToLog("CsReaderConnector.processStreamInData: readData len = " + len);
+ if (utility.DEBUG_FMDATA && len != 0) {
+ byte[] debugData = new byte[len];
+ System.arraycopy(cs108DataLeft, cs108DataLeftOffset, debugData, 0, len);
+ appendToLog("FmData: " + len + " dataIn = " + byteArrayToString(debugData));
+ }
+ //if (len != 0 && bFirst) { bFirst = false; } //writeDebug2File("B" + String.valueOf(getIntervalProcessBleStreamInData()) + ", " + System.currentTimeMillis()); }
+ cs108DataLeftOffset += len;
+ if (len == 0) {
+ appendToLog("FmData: len is zero !!!");
+ if (zeroLenDisplayed == false) {
+ zeroLenDisplayed = true;
+ if (!usbConnector.isConnected()) {
+ if (bluetoothGatt.getStreamInTotalCounter() != bluetoothGatt.getStreamInAddCounter() || bluetoothGatt.getStreamInAddTime() != 0 || cs108DataLeftOffset != 0) {
+ if (DEBUG)
+ appendToLog("FmData: processCs108DataIn(" + bluetoothGatt.getStreamInTotalCounter() + "," + bluetoothGatt.getStreamInAddCounter() + "): len=0, getStreamInAddTime()=" + bluetoothGatt.getStreamInAddTime() + ", Offset=" + cs108DataLeftOffset);
+ }
+ }
+ }
+ if (cs108DataLeftOffset == cs108DataLeft.length) {
+ if (DEBUG) appendToLog("FmData: cs108DataLeftOffset=" + cs108DataLeftOffset + ", cs108DataLeft=" + byteArrayToString(cs108DataLeft));
+ }
+ break;
+ } else {
+ dataRead = true;
+ zeroLenDisplayed = false;
+
+ if (utility.DEBUG_FMDATA) appendToLog("FmData: cs108DataLeftOffset = " + cs108DataLeftOffset + ", cs108DataReadStart = " + cs108DataReadStart);
+ while (cs108DataLeftOffset >= cs108DataReadStart + 8) {
+ if (DEBUG) appendToLog("FmData: while looping");
+ validHeader = false;
+ byte[] dataIn = cs108DataLeft;
+ int iPayloadLength = (dataIn[cs108DataReadStart + 2] & 0xFF);
+ if ((dataIn[cs108DataReadStart + 0] == (byte) 0xA7)
+ && (dataIn[cs108DataReadStart + 1] == ((usbConnector != null && usbConnector.isConnected()) ? (byte) 0xE6 : (byte) 0xB3))
+ && (dataIn[cs108DataReadStart + 3] == (byte) 0xC2
+ || dataIn[cs108DataReadStart + 3] == (byte) 0x6A
+ || dataIn[cs108DataReadStart + 3] == (byte) 0xD9
+ || dataIn[cs108DataReadStart + 3] == (byte) 0xE8
+ || dataIn[cs108DataReadStart + 3] == (byte) 0x5F)
+ //&& ((dataIn[cs108DataReadStart + 4] == (byte) 0x82) || ((dataIn[cs108DataReadStart + 3] == (byte) 0xC2) && (dataIn[cs108DataReadStart + 8] == (byte) 0x81)))
+ && (dataIn[cs108DataReadStart + 5] == (byte) 0x9E)) {
+ if (DEBUG) appendToLog("FmData: matched header with cs108DataLeftOffset = " + cs108DataLeftOffset + ", cs108DataReadStart = " + cs108DataReadStart + ", iPayloadLength = " + iPayloadLength);
+ if (cs108DataLeftOffset - cs108DataReadStart < (iPayloadLength + 8))
+ break;
+
+ boolean bcheckChecksum = true;
+ int checksum = ((byte) dataIn[cs108DataReadStart + 6] & 0xFF) * 256 + ((byte) dataIn[cs108DataReadStart + 7] & 0xFF);
+ int checksum2 = 0;
+ if (bcheckChecksum) {
+ for (int i = cs108DataReadStart; i < cs108DataReadStart + 8 + iPayloadLength; i++) {
+ if (i != (cs108DataReadStart + 6) && i != (cs108DataReadStart + 7)) {
+ int index = (checksum2 ^ ((byte) dataIn[i] & 0x0FF)) & 0x0FF;
+ int table_value = crc_lookup_table[index];
+ checksum2 = (checksum2 >> 8) ^ table_value;
+ }
+ }
+ if (DEBUG) appendToLog("FmData: checksum = " + String.format("%04X", checksum) + ", checksum2 = " + String.format("%04X", checksum2));
+ }
+ if (DEBUG) appendToLog("FmData: bcheckChecksum = " + bcheckChecksum + ", checksum = " + checksum + ", checksum2 = " + checksum2);
+ if (bcheckChecksum && checksum != checksum2) {
+ if (utility.DEBUG_FMDATA) {
+ if (iPayloadLength < 0) {
+ appendToLog("FmData: CheckSum ERROR, iPayloadLength=" + iPayloadLength + ", cs108DataLeftOffset=" + cs108DataLeftOffset + ", dataIn=" + byteArrayToString(dataIn));
+ }
+ byte[] invalidPart = new byte[8 + iPayloadLength];
+ System.arraycopy(dataIn, cs108DataReadStart, invalidPart, 0, invalidPart.length);
+ appendToLog("FmData: processCs108DataIn_ERROR, INCORRECT RevChecksum=" + Integer.toString(checksum, 16) + ", CalChecksum2=" + Integer.toString(checksum2, 16) + ",data=" + byteArrayToString(invalidPart));
+ }
+ } else {
+ validHeader = true;
+ if (cs108DataReadStart > cs108DataReadStartOld) {
+ if (utility.DEBUG_FMDATA) {
+ byte[] invalidPart = new byte[cs108DataReadStart - cs108DataReadStartOld];
+ System.arraycopy(dataIn, cs108DataReadStartOld, invalidPart, 0, invalidPart.length);
+ appendToLog("FmData: processCs108DataIn_ERROR, before valid data, invalid unused data: " + invalidPart.length + ", " + byteArrayToString(invalidPart));
+ }
+ } else if (cs108DataReadStart < cs108DataReadStartOld)
+ if (utility.DEBUG_FMDATA) appendToLog("FmData: processCs108DataIn_ERROR, invalid cs108DataReadStartdata=" + cs108DataReadStart + " < cs108DataReadStartOld=" + cs108DataReadStartOld);
+ cs108DataReadStartOld = cs108DataReadStart;
+
+ ConnectorData connectorData = new ConnectorData();
+ byte[] dataValues = new byte[iPayloadLength];
+ System.arraycopy(dataIn, cs108DataReadStart + 8, dataValues, 0, dataValues.length);
+ connectorData.dataValues = dataValues;
+ connectorData.milliseconds = System.currentTimeMillis();
+ if (utility.DEBUG_FMDATA) {
+ byte[] headerbytes = new byte[8];
+ System.arraycopy(dataIn, cs108DataReadStart, headerbytes, 0, headerbytes.length);
+ appendToLog("FmData: Got formatted dataIn = " + byteArrayToString(headerbytes) + " " + byteArrayToString(dataValues));
+ }
+ switch (dataIn[cs108DataReadStart + 3]) {
+ case (byte) 0xC2:
+ case (byte) 0x6A:
+ if (dataIn[cs108DataReadStart + 3] == (byte) 0xC2) connectorData.connectorTypes = ConnectorData.ConnectorTypes.RFID;
+ else connectorData.connectorTypes = ConnectorData.ConnectorTypes.BARCODE;
+ if (dataIn[cs108DataReadStart + 8] == (byte) 0x81 || (bis108 == false && dataIn[cs108DataReadStart + 8] == (byte) 0x91)) {
+ int iSequenceNumber = (int) (dataIn[cs108DataReadStart + 4] & 0xFF);
+ int itemp = iSequenceNumber;
+ if (itemp < this.iSequenceNumber) {
+ itemp += 256;
+ }
+ itemp -= (this.iSequenceNumber + 1);
+ if (DEBUG) appendToLog("FmData: iSequenceNumber = " + iSequenceNumber + ", old iSequenceNumber = " + this.iSequenceNumber + ", difference = " + itemp);
+ if (itemp != 0) {
+ if (DEBUG) appendToLog("FmData: Non-zero iSequenceNumber difference = " + itemp);
+ connectorData.invalidSequence = true;
+ if (bFirstSequence == false) {
+ invalidata += itemp;
+ String stringSequenceList = "";
+ for (int i = 0; i < itemp; i++) {
+ int iMissedNumber = (iSequenceNumber - i - 1);
+ if (iMissedNumber < 0) iMissedNumber += 256;
+ stringSequenceList += (i != 0 ? ", " : "") + String.format("%X", iMissedNumber);
+ }
+ if (DEBUG) utility.appendToLogView("FmData: " + String.format("ERROR !!!: invalidata = %d, %X - %X, miss %d: ", invalidata, iSequenceNumber, this.iSequenceNumber, itemp) + stringSequenceList);
+ }
+ }
+ bFirstSequence = false;
+ this.iSequenceNumber = iSequenceNumber;
+ }
+ if (DEBUG) utility.appendToLogView("FmData: Rin: " + (connectorData.invalidSequence ? "invalid sequence" : "ok") + "," + byteArrayToString(connectorData.dataValues));
+ validata++;
+ break;
+ case (byte) 0xD9:
+ if (DEBUG) appendToLog("FmData: BARTRIGGER NotificationData = " + byteArrayToString(connectorData.dataValues));
+ connectorData.connectorTypes = ConnectorData.ConnectorTypes.NOTIFICATION;
+ break;
+ case (byte) 0xE8:
+ connectorData.connectorTypes = ConnectorData.ConnectorTypes.SILICONLAB;
+ break;
+ case (byte) 0x5F:
+ connectorData.connectorTypes = ConnectorData.ConnectorTypes.BLUETOOTH;
+ break;
+ }
+ this.connectorDataList.add(connectorData);
+ if (utility.DEBUG_FMDATA) appendToLog("FmData: Got PackageIn with connectorData Type = " + connectorData.connectorTypes.toString() + ", Data = " + byteArrayToString(connectorData.dataValues));
+ utility.writeDebug2File("Up2 " + connectorData.connectorTypes.toString() + ", " + byteArrayToString(connectorData.dataValues));
+ cs108DataReadStart += ((8 + iPayloadLength));
+
+ byte[] cs108DataLeftNew = new byte[CS108DATALEFT_SIZE];
+ if (cs108DataLeftOffset - cs108DataReadStart < 0) {
+ if (utility.DEBUG_FMDATA) appendToLog("FmData: cs108DataLeftOffset = " + cs108DataLeftOffset + ", cs108DataReadStart = " + cs108DataReadStart + ", buffer = " + byteArrayToString(cs108DataLeft));
+ break;
+ }
+ System.arraycopy(cs108DataLeft, cs108DataReadStart, cs108DataLeftNew, 0, cs108DataLeftOffset - cs108DataReadStart);
+ cs108DataLeft = cs108DataLeftNew;
+ cs108DataLeftOffset -= cs108DataReadStart;
+ cs108DataReadStart = 0;
+ cs108DataReadStart = -1;
+ if (true || mCs108DataReadRequest == false) {
+ mCs108DataReadRequest = true;
+ if (DEBUGTHREAD && DEBUG) appendToLog("ready2Write: start immediate mReadWriteRunnable");
+ //appendToLog("post mReadWriteRunnable within processBleStreamInData");
+ mHandler.removeCallbacks(mReadWriteRunnable); mHandler.post(mReadWriteRunnable);
+ if (utility.DEBUG_BTDATA && DEBUG) appendToLog("BtData: CsReaderConnector.processBleStreamOut starts mReadWriteRunnable as mCs108DataReadRequest");
+ } //appendToLog("BtData: processBleStreamOut cannot start mReadWriteRunnable as mCs108DataReadRequest is true");
+ }
+ }
+ if (DEBUG) appendToLog("FmData: going to loop again with validHeader = " + validHeader + ", cs108DataReadStart = " + cs108DataReadStart + ", cs108DataReadStartOld = " + cs108DataReadStartOld);
+ if (validHeader && cs108DataReadStart < 0) {
+ cs108DataReadStart = 0;
+ cs108DataReadStartOld = 0;
+ } else {
+ cs108DataReadStart++;
+ }
+ }
+ if (DEBUG) appendToLog("FmData: end of while loop with cs108DataReadStart = " + cs108DataReadStart + ", cs108DataLeftOffset = " + cs108DataLeftOffset);
+ if (cs108DataReadStart != 0 && cs108DataLeftOffset >= 8) {
+ if (utility.DEBUG_FMDATA) {
+ byte[] invalidPart = new byte[cs108DataReadStart];
+ System.arraycopy(cs108DataLeft, 0, invalidPart, 0, invalidPart.length);
+ byte[] validPart = new byte[cs108DataLeftOffset - cs108DataReadStart];
+ System.arraycopy(cs108DataLeft, cs108DataReadStart, validPart, 0, validPart.length);
+ appendToLog("FmData: processCs108DataIn_ERROR, ENDLOOP invalid unused data: " + invalidPart.length + ", " + byteArrayToString(invalidPart) + ", with valid data length=" + validPart.length + ", " + byteArrayToString(validPart));
+ utility.writeDebug2File("Up2 Invalid " + invalidPart.length + ", " + byteArrayToString(invalidPart));
+ }
+
+ byte[] cs108DataLeftNew = new byte[CS108DATALEFT_SIZE];
+ System.arraycopy(cs108DataLeft, cs108DataReadStart, cs108DataLeftNew, 0, cs108DataLeftOffset - cs108DataReadStart);
+ cs108DataLeft = cs108DataLeftNew;
+ cs108DataLeftOffset -= cs108DataReadStart; cs108DataReadStart = 0;
+ }
+ }
+ }
+ if (DEBUG) appendToLog("CsReaderConnector.processStreamInData: while loop ending");
+ if (utility.DEBUG_FMDATA && bLooping) appendToLog("FmData: Exit loop with cs108DataLeftOffset=" + cs108DataLeftOffset);
+ }
+
+ private int readData(byte[] buffer, int byteOffset, int byteCount) {
+ if (usbConnector != null && usbConnector.isConnected()) return usbConnector.readSteamIn(buffer, byteOffset, byteCount);
+ return bluetoothGatt.readSteamIn(buffer, byteOffset, byteCount); }
+
+ public class CsConnectorData {
+ public int getVoltageMv() { return notificationConnector.mVoltageValue; }
+ public int getVoltageCnt() { return notificationConnector.mVoltageCount; }
+ boolean getTriggerButtonStatus() { return notificationConnector.triggerButtonStatus; }
+ public int getTriggerCount() { return notificationConnector.iTriggerCount; }
+ Date timeStamp;
+ String getTimeStamp() {
+ SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
+ return sdf.format(csConnectorData.timeStamp);
+ }
+
+ }
+ public CsConnectorData csConnectorData;
+ public SettingData settingData;
+
+ RfidConnector rfidConnector; public RfidReader rfidReader;
+ public BarcodeConnector barcodeConnector; public BarcodeNewland barcodeNewland;
+ public NotificationConnector notificationConnector;
+ public ControllerConnector controllerConnector;
+ public BluetoothConnector bluetoothConnector;
+
+ private Handler mHandler = new Handler();
+
+ public void csConnectorDataInit() {
+ connectorDataList = new ArrayList<>();
+ cs108DataLeft = new byte[CS108DATALEFT_SIZE];
+ cs108DataLeftOffset = 0;
+ zeroLenDisplayed = false;
+
+ invalidata = 0;
+ validata = 0;
+ //dataInBufferResetting = false;
+
+ writeDataCount = 0;
+
+ csConnectorData = new CsConnectorData();
+ notificationConnector = new NotificationConnector(context, utility, settingData.triggerReporting, settingData.triggerReportingCountSetting);
+ controllerConnector = new ControllerConnector(context, utility);
+ bluetoothConnector = new BluetoothConnector(context, utility, settingData.userDebugEnable);
+ //settingData = new SettingData(context, utility);
+
+ rfidReader = new RfidReader(context, utility, this, bis108, bluetoothGatt, settingData, notificationConnector);
+ rfidConnector = rfidReader.rfidConnector;
+ barcodeConnector = new BarcodeConnector(context, utility);
+ barcodeNewland = new BarcodeNewland(context, utility, barcodeConnector, settingData.barcode2TriggerMode);
+ barcodeConnector.barcodeConnectorCallback = new BarcodeConnector.BarcodeConnectorCallback(){
+ @Override
+ public boolean callbackMethod(byte[] dataValues, BarcodeConnector.CsReaderBarcodeData csReaderBarcodeData) {
+ barcodeNewland.decodeBarcodeUplinkData(dataValues, csReaderBarcodeData);
+ return false;
+ }
+ };
+ settingData.setConnectedConnectors(notificationConnector, rfidReader);
+ mHandler.removeCallbacks(mReadWriteRunnable); mHandler.post(mReadWriteRunnable);
+ appendToLog("!!! all major classes are initialised");
+ }
+
+ final int CS108DATALEFT_SIZE = 300; //4000; //100;
+ private ArrayList connectorDataList;
+ byte[] cs108DataLeft;
+ int cs108DataLeftOffset;
+ boolean zeroLenDisplayed;
+
+ public UsbConnector usbConnector;
+ public DeviceFinder deviceFinder;
+ public BluetoothGatt bluetoothGatt;
+ ScanCallback mScanCallback = null;
+ BluetoothAdapter.LeScanCallback mLeScanCallback = null;
+ Context context; TextView mLogView; Utility utility; boolean bis108; int iScanType;
+ void setScanType(int iScanType) { this.iScanType = iScanType; }
+ public CsReaderConnector(Context context, TextView mLogView, Utility utility, boolean bis108) {
+ this.context = context;
+ this.mLogView = mLogView;
+ this.utility = utility;
+ this.bis108 = bis108;
+ this.iScanType = iScanType;
+ appendToLog("CsReaderConnector.CsReaderConnector with bis108 = " + (bis108 ? "true" : "false"));
+
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
+ mScanCallback = new ScanCallback() {
+ @Override
+ public void onBatchScanResults(List results) {
+ if (DEBUG) appendToLog("onBatchScanResults()");
+ }
+
+ @Override
+ public void onScanFailed(int errorCode) {
+ if (DEBUG) appendToLog("onScanFailed()");
+ }
+
+ @Override
+ public void onScanResult(int callbackType, ScanResult result) {
+ boolean DEBUG = true;
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
+ BluetoothGatt.CsScanData scanResultA = new BluetoothGatt.CsScanData(result.getDevice(), result.getRssi(), result.getScanRecord().getBytes());
+ boolean found98 = true;
+ if (true) {
+ CheckResult resultc = check9800(scanResultA);
+ if (resultc != null) {
+ found98 = resultc.is9802;
+ scanResultA.name = resultc.stringName;
+ }
+ }
+ if (DEBUG) appendToLog("CsReaderConnector " + bis108 + ", found98 = " + found98 + ", mScanResultList 0 = " + (mScanResultList != null ? "VALID" : "NULL"));
+ if (mScanResultList != null && found98) {
+ scanResultA.serviceUUID2p2 = check9800_serviceUUID2p1;
+ appendToLog("found980 with name = " + scanResultA.name + ", device.name = " + scanResultA.device.getName());
+ mScanResultList.add(scanResultA);
+ if (DEBUG) appendToLog("CsReaderConnector, bis108 = " + bis108 + ", mScanResultList 0 = " + mScanResultList.size() + ", serviceUUID2p2 = " + scanResultA.serviceUUID2p2);
+ }
+ }
+ }
+ };
+ } else {
+ mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
+ @Override
+ public void onLeScan(final BluetoothDevice device, final int rssi, final byte[] scanRecord) {
+ if (true) appendToLog("onLeScan()");
+ BluetoothGatt.CsScanData scanResultA = new BluetoothGatt.CsScanData(device, rssi, scanRecord);
+ boolean found98 = true;
+ if (true) {
+ CheckResult resultc = check9800(scanResultA);
+ if (resultc != null) {
+ found98 = resultc.is9802;
+ scanResultA.name = resultc.stringName;
+ }
+ }
+ appendToLog("found98 = " + found98 + ", mScanResultList 1 = " + (mScanResultList != null ? "VALID" : "NULL"));
+ if (mScanResultList != null && found98) {
+ scanResultA.serviceUUID2p2 = check9800_serviceUUID2p1;
+ mScanResultList.add(scanResultA);
+ appendToLog("mScanResultList 1 = " + mScanResultList.size());
+ }
+ }
+ };
+ }
+
+ DEBUG_APDATA = utility.DEBUG_APDATA;
+ if (utility.ENABLE_USBDATA && !bis108) {
+ usbConnector = new UsbConnector(this, context, null, -1, -1, utility);
+ usbConnector.connectorCallback = new UsbConnector.ConnectorCallback() {
+ @Override
+ public void callbackMethod() {
+ //appendToLog("going to processBleStreamInData with bis108 " + bis108 + " and connected " + isBleConnected());
+ processStreamInData();
+ }
+ };
+ }
+ if (bis108) {
+ deviceFinder = new DeviceFinder(this, utility);
+ }
+ bluetoothGatt = new BluetoothGatt(context, utility, (bis108 ? "9800" : "9802"));
+ bluetoothGatt.connectorCallback = new BluetoothGatt.ConnectorCallback() {
+ @Override
+ public void callbackMethod() {
+ //appendToLog("going to processBleStreamInData with bis108 " + bis108 + " and connected " + isBleConnected());
+ processStreamInData();
+ }
+ };
+ DEBUG_CONNECT = utility.DEBUG_CONNECT; DEBUG_SCAN = utility.DEBUG_SCAN;
+
+ //cs108ConnectorDataInit();
+ //mHandler.removeCallbacks(bluetoothGatt.runnableProcessBleStreamInData); mHandler.post(bluetoothGatt.runnableProcessBleStreamInData);
+ //if (DEBUGTHREAD) appendToLog("start immediate mReadWriteRunnable");
+ //mHandler.removeCallbacks(mReadWriteRunnable); mHandler.post(mReadWriteRunnable);
+ //mHandler.removeCallbacks(runnableRx000UplinkHandler); mHandler.post(runnableRx000UplinkHandler);
+ appendToLog("foregroundReader: new SettingData for bis108 as " + bis108);
+ settingData = new SettingData(context, utility, this);
+ }
+
+ public BluetoothGatt.CsScanData getNewDeviceScanned() {
+ if (!mScanResultList.isEmpty()) {
+ if (DEBUG_SCAN) appendToLog("mScanResultList.size() = " + mScanResultList.size());
+ BluetoothGatt.CsScanData csScanData = mScanResultList.get(0); mScanResultList.remove(0);
+ if (csScanData != null) {
+ appendToLog("found981 with name = " + csScanData.name + ", device.name = " + csScanData.device.getName());
+ //appendToLog("DeviceFinder, CsReaderConnector.getNewDeviceScanned: csScanData.getAddress is " + csScanData.getAddress());
+ }
+ return csScanData;
+ } else return null;
+ }
+ ArrayList mScanResultList = new ArrayList<>();
+ int check9800_serviceUUID2p1 = 0;
+ class CheckResult {
+ boolean is9802;
+ String stringName;
+ }
+ CheckResult check9800(BluetoothGatt.CsScanData scanResultA) {
+ boolean found98 = false, DEBUG = true;
+ if (DEBUG) appendToLog("decoded data size = " + scanResultA.decoded_scanRecord.size());
+ int iNewADLength = 0;
+ byte[] newAD = new byte[0];
+ int iNewADIndex = 0;
+ check9800_serviceUUID2p1 = -1;
+ if (bluetoothGatt.isBLUETOOTH_CONNECTinvalid()) return null;
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S && ActivityCompat.checkSelfPermission(context, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED)
+ return null;
+ CheckResult checkResult = new CheckResult(); checkResult.is9802 = false;
+ String strTemp = scanResultA.getDevice().getName();
+ if (strTemp != null && DEBUG)
+ appendToLog("Found name = " + strTemp + ", length = " + String.valueOf(strTemp.length()));
+ for (byte bdata : scanResultA.getScanRecord()) {
+ if (iNewADIndex >= iNewADLength && iNewADLength != 0) {
+ scanResultA.decoded_scanRecord.add(newAD);
+ iNewADIndex = 0;
+ iNewADLength = 0;
+ if (DEBUG) {
+ String stringADType = "";
+ if (newAD[0] == 1) stringADType = "Flags";
+ else if (newAD[0] == 2) stringADType = "Incomplete List of 16-bit Service UUIDs";
+ else if (newAD[0] == 3) stringADType = "Complete list of 16-bit service UUIDs";
+ else if (newAD[0] == 9) {
+ byte[] byteString = new byte[newAD.length - 1];
+ System.arraycopy(newAD, 1, byteString, 0, byteString.length);
+ checkResult.stringName = new String(byteString, StandardCharsets.UTF_8);
+ stringADType = "Complete local name, " + checkResult.stringName;
+ }
+ else if (newAD[0] == 0x0A) stringADType = "Tx power level";
+ else if (newAD[0] == 0x12) stringADType = "Peripheral connection interval range";
+ else if (newAD[0] == 0x16) stringADType = "Service data - 16-bit UUID";
+ else if (newAD[0] == 0x19) stringADType = "Appearance";
+ else if (newAD[0] == (byte)0xFF) {
+ String stringManufactuer = "Unknown";
+ if (newAD[2] == 0x00 && newAD[1] == 0x06) stringManufactuer = "Microsoft";
+ else if (newAD[2] == 0x00 && newAD[1] == 0x4C) stringManufactuer = "Apple";
+ stringADType = stringManufactuer + " manufacturer specific Data";
+ }
+ else stringADType = "Unhandled";
+ appendToLog("Size = " + scanResultA.decoded_scanRecord.size() + ", " + byteArrayToString(newAD) + ", " + stringADType);
+ }
+ }
+ if (iNewADLength == 0) {
+ iNewADLength = bdata;
+ newAD = new byte[iNewADLength];
+ iNewADIndex = 0;
+ } else newAD[iNewADIndex++] = bdata;
+ }
+ if (DEBUG) appendToLog("decoded data size = " + scanResultA.decoded_scanRecord.size());
+ for (int i = 0; /*scanResultA.device.getType() == BluetoothDevice.DEVICE_TYPE_LE &&*/ i < scanResultA.decoded_scanRecord.size(); i++) {
+ byte[] currentAD = scanResultA.decoded_scanRecord.get(i);
+ if (DEBUG) appendToLog("Processing decoded data = " + byteArrayToString(currentAD));
+ if (currentAD[0] == 2) {
+ if (DEBUG) appendToLog("Processing UUIDs 0" + (bis108 ? "0" : "2"));
+ if (((currentAD[1] == 0 && ((iScanType & 0x01) != 0)) || (currentAD[1] == 2 && ((iScanType & 0x02) != 0))) && currentAD[2] == (byte) 0x98) {
+ if (DEBUG) appendToLog("Found 980" + (bis108 ? "0" : "2"));
+ found98 = true;
+ check9800_serviceUUID2p1 = currentAD[1];
+ if (DEBUG) appendToLog("serviceUD1D2p1 = " + check9800_serviceUUID2p1);
+ break;
+ }
+ }
+ }
+ if (found98 == false && DEBUG)
+ appendToLog("No 9800: with scanData = " + byteArrayToString(scanResultA.getScanRecord()));
+ else if (DEBUG_SCAN)
+ appendToLog("CsReaderConnector " + bis108 + ", Found 9800: with scanData = " + byteArrayToString(scanResultA.getScanRecord()));
+ checkResult.is9802 = found98;
+ return checkResult;
+ }
+
+ long timeReady; boolean aborting = false, sendFailure = false;
+ private final Runnable mReadWriteRunnable = new Runnable() {
+ boolean ready2Write = false, DEBUG = false;
+ int timer2Write = 0;
+ boolean validBuffer;
+
+ @Override
+ public void run() {
+ if (DEBUGTHREAD || utility.DEBUG_BTDATA) appendToLog("BtData: CsReaderConnector.mReadWriteRunnable starts");
+ if (rfidConnector == null) {
+ mHandler.postDelayed(mReadWriteRunnable, 500);
+ if (utility.DEBUG_BTDATA) appendToLog("BtData: CsReaderConnector.mReadWriteRunnable restart after 500ms");
+ return;
+ }
+ if (timer2Write != 0 || bluetoothGatt.getStreamInBufferSize() != 0 || rfidConnector.mRfidToRead.size() != 0) {
+ validBuffer = true;
+ if (DEBUG) appendToLog("mReadWriteRunnable(): START, timer2Write=" + timer2Write + ", streamInBufferSize = " + bluetoothGatt.getStreamInBufferSize() + ", mRfidToRead.size=" + rfidConnector.mRfidToRead.size() + ", mRx000ToRead.size=" + rfidReader.mRx000ToRead.size());
+ } else validBuffer = false;
+ int intervalReadWrite = 250; //50; //50; //500; //500, 100;
+ if (rfidConnector.rfidPowerOnTimeOut >= intervalReadWrite) {
+ rfidConnector.rfidPowerOnTimeOut -= intervalReadWrite;
+ if (rfidConnector.rfidPowerOnTimeOut <= 0) {
+ rfidConnector.rfidPowerOnTimeOut = 0;
+ }
+ }
+ if (barcodeConnector.barcodePowerOnTimeOut >= intervalReadWrite) {
+ barcodeConnector.barcodePowerOnTimeOut -= intervalReadWrite;
+ if (barcodeConnector.barcodePowerOnTimeOut <= 0) {
+ barcodeConnector.barcodePowerOnTimeOut = 0;
+ }
+ }
+ if (barcodeConnector.barcodePowerOnTimeOut != 0)
+ if (DEBUG) appendToLog("mReadWriteRunnable(): barcodePowerOnTimeOut = " + barcodeConnector.barcodePowerOnTimeOut);
+
+ long lTime = System.currentTimeMillis();
+ if (DEBUGTHREAD) appendToLog("start new mReadWriteRunnable after " + intervalReadWrite + " ms");
+ //appendToLog("postDelayed mReadWriteRunnable within mReadWriteRunnable");
+ mHandler.removeCallbacks(mReadWriteRunnable); mHandler.postDelayed(mReadWriteRunnable, intervalReadWrite);
+ if (utility.DEBUG_BTDATA) appendToLog("BtData: CsReaderConnector.mReadWriteRunnable restart after 250ms");
+ if (rfidReader == null) return;
+
+ boolean bFirst = true;
+ boolean bLooping = false;
+ mCs108DataReadRequest = false;
+ while (!connectorDataList.isEmpty()) {
+ if (utility.DEBUG_PKDATA && bLooping == false) appendToLog("PkData: Entering loop with connectorDataList.size = " + connectorDataList.size());
+ bLooping = true;
+
+ if (!isConnected()) {
+ connectorDataList.clear();
+ } else if (System.currentTimeMillis() - lTime > (intervalRx000UplinkHandler / 2)) {
+ utility.writeDebug2File("Up3 " + "Timeout");
+ utility.appendToLogView("PkData: mReadWriteRunnable: TIMEOUT !!! mCs108DataRead.size() = " + connectorDataList.size());
+ break;
+ } else {
+ if (bFirst) { bFirst = false; } //writeDebug2File("C" + String.valueOf(intervalReadWrite) + ", " + System.currentTimeMillis()); }
+ try {
+ ConnectorData connectorData = connectorDataList.get(0);
+ connectorDataList.remove(0);
+ boolean bValid = true;
+ if (utility.DEBUG_PKDATA) appendToLog("PkData: connectorData.type = " + connectorData.connectorTypes.toString() + ", connectorData.dataValues = " + byteArrayToString(connectorData.dataValues));
+ if (rfidConnector.isMatchRfidToWrite(connectorData)) {
+ if (false) {
+ for (int i = 0; i < rfidReader.mRx000ToRead.size(); i++) {
+ if (rfidReader.mRx000ToRead.get(i).responseType == RfidReaderChipData.HostCmdResponseTypes.TYPE_COMMAND_END)
+ if (DEBUG) appendToLog("mRx0000ToRead with COMMAND_END is removed");
+ }
+ if (DEBUG) appendToLog("mRx000ToRead.clear !!!");
+ }
+ rfidReader.mRx000ToRead.clear(); if (DEBUG) appendToLog("mRx000ToRead.clear !!!");
+ if (writeDataCount > 0) writeDataCount--; if (bis108) ready2Write = true; //btSendTime = 0; aborting = false;
+ } else if (barcodeConnector.isMatchBarcodeToWrite(connectorData)) {
+ if (writeDataCount > 0) writeDataCount--; if (bis108) ready2Write = true; if (true) appendToLog("true isMatchBarcodeToWrite "); //btSendTime = 0;
+ } else if (notificationConnector.isMatchNotificationToWrite(connectorData)) {
+ if (writeDataCount > 0) writeDataCount--; ready2Write = true; if (true) appendToLog("true isMatchNotificationToWrite"); btSendTime = 0; if (utility.DEBUG_PKDATA) appendToLog("PkData: mReadWriteRunnable: matched notification. btSendTime is set to 0 to allow new sending.");
+ } else if (controllerConnector.isMatchControllerToWrite(connectorData)) {
+ if (writeDataCount > 0) writeDataCount--; ready2Write = true; if (false) appendToLog("true isMatchSiliconLabIcToWrite"); btSendTime = 0; if (utility.DEBUG_PKDATA) appendToLog("PkData: mReadWriteRunnable: matched AtmelIc. btSendTime is set to 0 to allow new sending.");
+ } else if (bluetoothConnector.isMatchBluetoothIcToWrite(connectorData)) {
+ if (writeDataCount > 0) writeDataCount--; ready2Write = true; appendToLog("ready2Write is set true after true isMatchBluetoothIcToWrite "); btSendTime = 0; if (utility.DEBUG_PKDATA) appendToLog("PKData: mReadWriteRunnable: matched bluetoothIc. btSendTime is set to 0 to allow new sending.");
+ } else if (rfidConnector.isRfidToRead(connectorData)) { rfidConnector.rfidValid = true;
+ } else if (barcodeConnector.isBarcodeToRead(connectorData)) {
+ } else if (notificationConnector.isNotificationToRead(connectorData)) {
+ /* if (mRfidDevice.mRfidToWrite.size() != 0 && mNotificationDevice.mNotificationToRead.size() != 0) {
+ mNotificationDevice.mNotificationToRead.remove(0);
+ mRfidDevice.mRfidToWrite.clear();
+ mSiliconLabIcDevice.mSiliconLabIcToWrite.add(SiliconLabIcPayloadEvents.RESET);
+
+ timeReady = System.currentTimeMillis() - 1500;
+ appendToLog("mReadWriteRunnable: endingMessage: changed timeReady");
+ }*/
+ } else bValid = false;
+ if (bValid) {
+ //writeDebug2File("Up33 " + cs108ReadData.cs108ConnectedDevices.toString() + ", " + byteArrayToString(cs108ReadData.dataValues));
+ } else {
+ appendToLog("mReadWriteRunnable: !!! CANNOT process " + byteArrayToString(connectorData.dataValues) + " with mDataToWriteRemoved = " + barcodeConnector.mDataToWriteRemoved);
+ utility.writeDebug2File("Up3 Invalid " + connectorData.dataValues.length + ", " + byteArrayToString(connectorData.dataValues));
+ }
+ if (barcodeConnector.mDataToWriteRemoved) {
+ barcodeConnector.mDataToWriteRemoved = false; ready2Write = true; btSendTime = 0;
+ appendToLog("ready2Write is set true after true mBarcodeDevice.mDataToWriteRemoved ");
+ if (utility.DEBUG_PKDATA) appendToLog("PkData: mReadWriteRunnable: processed barcode. btSendTime is set to 0 to allow new sending.");
+ }
+ } catch (Exception ex) {
+ }
+ }
+ }
+ if (utility.DEBUG_PKDATA && bLooping) appendToLog("PkData: Exiting loop with connectorDataList.size = " + connectorDataList.size());
+
+ lTime = System.currentTimeMillis();
+ if (rfidConnector.mRfidToWriteRemoved) {
+ rfidConnector.mRfidToWriteRemoved = false; ready2Write = true; btSendTime = 0; if (false) appendToLog("ready2Write is set true after true mRfidDevice.mRfidToWriteRemoved ");
+ btSendTime = (lTime - btSendTimeOut + BTSENDDELAY);
+ if (DEBUGTHREAD) appendToLog("ready2Write: start new mReadWriteRunnable after " + BTSENDDELAY + " ms");
+ //appendToLog("postDelayed mReadWriteRunnable within mReadWriteRunnable 2");
+ mHandler.removeCallbacks(mReadWriteRunnable); mHandler.postDelayed(mReadWriteRunnable, BTSENDDELAY + 2);
+ if (utility.DEBUG_BTDATA) appendToLog("BtData: CsReaderConnector.mReadWriteRunnable restart after " + (BTSENDDELAY + 2) +"ms") ;
+ if (utility.DEBUG_PKDATA) appendToLog("PkData: mReadWriteRunnable: processed Rfidcode. btSendTime is set to 0 to allow new sending with systime = " + lTime);
+ }
+ if (bis108) {
+ int timeout2Ready = 2000;
+ if (aborting || sendFailure) timeout2Ready = 200;
+ if (System.currentTimeMillis() > timeReady + timeout2Ready) ready2Write = true;
+ } else {
+ if (ready2Write == false && lTime - btSendTime > btSendTimeOut) {
+ appendToLog("ready2Write is set to true from false with difference = " + (lTime - btSendTime) + ", systime = " + lTime + ", btSendTime = " + btSendTime + ", btSendTimeOut = " + btSendTime);
+ ready2Write = true;
+ }
+ }
+ if (DEBUG) appendToLog("BtData: ready2Write = " + ready2Write);
+ if (ready2Write) {
+ timeReady = System.currentTimeMillis();
+ timer2Write = 0;
+ if (rfidConnector.rfidFailure) {
+ rfidConnector.mRfidToWrite.clear(); appendToLog("BtDataOut: mRfidToWrite.clear 2");
+ }
+ //if (barcodeConnector.barcodeFailure) { barcodeConnector.barcodeToWrite.clear(); appendToLog("barcodeToWrite is clear"); }
+ if (rfidReader.mRx000ToWrite.size() != 0 && rfidConnector.mRfidToWrite.size() == 0) {
+ if (DEBUG)
+ appendToLog("mReadWriteRunnable(): mRx000ToWrite.size=" + rfidReader.mRx000ToWrite.size() + ", mRfidToWrite.size=" + rfidConnector.mRfidToWrite.size());
+ rfidReader.addRfidToWrite(rfidReader.mRx000ToWrite.get(0));
+ }
+ boolean bisRfidCommandStop = false, bisRfidCommandExecute = false;
+ if (rfidConnector.mRfidToWrite.size() != 0 && DEBUG)
+ appendToLog("mRfidToWrite = " + rfidConnector.mRfidToWrite.get(0).rfidPayloadEvent.toString() + "." + byteArrayToString(rfidConnector.mRfidToWrite.get(0).dataValues) + ", ready2write = " + ready2Write);
+ if (rfidConnector.mRfidToWrite.size() != 0) {
+ RfidConnector.CsReaderRfidData csReaderRfidData = rfidConnector.mRfidToWrite.get(0);
+ if (csReaderRfidData.rfidPayloadEvent == RfidConnector.RfidPayloadEvents.RFID_COMMAND) {
+ int ii;
+ if (false) {
+ byte[] byCommandExeccute = new byte[]{0x70, 1, 0, (byte) 0xF0};
+ for (ii = 0; ii < 4; ii++) {
+ if (byCommandExeccute[ii] != csReaderRfidData.dataValues[ii]) break;
+ }
+ if (ii == 4) bisRfidCommandExecute = true;
+ }
+
+ byte[] byCommandStop = new byte[]{(byte) 0x40, 3, 0, 0, 0, 0, 0, 0};
+ for (ii = 0; ii < 4; ii++) {
+ if (byCommandStop[ii] != csReaderRfidData.dataValues[ii]) break;
+ }
+ if (ii == 4) bisRfidCommandStop = true;
+ if (DEBUG)
+ appendToLog("mRfidToWrite(0).dataValues = " + byteArrayToString(rfidConnector.mRfidToWrite.get(0).dataValues) + ", bisRfidCommandExecute = " + bisRfidCommandExecute + ", bisRfidCommandStop = " + bisRfidCommandStop);
+ }
+ }
+ if (barcodeConnector.barcodeToWrite.size() != 0 && true)
+ appendToLog("AAA 1 barcodeToWrite.size = " + barcodeConnector.barcodeToWrite.size() + ", bisRfidCommandStop = " + bisRfidCommandStop + ", barcodePowerOnTimeOut = " + barcodeConnector.barcodePowerOnTimeOut);
+ if (DEBUG) appendToLog("BtData: bisRfidCommandStop is " + bisRfidCommandStop);
+ if (bisRfidCommandStop) {
+ if (rfidConnector.rfidPowerOnTimeOut != 0) {
+ if (DEBUG) appendToLog("rfidPowerOnTimeOut = " + rfidConnector.rfidPowerOnTimeOut + ", mRfidToWrite.size() = " + rfidConnector.mRfidToWrite.size());
+ } else if (rfidConnector.rfidFailure == false && rfidConnector.mRfidToWrite.size() != 0) {
+ if (isConnected() == false) {
+ rfidConnector.mRfidToWrite.clear(); appendToLog("BtDataOut: mRfidToWrite.clear 3");
+ } else {
+ if (utility.DEBUG_BTDATA) appendToLog("BtData: CsReaderConnector.mReadWriteRunnable 1: currentTime = " + System.currentTimeMillis() + ", btSendTime = " + btSendTime + ", difference = " + (System.currentTimeMillis() - btSendTime) + ", btSendTimeOut = " + btSendTimeOut);
+ if (System.currentTimeMillis() - btSendTime > btSendTimeOut) {
+ boolean retValue = false;
+ appendToLog("aabb 5A");
+ byte[] dataOut = rfidConnector.sendRfidToWrite(usbConnector != null && usbConnector.isConnected());
+ if (dataOut != null) {
+ appendToLog("CsReaderConnector.mReadWriteRunnable: UsbConnector: going to writeData 1");
+ retValue = writeData(dataOut, (rfidConnector.mRfidToWrite.get(0).waitUplinkResponse ? 500 : 0));
+ if (false) appendToLog("BtData: done writeData with waitUplinkResponse = " + rfidConnector.mRfidToWrite.get(0).waitUplinkResponse);
+ }
+ appendToLog("BtData: done writeRfid with size = " + rfidConnector.mRfidToWrite.size() + ", PayloadEvents = " + rfidConnector.mRfidToWrite.get(0).rfidPayloadEvent.toString() + ", data=" + byteArrayToString(rfidConnector.mRfidToWrite.get(0).dataValues));
+ rfidConnector.sendRfidToWriteSent++;
+ if (retValue) {
+ rfidConnector.mRfidToWriteRemoved = false;
+ if (DEBUG) appendToLog("writeRfid() with sendRfidToWriteSent = " + rfidConnector.sendRfidToWriteSent);
+ sendFailure = false;
+ //bValue = true;
+ } else sendFailure = true;
+ ready2Write = false; //
+ appendToLog("ready2Write is set false after sendRfidToWrite");
+ }
+ }
+ }
+ } else if (!bis108 && rfidReader.isInventoring()) {
+ if (rfidConnector.rfidPowerOnTimeOut != 0) {
+ if (DEBUG) appendToLog("rfidPowerOnTimeOut = " + rfidConnector.rfidPowerOnTimeOut + ", mRfidToWrite.size() = " + rfidConnector.mRfidToWrite.size());
+ } else if (rfidConnector.rfidFailure == false && rfidConnector.mRfidToWrite.size() != 0) {
+ if (isConnected() == false) {
+ rfidConnector.mRfidToWrite.clear(); appendToLog("BtDataOut: mRfidToWrite.clear 4");
+ } else {
+ if (DEBUG)
+ appendToLog("BtDataOut 2: currentTime = " + System.currentTimeMillis() + ", btSendTime = " + btSendTime + ", difference = " + (System.currentTimeMillis() - btSendTime) + ", btSendTimeOut = " + btSendTimeOut);
+ if (System.currentTimeMillis() - btSendTime > btSendTimeOut) {
+ boolean retValue = false;
+ appendToLog("aabb 5b");
+ byte[] dataOut = rfidConnector.sendRfidToWrite(usbConnector != null && usbConnector.isConnected());
+ if (dataOut != null) {
+ appendToLog("CsReaderConnector.mReadWriteRunnable: UsbConnector: going to writeData 2");
+ retValue = writeData(dataOut, (rfidConnector.mRfidToWrite.get(0).waitUplinkResponse ? 500 : 0));
+ if (false) appendToLog("done writeData with waitUplinkResponse = " + rfidConnector.mRfidToWrite.get(0).waitUplinkResponse);
+ }
+ if (DEBUG) appendToLog("BtDataOut: done writeRfid with size = " + rfidConnector.mRfidToWrite.size() + ", PayloadEvents = " + rfidConnector.mRfidToWrite.get(0).rfidPayloadEvent.toString() + ", data=" + byteArrayToString(rfidConnector.mRfidToWrite.get(0).dataValues));
+ rfidConnector.sendRfidToWriteSent++;
+ if (retValue) {
+ rfidConnector.mRfidToWriteRemoved = false;
+ if (DEBUG) appendToLog("writeRfid() with sendRfidToWriteSent = " + rfidConnector.sendRfidToWriteSent);
+ sendFailure = false;
+ //bValue = true;
+ } else sendFailure = true;
+
+ if (retValue) {
+ ready2Write = false;
+ if (false) appendToLog("ready2Write is set false after true sendRfidToWrite");
+ }
+ }
+ }
+ }
+ } else if (notificationConnector.notificationToWrite.size() != 0) {
+ appendToLog("aabb 3n");
+ if (isConnected() == false) {
+ notificationConnector.notificationToWrite.clear(); appendToLog("notificationToWrite is clear"); }
+ else if (System.currentTimeMillis() - btSendTime > btSendTimeOut) {
+ appendToLog("aabb 3n1");
+ appendToLog("1 UsbConnector is " + (usbConnector == null ? "null" : "valid") + "with bis108 as " + bis108);
+ byte[] dataOut = notificationConnector.sendNotificationToWrite((usbConnector != null && usbConnector.isConnected()));
+ boolean retValue = false;
+
+ if (utility.DEBUG_PKDATA && notificationConnector.sendDataToWriteSent != 0)
+ appendToLog("!!! notificationToWrite.sendDataToWriteSent = " + controllerConnector.sendDataToWriteSent);
+ if (utility.DEBUG_PKDATA)
+ appendToLog(String.format("PkData: write notificationToWrite.%s with notificationConnector.sendDataToWriteSent = %d",
+ notificationConnector.notificationToWrite.get(0).notificationPayloadEvent.toString(),
+ notificationConnector.sendDataToWriteSent));
+ if (false && notificationConnector.sendDataToWriteSent != 0)
+ appendToLog("!!! mSiliconLabIcDevice.sendDataToWriteSent = " + notificationConnector.sendDataToWriteSent);
+
+ if (dataOut != null) {
+ appendToLog("aabb 3n2");
+ appendToLog("CsReaderConnector.mReadWriteRunnable: UsbConnector: going to writeData 3 " + byteArrayToString(dataOut));
+ retValue = writeData(dataOut, 0);
+ }
+ if (retValue) {
+ //notificationController.sendDataToWriteSent++;
+ } else {
+ //if (DEBUG) appendToLogView("failure to send " + notificationController.notificationToWrite.get(0).toString());
+ //notificationController.notificationToWrite.remove(0); notificationController.sendDataToWriteSent = 0; appendToLog("notificationToWrite remove0 with length = " + notificationToWrite.size());
+ }
+ }
+ ready2Write = false; //
+ if (false) appendToLog("ready2Write is set false after true sendSiliconLabIcToWrite");
+ } else if (controllerConnector.controllerToWrite.size() != 0) {
+ appendToLog("AAA 5");
+ if (isConnected() == false) controllerConnector.controllerToWrite.clear();
+ else if (System.currentTimeMillis() - btSendTime > btSendTimeOut) {
+ byte[] dataOut = controllerConnector.sendControllerToWrite(usbConnector != null && usbConnector.isConnected());
+ boolean retValue = false;
+
+ if (utility.DEBUG_PKDATA && controllerConnector.sendDataToWriteSent != 0)
+ appendToLog("!!! siliconLabIcDevice.sendDataToWriteSent = " + controllerConnector.sendDataToWriteSent);
+ if (utility.DEBUG_PKDATA)
+ appendToLog(String.format("PkData: write mSiliconLabIcDevice.%s with mSiliconLabIcDevice.sendDataToWriteSent = %d",
+ controllerConnector.controllerToWrite.get(0).toString(),
+ controllerConnector.sendDataToWriteSent));
+ if (false && controllerConnector.sendDataToWriteSent != 0)
+ appendToLog("!!! mSiliconLabIcDevice.sendDataToWriteSent = " + controllerConnector.sendDataToWriteSent);
+
+ if (dataOut != null) {
+ appendToLog("CsReaderConnector.mReadWriteRunnable: UsbConnector: going to writeData 4");
+ retValue = writeData(dataOut, 0);
+ }
+ if (retValue) {
+ //controllerConnector.sendDataToWriteSent++;
+ } else {
+ //if (DEBUG) appendToLogView("failure to send " + controllerConnector.controllerToWrite.get(0).toString());
+ //controllerConnector.controllerToWrite.remove(0); controllerConnector.sendDataToWriteSent = 0;
+ }
+ }
+ ready2Write = false; //
+ if (false) appendToLog("ready2Write is set false after true sendSiliconLabIcToWrite");
+ } else if (bluetoothConnector.bluetoothIcToWrite.size() != 0) { //Bluetooth version affects Barcode operation
+ appendToLog("AAA 6");
+ if (isConnected() == false) bluetoothConnector.bluetoothIcToWrite.clear();
+ else if (System.currentTimeMillis() - btSendTime > btSendTimeOut) {
+ byte[] dataOut = bluetoothConnector.sendBluetoothIcToWrite(usbConnector != null && usbConnector.isConnected());
+ boolean retValue = false;
+
+ if (utility.DEBUG_PKDATA && bluetoothConnector.sendDataToWriteSent != 0)
+ appendToLog("!!! mBluetoothIcDevice.sendDataToWriteSent = " + bluetoothConnector.sendDataToWriteSent);
+ if (utility.DEBUG_PKDATA)
+ appendToLog(String.format("PkData: write mBluetoothIcDevice.%s.%s with mBluetoothIcDevice.sendDataToWriteSent = %d",
+ bluetoothConnector.bluetoothIcToWrite.get(0).bluetoothIcPayloadEvent.toString(),
+ byteArrayToString(bluetoothConnector.bluetoothIcToWrite.get(0).dataValues),
+ bluetoothConnector.sendDataToWriteSent));
+ if (bluetoothConnector.sendDataToWriteSent != 0)
+ appendToLog("!!! mBluetoothIcDevice.sendDataToWriteSent = " + bluetoothConnector.sendDataToWriteSent);
+
+ if (dataOut != null) {
+ appendToLog("CsReaderConnector.mReadWriteRunnable: UsbConnector: going to writeData 5");
+ retValue = writeData(dataOut, 0);
+ }
+ if (retValue) {
+ //bluetoothConnector.sendDataToWriteSent++;
+ } else {
+ //if (DEBUG) appendToLogView("failure to send " + bluetoothConnector.bluetoothIcToWrite.get(0).bluetoothIcPayloadEvent.toString());
+ //bluetoothConnector.bluetoothIcToWrite.remove(0); bluetoothConnector.sendDataToWriteSent = 0;
+ }
+ }
+ ready2Write = false;
+ appendToLog("ready2Write is set false after non-zero mBluetoothIcToWrite.size()");
+ } else if (barcodeConnector.barcodeToWrite.size() != 0 && barcodeConnector.barcodePowerOnTimeOut == 0) {
+ appendToLog("AAA 7 barcodeToWrite.size = " + barcodeConnector.barcodeToWrite.size());
+ if (isConnected() == false) { barcodeConnector.barcodeToWrite.clear(); appendToLog("barcodeToWrite is clear"); }
+ else if (System.currentTimeMillis() - btSendTime > btSendTimeOut) {
+ appendToLog("2 UsbConnector is " + (usbConnector == null ? "null" : "valid"));
+ byte[] dataOut = barcodeConnector.sendBarcodeToWrite( usbConnector != null && usbConnector.isConnected());
+ if (dataOut != null) {
+ appendToLog("CsReaderConnector.mReadWriteRunnable: UsbConnector: going to writeData 6");
+ writeData(dataOut, (barcodeConnector.barcodeToWrite.get(0).waitUplinkResponse ? 500 : 0));
+ }
+ }
+ ready2Write = false;
+ appendToLog("ready2Write is set false after true sendBarcodeToWrite");
+ } else if (rfidConnector.rfidPowerOnTimeOut != 0) {
+ if (DEBUG || true) appendToLog("rfidPowerOnTimeOut = " + rfidConnector.rfidPowerOnTimeOut + ", mRfidToWrite.size() = " + rfidConnector.mRfidToWrite.size());
+ } else if (rfidConnector.rfidFailure == false && rfidConnector.mRfidToWrite.size() != 0) {
+ appendToLog("aabb 3");
+ if (utility.DEBUG_BTDATA) appendToLog("BtData: CsReaderConnector.mReadWriteRunnable rfidFailure is false and mRfidToWrite.size is " + rfidConnector.mRfidToWrite.size());
+ if (isConnected() == false) {
+ rfidConnector.mRfidToWrite.clear(); appendToLog("BtDataOut: mRfidToWrite.clear 5");
+ } else {
+ if (utility.DEBUG_BTDATA)
+ appendToLog("BtData: CsReaderConnector.mReadWriteRunnable 3 currentTime = " + System.currentTimeMillis() + ", btSendTime = " + btSendTime + ", difference = " + (System.currentTimeMillis() - btSendTime) + ", btSendTimeOut = " + btSendTimeOut);
+ appendToLog("aabb 4");
+ if (System.currentTimeMillis() - btSendTime > btSendTimeOut) {
+ boolean retValue = false;
+ appendToLog("aabb 5c");
+ byte[] dataOut = rfidConnector.sendRfidToWrite(usbConnector != null && usbConnector.isConnected());
+ if (dataOut != null) {
+ appendToLog("CsReaderConnector.mReadWriteRunnable: UsbConnector: going to writeData 7");
+ retValue = writeData(dataOut, (rfidConnector.mRfidToWrite.get(0).waitUplinkResponse ? 500 : 0));
+ if (false) appendToLog("done writeData with waitUplinkResponse = " + rfidConnector.mRfidToWrite.get(0).waitUplinkResponse);
+
+ if (false) appendToLog("AAA sending rifd data = " + byteArrayToString(dataOut));
+ String string = byteArrayToString(dataOut).substring(16);
+ String stringCompare = "800280B310A";
+ if (bis108) stringCompare = "8002700100F00F000000";
+ if (false) appendToLog("AAA sending rifd data portion = " + string + ", " + string.indexOf(stringCompare));
+ if (string.indexOf(stringCompare) == 0)
+ rfidReader.setInventoring(true);
+ }
+ if (DEBUG && !rfidConnector.mRfidToWrite.isEmpty())
+ appendToLog("BtDataOut: done writeRfid with size = " + rfidConnector.mRfidToWrite.size() + ", PayloadEvents = " + rfidConnector.mRfidToWrite.get(0).rfidPayloadEvent.toString() + ", data=" + byteArrayToString(rfidConnector.mRfidToWrite.get(0).dataValues));
+ rfidConnector.sendRfidToWriteSent++;
+ if (retValue) {
+ rfidConnector.mRfidToWriteRemoved = false;
+ if (DEBUG)
+ appendToLog("writeRfid() with sendRfidToWriteSent = " + rfidConnector.sendRfidToWriteSent);
+ sendFailure = false;
+ //bValue = true;
+ } else sendFailure = true;
+
+ if (retValue) {
+ if (false) appendToLog("ready2Write is set false after true sendRfidToWrite");
+ ready2Write = false;
+ }
+ }
+ }
+ }
+ }
+ /*if (validBuffer) {
+ if (DEBUG) appendToLog("mReadWriteRunnable: END, timer2Write=" + timer2Write + ", streamInBufferSize = " + bluetoothGatt.getStreamInBufferSize() + ", mRfidToRead.size=" + rfidConnector.mRfidToRead.size() + ", mRx000ToRead.size=" + rfidReader.mRx000ToRead.size());
+ }*/
+ //appendToLog("mRfidDevice is " + (mRfidDevice == null ? "null" : "valid"));
+ //appendToLog("mRfidDevice.mRfidReaderChip is " + (mRfidDevice.mRfidReaderChip == null ? "null" : "valid"));
+ //appendToLog("mRfidDevice.mRfidReaderChip.mRfidReaderChip is " + (mRfidDevice.mRfidReaderChip.mRfidReaderChip == null ? "null" : "valid"));
+ if (rfidReader != null) rfidReader.uplinkHandler();
+ if (DEBUGTHREAD) appendToLog("mReadWriteRunnable: mReadWriteRunnable ends");
+ }
+ };
+
+ int intervalRx000UplinkHandler = 250;
+ /*private final Runnable runnableRx000UplinkHandler = new Runnable() {
+ @Override
+ public void run() {
+// mRfidDevice.mRx000Device.mRx000UplinkHandler();
+ mHandler.postDelayed(runnableRx000UplinkHandler, intervalRx000UplinkHandler);
+ }
+ };
+ */
+
+ public String getModelName() {
+ boolean DEBUG = true;
+ if (bis108) return controllerConnector.getModelName();
+ String strModelName = controllerConnector.getModelName();
+ if (DEBUG) appendToLog("Cs710Library4A.getModelName 0xb006 = " + strModelName);
+ if (true) {
+ String strModelName1 = rfidReader.rfidReaderChipE710.rx000Setting.getModelCode();
+ if (DEBUG) appendToLog("Cs710Library4A.getModelName strModelName1 = " + strModelName1);
+ if (strModelName == null || strModelName.length() == 0) {
+ if (DEBUG) appendToLog("Cs710Library4A.getModelName strModeName is updated as modeCode");
+ strModelName = strModelName1;
+ }
+ }
+ return strModelName;
+ }
+
+ public int getBatteryLevel() {
+ int iValue = csConnectorData.getVoltageMv();
+ if (!bis108) {
+ String hostVersion = controllerConnector.getVersion(); //false if lower, true if equal or higher
+ String strVersionHost = "2.1.5";
+ String[] strHostVersions = strVersionHost.split("\\.");
+ boolean bResult = utility.checkHostProcessorVersion(hostVersion, Integer.parseInt(strHostVersions[0].trim()), Integer.parseInt(strHostVersions[1].trim()), Integer.parseInt(strHostVersions[2].trim()));
+ if (false)
+ appendToLog("getBatteryLevel: hostVersion = " + hostVersion + ", bResult = " + bResult + ", level = " + iValue);
+ if (!bResult) {
+ if (iValue >= 4450) iValue -= 430;
+ else if (iValue > 350) iValue -= 350;
+ }
+ }
+ return iValue;
+ }
+
+ public String checkVersion() {
+ appendToLog("CsReaderConnector.checkVersion, getMacVer");
+ String macVersion = rfidReader.getMacVer();
+ String hostVersion = controllerConnector.getVersion();
+ String bluetoothVersion = bluetoothConnector.getBluetoothIcVersion();
+ String stringPopup = "";
+ int icsModel = bluetoothConnector.getCsModel();
+
+ if (!rfidReader.isRfidFailure()) {
+ if (bis108) return null; //Assume no checking
+ if (bis108) {
+ String strVersionRFID = "2.6.46"; String[] strRFIDVersions = strVersionRFID.split("\\.");
+ String strVersionBT = "1.0.22"; String[] strBTVersions = strVersionBT.split("\\.");
+ String strVersionHost = "1.0.17"; String[] strHostVersions = strVersionHost.split("\\.");
+ if (true) {
+ if (utility.checkHostProcessorVersion(macVersion, Integer.parseInt(strRFIDVersions[0].trim()), Integer.parseInt(strRFIDVersions[1].trim()), Integer.parseInt(strRFIDVersions[2].trim())) == false)
+ stringPopup += "\nRFID processor firmware: V" + strVersionRFID;
+ if (icsModel != 463) {
+ if (utility.checkHostProcessorVersion(hostVersion, Integer.parseInt(strHostVersions[0].trim()), Integer.parseInt(strHostVersions[1].trim()), Integer.parseInt(strHostVersions[2].trim())) == false)
+ stringPopup += "\nSiliconLab firmware: V" + strVersionHost;
+ if (utility.checkHostProcessorVersion(bluetoothVersion, Integer.parseInt(strBTVersions[0].trim()), Integer.parseInt(strBTVersions[1].trim()), Integer.parseInt(strBTVersions[2].trim())) == false)
+ stringPopup += "\nBluetooth firmware: V" + strVersionBT;
+ }
+ }
+ } else {
+ String strVersionRFID = "0.0.0";
+ String strVersionHost = "0.0.0";
+ String strVersionBT = "1.0.8"; String[] strBTVersions = strVersionBT.split("\\.");
+ boolean bValidMac = true;
+ if (macVersion.indexOf("2.01") == 0) {
+ strVersionRFID = "2.1.0";
+ strVersionHost = "2.1.5";
+ } else if (macVersion.indexOf("2.00") == 0) {
+ strVersionRFID = "2.0.0";
+ strVersionHost = "2.0.6";
+ } else if (macVersion.indexOf("1.2.") == 0) {
+ strVersionRFID = "1.2.0";
+ strVersionHost = "0.2.20";
+ } else {
+ bValidMac = false;
+ stringPopup += "Unknown RFID firmware version";
+ }
+ if (bValidMac) {
+ String[] strRFIDVersions = strVersionRFID.split("\\.");
+ if (false && !utility.checkHostProcessorVersion(macVersion, Integer.parseInt(strRFIDVersions[0].trim()), Integer.parseInt(strRFIDVersions[1].trim()), Integer.parseInt(strRFIDVersions[2].trim())))
+ stringPopup += "\nRFID processor firmware: V" + strVersionRFID;
+ String[] strHostVersions = strVersionHost.split("\\.");
+ if (hostVersion.indexOf(strVersionHost.substring(0, 4)) != 0 ||
+ utility.checkHostProcessorVersion(hostVersion, Integer.parseInt(strHostVersions[0].trim()), Integer.parseInt(strHostVersions[1].trim()), Integer.parseInt(strHostVersions[2].trim())) == false)
+ stringPopup += "\nAtmel firmware: V" + strVersionHost;
+
+ if (icsModel != 463) {
+ if (false && utility.checkHostProcessorVersion(bluetoothVersion, Integer.parseInt(strBTVersions[0].trim()), Integer.parseInt(strBTVersions[1].trim()), Integer.parseInt(strBTVersions[2].trim())) == false)
+ stringPopup += "\nBluetooth firmware: V" + strVersionBT;
+ }
+ }
+ }
+ }
+ return stringPopup;
+ }
+}
+
+
+
+package com.csl.cslibrary4a;
+
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.net.DatagramPacket;
+import java.net.DatagramSocket;
+import java.net.InetAddress;
+import java.net.Socket;
+import java.nio.charset.StandardCharsets;
+import java.util.Random;
+
+public class DeviceFinder{
+ CsReaderConnector csReaderConnector;
+ Utility utility;
+ BluetoothGatt.CsScanData scanResultA = null;
+
+ public DeviceFinder(CsReaderConnector csReaderConnector, Utility utility) {
+ this.csReaderConnector = csReaderConnector;
+ this.utility = utility;
+ appendToLog("DeviceFinder.DeviceFinder");
+ }
+
+ void scanDevice(boolean enable) {
+ if (enable) {
+ Thread thread = new Thread(runnable);
+ thread.start();
+ }
+ }
+
+ Runnable runnable = new Runnable() {
+ @Override
+ public void run() {
+ appendToLog("DeviceFinder.runnable");
+
+ DatagramSocket udpSocket = null;
+ Socket tcpSocket = null;
+ ReaderSetting readerSetting = null;
+ try {
+ String strDestip = "255.255.255.255"; //"255.255.255.255", "192.168.25.197"
+
+ udpSocket = new DatagramSocket();
+ appendToLog("DeviceFinder.runnable: new udpSocket is " + (udpSocket == null ? "null" : "valid"));
+// udpSocket.setBroadcast(true);
+// appendToLog("DeviceFinder.runnable: done udpSocket.setBoardcast");
+ udpSocket.setSoTimeout(1000);
+ appendToLog("DeviceFinder.runnable: done udpSocket.setSoTimeout");
+
+ byte[] sbuffer = null; InetAddress address = null; int portnum = -1; DatagramPacket packet = null;
+ DatagramPacket p = null; byte[] message = null;
+ if (true) {
+ sbuffer = getBytesUdpSearch();
+
+ address = InetAddress.getByName(strDestip);
+ portnum = 3040;
+ appendToLog("DeviceFinder.runnable: done InetAddress.getByName with strDestip as " + strDestip + ", port as " + portnum);
+ packet = new DatagramPacket(sbuffer, sbuffer.length, address, portnum);
+
+ //Exception here
+ udpSocket.send(packet);
+ appendToLog("DeviceFinder.runnable: done udpSocket.send with sent data as " + utility.byteArrayToString(sbuffer));
+
+ message = new byte[200];
+ p = new DatagramPacket(message, message.length);
+ udpSocket.receive(p); //keeps on waiting here but i am sending data back from server, but it never receives
+ appendToLog("DeviceFinder.runnable: done udpSocket.receive");
+
+ final byte[] rxbuffer = p.getData();
+ appendToLog("DeviceFinder.runnable: with received " + (rxbuffer == null ? "null data" : ("data length as " + rxbuffer.length)));
+
+ readerSetting = decodeSearchReply(sbuffer, rxbuffer);
+ if (readerSetting != null) {
+ BluetoothGatt.CsScanData scanResultA = new BluetoothGatt.CsScanData(null, 0, readerSetting.rxbuffer1);
+ StringBuilder sb = new StringBuilder(300);
+ for (int k = 0; k < readerSetting.mac.length; k++) {
+ if (k != 0) sb.append(":");
+ sb.append(String.format("%02X", readerSetting.mac[k]));
+ }
+ sb.append(" ");
+ for (int k = 0; k < readerSetting.ip.length; k++) {
+ if (k != 0) sb.append(".");
+ sb.append(String.valueOf(readerSetting.ip[k] & 0xFF));
+ }
+ scanResultA.address = sb.toString();
+ appendToLog("DeviceFinder.runnable: scanResultA.address is " + scanResultA.address);
+
+ sb = new StringBuilder(100);
+ for (int k = 0; k < 4; k++) {
+ if (readerSetting.device_name[k] != null) {
+ if (k != 0) sb.append(", ");
+ sb.append(readerSetting.device_name[k]);
+ }
+ }
+ scanResultA.name = sb.toString();
+ appendToLog("DeviceFinder.runnable: scanResultA.name is " + scanResultA.name);
+ scanResultA.serviceUUID2p2 = 4;
+
+ if (csReaderConnector.mScanResultList != null) {
+ csReaderConnector.mScanResultList.add(scanResultA);
+ //appendToLog("DeviceFinder.runnable: scanResultA.getAddress is " + csReaderConnector.mScanResultList.get(0).getAddress());
+ }
+ }
+ } //3040 UdpSearch
+ if (false && readerSetting != null) {
+ sbuffer = getBytesUdpAssignment(readerSetting);
+
+ address = InetAddress.getByAddress(readerSetting.ip);
+ portnum = 3040;
+ appendToLog("DeviceFinder.runnable: done InetAddress.getByName with ip as " + utility.byteArrayToString(readerSetting.ip) + ", port as " + portnum);
+ packet = new DatagramPacket(sbuffer, sbuffer.length, address, portnum);
+
+ udpSocket.send(packet);
+ appendToLog("DeviceFinder.runnable: done udpSocket.send with sent data as " + utility.byteArrayToString(sbuffer));
+
+ p = new DatagramPacket(message, message.length);
+ udpSocket.receive(p); //keeps on waiting here but i am sending data back from server, but it never receives
+ appendToLog("DeviceFinder.runnable: done udpSocket.receive");
+
+ final byte[] rxbuffer = p.getData(); //exception here as java.net.SocketTimeoutException: Poll timed out
+ appendToLog("DeviceFinder.runnable: with received " + (rxbuffer == null ? "null data" : ("data length as " + rxbuffer.length)));
+
+ if (decodeAssignmentReply(sbuffer, rxbuffer)) appendToLog("DeviceFinder.runnable: decodeAssignmentReply is Okay");
+ else appendToLog("DeviceFinder.runnable: decodeAssignmentReply is invalid");
+ } //3040 UdpAssignment -- no reply
+ if (false && readerSetting != null) {
+ sbuffer = getBytesUdpControl(readerSetting.ip, UpdControlCommands.CheckStatus);
+
+ address = InetAddress.getByAddress(readerSetting.ip);
+ portnum = 3041;
+ appendToLog("DeviceFinder.runnable: done InetAddress.getByName with ip as " + utility.byteArrayToString(readerSetting.ip) + ", port as " + portnum);
+ packet = new DatagramPacket(sbuffer, sbuffer.length, address, portnum);
+
+ udpSocket.send(packet);
+ appendToLog("DeviceFinder.runnable: done udpSocket.send with sent data as " + utility.byteArrayToString(sbuffer));
+
+ p = new DatagramPacket(message, message.length);
+ udpSocket.receive(p); //keeps on waiting here but i am sending data back from server, but it never receives
+ appendToLog("DeviceFinder.runnable: done udpSocket.receive");
+
+ final byte[] rxbuffer2 = p.getData(); //exception here as java.net.SocketTimeoutException: Poll timed out
+ appendToLog("DeviceFinder.runnable: with received " + (rxbuffer2 == null ? "null data" : ("data length as " + rxbuffer2.length)));
+
+ if (decodeUdpControlReply(sbuffer, rxbuffer2)) appendToLog("DeviceFinder.runnable: decodeUdpControlReply is Okay");
+ else appendToLog("DeviceFinder.runnable: decodeUdpControlReply is invalid");
+ } //3041 UdpControl CheckStatus
+ if (false && readerSetting != null) {
+ sbuffer = getBytesUdpControl(readerSetting.ip, UpdControlCommands.GetBootloaderVersion);
+
+ address = InetAddress.getByAddress(readerSetting.ip);
+ portnum = 3041;
+ appendToLog("DeviceFinder.runnable: done InetAddress.getByName with ip as " + utility.byteArrayToString(readerSetting.ip) + ", port as " + portnum);
+ packet = new DatagramPacket(sbuffer, sbuffer.length, address, portnum);
+
+ udpSocket.send(packet);
+ appendToLog("DeviceFinder.runnable: done udpSocket.send with sent data as " + utility.byteArrayToString(sbuffer));
+
+ p = new DatagramPacket(message, message.length);
+ udpSocket.receive(p); //keeps on waiting here but i am sending data back from server, but it never receives
+ appendToLog("DeviceFinder.runnable: done udpSocket.receive");
+
+ final byte[] rxbuffer2 = p.getData(); //exception here as java.net.SocketTimeoutException: Poll timed out
+ appendToLog("DeviceFinder.runnable: with received " + (rxbuffer2 == null ? "null data" : ("data length as " + rxbuffer2.length)));
+
+ if (decodeUdpControlReply(sbuffer, rxbuffer2)) appendToLog("DeviceFinder.runnable: decodeUdpControlReply is Okay");
+ else appendToLog("DeviceFinder.runnable: decodeUdpControlReply is invalid");
+ } //3041 UdpControl GetBootloaderVersion
+ if (false && readerSetting != null) {
+ sbuffer = getBytesUdpControl(readerSetting.ip, UpdControlCommands.GetImageVersion);
+
+ address = InetAddress.getByAddress(readerSetting.ip);
+ portnum = 3041;
+ appendToLog("DeviceFinder.runnable: done InetAddress.getByName with ip as " + utility.byteArrayToString(readerSetting.ip) + ", port as " + portnum);
+ packet = new DatagramPacket(sbuffer, sbuffer.length, address, portnum);
+
+ udpSocket.send(packet);
+ appendToLog("DeviceFinder.runnable: done udpSocket.send with sent data as " + utility.byteArrayToString(sbuffer));
+
+ p = new DatagramPacket(message, message.length);
+ udpSocket.receive(p); //keeps on waiting here but i am sending data back from server, but it never receives
+ appendToLog("DeviceFinder.runnable: done udpSocket.receive");
+
+ final byte[] rxbuffer2 = p.getData(); //exception here as java.net.SocketTimeoutException: Poll timed out
+ appendToLog("DeviceFinder.runnable: with received " + (rxbuffer2 == null ? "null data" : ("data length as " + rxbuffer2.length)));
+
+ if (decodeUdpControlReply(sbuffer, rxbuffer2)) appendToLog("DeviceFinder.runnable: decodeUdpControlReply is Okay");
+ else appendToLog("DeviceFinder.runnable: decodeUdpControlReply is invalid");
+ } //3041 UdpControl GetImageVersion
+ } catch (Exception ex) {
+ appendToLog("DeviceFinder.runnable upd exception as " + ex.toString());
+ }
+ if (udpSocket != null && !udpSocket.isClosed()) {
+ udpSocket.close();
+ appendToLog("DeviceFinder.runnable: done udpSocket.close");
+ }
+
+ if (false && readerSetting != null) {
+ String stringIp = String.format("%d.%d.%d.%d", (readerSetting.ip[0] & 0xFF),
+ (readerSetting.ip[1] & 0xFF), (readerSetting.ip[2] & 0xFF), (readerSetting.ip[3] & 0xFF));
+ appendToLog("DeviceFinder.runnable: stringIp is " + stringIp);
+ byte[] data = null; InputStream input = null; byte[] dataIn = null; int iValue;
+ try {
+ tcpSocket = new Socket(stringIp, 1515);
+ appendToLog("DeviceFinder.runnable: done new Socket with Ip " + stringIp + " and port 1515");
+ OutputStream output = tcpSocket.getOutputStream();
+ appendToLog("DeviceFinder.runnable: done socket.getOutputStream");
+
+ if (true) {
+ data = getBytesTcpReader(TcpReaderCommands.Reset);
+ output.write(data);
+ appendToLog("DeviceFinder.runnable: done outputStream.write with sent data as " + utility.byteArrayToString(data));
+
+ input = tcpSocket.getInputStream();
+ appendToLog("DeviceFinder.runnable: done socket.getInputStream");
+
+ dataIn = new byte[64];
+ iValue = input.read(dataIn);
+ appendToLog("DeviceFinder.runnable: done inputStream.read with output value as " + iValue);
+ if (iValue > 0) {
+ byte[] dataIn1 = new byte[iValue];
+ System.arraycopy(dataIn, 0, dataIn1, 0, dataIn1.length);
+ appendToLog("DeviceFinder.runnable: with data as " + utility.byteArrayToString(dataIn1));
+ }
+ } //1515 TcpReaderCommand.Reset
+ if (false) {
+ data = getBytesTcpReader(TcpReaderCommands.WriteCommandClearError);
+ output.write(data);
+ appendToLog("DeviceFinder.runnable: done outputStream.write with data as " + utility.byteArrayToString(data));
+
+ input = tcpSocket.getInputStream();
+ appendToLog("DeviceFinder.runnable: done socket.getInputStream");
+
+ dataIn = new byte[64];
+ iValue = input.read(dataIn);
+ appendToLog("DeviceFinder.runnable: done inputStream.read with output value as " + iValue);
+ if (iValue > 0) {
+ byte[] dataIn1 = new byte[iValue];
+ System.arraycopy(dataIn, 0, dataIn1, 0, dataIn1.length);
+ appendToLog("DeviceFinder.runnable: with data as " + utility.byteArrayToString(dataIn1));
+ }
+ } //1515 TcpReaderCommandClearError
+ if (false) {
+ data = getBytesTcpReader(TcpReaderCommands.WriteOemAddress);
+ output.write(data);
+ appendToLog("DeviceFinder.runnable: done outputStream.write with data as " + utility.byteArrayToString(data));
+ data = getBytesTcpReader(TcpReaderCommands.WriteCommandOemRead);
+ output.write(data);
+ appendToLog("DeviceFinder.runnable: done outputStream.write with data as " + utility.byteArrayToString(data));
+
+ input = tcpSocket.getInputStream();
+ appendToLog("DeviceFinder.runnable: done socket.getInputStream");
+
+ dataIn = new byte[64];
+ iValue = input.read(dataIn);
+ appendToLog("DeviceFinder.runnable: done inputStream.read with output value as " + iValue);
+ if (iValue > 0) {
+ byte[] dataIn1 = new byte[iValue];
+ System.arraycopy(dataIn, 0, dataIn1, 0, dataIn1.length);
+ appendToLog("DeviceFinder.runnable: with data as " + utility.byteArrayToString(dataIn1));
+ }
+ } //1515 TcpReaderCommandWriteOemAddress, WriteCommandOemRead
+ if (false) {
+ data = getBytesTcpReader(TcpReaderCommands.ReadMac705);
+ output.write(data);
+ appendToLog("DeviceFinder.runnable: done outputStream.write with data as " + utility.byteArrayToString(data));
+
+ input = tcpSocket.getInputStream();
+ appendToLog("DeviceFinder.runnable: done socket.getInputStream");
+
+ dataIn = new byte[64];
+ iValue = input.read(dataIn);
+ appendToLog("DeviceFinder.runnable: done inputStream.read with output value as " + iValue);
+ if (iValue > 0) {
+ byte[] dataIn1 = new byte[iValue];
+ System.arraycopy(dataIn, 0, dataIn1, 0, dataIn1.length);
+ appendToLog("DeviceFinder.runnable: with data as " + utility.byteArrayToString(dataIn1));
+ }
+ } //1515 TcpReaderCommandReadMac705
+ } catch (Exception ex) {
+ appendToLog("DeviceFinder.runnable tcp exception as " + ex.toString());
+ }
+ if (tcpSocket != null && !tcpSocket.isClosed()) {
+ try {
+ tcpSocket.close();
+ appendToLog("DeviceFinder.runnable: done tcpSocket.close");
+ } catch (Exception ex) {
+ appendToLog("DeviceFinder.runnable tcp exception as " + ex.toString());
+ }
+ }
+
+ if (false) {
+ try {
+ tcpSocket = new Socket(stringIp, 1516); //failed to connect with port 1516
+ appendToLog("DeviceFinder.runnable: done new Socket with Ip " + stringIp + " and port 1515");
+ OutputStream output = tcpSocket.getOutputStream();
+ appendToLog("DeviceFinder.runnable: done socket.getOutputStream");
+
+ if (true) {
+ data = getBytesTcpControl();
+ output.write(data);
+ appendToLog("DeviceFinder.runnable: done outputStream.write with data as " + utility.byteArrayToString(data));
+
+ input = tcpSocket.getInputStream();
+ appendToLog("DeviceFinder.runnable: done socket.getInputStream");
+
+ dataIn = new byte[64];
+ iValue = input.read(dataIn);
+ appendToLog("DeviceFinder.runnable: done inputStream.read with output value as " + iValue);
+ if (iValue > 0) {
+ byte[] dataIn1 = new byte[iValue];
+ System.arraycopy(dataIn, 0, dataIn1, 0, dataIn1.length);
+ appendToLog("DeviceFinder.runnable: with data as " + utility.byteArrayToString(dataIn1));
+ }
+ } //1516 TcpControlCommand -- failed to connect with port 1516
+ } catch (Exception ex) {
+ appendToLog("DeviceFinder.runnable tcp exception as " + ex.toString());
+ }
+ if (tcpSocket != null && !tcpSocket.isClosed()) {
+ try {
+ tcpSocket.close();
+ appendToLog("DeviceFinder.runnable: done tcpSocket.close");
+ } catch (Exception ex) {
+ appendToLog("DeviceFinder.runnable tcp exception as " + ex.toString());
+ }
+ }
+ } //1516 TcpCommand -- failed to connect with port 1516
+ }
+ }
+ };
+
+ static class ReaderSetting {
+ byte[] rxbuffer1 = null;
+ byte mode; //for search only
+ byte connection_mode; //for search only
+ byte dhcp_retry; //for search only
+ //byte[] device_name1, device_name2, device_name3; //for Search only
+ byte[] ip = new byte[4]; //
+ byte[] trusted_host_ip = new byte[4]; //
+ byte tcp_timeout;
+ byte ip_mode; //
+ byte[] mac = new byte[6]; //
+ byte trusted_host_mode; //
+ //byte[] device_name = new byte[32]; //
+ String[] device_name = new String[4];
+ byte[] subnet = new byte[4]; //
+ byte[] gateway = new byte[4]; //
+ byte gateway_check; //
+ }
+ byte[] getBytesUdpSearch() {
+ Random randomNumber = new Random();
+ byte[] sbuffer = new byte[4];
+ randomNumber.nextBytes(sbuffer);
+ sbuffer[0] = 0;
+ sbuffer[1] = 0;
+ return sbuffer;
+ }
+ ReaderSetting decodeSearchReply(byte[] sbuffer, byte[] rxbuffer) {
+ boolean DEBUG = false;
+ ReaderSetting readerSetting = null;
+ boolean bValue = false;
+ int iLengthMin = 45;
+ int iNull = 0, index = 40, i = index;
+ if (rxbuffer != null && rxbuffer.length >= iLengthMin) {
+ if (rxbuffer[0] == 1 && rxbuffer[1] == 0 && rxbuffer[2] == sbuffer[2] && rxbuffer[3] == sbuffer[3]) {
+ for (; i < rxbuffer.length; i++) {
+ if (rxbuffer[i] == 0) {
+ if (DEBUG) appendToLog("DeviceFinder.decodeSearchReply: i = " + i);
+ if (++iNull == 4) break;
+ }
+ }
+ if (iNull == 4 && rxbuffer.length > i) bValue = true;
+ }
+ }
+ if (bValue) {
+ byte[] rxbuffer1 = new byte[i + 2];
+ System.arraycopy(rxbuffer, 0, rxbuffer1, 0, rxbuffer1.length);
+
+ readerSetting = new ReaderSetting();
+
+ readerSetting.rxbuffer1 = rxbuffer1;
+ appendToLog("DeviceFinder.decodeSearchReply: " + rxbuffer1.length + " data received " + utility.byteArrayToString(rxbuffer1));
+
+ readerSetting.mode = rxbuffer1[1];
+
+ System.arraycopy(rxbuffer1, 14, readerSetting.mac, 0, readerSetting.mac.length);
+ if (DEBUG) appendToLog("DeviceFinder.decodeSearchReply: mac address is " + utility.byteArrayToString(readerSetting.mac));
+
+ System.arraycopy(rxbuffer1, 20, readerSetting.ip, 0, readerSetting.ip.length);
+ if (DEBUG) appendToLog("DeviceFinder.decodeSearchReply: ip address is " + utility.byteArrayToString(readerSetting.ip));
+
+ System.arraycopy(rxbuffer1, 4, readerSetting.trusted_host_ip, 0, readerSetting.trusted_host_ip.length);
+ readerSetting.trusted_host_mode = rxbuffer1[28];
+ readerSetting.connection_mode = rxbuffer1[29];
+ readerSetting.dhcp_retry = rxbuffer1[30];
+ readerSetting.ip_mode = rxbuffer1[31];
+ System.arraycopy(rxbuffer1, 32, readerSetting.subnet, 0, readerSetting.ip.length);
+ System.arraycopy(rxbuffer1, 36, readerSetting.gateway, 0, readerSetting.ip.length);
+
+ i = index;
+ int indexString = 0;
+ for (; i < rxbuffer1.length; i++) {
+ if (rxbuffer1[i] == 0) {
+ if (i > index) {
+ byte[] bytesName = new byte[i - index];
+ System.arraycopy(rxbuffer1, index, bytesName, 0, bytesName.length);
+ if (DEBUG) appendToLog("DeviceFinder.decodeSearchReply: name is " + utility.byteArrayToString(bytesName) + " " + new String(bytesName, StandardCharsets.UTF_8));
+ readerSetting.device_name[indexString++] = new String(bytesName, StandardCharsets.UTF_8);
+ }
+ if (++iNull == 4) break;
+ index = i + 1;
+ }
+ }
+ readerSetting.gateway_check = rxbuffer1[rxbuffer1.length-1];
+ }
+ return readerSetting;
+ }
+ byte[] getBytesUdpAssignment(ReaderSetting readerSetting) {
+ Random randomNumber = new Random();
+ byte[] sbuffer = new byte[65];
+ sbuffer[0] = 2; sbuffer[1] = 0;
+
+ byte[] sbuffer1 = new byte[2];
+ randomNumber.nextBytes(sbuffer1);
+ System.arraycopy(sbuffer1, 0, sbuffer, 2, sbuffer1.length);
+ System.arraycopy(readerSetting.ip, 0, sbuffer, 4, readerSetting.ip.length);
+ System.arraycopy(readerSetting.trusted_host_ip, 0, sbuffer, 8, readerSetting.trusted_host_ip.length);
+ sbuffer[14] = readerSetting.tcp_timeout;
+ sbuffer[15] = readerSetting.ip_mode;
+ System.arraycopy(readerSetting.mac, 0, sbuffer, 16, readerSetting.mac.length);
+ sbuffer[22] = readerSetting.trusted_host_mode;
+ byte[] deviceName = readerSetting.device_name[0].getBytes();
+ int length = deviceName.length;
+ if (length > 32) length = 32;
+ System.arraycopy(deviceName, 0, sbuffer, 24, length);
+ System.arraycopy(readerSetting.subnet, 0, sbuffer, 56, readerSetting.subnet.length);
+ System.arraycopy(readerSetting.gateway, 0, sbuffer, 60, readerSetting.gateway.length);
+ sbuffer[64] = readerSetting.gateway_check;
+ return sbuffer;
+ }
+ boolean decodeAssignmentReply(byte[] sbuffer, byte[] rxbuffer) {
+ boolean bValue = false;;
+ if (rxbuffer != null && rxbuffer.length >= 4) {
+ if (rxbuffer[0] == 3 && rxbuffer[1] == 0 && rxbuffer[2] == sbuffer[2] && rxbuffer[3] == sbuffer[3]) {
+ bValue = true;
+ }
+ }
+ return bValue;
+ }
+ byte[] getBytesUdpControl(byte[] ip, UpdControlCommands updControlCommands) {
+ byte[] bytes = new byte[7];
+ int length = ip.length;
+ appendToLog("DeviceFinder length is " + length);
+ if (length == 4) {
+ bytes[0] = (byte) 0x80;
+ System.arraycopy(ip, 0, bytes, 1, length);
+ bytes[5] = 0;
+ if (updControlCommands == UpdControlCommands.CheckStatus) bytes[6] = 1;
+ else if (updControlCommands == UpdControlCommands.GetBootloaderVersion) bytes[6] = 0x15;
+ else if (updControlCommands == UpdControlCommands.GetImageVersion) bytes[6] = 0x16;
+ } else bytes = null;
+ return bytes;
+ }
+ public enum UpdControlCommands { CheckStatus, GetBootloaderVersion, GetImageVersion }
+ boolean decodeUdpControlReply(byte[] sBuffer, byte[] rxbufferRaw) {
+ boolean bValue = false;
+ byte[] rxbuffer = new byte[4 + rxbufferRaw[2]];
+ System.arraycopy(rxbufferRaw, 0, rxbuffer, 0, rxbuffer.length);
+ appendToLog("DeviceFinder.decodeUdpControlReply: data received as " + utility.byteArrayToString(rxbuffer));
+ if (rxbuffer[0] == (byte) 0x81 && rxbuffer[3] == sBuffer[6]) {
+ if (rxbuffer[1] == 1) bValue = true;
+ }
+ return bValue;
+ }
+ enum TcpReaderCommands { Reset, WriteCommandClearError, WriteOemAddress, WriteCommandOemRead, ReadMac705 }
+ byte[] getBytesTcpReader(TcpReaderCommands tcpReaderCommands) {
+ byte[] bytes = null;
+ if (tcpReaderCommands == TcpReaderCommands.Reset) bytes = new byte[] { 0x40, 0x03, 0, 0, 0, 0, 0, 0 };
+ else if (tcpReaderCommands == TcpReaderCommands.WriteCommandClearError) bytes = new byte[] { 1, 0, 0, (byte) 0xf0, 0x15, 0, 0, 0 };
+ else if (tcpReaderCommands == TcpReaderCommands.WriteOemAddress) bytes = new byte[] { 1, 0, 0, 5, (byte) 0xA4, 0, 0, 0 };
+ else if (tcpReaderCommands == TcpReaderCommands.WriteCommandOemRead) bytes = new byte[] { 1, 0, 0, (byte) 0xf0, 3, 0, 0, 0 };
+ else if (tcpReaderCommands == TcpReaderCommands.ReadMac705) bytes = new byte[] { 0, 0, 0x05, 0x07, 0, 0, 0, 0 };
+ return bytes;
+ }
+ byte[] getBytesTcpControl() {
+ return new byte[] { (byte) 0x80, 0, 0, 0x12 };
+ }
+
+ boolean deviceFinderConnectState = false;
+ boolean connect(ReaderDevice readerDevice) {
+ boolean DEBUG = true, bValue = true;
+ if (DEBUG) appendToLog("DeviceFinder.connect: readerDevice is " + (readerDevice == null ? "null" : "valid"));
+ if (readerDevice == null) {
+ bValue = false;
+ if (DEBUG) appendToLog("DeviceFinder.connect with NULL readerDevice");
+ } else deviceFinderConnectState = true;
+ return bValue;
+ }
+ //============ utility ============
+ public void appendToLog(String s) {
+ utility.appendToLog(s);
+ }
+}
+
+
+
+package com.csl.cslibrary4a;
+
+import android.content.Context;
+import android.widget.Toast;
+
+import java.util.ArrayList;
+
+public class NotificationConnector {
+ boolean DEBUG_PKDATA;
+ boolean userDebugEnableDefault = false, userDebugEnable = userDebugEnableDefault;
+ public int mVoltageValue;
+ public int mVoltageCount;
+ public boolean triggerButtonStatus; public int iTriggerCount;
+ String stringVersion;
+ public enum NotificationPayloadEvents {
+ NOTIFICATION_GET_BATTERY_VOLTAGE, NOTIFICATION_GET_TRIGGER_STATUS,
+ NOTIFICATION_AUTO_BATTERY_VOLTAGE, NOTIFICATION_STOPAUTO_BATTERY_VOLTAGE,
+ NOTIFICATION_AUTO_RFIDINV_ABORT, NOTIFICATION_GET_AUTO_RFIDINV_ABORT,
+ NOTIFICATION_AUTO_BARINV_STARTSTOP, NOTIFICATION_GET_AUTO_BARINV_STARTSTOP,
+ NOTIFICATION_AUTO_TRIGGER_REPORT, NOTIFICATION_STOP_TRIGGER_REPORT,
+
+ NOTIFICATION_BATTERY_FAILED, NOTIFICATION_BATTERY_ERROR,
+ NOTIFICATION_TRIGGER_PUSHED, NOTIFICATION_TRIGGER_RELEASED
+ }
+ public class CsReaderNotificationData {
+ public NotificationPayloadEvents notificationPayloadEvent;
+ public byte[] dataValues;
+ }
+
+ public interface NotificationListener { void onChange(); }
+
+ NotificationListener listener;
+ public void setNotificationListener0(NotificationListener listener) { this.listener = listener; }
+
+ //NotificationListener getListener() { return listener; }
+ boolean mTriggerStatus;
+ public boolean getTriggerStatus() { return mTriggerStatus; }
+ void setTriggerStatus(boolean mTriggerStatus) {
+ if (this.mTriggerStatus != mTriggerStatus) {
+ this.mTriggerStatus = mTriggerStatus;
+ if (listener != null) listener.onChange();
+ }
+ }
+
+ boolean autoRfidAbortStatus = true, autoRfidAbortStatusUpdate = false;
+ boolean getAutoRfidAbortStatus() {
+ if (!autoRfidAbortStatusUpdate) {
+ CsReaderNotificationData csReaderNotificationData = new CsReaderNotificationData();
+ csReaderNotificationData.notificationPayloadEvent = NotificationPayloadEvents.NOTIFICATION_GET_AUTO_RFIDINV_ABORT;
+ notificationToWrite.add(csReaderNotificationData); if (true) appendToLog("notificationToWrite is added with length = " + notificationToWrite.size());
+ if (DEBUG_PKDATA) appendToLog("PkData: add NOTIFICATION_GET_AUTO_RFIDINV_ABORT to mNotificationToWrite with length = " + notificationToWrite.size());
+ }
+ return autoRfidAbortStatus;
+ }
+ void setAutoRfidAbortStatus(boolean mAutoRfidAbortStatus) { this.autoRfidAbortStatus = mAutoRfidAbortStatus; autoRfidAbortStatusUpdate = true; }
+
+ boolean mAutoBarStartStopStatus = false, mAutoBarStartStopStatusUpdated = false;
+ public boolean getAutoBarStartStopStatus() {
+ if (mAutoBarStartStopStatusUpdated == false) {
+ CsReaderNotificationData csReaderNotificationData = new CsReaderNotificationData();
+ csReaderNotificationData.notificationPayloadEvent = NotificationPayloadEvents.NOTIFICATION_GET_AUTO_BARINV_STARTSTOP;
+ notificationToWrite.add(csReaderNotificationData); if (true) appendToLog("notificationToWrite is added with length = " + notificationToWrite.size());
+ if (DEBUG_PKDATA) appendToLog("PkData: add NOTIFICATION_GET_AUTO_BARINV_STARTSTOP to mNotificationToWrite with length = " + notificationToWrite.size());
+ }
+ return mAutoBarStartStopStatus;
+ }
+ void setAutoBarStartStopStatus(boolean mAutoBarStartStopStatus) { this.mAutoBarStartStopStatus = mAutoBarStartStopStatus; mAutoBarStartStopStatusUpdated = true; }
+
+ public ArrayList notificationToWrite = new ArrayList<>();
+ public ArrayList notificationToRead = new ArrayList<>();
+
+ private boolean arrayTypeSet(byte[] dataBuf, int pos, NotificationPayloadEvents event) {
+ boolean validEvent = false;
+ switch (event) {
+ case NOTIFICATION_GET_BATTERY_VOLTAGE:
+ validEvent = true;
+ break;
+ case NOTIFICATION_GET_TRIGGER_STATUS:
+ dataBuf[pos] = 1;
+ validEvent = true;
+ break;
+ case NOTIFICATION_AUTO_BATTERY_VOLTAGE:
+ //if (false && checkHostProcessorVersion(controllerConnector.getVersion(), 0, 0, 2) == false) {
+ // validEvent = false;
+ //} else {
+ dataBuf[pos] = 2;
+ validEvent = true;
+ //}
+ break;
+ case NOTIFICATION_STOPAUTO_BATTERY_VOLTAGE:
+ //if (false && checkHostProcessorVersion(controllerConnector.getVersion(), 0, 0, 1) == false) {
+ // validEvent = false;
+ //} else {
+ dataBuf[pos] = 3;
+ validEvent = true;
+ //}
+ break;
+ case NOTIFICATION_AUTO_RFIDINV_ABORT:
+ //if (false && checkHostProcessorVersion(bluetoothConnector.getBluetoothIcVersion(), 0, 0, 13) == false) {
+ // validEvent = false;
+ //} else {
+ dataBuf[pos] = 4;
+ validEvent = true;
+ //}
+ break;
+ case NOTIFICATION_GET_AUTO_RFIDINV_ABORT:
+ //if (false && checkHostProcessorVersion(bluetoothConnector.getBluetoothIcVersion(), 1, 0, 13) == false) {
+ // validEvent = false;
+ //} else {
+ dataBuf[pos] = 5;
+ validEvent = true;
+ //}
+ break;
+ case NOTIFICATION_AUTO_BARINV_STARTSTOP:
+ //if (false && checkHostProcessorVersion(bluetoothConnector.getBluetoothIcVersion(), 1, 0, 14) == false) {
+ // validEvent = false;
+ //} else {
+ dataBuf[pos] = 6;
+ validEvent = true;
+ //}
+ break;
+ case NOTIFICATION_GET_AUTO_BARINV_STARTSTOP:
+ //if (false && checkHostProcessorVersion(bluetoothConnector.getBluetoothIcVersion(), 1, 0, 14) == false) {
+ // validEvent = false;
+ //} else {
+ dataBuf[pos] = 7;
+ validEvent = true;
+ //}
+ break;
+ case NOTIFICATION_AUTO_TRIGGER_REPORT:
+ //if (false && checkHostProcessorVersion(controllerConnector.getVersion(), 1, 0, 16) == false) {
+ // validEvent = false;
+ //} else {
+ dataBuf[pos] = 8;
+ validEvent = true;
+ //}
+ break;
+ case NOTIFICATION_STOP_TRIGGER_REPORT:
+ //if (false && checkHostProcessorVersion(controllerConnector.getVersion(), 1, 0, 16) == false) {
+ // validEvent = false;
+ //} else {
+ dataBuf[pos] = 9;
+ validEvent = true;
+ //}
+ break;
+ }
+ return validEvent;
+ }
+
+ private byte[] writeNotification(CsReaderNotificationData data, boolean usbConnection) {
+ int datalength = 0; boolean DEBUG = true;
+ if (data.dataValues != null) datalength = data.dataValues.length;
+ byte[] dataOutRef = new byte[]{(byte) 0xA7, (byte) 0xB3, 2, (byte) 0xD9, (byte) 0x82, (byte) 0x37, 0, 0, (byte) 0xA0, 0};
+ if (usbConnection) dataOutRef[1] = (byte) 0xE6;
+ byte[] dataOut = new byte[10 + datalength];
+ if (DEBUG) appendToLog("event = " + data.notificationPayloadEvent.toString() + ", with datalength = " + datalength);
+ if (datalength != 0) {
+ System.arraycopy(data.dataValues, 0, dataOut, 10, datalength);
+ dataOutRef[2] += datalength;
+ }
+ System.arraycopy(dataOutRef, 0, dataOut, 0, dataOutRef.length);
+ if (arrayTypeSet(dataOut, 9, data.notificationPayloadEvent)) {
+ if (DEBUG_PKDATA) appendToLog(String.format("PkData: write mNotificationDevice.%s.%s with mNotificationDevice.sendDataToWriteSent = %d", data.notificationPayloadEvent.toString(), byteArrayToString(data.dataValues), sendDataToWriteSent));
+ if (DEBUG) appendToLogView("NOut: " + byteArrayToString(dataOut));
+ return dataOut;
+ }
+ return null;
+ }
+ public boolean isMatchNotificationToWrite(ConnectorData connectorData) {
+ boolean match = false;
+ if (notificationToWrite.size() != 0 && connectorData.dataValues[0] == (byte)0xA0) {
+ byte[] dataInCompare = new byte[]{(byte) 0xA0, 0};
+ if (arrayTypeSet(dataInCompare, 1, notificationToWrite.get(0).notificationPayloadEvent) && (connectorData.dataValues.length >= dataInCompare.length + 1)) {
+ if (match = compareArray(connectorData.dataValues, dataInCompare, dataInCompare.length)) {
+ boolean bprocessed = false;
+ byte[] data1 = new byte[connectorData.dataValues.length - 2]; System.arraycopy(connectorData.dataValues, 2, data1, 0, data1.length);
+ if (DEBUG_PKDATA) appendToLog("PkData: matched Notification.Reply with payload = " + byteArrayToString(connectorData.dataValues) + " for writeData Notification." + notificationToWrite.get(0).notificationPayloadEvent.toString());
+ if (notificationToWrite.get(0).notificationPayloadEvent == NotificationPayloadEvents.NOTIFICATION_GET_BATTERY_VOLTAGE) {
+ if (connectorData.dataValues.length >= dataInCompare.length + 2) {
+ mVoltageValue = (connectorData.dataValues[2] & 0xFF) * 256 + (connectorData.dataValues[3] & 0xFF);
+ mVoltageCount++;
+ bprocessed = true;
+ }
+ if (DEBUG_PKDATA) appendToLog("PkData: matched Notification.Reply.GetBatteryVoltage with result = " + String.format("%X", mVoltageValue));
+ } else if (notificationToWrite.get(0).notificationPayloadEvent == NotificationPayloadEvents.NOTIFICATION_GET_TRIGGER_STATUS) {
+ if (connectorData.dataValues[2] != 0) {
+ setTriggerStatus(true); //mTriggerStatus = true;
+ triggerButtonStatus = true;
+ } else {
+ setTriggerStatus(false); //mTriggerStatus = false;
+ triggerButtonStatus = false;
+ }
+ iTriggerCount++;
+ if (DEBUG_PKDATA) appendToLog("PkData: BARTRIGGER: isMatchNotificationToWrite finds trigger = " + getTriggerStatus());
+ bprocessed = true;
+ } else if (notificationToWrite.get(0).notificationPayloadEvent == NotificationPayloadEvents.NOTIFICATION_GET_AUTO_RFIDINV_ABORT) {
+ if (connectorData.dataValues[2] != 0) setAutoRfidAbortStatus(true);
+ else setAutoRfidAbortStatus(false);
+ if (DEBUG_PKDATA) appendToLog("PkData: matched Notification.Reply.GetAutoRfidinvAbort with result = " + connectorData.dataValues[2] + " and autoRfidAbortStatus = " + getAutoRfidAbortStatus());
+ bprocessed = true;
+ } else if (notificationToWrite.get(0).notificationPayloadEvent == NotificationPayloadEvents.NOTIFICATION_GET_AUTO_BARINV_STARTSTOP) {
+ if (connectorData.dataValues[2] != 0) setAutoBarStartStopStatus(true);
+ else setAutoBarStartStopStatus(false);
+ if (DEBUG_PKDATA) appendToLog("PkData: matched Notification.Reply.GetAutoBarinvStartstop with result = " + connectorData.dataValues[2] + " and " + getAutoBarStartStopStatus());
+ bprocessed = true;
+ } else {
+ bprocessed = true;
+ if (DEBUG_PKDATA) appendToLog("PkData: matched Notification.Reply." + notificationToWrite.get(0).notificationPayloadEvent.toString() + " with result = " + connectorData.dataValues[2]);
+ }
+ String string = "Up31 " + (bprocessed ? "" : "Unprocessed, ") + notificationToWrite.get(0).notificationPayloadEvent.toString() + ", " + byteArrayToString(data1);
+ utility.writeDebug2File(string);
+ appendToLog("Notification.isMatchNotificationToWrite: UsbConnector: going to notificationToWrite.remove[0] 1");
+ notificationToWrite.remove(0); sendDataToWriteSent = 0; if (false) appendToLog("notificationToWrite remove0 with length = " + notificationToWrite.size());
+ if (DEBUG_PKDATA) appendToLog("PkData: new mNotificationToWrite size = " + notificationToWrite.size());
+ }
+ }
+ }
+ return match;
+ }
+
+ public int sendDataToWriteSent = 0;
+ boolean notificationFailure = false;
+ public byte[] sendNotificationToWrite(boolean usbConnection) {
+ boolean DEBUG = false;
+ appendToLog("NotificationConnector.sendNotificationToWrite: starts");
+ if (notificationFailure) {
+ appendToLog("Notification.sendNotificationToWrite: UsbConnector: going to notificationToWrite.remove[0] 1");
+ notificationToWrite.remove(0); sendDataToWriteSent = 0; if (false) appendToLog("notificationToWrite remove0 with length = " + notificationToWrite.size());
+ } else if (sendDataToWriteSent >= 5) {
+ int oldSize = notificationToWrite.size();
+ CsReaderNotificationData csReaderNotificationData = notificationToWrite.get(0);
+ appendToLog("Notification.sendNotificationToWrite: UsbConnector: going to notificationToWrite.remove[0] 2");
+ notificationToWrite.remove(0); sendDataToWriteSent = 0; if (true) appendToLog("notificationToWrite remove0 with length = " + notificationToWrite.size());
+ if (DEBUG) appendToLog("Removed after sending count-out with oldSize = " + oldSize + ", updated mNotificationToWrite.size() = " + notificationToWrite.size());
+ if (DEBUG) appendToLog("Removed after sending count-out.");
+ String string = "Problem in sending data to Notification Module. Removed data sending after count-out";
+ if (userDebugEnable) Toast.makeText(context, string, Toast.LENGTH_SHORT).show();
+ else appendToLogView(string);
+ if (true) Toast.makeText(context, csReaderNotificationData.notificationPayloadEvent.toString(), Toast.LENGTH_LONG).show();
+ notificationFailure = true; // disconnect(false);
+ } else {
+ sendDataToWriteSent++;
+ return writeNotification(notificationToWrite.get(0), usbConnection);
+ }
+ return null;
+ }
+
+ long timeTriggerRelease;
+ public boolean isNotificationToRead(ConnectorData connectorData) {
+ boolean found = false, DEBUG = false;
+ CsReaderNotificationData csReaderNotificationData = new CsReaderNotificationData();
+ byte[] data1 = new byte[connectorData.dataValues.length - 2]; System.arraycopy(connectorData.dataValues, 2, data1, 0, data1.length);
+ if (connectorData.dataValues[0] == (byte) 0xA0 && connectorData.dataValues[1] == (byte) 0x00 && connectorData.dataValues.length >= 4) {
+ mVoltageValue = (connectorData.dataValues[2] & 0xFF) * 256 + (connectorData.dataValues[3] & 0xFF);
+ mVoltageCount++;
+ csReaderNotificationData.notificationPayloadEvent = NotificationPayloadEvents.NOTIFICATION_GET_BATTERY_VOLTAGE;
+ csReaderNotificationData.dataValues = data1;
+ if (false) notificationToRead.add(csReaderNotificationData);
+ if (DEBUG_PKDATA) appendToLog("PkData: found Notification.Uplink with payload = " + byteArrayToString(connectorData.dataValues));
+ if (DEBUG_PKDATA) appendToLog("PkData: Notification.Uplink.GetCurrentBattteryVoltage is processed as mVoltageValue = " + mVoltageValue + " and mVoltageCount = " + mVoltageCount);
+ found = true;
+ } else if (connectorData.dataValues[0] == (byte) 0xA0 && connectorData.dataValues[1] == (byte) 0x01 && connectorData.dataValues.length >= 3) {
+ if (connectorData.dataValues[2] == 0) triggerButtonStatus = false;
+ else triggerButtonStatus = true;
+ iTriggerCount++;
+ csReaderNotificationData.notificationPayloadEvent = NotificationPayloadEvents.NOTIFICATION_GET_TRIGGER_STATUS;
+ csReaderNotificationData.dataValues = data1;
+ if (DEBUG_PKDATA) appendToLog("PkData: found Notification.Uplink with payload = " + byteArrayToString(connectorData.dataValues));
+ if (DEBUG_PKDATA) appendToLog("PkData: Notification.Uplink.GetCurrentTriggerState is processed as triggerButtonStatus = " + triggerButtonStatus + " and iTriggerCount = " + iTriggerCount);
+ found = true;
+ } else if (connectorData.dataValues[0] == (byte) 0xA1) {
+ if (DEBUG_PKDATA) appendToLog("PkData: found Notification.Uplink with payload = " + byteArrayToString(connectorData.dataValues));
+ //Cs108NotificatiionData cs108NotificatiionData = new Cs108NotificatiionData();
+ switch (connectorData.dataValues[1]) {
+ case 0:
+ if (DEBUG) appendToLog("matched batteryFailed data is found.");
+ csReaderNotificationData.notificationPayloadEvent = NotificationPayloadEvents.NOTIFICATION_BATTERY_FAILED;
+ csReaderNotificationData.dataValues = null;
+ if (true) notificationToRead.add(csReaderNotificationData);
+ if (DEBUG_PKDATA) appendToLog("PkData: Notification.Uplink.Reserve is processed");
+ found = true;
+ break;
+ case 1:
+ if (DEBUG) appendToLog("matched Error data is found, " + byteArrayToString(connectorData.dataValues));
+ csReaderNotificationData.notificationPayloadEvent = NotificationPayloadEvents.NOTIFICATION_BATTERY_ERROR;
+ csReaderNotificationData.dataValues = data1;
+ if (true) notificationToRead.add(csReaderNotificationData);
+ //btSendTime = System.currentTimeMillis() - btSendTimeOut + 50;
+ if (DEBUG_PKDATA) appendToLog("PkData: Notification.Uplink.ErrorCode with value = " + byteArrayToString(data1) + " is addded to mNotificationToRead");
+ found = true;
+ break;
+ case 2:
+ csReaderNotificationData.notificationPayloadEvent = NotificationPayloadEvents.NOTIFICATION_TRIGGER_PUSHED;
+ csReaderNotificationData.dataValues = data1;
+ setTriggerStatus(true);
+ if (DEBUG) appendToLog("BARTRIGGER: isNotificationToRead finds trigger = " + getTriggerStatus());
+ if (false) notificationToRead.add(csReaderNotificationData);
+ if (DEBUG_PKDATA) appendToLog("PkData: Notification.Uplink.TriggerPushed is processed as trigger = " + getTriggerStatus());
+ found = true;
+ break;
+ case 3:
+ csReaderNotificationData.notificationPayloadEvent = NotificationPayloadEvents.NOTIFICATION_TRIGGER_RELEASED;
+ csReaderNotificationData.dataValues = data1;
+ setTriggerStatus(false);
+ if (DEBUG) appendToLog("BARTRIGGER: isNotificationToRead finds trigger = " + getTriggerStatus());
+ if (false) notificationToRead.add(csReaderNotificationData);
+ if (DEBUG_PKDATA) appendToLog("PkData: Notification.Uplink.TriggerReleased is processed as trigger = " + getTriggerStatus());
+ found = true;
+ break;
+ default:
+ appendToLog("Notification.Uplink with mis-matched result");
+ break;
+ }
+ }
+ if (DEBUG_PKDATA && found) appendToLog("found Notification.read data = " + byteArrayToString(connectorData.dataValues));
+ if (found) utility.writeDebug2File("Up32 " + csReaderNotificationData.notificationPayloadEvent.toString() + ", " + byteArrayToString(csReaderNotificationData.dataValues));
+ return found;
+ }
+ Context context; Utility utility; boolean triggerReporting; short triggerReportingCountSetting;
+ public NotificationConnector(Context context, Utility utility, boolean triggerReporting, short triggerReportingCountSetting) {
+ this.context = context;
+ this.utility = utility; DEBUG_PKDATA = utility.DEBUG_PKDATA;
+ this.triggerReporting = triggerReporting;
+ this.triggerReportingCountSetting = triggerReportingCountSetting;
+ }
+ private void appendToLog(String s) { utility.appendToLog(s); }
+ private String byteArrayToString(byte[] packet) { return utility.byteArrayToString(packet); }
+ private boolean compareArray(byte[] array1, byte[] array2, int length) { return utility.compareByteArray(array1, array2, length); }
+ private void appendToLogView(String s) { utility.appendToLogView(s); }
+ public boolean batteryLevelRequest() {
+ CsReaderNotificationData csReaderNotificationData = new CsReaderNotificationData();
+ csReaderNotificationData.notificationPayloadEvent = NotificationPayloadEvents.NOTIFICATION_GET_BATTERY_VOLTAGE;
+ boolean bValue = notificationToWrite.add(csReaderNotificationData); if (true) appendToLog("notificationToWrite is added with length = " + notificationToWrite.size());
+ if (DEBUG_PKDATA) appendToLog("PkData: add NOTIFICATION_GET_BATTERY_VOLTAGE to mNotificationToWrite with length = " + notificationToWrite.size());
+ return bValue;
+ }
+ public boolean triggerButtoneStatusRequest() {
+ CsReaderNotificationData csReaderNotificationData = new CsReaderNotificationData();
+ csReaderNotificationData.notificationPayloadEvent = NotificationPayloadEvents.NOTIFICATION_GET_TRIGGER_STATUS;
+ boolean bValue = notificationToWrite.add(csReaderNotificationData); if (true) appendToLog("notificationToWrite is added with length = " + notificationToWrite.size());
+ if (DEBUG_PKDATA) appendToLog("PkData: add NOTIFICATION_GET_TRIGGER_STATUS to mNotificationToWrite with length = " + notificationToWrite.size());
+ return bValue;
+ }
+ public boolean setBatteryAutoReport(boolean on) {
+ CsReaderNotificationData csReaderNotificationData = new CsReaderNotificationData();
+ csReaderNotificationData.notificationPayloadEvent = (on ? NotificationPayloadEvents.NOTIFICATION_AUTO_BATTERY_VOLTAGE: NotificationPayloadEvents.NOTIFICATION_STOPAUTO_BATTERY_VOLTAGE);
+ boolean bValue = notificationToWrite.add(csReaderNotificationData); appendToLog("notificationToWrite is added with length = " + notificationToWrite.size());
+ if (DEBUG_PKDATA) appendToLog("PkData: add " + csReaderNotificationData.notificationPayloadEvent.toString() + " to mNotificationToWrite with length = " + notificationToWrite.size());
+ return bValue;
+ }
+ public boolean setAutoRFIDAbort(boolean enable) {
+ if (false) appendToLog("BtDataOut: setAutoRFIDAbort with enable = " + enable + ", current autoRFIDAbort is " + autoRfidAbortStatus);
+ if (autoRfidAbortStatusUpdate) {
+ if ((enable && autoRfidAbortStatus) || (!enable && !autoRfidAbortStatus))
+ return true;
+ }
+ CsReaderNotificationData csReaderNotificationData = new CsReaderNotificationData();
+ csReaderNotificationData.notificationPayloadEvent = NotificationPayloadEvents.NOTIFICATION_AUTO_RFIDINV_ABORT;
+ csReaderNotificationData.dataValues = new byte[1];
+ setAutoRfidAbortStatus(enable);
+ csReaderNotificationData.dataValues[0] = (enable ? (byte)1 : 0);
+ boolean bValue = notificationToWrite.add(csReaderNotificationData); appendToLog("notificationToWrite is added with length = " + notificationToWrite.size());
+ if (DEBUG_PKDATA) appendToLog("PkData: add NOTIFICATION_AUTO_RFIDINV_ABORT." + byteArrayToString(csReaderNotificationData.dataValues) + " to mNotificationToWrite with length = " + notificationToWrite.size());
+ return bValue;
+ }
+ public boolean getAutoRFIDAbort() {
+ return getAutoRfidAbortStatus(); }
+
+ public boolean setAutoBarStartSTop(boolean enable) {
+ boolean autoBarStartStopStatus = getAutoBarStartSTop();
+ if (enable & autoBarStartStopStatus) return true;
+ else if (enable == false && autoBarStartStopStatus == false) return true;
+
+ CsReaderNotificationData csReaderNotificationData = new CsReaderNotificationData();
+ csReaderNotificationData.notificationPayloadEvent = NotificationPayloadEvents.NOTIFICATION_AUTO_BARINV_STARTSTOP;
+ csReaderNotificationData.dataValues = new byte[1];
+ setAutoBarStartStopStatus(enable);
+ csReaderNotificationData.dataValues[0] = (enable ? (byte)1 : 0);
+ boolean bValue = notificationToWrite.add(csReaderNotificationData); appendToLog("notificationToWrite is added with length = " + notificationToWrite.size());
+ if (DEBUG_PKDATA) appendToLog("PkData: add NOTIFICATION_AUTO_BARINV_STARTSTOP." + byteArrayToString(csReaderNotificationData.dataValues) + " to mNotificationToWrite with length = " + notificationToWrite.size());
+ return bValue;
+ }
+ public boolean getAutoBarStartSTop() { return getAutoBarStartStopStatus(); }
+
+ public boolean getTriggerReporting() { return triggerReporting; }
+ public boolean setTriggerReporting(boolean triggerReporting) {
+ boolean bValue = false;
+ appendToLog("FileA setTriggerReporting starts with triggerReporting as " + triggerReporting);
+ //if (this.triggerReporting == triggerReporting) return true;
+ if (triggerReporting) {
+ appendToLog("FileA going to setAutoTriggerReporting 3 with triggerReportingCountSetting as " + triggerReportingCountSetting);
+ byte byteWord = (byte) triggerReportingCountSetting;
+ appendToLog("FileA going to setAutoTriggerReporting 4 with byteWord as " + byteWord);
+ bValue = setAutoTriggerReporting(byteWord);
+ } else {
+ appendToLog("FileA going to stopAutoTriggerReporting 3");
+ bValue = stopAutoTriggerReporting();
+ }
+ if (bValue) this.triggerReporting = triggerReporting;
+ appendToLog("FileA setTriggerReporting ends");
+ return bValue;
+ }
+
+ public final int iNO_SUCH_SETTING = 10000;
+ //public short triggerReportingCountSettingDefault = 1;
+ //public short triggerReportingCountSetting = triggerReportingCountSettingDefault;
+ public short getTriggerReportingCount() {
+ //if (getcsModel() == 108) bValue = checkHostProcessorVersion(hostProcessorICGetFirmwareVersion(), 1, 0, 16);
+ //if (bValue == false) return iNO_SUCH_SETTING; else
+ return triggerReportingCountSetting;
+ }
+ public boolean setTriggerReportingCount(short triggerReportingCount) {
+ boolean bValue = false;
+ if (triggerReportingCount < 0 || triggerReportingCount > 255) return false;
+ if (getTriggerReporting()) {
+ if (triggerReportingCountSetting == triggerReportingCount) return true;
+ bValue = setAutoTriggerReporting((byte)(triggerReportingCount & 0xFF));
+ } else bValue = true;
+ if (bValue) triggerReportingCountSetting = triggerReportingCount;
+ return true;
+ }
+ byte timeSecondAutoTriggerReporting = 0;
+ public boolean setAutoTriggerReporting(byte timeSecond) {
+ boolean DEBUG = false;
+ if (DEBUG) appendToLog("NotificationConnector.setAutoTriggerReporting with checkVersion = " + checkVersion() + ", timeSecond = " + timeSecond);
+ if (!checkVersion()) return false;
+ if (timeSecond == timeSecondAutoTriggerReporting) {
+ if (DEBUG) appendToLog("NotificationConnector.setAutoTriggerReporting matched timeSecond");
+ return true;
+ }
+ CsReaderNotificationData csReaderNotificationData = new CsReaderNotificationData();
+ csReaderNotificationData.notificationPayloadEvent = NotificationPayloadEvents.NOTIFICATION_AUTO_TRIGGER_REPORT;
+ csReaderNotificationData.dataValues = new byte[1];
+ csReaderNotificationData.dataValues[0] = timeSecond;
+ boolean bValue = notificationToWrite.add(csReaderNotificationData); if (true) appendToLog("notificationToWrite is added with length = " + notificationToWrite.size());
+ if (bValue) timeSecondAutoTriggerReporting = timeSecond;
+ if (DEBUG_PKDATA) appendToLog("PkData: add NOTIFICATION_AUTO_TRIGGER_REPORT." + byteArrayToString(csReaderNotificationData.dataValues) + " to mNotificationToWrite with length = " + notificationToWrite.size());
+ return bValue;
+ }
+ public boolean stopAutoTriggerReporting() {
+ boolean DEBUG = false;
+ if (DEBUG) appendToLog("NotificationConnector.stopAutoTriggerReporting ***");
+ if (!checkVersion()) return false;
+ if (timeSecondAutoTriggerReporting == 0) {
+ if (DEBUG) appendToLog("NotificationConnector.setAutoTriggerReporting matched timeSecond");
+ return true;
+ }
+ CsReaderNotificationData csReaderNotificationData = new CsReaderNotificationData();
+ csReaderNotificationData.notificationPayloadEvent = NotificationPayloadEvents.NOTIFICATION_STOP_TRIGGER_REPORT;
+ boolean bValue = notificationToWrite.add(csReaderNotificationData); if (true) appendToLog("notificationToWrite is added with length = " + notificationToWrite.size());
+ if (bValue) timeSecondAutoTriggerReporting = 0;
+ if (DEBUG_PKDATA) appendToLog("PkData: add NOTIFICATION_STOP_TRIGGER_REPORT to mNotificationToWrite with length = " + notificationToWrite.size());
+ return bValue;
+ }
+ public void setVersion(String stringVersion) {
+ this.stringVersion = stringVersion;
+ }
+ boolean checkVersion() {
+ boolean DEBUG = true, bValue = false;
+ String stringCompare = "1.0.";
+ if (stringVersion == null) return true;
+ appendToLog("FileA setVersion with stringVersion as " + stringVersion + ", stringCompare as " + stringCompare);
+ int index = stringVersion.indexOf(stringCompare);
+ if (DEBUG) appendToLog("index = " + index);
+ if (index >= 0) {
+ if (DEBUG) appendToLog("substring = " + stringVersion.substring(index + stringCompare.length()));
+ if (Integer.parseInt(stringVersion.substring(index + stringCompare.length())) >= 16) bValue = true;
+ } else return true;
+ return bValue;
+ }
+}
+
+
+
+package com.csl.cslibrary4a;
+
+public class ReaderDevice implements Comparable {
+ private String name;
+ private String address; private String upcSerial;
+ boolean selected;
+ private String details;
+ int extra1Bank, extra2Bank, extra1Offset, extra2Offset;
+ String strPc, strXpc, strCrc16, strMdid, strExtra1, strExtra2;
+ private int count;
+ private double rssi;
+ private int serviceUUID2p1;
+ private int phase, channel, port;
+ public final int INVALID_STATUS = -1;
+ private int status = INVALID_STATUS;
+ public static final int INVALID_BACKPORT = -1, INVALID_CODESENSOR = -1, INVALID_CODERSSI = -1, INVALID_BRAND = -1, INVALID_SENSORDATA = 0x1000; public final float INVALID_CODETEMPC = -300;
+ private int backport1 = INVALID_BACKPORT, backport2 = INVALID_BACKPORT;
+ private int codeSensor = INVALID_CODESENSOR, codeSensorMax = INVALID_CODESENSOR, codeRssi = INVALID_CODERSSI, sensorData = INVALID_SENSORDATA; private float codeTempC = INVALID_CODETEMPC; private String brand;
+ private boolean isConnected;
+ private String timeOfRead, timeZone;
+ private String location;
+ private String compass;
+
+ public ReaderDevice(String name, String address, boolean selected, String details,
+ String strPc, String strXpc, String strCrc16, String strMdid,
+ String strExtra1, int extra1Bank, int extra1Offset,
+ String strExtra2, int extra2Bank, int extra2Offset,
+ String strTimeOfRead, String strTimeZone, String strLocation, String strCompass,
+ int count, double rssi, int phase, int channel, int port, int status, int backPort1, int backPort2, int codeSensor, int codeRssi, float codeTempC, String brand, int sensorData) {
+ this.name = name;
+ this.address = address;
+ this.selected = selected;
+ this.details = details;
+ this.strPc = strPc;
+ this.strXpc = strXpc;
+ this.strCrc16 = strCrc16;
+ this.strMdid = strMdid;
+ this.strExtra1 = strExtra1;
+ this.extra1Bank = extra1Bank;
+ this.extra1Offset = extra1Offset;
+ this.strExtra2 = strExtra2;
+ this.extra2Bank = extra2Bank;
+ this.extra2Offset = extra2Offset;
+
+ timeOfRead = strTimeOfRead;
+ timeZone = strTimeZone;
+ location = strLocation;
+ compass = strCompass;
+
+ this.count = count;
+ this.rssi = rssi;
+
+ this.phase = phase;
+ this.channel = channel;
+ this.port = port;
+ this.status = status;
+ this.backport1 = backPort1;
+ this.backport2 = backPort2;
+ this.codeSensor = codeSensor;
+ this.codeRssi = codeRssi;
+ this.codeTempC = codeTempC;
+ this.brand = brand;
+ this.sensorData = sensorData;
+ }
+
+ public ReaderDevice(String name, String address, boolean selected, String details, int count, double rssi, int serviceUUID2p1) {
+ this.name = name;
+ this.address = address;
+ this.selected = selected;
+ this.details = details;
+ this.count = count;
+ this.rssi = rssi;
+ this.serviceUUID2p1 = serviceUUID2p1;
+ }
+
+ public ReaderDevice(String name, String address, boolean selected, String details, int count, double rssi) {
+ this.name = name;
+ this.address = address;
+ this.selected = selected;
+ this.details = details;
+ this.count = count;
+ this.rssi = rssi;
+ }
+
+ public String getName() {
+ String strName = name;
+ if (strName != null) {
+ strName = strName.replaceAll("\\r|\\n", "");
+ strName = strName.trim();
+ }
+ return strName;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getAddress() { return address; }
+
+ public void setAddress(String address) {
+ this.address = address;
+ }
+
+ public String getUpcSerial() { return upcSerial; }
+
+ public void setUpcSerial(String upcSerial) {
+ this.upcSerial = upcSerial;
+ }
+
+ public boolean getSelected() {
+ return selected;
+ }
+
+ public void setSelected(boolean selected) {
+ this.selected = selected;
+ }
+
+ public String getDetails() {
+ if (details == null) {
+ String strDetail = "PC=" + strPc + ", CRC16=" + strCrc16; // + ", Port=" + String.valueOf(port+1);
+ if (strXpc != null) strDetail += "\nXPC=" + strXpc;
+ if (strExtra1 != null) {
+ String strHeader = null;
+ switch (extra1Bank) {
+ case 0:
+ strHeader = "RES";
+ break;
+ case 1:
+ strHeader = "EPC";
+ break;
+ case 2:
+ strHeader = "TID";
+ break;
+ case 3:
+ strHeader = "USER";
+ break;
+ }
+ if (strHeader != null)
+ strDetail += "\n" + strHeader + "=" + strExtra1;
+ }
+ if (strExtra2 != null) {
+ String strHeader = null;
+ switch (extra2Bank) {
+ case 0:
+ strHeader = "RES";
+ break;
+ case 1:
+ strHeader = "EPC";
+ break;
+ case 2:
+ strHeader = "TID";
+ break;
+ case 3:
+ strHeader = "USER";
+ break;
+ }
+ if (strHeader != null)
+ strDetail += "\n" + strHeader + "=" + strExtra2;
+ }
+ details = strDetail;
+ }
+ return details;
+ }
+
+ public void setDetails(String details) {
+ this.details = details;
+ }
+
+ public String getPc() { return strPc; }
+
+ public String getXpc() {
+ return strXpc;
+ }
+ public void setXpc(String strXpc) {
+ this.strXpc = strXpc;
+ }
+
+ public String getRes() {
+ if (extra1Bank == 0) return strExtra1;
+ else if (extra2Bank == 0) return strExtra2;
+ else return null;
+ }
+ public String getRes2() {
+ if (extra2Bank == 0) return strExtra2;
+ else if (extra1Bank == 0) return strExtra1;
+ else return null;
+ }
+ public String getEpc() {
+ if (extra1Bank == 1) return strExtra1;
+ else if (extra2Bank == 1) return strExtra2;
+ else return null;
+ }
+ public String getTid() {
+ if (extra1Bank == 2) return strExtra1;
+ else if (extra2Bank == 2) return strExtra2;
+ else return null;
+ }
+ public String getUser() {
+ if (extra1Bank == 3) return strExtra1;
+ else if (extra2Bank == 3) return strExtra2;
+ else return null;
+ }
+ public String getMdid() {
+ return strMdid;
+ }
+
+ public int getCount() {
+ return count;
+ }
+ public void setCount(int count) {
+ this.count = count;
+ }
+
+ public double getRssi() {
+ return rssi;
+ }
+ public void setRssi(double rssi) {
+ this.rssi = rssi;
+ }
+
+ public int getServiceUUID2p1() { return serviceUUID2p1; }
+ public void setServiceUUID2p1(int serviceUUID2p1) { this.serviceUUID2p1 = serviceUUID2p1; }
+
+ public int getPhase() { return phase; }
+ public void setPhase(int phase) { this.phase = phase; }
+
+ public int getChannel() {
+ return channel;
+ }
+ public void setChannel(int channel) {
+ this.channel = channel;
+ }
+
+ public int getPort() {
+ return port;
+ }
+ public void setPort(int port) {
+ this.port = port;
+ }
+
+ public int getStatus() { return status; }
+ public void setStatus(int status) {
+ this.status = status;
+ }
+
+ public int getBackport1() {
+ return backport1;
+ }
+ public void setBackport1(int backport1) {
+ this.backport1 = backport1;
+ }
+ public int getBackport2() {
+ return backport2;
+ }
+ public void setBackport2(int backport2) {
+ this.backport2 = backport2;
+ }
+
+ public int getCodeSensor() { return codeSensor; }
+ public void setCodeSensor(int codeSensor) {
+ this.codeSensor = codeSensor;
+ }
+
+ public int getCodeSensorMax() { return codeSensorMax; }
+ public void setCodeSensorMax(int codeSensor) {
+ this.codeSensorMax = codeSensor;
+ }
+
+ public int getCodeRssi() {
+ return codeRssi;
+ }
+ public void setCodeRssi(int codeRssi) {
+ this.codeRssi = codeRssi;
+ }
+
+ public float getCodeTempC() { return codeTempC; }
+ public void setCodeTempC(float codeTempC) {
+ this.codeTempC = codeTempC;
+ }
+
+ public String getBrand() {
+ return brand;
+ }
+ public void setBrand(String brand) { this.brand = brand; }
+
+ public int getSensorData() {
+ return sensorData;
+ }
+ public void setSensorData(int sensorData) { this.sensorData = sensorData; }
+
+ public String getstrExtra1() { return strExtra1; }
+ public void setExtra1(String strExtra1, int extra1Bank, int extra1Offset) {
+ this.strExtra1 = strExtra1;
+ this.extra1Bank = extra1Bank;
+ this.extra1Offset = extra1Offset;
+ }
+ public String getstrExtra2() { return strExtra2; }
+ public void setExtra2(String strExtra2, int extra2Bank, int extra2Offset) {
+ this.strExtra2 = strExtra2;
+ this.extra2Bank = extra2Bank;
+ this.extra2Offset = extra2Offset;
+ }
+ void setExtra(String strExtra1, int extra1Bank, int extra1Offset, String strExtra2, int extra2Bank, int extra2Offset) {
+ this.strExtra1 = strExtra1;
+ this.extra1Bank = extra1Bank;
+ this.extra1Offset = extra1Offset;
+ this.strExtra2 = strExtra2;
+ this.extra2Bank = extra2Bank;
+ this.extra2Offset = extra2Offset;
+ this.details = null; getDetails();
+ }
+
+ public boolean isConnected() {
+ return isConnected;
+ }
+
+ public void setConnected(boolean isConnected) {
+ this.isConnected = isConnected;
+ }
+
+ public String getTimeOfRead() { return timeOfRead; }
+ public String getTimeZone() { return timeZone; }
+ public String getLocation() { return location; }
+ public void setLocation(String location) { this.location = location; }
+ public String getCompass() { return compass; }
+ public void setCcompass(String compass) { this.compass = compass; }
+
+ @Override
+ public boolean equals(Object o) {
+ if (o == null || !(o instanceof ReaderDevice)) {
+ return false;
+ }
+ final ReaderDevice readerDevice = (ReaderDevice) o;
+ return ((this.getAddress() != null && readerDevice.getAddress() != null) && (readerDevice.getAddress().equalsIgnoreCase(this.getAddress())));
+ }
+
+ @Override
+ public int hashCode() {
+ int hash = 4;
+ hash = 53 * hash + (this.getAddress() != null ? this.getAddress().hashCode() : 0);
+ return hash;
+ }
+
+ public int compareTo(ReaderDevice other) {
+ return address.compareTo(other.address);
+ }
+}
+
+
+
+package com.csl.cslibrary4a;
+
+import android.content.Context;
+import android.widget.TextView;
+import android.widget.Toast;
+
+import java.util.ArrayList;
+
+public class RfidConnector {
+ Context context; Utility utility;
+ public RfidConnector(Context context, Utility utility) {
+ this.context = context;
+ this.utility = utility;
+ }
+ private String byteArrayToString(byte[] packet) { return utility.byteArrayToString(packet); }
+ private boolean compareArray(byte[] array1, byte[] array2, int length) { return utility.compareByteArray(array1, array2, length); }
+ private void appendToLog(String s) { utility.appendToLog(s); }
+ private void appendToLogView(String s) { utility.appendToLogView(s); }
+
+ public enum RfidPayloadEvents {
+ RFID_POWER_ON, RFID_POWER_OFF, RFID_COMMAND,
+ RFID_DATA_READ
+ }
+ public static class CsReaderRfidData {
+ public boolean waitUplinkResponse = false;
+ public boolean downlinkResponded = false;
+
+ public boolean uplinkResponded = false;
+ public boolean waitUplink1Response = false;
+
+ public RfidPayloadEvents rfidPayloadEvent;
+ public byte[] dataValues;
+ public boolean invalidSequence;
+ public long milliseconds;
+ }
+
+ public boolean onStatus = false; public boolean getOnStatus() { return onStatus; }
+
+ public interface RfidConnectorCallback {
+ boolean callbackMethod(byte[] dataValues);
+ }
+ public RfidConnectorCallback rfidConnectorCallback = null;
+
+ public ArrayList mRfidToWrite = new ArrayList<>();
+ public ArrayList mRfidToRead = new ArrayList<>();
+
+ public boolean arrayTypeSet(byte[] dataBuf, int pos, RfidPayloadEvents event) {
+ boolean validEvent = false;
+ switch (event) {
+ case RFID_POWER_ON:
+ validEvent = true;
+ break;
+ case RFID_POWER_OFF:
+ dataBuf[pos] = 1;
+ validEvent = true;
+ break;
+ case RFID_COMMAND:
+ dataBuf[pos] = 2;
+ validEvent = true;
+ break;
+ }
+ return validEvent;
+ }
+ public byte[] writeRfid(RfidConnector.CsReaderRfidData data, boolean usbConnection) {
+ boolean DEBUG = true;
+ int datalength = 0;
+ if (data.dataValues != null) datalength = data.dataValues.length;
+ byte[] dataOutRef = new byte[]{(byte) 0xA7, (byte) 0xB3, 2, (byte) 0xC2, (byte) 0x82, (byte) 0x37, 0, 0, (byte) 0x80, 0};
+ if (usbConnection) dataOutRef[1] = (byte) 0xE6;
+
+ byte[] dataOut = new byte[10 + datalength];
+ if (datalength != 0) {
+ System.arraycopy(data.dataValues, 0, dataOut, 10, datalength);
+ dataOutRef[2] += datalength;
+ }
+ System.arraycopy(dataOutRef, 0, dataOut, 0, dataOutRef.length);
+ /*if (data.rfidPayloadEvent == RfidConnector.RfidPayloadEvents.RFID_COMMAND) {
+ if (data.dataValues != null) {
+ byte[] dataOut1 = new byte[dataOut.length + data.dataValues.length];
+ System.arraycopy(dataOut, 0, dataOut1, 0, dataOut.length);
+ dataOut1[2] += data.dataValues.length;
+ System.arraycopy(data.dataValues, 0, dataOut1, dataOut.length, data.dataValues.length);
+ dataOut = dataOut1;
+ }
+ }*/
+ appendToLog("aabb 8");
+ if (arrayTypeSet(dataOut, 9, data.rfidPayloadEvent)) {
+ if (utility.DEBUG_PKDATA) appendToLog(String.format("PkData: write Rfid.%s.%s with mRfidDevice.sendRfidToWriteSent = %d", data.rfidPayloadEvent.toString(), byteArrayToString(data.dataValues), sendRfidToWriteSent));
+ if (sendRfidToWriteSent != 0) appendToLog("!!! mRfidDevice.sendRfidToWriteSent = " + sendRfidToWriteSent);
+ appendToLog("aabb 9");
+ if (DEBUG) appendToLogView("NOut: " + byteArrayToString(dataOut));
+ return dataOut;
+ }
+ return null;
+ }
+ public int rfidPowerOnTimeOut = 0; //int barcodePowerOnTimeOut = 0;
+ public boolean isMatchRfidToWrite(ConnectorData connectorData) {
+ boolean match = false, DEBUG = false;
+ if (mRfidToWrite.size() != 0 && connectorData.dataValues[0] == (byte)0x80) {
+ byte[] dataInCompare = new byte[]{(byte) 0x80, 0};
+ if (arrayTypeSet(dataInCompare, 1, mRfidToWrite.get(0).rfidPayloadEvent) && (connectorData.dataValues.length == dataInCompare.length + 1)) {
+ if (match = compareArray(connectorData.dataValues, dataInCompare, dataInCompare.length)) {
+ boolean bprocessed = false;
+ byte[] data1 = new byte[connectorData.dataValues.length - 2]; System.arraycopy(connectorData.dataValues, 2, data1, 0, data1.length);
+ if (utility.DEBUG_PKDATA) appendToLog("PkData: matched Rfid.Reply with payload = " + byteArrayToString(connectorData.dataValues) + " for writeData Rfid." + mRfidToWrite.get(0).rfidPayloadEvent.toString() + "." + byteArrayToString(mRfidToWrite.get(0).dataValues));
+ if (connectorData.dataValues[2] != 0) {
+ if (DEBUG) appendToLog("Rfid.reply data is found with error");
+ } else {
+ if (mRfidToWrite.get(0).rfidPayloadEvent == RfidConnector.RfidPayloadEvents.RFID_POWER_ON) {
+ rfidPowerOnTimeOut = 3000;
+ onStatus = true;
+ if (utility.DEBUG_PKDATA) appendToLog("PkData: matched Rfid.Reply.PowerOn with result 0 and onStatus = " + onStatus);
+ bprocessed = true;
+ } else if (mRfidToWrite.get(0).rfidPayloadEvent == RfidConnector.RfidPayloadEvents.RFID_POWER_OFF) {
+ onStatus = false;
+ if (utility.DEBUG_PKDATA) appendToLog("PkData: matched Rfid.Reply.PowerOff with result 0 and onStatus = " + onStatus);
+ bprocessed = true;
+ } else {
+ bprocessed = true;
+ if (utility.DEBUG_PKDATA) appendToLog("PkData: matched Rfid.Other.Reply data is found.");
+ }
+ RfidConnector.CsReaderRfidData csReaderRfidData = mRfidToWrite.get(0);
+ if (csReaderRfidData.waitUplinkResponse) {
+ csReaderRfidData.downlinkResponded = true;
+ mRfidToWrite.set(0, csReaderRfidData);
+ if (utility.DEBUG_PKDATA) appendToLog("PkData: mRfidToWrite.downlinkResponsed is set and waiting uplink data");
+ /*if (false) {
+ for (int i = 0; i < rfidReaderChip.mRfidReaderChip.mRx000ToRead.size(); i++) {
+ if (rfidReaderChip.mRfidReaderChip.mRx000ToRead.get(i).responseType == Cs710Library4A.HostCmdResponseTypes.TYPE_COMMAND_END)
+ if (DEBUG) appendToLog("mRx0000ToRead with COMMAND_END is removed");
+ }
+ if (DEBUG) appendToLog("mRx000ToRead.clear !!!");
+ }
+ rfidReaderChip.mRfidReaderChip.mRx000ToRead.clear(); if (DEBUG) appendToLog("mRx000ToRead.clear !!!");*/
+ utility.writeDebug2File("Up31 " + mRfidToWrite.get(0).rfidPayloadEvent.toString() + ", " + byteArrayToString(data1));
+ return true;
+ }
+ if (DEBUG) appendToLog("matched Rfid.reply data is found with mRfidToWrite.size=" + mRfidToWrite.size());
+ }
+
+ String string = "Up31 " + (bprocessed ? "" : "Unprocessed, ") + mRfidToWrite.get(0).rfidPayloadEvent.toString() + ", " + byteArrayToString(data1);
+ utility.writeDebug2File(string);
+ mRfidToWrite.remove(0); sendRfidToWriteSent = 0; mRfidToWriteRemoved = true; if (DEBUG) appendToLog("mmRfidToWrite remove 1 with remained write size = " + mRfidToWrite.size());
+ appendToLog("RfidConnector.isMatchRfidToWrite, UsbData: remove one");
+ if (utility.DEBUG_PKDATA) appendToLog("PkData: new mRfidToWrite size = " + mRfidToWrite.size());
+ /*if (false) {
+ for (int i = 0; i < rfidReaderChip.mRfidReaderChip.mRx000ToRead.size(); i++) {
+ if (rfidReaderChip.mRfidReaderChip.mRx000ToRead.get(i).responseType == Cs710Library4A.HostCmdResponseTypes.TYPE_COMMAND_END)
+ if (DEBUG) appendToLog("mRx0000ToRead with COMMAND_END is removed");
+ }
+ if (DEBUG) appendToLog("mRx000ToRead.clear !!!");
+ }
+ rfidReaderChip.mRfidReaderChip.mRx000ToRead.clear(); if (DEBUG) appendToLog("mRx000ToRead.clear !!!");*/
+ }
+ }
+ }
+ return match;
+ }
+
+ public int sendRfidToWriteSent = 0; public boolean mRfidToWriteRemoved = false;
+ public boolean rfidFailure = false; public boolean rfidValid = false;
+ public byte[] sendRfidToWrite(boolean usbConnection) {
+ boolean DEBUG = false;
+ boolean bValue = false;
+ //if (DEBUG) appendToLog("Timeout: btSendTimeOut = " + btSendTimeOut);
+ RfidConnector.RfidPayloadEvents rfidPayloadEvents = mRfidToWrite.get(0).rfidPayloadEvent;
+ int sendRfidToWriteSentMax = 5;
+ if (rfidPayloadEvents == RfidConnector.RfidPayloadEvents.RFID_COMMAND /*&& mRfidToWrite.get(0).dataValues[0] == 0x40*/) sendRfidToWriteSentMax = 5;
+ appendToLog("aabb 6");
+ if (sendRfidToWriteSent >= sendRfidToWriteSentMax) {
+ mRfidToWrite.remove(0); sendRfidToWriteSent = 0; mRfidToWriteRemoved = true; if (DEBUG) appendToLog("mmRfidToWrite remove 2");
+ if (DEBUG) appendToLog("Removed after sending count-out.");
+ if (true) {
+ appendToLog("Rfdid data transmission failure !!! clear mRfidToWrite buffer !!!");
+ //utility.writeDebug2File("Down fails to transmit " + byteArrayToString(mRfidToWrite.get(0).dataValues));
+ //appendToLog("BtDataOut: sendRfidToWrite 1 set rfidFailure as true with dataValues as " + byteArrayToString(mRfidToWrite.get(0).dataValues));
+ rfidFailure = true; appendToLog("BtDataOut: rfidFailure 1");
+ mRfidToWrite.clear(); appendToLog("BtDataOut: mRfidToWrite.clear 6");
+ } else if (rfidValid == false) {
+ Toast.makeText(context, "Problem in sending data to Rfid Module. Rfid is disabled.", Toast.LENGTH_SHORT).show();
+ appendToLog("BtDataOut: sendRfidToWrite 2 set rfidFailure as true");
+ rfidFailure = true; appendToLog("BtDataOut: rfidFailure 2");
+ } /*else {
+ Toast.makeText(context, "Problem in Sending Commands to RFID Module. Bluetooth Disconnected. Please Reconnect", Toast.LENGTH_SHORT).show();
+ appendToLog("disconnect d");
+ disconnect();
+ }*/
+ if (DEBUG) appendToLog("done");
+ } else {
+ if (DEBUG)
+ appendToLog("BtDataOut: size = " + mRfidToWrite.size() + ", PayloadEvents = " + rfidPayloadEvents.toString() + ", data=" + byteArrayToString(mRfidToWrite.get(0).dataValues));
+ appendToLog("aabb 7");
+ boolean retValue = false;
+ return writeRfid(mRfidToWrite.get(0), usbConnection);
+ }
+ return null;
+ }
+
+ public boolean found;
+ public int invalidUpdata;
+ public boolean isRfidToRead(ConnectorData connectorData) {
+ boolean DEBUG = false;
+ found = false;
+ if (connectorData.dataValues[0] == (byte) 0x81) {
+ appendToLog("BtData: RfidConnector.isRfidToRead dataValue = " + byteArrayToString(connectorData.dataValues));
+ RfidConnector.CsReaderRfidData cs108RfidReadData = new RfidConnector.CsReaderRfidData();
+ byte[] dataValues = new byte[connectorData.dataValues.length - 2];
+ System.arraycopy(connectorData.dataValues, 2, dataValues, 0, dataValues.length);
+ switch (connectorData.dataValues[1]) {
+ case 0:
+ appendToLog("BtData: RfidConnector.isRfidToRead rfidConnectorCallback is " + (rfidConnectorCallback == null ? "null" : "valid"));
+ if (rfidConnectorCallback != null) {
+ if (rfidConnectorCallback.callbackMethod(dataValues)) break;
+ }
+ cs108RfidReadData.rfidPayloadEvent = RfidConnector.RfidPayloadEvents.RFID_DATA_READ;
+ cs108RfidReadData.dataValues = dataValues;
+ cs108RfidReadData.invalidSequence = connectorData.invalidSequence;
+ cs108RfidReadData.milliseconds = connectorData.milliseconds;
+ mRfidToRead.add(cs108RfidReadData);
+ if (utility.DEBUG_PKDATA || true) appendToLog("PkData: Got Rfid.Uplink.DataRead with updated mRfidToRead data as " + byteArrayToString(dataValues));
+ found = true;
+ break;
+ default:
+ invalidUpdata++;
+ if (utility.DEBUG_PKDATA) appendToLog("PkData: !!! found INVALID Rfid.Uplink with payload = " + byteArrayToString(connectorData.dataValues));
+ break;
+ }
+ if (found) {
+ String string = "Up32 " + (found ? "" : "Unprocessed, ") + cs108RfidReadData.rfidPayloadEvent.toString() + ", " + byteArrayToString(dataValues);
+ utility.writeDebug2File(string);
+ }
+ }
+ return found;
+ }
+}
+
+
+
+package com.csl.cslibrary4a;
+
+import static java.lang.Math.log10;
+
+import android.content.Context;
+import android.util.Log;
+
+import androidx.annotation.NonNull;
+
+import java.math.BigInteger;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+
+public class RfidReader {
+ final boolean DEBUG = false;
+ public boolean bFirmware_reset_before = false;
+ RfidConnector rfidConnector; public RfidReaderChipR2000 rfidReaderChipR2000; public RfidReaderChipE710 rfidReaderChipE710;
+ ArrayList mRx000ToWrite;
+ ArrayList mRx000ToRead;
+ public ArrayList mRfidToWrite;
+ CountryChannelData countryChannelData;
+ Context context; Utility utility; boolean bis108; BluetoothGatt bluetoothGatt; SettingData settingData; NotificationConnector notificationConnector;
+ public RfidReader(Context context, Utility utility, CsReaderConnector csReaderConnector, boolean bis108, BluetoothGatt bluetoothGatt, SettingData settingData, NotificationConnector notificationConnector) {
+ this.context = context;
+ this.utility = utility;
+ this.bis108 = bis108;
+ this.bluetoothGatt = bluetoothGatt;
+ this.settingData = settingData;
+ this.notificationConnector = notificationConnector;
+
+ rfidConnector = new RfidConnector(context, utility); mRfidToWrite = rfidConnector.mRfidToWrite;
+ if (bis108) {
+ appendToLog("bis108: new RfidReaderChipR2000 is created");
+ rfidReaderChipR2000 = new RfidReaderChipR2000(context, utility, csReaderConnector);
+ mRx000ToWrite = rfidReaderChipR2000.mRx000ToWrite;
+ mRx000ToRead = rfidReaderChipR2000.mRx000ToRead;
+ } else {
+ appendToLog("bis108: new RfidReaderChipE710 is created");
+ rfidReaderChipE710 = new RfidReaderChipE710(context, utility, csReaderConnector);
+ mRx000ToWrite = rfidReaderChipE710.mRx000ToWrite;
+ mRx000ToRead = rfidReaderChipE710.mRx000ToRead;
+ rfidConnector.rfidConnectorCallback = new RfidConnector.RfidConnectorCallback(){
+ @Override
+ public boolean callbackMethod(byte[] dataValues) {
+ return rfidReaderChipE710.decode710Data(dataValues);
+ }
+ };
+ }
+ countryChannelData = new CountryChannelData();
+ countryChannelData.fccFreqTableIdx = new int[50];
+ int[] freqSortedINx = countryChannelData.fccFreqSortedIdx;
+ for (int i = 0; i < 50; i++) {
+ countryChannelData.fccFreqTableIdx[countryChannelData.fccFreqSortedIdx[i]] = i;
+ }
+ for (int i = 0; i < 50; i++) {
+ if (false) appendToLog("fccFreqTableIdx[" + i + "] = " + countryChannelData.fccFreqTableIdx[i]);
+ }
+ }
+
+ public enum TagType {
+ TAG_NULL,
+ TAG_IMPINJ, TAG_IMPINJ_M755, //E28011, E2C011
+ TAG_ALIEN, //E2003
+ TAG_NXP, TAG_NXP_UCODEDNA, TAG_NXP_UCODE8, //E2806, E2C06, E2806894
+ TAG_NXP_UCODE8_EPC, TAG_NXP_UCODE8_EPCTID, TAG_NXP_UCODE8_EPCBRAND, TAG_NXP_UCODE8_EPCBRANDTID, //E2806894A, E2806894B, E2806894C, E2806894d
+ TAG_EM, TAG_EM_BAP, TAG_EM_COLDCHAIN, TAG_EM_AURASENSE, TAG_EM_AURASENSE_ATBOOT, TAG_EM_AURASENSE_ATSELECT, //E280B, E200B0, E280B0, E280B12, E280B12A, E280B12B
+ TAG_KILOWAY, //E281D
+ TAG_LONGJING, //E201E
+ TAG_FDMICRO, //E2827001
+ TAG_CTESIUS, //E203510
+ TAG_ASYGN, //E283A
+ TAG_AXZON, TAG_MAGNUS_S2, TAG_MAGNUS_S3, TAG_AXZON_XERXES, //E2824, E282402, E282403, E282405
+ }
+ public static class ExtraBankData {
+ public int extra1Bank;
+ public int extra2Bank;
+ public int extra1Count;
+ public int extra2Count;
+ public int extra1Offset;
+ public int extra2Offset;
+
+ public ExtraBankData() {
+ extra1Bank = -1; extra2Bank = -1;
+ extra1Count = 0; extra2Count = 0;
+ extra1Offset = 0; extra2Offset = 0;
+ }
+
+ public void setExtraBankData(int extra1Bank, int extra1Count, int extra1Offset, int extra2Bank, int extra2Count, int extra2Offset) {
+ this.extra1Bank = extra1Bank; this.extra2Bank = extra2Bank;
+ this.extra1Count = extra1Count; this.extra2Count = extra2Count;
+ this.extra1Offset = extra1Offset; this.extra2Offset = extra2Offset;
+ }
+ public void setExtraBankData(RfidReader.TagType tagType, String mDid) {
+ extra2Bank = 2;
+ extra2Offset = 0;
+ extra2Count = 2;
+ Log.i("Hello", "tagType = " + (tagType == null ? "null" : tagType.toString()) + ", mDid = " + mDid);
+ if (mDid == null) mDid = "";
+ if (mDid.matches("E2801101") || mDid.matches("E2801102") || mDid.matches("E2801103") || mDid.matches("E2801104") || mDid.matches("E2801105")) {
+ extra1Bank = 0;
+ extra1Offset = 4;
+ extra1Count = 1;
+ if (mDid.matches("E2801101")) extra2Count = 6;
+ } else if (mDid.matches("E200B0")) {
+ extra1Bank = 2;
+ extra1Offset = 0;
+ extra1Count = 2;
+ extra2Bank = 3;
+ extra2Offset = 0x2d;
+ extra2Count = 1;
+ } else if (mDid.matches("E203510")) {
+ extra1Bank = 2;
+ extra1Offset = 0;
+ extra1Count = 2;
+ extra2Bank = 3;
+ extra2Offset = 8;
+ extra2Count = 2;
+ } else if (mDid.matches("E283A")) {
+ extra1Bank = 2;
+ extra1Offset = 0;
+ extra1Count = 2;
+ extra2Bank = 3;
+ extra2Offset = 0;
+ extra2Count = 8;
+ } else if (mDid.indexOf("E280B12") == 0) {
+ extra1Bank = 2;
+ extra1Offset = 0;
+ extra1Count = 2;
+ extra2Bank = 3;
+ extra2Offset = 0x120;
+ extra2Count = 1;
+ } else if (mDid.indexOf("E280B0") == 0) {
+ extra1Bank = 3;
+ extra1Offset = 188;
+ extra1Count = 2;
+ //extra2Bank = 3;
+ //extra2Offset = 0x10d;
+ //extra2Count = 1;
+ } else if (mDid.indexOf("E281D") == 0) { //need atmel firmware 0.2.20
+ extra1Bank = 0;
+ extra1Offset = 4;
+ extra1Count = 1;
+ extra2Count = 6;
+ } else if (mDid.indexOf("E201E") == 0) {
+ extra1Bank = 3;
+ extra1Offset = 112;
+ extra1Count = 1;
+ extra2Count = 6;
+ } else if (mDid.matches("E282402")) {
+ extra1Bank = 0;
+ extra1Offset = 11;
+ extra1Count = 1;
+ extra2Bank = 0;
+ extra2Offset = 13;
+ extra2Count = 1;
+ } else if (mDid.matches("E282403")) {
+ extra1Bank = 0;
+ extra1Offset = 12;
+ extra1Count = 3;
+ extra2Bank = 3;
+ extra2Offset = 8;
+ extra2Count = 4;
+ } else if (mDid.matches("E282405")) {
+ extra1Bank = 0;
+ extra1Offset = 10;
+ extra1Count = 5;
+ extra2Bank = 3;
+ extra2Offset = 0x12;
+ extra2Count = 4;
+ }
+ }
+
+ public void adjustExtraBank1() {
+ if (extra1Bank == -1 || extra1Count == 0) {
+ extra1Bank = extra2Bank;
+ extra2Bank = 0;
+ extra1Count = extra2Count;
+ extra2Count = 0;
+ extra1Offset = extra2Offset;
+ extra2Offset = 0;
+ }
+ if (extra1Bank == 1) extra1Offset += 2;
+ if (extra2Bank == 1) extra2Offset += 2;
+ }
+ }
+ public int setSelectData4Inventory(RfidReader.TagType tagType, String mDid, boolean bNeedSelectedTagByTID, String stringProtectPassword, int selectFor, int selectHold) {
+ int iValue = -1;
+ if (utility.DEBUG_SELECT) appendToLog("Debug_Select: RfidReader.setSelectData4Inventory with mDid = " + mDid);
+ if (mDid != null) {
+ setSelectCriteriaDisable(-1);
+ if (mDid.indexOf("E280B12") == 0) {
+ if (mDid.matches("E280B12B")) {
+ setSelectCriteria(0, true, 4, 0, 5, 1, 0x220, "8321");
+ appendToLog("Hello123: Set Sense at Select !!!");
+ } else { //if (MainActivity.mDid.matches("E280B12A")) {
+ //setSelectCriteriaDisable(-1);
+ appendToLog("Hello123: Set Sense at BOOT !!!");
+ }
+ } else if (mDid.matches("E203510")) {
+ setSelectCriteria(0, true, 7, 4, 0, 2, 0, mDid);
+ } else if (mDid.matches("E28240")) {
+ if (true || selectFor != 0) {
+ //setSelectCriteriaDisable(-1);
+ selectFor = 0;
+ iValue = selectFor;
+ }
+ } else if (mDid.matches("E282402")) {
+ appendToLog("selectFor = " + selectFor);
+ if (true || selectFor != 2) {
+ setSelectCriteria(0, true, 4, 2, 0, 3, 0xA0, "20");
+ selectFor = 2;
+ iValue = selectFor;
+ }
+ } else if (mDid.matches("E282403")) {
+ if (utility.DEBUG_SELECT) appendToLog("Debug_Select: RfidReader.setSelectData4Inventory selectFor = " + selectFor);
+ if (true || selectFor != 3) {
+ setSelectCriteria(0, true, 4, 2, 0, 3, 0xD0, "1F");
+ int delay = 0; if (bis108) delay = 5; //if delay in 710 causes no inventory after leaving and returning
+ setSelectCriteria(1, true, 4, 2, delay, 3, 0xE0, "");
+ selectFor = 3;
+ iValue = selectFor;
+ }
+ } else if (mDid.matches("E282405")) {
+ if (true || selectFor != 5) {
+ setSelectCriteria(0, true, 4, 5, selectHold, 3, 0x3B0, "00");
+ //setSelectCriteriaDisable(2);
+ selectFor = 5;
+ iValue = selectFor;
+ }
+ } else {
+ appendToLog("MainActivity.selectFor = " + selectFor);
+ if (true || selectFor != -1) {
+ //setSelectCriteriaDisable(-1);
+ selectFor = -1;
+ iValue = selectFor;
+ }
+ }
+
+ if (mDid.indexOf("E2806894") == 0) {
+ appendToLog("RfidReader.setSelectData 0 found " + mDid + ".indexOf[E2806894] == 0");
+ if (mDid.matches("E2806894A")) {
+ appendToLog("RfidReader.setSelectData 1 found E2806894A");
+ //setSelectCriteriaDisable(1);
+ } else if (mDid.matches("E2806894B")) {
+ appendToLog("RfidReader.setSelectData 2 found E2806894B");
+ appendToLog("BtDataOut BBB 2");
+ setSelectCriteria(0, true, 4, 0, 1, 0x203, "1", true);
+ setSelectCriteria(1, true, 4, 2, 2, 0, "E2806894", false);
+ } else if (mDid.matches("E2806894C") || mDid.matches("E2806894d")) {
+ appendToLog("RfidReader.setSelectData 3 found " + mDid);
+ setSelectCriteria(0, true, 4, 0, 1, 0x204, "1", true);
+ setSelectCriteria(1, true, 4, 2, 2, 0, "E2806894", false);
+ }
+ mDid = "E2806894";
+ }
+
+ if (bNeedSelectedTagByTID) {
+ String strMdid = mDid;
+ if (strMdid.indexOf("E28011") == 0) {
+ int iValue1 = Integer.valueOf(strMdid.substring(6, 8), 16);
+ iValue1 &= 0x0F;
+ appendToLog(String.format("iValue1 = 0x%X", iValue1));
+ if (iValue1 == 1) strMdid = "E2C011A2";
+ else if (iValue1 == 2) strMdid = "E28011C";
+ else if (iValue1 == 3) strMdid = "E28011B";
+ else if (iValue1 == 4) strMdid = "E28011A";
+ else if (iValue1 == 5) strMdid = "E280119";
+ else if (iValue1 == 6) strMdid = "E2801171";
+ else if (iValue1 == 7) strMdid = "E2801170";
+ else if (iValue1 == 8) strMdid = "E2801150";
+ else
+ strMdid = "E2001"; //strMdid.substring(0, 5); even E2801 or E2C01 will return
+ }
+ if (stringProtectPassword != null) {
+ if (stringProtectPassword.trim().length() == 0)
+ stringProtectPassword = "00000000";
+ if (utility.DEBUG_SELECT) appendToLog("Debug_Select: RfidReader.setSelectCriteria: Going to setSelectCriteria");
+ setSelectCriteria(-1, true, 4, 0, 3, 0, stringProtectPassword, false);
+ }
+ if (utility.DEBUG_SELECT) appendToLog("Debug_Select: RfidReader.setSelectCriteria: Going to setSelectedByTID");
+ setSelectedTagByTID(strMdid, -1);
+ }
+ }
+ return iValue;
+ }
+
+ //============ utility ============
+ private void appendToLog(String s) { utility.appendToLog(s); }
+
+ //============ Rfid ============
+ //============ Rfid ============
+ //============ Rfid ============
+ //============ Rfid ============
+ //============ Rfid ============
+
+ public boolean setInvAlgoNoSave(boolean dynamicAlgo) {
+ appendToLog("writeBleStreamOut: going to setInvAlgo with dynamicAlgo = " + dynamicAlgo);
+ return setInvAlgo1(dynamicAlgo);
+ }
+ public boolean setInvAlgo1(boolean dynamicAlgo) {
+ boolean bValue = true, DEBUG = false;
+ if (DEBUG) appendToLog("2 setInvAlgo1");
+ int iAlgo = getInvAlgoInChip();
+ int iRetry = getRetryCount();
+ int iAbFlip = (bis108 ? rfidReaderChipR2000.rx000Setting.getAlgoAbFlip() : rfidReaderChipE710.rx000Setting.getAlgoAbFlip());
+ if (DEBUG) appendToLog("2 setInvAlgo1: going to setInvAlgo with dynamicAlgo = " + dynamicAlgo + ", iAlgo = " + iAlgo + ", iRetry = " + iRetry + ", iabFlip = " + iAbFlip);
+ if ( (dynamicAlgo && iAlgo == 0) || (dynamicAlgo == false && iAlgo == 3)) {
+ bValue = (bis108 ? rfidReaderChipR2000.rx000Setting.setInvAlgo(dynamicAlgo ? 3 : 0) : rfidReaderChipE710.rx000Setting.setInvAlgo(dynamicAlgo ? 3 : 0));
+ if (DEBUG) appendToLog("After setInvAlgo, bValue = " + bValue);
+ if (DEBUG) appendToLog("Before setPopulation, population = " + getPopulation());
+ if (bValue) bValue = setPopulation(getPopulation());
+ if (DEBUG) appendToLog("After setPopulation, bValue = " + bValue);
+ if (bValue) bValue = setRetryCount(iRetry);
+ if (DEBUG) appendToLog("After setRetryCount, bValue = " + bValue);
+ if (bValue) bValue = (bis108 ? rfidReaderChipR2000.rx000Setting.setAlgoAbFlip(iAbFlip) : rfidReaderChipE710.rx000Setting.setAlgoAbFlip(iAbFlip));
+ if (DEBUG) appendToLog("After setAlgoAbFlip, bValue = " + bValue);
+ }
+ return bValue;
+ }
+
+ private int[] freqTable = null;
+ private int[] freqSortedIdx = null;
+ static class CountryChannelData {
+ final int FCC_CHN_CNT = 50;
+ private final double[] FCCTableOfFreq = new double[]{
+ 902.75, 903.25, 903.75, 904.25, 904.75, 905.25, 905.75, 906.25, 906.75, 907.25,//10
+ 907.75, 908.25, 908.75, 909.25, 909.75, 910.25, 910.75, 911.25, 911.75, 912.25,//20
+ 912.75, 913.25, 913.75, 914.25, 914.75, 915.25, 915.75, 916.25, 916.75, 917.25,
+ 917.75, 918.25, 918.75, 919.25, 919.75, 920.25, 920.75, 921.25, 921.75, 922.25,
+ 922.75, 923.25, 923.75, 924.25, 924.75, 925.25, 925.75, 926.25, 926.75, 927.25};
+ private final double[] FCCTableOfFreq0 = new double[]{
+ 903.75, 912.25, 907.75, 910.25, 922.75, 923.25, 923.75, 915.25, 909.25, 912.75,
+ 910.75, 913.75, 909.75, 905.25, 911.75, 902.75, 914.25, 918.25, 926.25, 925.75,
+ 920.75, 920.25, 907.25, 914.75, 919.75, 922.25, 903.25, 906.25, 905.75, 926.75,
+ 924.25, 904.75, 925.25, 924.75, 919.25, 916.75, 911.25, 921.25, 908.25, 908.75,
+ 913.25, 916.25, 904.25, 906.75, 917.75, 921.75, 917.25, 927.25, 918.75, 915.75};
+ private int[] fccFreqSortedIdx0;
+ private final double[] FCCTableOfFreq1 = new double[]{
+ 915.25, 920.75, 909.25, 912.25, 918.25, 920.25, 909.75, 910.25, 919.75, 922.75,
+ 908.75, 913.75, 903.75, 919.25, 922.25, 907.75, 911.75, 923.75, 916.75, 926.25,
+ 908.25, 912.75, 924.25, 916.25, 927.25, 907.25, 910.75, 903.25, 917.75, 926.75,
+ 905.25, 911.25, 924.75, 917.25, 925.75, 906.75, 914.25, 904.75, 918.75, 923.25,
+ 902.75, 914.75, 905.75, 915.75, 925.25, 906.25, 921.25, 913.25, 921.75, 904.25};
+ private int[] fccFreqSortedIdx1;
+ private int[] fccFreqTable = new int[]{
+ 0x00180E4F, //915.75 MHz
+ 0x00180E4D, //915.25 MHz
+ 0x00180E1D, //903.25 MHz
+ 0x00180E7B, //926.75 MHz
+ 0x00180E79, //926.25 MHz
+ 0x00180E21, //904.25 MHz
+ 0x00180E7D, //927.25 MHz
+ 0x00180E61, //920.25 MHz
+ 0x00180E5D, //919.25 MHz
+ 0x00180E35, //909.25 MHz
+ 0x00180E5B, //918.75 MHz
+ 0x00180E57, //917.75 MHz
+ 0x00180E25, //905.25 MHz
+ 0x00180E23, //904.75 MHz
+ 0x00180E75, //925.25 MHz
+ 0x00180E67, //921.75 MHz
+ 0x00180E4B, //914.75 MHz
+ 0x00180E2B, //906.75 MHz
+ 0x00180E47, //913.75 MHz
+ 0x00180E69, //922.25 MHz
+ 0x00180E3D, //911.25 MHz
+ 0x00180E3F, //911.75 MHz
+ 0x00180E1F, //903.75 MHz
+ 0x00180E33, //908.75 MHz
+ 0x00180E27, //905.75 MHz
+ 0x00180E41, //912.25 MHz
+ 0x00180E29, //906.25 MHz
+ 0x00180E55, //917.25 MHz
+ 0x00180E49, //914.25 MHz
+ 0x00180E2D, //907.25 MHz
+ 0x00180E59, //918.25 MHz
+ 0x00180E51, //916.25 MHz
+ 0x00180E39, //910.25 MHz
+ 0x00180E3B, //910.75 MHz
+ 0x00180E2F, //907.75 MHz
+ 0x00180E73, //924.75 MHz
+ 0x00180E37, //909.75 MHz
+ 0x00180E5F, //919.75 MHz
+ 0x00180E53, //916.75 MHz
+ 0x00180E45, //913.25 MHz
+ 0x00180E6F, //923.75 MHz
+ 0x00180E31, //908.25 MHz
+ 0x00180E77, //925.75 MHz
+ 0x00180E43, //912.75 MHz
+ 0x00180E71, //924.25 MHz
+ 0x00180E65, //921.25 MHz
+ 0x00180E63, //920.75 MHz
+ 0x00180E6B, //922.75 MHz
+ 0x00180E1B, //902.75 MHz
+ 0x00180E6D, //923.25 MHz
+ };
+ private int[] fccFreqTableIdx;
+ private final int[] fccFreqSortedIdx = new int[]{
+ 26, 25, 1, 48, 47,
+ 3, 49, 35, 33, 13,
+ 32, 30, 5, 4, 45,
+ 38, 24, 8, 22, 39,
+ 17, 18, 2, 12, 6,
+ 19, 7, 29, 23, 9,
+ 31, 27, 15, 16, 10,
+ 44, 14, 34, 28, 21,
+ 42, 11, 46, 20, 43,
+ 37, 36, 40, 0, 41};
+
+ private final int AUS_CHN_CNT = 10;
+ private final double[] AUSTableOfFreq = new double[]{
+ 920.75, 921.25, 921.75, 922.25, 922.75,
+ 923.25, 923.75, 924.25, 924.75, 925.25};
+ private final int[] AusFreqTable = new int[]{
+ 0x00180E63, // 920.75MHz
+ 0x00180E69, // 922.25MHz
+ 0x00180E6F, // 923.75MHz
+ 0x00180E73, // 924.75MHz
+ 0x00180E65, // 921.25MHz
+ 0x00180E6B, // 922.75MHz
+ 0x00180E71, // 924.25MHz
+ 0x00180E75, // 925.25MHz
+ 0x00180E67, // 921.75MHz
+ 0x00180E6D, // 923.25MHz
+ };
+ private final int[] ausFreqSortedIdx = new int[]{
+ 0, 3, 6, 8, 1,
+ 4, 7, 9, 2, 5};
+
+ private double[] PRTableOfFreq = new double[]{
+ 915.25, 915.75, 916.25, 916.75, 917.25,
+ 917.75, 918.25, 918.75, 919.25, 919.75, 920.25, 920.75, 921.25, 921.75, 922.25,
+ 922.75, 923.25, 923.75, 924.25, 924.75, 925.25, 925.75, 926.25, 926.75, 927.25};
+
+ private final int VZ_CHN_CNT = 10;
+ private final double[] VZTableOfFreq = new double[]{
+ 922.75, 923.25, 923.75, 924.25, 924.75,
+ 925.25, 925.75, 926.25, 926.75, 927.25};
+ private final int[] vzFreqTable = new int[]{
+ 0x00180E77, // 925.75 MHz
+ 0x00180E6B, // 922.75MHz
+ 0x00180E7D, // 927.25 MHz
+ 0x00180E75, // 925.25MHz
+ 0x00180E6D, // 923.25MHz
+ 0x00180E7B, // 926.75 MHz
+ 0x00180E73, // 924.75MHz
+ 0x00180E6F, // 923.75MHz
+ 0x00180E79, // 926.25 MHz
+ 0x00180E71, // 924.25MHz
+ };
+ private final int[] vzFreqSortedIdx = new int[]{
+ 6, 0, 9, 5, 1,
+ 8, 4, 2, 7, 3};
+
+ private final int BR1_CHN_CNT = 24;
+ private final double[] BR1TableOfFreq = new double[]{
+ //902.75, 903.25, 903.75, 904.25, 904.75,
+ //905.25, 905.75, 906.25, 906.75, 907.25,
+ //907.75, 908.25, 908.75, 909.25, 909.75,
+ //910.25, 910.75, 911.25, 911.75, 912.25,
+ //912.75, 913.25, 913.75, 914.25, 914.75,
+ //915.25,
+ 915.75, 916.25, 916.75, 917.25, 917.75,
+ 918.25, 918.75, 919.25, 919.75, 920.25,
+ 920.75, 921.25, 921.75, 922.25, 922.75,
+ 923.25, 923.75, 924.25, 924.75, 925.25,
+ 925.75, 926.25, 926.75, 927.25};
+ private final int[] br1FreqTable = new int[]{
+ 0x00180E4F, //915.75 MHz
+ //0x00180E4D, //915.25 MHz
+ //0x00180E1D, //903.25 MHz
+ 0x00180E7B, //926.75 MHz
+ 0x00180E79, //926.25 MHz
+ //0x00180E21, //904.25 MHz
+ 0x00180E7D, //927.25 MHz
+ 0x00180E61, //920.25 MHz
+ 0x00180E5D, //919.25 MHz
+ //0x00180E35, //909.25 MHz
+ 0x00180E5B, //918.75 MHz
+ 0x00180E57, //917.75 MHz
+ //0x00180E25, //905.25 MHz
+ //0x00180E23, //904.75 MHz
+ 0x00180E75, //925.25 MHz
+ 0x00180E67, //921.75 MHz
+ //0x00180E4B, //914.75 MHz
+ //0x00180E2B, //906.75 MHz
+ //0x00180E47, //913.75 MHz
+ 0x00180E69, //922.25 MHz
+ //0x00180E3D, //911.25 MHz
+ //0x00180E3F, //911.75 MHz
+ //0x00180E1F, //903.75 MHz
+ //0x00180E33, //908.75 MHz
+ //0x00180E27, //905.75 MHz
+ //0x00180E41, //912.25 MHz
+ //0x00180E29, //906.25 MHz
+ 0x00180E55, //917.25 MHz
+ //0x00180E49, //914.25 MHz
+ //0x00180E2D, //907.25 MHz
+ 0x00180E59, //918.25 MHz
+ 0x00180E51, //916.25 MHz
+ //0x00180E39, //910.25 MHz
+ //0x00180E3B, //910.75 MHz
+ //0x00180E2F, //907.75 MHz
+ 0x00180E73, //924.75 MHz
+ //0x00180E37, //909.75 MHz
+ 0x00180E5F, //919.75 MHz
+ 0x00180E53, //916.75 MHz
+ //0x00180E45, //913.25 MHz
+ 0x00180E6F, //923.75 MHz
+ //0x00180E31, //908.25 MHz
+ 0x00180E77, //925.75 MHz
+ //0x00180E43, //912.75 MHz
+ 0x00180E71, //924.25 MHz
+ 0x00180E65, //921.25 MHz
+ 0x00180E63, //920.75 MHz
+ 0x00180E6B, //922.75 MHz
+ //0x00180E1B, //902.75 MHz
+ 0x00180E6D, //923.25 MHz
+ };
+ private final int[] br1FreqSortedIdx = new int[]{
+ 0, 22, 21, 23, 9,
+ 7, 6, 4, 19, 12,
+ 13, 3, 5, 1, 18,
+ 8, 2, 16, 20, 17,
+ 11, 10, 14, 15};
+
+ private final int BR2_CHN_CNT = 33;
+ private double[] BR2TableOfFreq = new double[]{
+ 902.75, 903.25, 903.75, 904.25, 904.75,
+ 905.25, 905.75, 906.25, 906.75,
+ //907.25, 907.75, 908.25, 908.75, 909.25,
+ //909.75, 910.25, 910.75, 911.25, 911.75,
+ //912.25, 912.75, 913.25, 913.75, 914.25,
+ //914.75, 915.25,
+ 915.75, 916.25, 916.75, 917.25, 917.75,
+ 918.25, 918.75, 919.25, 919.75, 920.25,
+ 920.75, 921.25, 921.75, 922.25, 922.75,
+ 923.25, 923.75, 924.25, 924.75, 925.25,
+ 925.75, 926.25, 926.75, 927.25};
+ private final int[] br2FreqTable = new int[]{
+ 0x00180E4F, //915.75 MHz
+ //0x00180E4D, //915.25 MHz
+ 0x00180E1D, //903.25 MHz
+ 0x00180E7B, //926.75 MHz
+ 0x00180E79, //926.25 MHz
+ 0x00180E21, //904.25 MHz
+ 0x00180E7D, //927.25 MHz
+ 0x00180E61, //920.25 MHz
+ 0x00180E5D, //919.25 MHz
+ //0x00180E35, //909.25 MHz
+ 0x00180E5B, //918.75 MHz
+ 0x00180E57, //917.75 MHz
+ 0x00180E25, //905.25 MHz
+ 0x00180E23, //904.75 MHz
+ 0x00180E75, //925.25 MHz
+ 0x00180E67, //921.75 MHz
+ //0x00180E4B, //914.75 MHz
+ 0x00180E2B, //906.75 MHz
+ //0x00180E47, //913.75 MHz
+ 0x00180E69, //922.25 MHz
+ //0x00180E3D, //911.25 MHz
+ //0x00180E3F, //911.75 MHz
+ 0x00180E1F, //903.75 MHz
+ //0x00180E33, //908.75 MHz
+ 0x00180E27, //905.75 MHz
+ //0x00180E41, //912.25 MHz
+ 0x00180E29, //906.25 MHz
+ 0x00180E55, //917.25 MHz
+ //0x00180E49, //914.25 MHz
+ //0x00180E2D, //907.25 MHz
+ 0x00180E59, //918.25 MHz
+ 0x00180E51, //916.25 MHz
+ //0x00180E39, //910.25 MHz
+ //0x00180E3B, //910.75 MHz
+ //0x00180E2F, //907.75 MHz
+ 0x00180E73, //924.75 MHz
+ //0x00180E37, //909.75 MHz
+ 0x00180E5F, //919.75 MHz
+ 0x00180E53, //916.75 MHz
+ //0x00180E45, //913.25 MHz
+ 0x00180E6F, //923.75 MHz
+ //0x00180E31, //908.25 MHz
+ 0x00180E77, //925.75 MHz
+ //0x00180E43, //912.75 MHz
+ 0x00180E71, //924.25 MHz
+ 0x00180E65, //921.25 MHz
+ 0x00180E63, //920.75 MHz
+ 0x00180E6B, //922.75 MHz
+ 0x00180E1B, //902.75 MHz
+ 0x00180E6D, //923.25 MHz
+ };
+ private final int[] br2FreqSortedIdx = new int[]{
+ 9, 1, 31, 30, 3,
+ 32, 18, 16, 15, 13,
+ 5, 4, 28, 21, 8,
+ 22, 2, 6, 7, 12,
+ 14, 10, 27, 17, 11,
+ 25, 29, 26, 20, 19,
+ 23, 0, 24,
+ };
+
+ private final int BR3_CHN_CNT = 9;
+ private final double[] BR3TableOfFreq = new double[]{
+ 902.75, 903.25, 903.75, 904.25, 904.75, // 4
+ 905.25, 905.75, 906.25, 906.75};
+ private final int[] br3FreqTable = new int[]{
+ 0x00180E1D, //903.25 MHz
+ 0x00180E21, //904.25 MHz
+ 0x00180E25, //905.25 MHz
+ 0x00180E23, //904.75 MHz
+ 0x00180E2B, //906.75 MHz
+ 0x00180E1F, //903.75 MHz
+ 0x00180E27, //905.75 MHz
+ 0x00180E29, //906.25 MHz
+ 0x00180E1B, //902.75 MHz
+ };
+ private final int[] br3FreqSortedIdx = new int[]{
+ 1, 3, 5, 4, 8,
+ 2, 6, 7, 0};
+
+ private final int BR4_CHN_CNT = 4;
+ private final double[] BR4TableOfFreq = new double[]{
+ 902.75, 903.25, 903.75, 904.25};
+ private final int[] br4FreqTable = new int[]{
+ 0x00180E1D, //903.25 MHz
+ 0x00180E21, //904.25 MHz
+ 0x00180E1F, //903.75 MHz
+ 0x00180E1B, //902.75 MHz
+ };
+ private final int[] br4FreqSortedIdx = new int[]{
+ 1, 3, 2, 0};
+
+ private final int BR5_CHN_CNT = 14;
+ private final double[] BR5TableOfFreq = new double[]{
+ 917.75, 918.25, 918.75, 919.25, 919.75, // 4
+ 920.25, 920.75, 921.25, 921.75, 922.25, // 9
+ 922.75, 923.25, 923.75, 924.25};
+ private final int[] br5FreqTable = new int[]{
+ 0x00180E61, //920.25 MHz
+ 0x00180E5D, //919.25 MHz
+ 0x00180E5B, //918.75 MHz
+ 0x00180E57, //917.75 MHz
+ 0x00180E67, //921.75 MHz
+ 0x00180E69, //922.25 MHz
+ 0x00180E59, //918.25 MHz
+ 0x00180E5F, //919.75 MHz
+ 0x00180E6F, //923.75 MHz
+ 0x00180E71, //924.25 MHz
+ 0x00180E65, //921.25 MHz
+ 0x00180E63, //920.75 MHz
+ 0x00180E6B, //922.75 MHz
+ 0x00180E6D, //923.25 MHz
+ };
+ private final int[] br5FreqSortedIdx = new int[]{
+ 5, 3, 2, 0, 8,
+ 9, 1, 4, 12, 13,
+ 7, 6, 10, 11};
+
+ private final int HK_CHN_CNT = 8;
+ private final double[] HKTableOfFreq = new double[]{
+ 920.75, 921.25, 921.75, 922.25, 922.75,
+ 923.25, 923.75, 924.25};
+ private final int[] hkFreqTable = new int[]{
+ 0x00180E63, //920.75MHz
+ 0x00180E69, //922.25MHz
+ 0x00180E71, //924.25MHz
+ 0x00180E65, //921.25MHz
+ 0x00180E6B, //922.75MHz
+ 0x00180E6D, //923.25MHz
+ 0x00180E6F, //923.75MHz
+ 0x00180E67, //921.75MHz
+ };
+ private final int[] hkFreqSortedIdx = new int[]{
+ 0, 3, 7, 1, 4,
+ 5, 6, 2};
+
+ private final int BD_CHN_CNT = 4;
+ private final double[] BDTableOfFreq = new double[]{
+ 925.25, 925.75, 926.25, 926.75};
+ private final int[] bdFreqTable = new int[]{
+ 0x00180E75, //925.25MHz
+ 0x00180E77, //925.75MHz
+ 0x00180E79, //926.25MHz
+ 0x00180E7B, //926.75MHz
+ };
+ private final int[] bdFreqSortedIdx = new int[]{
+ 0, 3, 1, 2};
+
+ private final int TW_CHN_CNT = 12;
+ private final double[] TWTableOfFreq = new double[]{
+ 922.25, 922.75, 923.25, 923.75, 924.25,
+ 924.75, 925.25, 925.75, 926.25, 926.75,
+ 927.25, 927.75};
+ private int[] twFreqTable = new int[]{
+ 0x00180E7D, //927.25MHz 10
+ 0x00180E73, //924.75MHz 5
+ 0x00180E6B, //922.75MHz 1
+ 0x00180E75, //925.25MHz 6
+ 0x00180E7F, //927.75MHz 11
+ 0x00180E71, //924.25MHz 4
+ 0x00180E79, //926.25MHz 8
+ 0x00180E6D, //923.25MHz 2
+ 0x00180E7B, //926.75MHz 9
+ 0x00180E69, //922.25MHz 0
+ 0x00180E77, //925.75MHz 7
+ 0x00180E6F, //923.75MHz 3
+ };
+ private final int[] twFreqSortedIdx = new int[]{
+ 10, 5, 1, 6, 11,
+ 4, 8, 2, 9, 0,
+ 7, 3};
+
+ private final int MYS_CHN_CNT = 8;
+ private final double[] MYSTableOfFreq = new double[]{
+ 919.75, 920.25, 920.75, 921.25, 921.75,
+ 922.25, 922.75, 923.25};
+ private final int[] mysFreqTable = new int[]{
+ 0x00180E5F, //919.75MHz
+ 0x00180E65, //921.25MHz
+ 0x00180E6B, //922.75MHz
+ 0x00180E61, //920.25MHz
+ 0x00180E67, //921.75MHz
+ 0x00180E6D, //923.25MHz
+ 0x00180E63, //920.75MHz
+ 0x00180E69, //922.25MHz
+ };
+ private final int[] mysFreqSortedIdx = new int[]{
+ 0, 3, 6, 1, 4,
+ 7, 2, 5};
+
+ private final int ZA_CHN_CNT = 16;
+ private final double[] ZATableOfFreq = new double[]{
+ 915.7, 915.9, 916.1, 916.3, 916.5,
+ 916.7, 916.9, 917.1, 917.3, 917.5,
+ 917.7, 917.9, 918.1, 918.3, 918.5,
+ 918.7};
+ private final int[] zaFreqTable = new int[]{
+ 0x003C23C5, //915.7 MHz
+ 0x003C23C7, //915.9 MHz
+ 0x003C23C9, //916.1 MHz
+ 0x003C23CB, //916.3 MHz
+ 0x003C23CD, //916.5 MHz
+ 0x003C23CF, //916.7 MHz
+ 0x003C23D1, //916.9 MHz
+ 0x003C23D3, //917.1 MHz
+ 0x003C23D5, //917.3 MHz
+ 0x003C23D7, //917.5 MHz
+ 0x003C23D9, //917.7 MHz
+ 0x003C23DB, //917.9 MHz
+ 0x003C23DD, //918.1 MHz
+ 0x003C23DF, //918.3 MHz
+ 0x003C23E1, //918.5 MHz
+ 0x003C23E3, //918.7 MHz
+ };
+ private final int[] zaFreqSortedIdx = new int[]{
+ 0, 1, 2, 3, 4,
+ 5, 6, 7, 8, 9,
+ 10, 11, 12, 13, 14,
+ 15};
+
+ final int ID_CHN_CNT = 4;
+ private final double[] IDTableOfFreq = new double[]{
+ 923.25, 923.75, 924.25, 924.75};
+ private final int[] indonesiaFreqTable = new int[]{
+ 0x00180E6D, //923.25 MHz
+ 0x00180E6F,//923.75 MHz
+ 0x00180E71,//924.25 MHz
+ 0x00180E73,//924.75 MHz
+ };
+ private final int[] indonesiaFreqSortedIdx = new int[]{
+ 0, 1, 2, 3};
+
+ private final int IL_CHN_CNT = 7;
+ private final double[] ILTableOfFreq = new double[]{
+ 915.25, 915.5, 915.75, 916.0, 916.25, // 4
+ 916.5, 916.75};
+ private final int[] ilFreqTable = new int[]{
+ 0x00180E4D, //915.25 MHz
+ 0x00180E51, //916.25 MHz
+ 0x00180E4E, //915.5 MHz
+ 0x00180E52, //916.5 MHz
+ 0x00180E4F, //915.75 MHz
+ 0x00180E53, //916.75 MHz
+ 0x00180E50, //916.0 MHz
+ };
+ private final int[] ilFreqSortedIdx = new int[]{
+ 0, 4, 1, 5, 2, 6, 3};
+
+ private final int IL2019RW_CHN_CNT = 5;
+ private final double[] IL2019RWTableOfFreq = new double[]{
+ 915.9, 916.025, 916.15, 916.275, 916.4};
+ private final int[] il2019RwFreqTable = new int[]{
+ 0x003C23C7, //915.9 MHz
+ 0x003C23C8, //916.025 MHz
+ 0x003C23C9, //916.15 MHz
+ 0x003C23CA, //916.275 MHz
+ 0x003C23CB, //916.4 MHz
+ };
+ private final int[] il2019RwFreqSortedIdx = new int[]{
+ 0, 4, 1, 2, 3};
+
+ private final int PH_CHN_CNT = 8;
+ private final double[] PHTableOfFreq = new double[]{
+ 918.125, 918.375, 918.625, 918.875, 919.125, // 5
+ 919.375, 919.625, 919.875};
+ private final int[] phFreqTable = new int[]{
+ 0x00301CB1, //918.125MHz Channel 0
+ 0x00301CBB, //919.375MHz Channel 5
+ 0x00301CB7, //918.875MHz Channel 3
+ 0x00301CBF, //919.875MHz Channel 7
+ 0x00301CB3, //918.375MHz Channel 1
+ 0x00301CBD, //919.625MHz Channel 6
+ 0x00301CB5, //918.625MHz Channel 2
+ 0x00301CB9, //919.125MHz Channel 4
+ };
+ private final int[] phFreqSortedIdx = new int[]{
+ 0, 5, 3, 7, 1, 6, 2, 4};
+
+ private int NZ_CHN_CNT = 11;
+ private final double[] NZTableOfFreq = new double[]{
+ 922.25, 922.75, 923.25, 923.75, 924.25,// 4
+ 924.75, 925.25, 925.75, 926.25, 926.75,// 9
+ 927.25};
+ private final int[] nzFreqTable = new int[]{
+ 0x00180E71, //924.25 MHz
+ 0x00180E77, //925.75 MHz
+ 0x00180E69, //922.25 MHz
+ 0x00180E7B, //926.75 MHz
+ 0x00180E6D, //923.25 MHz
+ 0x00180E7D, //927.25 MHz
+ 0x00180E75, //925.25 MHz
+ 0x00180E6B, //922.75 MHz
+ 0x00180E79, //926.25 MHz
+ 0x00180E6F, //923.75 MHz
+ 0x00180E73, //924.75 MHz
+ };
+ private final int[] nzFreqSortedIdx = new int[]{
+ 4, 7, 0, 9, 2, 10, 6, 1, 8, 3, 5};
+
+ private final int CN_CHN_CNT = 16;
+ private final double[] CHNTableOfFreq = new double[]{
+ 920.625, 920.875, 921.125, 921.375, 921.625, 921.875, 922.125, 922.375, 922.625, 922.875,
+ 923.125, 923.375, 923.625, 923.875, 924.125, 924.375};
+ private final int[] cnFreqTable = new int[]{
+ 0x00301CD3, //922.375MHz
+ 0x00301CD1, //922.125MHz
+ 0x00301CCD, //921.625MHz
+ 0x00301CC5, //920.625MHz
+ 0x00301CD9, //923.125MHz
+ 0x00301CE1, //924.125MHz
+ 0x00301CCB, //921.375MHz
+ 0x00301CC7, //920.875MHz
+ 0x00301CD7, //922.875MHz
+ 0x00301CD5, //922.625MHz
+ 0x00301CC9, //921.125MHz
+ 0x00301CDF, //923.875MHz
+ 0x00301CDD, //923.625MHz
+ 0x00301CDB, //923.375MHz
+ 0x00301CCF, //921.875MHz
+ 0x00301CE3, //924.375MHz
+ };
+ private final int[] cnFreqSortedIdx = new int[]{
+ 7, 6, 4, 0, 10,
+ 14, 3, 1, 9, 8,
+ 2, 13, 12, 11, 5,
+ 15};
+
+ private final int UH1_CHN_CNT = 10;
+ private final double[] UH1TableOfFreq = new double[]{
+ 915.25, 915.75, 916.25, 916.75, 917.25,
+ 917.75, 918.25, 918.75, 919.25, 919.75};
+ private final int[] uh1FreqTable = new int[]{
+ 0x00180E4F, //915.75 MHz
+ 0x00180E4D, //915.25 MHz
+ 0x00180E5D, //919.25 MHz
+ 0x00180E5B, //918.75 MHz
+ 0x00180E57, //917.75 MHz
+ 0x00180E55, //917.25 MHz
+ 0x00180E59, //918.25 MHz
+ 0x00180E51, //916.25 MHz
+ 0x00180E5F, //919.75 MHz
+ 0x00180E53, //916.75 MHz
+ };
+ private final int[] uh1FreqSortedIdx = new int[]{
+ 1, 0, 8, 7, 5,
+ 4, 6, 2, 9, 3};
+
+ private final int UH2_CHN_CNT = 15;
+ private final double[] UH2TableOfFreq = new double[]{
+ 920.25, 920.75, 921.25, 921.75, 922.25, // 4
+ 922.75, 923.25, 923.75, 924.25, 924.75, // 9
+ 925.25, 925.75, 926.25, 926.75, 927.25};
+ private final int[] uh2FreqTable = new int[]{
+ 0x00180E7B, //926.75 MHz
+ 0x00180E79, //926.25 MHz
+ 0x00180E7D, //927.25 MHz
+ 0x00180E61, //920.25 MHz
+ 0x00180E75, //925.25 MHz
+ 0x00180E67, //921.75 MHz
+ 0x00180E69, //922.25 MHz
+ 0x00180E73, //924.75 MHz
+ 0x00180E6F, //923.75 MHz
+ 0x00180E77, //925.75 MHz
+ 0x00180E71, //924.25 MHz
+ 0x00180E65, //921.25 MHz
+ 0x00180E63, //920.75 MHz
+ 0x00180E6B, //922.75 MHz
+ 0x00180E6D, //923.25 MHz
+ };
+ private final int[] uh2FreqSortedIdx = new int[]{
+ 13, 12, 14, 0, 10,
+ 3, 4, 9, 7, 11,
+ 8, 2, 1, 5, 6,};
+
+ private final int LH_CHN_CNT = 26;
+ private double[] LHTableOfFreq = new double[]{
+ 902.75, 903.25, 903.75, 904.25, 904.75, // 4
+ 905.25, 905.75, 906.25, 906.75, 907.25, // 9
+ 907.75, 908.25, 908.75, 909.25, 909.75, // 14
+ 910.25, 910.75, 911.25, 911.75, 912.25, // 19
+ 912.75, 913.25, 913.75, 914.25, 914.75, // 24
+ 915.25, // 25
+ //915.75, 916.25, 916.75, 917.25, 917.75,
+ //918.25, 918.75, 919.25, 919.75, 920.25,
+ //920.75, 921.25, 921.75, 922.25, 922.75,
+ //923.25, 923.75, 924.25, 924.75, 925.25,
+ //925.75, 926.25, 926.75, 927.25,
+ };
+ private final int[] lhFreqTable = new int[]{
+ 0x00180E1B, //902.75 MHz
+ 0x00180E35, //909.25 MHz
+ 0x00180E1D, //903.25 MHz
+ 0x00180E37, //909.75 MHz
+ 0x00180E1F, //903.75 MHz
+ 0x00180E39, //910.25 MHz
+ 0x00180E21, //904.25 MHz
+ 0x00180E3B, //910.75 MHz
+ 0x00180E23, //904.75 MHz
+ 0x00180E3D, //911.25 MHz
+ 0x00180E25, //905.25 MHz
+ 0x00180E3F, //911.75 MHz
+ 0x00180E27, //905.75 MHz
+ 0x00180E41, //912.25 MHz
+ 0x00180E29, //906.25 MHz
+ 0x00180E43, //912.75 MHz
+ 0x00180E2B, //906.75 MHz
+ 0x00180E45, //913.25 MHz
+ 0x00180E2D, //907.25 MHz
+ 0x00180E47, //913.75 MHz
+ 0x00180E2F, //907.75 MHz
+ 0x00180E49, //914.25 MHz
+ 0x00180E31, //908.25 MHz
+ 0x00180E4B, //914.75 MHz
+ 0x00180E33, //908.75 MHz
+ 0x00180E4D, //915.25 MHz
+
+
+ //0x00180E4F, //915.75 MHz
+ //0x00180E7B, //926.75 MHz
+ //0x00180E79, //926.25 MHz
+ //0x00180E7D, //927.25 MHz
+ //0x00180E61, //920.25 MHz
+ //0x00180E5D, //919.25 MHz
+ //0x00180E5B, //918.75 MHz
+ //0x00180E57, //917.75 MHz
+ //0x00180E75, //925.25 MHz
+ //0x00180E67, //921.75 MHz
+ //0x00180E69, //922.25 MHz
+ //0x00180E55, //917.25 MHz
+ //0x00180E59, //918.25 MHz
+ //0x00180E51, //916.25 MHz
+ //0x00180E73, //924.75 MHz
+ //0x00180E5F, //919.75 MHz
+ //0x00180E53, //916.75 MHz
+ //0x00180E6F, //923.75 MHz
+ //0x00180E77, //925.75 MHz
+ //0x00180E71, //924.25 MHz
+ //0x00180E65, //921.25 MHz
+ //0x00180E63, //920.75 MHz
+ //0x00180E6B, //922.75 MHz
+ //0x00180E6D, //923.25 MHz
+ };
+ private final int[] lhFreqSortedIdx = new int[]{
+ 0, 13, 1, 14, 2,
+ 15, 3, 16, 4, 17,
+ 5, 18, 6, 19, 7,
+ 20, 8, 21, 9, 22,
+ 10, 23, 11, 24, 12,
+ 25};
+
+ private final int LH1_CHN_CNT = 14;
+ private double[] LH1TableOfFreq = new double[]{
+ 902.75, 903.25, 903.75, 904.25, 904.75, // 4
+ 905.25, 905.75, 906.25, 906.75, 907.25, // 9
+ 907.75, 908.25, 908.75, 909.25, // 13
+ };
+ private final int[] lh1FreqTable = new int[]{
+ 0x00180E1B, //902.75 MHz
+ 0x00180E35, //909.25 MHz
+ 0x00180E1D, //903.25 MHz
+ 0x00180E1F, //903.75 MHz
+ 0x00180E21, //904.25 MHz
+ 0x00180E23, //904.75 MHz
+ 0x00180E25, //905.25 MHz
+ 0x00180E27, //905.75 MHz
+ 0x00180E29, //906.25 MHz
+ 0x00180E2B, //906.75 MHz
+ 0x00180E2D, //907.25 MHz
+ 0x00180E2F, //907.75 MHz
+ 0x00180E31, //908.25 MHz
+ 0x00180E33, //908.75 MHz
+ };
+ private final int[] lh1FreqSortedIdx = new int[]{
+ 0, 13, 1, 2, 3,
+ 4, 5, 6, 7, 8,
+ 9, 10, 11, 12};
+
+ private final int LH2_CHN_CNT = 11;
+ private double[] LH2TableOfFreq = new double[]{
+ 909.75, 910.25, 910.75, 911.25, 911.75, // 4
+ 912.25, 912.75, 913.25, 913.75, 914.25, // 9
+ 914.75};
+ private final int[] lh2FreqTable = new int[]{
+ 0x00180E37, //909.75 MHz
+ 0x00180E39, //910.25 MHz
+ 0x00180E3B, //910.75 MHz
+ 0x00180E3D, //911.25 MHz
+ 0x00180E3F, //911.75 MHz
+ 0x00180E41, //912.25 MHz
+ 0x00180E43, //912.75 MHz
+ 0x00180E45, //913.25 MHz
+ 0x00180E47, //913.75 MHz
+ 0x00180E49, //914.25 MHz
+ 0x00180E4B, //914.75 MHz
+ };
+ private final int[] lh2FreqSortedIdx = new int[]{
+ 0, 1, 2, 3, 4,
+ 5, 6, 7, 8, 9,
+ 10};
+
+ private final int ETSI_CHN_CNT = 4;
+ private final double[] ETSITableOfFreq = new double[]{
+ 865.70, 866.30, 866.90, 867.50};
+ private final int[] etsiFreqTable = new int[]{
+ 0x003C21D1, //865.700MHz
+ 0x003C21D7, //866.300MHz
+ 0x003C21DD, //866.900MHz
+ 0x003C21E3, //867.500MHz
+ };
+ private final int[] etsiFreqSortedIdx = new int[]{
+ 0, 1, 2, 3};
+
+ private final int IDA_CHN_CNT = 3;
+ private final double[] IDATableOfFreq = new double[]{
+ 865.70, 866.30, 866.90};
+ private final int[] indiaFreqTable = new int[]{
+ 0x003C21D1, //865.700MHz
+ 0x003C21D7, //866.300MHz
+ 0x003C21DD, //866.900MHz
+ };
+ private final int[] indiaFreqSortedIdx = new int[]{
+ 0, 1, 2};
+
+ private final int KR_CHN_CNT = 19;
+ private final double[] KRTableOfFreq = new double[]{
+ 910.20, 910.40, 910.60, 910.80, 911.00, 911.20, 911.40, 911.60, 911.80, 912.00,
+ 912.20, 912.40, 912.60, 912.80, 913.00, 913.20, 913.40, 913.60, 913.80};
+ private int[] krFreqTable = new int[]{
+ 0x003C23A8, //912.8MHz 13
+ 0x003C23A0, //912.0MHz 9
+ 0x003C23AC, //913.2MHz 15
+ 0x003C239E, //911.8MHz 8
+ 0x003C23A4, //912.4MHz 11
+ 0x003C23B2, //913.8MHz 18
+ 0x003C2392, //910.6MHz 2
+ 0x003C23B0, //913.6MHz 17
+ 0x003C2390, //910.4MHz 1
+ 0x003C239C, //911.6MHz 7
+ 0x003C2396, //911.0MHz 4
+ 0x003C23A2, //912.2MHz 10
+ 0x003C238E, //910.2MHz 0
+ 0x003C23A6, //912.6MHz 12
+ 0x003C2398, //911.2MHz 5
+ 0x003C2394, //910.8MHz 3
+ 0x003C23AE, //913.4MHz 16
+ 0x003C239A, //911.4MHz 6
+ 0x003C23AA, //913.0MHz 14
+ };
+ private final int[] krFreqSortedIdx = new int[]{
+ 13, 9, 15, 8, 11,
+ 18, 2, 17, 1, 7,
+ 4, 10, 0, 12, 5,
+ 3, 16, 6, 14};
+
+ private final int KR2017RW_CHN_CNT = 6;
+ private final double[] KR2017RwTableOfFreq = new double[]{
+ 917.30, 917.90, 918.50, 919.10, 919.70, 920.30};
+ private int[] kr2017RwFreqTable = new int[]{
+ 0x003C23D5, // 917.3 -> 917.25 MHz Channel 1
+ 0x003C23DB, //917.9 -> 918 MHz Channel 2
+ 0x003C23E1, //918.5 MHz Channel 3
+ 0x003C23E7, //919.1 -> 919 MHz Channel 4
+ 0x003C23ED, //919.7 -> 919.75 MHz Channel 5
+ 0x003C23F3 // 920.3 -> 920.25 MHz Channel 6
+ };
+ private final int[] kr2017RwFreqSortedIdx = new int[]{
+ 3, 0, 5, 1, 4, 2};
+
+ private final int JPN2012_CHN_CNT = 4;
+ private final double[] JPN2012TableOfFreq = new double[]{
+ 916.80, 918.00, 919.20, 920.40};
+ private final int[] jpn2012FreqTable = new int[]{
+ 0x003C23D0, //916.800MHz Channel 1
+ 0x003C23DC, //918.000MHz Channel 2
+ 0x003C23E8, //919.200MHz Channel 3
+ 0x003C23F4, //920.400MHz Channel 4
+ //0x003C23F6, //920.600MHz Channel 5
+ //0x003C23F8, //920.800MHz Channel 6
+ };
+ private final int[] jpn2012FreqSortedIdx = new int[]{
+ 0, 1, 2, 3};
+
+ private final int JPN2012A_CHN_CNT = 6;
+ private final double[] JPN2012ATableOfFreq = new double[]{
+ 916.80, 918.00, 919.20, 920.40, 920.60, 920.80};
+ private final int[] jpn2012AFreqTable = new int[]{
+ 0x003C23D0, //916.800MHz Channel 1
+ 0x003C23DC, //918.000MHz Channel 2
+ 0x003C23E8, //919.200MHz Channel 3
+ 0x003C23F4, //920.400MHz Channel 4
+ 0x003C23F6, //920.600MHz Channel 5
+ 0x003C23F8, //920.800MHz Channel 6
+ };
+ private final int[] jpn2012AFreqSortedIdx = new int[]{
+ 0, 1, 2, 3, 4, 5};
+
+ private final int ETSIUPPERBAND_CHN_CNT = 4;
+ private final double[] ETSIUPPERBANDTableOfFreq = new double[]{
+ 916.3, 917.5, 918.7, 919.9};
+ private final int[] etsiupperbandFreqTable = new int[]{
+ 0x003C23CB, //916.3 MHz
+ 0x003C23D7, //917.5 MHz
+ 0x003C23E3, //918.7 MHz
+ 0x003C23EF, //919.9 MHz
+ };
+ private final int[] etsiupperbandFreqSortedIdx = new int[]{
+ 0, 1, 2, 3};
+
+ private final int VN1_CHN_CNT = 3;
+ private final double[] VN1TableOfFreq = new double[]{
+ 866.30, 866.90, 867.50};
+ private final int[] vietnam1FreqTable = new int[]{
+ 0x003C21D7, //866.300MHz
+ 0x003C21DD, //866.900MHz
+ 0x003C21E3, //867.500MHz
+ };
+ private final int[] vietnam1FreqSortedIdx = new int[]{
+ 0, 1, 2};
+
+ private final int VN2_CHN_CNT = 8;
+ private final double[] VN2TableOfFreq = new double[]{
+ 918.75, 919.25, 919.75, 920.25, 920.75, 921.25, 921.75, 922.25};
+ private final int[] vietnam2FreqTable = new int[]{
+ 0x00180E61, //920.25 MHz
+ 0x00180E5D, //919.25 MHz
+ 0x00180E5B, //918.75 MHz
+ 0x00180E67, //921.75 MHz
+ 0x00180E69, //922.25 MHz
+ 0x00180E5F, //919.75 MHz
+ 0x00180E65, //921.25 MHz
+ 0x00180E63, //920.75 MHz
+ };
+ private final int[] vietnam2FreqSortedIdx = new int[]{
+ 3, 1, 0, 6, 7, 2, 5, 4};
+
+ private final int VN3_CHN_CNT = 4;
+ private final double[] VN3TableOfFreq = new double[]{
+ 920.75, 921.25, 921.75, 922.25};
+ private final int[] vietnam3FreqTable = new int[]{
+ 0x00180E67, //921.75 MHz
+ 0x00180E69, //922.25 MHz
+ 0x00180E65, //921.25 MHz
+ 0x00180E63, //920.75 MHz
+ };
+ private final int[] vietnam3FreqSortedIdx = new int[]{
+ 2, 3, 1, 0};
+
+ public final int iCountryEnumInfoColumn = 7;
+ public String[] strCountryEnumInfo = {
+ "1", "Albania1", "-1", "4", "Fixed", "600", "865.7",
+ "2", "Albania2", "-2 RW", "23", "Hop", "250", "915.25",
+ "3", "Algeria1", "-1", "4", "Fixed", "600", "871.6",
+ "4", "Algeria2", "-1", "4", "Fixed", "600", "881.6",
+ "5", "Algeria3", "-9", "3", "Fixed", "1200", "916.3",
+ "6", "Algeria4", "-7", "2", "Fixed", "500", "925.25",
+ "7", "Argentina", "-2 RW", "50", "Hop", "500", "902.75",
+ "8", "Armenia", "-1", "4", "Fixed", "600", "865.7",
+ "9", "Australia1", "-2 AS", "10", "Hop", "500", "920.75",
+ "10", "Australia2", "-2 AS", "14", "Hop", "500", "918.75",
+ "11", "Austria1", "-1", "4", "Fixed", "600", "865.7",
+ "12", "Austria2", "-9", "3", "Fixed", "1200", "916.3",
+ "13", "Azerbaijan", "-1", "4", "Fixed", "600", "865.7",
+ "14", "Bahrain", "-1", "4", "Fixed", "600", "865.7",
+ "15", "Bangladesh", "-1", "4", "Fixed", "600", "865.7",
+ "16", "Belarus", "-1", "4", "Fixed", "600", "865.7",
+ "17", "Belgium1", "-1", "4", "Fixed", "600", "865.7",
+ "18", "Belgium2", "-9", "3", "Fixed", "1200", "916.3",
+ "19", "Bolivia", "-2", "50", "Hop", "500", "902.75",
+ "20", "Bosnia", "-1", "4", "Fixed", "600", "865.7",
+ "21", "Botswana", "-1", "4", "Fixed", "600", "865.7",
+ "22", "Brazil1", "-2 RW", "9", "Fixed", "500", "902.75",
+ "23", "Brazil2", "-2 RW", "24", "Fixed", "500", "915.75",
+ "24", "Brunei1", "-1", "4", "Fixed", "600", "865.7",
+ "25", "Brunei2", "-7", "7", "Fixed", "250", "923.25",
+ "26", "Blgaria1", "-1", "4", "Fixed", "600", "865.7",
+ "27", "Bulgaria2", "-9", "3", "Fixed", "1200", "916.3",
+ "28", "Cambodia", "-7", "16", "Hop", "250", "920.625",
+ "29", "Cameroon", "-1", "4", "Fixed", "600", "865.7",
+ "30", "Canada", "-2", "50", "Hop", "500", "902.75",
+ "31", "Chile1", "-2 RW", "3", "Fixed", "1200", "916.3",
+ "32", "Chile2", "-2 RW", "24", "Hop", "500", "915.75",
+ "33", "Chile3", "-2 RW", "4", "Hop", "500", "925.75",
+ "34", "China", "-7", "16", "Hop", "250", "920.625",
+ "35", "Colombia", "-2 RW", "50", "Hop", "500", "902.75",
+ "36", "Congo", "-1", "4", "Fixed", "600", "865.7",
+ "37", "CostaRica", "-2 RW", "50", "Hop", "500", "902.75",
+ "38", "Cotedlvoire", "-1", "4", "Fixed", "600", "865.7",
+ "39", "Croatia", "-1", "4", "Fixed", "600", "865.7",
+ "40", "Cuba", "-2 RW", "50", "Hop", "500", "902.75",
+ "41", "Cyprus1", "-1", "4", "Fixed", "600", "865.7",
+ "42", "Cyprus2", "-9", "3", "Fixed", "1200", "916.3",
+ "43", "Czech1", "-1", "4", "Fixed", "600", "865.7",
+ "44", "Czech2", "-9", "3", "Fixed", "1200", "916.3",
+ "45", "Denmark1", "-1", "4", "Fixed", "600", "865.7",
+ "46", "Denmark2", "-9", "3", "Fixed", "1200", "916.3",
+ "47", "Dominican", "-2 RW", "50", "Hop", "500", "902.75",
+ "48", "Ecuador", "-2 RW", "50", "Hop", "500", "902.75",
+ "49", "Egypt", "-1", "4", "Fixed", "600", "865.7",
+ "50", "ElSalvador", "-2 RW", "50", "Hop", "500", "902.75",
+ "51", "Estonia", "-1", "4", "Fixed", "600", "865.7",
+ "52", "Finland1", "-1", "4", "Fixed", "600", "865.7",
+ "53", "Finland2", "-9", "3", "Fixed", "1200", "916.3",
+ "54", "France", "-1", "4", "Fixed", "600", "865.7",
+ "55", "Georgia", "-1", "4", "Fixed", "600", "865.7",
+ "56", "Germany", "-1", "4", "Fixed", "600", "865.7",
+ "57", "Ghana", "-1", "4", "Fixed", "600", "865.7",
+ "58", "Greece", "-1", "4", "Fixed", "600", "865.7",
+ "59", " Guatemala", "-2 RW", "50", "Hop", "500", "902.75",
+ "60", "HongKong1", "-1", "4", "Fixed", "600", "865.7",
+ "61", "HongKong2", "-2 OFCA", "50", "Hop", "50", "921.25",
+ "62", "Hungary1", "-1", "4", "Fixed", "600", "865.7",
+ "63", "Hungary2", "-9", "3", "Fixed", "1200", "916.3",
+ "64", "Iceland", "-1", "4", "Fixed", "600", "865.7",
+ "65", "India", "-1", "3", "Fixed", "600", "865.7",
+ "66", "Indonesia", "-7", "4", "Hop", "500", "923.75",
+ "67", "Iran", "-1", "4", "Fixed", "600", "865.7",
+ "68", "Ireland1", "-1", "4", "Fixed", "600", "865.7",
+ "69", "Ireland2", "-9", "3", "Fixed", "1200", "916.3",
+ "70", "Israel", "-9", "3", "Fixed", "500", "915.5",
+ "71", "Italy", "-1", "4", "Fixed", "600", "865.7",
+ "72", "Jamaica", "-2 RW", "50", "Hop", "500", "902.75",
+ "73", "Japan4", "-8", "4", "Fixed", "1200", "916.8",
+ "74", "Japan6", "-8", "6", "Fixed", "1200", "916.8",
+ "75", "Jordan", "-1", "4", "Fixed", "600", "865.7",
+ "76", "Kazakhstan", "-1", "4", "Fixed", "600", "865.7",
+ "77", "Kenya", "-1", "4", "Fixed", "600", "865.7",
+ "78", "Korea", "-6", "6", "Hop", "600", "917.3",
+ "79", "KoreaDPR", "-7", "16", "Hop", "250", "920.625",
+ "80", "Kuwait", "-1", "4", "Fixed", "600", "865.7",
+ "81", "Kyrgyz", "-1", "4", "Fixed", "600", "865.7",
+ "82", "Latvia", "-1", "4", "Fixed", "600", "865.7",
+ "83", "Lebanon", "-1", "4", "Fixed", "600", "865.7",
+ "84", "Libya", "-1", "4", "Fixed", "600", "865.7",
+ "85", "Liechtenstein1", "-1", "4", "Fixed", "600", "865.7",
+ "86", "Liechtenstein2", "-9", "3", "Fixed", "1200", "916.3",
+ "87", "Lithuania1", "-1", "4", "Fixed", "600", "865.7",
+ "88", "Lithuania2", "-9", "3", "Fixed", "1200", "916.3",
+ "89", "Luxembourg1", "-1", "4", "Fixed", "600", "865.7",
+ "90", "Luxembourg2", "-9", "3", "Fixed", "1200", "916.3",
+ "91", "Macao", "-7", "16", "Hop", "250", "920.625",
+ "92", "Macedonia", "-1", "4", "Fixed", "600", "865.7",
+ "93", "Malaysia", "-7", "6", "Hop", "500", "919.75",
+ "94", "Malta1", "-1", "4", "Fixed", "600", "865.7",
+ "95", "Malta2", "-9", "3", "Fixed", "1200", "916.3",
+ "96", "Mauritius", "-1", "4", "Fixed", "600", "865.7",
+ "97", "Mexico", "-2", "50", "Hop", "500", "902.75",
+ "98", "Moldova1", "-1", "4", "Fixed", "600", "865.7",
+ "99", "Moldova2", "-9", "3", "Fixed", "1200", "916.3",
+ "100", "Mongolia", "-7", "16", "Hop", "250", "920.625",
+ "101", "Montenegro", "-1", "4", "Fixed", "600", "865.7",
+ "102", "Morocco", "-1", "4", "Fixed", "600", "865.7",
+ "103", "Netherlands", "-1", "4", "Fixed", "600", "865.7",
+ "104", "NewZealand1", "-1", "4", "Hop", "500", "864.75",
+ "105", "NewZealand2", "-2 NZ", "14", "Hop", "500", "920.75",
+ "106", "Nicaragua", "-2 RW", "50", "Hop", "500", "902.75",
+ "107", "Nigeria", "-1", "4", "Fixed", "600", "865.7",
+ "108", "Norway1", "-1", "4", "Fixed", "600", "865.7",
+ "109", "Norway2", "-9", "3", "Fixed", "1200", "916.3",
+ "110", "Oman", "-1", "4", "Fixed", "600", "865.7",
+ "111", "Pakistan", "-1", "4", "Fixed", "600", "865.7",
+ "112", "Panama", "-2 RW", "50", "Hop", "500", "902.75",
+ "113", "Paraguay", "-2 RW", "50", "Hop", "500", "902.75",
+ "114", "Peru", "-2 RW", "24", "Hop", "500", "915.75",
+ "115", "Philippines", "-2 RW", "50", "Hop", "250", "918.125",
+ "116", "Poland", "-1", "4", "Fixed", "600", "865.7",
+ "117", "Portugal", "-1", "4", "Fixed", "600", "865.7",
+ "118", "Romania", "-1", "4", "Fixed", "600", "865.7",
+ "119", "Russia1", "-1", "4", "Fixed", "600", "866.3",
+ "120", "Russia3", "-9", "4", "Fixed", "1200", "915.6",
+ "121", "Senegal", "-1", "4", "Fixed", "600", "865.7",
+ "122", "Serbia", "-1", "4", "Fixed", "600", "865.7",
+ "123", "Singapore1", "-1", "4", "Fixed", "600", "865.7",
+ "124", "Singapore2", "-2 RW", "8", "Hop", "500", "920.75",
+ "125", "Slovak1", "-1", "4", "Fixed", "600", "865.7",
+ "126", "Slovak2", "-9", "3", "Fixed", "1200", "916.3",
+ "127", "Slovenia1", "-1", "4", "Fixed", "600", "865.7",
+ "128", "Solvenia2", "-9", "3", "Fixed", "1200", "916.3",
+ "129", "SAfrica1", "-1", "4", "Fixed", "600", "865.7",
+ "130", "SAfrica2", "-9", "7", "Fixed", "500", "915.7",
+ "131", "Spain", "-1", "4", "Fixed", "600", "865.7",
+ "132", "SriLanka", "-1", "4", "Fixed", "600", "865.7",
+ "133", "Sudan", "-1", "4", "Fixed", "600", "865.7",
+ "134", "Sweden1", "-1", "4", "Fixed", "600", "865.7",
+ "135", "Sweden2", "-9", "3", "Fixed", "1200", "916.3",
+ "136", "Switzerland1", "-1", "4", "Fixed", "600", "865.7",
+ "137", "Switzerland2", "-9", "3", "Fixed", "1200", "916.3",
+ "138", "Syria", "-1", "4", "Fixed", "600", "865.7",
+ "139", "Taiwan1", "-4", "12", "Hop", "375", "922.875",
+ "140", "Taiwan2", "-4", "12", "Hop", "375", "922.875",
+ "141", "Tajikistan", "-1", "4", "Fixed", "600", "865.7",
+ "142", "Tanzania", "-1", "4", "Fixed", "600", "865.7",
+ "143", "Thailand", "-2 RW", "8", "Hop", "500", "920.75",
+ "144", "Trinidad", "-2 RW", "50", "Hop", "500", "902.75",
+ "145", "Tunisia", "-1", "4", "Fixed", "600", "865.7",
+ "146", "Turkey", "-1", "4", "Fixed", "600", "865.7",
+ "147", "Turkmenistan", "-1", "4", "Fixed", "600", "865.7",
+ "148", "Uganda", "-1", "4", "Fixed", "600", "865.7",
+ "149", "Ukraine", "-1", "4", "Fixed", "600", "865.7",
+ "150", "UAE", "-1", "4", "Fixed", "600", "865.7",
+ "151", "UK1", "-1", "4", "Fixed", "600", "865.7",
+ "152", "UK2", "-9", "3", "Fixed", "1200", "916.3",
+ "153", "USA", "-2", "50", "Hop", "500", "902.75",
+ "154", "Uruguay", "-2 RW", "50", "Hop", "500", "902.75",
+ "155", "Venezuela", "-2 RW", "50", "Hop", "500", "902.75",
+ "156", "Vietnam1", "-1", "4", "Fixed", "600", "866.3",
+ "157", "Vietnam2", "-7", "16", "Hop", "500", "918.75",
+ "158", "Yemen", "-1", "4", "Fixed", "600", "865.7",
+ "159", "Zimbabwe", "-1", "4", "Fixed", "600", "865.7",
+ "160", "Vietnam3", "-7", "4", "Hop", "500", "920.75"
+ };
+ }
+/*
+ boolean setChannelData(RegionCodes regionCode) {
+ return true;
+ }
+ private void SetFrequencyBand (UInt32 frequencySelector, BandState config, UInt32 multdiv, UInt32 pllcc)
+ {
+ MacWriteRegister(MACREGISTER.HST_RFTC_FRQCH_SEL, frequencySelector);
+
+ MacWriteRegister(MACREGISTER.HST_RFTC_FRQCH_CFG, (uint)config);
+
+ if (config == BandState.ENABLE)
+ {
+ MacWriteRegister(MACREGISTER.HST_RFTC_FRQCH_DESC_PLLDIVMULT, multdiv);
+
+ MacWriteRegister(MACREGISTER.HST_RFTC_FRQCH_DESC_PLLDACCTL, pllcc);
+ }
+ }
+*/
+ public double[] GetAvailableFrequencyTable(RegionCodes regionCode) {
+ double[] freqText = null;
+ if (bis108) {
+ switch (regionCode) {
+ case FCC:
+ case AG:
+ case CL:
+ case CO:
+ case CR:
+ case DR:
+ case MX:
+ case PM:
+ case UG:
+// switch (mRfidDevice.mRx000Device.mRx000OemSetting.getVersionCode()) {
+// case 0:
+// return FCCTableOfFreq0;
+// case 1:
+// return FCCTableOfFreq1;
+// default:
+// return FCCTableOfFreq;
+// }
+ return countryChannelData.FCCTableOfFreq;
+ case PR:
+ return countryChannelData.PRTableOfFreq;
+ case VZ:
+ return countryChannelData.VZTableOfFreq;
+ case AU:
+ return countryChannelData.AUSTableOfFreq;
+ case BR1:
+ return countryChannelData.BR1TableOfFreq;
+ case BR2:
+ return countryChannelData.BR2TableOfFreq;
+ case BR3:
+ return countryChannelData.BR3TableOfFreq;
+ case BR4:
+ return countryChannelData.BR4TableOfFreq;
+ case BR5:
+ return countryChannelData.BR5TableOfFreq;
+ case HK:
+ case SG:
+ case TH:
+ case VN:
+ return countryChannelData.HKTableOfFreq;
+ case VN1:
+ return countryChannelData.VN1TableOfFreq;
+ case VN2:
+ return countryChannelData.VN2TableOfFreq;
+ case VN3:
+ return countryChannelData.VN3TableOfFreq;
+ case BD:
+ return countryChannelData.BDTableOfFreq;
+ case TW:
+ return countryChannelData.TWTableOfFreq;
+ case MY:
+ return countryChannelData.MYSTableOfFreq;
+ case ZA:
+ return countryChannelData.ZATableOfFreq;
+ case ID:
+ return countryChannelData.IDTableOfFreq;
+ case IL:
+ return countryChannelData.ILTableOfFreq;
+ case IL2019RW:
+ return countryChannelData.IL2019RWTableOfFreq;
+ case PH:
+ return countryChannelData.PHTableOfFreq;
+ case NZ:
+ return countryChannelData.NZTableOfFreq;
+ case CN:
+ return countryChannelData.CHNTableOfFreq;
+
+ case UH1:
+ return countryChannelData.UH1TableOfFreq;
+ case UH2:
+ return countryChannelData.UH2TableOfFreq;
+ case LH:
+ return countryChannelData.LHTableOfFreq;
+ case LH1:
+ return countryChannelData.LH1TableOfFreq;
+ case LH2:
+ return countryChannelData.LH2TableOfFreq;
+
+ case ETSI:
+ appendToLog("Got ETSI Table of Frequencies");
+ return countryChannelData.ETSITableOfFreq;
+ case IN:
+ return countryChannelData.IDATableOfFreq;
+ case KR:
+ return countryChannelData.KRTableOfFreq;
+ case KR2017RW:
+ return countryChannelData.KR2017RwTableOfFreq;
+ case JP:
+ return countryChannelData.JPN2012TableOfFreq;
+ case JP6:
+ return countryChannelData.JPN2012ATableOfFreq;
+ case ETSIUPPERBAND:
+ return countryChannelData.ETSIUPPERBANDTableOfFreq;
+
+ default:
+ return new double[0];
+ }
+ } else {
+ int iRegionEnum = regionCode.ordinal() - RegionCodes.Albania1.ordinal() + 1;
+ if (DEBUG) appendToLog("regionCode = " + regionCode.toString() + ", iRegionEnum = " + iRegionEnum);
+
+ String strChannelCount = countryChannelData.strCountryEnumInfo[(iRegionEnum - 1) * countryChannelData.iCountryEnumInfoColumn + 3];
+ int iChannelCount = -1;
+ try {
+ iChannelCount = Integer.parseInt(strChannelCount);
+ } catch (Exception ex) { }
+ if (DEBUG) appendToLog("strChannelCount = " + strChannelCount + ", iChannelCount = " + iChannelCount);
+
+ String strChannelSeparation = countryChannelData.strCountryEnumInfo[(iRegionEnum - 1) * countryChannelData.iCountryEnumInfoColumn + 5];
+ int iChannelSeparation = -1;
+ try {
+ iChannelSeparation = Integer.parseInt(strChannelSeparation);
+ } catch (Exception ex) { }
+ if (DEBUG) appendToLog("strChannelSeparation = " + strChannelSeparation + ",iChannelSeparation = " + iChannelSeparation);
+
+ String strChannelFirst = countryChannelData.strCountryEnumInfo[(iRegionEnum - 1) * countryChannelData.iCountryEnumInfoColumn + 6];
+ double dChannelFirst = -1;
+ try {
+ dChannelFirst = Double.parseDouble(strChannelFirst);
+ } catch (Exception ex) { }
+ if (DEBUG) appendToLog("strChannelFirst = " + strChannelFirst + ", dChannelFirst = " + dChannelFirst);
+
+ if (iChannelCount > 0) {
+ freqText = new double[iChannelCount];
+ for (int i = 0; i < iChannelCount; i++) {
+ freqText[i] = dChannelFirst + ((double) iChannelSeparation) / 1000 * i;
+ if (DEBUG) appendToLog("Frequency freqTable[" + i + "] = " + freqText[i]);
+ }
+ }
+ return freqText;
+ }
+ }
+ public int[] FreqIndex(RegionCodes regionCode) {
+ if (bis108) {
+ switch (regionCode) {
+ case FCC:
+ case AG:
+ case CL:
+ case CO:
+ case CR:
+ case DR:
+ case MX:
+ case PM:
+ case UG:
+// switch (mRfidDevice.mRx000Device.mRx000OemSetting.getVersionCode()) {
+// case 0:
+// return fccFreqSortedIdx0;
+// case 1:
+// return fccFreqSortedIdx1;
+// default:
+// return fccFreqSortedIdx;
+// }
+ return countryChannelData.fccFreqSortedIdx;
+ case PR:
+ if (freqSortedIdx == null) {
+ freqSortedIdx = new int[countryChannelData.PRTableOfFreq.length];
+ if (DEBUG) appendToLog("PR: freqSortedIdx size = " + freqSortedIdx.length);
+ ArrayList list = new ArrayList();
+ for (int i = 0; i < freqSortedIdx.length; i++) list.add(new Integer(i));
+ Collections.shuffle(list);
+ for (int i = 0; i < freqSortedIdx.length; i++) {
+ freqSortedIdx[i] = list.get(i);
+ if (DEBUG) appendToLog("PR: Random Value = " + freqSortedIdx[i]);
+ }
+ }
+ return freqSortedIdx;
+ case VZ:
+ return countryChannelData.vzFreqSortedIdx;
+ case AU:
+ return countryChannelData.ausFreqSortedIdx;
+ case BR1:
+ return countryChannelData.br1FreqSortedIdx;
+ case BR2:
+ return countryChannelData.br2FreqSortedIdx;
+ case BR3:
+ return countryChannelData.br3FreqSortedIdx;
+ case BR4:
+ return countryChannelData.br4FreqSortedIdx;
+ case BR5:
+ return countryChannelData.br5FreqSortedIdx;
+ case HK:
+ case SG:
+ case TH:
+ case VN:
+ return countryChannelData.hkFreqSortedIdx;
+ case VN1:
+ return countryChannelData.vietnam1FreqSortedIdx;
+ case VN2:
+ return countryChannelData.vietnam2FreqSortedIdx;
+ case VN3:
+ return countryChannelData.vietnam3FreqSortedIdx;
+ case BD:
+ return countryChannelData.bdFreqSortedIdx;
+ case TW:
+ return countryChannelData.twFreqSortedIdx;
+ case MY:
+ return countryChannelData.mysFreqSortedIdx;
+ case ZA:
+ return countryChannelData.zaFreqSortedIdx;
+ case ID:
+ return countryChannelData.indonesiaFreqSortedIdx;
+ case IL:
+ return countryChannelData.ilFreqSortedIdx;
+ case IL2019RW:
+ return countryChannelData.il2019RwFreqSortedIdx;
+ case PH:
+ return countryChannelData.phFreqSortedIdx;
+ case NZ:
+ return countryChannelData.nzFreqSortedIdx;
+ case CN:
+ return countryChannelData.cnFreqSortedIdx;
+
+ case UH1:
+ return countryChannelData.uh1FreqSortedIdx;
+ case UH2:
+ return countryChannelData.uh2FreqSortedIdx;
+ case LH:
+ return countryChannelData.lhFreqSortedIdx;
+ case LH1:
+ return countryChannelData.lh1FreqSortedIdx;
+ case LH2:
+ return countryChannelData.lh2FreqSortedIdx;
+
+ case ETSI:
+ return countryChannelData.etsiFreqSortedIdx;
+ case IN:
+ return countryChannelData.indiaFreqSortedIdx;
+ case KR:
+ return countryChannelData.krFreqSortedIdx;
+ case KR2017RW:
+ return countryChannelData.kr2017RwFreqSortedIdx;
+ case JP:
+ return countryChannelData.jpn2012FreqSortedIdx;
+ case JP6:
+ return countryChannelData.jpn2012AFreqSortedIdx;
+ case ETSIUPPERBAND:
+ return countryChannelData.etsiupperbandFreqSortedIdx;
+
+ default:
+ return null;
+ }
+ } else {
+ int[] iFreqSortedIdx = null;
+ int iFreqChnCnt = FreqChnCnt(regionCode);
+ if (iFreqChnCnt > 0) {
+ iFreqSortedIdx = new int[iFreqChnCnt];
+ for (int i = 0; i < iFreqChnCnt; i++) {
+ iFreqSortedIdx[i] = (byte)i;
+ if (false) appendToLog("Frequency index[" + i + "] = " + iFreqSortedIdx[i]);
+ }
+ }
+ return iFreqSortedIdx;
+ }
+ }
+ public int[] FreqTable(RegionCodes regionCode) {
+ switch (regionCode) {
+ case FCC:
+ case AG:
+ case CL:
+ case CO:
+ case CR:
+ case DR:
+ case MX:
+ case PM:
+ case UG:
+// int[] freqTableIdx = fccFreqTableIdx;
+// int[] freqSortedIdx;
+// int[] freqTable = new int[50];
+// if (DEBUG) appendToLog("gerVersionCode = " + mRfidDevice.mRx000Device.mRx000OemSetting.getVersionCode());
+// switch (mRfidDevice.mRx000Device.mRx000OemSetting.getVersionCode()) {
+// case 0:
+// freqSortedIdx = fccFreqSortedIdx0;
+// break;
+// case 1:
+// freqSortedIdx = fccFreqSortedIdx1;
+// break;
+// default:
+// freqSortedIdx = fccFreqSortedIdx;
+// break;
+// }
+// for (int i = 0; i < 50; i++) {
+// freqTable[i] = fccFreqTable[fccFreqTableIdx[freqSortedIdx[i]]];
+// if (DEBUG) appendToLog("i = " + i + ", freqSortedIdx = " + freqSortedIdx[i] + ", fccFreqTableIdx = " + fccFreqTableIdx[freqSortedIdx[i]] + ", freqTable[" + i + "] = " + freqTable[i]);
+// }
+// return freqTable;
+ return countryChannelData.fccFreqTable;
+ case PR:
+ int[] freqSortedIndex = FreqIndex(regionCode);
+ int[] freqTable = null;
+ if (freqSortedIndex != null) {
+ freqTable = new int[freqSortedIndex.length];
+ for (int i = 0; i < freqSortedIndex.length; i++) {
+ int j = 0;
+ for (; j < countryChannelData.FCCTableOfFreq.length; j++) {
+ if (countryChannelData.FCCTableOfFreq[j] == countryChannelData.PRTableOfFreq[freqSortedIndex[i]]) break;
+ }
+ freqTable[i] = countryChannelData.fccFreqTable[countryChannelData.fccFreqTableIdx[j]];
+ }
+ } else
+ if (DEBUG) appendToLog("NULL freqSortedIndex");
+ return freqTable; // return prFreqTable;
+ case VZ:
+ return countryChannelData.vzFreqTable;
+ case AU:
+ return countryChannelData.AusFreqTable;
+
+ case BR1:
+ return countryChannelData.br1FreqTable;
+ case BR2:
+ return countryChannelData.br2FreqTable;
+ case BR3:
+ return countryChannelData.br3FreqTable;
+ case BR4:
+ return countryChannelData.br4FreqTable;
+ case BR5:
+ return countryChannelData.br5FreqTable;
+
+ case HK:
+ case SG:
+ case TH:
+ case VN:
+ return countryChannelData.hkFreqTable;
+ case VN1:
+ return countryChannelData.vietnam1FreqTable;
+ case VN2:
+ return countryChannelData.vietnam2FreqTable;
+ case VN3:
+ return countryChannelData.vietnam3FreqTable;
+ case BD:
+ return countryChannelData.bdFreqTable;
+ case TW:
+ return countryChannelData.twFreqTable;
+ case MY:
+ return countryChannelData.mysFreqTable;
+ case ZA:
+ return countryChannelData.zaFreqTable;
+
+ case ID:
+ return countryChannelData.indonesiaFreqTable;
+ case IL:
+ return countryChannelData.ilFreqTable;
+ case IL2019RW:
+ return countryChannelData.il2019RwFreqTable;
+ case PH:
+ return countryChannelData.phFreqTable;
+ case NZ:
+ return countryChannelData.nzFreqTable;
+ case CN:
+ return countryChannelData.cnFreqTable;
+
+ case UH1:
+ return countryChannelData.uh1FreqTable;
+ case UH2:
+ return countryChannelData.uh2FreqTable;
+ case LH:
+ return countryChannelData.lhFreqTable;
+ case LH1:
+ return countryChannelData.lh1FreqTable;
+ case LH2:
+ return countryChannelData.lh2FreqTable;
+
+ case ETSI:
+ return countryChannelData.etsiFreqTable;
+ case IN:
+ return countryChannelData.indiaFreqTable;
+ case KR:
+ return countryChannelData.krFreqTable;
+ case KR2017RW:
+ return countryChannelData.kr2017RwFreqTable;
+ case JP:
+ return countryChannelData.jpn2012FreqTable;
+ case JP6:
+ return countryChannelData.jpn2012AFreqTable;
+ case ETSIUPPERBAND:
+ return countryChannelData.etsiupperbandFreqTable;
+
+ default:
+ return null;
+ }
+ }
+ private long GetPllcc(RegionCodes regionCode) {
+ switch (regionCode) {
+ case ETSI:
+ case IN:
+ return 0x14070400; //Notice: the read value is 0x14040400
+ }
+ return 0x14070200; //Notice: the read value is 0x14020200
+ }
+ private boolean FreqChnWithinRange(int Channel, RegionCodes regionCode) {
+ int TotalCnt = FreqChnCnt(regionCode);
+ if (TotalCnt <= 0) return false;
+ if (Channel >= 0 && Channel < TotalCnt) return true;
+ return false;
+ }
+ private int FreqSortedIdxTbls(RegionCodes regionCode, int Channel) {
+ int TotalCnt = FreqChnCnt(regionCode);
+ int[] freqIndex = FreqIndex(regionCode);
+ if (!FreqChnWithinRange(Channel, regionCode) || freqIndex == null)
+ return -1;
+ for (int i = 0; i < TotalCnt; i++) {
+ if (freqIndex[i] == Channel) return i;
+ }
+ return -1;
+ }
+ byte tagDelayDefaultCompactSetting = 0;
+ public byte tagDelayDefaultNormalSetting = 30;
+ public byte tagDelaySettingDefault = tagDelayDefaultCompactSetting, tagDelaySetting = tagDelaySettingDefault;
+ public long cycleDelaySettingDefault = 0, cycleDelaySetting = cycleDelaySettingDefault;
+ /*
+ byte[] string2ByteArray(String string) {
+ byte[] bytes = null;
+ if (string == null) return null;
+ if ((string.length()/2)*2 != string.length()) string += "0";
+ for (int i = 0; i < string.length(); i+=2) {
+ try {
+ Short sValue = Short.parseShort(string.substring(i, i + 2), 16);
+ byte[] bytesNew = new byte[1];
+ if (bytes != null) {
+ bytesNew = new byte[bytes.length + 1];
+ System.arraycopy(bytes, 0, bytesNew, 0, bytes.length);
+ }
+ bytesNew[bytesNew.length - 1] = (byte) (sValue & 0xFF);
+ bytes = bytesNew;
+ } catch (Exception ex) {
+ appendToLog("Exception in i = " + i + ", substring = " + string.substring(i, i+2));
+ break;
+ }
+ }
+ return bytes;
+ }
+*/
+ public boolean starAuthOperation() {
+ if (bis108) {
+ rfidReaderChipR2000.setPwrManagementMode(false);
+ return rfidReaderChipR2000.sendHostRegRequestHST_CMD(RfidReaderChipData.HostCommands.CMD_18K6CAUTHENTICATE);
+ }
+ rfidReaderChipE710.setPwrManagementMode(false);
+ return rfidReaderChipE710.sendHostRegRequestHST_CMD(RfidReaderChipData.HostCommands.CMD_18K6CAUTHENTICATE);
+ }
+
+ //============ Rfid ============
+ //============ Rfid ============
+
+ public String getAuthMatchData() {
+ int iValue1 = 96;
+ String strValue;
+ if (bis108) strValue = rfidReaderChipR2000.rx000Setting.getAuthMatchData();
+ else strValue = rfidReaderChipE710.rx000Setting.getAuthMatchData();
+ if (strValue == null) return null;
+ int strLength = iValue1 / 4;
+ if (strLength * 4 != iValue1) strLength++;
+ return strValue.substring(0, strLength);
+ }
+ public boolean setAuthMatchData(String mask) {
+ boolean result = false;
+ if (mask != null) {
+ if (bis108) result = rfidReaderChipR2000.rx000Setting.setAuthMatchData(mask);
+ else result = rfidReaderChipE710.rx000Setting.setAuthenticateMessage(mask.getBytes());
+ }
+ return result;
+ }
+ public int getStartQValue() {
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.getAlgoStartQ(3) : rfidReaderChipE710.rx000Setting.getAlgoStartQ(3));
+ }
+ public int getMaxQValue() {
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.getAlgoMaxQ(3) : rfidReaderChipE710.rx000Setting.getAlgoMaxQ(3));
+ }
+ public int getMinQValue() {
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.getAlgoMinQ(3) : rfidReaderChipE710.rx000Setting.getAlgoMinQ(3));
+ }
+ public boolean setDynamicQParms(int startQValue, int minQValue, int maxQValue, int retryCount) {
+ appendToLog("setTagGroup: going to setAlgoSelect with input as 3");
+ boolean result;
+ result = (bis108 ? rfidReaderChipR2000.rx000Setting.setAlgoSelect(3) : rfidReaderChipE710.rx000Setting.setAlgoSelect(3));
+ if (result) {
+ result = (bis108 ? rfidReaderChipR2000.rx000Setting.setAlgoStartQ(startQValue, maxQValue, minQValue, -1, -1, -1) : rfidReaderChipE710.rx000Setting.setAlgoStartQ(startQValue, maxQValue, minQValue, -1, -1, -1));
+ }
+ if (result) result = setRetryCount(retryCount);
+ return result;
+ }
+ public int getFixedQValue() {
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.getAlgoStartQ(0) : rfidReaderChipE710.rx000Setting.getAlgoStartQ(0));
+ }
+ public int getFixedRetryCount() {
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.getAlgoRetry(0) : rfidReaderChipE710.rx000Setting.getAlgoMinQCycles());
+ }
+ public boolean getRepeatUnitNoTags() {
+ if (bis108) return rfidReaderChipR2000.rx000Setting.getAlgoRunTilZero(0) == 1 ? true : false;
+ return rfidReaderChipE710.rx000Setting.getAlgoRunTilZero(0) == 1 ? true : false;
+ }
+ public boolean setFixedQParms(int qValue, int retryCount, boolean repeatUnitNoTags) {
+ boolean result, DEBUG = false;
+ if (DEBUG) appendToLog("qValue=" + qValue + ", retryCount = " + retryCount + ", repeatUntilNoTags = " + repeatUnitNoTags);
+ result = (bis108 ? rfidReaderChipR2000.rx000Setting.setAlgoSelect(0) : rfidReaderChipE710.rx000Setting.setAlgoSelect(0));
+ if (DEBUG) appendToLog("after setAlgoSelect, result = " + result);
+ if (qValue == getFixedQValue() && retryCount == getFixedRetryCount() && repeatUnitNoTags == getRepeatUnitNoTags()) {
+ appendToLog("!!! Skip repeated repeated data with qValue=" + qValue + ", retryCount = " + retryCount + ", repeatUntilNoTags = " + repeatUnitNoTags);
+ return true;
+ }
+
+ if (result) {
+ result = (bis108 ? rfidReaderChipR2000.rx000Setting.setAlgoStartQ(qValue, -1, -1, -1, -1, -1) : rfidReaderChipE710.rx000Setting.setAlgoStartQ(qValue));
+ }
+ if (result) result = setRetryCount(retryCount);
+ if (result) {
+ result = (bis108 ? rfidReaderChipR2000.rx000Setting.setAlgoRunTilZero(repeatUnitNoTags ? 1 : 0) : rfidReaderChipE710.rx000Setting.setAlgoRunTilZero(repeatUnitNoTags ? 1 : 0));
+ }
+ return result;
+ }
+
+ public static class PreMatchData {
+ public boolean enable; public int target;
+ public int action; public int bank;
+ public int offset; public String mask; public int maskblen; public int querySelect; public long pwrlevel; public boolean invAlgo; public int qValue;
+ public PreMatchData(boolean enable, int target, int action, int bank, int offset, String mask, int maskblen, int querySelect, long pwrlevel, boolean invAlgo, int qValue) {
+ this.enable = enable;
+ this.target = target;
+ this.action = action;
+ this.bank = bank;
+ this.offset = offset;
+ this.mask = mask;
+ this.maskblen = maskblen;
+ this.querySelect = querySelect;
+ this.pwrlevel = pwrlevel;
+ this.invAlgo = invAlgo;
+ this.qValue = qValue;
+ }
+ }
+ public PreMatchData preMatchData;
+ public boolean setOnlyPowerLevel(long pwrlevel) {
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.setAntennaPower(pwrlevel) : rfidReaderChipE710.rx000Setting.setAntennaPower(pwrlevel));
+ }
+
+ boolean[] bSelectEnabled = { false, false, false };
+ boolean setSelectCriteria3(int index, boolean enable, int target, int action, int delay, int bank, int offset, String mask, int maskblen) {
+ boolean DEBUG = false;
+ if (utility.DEBUG_SELECT) appendToLog("Debug_Select: RfidReader.setSelectCriteria3 with index = " + index + ", enable = " + enable + ", bSelectEnable = " + bSelectEnabled[index]
+ + ", target = " + target + ", action = " + action + ", delay = " + delay
+ + ", bank = " + bank + ", offset = " + offset + ", mask = " + mask + ", maskbitlen = " + maskblen);
+ if (!enable) {
+ if (bSelectEnabled[index] = false) return true;
+ }
+ int maskbytelen = maskblen / 4; if ((maskblen % 4) != 0) maskbytelen++; if (maskbytelen > 64) maskbytelen = 64;
+ if (mask == null) mask = "";
+ if (mask.length() > maskbytelen ) mask = mask.substring(0, maskbytelen);
+ if (index == 0) preMatchData = new RfidReader.PreMatchData(enable, target, action, bank, offset, mask, maskblen,
+ (bis108 ? rfidReaderChipR2000.rx000Setting.getQuerySelect() : rfidReaderChipE710.rx000Setting.getQuerySelect()), getPwrlevel(), getInvAlgo(), getQValue());
+ boolean result = true;
+ if (index != (bis108 ? rfidReaderChipR2000.rx000Setting.getInvSelectIndex() : rfidReaderChipE710.rx000Setting.getInvSelectIndex())) {
+ if (utility.DEBUG_SELECT) appendToLog("Debug_Select: RfidReader.setSelectCriteria3 goes to setInvSelectIndex");
+ result = (bis108 ? rfidReaderChipR2000.rx000Setting.setInvSelectIndex(index) : rfidReaderChipE710.rx000Setting.setInvSelectIndex(index));
+ if (DEBUG) appendToLog("After setInvSelectIndex, result = " + result);
+ }
+ if (utility.DEBUG_SELECT) appendToLog("Debug_Select: RfidReader.setSelectCriteria3 goes to setSelectEnable");
+ if (result) result = (bis108 ? rfidReaderChipR2000.rx000Setting.setSelectEnable(enable ? 1 : 0, target, action, delay) : rfidReaderChipE710.rx000Setting.setSelectEnable(enable ? 1 : 0, target, action, delay));
+ if (DEBUG) appendToLog("After setSelectEnable, result = " + result);
+ if (result) result = (bis108 ? rfidReaderChipR2000.rx000Setting.setSelectMaskBank(bank) : rfidReaderChipE710.rx000Setting.setSelectMaskBank(bank));
+ if (DEBUG) appendToLog("After setSelectMaskBank, result = " + result);
+ if (result) result = (bis108 ? rfidReaderChipR2000.rx000Setting.setSelectMaskOffset(offset) : rfidReaderChipE710.rx000Setting.setSelectMaskOffset(offset));
+ if (DEBUG) appendToLog("After setSelectMaskOffset, result = " + result + " and mask = " + mask);
+ if (mask == null) return false;
+ if (result) result = (bis108 ? rfidReaderChipR2000.rx000Setting.setSelectMaskLength(maskblen) : rfidReaderChipE710.rx000Setting.setSelectMaskLength(maskblen));
+ if (DEBUG) appendToLog("After setSelectMaskLength, result = " + result);
+ if (result) result = (bis108 ? rfidReaderChipR2000.rx000Setting.setSelectMaskData(mask) : rfidReaderChipE710.rx000Setting.setSelectMaskData(mask));
+ if (DEBUG) appendToLog("After setSelectMaskData, result = " + result);
+ if (result) {
+ //appendToLog("BtDataOut: RfidReader.setSelectCriteria3 with enable = " + enable);
+ if (enable) {
+ result = (bis108 ? rfidReaderChipR2000.rx000Setting.setTagSelect(1) : rfidReaderChipE710.rx000Setting.setTagSelect(1));
+ if (DEBUG) appendToLog("After setTagSelect[1], result = " + result);
+ if (result) result = (bis108 ? rfidReaderChipR2000.rx000Setting.setQuerySelect(3) : rfidReaderChipE710.rx000Setting.setQuerySelect(3));
+ if (DEBUG) appendToLog("After setQuerySelect[3], result = " + result);
+ } else {
+ result = (bis108 ? rfidReaderChipR2000.rx000Setting.setTagSelect(0) : rfidReaderChipE710.rx000Setting.setTagSelect(0));
+ if (DEBUG) appendToLog("After setTagSelect[0], result = " + result);
+ if (result) result = (bis108 ? rfidReaderChipR2000.rx000Setting.setQuerySelect(0) : rfidReaderChipE710.rx000Setting.setQuerySelect(0));
+ if (DEBUG) appendToLog("After setQuerySelect[0], result = " + result);
+ }
+ }
+ if (result) {
+ bSelectEnabled[index] = enable;
+ }
+ return result;
+ }
+ public PostMatchData postMatchDataOld; public boolean postMatchDataChanged = false;
+ public RfidReader.PreMatchData preMatchDataOld; public boolean preMatchDataChanged = false;
+ public boolean setSelectedTag1(boolean selectOne, String selectMask, int selectBank, int selectOffset, int delay, long pwrlevel, int qValue, int matchRep) {
+ if (utility.DEBUG_SELECT) appendToLog("Debug_Select: RfidReader.setSelectedTag1[selectOne = " + selectOne + ", selectMask = "
+ + selectMask + ", selectBank = " + selectBank + ", selectOffset = " + selectOffset + ", delay = "
+ + delay + ", pwrlevel = " + pwrlevel + ", qValue = " + qValue + ", matchRep = " + matchRep);
+ boolean setSuccess = true, DEBUG = false;
+ if (selectMask == null) selectMask = "";
+
+ if (preMatchDataChanged == false) {
+ preMatchDataChanged = true; if (DEBUG) appendToLog("setSelectCriteria preMatchDataChanged is SET with preMatchData = " + (preMatchData != null ? "valid" : "null"));
+ if (preMatchData == null) {
+ preMatchData = new RfidReader.PreMatchData(false,
+ (bis108 ? rfidReaderChipR2000.rx000Setting.getQueryTarget() : rfidReaderChipE710.rx000Setting.getQueryTarget()), 0, 0, 0, "", 0,
+ (bis108 ? rfidReaderChipR2000.rx000Setting.getQuerySelect() : rfidReaderChipE710.rx000Setting.getQuerySelect()), getPwrlevel(), getInvAlgo(), getQValue());
+ }
+ preMatchDataOld = preMatchData;
+ }
+ int indexCurrent = (bis108 ? rfidReaderChipR2000.rx000Setting.invSelectIndex : rfidReaderChipE710.rx000Setting.invSelectIndex);
+ for (int i = 0; i < 7; i++) {
+ if (utility.DEBUG_SELECT) appendToLog("Debug_Select: RfidReader.setSelectedTag1 1 goes to setInvSelectIndex with i = " + i);
+ if (bis108) rfidReaderChipR2000.rx000Setting.setInvSelectIndex(i); else rfidReaderChipE710.rx000Setting.setInvSelectIndex(i);
+ int isEnabled = (bis108 ? rfidReaderChipR2000.rx000Setting.getSelectEnable() : rfidReaderChipE710.rx000Setting.getSelectEnable());
+ if (isEnabled == 0 || selectOne) {
+ if (utility.DEBUG_SELECT) appendToLog("Debug_Select: RfidReader.setSelectedTag1. goes to setSelectCriteria3");
+ setSuccess = setSelectCriteria3(i, true, 4, 0, delay, selectBank, selectOffset, selectMask, selectMask.length() * 4);
+ if (DEBUG) appendToLog("setSelectCriteria after setSelectCriteria, setSuccess = " + setSuccess);
+ break;
+ }
+ }
+ if (utility.DEBUG_SELECT) appendToLog("Debug_Select: RfidReader.setSelectedTag1 2 goes to setInvSelectIndex with indexCurrent = " + indexCurrent);
+ if (bis108) rfidReaderChipR2000.rx000Setting.setInvSelectIndex(indexCurrent); else rfidReaderChipE710.rx000Setting.setInvSelectIndex(indexCurrent);
+
+ if (setSuccess) setSuccess = setOnlyPowerLevel(pwrlevel);
+ if (DEBUG) appendToLog("setSelectCriteria after setOnlyPowerLevel, setSuccess = " + setSuccess);
+ if (false) {
+ if (setSuccess) setSuccess = setFixedQParms(qValue, 5, false);
+ if (DEBUG) appendToLog("setSelectCriteria after setFixedQParms, setSuccess = " + setSuccess);
+ if (setSuccess) setSuccess = (bis108 ? rfidReaderChipR2000.rx000Setting.setAlgoAbFlip(1) : rfidReaderChipE710.rx000Setting.setAlgoAbFlip(1));
+ if (DEBUG) appendToLog("setSelectCriteria after setAlgoAbFlip, setSuccess = " + setSuccess);
+ if (setSuccess) setSuccess = setInvAlgo1(false);
+ if (DEBUG) appendToLog("setSelectCriteria after setInvAlgo1, setSuccess = " + setSuccess);
+ }
+
+ if (utility.DEBUG_INVCFG) appendToLog("Debug_InvCfg: RfidReader.setSelectTag1 goes to setMatchRep with matchRep = " + matchRep);
+ if (setSuccess) setSuccess = setMatchRep(matchRep);
+ if (DEBUG) appendToLog("setSelectCriteria after setMatchRep, setSuccess = " + setSuccess);
+ if (setSuccess) setSuccess = setTagDelay2RfidReader(tagDelayDefaultNormalSetting);
+ if (DEBUG) appendToLog("setSelectCriteria after setTagDelay, setSuccess = " + setSuccess);
+ if (setSuccess) setSuccess = (bis108 ? rfidReaderChipR2000.rx000Setting.setCycleDelay(cycleDelaySetting) : rfidReaderChipE710.rx000Setting.setCycleDelay(cycleDelaySetting));
+ if (DEBUG) appendToLog("setSelectCriteria after setCycleDelay, setSuccess = " + setSuccess);
+ if (utility.DEBUG_COMPACT) appendToLog("Debug_Compact 3: RfidReadder.setSelectedTag1 goes to setInvModeCompact");
+ if (setSuccess) setSuccess = setInvModeCompact(false);
+ if (DEBUG) appendToLog("setSelectCriteria after setInvModeCompact, setSuccess = " + setSuccess);
+ return setSuccess;
+ }
+ public boolean setSelectedTag4Access(boolean selectOne, String selectMask, int selectBank, int selectOffset, long pwrlevel, int qValue, int matchRep) {
+ if (utility.DEBUG_SELECT) appendToLog("Debug_Select: RfidReader.setSelectedTag long goes to setSelectedTag1");
+ return setSelectedTag1(selectOne, selectMask, selectBank, selectOffset, 0, pwrlevel, qValue, matchRep);
+ }
+ public boolean setSelectedTag(String selectMask, int selectBank, long pwrlevel) {
+ boolean isValid = false;
+ if (selectBank < 0 || selectBank > 3) return false;
+ int selectOffset = (selectBank == 1 ? 32 : 0);
+ //appendToLog("BtDataOut: RfidReader.setSelectTag");
+ //isValid = setSelectCriteriaDisable(-1);
+ appendToLog("BtDataOut: RfidReader.setSelectedTag short goes to setSelectedTag1");
+ isValid = setSelectedTag1(true, selectMask, selectBank, selectOffset, 0, pwrlevel, 0, 0);
+ return isValid;
+ }
+ public boolean setSelectedTagByTID(String selectMask, long pwrlevel) {
+ if (pwrlevel < 0) pwrlevel = pwrlevelSetting;
+ if (utility.DEBUG_SELECT) appendToLog("Debug_Select: RfidReader.setSelectedTagByTID goes to setSelectedTag1");
+ return setSelectedTag1(false, selectMask, 2, 0, 0, pwrlevel, 0, 0);
+ }
+
+ public final int modifyCodeAA = 0xAA;
+ public enum RegionCodes {
+ NULL,
+ AG, BD, CL, CO, CR, DR, MX, PM, UG,
+ BR1, BR2, BR3, BR4, BR5,
+ IL, IL2019RW, PR, PH, SG, ZA, VZ,
+ AU, NZ, HK, MY, VN, VN1, VN2, VN3,
+ CN, TW, KR, KR2017RW, JP, JP6, TH, IN, FCC,
+ UH1, UH2, LH, LH1, LH2,
+ ETSI, ID, ETSIUPPERBAND,
+
+ Albania1, Albania2, Algeria1, Algeria2, Algeria3, Algeria4, Argentina, Armenia, Australia1, Australia2,
+ Austria1, Austria2, Azerbaijan, Bahrain, Bangladesh, Belarus, Belgium1, Belgium2, Bolivia, Bosnia,
+ Botswana, Brazil1, Brazil2, Brunei1, Brunei2, Bulgaria1, Bulgaria2, Cambodia, Cameroon, Canada,
+ Chile1, Chile2, Chile3, China, Colombia, Congo, CostaRica, Cotedlvoire, Croatia, Cuba,
+ Cyprus1, Cyprus2, Czech1, Czech2, Denmark1, Denmark2, Dominican, Ecuador, Egypt, ElSalvador,
+ Estonia, Finland1, Finland2, France, Georgia, Germany, Ghana, Greece, Guatemala, HongKong1,
+ HongKong2, Hungary1, Hungary2, Iceland, India, Indonesia, Iran, Ireland1, Ireland2, Israel,
+ Italy, Jamaica, Japan4, Japan6, Jordan, Kazakhstan, Kenya, Korea, KoreaDPR, Kuwait,
+ Kyrgyz, Latvia, Lebanon, Libya, Liechtenstein1, Liechtenstein2, Lithuania1, Lithuania2, Luxembourg1, Luxembourg2,
+ Macao, Macedonia, Malaysia, Malta1, Malta2, Mauritius, Mexico, Moldova1, Moldova2, Mongolia,
+ Montenegro, Morocco, Netherlands, NewZealand1, NewZealand2, Nicaragua, Nigeria, Norway1, Norway2, Oman,
+ Pakistan, Panama, Paraguay, Peru, Philippines, Poland, Portugal, Romania, Russia1, Russia3,
+ Senegal, Serbia, Singapore1, Singapore2, Slovak1, Slovak2, Slovenia1, Solvenia2, SAfrica1, SAfrica2,
+ Spain, SriLanka, Sudan, Sweden1, Sweden2, Switzerland1, Switzerland2, Syria, Taiwan1, Taiwan2,
+ Tajikistan, Tanzania, Thailand, Trinidad, Tunisia, Turkey, Turkmenistan, Uganda, Ukraine, UAE,
+ UK1, UK2, USA, Uruguay, Venezuela, Vietnam1, Vietnam2, Yemen, Zimbabwe, Vietnam3
+ }
+ public String regionCode2StringArray(@NonNull RegionCodes region) {
+ switch (region) {
+ case AG:
+ return "Argentina";
+ case CL:
+ return "Chile";
+ case CO:
+ return "Columbia";
+ case CR:
+ return "Costa Rica";
+ case DR:
+ return "Dominican Republic";
+ case MX:
+ return "Mexico";
+ case PM:
+ return "Panama";
+ case UG:
+ return "Uruguay";
+ case BR1:
+ return "Brazil 915-927";
+ case BR2:
+ return "Brazil 902-906, 915-927";
+ case BR3:
+ return "Brazil 902-906";
+ case BR4:
+ return "Brazil 902-904";
+ case BR5:
+ return "Brazil 917-924";
+ case IL:
+ case IL2019RW:
+ return "Israel";
+ case PR:
+ return "Peru";
+ case PH:
+ return "Philippines";
+ case SG:
+ return "Singapore";
+ case ZA:
+ return "South Africa";
+ case VZ:
+ return "Venezuela";
+ case AU:
+ return "Australia";
+ case NZ:
+ return "New Zealand";
+ case HK:
+ return "Hong Kong";
+ case MY:
+ return "Malaysia";
+ case VN:
+ return "Vietnam";
+ case VN1:
+ return "Vietnam1";
+ case VN2:
+ return "Vietnam2";
+ case VN3:
+ return "Vietnam3";
+ case BD:
+ return "Bangladesh";
+ case CN:
+ return "China";
+ case TW:
+ return "Taiwan";
+ case KR:
+ case KR2017RW:
+ return "Korea";
+ case JP:
+ return "Japan";
+ case JP6:
+ return "Japan";
+ case TH:
+ return "Thailand";
+ case ID:
+ return "Indonesia";
+ case FCC:
+ if (getFreqModifyCode() == modifyCodeAA) return "FCC";
+ return "USA/Canada";
+ case UH1:
+ return "UH1";
+ case UH2:
+ return "UH2";
+ case LH:
+ return "LH";
+ case LH1:
+ return "LH1";
+ case LH2:
+ return "LH2";
+ case ETSI:
+ return "Europe";
+ case IN:
+ return "India";
+ case ETSIUPPERBAND:
+ return "ETSI Upper Band";
+ default:
+ return region.toString();
+ }
+ }
+ public RegionCodes regionCode = null;
+ RegionCodes[] getRegionList1() {
+ boolean DEBUG = false;
+ RegionCodes[] regionList = null;
+ regionCode = null;
+ if (DEBUG) appendToLog("3 getCountryList: getCountryCode is " + getCountryCode());
+ switch (getCountryCode()) {
+ case 1:
+ RegionCodes RegionCodes;
+ regionList = new RfidReader.RegionCodes[]{
+ RfidReader.RegionCodes.Albania1, RfidReader.RegionCodes.Algeria1, RfidReader.RegionCodes.Algeria2, RfidReader.RegionCodes.Armenia, RfidReader.RegionCodes.Austria1,
+ RfidReader.RegionCodes.Azerbaijan, RfidReader.RegionCodes.Bahrain, RfidReader.RegionCodes.Bangladesh, RfidReader.RegionCodes.Belarus, RfidReader.RegionCodes.Belgium1,
+ RfidReader.RegionCodes.Bosnia, RfidReader.RegionCodes.Botswana, RfidReader.RegionCodes.Brunei1, RfidReader.RegionCodes.Bulgaria1, RfidReader.RegionCodes.Cameroon,
+ RfidReader.RegionCodes.Congo, RfidReader.RegionCodes.Cotedlvoire, RfidReader.RegionCodes.Croatia, RfidReader.RegionCodes.Cyprus1, RfidReader.RegionCodes.Czech1,
+ RfidReader.RegionCodes.Denmark1, RfidReader.RegionCodes.Egypt, RfidReader.RegionCodes.Estonia, RfidReader.RegionCodes.Finland1, RfidReader.RegionCodes.France,
+ RfidReader.RegionCodes.Georgia, RfidReader.RegionCodes.Germany, RfidReader.RegionCodes.Ghana, RfidReader.RegionCodes.Greece, RfidReader.RegionCodes.HongKong1,
+ RfidReader.RegionCodes.Hungary1, RfidReader.RegionCodes.Iceland, RfidReader.RegionCodes.India, RfidReader.RegionCodes.Iran, RfidReader.RegionCodes.Ireland1,
+ RfidReader.RegionCodes.Italy, RfidReader.RegionCodes.Jordan, RfidReader.RegionCodes.Kazakhstan, RfidReader.RegionCodes.Kenya, RfidReader.RegionCodes.Kuwait,
+ RfidReader.RegionCodes.Kyrgyz, RfidReader.RegionCodes.Latvia, RfidReader.RegionCodes.Lebanon, RfidReader.RegionCodes.Libya, RfidReader.RegionCodes.Liechtenstein1,
+ RfidReader.RegionCodes.Lithuania1, RfidReader.RegionCodes.Luxembourg1, RfidReader.RegionCodes.Macedonia, RfidReader.RegionCodes.Malta1, RfidReader.RegionCodes.Mauritius,
+ RfidReader.RegionCodes.Moldova1, RfidReader.RegionCodes.Montenegro, RfidReader.RegionCodes.Morocco, RfidReader.RegionCodes.Netherlands, RfidReader.RegionCodes.NewZealand1,
+ RfidReader.RegionCodes.Nigeria, RfidReader.RegionCodes.Norway1, RfidReader.RegionCodes.Oman, RfidReader.RegionCodes.Pakistan, RfidReader.RegionCodes.Poland,
+ RfidReader.RegionCodes.Portugal, RfidReader.RegionCodes.Romania, RfidReader.RegionCodes.Russia1, RfidReader.RegionCodes.SAfrica1, RfidReader.RegionCodes.Senegal,
+ RfidReader.RegionCodes.Serbia, RfidReader.RegionCodes.Singapore1, RfidReader.RegionCodes.Slovak1, RfidReader.RegionCodes.Slovenia1, RfidReader.RegionCodes.Spain,
+ RfidReader.RegionCodes.SriLanka, RfidReader.RegionCodes.Sudan, RfidReader.RegionCodes.Sweden1, RfidReader.RegionCodes.Switzerland1, RfidReader.RegionCodes.Syria,
+ RfidReader.RegionCodes.Tajikistan, RfidReader.RegionCodes.Tanzania, RfidReader.RegionCodes.Tunisia, RfidReader.RegionCodes.Turkey, RfidReader.RegionCodes.Turkmenistan,
+ RfidReader.RegionCodes.UAE, RfidReader.RegionCodes.Uganda, RfidReader.RegionCodes.UK1, RfidReader.RegionCodes.Ukraine, RfidReader.RegionCodes.Vietnam1,
+ RfidReader.RegionCodes.Yemen, RfidReader.RegionCodes.Zimbabwe, RfidReader.RegionCodes.Vietnam3
+ };
+ break;
+ case 2:
+ String strSpecialCountryVersion = getSpecialCountryVersion();
+ if (DEBUG) appendToLog("3A getCountryList: getSpecialCountryVersion is [" + strSpecialCountryVersion + "]");
+ if (strSpecialCountryVersion == null || (strSpecialCountryVersion != null && strSpecialCountryVersion.length() == 0)) {
+ regionList = new RegionCodes[]{
+ RfidReader.RegionCodes.Bolivia, RfidReader.RegionCodes.Canada, RfidReader.RegionCodes.Mexico, RfidReader.RegionCodes.USA
+ };
+ } else if (strSpecialCountryVersion.contains("AS")) {
+ regionList = new RegionCodes[]{
+ RfidReader.RegionCodes.Australia1, RfidReader.RegionCodes.Australia2
+ };
+ } else if (strSpecialCountryVersion.contains("NZ")) {
+ regionList = new RegionCodes[]{
+ RfidReader.RegionCodes.NewZealand2
+ };
+ } else if (strSpecialCountryVersion.contains("OFCA")) {
+ regionList = new RegionCodes[]{
+ RfidReader.RegionCodes.HongKong2
+ };
+ } else if (strSpecialCountryVersion.contains("SG")) {
+ regionList = new RegionCodes[]{
+ RfidReader.RegionCodes.Singapore2
+ };
+ } else if (strSpecialCountryVersion.contains("RW")) {
+ regionList = new RegionCodes[]{
+ RfidReader.RegionCodes.Albania2, RfidReader.RegionCodes.Argentina, RfidReader.RegionCodes.Brazil1, RfidReader.RegionCodes.Brazil2, RfidReader.RegionCodes.Chile1,
+ RfidReader.RegionCodes.Chile2, RfidReader.RegionCodes.Chile3, RfidReader.RegionCodes.Colombia, RfidReader.RegionCodes.CostaRica, RfidReader.RegionCodes.Cuba,
+ RfidReader.RegionCodes.Dominican, RfidReader.RegionCodes.Ecuador, RfidReader.RegionCodes.ElSalvador, RfidReader.RegionCodes.Guatemala, RfidReader.RegionCodes.Jamaica,
+ RfidReader.RegionCodes.Nicaragua, RfidReader.RegionCodes.Panama, RfidReader.RegionCodes.Paraguay, RfidReader.RegionCodes.Peru, RfidReader.RegionCodes.Philippines,
+ RfidReader.RegionCodes.Singapore2, RfidReader.RegionCodes.Thailand, RfidReader.RegionCodes.Trinidad, RfidReader.RegionCodes.Uruguay, RfidReader.RegionCodes.Venezuela
+ };
+ }
+ break;
+ case 4:
+ regionList = new RfidReader.RegionCodes[]{
+ RfidReader.RegionCodes.Taiwan1, RfidReader.RegionCodes.Taiwan2
+ };
+ break;
+ case 6:
+ regionList = new RfidReader.RegionCodes[]{
+ RfidReader.RegionCodes.Korea
+ };
+ break;
+ case 7:
+ regionList = new RfidReader.RegionCodes[]{
+ RfidReader.RegionCodes.Algeria4, RfidReader.RegionCodes.Brunei2, RfidReader.RegionCodes.Cambodia, RfidReader.RegionCodes.China, RfidReader.RegionCodes.Indonesia,
+ RfidReader.RegionCodes.KoreaDPR, RfidReader.RegionCodes.Macao, RfidReader.RegionCodes.Malaysia, RfidReader.RegionCodes.Mongolia, RfidReader.RegionCodes.Vietnam2
+ };
+ break;
+ case 8:
+ regionList = new RfidReader.RegionCodes[]{
+ RfidReader.RegionCodes.Japan4, RfidReader.RegionCodes.Japan6
+ };
+ break;
+ case 9:
+ regionList = new RfidReader.RegionCodes[]{
+ RfidReader.RegionCodes.Algeria3, RfidReader.RegionCodes.Austria2, RfidReader.RegionCodes.Belgium2, RfidReader.RegionCodes.Bulgaria2, RfidReader.RegionCodes.Cyprus2,
+ RfidReader.RegionCodes.Czech2, RfidReader.RegionCodes.Denmark2, RfidReader.RegionCodes.Finland2, RfidReader.RegionCodes.Hungary2, RfidReader.RegionCodes.Ireland2,
+ RfidReader.RegionCodes.Israel, RfidReader.RegionCodes.Liechtenstein2, RfidReader.RegionCodes.Lithuania2, RfidReader.RegionCodes.Luxembourg2, RfidReader.RegionCodes.Malta2,
+ RfidReader.RegionCodes.Moldova2, RfidReader.RegionCodes.Norway2, RfidReader.RegionCodes.Russia3, RfidReader.RegionCodes.SAfrica2, RfidReader.RegionCodes.Slovak2,
+ RfidReader.RegionCodes.Solvenia2, RfidReader.RegionCodes.Sweden2, RfidReader.RegionCodes.Switzerland2, RfidReader.RegionCodes.UK2
+ };
+ break;
+ default:
+ int indexBegin = RfidReader.RegionCodes.Albania1.ordinal();
+ int indexEnd = RfidReader.RegionCodes.Vietnam3.ordinal();
+ regionList = new RegionCodes[indexEnd - indexBegin + 1];
+ for (int i = 0; i < regionList.length; i++)
+ regionList[i] = RfidReader.RegionCodes.values()[indexBegin + i];
+ break;
+ }
+ int iValue = rfidReaderChipE710.rx000Setting.getCountryEnum();
+ if (DEBUG) appendToLog("3b getCountryList: getCountryEnum is " + iValue);
+ if (iValue < 0) return null;
+
+ iValue += RfidReader.RegionCodes.Albania1.ordinal() - 1;
+ regionCode = RfidReader.RegionCodes.values()[iValue];
+ if (DEBUG) appendToLog("3C getCountryList: regionCode is " + regionCode.toString());
+ return regionList;
+ }
+ public final RegionCodes regionCodeDefault4Country2 = RegionCodes.FCC;
+ public RegionCodes[] getRegionList() {
+ if (bis108) {
+ boolean DEBUG = false;
+ RegionCodes[] regionList = null;
+ {
+ switch (getCountryCode()) {
+ case 1:
+ if (regionCode == null) regionCode = RegionCodes.ETSI;
+ regionList = new RegionCodes[]{RegionCodes.ETSI, RegionCodes.IN, RegionCodes.VN1};
+ break;
+ default:
+ case 2:
+ int modifyCode = getFreqModifyCode();
+ if (modifyCode != modifyCodeAA) {
+ if (regionCode == null) regionCode = regionCodeDefault4Country2;
+ regionList = new RegionCodes[]{
+ RegionCodes.AG,
+ RegionCodes.AU,
+ RegionCodes.BD,
+ RegionCodes.BR1, RegionCodes.BR2, RegionCodes.BR3, RegionCodes.BR4, RegionCodes.BR5,
+ RegionCodes.CL, RegionCodes.CO, RegionCodes.CR, RegionCodes.DR,
+ RegionCodes.HK,
+ RegionCodes.ID,
+ RegionCodes.IL2019RW,
+ RegionCodes.KR2017RW,
+ RegionCodes.LH1, RegionCodes.LH2,
+ RegionCodes.MY,
+ RegionCodes.MX, RegionCodes.PM,
+ RegionCodes.PR,
+ RegionCodes.PH, RegionCodes.SG,
+ RegionCodes.ZA,
+ RegionCodes.TH,
+ RegionCodes.UH1, RegionCodes.UH2,
+ RegionCodes.UG,
+ RegionCodes.FCC,
+ RegionCodes.VZ,
+ RegionCodes.VN};
+ } else {
+ String strSpecialCountryVersion = rfidReaderChipR2000.rx000OemSetting.getSpecialCountryVersion();
+ if (strSpecialCountryVersion.contains("OFCA")) {
+ regionCode = RegionCodes.HK;
+ regionList = new RegionCodes[]{RegionCodes.HK};
+ } else if (strSpecialCountryVersion.contains("SG")) {
+ regionCode = RegionCodes.SG;
+ regionList = new RegionCodes[]{RegionCodes.SG};
+ } else if (strSpecialCountryVersion.contains("AS")) {
+ regionCode = RegionCodes.AU;
+ regionList = new RegionCodes[]{RegionCodes.AU};
+ } else if (strSpecialCountryVersion.contains("NZ")) {
+ regionCode = RegionCodes.NZ;
+ regionList = new RegionCodes[]{RegionCodes.NZ};
+ } else if (strSpecialCountryVersion.contains("ZA")) {
+ regionCode = RegionCodes.ZA;
+ regionList = new RegionCodes[]{RegionCodes.ZA};
+ } else if (strSpecialCountryVersion.contains("TH")) {
+ regionCode = RegionCodes.TH;
+ regionList = new RegionCodes[]{RegionCodes.TH};
+ } else { //if (strSpecialCountryVersion.contains("*USA")) {
+ regionCode = regionCodeDefault4Country2;
+ regionList = new RegionCodes[]{RegionCodes.FCC};
+ }
+ }
+ break;
+ case 3:
+// break;
+ case 4:
+ if (regionCode == null) regionCode = RegionCodes.TW;
+ regionList = new RegionCodes[]{RegionCodes.TW, RegionCodes.AU, RegionCodes.MY,
+ RegionCodes.HK, RegionCodes.SG, RegionCodes.ID, RegionCodes.CN};
+ break;
+ case 5:
+ regionCode = RegionCodes.KR;
+ regionList = new RegionCodes[]{RegionCodes.KR};
+ break;
+ case 6:
+ regionCode = RegionCodes.KR2017RW;
+ regionList = new RegionCodes[]{RegionCodes.KR2017RW};
+ break;
+ case 7:
+ if (regionCode == null) regionCode = RegionCodes.CN;
+ regionList = new RegionCodes[]{RegionCodes.CN, RegionCodes.AU, RegionCodes.HK, RegionCodes.TH,
+ RegionCodes.SG, RegionCodes.MY, RegionCodes.ID, RegionCodes.VN2, RegionCodes.VN3};
+ break;
+ case 8:
+ String strSpecialCountryVersion = rfidReaderChipR2000.rx000OemSetting.getSpecialCountryVersion();
+ if (strSpecialCountryVersion.contains("6")) {
+ regionCode = RegionCodes.JP6;
+ regionList = new RegionCodes[]{RegionCodes.JP6};
+ } else {
+ regionCode = RegionCodes.JP;
+ regionList = new RegionCodes[]{RegionCodes.JP};
+ }
+ break;
+ case 9:
+ regionCode = RegionCodes.ETSIUPPERBAND;
+ regionList = new RegionCodes[]{RegionCodes.ETSIUPPERBAND};
+ break;
+ }
+ }
+ countryInList = 0; if (DEBUG) appendToLog("saveSetting2File testpoint 1");
+ for (int i = 0; i < regionList.length; i++) {
+ if (regionCode == regionList[i]) {
+ countryInList = i; if (DEBUG) appendToLog("saveSetting2File testpoint 2"); break;
+ }
+ }
+ if (countryInListDefault < 0) countryInListDefault = countryInList;
+ appendToLog("countryInListDefault = " + countryInListDefault);
+ return regionList;
+ } else {
+ boolean DEBUG = false;
+ RegionCodes[] regionList;
+ regionCode = null;
+ if (DEBUG) appendToLog("2 getCountryList");
+ regionList = getRegionList1();
+ if (DEBUG) appendToLog("2A getCountryList: regionList is " + (regionList != null ? "Valid" : "null"));
+ if (regionList != null) {
+ if (DEBUG) appendToLog(String.format("2b getCountryList: countryInList = %d, regionCode = %s", countryInList, (regionCode != null ? regionCode.toString() : "")));
+ if (countryInList < 0) {
+ if (regionCode == null) regionCode = regionList[0];
+ countryInList = 0;
+ for (int i = 0; i < regionList.length; i++) {
+ if (regionCode == regionList[i]) {
+ countryInList = i;
+ break;
+ }
+ }
+ if (countryInListDefault < 0) countryInListDefault = countryInList;
+ regionCode = regionList[countryInList];
+ if (DEBUG) appendToLog(String.format("2C getCountryList: countryInList = %d, regionCode = %s", countryInList, regionCode.toString()));
+ }
+ } else regionCode = null;
+ return regionList;
+ }
+ }
+ public boolean getChannelHoppingDefault() {
+ int countryCode = getCountryCode();
+ appendToLog("getChannelHoppingDefault: countryCode (for channelOrderType) = " + countryCode);
+ {
+ if (countryCode == 1 || countryCode == 8 || countryCode == 9) return false;
+ return true;
+ }
+ }
+ public int getCountryCode() {
+ if (bis108) return rfidReaderChipR2000.rx000OemSetting.getCountryCode();
+ final boolean DEBUG = false;
+ int iCountrycode = -1;
+ int iValue = rfidReaderChipE710.rx000Setting.getCountryEnum();
+ if (DEBUG) appendToLog("getCountryEnum 0x3014 = " + iValue);
+ if (iValue > 0 && iValue < countryChannelData.strCountryEnumInfo.length/countryChannelData.iCountryEnumInfoColumn) {
+ if (DEBUG) {
+ for (int i = 1; i <= 160; i++) {
+ appendToLog("i = " + i + ", " + countryChannelData.strCountryEnumInfo[(i - 1) * countryChannelData.iCountryEnumInfoColumn + 0]
+ + ", " + countryChannelData.strCountryEnumInfo[(i - 1) * countryChannelData.iCountryEnumInfoColumn + 1]
+ + ", " + countryChannelData.strCountryEnumInfo[(i - 1) * countryChannelData.iCountryEnumInfoColumn + 2]
+ + ", " + countryChannelData.strCountryEnumInfo[(i - 1) * countryChannelData.iCountryEnumInfoColumn + 3]
+ + ", " + countryChannelData.strCountryEnumInfo[(i - 1) * countryChannelData.iCountryEnumInfoColumn + 4]
+ + ", " + countryChannelData.strCountryEnumInfo[(i - 1) * countryChannelData.iCountryEnumInfoColumn + 5]
+ + ", " + countryChannelData.strCountryEnumInfo[(i - 1) * countryChannelData.iCountryEnumInfoColumn + 6]
+ );
+ }
+ }
+ String strCountryCode = countryChannelData.strCountryEnumInfo[(iValue - 1) * countryChannelData.iCountryEnumInfoColumn + 2];
+ if (DEBUG) appendToLog("strCountryCode 0 = " + strCountryCode);
+ String[] countryCodePart = strCountryCode.split(" ");
+ strCountryCode = countryCodePart[0].substring(1);
+ if (DEBUG) appendToLog("strCountryCode 1 = " + strCountryCode);
+ try {
+ iCountrycode = Integer.decode(strCountryCode);
+ if (DEBUG) appendToLog("iCountrycode = " + iCountrycode);
+ } catch (Exception ex) {
+ }
+ }
+ if (true) {
+ int iCountrycode1 = rfidReaderChipE710.rx000Setting.getCountryEnumOem();
+ if (DEBUG) appendToLog("getCountryEnumOem 0x5040 = " + iCountrycode1);
+ int iCountrycode2 = rfidReaderChipE710.rx000Setting.getCountryCodeOem();
+ if (DEBUG) appendToLog("getCountryCodeOem 0xef98 = " + iCountrycode2);
+ if (iCountrycode < 0 && iCountrycode1 > 0 && iCountrycode1 < 10) iCountrycode = iCountrycode1;
+ if (iCountrycode < 0 && iCountrycode2 > 0 && iCountrycode2 < 10) iCountrycode = iCountrycode2;
+ }
+ return iCountrycode;
+ }
+ public int getFreqModifyCode() {
+ if (bis108) return rfidReaderChipR2000.rx000OemSetting.getFreqModifyCode();
+ boolean DEBUG = false;
+ int iFreqModifyCode = rfidReaderChipE710.rx000Setting.getFreqModifyCode();
+ if (DEBUG) appendToLog("getFreqModifyCode 0xefb0 = " + iFreqModifyCode);
+ return iFreqModifyCode;
+ }
+ public boolean getRfidOnStatus() {
+ return rfidConnector.getOnStatus();
+ }
+ public boolean isRfidFailure() {
+ return rfidConnector.rfidFailure;
+ }
+ public void setReaderDefault() {
+ setPowerLevel(300);
+ setTagGroup(0, 0, 2);
+ setPopulation(60);
+ setInvAlgoNoSave(true);
+ setBasicCurrentLinkProfile();
+
+ setCountryInList(countryInListDefault);
+ setChannel(0);
+
+ //getAntennaPower(0)
+ //getPopulation()
+ //getQuerySession()
+ //getQueryTarget()
+ setTagFocus(false);
+ setFastId(false);
+ //getInvAlgo()
+ //\\getRetryCount()
+ //getCurrentProfile() + "\n"));
+ //\\getRxGain() + "\n"));
+ }
+ public void getReaderDefault() {
+ if (bis108 == false) {
+ rfidReaderChipE710.rx000Setting.getAntennaPortConfig(0);
+ rfidReaderChipE710.rx000Setting.getAntennaPortConfig(1);
+ rfidReaderChipE710.rx000Setting.getSelectConfiguration(0);
+ rfidReaderChipE710.rx000Setting.getSelectConfiguration(1);
+ rfidReaderChipE710.rx000Setting.getSelectConfiguration(2);
+ rfidReaderChipE710.rx000Setting.getMultibankReadConfig(0);
+ rfidReaderChipE710.rx000Setting.getMultibankReadConfig(1);
+ rfidReaderChipE710.rx000Setting.getRx000AccessPassword();
+ rfidReaderChipE710.rx000Setting.getRx000KillPassword();
+ rfidReaderChipE710.rx000Setting.getDupElimRollWindow();
+ //rfidReaderChip.rx000Setting.getEventPacketUplinkEnable();
+ rfidReaderChipE710.rx000Setting.setEventPacketUplinkEnable((byte) 0x09);
+ rfidReaderChipE710.rx000Setting.getIntraPacketDelay();
+ rfidReaderChipE710.rx000Setting.getFrequencyChannelIndex();
+ rfidReaderChipE710.rx000Setting.getCurrentPort();
+ }
+ }
+ public String getMacVer() {
+ appendToLog("RfidReader.getMacVersion: bis108 is " + bis108);
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.getMacVer() : rfidReaderChipE710.rx000Setting.getMacVer());
+ }
+ public String getRadioSerial() {
+ boolean DEBUG = true;
+ String strValue, strValue1;
+ strValue = getSerialNumber();
+ if (bis108 == false) {
+ if (DEBUG) appendToLog("getSerialNumber 0xEF9C = " + strValue);
+ strValue1 = getProductSerialNumber();
+ if (DEBUG) appendToLog("getProductSerialNumber 0x5020 = " + strValue1);
+ if (strValue1 != null && false) strValue = strValue1;
+ }
+ if (strValue != null) {
+ appendToLog("strValue length = " + strValue.length());
+ if (strValue.length() >= 13) strValue = strValue.substring(0, 13);
+ } else appendToLog("BBB");
+ if (DEBUG) appendToLog("strValue = " + strValue);
+ return strValue;
+ }
+ public String getRadioBoardVersion() {
+ String str = getSerialNumber();
+ if (str == null) return null;
+ if (str.length() != 16) return null;
+ if (bis108) {
+ String strOut;
+ if (str.substring(13, 14).matches("0")) strOut = str.substring(14, 15);
+ else strOut = str.substring(13, 15);
+ strOut += "." + str.substring(15);
+ str = strOut;
+ } else {
+ str = str.substring(13);
+ String string = "";
+ if (str.length() >= 2) string = str.substring(0, 2);
+ if (str.length() >= 3) string += ("." + str.substring(2, 3));
+ str = string;
+ }
+ return str;
+ }
+ public int getAntennaSelect() {
+ int iValue = 0;
+ iValue = (bis108 ? rfidReaderChipR2000.rx000Setting.getAntennaSelect() : rfidReaderChipE710.rx000Setting.getAntennaPort());
+ appendToLog("AntennaSelect = " + iValue);
+ return iValue;
+ }
+ public boolean setAntennaSelect(int number) {
+ boolean bValue = false;
+ bValue = (bis108 ? rfidReaderChipR2000.rx000Setting.setAntennaSelect(number) : rfidReaderChipE710.rx000Setting.setAntennaSelect(number));
+ appendToLog("AntennaSelect = " + number + " returning " + bValue);
+ return bValue;
+ }
+ public boolean getAntennaEnable() {
+ int iValue; boolean DEBUG = false;
+ if (DEBUG) appendToLog("1 getAntennaEnable");
+ iValue = (bis108 ? rfidReaderChipR2000.rx000Setting.getAntennaEnable() : rfidReaderChipE710.rx000Setting.getAntennaEnable());
+ if (DEBUG) appendToLog("1A getAntennaEnable: AntennaEnable = " + iValue);
+ if (iValue > 0) return true;
+ else return false;
+ }
+ public boolean setAntennaEnable(boolean enable) {
+ int iEnable = 0;
+ if (enable) iEnable = 1;
+ boolean bValue = false;
+ appendToLog("1A setAntennaEnable: iEnable = " + iEnable);
+ bValue = (bis108 ? rfidReaderChipR2000.rx000Setting.setAntennaEnable(iEnable) : rfidReaderChipE710.rx000Setting.setAntennaEnable(iEnable));
+ appendToLog("AntennaEnable = " + iEnable + " returning " + bValue);
+ if (bValue && bis108 == false) bValue = rfidReaderChipE710.rx000Setting.updateCurrentPort();
+ return bValue;
+ }
+ public long getAntennaDwell() {
+ long lValue = 0; boolean DEBUG = false;
+ if (DEBUG) appendToLog("1 getAntennaDwell");
+ lValue = (bis108 ? rfidReaderChipR2000.rx000Setting.getAntennaDwell() : rfidReaderChipE710.rx000Setting.getAntennaDwell());
+ if (DEBUG) appendToLog("1A getAntennaDwell: lValue = " + lValue);
+ //appendToLog("BtDataOut: getAntennaDwell as " + lValue);
+ return lValue;
+ }
+ public boolean setAntennaDwell(long antennaDwell) {
+ boolean bValue = false, DEBUG = false;
+ //appendToLog("BtDataOut: setAntennaDwell as " + antennaDwell);
+ if (DEBUG) appendToLog("1 AntennaDwell = " + antennaDwell + " returning " + bValue);
+ if (getAntennaDwell() == antennaDwell) return true;
+ bValue = (bis108 ? rfidReaderChipR2000.rx000Setting.setAntennaDwell(antennaDwell) : rfidReaderChipE710.rx000Setting.setAntennaDwell(antennaDwell));
+ if (DEBUG) appendToLog("1A AntennaDwell = " + antennaDwell + " returning " + bValue);
+ return bValue;
+ }
+ public long getPwrlevel() {
+ long lValue = 0;
+ lValue = (bis108 ? rfidReaderChipR2000.rx000Setting.getAntennaPower(-1) : rfidReaderChipE710.rx000Setting.getAntennaPower(-1));
+ return lValue;
+ }
+ public long pwrlevelSetting;
+ public boolean setPowerLevel(long pwrlevel) {
+ pwrlevelSetting = pwrlevel;
+ boolean bValue = false;
+ bValue = (bis108 ? rfidReaderChipR2000.rx000Setting.setAntennaPower(pwrlevel) : rfidReaderChipE710.rx000Setting.setAntennaPower(pwrlevel));
+ if (false) appendToLog("PowerLevel = " + pwrlevel + " returning " + bValue);
+ return bValue;
+ }
+ public int getQueryTarget() {
+ int iValue; boolean DEBUG = false;
+ iValue = (bis108 ? rfidReaderChipR2000.rx000Setting.getAlgoAbFlip() : rfidReaderChipE710.rx000Setting.getQueryTarget());
+ if (DEBUG) appendToLog("getQueryTarget with bis108 = " + bis108 + ", iValue = " + iValue);
+ if (bis108) {
+ if (iValue > 0) {
+ rfidReaderChipR2000.rx000Setting.getQueryTarget();
+ return 2;
+ }
+ else {
+ if (DEBUG) appendToLog("getQueryTarget");
+ iValue = rfidReaderChipR2000.rx000Setting.getQueryTarget();
+ if (iValue > 0) return 1;
+ return 0;
+ }
+ } else {
+ if (DEBUG) appendToLog("1A getQueryTarget: iValue = " + iValue);
+ if (iValue < 0) iValue = 0;
+ return iValue;
+ }
+ }
+ public int getQuerySession() {
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.getQuerySession() : rfidReaderChipE710.rx000Setting.getQuerySession());
+ }
+ public int getQuerySelect() {
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.getQuerySelect() : rfidReaderChipE710.rx000Setting.getQuerySelect());
+ }
+ public boolean setTagGroup(int sL, int session, int target1) {
+ if (bis108) {
+ rfidReaderChipR2000.rx000Setting.setAlgoSelect(getInvAlgoInChip()); //Must not delete this line
+ if (false) appendToLog("RfidReader.setTagGroup[" + target1 + ", " + session + ", " + sL);
+ return rfidReaderChipR2000.rx000Setting.setQueryTarget(target1, session, sL);
+ } else {
+ //appendToLog("1d");
+ int iAlgoAbFlip = rfidReaderChipE710.rx000Setting.getAlgoAbFlip();
+ appendToLog("sL = " + sL + ", session = " + session + ", target = " + target1 + ", getAlgoAbFlip = " + iAlgoAbFlip);
+ boolean bValue = false;
+ bValue = rfidReaderChipE710.rx000Setting.setQueryTarget(target1, session, sL);
+ if (bValue) {
+ if (iAlgoAbFlip != 0 && target1 < 2)
+ bValue = rfidReaderChipE710.rx000Setting.setAlgoAbFlip(0);
+ else if (iAlgoAbFlip == 0 && target1 >= 2)
+ bValue = rfidReaderChipE710.rx000Setting.setAlgoAbFlip(1);
+ }
+ return bValue;
+ }
+ }
+ public int tagFocus = -1;
+ public int getTagFocus() {
+ if (bis108) {
+ tagFocus = rfidReaderChipR2000.rx000Setting.getImpinjExtension();
+ if (tagFocus > 0) tagFocus = ((tagFocus & 0x10) >> 4);
+ } else {
+ tagFocus = rfidReaderChipE710.rx000Setting.getImpinjExtension() & 0x04;
+ }
+ return tagFocus;
+ }
+ public boolean setTagFocus(boolean tagFocusNew) {
+ boolean bRetValue;
+ if (bis108) {
+ bRetValue = rfidReaderChipR2000.rx000Setting.setImpinjExtension(tagFocusNew, (fastId > 0 ? true : false));
+ } else {
+ bRetValue = rfidReaderChipE710.rx000Setting.setImpinjExtension(tagFocusNew, (fastId > 0 ? true : false));
+ }
+ if (bRetValue) tagFocus = (tagFocusNew ? 1 : 0);
+ return bRetValue;
+ }
+ public int fastId = -1;
+ public int getFastId() {
+ if (rfidReaderChipR2000 != null) {
+ fastId = rfidReaderChipR2000.rx000Setting.getImpinjExtension();
+ if (fastId > 0) fastId = ((fastId & 0x20) >> 5);
+ } else {
+ fastId = rfidReaderChipE710.rx000Setting.getImpinjExtension() & 0x02;
+ }
+ return fastId;
+ }
+ public boolean setFastId(boolean fastIdNew) {
+ boolean bRetValue;
+ if (bis108) {
+ bRetValue = rfidReaderChipR2000.rx000Setting.setImpinjExtension((tagFocus > 0 ? true : false), fastIdNew);
+ } else {
+ bRetValue = rfidReaderChipE710.rx000Setting.setImpinjExtension((tagFocus > 0 ? true : false), fastIdNew);
+ }
+ if (bRetValue) fastId = (fastIdNew ? 1 : 0);
+ return bRetValue;
+ }
+ public boolean invAlgoSetting = true;
+ public boolean getInvAlgo() {
+ return invAlgoSetting;
+ }
+ public int getInvAlgoInChip() {
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.getInvAlgo() : rfidReaderChipE710.rx000Setting.getInvAlgo());
+ }
+ public boolean setInvAlgo(boolean dynamicAlgo) {
+ boolean DEBUG = false;
+ if (DEBUG) appendToLog("1 setInvAlgo with dynamicAlgo = " + dynamicAlgo);
+ boolean bValue = setInvAlgo1(dynamicAlgo);
+ if (bValue) invAlgoSetting = dynamicAlgo;
+ if (DEBUG) appendToLog("1A setInvAlgo with bValue = " + bValue);
+ return bValue;
+ }
+ public List getProfileList() {
+ if (bis108) return Arrays.asList(context.getResources().getStringArray(R.array.profile1_options));
+ appendToLog("getMacVer = " + rfidReaderChipE710.rx000Setting.getMacVer());
+ if (bluetoothGatt.isVersionGreaterEqual(rfidReaderChipE710.rx000Setting.getMacVer(), 2, 1, 1)) {
+ appendToLog("equal or greater than 2.1.1");
+ return Arrays.asList(context.getResources().getStringArray(R.array.profile4_options));
+ } else if (bluetoothGatt.isVersionGreaterEqual(rfidReaderChipE710.rx000Setting.getMacVer(), 1, 0, 250)) {
+ appendToLog("equal or greater than 1.0.250");
+ return Arrays.asList(context.getResources().getStringArray(R.array.profile3A_options));
+ } else {
+ appendToLog("matching less than 1.0.250");
+ return Arrays.asList(context.getResources().getStringArray(R.array.profile2_options)); //for 1.0.12
+ }
+ }
+ public int getCurrentProfile() {
+ if (bis108) return rfidReaderChipR2000.rx000Setting.getCurrentProfile();
+ boolean DEBUG = false;
+ if (DEBUG) appendToLog("1 getCurrentProfile");
+ int iValue;
+ if (true) {
+ iValue = rfidReaderChipE710.rx000Setting.getCurrentProfile();
+ if (DEBUG) appendToLog("1A getCurrentProfile: getCurrentProfile = " + iValue);
+ if (iValue > 0) {
+ List profileList = getProfileList();
+ if (DEBUG) appendToLog("1b getCurrentProfile: getProfileList = " + (profileList != null ? "valid" : ""));
+ int index = 0;
+ for (; index < profileList.size(); index++) {
+ if (Integer.valueOf(profileList.get(index).substring(0, profileList.get(index).indexOf(":"))) == iValue)
+ break;
+ }
+ if (index >= profileList.size()) {
+ index = profileList.size()-1;
+ setCurrentLinkProfile(index);
+ }
+ if (DEBUG) appendToLog("1C getCurrentProfile: index in the profileList = " + index);
+ iValue = index;
+ }
+ }
+ return iValue;
+ }
+ public boolean setBasicCurrentLinkProfile() {
+ if (bis108) return setCurrentLinkProfile(1);
+ boolean b211 = bluetoothGatt.isVersionGreaterEqual(rfidReaderChipE710.rx000Setting.getMacVer(), 2, 1, 1);
+ int profile = (b211 ? 343 : 244);
+ if (getCountryCode() == 1) profile = (b211 ? 342 : 241);
+ appendToLog("profile is " + profile);
+ return rfidReaderChipE710.rx000Setting.setCurrentProfile(profile);
+ }
+ public boolean setCurrentLinkProfile(int profile) {
+ if (bis108) {
+ if (profile == getCurrentProfile()) return true;
+ boolean result;
+ result = rfidReaderChipR2000.rx000Setting.setCurrentProfile(profile);
+ if (result) {
+ rfidReaderChipR2000.setPwrManagementMode(false);
+ result = rfidReaderChipR2000.sendHostRegRequestHST_CMD(RfidReaderChipData.HostCommands.CMD_UPDATELINKPROFILE);
+ }
+ if (result && profile == 3) {
+ appendToLog("It is profile3");
+ if (getTagDelay() < 2) result = setTagDelay((byte) 2);
+ }
+ return result;
+ }
+ boolean DEBUG = true;
+ if (DEBUG) appendToLog("1 setCurrentLinkProfile: input profile = " + profile);
+ if (true && profile < 50) {
+ List profileList = getProfileList();
+ if (profile < 0 || profile >= profileList.size()) return false;
+ int profile1 = Integer.valueOf(profileList.get(profile).substring(0, profileList.get(profile).indexOf(":")));
+ profile = profile1;
+ }
+ if (DEBUG) appendToLog("1A setCurrentLinkProfile: adjusted profile = " + profile);
+ boolean result = rfidReaderChipE710.rx000Setting.setCurrentProfile(profile);
+ if (DEBUG) appendToLog("1b setCurrentLinkProfile: after setCurrentProfile, result = " + result);
+ if (result) {
+ setPwrManagementMode(false);
+ }
+ if (DEBUG) appendToLog("1C setCurrentLinkProfile: after setPwrManagementMode, result = " + result + ", profile = " + profile);
+ if (result && profile == 3) {
+ if (getTagDelay() < 2) result = setTagDelay((byte)2);
+ }
+ if (DEBUG) appendToLog("1d setCurrentLinkProfile: after setTagDelay, result = " + result);
+ getCurrentProfile();
+ return result;
+ }
+ public void resetEnvironmentalRSSI() {
+ if (bis108) rfidReaderChipR2000.rx000EngSetting.resetRSSI();
+ else rfidReaderChipE710.rx000EngSetting.resetRSSI();
+ }
+ public String getEnvironmentalRSSI() {
+ int iValue;
+ if (bis108) {
+ rfidReaderChipR2000.setPwrManagementMode(false);
+ iValue = rfidReaderChipR2000.rx000EngSetting.getwideRSSI();
+ }
+ else {
+ rfidReaderChipE710.setPwrManagementMode(false);
+ iValue = rfidReaderChipE710.getwideRSSI();
+ }
+
+ if (iValue < 0) return null;
+ if (iValue > 255) return "Invalid data";
+ double dValue = (bis108 ? rfidReaderChipR2000.decodeNarrowBandRSSI((byte)iValue) : rfidReaderChipE710.decodeNarrowBandRSSI((byte)iValue));
+ return String.format("%.2f dB", dValue);
+ }
+ public int getHighCompression() {
+ return (bis108 ? rfidReaderChipR2000.rx000MbpSetting.getHighCompression() : rfidReaderChipE710.getHighCompression());
+ }
+ public int getRflnaGain() {
+ return (bis108 ? rfidReaderChipR2000.rx000MbpSetting.getRflnaGain() : rfidReaderChipE710.getRflnaGain());
+ }
+ public int getIflnaGain() {
+ return (bis108 ? rfidReaderChipR2000.rx000MbpSetting.getIflnaGain() : rfidReaderChipE710.getIflnaGain());
+ }
+ public int getAgcGain() {
+ return (bis108 ? rfidReaderChipR2000.rx000MbpSetting.getAgcGain() : rfidReaderChipE710.getAgcGain());
+ }
+ public int getRxGain() {
+ return (bis108 ? rfidReaderChipR2000.rx000MbpSetting.getRxGain() : rfidReaderChipE710.getRxGain());
+ }
+ public boolean setRxGain(int highCompression, int rflnagain, int iflnagain, int agcgain) {
+ return (bis108 ? rfidReaderChipR2000.rx000MbpSetting.setRxGain(highCompression, rflnagain, iflnagain, agcgain) : rfidReaderChipE710.setRxGain(highCompression, rflnagain, iflnagain, agcgain));
+ }
+ public boolean setRxGain(int rxGain) {
+ return (bis108 ? rfidReaderChipR2000.rx000MbpSetting.setRxGain(rxGain) : rfidReaderChipE710.setRxGain(rxGain));
+ }
+ public int FreqChnCnt() {
+ return FreqChnCnt(regionCode);
+ }
+ public int FreqChnCnt(RegionCodes regionCode) {
+ if (bis108) {
+ switch (regionCode) {
+ case FCC:
+ case AG:
+ case CL:
+ case CO:
+ case CR:
+ case DR:
+ case MX:
+ case PM:
+ case UG:
+ return countryChannelData.FCC_CHN_CNT;
+ case PR:
+ return countryChannelData.PRTableOfFreq.length;
+ case VZ:
+ return countryChannelData.VZ_CHN_CNT;
+ case AU:
+ return countryChannelData.AUS_CHN_CNT;
+ case BR1:
+ return countryChannelData.BR1_CHN_CNT;
+ case BR2:
+ return countryChannelData.BR2_CHN_CNT;
+ case BR3:
+ return countryChannelData.BR3_CHN_CNT;
+ case BR4:
+ return countryChannelData.BR4_CHN_CNT;
+ case BR5:
+ return countryChannelData.BR5_CHN_CNT;
+ case HK:
+ case SG:
+ case TH:
+ case VN:
+ return countryChannelData.HK_CHN_CNT;
+ case VN1:
+ return countryChannelData.VN1_CHN_CNT;
+ case VN2:
+ return countryChannelData.VN2_CHN_CNT;
+ case VN3:
+ return countryChannelData.VN3_CHN_CNT;
+ case BD:
+ return countryChannelData.BD_CHN_CNT;
+ case TW:
+ return countryChannelData.TW_CHN_CNT;
+ case MY:
+ return countryChannelData.MYS_CHN_CNT;
+ case ZA:
+ return countryChannelData.ZA_CHN_CNT;
+ case ID:
+ return countryChannelData.ID_CHN_CNT;
+ case IL:
+ return countryChannelData.IL_CHN_CNT;
+ case IL2019RW:
+ return countryChannelData.IL2019RW_CHN_CNT;
+ case PH:
+ return countryChannelData.PH_CHN_CNT;
+ case NZ:
+ return countryChannelData.NZ_CHN_CNT;
+ case CN:
+ return countryChannelData.CN_CHN_CNT;
+
+ case UH1:
+ return countryChannelData.UH1_CHN_CNT;
+ case UH2:
+ return countryChannelData.UH2_CHN_CNT;
+ case LH:
+ return countryChannelData.LH_CHN_CNT;
+ case LH1:
+ return countryChannelData.LH1_CHN_CNT;
+ case LH2:
+ return countryChannelData.LH2_CHN_CNT;
+
+ case ETSI:
+ return countryChannelData.ETSI_CHN_CNT;
+ case IN:
+ return countryChannelData.IDA_CHN_CNT;
+ case KR:
+ return countryChannelData.KR_CHN_CNT;
+ case KR2017RW:
+ return countryChannelData.KR2017RW_CHN_CNT;
+ case JP:
+ return countryChannelData.JPN2012_CHN_CNT;
+ case JP6:
+ return countryChannelData.JPN2012A_CHN_CNT;
+ case ETSIUPPERBAND:
+ return countryChannelData.ETSIUPPERBAND_CHN_CNT;
+
+ default:
+ return 0;
+ }
+ } else {
+ boolean DEBUG = true;
+ int iFreqChnCnt = -1, iValue = -1; //mRfidDevice.mRfidReaderChip.mRfidReaderChip.mRx000Setting.getCountryEnum(); //iValue--;
+ iValue = regionCode.ordinal() - RegionCodes.Albania1.ordinal() + 1;
+ if (DEBUG) appendToLog("regionCode = " + regionCode.toString() + ", regionCodeEnum = " + iValue);
+ if (iValue > 0) {
+ String strFreqChnCnt = countryChannelData.strCountryEnumInfo[(iValue - 1) * countryChannelData.iCountryEnumInfoColumn + 3];
+ if (DEBUG) appendToLog("strFreqChnCnt = " + strFreqChnCnt);
+ try {
+ iFreqChnCnt = Integer.parseInt(strFreqChnCnt);
+ } catch (Exception ex) {
+ appendToLog("!!! CANNOT parse strFreqChnCnt = " + strFreqChnCnt);
+ }
+ }
+ if (DEBUG) appendToLog("iFreqChnCnt = " + iFreqChnCnt);
+ return iFreqChnCnt; //1 for hopping, 0 for fixed
+ }
+ }
+ public double getLogicalChannel2PhysicalFreq(int channel) {
+ if (bis108) {
+ getCountryList(); // used to set up possibly regionCode
+ int TotalCnt = FreqChnCnt(regionCode);
+ int[] freqIndex = FreqIndex(regionCode);
+ double[] freqTable = GetAvailableFrequencyTable(regionCode);
+ if (freqIndex.length != TotalCnt || freqTable.length != TotalCnt || channel >= TotalCnt)
+ return -1;
+ return freqTable[freqIndex[channel]];
+ }
+ boolean DEBUG = false;
+ if (DEBUG) appendToLog("regionCode = " + regionCode.toString());
+ int TotalCnt = FreqChnCnt(regionCode);
+ if (DEBUG) appendToLog("TotalCnt = " + TotalCnt);
+ int[] freqIndex = FreqIndex(regionCode);
+ if (DEBUG) appendToLog("Frequency index " + (freqIndex != null ? ("length = " + freqIndex.length) : "null"));
+ double[] freqTable = GetAvailableFrequencyTable(regionCode);
+ if (DEBUG) appendToLog("Frequency freqTable " + (freqTable != null ? ("length = " + freqTable.length) : "null"));
+ if (DEBUG) appendToLog("Check TotalCnt = " + TotalCnt + ", freqIndex.length = " + freqIndex.length + ", freqTable.length = " + freqTable.length + ", channel = " + channel);
+ if (freqIndex.length != TotalCnt || freqTable.length != TotalCnt || channel >= TotalCnt) return -1;
+ double dRetvalue = freqTable[freqIndex[channel]];
+ if (DEBUG) appendToLog("channel = " + channel + ", dRetvalue = " + dRetvalue);
+ return dRetvalue;
+ }
+ public byte getTagDelay() {
+ return tagDelaySetting;
+ }
+ public boolean setTagDelay(byte tagDelay) {
+ tagDelaySetting = tagDelay;
+ return true;
+ }
+ boolean setTagDelay2RfidReader(int tagDelay) {
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.setTagDelay2RfidReader(tagDelay) : rfidReaderChipE710.rx000Setting.setTagDelay(tagDelay));
+ }
+ public byte getIntraPkDelay() {
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.getIntraPacketDelay() : rfidReaderChipE710.rx000Setting.getIntraPacketDelay());
+ }
+ public boolean setIntraPkDelay(byte intraPkDelay) {
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.setIntraPacketDelay(intraPkDelay) : rfidReaderChipE710.rx000Setting.setIntraPacketDelay(intraPkDelay));
+ }
+ public byte getDupDelay() {
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.getDupElimRollWindow() : rfidReaderChipE710.rx000Setting.getDupElimRollWindow());
+ }
+ public boolean setDupDelay(byte dupElim) {
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.setDupElimRollWindow(dupElim) : rfidReaderChipE710.rx000Setting.setDupElimRollWindow(dupElim));
+ }
+ public long getCycleDelay() {
+ cycleDelaySetting = (bis108 ? rfidReaderChipR2000.rx000Setting.getCycleDelay() : rfidReaderChipE710.rx000Setting.getCycleDelay());
+ return cycleDelaySetting;
+ }
+ public boolean setCycleDelay(long cycleDelay) {
+ cycleDelaySetting = cycleDelay;
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.setCycleDelay(cycleDelay) : rfidReaderChipE710.rx000Setting.setCycleDelay(cycleDelay));
+ }
+ public void getAuthenticateReplyLength() {
+ if (bis108) rfidReaderChipR2000.rx000Setting.getAuthenticateReplyLength();
+ else rfidReaderChipE710.rx000Setting.getAuthenticateReplyLength();
+ }
+ public boolean setTamConfiguration(boolean header, String matchData) {
+ appendToLog("header = " + header + ", matchData.length = " + matchData.length() + ", matchData = " + matchData);
+ if (matchData == null) matchData = "";
+ if (matchData.length() != 12) return false;
+ boolean retValue = false; String preChallenge = matchData.substring(0, 2);
+ int iValue = Integer.parseInt(preChallenge, 16);
+ iValue &= 0x07;
+ if (header) iValue |= 0x04;
+ else iValue &= ~0x04;
+ preChallenge = String.format("%02X", iValue);
+ matchData = preChallenge + matchData.substring(2);
+ appendToLog("new matchData = " + matchData);
+ if (bis108) {
+ retValue = setAuthMatchData(matchData);
+ appendToLog("setAuthMatchData returns " + retValue);
+ if (retValue) {
+ retValue = rfidReaderChipR2000.rx000Setting.setHST_AUTHENTICATE_CFG(true, true, 1, matchData.length() * 4);
+ appendToLog("setHST_AUTHENTICATE_CFG returns " + retValue);
+ }
+ return retValue;
+ } else {
+ boolean bValue = rfidReaderChipE710.rx000Setting.setAuthenticateConfig(((matchData.length() * 4) << 10) | (1 << 2) | 0x03);
+ appendToLog("setAuthenticateConfiguration 1 revised matchData = " + matchData + " with bValue = " + (bValue ? "true" : "false"));
+ appendToLog("revised bytes = " + utility.byteArrayToString(utility.string2ByteArray(matchData)));
+ if (bValue) {
+ bValue = rfidReaderChipE710.rx000Setting.setAuthenticateMessage(utility.string2ByteArray(matchData));
+ appendToLog("setAuthenticateConfiguration 2: bValue = " + (bValue ? "true" : "false"));
+ }
+ if (bValue) {
+ int iLength = 8 * 8;
+ if (header) iLength = 16 * 8;
+ bValue = rfidReaderChipE710.rx000Setting.setAuthenticateResponseLen(iLength);
+ appendToLog("setAuthenticateConfiguration 3: bValue = " + (bValue ? "true" : "false"));
+ }
+ return bValue;
+ }
+ }
+ public boolean setTam1Configuration(int keyId, String matchData) {
+ appendToLog("keyId = " + keyId + ", matchData = " + matchData);
+ if (keyId > 255) return false;
+ if (matchData == null) matchData = "";
+ if (matchData.length() != 20) return false;
+
+ boolean retValue = false; String preChallenge = "00";
+ preChallenge += String.format("%02X", keyId);
+ matchData = preChallenge + matchData;
+ if (bis108) {
+ retValue = setAuthMatchData(matchData);
+ appendToLog("setAuthMatchData returns " + retValue);
+ if (retValue) {
+ retValue = rfidReaderChipR2000.rx000Setting.setHST_AUTHENTICATE_CFG(true, true, 0, matchData.length() * 4);
+ appendToLog("setHST_AUTHENTICATE_CFG returns " + retValue);
+ }
+ return retValue;
+ } else {
+ boolean bValue = rfidReaderChipE710.rx000Setting.setAuthenticateConfig(((matchData.length() * 4) << 10) | (0 << 2) | 0x03);
+ appendToLog("setAuthenticateConfiguration 1 revised matchData = " + matchData + " with bValue = " + (bValue ? "true" : "false"));
+ appendToLog("revised bytes = " + utility.byteArrayToString(utility.string2ByteArray(matchData)));
+ if (bValue) {
+ if (true)
+ bValue = rfidReaderChipE710.rx000Setting.setAuthenticateMessage(utility.string2ByteArray(matchData));
+ else
+ bValue = rfidReaderChipE710.rx000Setting.setAuthenticateMessage(new byte[]{
+ 0, 0, (byte) 0xFD, (byte) 0x5D,
+ (byte) 0x80, 0x48, (byte) 0xF4, (byte) 0x8D,
+ (byte) 0xD0, (byte) 0x9A, (byte) 0xAD, 0x22});
+ appendToLog("setAuthenticateConfiguration 2: bValue = " + (bValue ? "true" : "false"));
+ }
+ if (bValue) {
+ bValue = rfidReaderChipE710.rx000Setting.setAuthenticateResponseLen(16 * 8);
+ appendToLog("setAuthenticateConfiguration 3: bValue = " + (bValue ? "true" : "false"));
+ }
+ return bValue;
+ }
+ }
+ public boolean setTam2Configuration(int keyId, String matchData, int profile, int offset, int blockId, int protMode) {
+ if (keyId > 255) return false;
+ if (matchData == null) matchData = "";
+ if (matchData.length() != 20) return false;
+ if (profile > 15) return false;
+ if (offset > 0xFFF) return false;
+ if (blockId > 15) return false;
+ if (protMode > 15) return false;
+
+ boolean retValue = false;
+ String preChallenge = "20";
+ String postChallenge;
+ preChallenge += String.format("%02X", keyId);
+ postChallenge = String.valueOf(profile);
+ postChallenge += String.format("%03X", offset);
+ postChallenge += String.valueOf(blockId);
+ postChallenge += String.valueOf(protMode);
+ matchData = preChallenge + matchData + postChallenge;
+ if (bis108) {
+ retValue = setAuthMatchData(matchData);
+ if (retValue) {
+ retValue = rfidReaderChipR2000.rx000Setting.setHST_AUTHENTICATE_CFG(true, true, 0, matchData.length() * 4);
+ }
+ return retValue;
+ } else {
+ boolean bValue = rfidReaderChipE710.rx000Setting.setAuthenticateConfig(((matchData.length() * 4) << 10) | (0 << 2) | 0x03);
+ appendToLog("setAuthenticateConfiguration 1 revised matchData = " + matchData + " with bValue = " + (bValue ? "true" : "false"));
+ appendToLog("revised bytes = " + utility.byteArrayToString(utility.string2ByteArray(matchData)));
+ if (bValue) {
+ if (true)
+ bValue = rfidReaderChipE710.rx000Setting.setAuthenticateMessage(utility.string2ByteArray(matchData));
+ else
+ bValue = rfidReaderChipE710.rx000Setting.setAuthenticateMessage(new byte[]{
+ 0, 0, (byte) 0xFD, (byte) 0x5D,
+ (byte) 0x80, 0x48, (byte) 0xF4, (byte) 0x8D,
+ (byte) 0xD0, (byte) 0x9A, (byte) 0xAD, 0x22});
+ appendToLog("setAuthenticateConfiguration 2: bValue = " + (bValue ? "true" : "false"));
+ }
+ if (bValue) {
+ int iSize = 32;
+ if (protMode > 2) iSize = 44;
+ bValue = rfidReaderChipE710.rx000Setting.setAuthenticateResponseLen(iSize * 8);
+ appendToLog("setAuthenticateConfiguration 3: protMode = " + protMode + ", bValue = " + (bValue ? "true" : "false"));
+ }
+ return bValue;
+ }
+ }
+ public int getUntraceableEpcLength() {
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.getUntraceableEpcLength() : rfidReaderChipE710.rx000Setting.getUntraceableEpcLength());
+ }
+ public boolean setUntraceable(boolean bHideEpc, int ishowEpcSize, int iHideTid, boolean bHideUser, boolean bHideRange) {
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.setHST_UNTRACEABLE_CFG(bHideRange ? 2 : 0, bHideUser, iHideTid, ishowEpcSize, bHideEpc, false) : rfidReaderChipE710.rx000Setting.setHST_UNTRACEABLE_CFG(bHideRange ? 2 : 0, bHideUser, iHideTid, ishowEpcSize, bHideEpc, false));
+ }
+ public boolean setUntraceable(int range, boolean user, int tid, int epcLength, boolean epc, boolean uxpc) {
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.setHST_UNTRACEABLE_CFG(range, user, tid, epcLength, epc, uxpc) : rfidReaderChipE710.rx000Setting.setHST_UNTRACEABLE_CFG(range, user, tid, epcLength, epc, uxpc));
+ }
+ public boolean setAuthenticateConfiguration() {
+ boolean bValue = (bis108 ?
+ rfidReaderChipR2000.rx000Setting.setHST_AUTHENTICATE_CFG(true, true, 1, 48)
+ : rfidReaderChipE710.rx000Setting.setAuthenticateConfig((48 << 10) | (1 << 2) | 0x03));
+ if (bis108) {
+ if (bValue) {
+ bValue = rfidReaderChipR2000.rx000Setting.setAuthMatchData("049CA53E55EA"); //setAuthenticateMessage(new byte[] { 0x04, (byte)0x9C, (byte)0xA5, 0x3E, 0x55, (byte)0xEA } );
+ appendToLog("setAuthenuateConfiguration 2: bValue = " + (bValue ? "true" : "false"));
+ }
+ /*if (bValue) {
+ bValue = mRfidDevice.mRfidReaderChip.mRfidReaderChip.mRx000Setting.setAuthenticateResponseLen(16 * 8);
+ appendToLog("setAuthenuateConfiguration 3: bValue = " + (bValue ? "true" : "false"));
+ }*/
+ return false; //bValue;
+ } else {
+ if (bValue) {
+ bValue = rfidReaderChipE710.rx000Setting.setAuthenticateMessage(new byte[]{0x04, (byte) 0x9C, (byte) 0xA5, 0x3E, 0x55, (byte) 0xEA});
+ appendToLog("setAuthenticateConfiguration 2: bValue = " + (bValue ? "true" : "false"));
+ }
+ if (bValue) {
+ bValue = rfidReaderChipE710.rx000Setting.setAuthenticateResponseLen(16 * 8);
+ appendToLog("setAuthenticateConfiguration 3: bValue = " + (bValue ? "true" : "false"));
+ }
+ return bValue;
+ }
+ }
+ public int getRetryCount() {
+ if (bis108) {
+ int algoSelect;
+ algoSelect = rfidReaderChipR2000.rx000Setting.getAlgoSelect();
+ if (algoSelect == 0 || algoSelect == 3) {
+ return rfidReaderChipR2000.rx000Setting.getAlgoRetry(algoSelect);
+ } else return -1;
+ } else {
+ return rfidReaderChipE710.rx000Setting.getAlgoMinQCycles();
+ }
+ }
+ public boolean setRetryCount(int retryCount) {
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.setAlgoRetry(retryCount) : rfidReaderChipE710.rx000Setting.setAlgoMinQCycles(retryCount));
+ }
+ public int getInvSelectIndex() {
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.getInvSelectIndex(): rfidReaderChipE710.rx000Setting.getInvSelectIndex());
+ }
+ public boolean getSelectEnable() {
+ int iValue = (bis108 ?
+ rfidReaderChipR2000.rx000Setting.getSelectEnable() :
+ rfidReaderChipE710.rx000Setting.getSelectEnable());
+ return iValue > 0 ? true : false;
+ }
+ public int getSelectTarget() {
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.getSelectTarget() : rfidReaderChipE710.rx000Setting.getSelectTarget());
+ }
+ public int getSelectAction() {
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.getSelectAction() : rfidReaderChipE710.rx000Setting.getSelectAction());
+ }
+ public int getSelectMaskBank() {
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.getSelectMaskBank() : rfidReaderChipE710.rx000Setting.getSelectMaskBank());
+ }
+ public int getSelectMaskOffset() {
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.getSelectMaskOffset() : rfidReaderChipE710.rx000Setting.getSelectMaskOffset());
+ }
+ public String getSelectMaskData() {
+ int iValue1;
+ iValue1 = (bis108 ? rfidReaderChipR2000.rx000Setting.getSelectMaskLength() : rfidReaderChipE710.rx000Setting.getSelectMaskLength());
+ if (iValue1 < 0) return null;
+ String strValue = (bis108 ? rfidReaderChipR2000.rx000Setting.getSelectMaskData() : rfidReaderChipE710.rx000Setting.getSelectMaskData());
+ if (strValue == null) return null;
+ int strLength = iValue1 / 4;
+ if (strLength * 4 != iValue1) strLength++;
+ if (false) appendToLog("Mask data = iValue1 = " + iValue1 + ", strValue = " + strValue + ", strLength = " + strLength);
+ if (strValue.length() < strLength) strLength = strValue.length();
+ return strValue.substring(0, strLength);
+ }
+ public boolean setInvSelectIndex(int invSelect) {
+ if (false) appendToLog("BtDataOut: RfidReader.setSelectIndex goes to setInvSelectIndex");
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.setInvSelectIndex(invSelect) : rfidReaderChipE710.rx000Setting.setInvSelectIndex(invSelect));
+ }
+ public int findFirstEmptySelect() {
+ int iValue = -1, iSelectEnable;
+ for (int i = 0; i < 3; i++) {
+ if (false) appendToLog("RfidReader.findFirstEmptySelect goes to setInvSelectIndex with i = " + i);
+ if (bis108) rfidReaderChipR2000.rx000Setting.setInvSelectIndex(i);
+ iSelectEnable = (bis108 ? rfidReaderChipR2000.rx000Setting.getSelectEnable() : rfidReaderChipE710.rx000Setting.selectConfiguration[i][0]);
+ if (iSelectEnable == 0) {
+ iValue = i;
+ appendToLog("cs710Library4A: setSelectCriteria 1 with New index = " + iValue);
+ break;
+ }
+ }
+ return iValue;
+ }
+ public boolean setSelectCriteriaDisable(int index) {
+ if (bis108) rfidReaderChipR2000.rx000Setting.setQuerySelect(0);
+ else rfidReaderChipE710.rx000Setting.setQuerySelect(0);
+ if (utility.DEBUG_SELECT) appendToLog("Debug_Select: RfidReader.setSelectCriteriaDisable[" + index + "] goes to setSelectCriteria");
+ boolean bValue = false;
+ if (index < 0) {
+ for (int i = 0; i < 3; i++) {
+ bValue = setSelectCriteria(i, false, 0, 0, 0, 0, 0, "");
+ if (bValue == false) {
+ break;
+ }
+ }
+ } else {
+ bValue = setSelectCriteria(index, false, 0, 0, 0, 0, 0, "");
+ }
+ return bValue;
+ }
+ public boolean setSelectCriteria(int index, boolean enable, int target, int action, int bank, int offset, String mask, boolean maskbit) {
+ if (index == 0) settingData.preFilterData = new SettingData.PreFilterData(enable, target, action, bank, offset, mask, maskbit);
+ if (index < 0) index = findFirstEmptySelect();
+ if (index < 0) {
+ appendToLog("cs710Library4A: no index is available !!!"); return false;
+ }
+
+ appendToLog("mask = " + mask + ", maskbit = " + maskbit);
+ if (mask == null) mask = "";
+ int maskblen = mask.length() * 4;
+ String maskHex = ""; int iHex = 0;
+ if (maskbit) {
+ for (int i = 0; i < mask.length(); i++) {
+ iHex <<= 1;
+ if (mask.substring(i, i+1).matches("0")) iHex &= 0xFE;
+ else if (mask.substring(i, i+1).matches("1")) iHex |= 0x01;
+ else return false;
+ if ((i+1) % 4 == 0) maskHex += String.format("%1X", iHex & 0x0F);
+ }
+ int iBitRemain = mask.length() % 4;
+ if (iBitRemain != 0) {
+ iHex <<= (4 - iBitRemain);
+ maskHex += String.format("%1X", iHex & 0x0F);
+ }
+ maskblen = mask.length();
+ mask = maskHex;
+ }
+ if (false) appendToLog("RfidReader.setSelectCriteria goes to setSelectCriteria3");
+ return setSelectCriteria3(index, enable, target, action, 0, bank, offset, mask, maskblen);
+ }
+ public boolean setSelectCriteria(int index, boolean enable, int target, int action, int delay, int bank, int offset, String mask) {
+ if (utility.DEBUG_SELECT) appendToLog("Debug_Select: RfidReader.setSelectCriteria with index = " + index + ", enable = " + enable + ", bSelectedEnable[" + index + "] = " + bSelectEnabled[index]);
+ if (bis108) {
+ if (!enable) {
+ if (bSelectEnabled[index] == enable) return true;
+ }
+ if (false) appendToLog("cs108Library4A: setSelectCriteria 2 with index = " + index + ", enable = " + enable + ", target = " + target + ", action = " + action + ", delay = " + delay + ", bank = " + bank + ", offset = " + offset + ", mask = " + mask);
+ if (index < 0) index = findFirstEmptySelect();
+ if (index < 0) {
+ appendToLog("cs710Library4A: no index is available !!!");
+ return false;
+ }
+
+ if (index == 0)
+ settingData.preFilterData = new SettingData.PreFilterData(enable, target, action, bank, offset, mask, false);
+ if (mask == null) mask = "";
+ if (mask.length() > 64) mask = mask.substring(0, 64);
+ if (index == 0)
+ preMatchData = new RfidReader.PreMatchData(enable, target, action, bank, offset, mask, mask.length() * 4, rfidReaderChipR2000.rx000Setting.getQuerySelect(), getPwrlevel(), getInvAlgo(), getQValue());
+ boolean result = true;
+ if (index != rfidReaderChipR2000.rx000Setting.getInvSelectIndex()) {
+ if (false) appendToLog("RfidReader.setSelectCriteria goes to setInvSelectIndex");
+ result = rfidReaderChipR2000.rx000Setting.setInvSelectIndex(index);
+ }
+ if (rfidReaderChipR2000.rx000Setting.getSelectEnable() == 0 && enable == false) {
+ appendToLog("cs108Library4A: setSelectCriteria 2: no need to set as when index = " + index + ", getSelectEnable() = " + rfidReaderChipR2000.rx000Setting.getSelectEnable() + ", new enable = " + enable);
+ result = true;
+ } else {
+ if (utility.DEBUG_SELECT) appendToLog("Debug_Select: RfidReader.setSelectCriteria goes to setSelectEnable with result = " + result);
+ if (result)
+ result = rfidReaderChipR2000.rx000Setting.setSelectEnable(enable ? 1 : 0, target, action, delay);
+ if (result) result = rfidReaderChipR2000.rx000Setting.setSelectMaskBank(bank);
+ if (result) result = rfidReaderChipR2000.rx000Setting.setSelectMaskOffset(offset);
+ if (mask == null) return false;
+ if (result)
+ result = rfidReaderChipR2000.rx000Setting.setSelectMaskLength(mask.length() * 4);
+ if (result) result = rfidReaderChipR2000.rx000Setting.setSelectMaskData(mask);
+ if (false) appendToLog("RfidReader.setSelectCriteria with result = " + result + ", enable = " + enable);
+ if (result) {
+ if (enable) {
+ rfidReaderChipR2000.rx000Setting.setTagSelect(1);
+ rfidReaderChipR2000.rx000Setting.setQuerySelect(3);
+ } else {
+ rfidReaderChipR2000.rx000Setting.setTagSelect(0);
+ rfidReaderChipR2000.rx000Setting.setQuerySelect(0);
+ }
+ }
+ }
+ if (result) {
+ bSelectEnabled[index] = enable;
+ }
+ return result;
+ } else {
+ boolean bValue = false, DEBUG = false;
+ appendToLog("cs710Library4A: setSelectCriteria 2 with index = " + index + ", enable = " + enable + ", target = " + target + ", action = " + action + ", delay = " + delay + ", bank = " + bank + ", offset = " + offset + ", mask = " + mask);
+ if (index < 0) index = findFirstEmptySelect();
+ if (index < 0) {
+ appendToLog("cs710Library4A: no index is available !!!"); return false;
+ }
+
+ if (rfidReaderChipE710.rx000Setting.selectConfiguration[index] == null) appendToLog("CANNOT continue as selectConfiguration[" + index + "] is null !!!");
+ else if (rfidReaderChipE710.rx000Setting.selectConfiguration[index][0] != 0 || enable != false) {
+ if (DEBUG) appendToLog("0 selectConfiguration[" + index + "] = " + utility.byteArrayToString(rfidReaderChipE710.rx000Setting.selectConfiguration[index]));
+ byte[] byteArrayMask = null;
+ if (mask != null) byteArrayMask = utility.string2ByteArray(mask);
+ bValue = rfidReaderChipE710.rx000Setting.setSelectConfiguration(index, enable, bank, offset, byteArrayMask, target, action, delay);
+ if (DEBUG) appendToLog("0 selectConfiguration[" + index + "] = " + utility.byteArrayToString(rfidReaderChipE710.rx000Setting.selectConfiguration[index]));
+ } else {
+ appendToLog("cs710Library4A: setSelectCriteria 2: no need to set as old selectConfiguration[" + index + "][0] = " + rfidReaderChipE710.rx000Setting.selectConfiguration[index][0] + ", new enable = " + enable);
+ bValue = true;
+ }
+ return bValue;
+ }
+ }
+ public boolean getRssiFilterEnable() {
+ int iValue = (bis108 ? rfidReaderChipR2000.rx000Setting.getRssiFilterType() : rfidReaderChipE710.rx000Setting.getRssiFilterType());
+ if (iValue < 0) return false;
+ iValue &= 0xF;
+ return (iValue > 0 ? true : false);
+ }
+ public int getRssiFilterType() {
+ int iValue = (bis108 ? rfidReaderChipR2000.rx000Setting.getRssiFilterType() : rfidReaderChipE710.rx000Setting.getRssiFilterType());
+ if (iValue < 0) return 0;
+ iValue &= 0xF;
+ if (iValue < 2) return 0;
+ return iValue - 1;
+ }
+ public int getRssiFilterOption() {
+ int iValue = (bis108 ? rfidReaderChipR2000.rx000Setting.getRssiFilterOption() : rfidReaderChipE710.rx000Setting.getRssiFilterOption());
+ if (iValue < 0) return 0;
+ iValue &= 0xF;
+ return iValue;
+ }
+ public boolean setRssiFilterConfig(boolean enable, int rssiFilterType, int rssiFilterOption) {
+ int iValue = 0;
+ if (enable == false) iValue = 0;
+ else iValue = rssiFilterType + 1;
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.setHST_INV_RSSI_FILTERING_CONFIG(iValue, rssiFilterOption) : rfidReaderChipE710.rx000Setting.setHST_INV_RSSI_FILTERING_CONFIG(iValue, rssiFilterOption));
+ }
+ public double getRssiFilterThreshold1() {
+ double dValue;
+ if (bis108) {
+ int iValue = rfidReaderChipR2000.rx000Setting.getRssiFilterThreshold1();
+ byte byteValue = (byte) (iValue & 0xFF);
+ dValue = rfidReaderChipR2000.decodeNarrowBandRSSI(byteValue);
+ } else {
+ int iValue = rfidReaderChipE710.rx000Setting.getRssiFilterThreshold1();
+ dValue = (double) iValue;
+ dValue /= 100;
+ dValue += dBuV_dBm_constant;
+ }
+ return dValue;
+ }
+ public double getRssiFilterThreshold2() {
+ int iValue = (bis108 ? rfidReaderChipR2000.rx000Setting.getRssiFilterThreshold2() : rfidReaderChipE710.rx000Setting.getRssiFilterThreshold2());
+ appendToLog("iValue = " + iValue);
+ byte byteValue = (byte)(iValue & 0xFF);
+ double dValue = (bis108 ? rfidReaderChipR2000.decodeNarrowBandRSSI(byteValue) : rfidReaderChipE710.decodeNarrowBandRSSI(byteValue));
+ return dValue;
+ }
+ public boolean setRssiFilterThreshold(double rssiFilterThreshold1, double rssiFilterThreshold2) {
+ if (bis108) {
+ appendToLog("rssiFilterThreshold = " + rssiFilterThreshold1 + ", " + rssiFilterThreshold2);
+ return rfidReaderChipR2000.rx000Setting.setHST_INV_RSSI_FILTERING_THRESHOLD(rfidReaderChipR2000.encodeNarrowBandRSSI(rssiFilterThreshold1), rfidReaderChipR2000.encodeNarrowBandRSSI(rssiFilterThreshold2));
+ } else {
+ appendToLog("rssiFilterThreshold = " + rssiFilterThreshold1 + ", rssiFilterThreshold2 = " + rssiFilterThreshold2);
+ rssiFilterThreshold1 -= dBuV_dBm_constant;
+ rssiFilterThreshold2 -= dBuV_dBm_constant;
+ appendToLog("After adjustment, rssiFilterThreshold = " + rssiFilterThreshold1 + ", rssiFilterThreshold2 = " + rssiFilterThreshold2);
+ rssiFilterThreshold1 *= 100;
+ rssiFilterThreshold2 *= 100;
+ appendToLog("After multiplication, rssiFilterThreshold = " + rssiFilterThreshold1 + ", rssiFilterThreshold2 = " + rssiFilterThreshold2);
+ return rfidReaderChipE710.rx000Setting.setHST_INV_RSSI_FILTERING_THRESHOLD((int) rssiFilterThreshold1, (int) rssiFilterThreshold2);
+ }
+ }
+ public long getRssiFilterCount() {
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.getRssiFilterCount() : rfidReaderChipE710.rx000Setting.getRssiFilterCount());
+ }
+ public boolean setRssiFilterCount(long rssiFilterCount) {
+ appendToLog("rssiFilterCount = " + rssiFilterCount);
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.setHST_INV_RSSI_FILTERING_COUNT(rssiFilterCount) : rfidReaderChipE710.rx000Setting.setHST_INV_RSSI_FILTERING_COUNT(rssiFilterCount));
+ }
+ public boolean getInvMatchEnable() {
+ int iValue = (bis108 ? rfidReaderChipR2000.rx000Setting.getInvMatchEnable() : rfidReaderChipE710.rx000Setting.getInvMatchEnable());
+ return iValue > 0 ? true : false;
+ }
+ public boolean getInvMatchType() {
+ int iValue = (bis108 ? rfidReaderChipR2000.rx000Setting.getInvMatchType() : rfidReaderChipE710.rx000Setting.getInvMatchType());
+ return iValue > 0 ? true : false;
+ }
+ public int getInvMatchOffset() {
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.getInvMatchOffset() : rfidReaderChipE710.rx000Setting.getInvMatchOffset());
+ }
+ public String getInvMatchData() {
+ int iValue1 = (bis108 ? rfidReaderChipR2000.rx000Setting.getInvMatchLength() : rfidReaderChipE710.rx000Setting.getInvMatchLength());
+ if (iValue1 < 0) return null;
+ String strValue = (bis108 ? rfidReaderChipR2000.rx000Setting.getInvMatchData() : rfidReaderChipE710.rx000Setting.getInvMatchData());
+ int strLength = iValue1 / 4;
+ if (strLength * 4 != iValue1) strLength++;
+ return strValue.substring(0, strLength);
+ }
+ String getSpecialCountryVersion() {
+ boolean DEBUG = false;
+ if (bis108) return rfidReaderChipR2000.rx000OemSetting.getSpecialCountryVersion();
+ String strSpecialCountryCode = null;
+ int iValue = rfidReaderChipE710.rx000Setting.getCountryEnum();
+ if (DEBUG) appendToLog("getCountryEnum 0x3014 = " + iValue);
+ if (iValue > 0 && iValue < countryChannelData.strCountryEnumInfo.length/countryChannelData.iCountryEnumInfoColumn) {
+ String strCountryCode = countryChannelData.strCountryEnumInfo[(iValue - 1) * countryChannelData.iCountryEnumInfoColumn + 2];
+ if (DEBUG) appendToLog("strCountryCode 0 = " + strCountryCode);
+ String[] countryCodePart = strCountryCode.split(" ");
+ if (DEBUG) appendToLog("countryCodePart.length = " + countryCodePart.length);
+ if (countryCodePart.length >= 2) strSpecialCountryCode = countryCodePart[1];
+ else strSpecialCountryCode = "";
+ if (DEBUG) appendToLog("strSpecialCountryCode = " + strSpecialCountryCode);
+ }
+ if (true) {
+ String strValue = rfidReaderChipE710.rx000Setting.getSpecialCountryCodeOem();
+ if (DEBUG) appendToLog("getCountryCodeOem 0xefac = " + strValue);
+ if (strSpecialCountryCode == null && strValue != null) {
+ if (DEBUG) appendToLog("strSpecialCountryCode is replaced with countryCodeOem");
+ strSpecialCountryCode = strValue;
+ }
+ }
+ return strSpecialCountryCode;
+ }
+ public static class PostMatchData {
+ public boolean enable; public boolean target; public int offset; public String mask; public long pwrlevel; public boolean invAlgo; public int qValue;
+ public PostMatchData(boolean enable, boolean target, int offset, String mask, int antennaCycle, long pwrlevel, boolean invAlgo, int qValue) {
+ this.enable = enable;
+ this.target = target;
+ this.offset = offset;
+ this.mask = mask;
+ this.pwrlevel = pwrlevel;
+ this.invAlgo = invAlgo;
+ this.qValue = qValue;
+ }
+ }
+ public PostMatchData postMatchData;
+ public boolean setPostMatchCriteria(boolean enable, boolean target, int offset, String mask) {
+ postMatchData = new RfidReader.PostMatchData(enable, target, offset, mask, getAntennaCycle(), getPwrlevel(), getInvAlgo(), getQValue());
+ boolean result = (bis108 ? rfidReaderChipR2000.rx000Setting.setInvMatchEnable(enable ? 1 : 0, target ? 1 : 0, mask == null ? -1 : mask.length() * 4, offset)
+ : rfidReaderChipE710.rx000Setting.setInvMatchEnable(enable ? 1 : 0, target ? 1 : 0, mask == null ? -1 : mask.length() * 4, offset));
+ if (result && mask != null) result = (bis108 ? rfidReaderChipR2000.rx000Setting.setInvMatchData(mask) : rfidReaderChipE710.rx000Setting.setInvMatchData(mask));
+ return result;
+ }
+ public int rfidToWriteSize() {
+ return mRfidToWrite.size();
+ }
+ public void mrfidToWritePrint() {
+ for (int i = 0; i < mRfidToWrite.size(); i++) {
+ appendToLog(utility.byteArrayToString(mRfidToWrite.get(i).dataValues));
+ }
+ }
+ public long getTagRate() {
+ return (bis108 ? -1 : rfidReaderChipE710.rx000Setting.getTagRate());
+ }
+ public boolean startOperation(RfidReaderChipData.OperationTypes operationTypes) {
+ boolean retValue = false;
+ switch (operationTypes) {
+ case TAG_INVENTORY_COMPACT:
+ case TAG_INVENTORY:
+ case TAG_SEARCHING:
+ //setInventoring(true);
+ if (false && operationTypes == RfidReaderChipData.OperationTypes.TAG_INVENTORY) {
+ //setTam1Configuration(0, "FD5D8048F48DD09AAD22");
+ setTam2Configuration(1, "FD5D8048F48DD09AAD22", 0, 0, 1, 1);
+ setInvAuthenticate(true);
+ }
+ if (utility.DEBUG_COMPACT) appendToLog("Debug_Compact 0: RfidReadder.startOperation operationTypes is " + operationTypes.toString());
+ if (operationTypes == RfidReaderChipData.OperationTypes.TAG_INVENTORY_COMPACT) {
+ setTagDelay2RfidReader(0); setMatchRep(0);
+ if (false && tagFocus >= 1) {
+ setTagGroup(-1, 1, 0); //Set Session S1, Target A
+ setTagDelay2RfidReader(0);
+ setAntennaDwell(2000);
+ }
+ if (utility.DEBUG_COMPACT) appendToLog("Debug_Compact 4: RfidReadder.startOperation goes to setInvModeCompact");
+ setInvModeCompact(true);
+ } else {
+ setTagDelay2RfidReader(tagDelayDefaultNormalSetting);
+ if (bis108) {
+ rfidReaderChipR2000.rx000Setting.setCycleDelay(cycleDelaySetting);
+ } else {
+ rfidReaderChipE710.rx000Setting.setCycleDelay(cycleDelaySetting);
+ }
+ setInvModeCompact(false);
+ if (utility.DEBUG_COMPACT) appendToLog("Debug_Compact 5: RfidReadder.startOperation goes to setInvModeCompact");
+ if (operationTypes == RfidReaderChipData.OperationTypes.TAG_SEARCHING && bis108 == false) rfidReaderChipE710.rx000Setting.setDupElimRollWindow((byte)0);
+ }
+ if (bis108) {
+ notificationConnector.getAutoRFIDAbort();
+ notificationConnector.setAutoRFIDAbort(true);
+ notificationConnector.getAutoRFIDAbort();
+ rfidReaderChipR2000.setPwrManagementMode(false);
+ appendToLog("going to sendHostRegRequestHST_CMD(Cs108Library4A.HostCommands.CMD_18K6CINV)");
+
+ retValue = true;
+ RfidReaderChipData.HostCommands hostCommand = RfidReaderChipData.HostCommands.CMD_18K6CINV;
+ retValue = rfidReaderChipR2000.sendHostRegRequestHST_CMD(hostCommand);
+ break;
+ } else {
+ rfidReaderChipE710.rx000Setting.setEventPacketUplinkEnable((byte)0x09);
+ rfidReaderChipE710.setPwrManagementMode(false);
+ RfidReaderChipData.HostCommands hostCommands = RfidReaderChipData.HostCommands.CMD_18K6CINV;
+ appendToLog("BtData: tagFocus = " + rfidReaderChipE710.rx000Setting.getImpinjExtension());
+ boolean bTagFocus = ((rfidReaderChipE710.rx000Setting.getImpinjExtension() & 0x04) != 0);
+ appendToLog("0 OperationTypes = " + operationTypes.toString() + ", hostCommands = " + hostCommands.toString() + ", bTagFocus = " + bTagFocus);
+ if (operationTypes == RfidReaderChipData.OperationTypes.TAG_INVENTORY_COMPACT) hostCommands = RfidReaderChipData.HostCommands.CMD_18K6CINV_COMPACT;
+ else if (rfidReaderChipE710.rx000Setting.getTagRead() != 0 && bTagFocus == false) hostCommands = RfidReaderChipData.HostCommands.CMD_18K6CINV_MB;
+ appendToLog("1 OperationTypes = " + operationTypes.toString() + ", hostCommands = " + hostCommands.toString());
+ if (true) {
+ appendToLog("BtDataOut: 3030: " + utility.byteArrayToString(rfidReaderChipE710.rx000Setting.antennaPortConfig[0]));
+ appendToLog("BtDataOut: 3140: " + utility.byteArrayToString(rfidReaderChipE710.rx000Setting.selectConfiguration[0]));
+ appendToLog("BtDataOut: 3270: " + utility.byteArrayToString(rfidReaderChipE710.rx000Setting.multibankReadConfig[0]));
+ appendToLog("BtDataOut: 3277: " + utility.byteArrayToString(rfidReaderChipE710.rx000Setting.multibankReadConfig[1]));
+ appendToLog("BtDataOut: 3908: " + utility.byteArrayToString(rfidReaderChipE710.rx000Setting.intraPacketDelay));
+ }
+ retValue = rfidReaderChipE710.sendHostRegRequestHST_CMD(hostCommands);
+ break;
+ }
+ }
+ return retValue;
+ }
+ public boolean abortOperation() {
+ boolean bRetValue = (bis108 ? rfidReaderChipR2000.sendControlCommand(RfidReaderChipR2000.ControlCommands.ABORT) : rfidReaderChipE710.sendHostRegRequestHST_CMD(RfidReaderChipData.HostCommands.NULL));
+ setInventoring(false);
+ return bRetValue;
+ }
+ public boolean setMatchRep(int matchRep) {
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.setMatchRep(matchRep) : rfidReaderChipE710.rx000Setting.setMatchRep(matchRep));
+ }
+ public String[] getCountryList() {
+ String[] strCountryList = null;
+ RegionCodes[] regionList = getRegionList();
+ if (regionList != null) {
+ strCountryList = new String[regionList.length];
+ for (int i = 0; i < regionList.length; i++) {
+ strCountryList[i] = regionCode2StringArray(regionList[i]);
+ }
+ }
+ return strCountryList;
+ }
+ public int countryInList = -1, countryInListDefault = -1;
+ public int getCountryNumberInList() {
+ return countryInList;
+ }
+ public boolean setCountryInList(int countryInList) {
+ if (bis108) {
+ boolean DEBUG = true;
+ if (DEBUG)
+ appendToLog("this.countryInList =" + this.countryInList + ", countryInList = " + countryInList);
+ if (this.countryInList == countryInList) return true;
+
+ RegionCodes[] regionList = getRegionList();
+ if (DEBUG)
+ appendToLog("regionList length =" + (regionList == null ? "NULL" : regionList.length));
+ if (regionList == null) return false;
+ if (countryInList < 0 || countryInList >= regionList.length) return false;
+
+ int[] freqDataTableOld = FreqTable(regionCode);
+ if (DEBUG)
+ appendToLog("regionCode =" + regionCode + ", freqDataTableOld length = " + (freqDataTableOld == null ? "NULL" : freqDataTableOld.length));
+ if (freqDataTableOld == null) return false;
+
+ RegionCodes regionCodeNew = regionList[countryInList];
+ final int[] freqDataTable = FreqTable(regionCodeNew);
+ if (DEBUG)
+ appendToLog("regionCodeNew =" + regionCodeNew + ", freqDataTable length = " + (freqDataTable == null ? "NULL" : freqDataTable.length));
+ if (freqDataTable == null) return false;
+
+ this.countryInList = countryInList;
+ appendToLog("saveSetting2File testpoint 4");
+ regionCode = regionCodeNew;
+ if (DEBUG)
+ appendToLog("getChannel =" + getChannel() + ", FreqChnCnt = " + FreqChnCnt());
+ appendToLog("X channel = ");
+ if (getChannel() >= FreqChnCnt()) setChannel(0);
+ switch (getCountryCode()) {
+ case 1:
+ case 5:
+ case 8:
+ case 9:
+ break;
+ case 2:
+ if (false && regionCode == regionCodeDefault4Country2) {
+ if (DEBUG) appendToLog("FCC Region is set");
+// toggledConnection = false;
+// mHandler.removeCallbacks(runnableToggleConnection);
+// mHandler.postDelayed(runnableToggleConnection, 500);
+ return true;
+ }
+ default: // 2, 4, 7
+ if (freqDataTable.length == freqDataTableOld.length) {
+ int i = 0;
+ for (; i < freqDataTable.length; i++) {
+ if (freqDataTable[i] != freqDataTableOld[i]) break;
+ }
+ if (i == freqDataTable.length) {
+ if (DEBUG) appendToLog("Break as same freqDataTable");
+ break;
+ }
+ }
+ if (DEBUG) appendToLog("Finish as different freqDataTable");
+ int k = 0;
+ for (; k < freqDataTable.length; k++) {
+ if (DEBUG) appendToLog("Setting channel = " + k);
+ rfidReaderChipR2000.rx000Setting.setFreqChannelSelect(k);
+ rfidReaderChipR2000.rx000Setting.setFreqChannelConfig(true);
+ rfidReaderChipR2000.rx000Setting.setFreqPllMultiplier(freqDataTable[k]);
+ }
+ for (; k < 50; k++) {
+ if (DEBUG) appendToLog("Resetting channel = " + k);
+ rfidReaderChipR2000.rx000Setting.setFreqChannelSelect(k);
+ rfidReaderChipR2000.rx000Setting.setFreqChannelConfig(false);
+ }
+ break;
+ }
+ if (DEBUG)
+ appendToLog("New regionCode = " + regionCode.toString() + ", channel = " + getChannel() + ", FreqChnCnt = " + FreqChnCnt());
+ return true;
+ } else {
+ boolean DEBUG = true;
+ if (this.countryInList == countryInList) return true;
+
+ if (DEBUG) appendToLog("1 setCountryInList with countryInList = " + countryInList);
+ RegionCodes[] regionList = getRegionList();
+ if (regionList == null) return false;
+
+ RegionCodes regionCodeNew = regionList[countryInList];
+ regionCode = regionCodeNew;
+
+ int indexBegin = RegionCodes.Albania1.ordinal();
+ int indexEnd = RegionCodes.Vietnam3.ordinal();
+ int i = indexBegin;
+ for (; i < indexEnd + 1; i++) {
+ if (regionCode == RegionCodes.values()[i]) {
+ break;
+ }
+ }
+
+ boolean bValue = false;
+ if (i < indexEnd + 1) {
+ appendToLog("countryEnum: i = " + i + ", indexEnd = " + indexEnd);
+ bValue = rfidReaderChipE710.rx000Setting.setCountryEnum((short)(i - indexBegin + 1));
+ if (bValue) {
+ this.countryInList = countryInList;
+ channelOrderType = -1;
+ }
+ }
+ if (DEBUG) appendToLog("1A setCountryInList with bValue = " + bValue);
+ return bValue;
+ }
+ }
+ public int channelOrderType; // 0 for frequency hopping / agile, 1 for fixed frequencey
+ public boolean getChannelHoppingStatus() {
+ if (bis108) {
+ appendToLog("countryCode with channelOrderType = " + channelOrderType);
+ if (channelOrderType < 0) {
+ if (getChannelHoppingDefault()) channelOrderType = 0;
+ else channelOrderType = 1;
+ }
+ return (channelOrderType == 0 ? true : false);
+ } else {
+ boolean bValue = false, DEBUG = false;
+ int iValue = rfidReaderChipE710.rx000Setting.getCountryEnum(); //iValue--;
+ if (DEBUG) appendToLog("getChannelHoppingStatus: countryEnum = " + iValue);
+ if (iValue > 0) {
+ String strFixedHop = countryChannelData.strCountryEnumInfo[(iValue - 1) * countryChannelData.iCountryEnumInfoColumn + 4];
+ if (DEBUG) appendToLog("getChannelHoppingStatus: FixedHop = " + strFixedHop);
+ if (strFixedHop.matches("Hop")) {
+ if (DEBUG) appendToLog("getChannelHoppingStatus: matched");
+ bValue = true;
+ }
+ }
+ if (DEBUG) appendToLog("getChannelHoppingStatus: bValue = " + bValue);
+ return bValue; //1 for hopping, 0 for fixed
+ }
+ }
+ public boolean setChannelHoppingStatus(boolean channelOrderHopping) {
+ if (this.channelOrderType != (channelOrderHopping ? 0 : 1)) {
+ if (bis108) {
+ boolean result = true;
+ if (getChannelHoppingDefault() == false) {
+ result = rfidReaderChipR2000.rx000Setting.setAntennaFreqAgile(channelOrderHopping ? 1 : 0);
+ }
+ int freqcnt = FreqChnCnt();
+ appendToLog("FrequencyA Count = " + freqcnt);
+ int channel = getChannel();
+ appendToLog(" FrequencyA Channel = " + channel);
+ for (int i = 0; i < freqcnt; i++) {
+ if (result == true) rfidReaderChipR2000.rx000Setting.setFreqChannelSelect(i);
+ if (result == true) rfidReaderChipR2000.rx000Setting.setFreqChannelConfig(channelOrderHopping);
+ }
+ if (result == true) rfidReaderChipR2000.rx000Setting.setFreqChannelSelect(channel);
+ if (result == true) rfidReaderChipR2000.rx000Setting.setFreqChannelConfig(true);
+ } else {
+ boolean result = true;
+ if (getChannelHoppingDefault() == false) {
+ result = rfidReaderChipE710.rx000Setting.setAntennaFreqAgile(channelOrderHopping ? 1 : 0);
+ }
+ int freqcnt = FreqChnCnt(); appendToLog("FrequencyA Count = " + freqcnt);
+ int channel = getChannel(); appendToLog(" FrequencyA Channel = " + channel);
+ }
+ appendToLog(" FrequencyA: end of setting");
+
+ this.channelOrderType = (channelOrderHopping ? 0 : 1);
+ appendToLog("setChannelHoppingStatus: channelOrderType = " + channelOrderType);
+ }
+ return true;
+ }
+ public String[] getChannelFrequencyList() {
+ if (bis108) {
+ boolean DEBUG = true;
+ appendToLog("regionCode is " + regionCode.toString());
+ double[] table = GetAvailableFrequencyTable(regionCode);
+ appendToLog("table length = " + table.length);
+ for (int i = 0; i < table.length; i++) appendToLog("table[" + i + "] = " + table[i]);
+ String[] strChannnelFrequencyList = new String[table.length];
+ for (int i = 0; i < table.length; i++) {
+ strChannnelFrequencyList[i] = String.format("%.2f MHz", table[i]);
+ appendToLog("strChannnelFrequencyList[" + i + "] = " + strChannnelFrequencyList[i]);
+ }
+ return strChannnelFrequencyList;
+ } else {
+ boolean DEBUG = true;
+ int iCountryEnum = rfidReaderChipE710.rx000Setting.getCountryEnum();
+ appendToLog("countryEnum = " + iCountryEnum);
+ appendToLog("i = " + iCountryEnum + ", " + countryChannelData.strCountryEnumInfo[(iCountryEnum - 1) * countryChannelData.iCountryEnumInfoColumn + 0]
+ + ", " + countryChannelData.strCountryEnumInfo[(iCountryEnum - 1) * countryChannelData.iCountryEnumInfoColumn + 1]
+ + ", " + countryChannelData.strCountryEnumInfo[(iCountryEnum - 1) * countryChannelData.iCountryEnumInfoColumn + 2]
+ + ", " + countryChannelData.strCountryEnumInfo[(iCountryEnum - 1) * countryChannelData.iCountryEnumInfoColumn + 3]
+ + ", " + countryChannelData.strCountryEnumInfo[(iCountryEnum - 1) * countryChannelData.iCountryEnumInfoColumn + 4]
+ + ", " + countryChannelData.strCountryEnumInfo[(iCountryEnum - 1) * countryChannelData.iCountryEnumInfoColumn + 5]
+ + ", " + countryChannelData.strCountryEnumInfo[(iCountryEnum - 1) * countryChannelData.iCountryEnumInfoColumn + 6]
+ );
+ int iFrequencyCount = Integer.valueOf(countryChannelData.strCountryEnumInfo[(iCountryEnum - 1) * countryChannelData.iCountryEnumInfoColumn + 3]);
+ int iFrequencyInterval = Integer.valueOf(countryChannelData.strCountryEnumInfo[(iCountryEnum - 1) * countryChannelData.iCountryEnumInfoColumn + 5]);
+ float iFrequencyStart = Float.valueOf(countryChannelData.strCountryEnumInfo[(iCountryEnum - 1) * countryChannelData.iCountryEnumInfoColumn + 6]);
+ appendToLog("iFrequencyCount = " + iFrequencyCount + ", interval = " + iFrequencyInterval + ", start = " + iFrequencyStart);
+
+ String[] strChannnelFrequencyList = new String[iFrequencyCount];
+ for (int i = 0; i < iFrequencyCount ; i++) {
+ strChannnelFrequencyList[i] = String.format("%.2f MHz", (iFrequencyStart * 1000 + iFrequencyInterval * i) / 1000);
+ appendToLog("strChannnelFrequencyList[" + i + "] = " + strChannnelFrequencyList[i]);
+ }
+ return strChannnelFrequencyList;
+ }
+ }
+ public int getChannel() {
+ if (true) return settingData.channel;
+ if (bis108) {
+ int channel = -1;
+ if (rfidReaderChipR2000.rx000Setting.getFreqChannelConfig() != 0) {
+ channel = rfidReaderChipR2000.rx000Setting.getFreqChannelSelect();
+ }
+ if (getChannelHoppingStatus()) {
+ channel = 0;
+ }
+ return channel;
+ } else {
+ int channel = -1;
+ channel = rfidReaderChipE710.rx000Setting.getFrequencyChannelIndex();
+ if (getChannelHoppingStatus()) channel = 0;
+ else if (channel > 0) channel--;
+ return channel;
+ }
+ }
+ public boolean setChannel(int channelSelect) {
+ if (bis108) {
+ boolean result = true;
+ if (result == true) result = rfidReaderChipR2000.rx000Setting.setFreqChannelConfig(false);
+ if (result == true)
+ result = rfidReaderChipR2000.rx000Setting.setFreqChannelSelect(channelSelect);
+ if (result == true) result = rfidReaderChipR2000.rx000Setting.setFreqChannelConfig(true);
+ if (result) settingData.channel = channelSelect;
+ return result;
+ } else {
+ boolean result = true; int channel = channelSelect;
+ if (getChannelHoppingStatus()) channelSelect = 0;
+ else channelSelect++;
+ if (result == true) result = rfidReaderChipE710.rx000Setting.setFrequencyChannelIndex((byte)(channelSelect & 0xFF));
+ if (result) settingData.channel = channel;
+ return result;
+ }
+ }
+ public byte getPopulation2Q(int population) {
+ double dValue = 1 + log10(population * 2) / log10(2);
+ if (dValue < 0) dValue = 0;
+ if(dValue > 15) dValue = 15;
+ byte iValue = (byte) dValue;
+ if (DEBUG || true) appendToLog("getPopulation2Q(" + population + "): log dValue = " + dValue + ", iValue = " + iValue);
+ return iValue;
+ }
+ public int population = 30;
+ public int getPopulation() {
+ return population;
+ }
+ public boolean setPopulation(int population) {
+ if (true) appendToLog("setPopulation " + population);
+ byte iValue = getPopulation2Q(population);
+ if (true) appendToLog("getPopulation2Q = " + iValue);
+ this.population = population;
+ return setQValue(iValue);
+ }
+ public byte qValueSetting = -1;
+ public byte getQValue() {
+ return qValueSetting;
+ }
+ public boolean setQValue(byte byteValue) {
+ qValueSetting = byteValue;
+ if (false) appendToLog("Stream population qValue = " + qValueSetting);
+ return setQValue1(byteValue);
+ }
+ int getQValue1() {
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.getAlgoStartQ() : rfidReaderChipE710.rx000Setting.getAlgoStartQ());
+ }
+ public boolean setQValue1(int iValue) {
+ if (bis108) {
+ boolean result = true;
+ {
+ int invAlgo = getInvAlgoInChip();
+ if (iValue != rfidReaderChipR2000.rx000Setting.getAlgoStartQ(invAlgo)) {
+ if (false)
+ appendToLog("setTagGroup: going to setAlgoSelect with invAlgo = " + invAlgo);
+ result = rfidReaderChipR2000.rx000Setting.setAlgoSelect(invAlgo);
+ }
+ }
+ if (result) {
+ result = rfidReaderChipR2000.rx000Setting.setAlgoStartQ(iValue);
+ }
+ return result;
+ } else {
+ boolean result = true;
+ if (false) appendToLog("3 setAlgoStartQ with iValue = " + iValue);
+ result = rfidReaderChipE710.rx000Setting.setAlgoStartQ(iValue);
+ return result;
+ }
+ }
+ public static final double dBuV_dBm_constant = 106.98;
+ public RfidReaderChipData.Rx000pkgData onRFIDEvent() {
+ if (bis108) {
+ RfidReaderChipData.Rx000pkgData rx000pkgData = null;
+ //if (mrfidToWriteSize() != 0) mRfidReaderChip.mRx000ToRead.clear();
+ if (rfidReaderChipR2000.bRx000ToReading == false && rfidReaderChipR2000.mRx000ToRead.size() != 0) {
+ rfidReaderChipR2000.bRx000ToReading = true;
+ int index = 0;
+ try {
+ rx000pkgData = rfidReaderChipR2000.mRx000ToRead.get(index);
+ if (false)
+ appendToLog("rx000pkgData.type = " + rx000pkgData.responseType.toString());
+ rfidReaderChipR2000.mRx000ToRead.remove(index); //appendToLog("mRx000ToRead.remove");
+ } catch (Exception ex) {
+ rx000pkgData = null;
+ }
+ rfidReaderChipR2000.bRx000ToReading = false;
+ }
+ return rx000pkgData;
+ } else {
+ boolean DEBUG = false;
+ RfidReaderChipData.Rx000pkgData rx000pkgData = null;
+ //if (mrfidToWriteSize() != 0) mRfidDevice.mRfidReaderChip.mRfidReaderChip.mRx000ToRead.clear()
+ if (rfidReaderChipE710.bRx000ToReading == false && rfidReaderChipE710.mRx000ToRead.size() != 0) {
+ rfidReaderChipE710.bRx000ToReading = true;
+ int index = 0;
+ try {
+ rx000pkgData = rfidReaderChipE710.mRx000ToRead.get(index);
+ if (false && rx000pkgData.responseType == RfidReaderChipData.HostCmdResponseTypes.TYPE_COMMAND_END)
+ if (DEBUG) appendToLog("get mRx000ToRead with COMMAND_END");
+ rfidReaderChipE710.mRx000ToRead.remove(index);
+ if (DEBUG) appendToLog("got one mRx000ToRead with responseType = " + rx000pkgData.responseType.toString() + ", and remained size = " + rfidReaderChipE710.mRx000ToRead.size());
+ } catch (Exception ex) {
+ rx000pkgData = null;
+ }
+ rfidReaderChipE710.bRx000ToReading = false;
+ }
+
+ if (rx000pkgData != null && rx000pkgData.responseType != null) {
+ if (rx000pkgData.responseType == RfidReaderChipData.HostCmdResponseTypes.TYPE_18K6C_INVENTORY || rx000pkgData.responseType == RfidReaderChipData.HostCmdResponseTypes.TYPE_18K6C_INVENTORY_COMPACT) {
+ if (DEBUG) appendToLog("Before adjustment, decodedRssi = " + rx000pkgData.decodedRssi);
+ rx000pkgData.decodedRssi += dBuV_dBm_constant;
+ if (DEBUG) appendToLog("After adjustment, decodedRssi = " + rx000pkgData.decodedRssi);
+ if (rfidReaderChipE710.rx000Setting.getInvMatchEnable() > 0) {
+ byte[] bytesCompared = new byte[rx000pkgData.decodedEpc.length];
+ System.arraycopy(rx000pkgData.decodedEpc, 0, bytesCompared, 0, rx000pkgData.decodedEpc.length);
+ //bytesCompared = new byte[] { (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0x2F };
+ //bytesCompared = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, (byte) 0xFF, (byte) 0xFF, (byte) 0x2F };
+ appendToLog("decodedEpc = " + utility.byteArrayToString(rx000pkgData.decodedEpc));
+ if (rfidReaderChipE710.rx000Setting.getInvMatchOffset() > 0) {
+ appendToLog("getInvMatchOffset = " + rfidReaderChipE710.rx000Setting.getInvMatchOffset());
+ BigInteger bigInt = new BigInteger(bytesCompared);
+ BigInteger shiftInt = bigInt.shiftLeft(rfidReaderChipE710.rx000Setting.getInvMatchOffset());
+ byte [] shifted = shiftInt.toByteArray();
+ appendToLog("shifted = " + utility.byteArrayToString(shifted));
+ if (shifted.length > bytesCompared.length) System.arraycopy(shifted, shifted.length - bytesCompared.length, bytesCompared, 0, bytesCompared.length);
+ else if (shifted.length < bytesCompared.length) {
+ System.arraycopy(shifted, 0, bytesCompared, bytesCompared.length - shifted.length, shifted.length);
+ for (int i = 0; i < bytesCompared.length - shifted.length; i++) {
+ if ((shifted[0] & 0x80) == 0) bytesCompared[i] = 0;
+ else bytesCompared[i] = (byte)0xFF;
+ }
+ }
+ appendToLog("new bytesCompared 1 = " + utility.byteArrayToString(bytesCompared));
+ }
+
+ if (rfidReaderChipE710.rx000Setting.getInvMatchType() > 0) {
+ appendToLog("getInvMatchType = " + rfidReaderChipE710.rx000Setting.getInvMatchType());
+ for (int i = 0; i < bytesCompared.length; i++) {
+ bytesCompared[i] ^= (byte) 0xFF;
+ }
+ }
+ appendToLog("new bytesCompared 2 = " + utility.byteArrayToString(bytesCompared));
+ appendToLog("getInvMatchData = " + rfidReaderChipE710.rx000Setting.getInvMatchData());
+ if (utility.byteArrayToString(bytesCompared).indexOf(rfidReaderChipE710.rx000Setting.getInvMatchData()) != 0) {
+ appendToLog("Post Mis-Matched !!!");
+ rx000pkgData = null;
+ }
+ }
+ }
+ }
+ if (rx000pkgData != null && DEBUG) appendToLog("response = " + rx000pkgData.responseType.toString() + ", " + utility.byteArrayToString(rx000pkgData.dataValues));
+ return rx000pkgData;
+ }
+ }
+ public String getModelNumber(String strModelName) {
+ if (bis108) {
+ int iCountryCode = getCountryCode();
+ String strCountryCode = "";
+ appendToLog("iCountryCode = " + iCountryCode + ", strModelNumber = " + strModelName);
+ if (strModelName != null && strModelName.length() != 0) {
+ if (iCountryCode > 0)
+ strCountryCode = strModelName + "-" + String.valueOf(iCountryCode) + " " + rfidReaderChipR2000.rx000OemSetting.getSpecialCountryVersion();
+ else strCountryCode = strModelName;
+ }
+ return strCountryCode;
+ } else {
+ boolean DEBUG = false;
+ if (DEBUG) appendToLog("getModelName = " + strModelName);
+ int iCountryCode = getCountryCode();
+ if (DEBUG) appendToLog("getCountryCode = " + iCountryCode);
+ String strSpecialCountryVersion = getSpecialCountryVersion();
+ if (DEBUG) appendToLog("getSpecialCountryVersion = " + strSpecialCountryVersion);
+ int iFreqModifyCode = getFreqModifyCode();
+ if (DEBUG) appendToLog("getFreqModifyCode = " + iFreqModifyCode);
+
+ String strModelNumber = (strModelName == null ? "" : strModelName);
+ if (iCountryCode > 0) strModelNumber += ("-" + String.valueOf(iCountryCode) + (strSpecialCountryVersion == null ? "" : (" " + strSpecialCountryVersion)));
+ if (DEBUG) appendToLog("strModelNumber = " + strModelNumber);
+ return strModelNumber;
+ }
+ }
+ public boolean setRx000KillPassword(String password) {
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.setRx000KillPassword(password) : rfidReaderChipE710.rx000Setting.setRx000KillPassword(password));
+ }
+ public boolean setRx000AccessPassword(String password) {
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.setRx000AccessPassword(password) : rfidReaderChipE710.rx000Setting.setRx000AccessPassword(password));
+ }
+ public boolean setAccessRetry(boolean accessVerfiy, int accessRetry) {
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.setAccessRetry(accessVerfiy, accessRetry) : rfidReaderChipE710.rx000Setting.setAccessRetry(accessVerfiy, accessRetry));
+ }
+ public boolean setInvModeCompact(boolean invModeCompact) {
+ if (utility.DEBUG_COMPACT) appendToLog("Debug_Compact: RfidReader.setInvModeCompact as " + invModeCompact);
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.setInvModeCompact(invModeCompact) : rfidReaderChipE710.rx000Setting.setInvModeCompact(invModeCompact));
+ }
+ public boolean setAccessLockAction(int accessLockAction, int accessLockMask) {
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.setAccessLockAction(accessLockAction, accessLockMask)
+ : rfidReaderChipE710.rx000Setting.setAccessLockAction(accessLockAction, accessLockMask));
+ }
+ public boolean setAccessBank(int accessBank) {
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.setAccessBank(accessBank) : rfidReaderChipE710.rx000Setting.setAccessBank(accessBank));
+ }
+ public boolean setAccessBank(int accessBank, int accessBank2) {
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.setAccessBank(accessBank, accessBank2) : rfidReaderChipE710.rx000Setting.setAccessBank(accessBank, accessBank2));
+ }
+ public boolean setAccessOffset(int accessOffset) {
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.setAccessOffset(accessOffset) : rfidReaderChipE710.rx000Setting.setAccessOffset(accessOffset));
+ }
+ public boolean setAccessOffset(int accessOffset, int accessOffset2) {
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.setAccessOffset(accessOffset, accessOffset2) : rfidReaderChipE710.rx000Setting.setAccessOffset(accessOffset, accessOffset2));
+ }
+ public boolean setAccessCount(int accessCount) {
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.setAccessCount(accessCount) : rfidReaderChipE710.rx000Setting.setAccessCount(accessCount));
+ }
+ public boolean setAccessCount(int accessCount, int accessCount2) {
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.setAccessCount(accessCount, accessCount2) : rfidReaderChipE710.rx000Setting.setAccessCount(accessCount, accessCount2));
+ }
+ public boolean setAccessWriteData(String dataInput) {
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.setAccessWriteData(dataInput) : rfidReaderChipE710.rx000Setting.setAccessWriteData(dataInput));
+ }
+ public boolean setResReadNoReply(boolean resReadNoReply) {
+ return (bis108 ? false : rfidReaderChipE710.rx000Setting.setResReadNoReply(resReadNoReply));
+ }
+ public boolean setTagRead(int tagRead) {
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.setTagRead(tagRead) : rfidReaderChipE710.rx000Setting.setTagRead(tagRead));
+ }
+ public boolean setInvBrandId(boolean invBrandId) {
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.setInvBrandId(invBrandId) : rfidReaderChipE710.rx000Setting.setInvBrandId(invBrandId));
+ }
+ public boolean setInvAuthenticate(boolean invAuthenticate) {
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.setInvAuthenticate(invAuthenticate) : false);
+ }
+ public boolean sendHostRegRequestHST_CMD(RfidReaderChipData.HostCommands hostCommand) {
+ if (bis108) {
+ rfidReaderChipR2000.setPwrManagementMode(false);
+ rfidReaderChipR2000.rx000Setting.setAlgoRetry(5);
+ }
+ else rfidReaderChipE710.setPwrManagementMode(false);
+ return (bis108 ? rfidReaderChipR2000.sendHostRegRequestHST_CMD(hostCommand) : rfidReaderChipE710.sendHostRegRequestHST_CMD(hostCommand));
+ }
+ public boolean setPwrManagementMode(boolean bLowPowerStandby) {
+ return (bis108 ? rfidReaderChipR2000.setPwrManagementMode(bLowPowerStandby) : rfidReaderChipE710.setPwrManagementMode(bLowPowerStandby));
+ }
+ void macRead(int address) {
+ if (bis108) rfidReaderChipR2000.rx000Setting.readMAC(address);
+ else rfidReaderChipE710.rx000Setting.readMAC(address);
+ }
+ public boolean macWrite(int address, long value) {
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.writeMAC(address, value) : rfidReaderChipE710.rx000Setting.writeMAC(address, value));
+ }
+ public void set_fdCmdCfg(int value) {
+ macWrite(0x117, value);
+ }
+ public void set_fdRegAddr(int addr) {
+ macWrite(0x118, addr);
+ }
+ public void set_fdWrite(int addr, long value) {
+ macWrite(0x118, addr);
+ macWrite(0x119, value);
+ }
+ public void set_fdPwd(int value) {
+ macWrite(0x11A, value);
+ }
+ public void set_fdBlockAddr4GetTemperature(int addr) {
+ macWrite(0x11b, addr);
+ }
+ public void set_fdReadMem(int addr, long len) {
+ macWrite(0x11c, addr);
+ macWrite(0x11d, len);
+ }
+ public void set_fdWriteMem(int addr, int len, long value) {
+ set_fdReadMem(addr, len);
+ macWrite(0x11e, value);
+ }
+ public void setImpinJExtension(boolean tagFocus, boolean fastId) {
+ if (rfidReaderChipR2000 != null) {
+ int iValue = 0;
+ if (tagFocus) iValue |= 0x10;
+ if (fastId) iValue |= 0x20;
+ if (false) appendToLog("ivalue = " + iValue + ", impinjExtensionValue = " + rfidReaderChipR2000.rx000Setting.impinjExtensionValue);
+ boolean bRetValue;
+ bRetValue = macWrite(0x203, iValue);
+ } else {
+ boolean bRetValue;
+ bRetValue = rfidReaderChipE710.rx000Setting.setImpinjExtension(tagFocus, fastId);
+ if (bRetValue) this.tagFocus = (tagFocus ? 1 : 0);
+ }
+ }
+ public String getSerialNumber() {
+ return (bis108 ? rfidReaderChipR2000.rx000OemSetting.getSerialNumber() : rfidReaderChipE710.rx000Setting.getBoardSerialNumber());
+ }
+ public boolean isInventoring() {
+ boolean bValue;
+ if (bis108) bValue = rfidReaderChipR2000.isInventoring();
+ else bValue = rfidReaderChipE710.isInventoring();
+ //appendToLog("isInventoring " + bValue + " with bis108 " + bis108);
+ return bValue;
+ }
+ public void setInventoring(boolean enable) {
+ appendToLog("setInventoring " + enable + " with bis108 " + bis108);
+ if (bis108) rfidReaderChipR2000.setInventoring(enable);
+ else rfidReaderChipE710.setInventoring(enable);
+ }
+ void addRfidToWrite(RfidConnector.CsReaderRfidData csReaderRfidData) {
+ if (bis108) rfidReaderChipR2000.addRfidToWrite(csReaderRfidData);
+ else rfidReaderChipE710.addRfidToWrite(csReaderRfidData);
+ }
+ void uplinkHandler() {
+ if (bis108) rfidReaderChipR2000.uplinkHandler();
+ else rfidReaderChipE710.uplinkHandler();
+ }
+ public int getAntennaCycle() {
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.getAntennaCycle() : rfidReaderChipE710.rx000Setting.getAntennaCycle());
+ }
+ public boolean setAntennaCycle(int antennaCycle) {
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.setAntennaCycle(antennaCycle) : rfidReaderChipE710.rx000Setting.setAntennaCycle(antennaCycle));
+ }
+ public boolean setAntennaInvCount(long antennaInvCount) {
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.setAntennaInvCount(antennaInvCount) : rfidReaderChipE710.rx000Setting.setAntennaInvCount(antennaInvCount));
+ }
+ public int getFreqChannelConfig() {
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.getFreqChannelConfig(): -1);
+ }
+ public int getDiagnosticConfiguration() {
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.getDiagnosticConfiguration(): -1);
+ }
+ public boolean setDiagnosticConfiguration(boolean bCommmandActive) {
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.setDiagnosticConfiguration(bCommmandActive): false);
+ }
+ public int getImpinjExtension() {
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.getImpinjExtension(): rfidReaderChipE710.rx000Setting.getImpinjExtension());
+ }
+ public String getProductSerialNumber() {
+ return (bis108 ? rfidReaderChipR2000.rx000OemSetting.getProductSerialNumber(): rfidReaderChipE710.rx000Setting.getProductSerialNumber());
+ }
+ public boolean turnOn(boolean onStatus) {
+ return (bis108 ? rfidReaderChipR2000.turnOn(onStatus): rfidReaderChipE710.turnOn(onStatus));
+ }
+}
+
+
+
+package com.csl.cslibrary4a;
+
+import androidx.annotation.Keep;
+
+public class RfidReaderChipData {
+ public enum OperationTypes {
+ TAG_RDOEM,
+ TAG_INVENTORY_COMPACT, TAG_INVENTORY, TAG_SEARCHING
+ }
+
+ public enum HostCommands {
+ NULL, CMD_WROEM, CMD_RDOEM, CMD_ENGTEST, CMD_MBPRDREG, CMD_MBPWRREG,
+ CMD_18K6CINV, CMD_18K6CREAD, CMD_18K6CWRITE, CMD_18K6CLOCK, CMD_18K6CKILL, CMD_SETPWRMGMTCFG, CMD_18K6CAUTHENTICATE, CMD_UNTRACEABLE,
+ CMD_UPDATELINKPROFILE,
+ CMD_18K6CBLOCKWRITE,
+ CMD_CHANGEEAS, CMD_GETSENSORDATA,
+ CMD_READBUFFER,
+ CMD_FDM_RDMEM, CMD_FDM_WRMEM, CMD_FDM_AUTH, CMD_FDM_GET_TEMPERATURE, CMD_FDM_START_LOGGING, CMD_FDM_STOP_LOGGING,
+ CMD_FDM_WRREG, CMD_FDM_RDREG, CMD_FDM_DEEP_SLEEP, CMD_FDM_OPMODE_CHECK, CMD_FDM_INIT_REGFILE, CMD_FDM_LED_CTRL,
+ CMD_18K6CINV_SELECT,
+ CMD_18K6CINV_COMPACT, CMD_18K6CINV_COMPACT_SELECT,
+ CMD_18K6CINV_MB, CMD_18K6CINV_MB_SELECT
+ }
+
+ public enum HostCmdResponseTypes {
+ NULL,
+ TYPE_COMMAND_BEGIN,
+ TYPE_COMMAND_END,
+ TYPE_18K6C_INVENTORY, TYPE_18K6C_INVENTORY_COMPACT,
+ TYPE_18K6C_TAG_ACCESS,
+ TYPE_ANTENNA_CYCLE_END,
+ TYPE_COMMAND_ACTIVE,
+ TYPE_COMMAND_ABORT_RETURN
+ }
+
+ public static class Rx000pkgData {
+ public RfidReaderChipData.HostCmdResponseTypes responseType;
+ public int flags;
+ public byte[] dataValues;
+ public long decodedTime;
+ public double decodedRssi;
+ public int decodedPhase, decodedChidx, decodedPort;
+ public byte[] decodedPc, decodedEpc, decodedCrc, decodedData1, decodedData2;
+ public String decodedResult;
+ public String decodedError;
+ }
+
+ public enum CsvColumn {
+ RESERVE_BANK,
+ EPC_BANK,
+ TID_BANK,
+ USER_BANK,
+ PHASE,
+ CHANNEL,
+ TIME, TIMEZONE,
+ LOCATION, DIRECTION,
+ OTHERS
+ }
+}
+
+
+
+package com.csl.cslibrary4a;
+
+import static java.lang.Math.log10;
+import static java.lang.Math.pow;
+
+import android.content.Context;
+
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Date;
+
+public class RfidReaderChipE710 {
+ boolean DEBUG_PKDATA;
+ boolean sameCheck = true;
+ //RfidReaderChip mRfidReaderChip;
+ boolean DEBUGTHREAD = false, DEBUG_APDATA = false;
+ int intervalRx000UplinkHandler;
+ boolean aborting = false;
+ Context context; Utility utility; CsReaderConnector csReaderConnector;
+ public RfidReaderChipE710(Context context, Utility utility, CsReaderConnector csReaderConnector) {
+ this.context = context;
+ this.utility = utility; DEBUG_PKDATA = utility.DEBUG_PKDATA;
+ //mRfidReaderChip = new RfidReaderChip();
+ this.csReaderConnector = csReaderConnector;
+ this.DEBUGTHREAD = csReaderConnector.DEBUGTHREAD;
+ this.DEBUG_APDATA = csReaderConnector.DEBUG_APDATA;
+ this.intervalRx000UplinkHandler = csReaderConnector.intervalRx000UplinkHandler;
+ }
+ private String byteArrayToString(byte[] packet) { return utility.byteArrayToString(packet); }
+ private boolean compareArray(byte[] array1, byte[] array2, int length) { return utility.compareByteArray(array1, array2, length); }
+ private void appendToLog(String s) { utility.appendToLog(s); }
+ private void appendToLogView(String s) { utility.appendToLogView(s); }
+ void writeDebug2File(String stringDebug) { utility.writeDebug2File(stringDebug); }
+ private String byteArray2DisplayString(byte[] byteData) { return utility.byteArray2DisplayString(byteData); }
+ private int byteArrayToInt(byte[] bytes) { return utility.byteArrayToInt(bytes); }
+ private double get2BytesOfRssi(byte[] bytes, int index) { return utility.get2BytesOfRssi(bytes, index); }
+ enum ControlCommands {
+ NULL,
+ CANCEL, SOFTRESET, ABORT, PAUSE, RESUME, GETSERIALNUMBER, RESETTOBOOTLOADER
+ }
+ enum HostRegRequests {
+ MAC_OPERATION,
+ //MAC_VER, MAC_LAST_COMMAND_DURATION,
+ //HST_CMNDIAGS,
+ //HST_MBP_ADDR, HST_MBP_DATA,
+ //HST_OEM_ADDR, HST_OEM_DATA,
+ HST_ANT_CYCLES, HST_ANT_DESC_SEL, HST_ANT_DESC_CFG, MAC_ANT_DESC_STAT, HST_ANT_DESC_PORTDEF, HST_ANT_DESC_DWELL, HST_ANT_DESC_RFPOWER, HST_ANT_DESC_INV_CNT,
+ HST_TAGMSK_DESC_SEL, HST_TAGMSK_DESC_CFG, HST_TAGMSK_BANK, HST_TAGMSK_PTR, HST_TAGMSK_LEN, HST_TAGMSK_0_3,
+ HST_QUERY_CFG, HST_INV_CFG, HST_INV_SEL, HST_INV_ALG_PARM_0, HST_INV_ALG_PARM_1, HST_INV_ALG_PARM_2, HST_INV_ALG_PARM_3, HST_INV_RSSI_FILTERING_CONFIG, HST_INV_RSSI_FILTERING_THRESHOLD, HST_INV_RSSI_FILTERING_COUNT, HST_INV_EPC_MATCH_CFG, HST_INV_EPCDAT_0_3,
+ HST_TAGACC_DESC_CFG, HST_TAGACC_BANK, HST_TAGACC_PTR, HST_TAGACC_CNT, HST_TAGACC_LOCKCFG, HST_TAGACC_ACCPWD, HST_TAGACC_KILLPWD, HST_TAGWRDAT_SEL, HST_TAGWRDAT_0,
+ HST_RFTC_CURRENT_PROFILE,
+ HST_RFTC_FRQCH_SEL, HST_RFTC_FRQCH_CFG, HST_RFTC_FRQCH_DESC_PLLDIVMULT, HST_RFTC_FRQCH_DESC_PLLDACCTL, HST_RFTC_FRQCH_CMDSTART,
+ HST_AUTHENTICATE_CFG, HST_AUTHENTICATE_MSG, HST_READBUFFER_LEN, HST_UNTRACEABLE_CFG,
+ HST_CMD
+ }
+ public class Rx000Setting {
+ Rx000Setting(boolean set_default_setting) {
+ if (set_default_setting) {
+ macVer = mDefault.macVer;
+ diagnosticCfg = mDefault.diagnosticCfg;
+ oemAddress = mDefault.oemAddress;
+
+ //RFTC block paramters
+ currentProfile = mDefault.currentProfile;
+
+ // Antenna block parameters
+ antennaCycle = mDefault.antennaCycle;
+ antennaFreqAgile = mDefault.antennaFreqAgile;
+ antennaSelect = mDefault.antennaSelect;
+ }
+ antennaSelectedData = new AntennaSelectedData[ANTSELECT_MAX + 1];
+ for (int i = 0; i < antennaSelectedData.length; i++) {
+ int default_setting_type = 0;
+ if (set_default_setting) {
+ if (i == 0) default_setting_type = 1;
+ else if (i >= 1 && i <= 3) default_setting_type = 2;
+ else if (i >= 4 && i <= 7) default_setting_type = 3;
+ else if (i >= 8 && i <= 11) default_setting_type = 4;
+ else default_setting_type = 5;
+ }
+ antennaSelectedData[i] = new AntennaSelectedData(set_default_setting, default_setting_type);
+ }
+
+ //Tag select block parameters
+ if (set_default_setting) invSelectIndex = 0;
+ invSelectData = new InvSelectData[INVSELECT_MAX + 1];
+ for (int i = 0; i < invSelectData.length; i++) {
+ invSelectData[i] = new InvSelectData(set_default_setting);
+ }
+
+ if (set_default_setting) {
+ //Inventtory block paraameters
+ //queryTarget = mDefault.queryTarget;
+ //querySession = mDefault.querySession;
+ //querySelect = mDefault.querySelect;
+ invAlgo = mDefault.invAlgo;
+ matchRep = mDefault.matchRep;
+ tagSelect = mDefault.tagSelect;
+ noInventory = mDefault.noInventory;
+ tagDelay = mDefault.tagDelay;
+ invModeCompact = mDefault.tagJoin;
+ invBrandId = mDefault.brandid;
+ }
+
+ if (set_default_setting) algoSelect = 3;
+ algoSelectedData = new AlgoSelectedData[ALGOSELECT_MAX + 1];
+ for (int i = 0; i < algoSelectedData.length; i++) {//0 for invalid default, 1 for 0, 2 for 1, 3 for 2, 4 for 3
+ int default_setting_type = 0;
+ if (set_default_setting) {
+ default_setting_type = i + 1;
+ }
+ algoSelectedData[i] = new AlgoSelectedData(set_default_setting, default_setting_type);
+ }
+
+ if (set_default_setting) {
+ rssiFilterType = mDefault.rssiFilterType;
+ rssiFilterOption = mDefault.rssiFilterOption;
+ rssiFilterThreshold1 = mDefault.rssiFilterThreshold;
+ rssiFilterThreshold2 = mDefault.rssiFilterThreshold;
+ rssiFilterCount = mDefault.rssiFilterCount;
+
+ matchEnable = mDefault.matchEnable;
+ matchType = mDefault.matchType;
+ matchLength = mDefault.matchLength;
+ matchOffset = mDefault.matchOffset;
+ invMatchDataReady = mDefault.invMatchDataReady;
+
+ //Tag access block parameters
+ //accessRetry = mDefault.accessRetry;
+ //accessBank = mDefault.accessBank; accessBank2 = mDefault.accessBank2;
+ //accessOffset = mDefault.accessOffset; accessOffset2 = mDefault.accessOffset2;
+ //accessCount = mDefault.accessCount; accessCount2 = mDefault.accessCount2;
+ //accessLockAction = mDefault.accessLockAction;
+ //accessLockMask = mDefault.accessLockMask;
+ //long accessPassword = 0;
+ //long killPassword = 0;
+ //accessWriteDataSelect = mDefault.accessWriteDataSelect;
+ //accWriteDataReady = mDefault.accWriteDataReady;
+
+ authMatchDataReady = mDefault.authMatchDataReady;
+ }
+
+ invMatchData0_63 = new byte[4 * 16];
+ accWriteData0_63 = new byte[4 * 16 * 2];
+ authMatchData0_63 = new byte[4 * 4];
+ }
+
+ class Rx000Setting_default {
+ String macVer;
+ int diagnosticCfg = 0x210;
+ int mbpAddress = 0; // ?
+ int mbpData = 0; // ?
+ int oemAddress = 4; // ?
+ int oemData = 0; // ?
+
+ //RFTC block paramters
+ int currentProfile = 1;
+ int freqChannelSelect = 0;
+
+ // Antenna block parameters
+ int antennaCycle = 1;
+ int antennaFreqAgile = 0;
+ int antennaSelect = 0;
+
+ //Tag select block parameters
+ int invSelectIndex = 0;
+
+ //Inventtory block paraameters
+ int queryTarget = 0;
+ int querySession = 2;
+ int querySelect = 1;
+ int invAlgo = 3;
+ int matchRep = 0;
+ int tagSelect = 0;
+ int noInventory = 0;
+ int tagRead = 0;
+ int tagDelay = 0;
+ int tagJoin = 0;
+ int brandid = 0;
+ int algoSelect = 3;
+
+ int rssiFilterType = 0;
+ int rssiFilterOption = 0;
+ int rssiFilterThreshold = 0;
+ long rssiFilterCount = 0;
+
+ int matchEnable = 0;
+ int matchType = 0;
+ int matchLength = 0;
+ int matchOffset = 0;
+ byte[] invMatchData0_63; int invMatchDataReady = 0;
+
+ //Tag access block parameters
+ int accessRetry = 3;
+ int accessBank = 1; int accessBank2 = 0;
+ int accessOffset = 2; int accessOffset2 = 0;
+ int accessCount = 1; int accessCount2 = 0;
+ int accessLockAction = 0;
+ int accessLockMask = 0;
+ //long accessPassword = 0;
+ // long killPassword = 0;
+ int accessWriteDataSelect = 0;
+ byte[] accWriteData0_63; int accWriteDataReady = 0;
+
+ byte[] authMatchData; int authMatchDataReady = 0;
+ }
+ Rx000Setting_default mDefault = new Rx000Setting_default();
+
+ boolean readMAC(int address, int length) {
+ boolean DEBUG = false;
+ byte[] msgBuffer = new byte[]{(byte) 0x80, (byte)0xb3, 0x14, 0x71, 0, 0, 4, 1, 0, 8, 0};
+ msgBuffer[8] = (byte) ((address >> 8) % 256);
+ msgBuffer[9] = (byte) (address % 256);
+ msgBuffer[10] = (byte) (length & 0xFF);
+ if (DEBUG) appendToLog("RfidReaderChipE710.readMAC mRfidToWrite.size = " + csReaderConnector.rfidConnector.mRfidToWrite.size() + ", msgBufferIn = " + byteArrayToString(msgBuffer));
+ if (csReaderConnector.rfidConnector.mRfidToWrite.size() != 0) {
+ for (int i = 1; i < csReaderConnector.rfidConnector.mRfidToWrite.size(); i++) {
+ byte[] msgBufferOld = csReaderConnector.rfidConnector.mRfidToWrite.get(i).dataValues;
+ if (DEBUG) appendToLog("mRfidToWrite[" + i + "].dataValues = " + byteArrayToString(msgBufferOld));
+ int k = 0, m = 4;
+ for (; k < m; k++) {
+ if ((byte)msgBufferOld[k] != (byte)msgBuffer[k]) break;
+ }
+ int iMultipleNumber = 25; //25 for normal, 3 for Usb, 16 or above will have multiple uplinks
+ if (utility.ENABLE_USBDATA) iMultipleNumber = 3;
+ if (k == m && msgBufferOld[7] < iMultipleNumber) {
+ for (int x = 8; x < msgBufferOld.length; x+=3) {
+ if (msgBufferOld[x] == msgBuffer[8]
+ && msgBufferOld[x+1] == msgBuffer[9]
+ && msgBufferOld[x+2] == msgBuffer[10]
+ ) {
+ if (DEBUG) appendToLog("RfidReaderChipE710.readMAC matched payload read at x = " + x + ", and no adding");
+ return true;
+ }
+ }
+ byte[] msgBufferProposed = new byte[msgBufferOld.length + 3];
+ System.arraycopy(msgBufferOld, 0, msgBufferProposed, 0, msgBufferOld.length);
+ byte payloadLen = msgBufferProposed[6];
+ msgBufferProposed[6] += 3; //(byte)(payloadLen + 3);
+ if (msgBufferProposed[6] < payloadLen) break;
+
+ msgBufferProposed[7]++;
+ System.arraycopy(msgBuffer, 8, msgBufferProposed, msgBufferOld.length, 3);
+ if (DEBUG) appendToLog("RfidReaderChipE710.readMAC msgBufferProposed = " + byteArrayToString(msgBufferProposed));
+
+ csReaderConnector.rfidConnector.mRfidToWrite.remove(i);
+ msgBuffer = msgBufferProposed;
+ }
+ }
+ }
+ if (DEBUG) appendToLog("RfidReaderChipE710.readMAC msgBufferOut = " + byteArrayToString(msgBuffer));
+ return sendHostRegRequest(HostRegRequests.MAC_OPERATION, false, msgBuffer);
+ }
+ boolean writeMAC(int address, byte[] bytes, boolean bReady) {
+ byte[] header = new byte[] {(byte) 0x80, (byte)0xb3, (byte)0x9A, 6, 0, 0, 4, 1, 0, 8, 0 };
+ byte[] msgBuffer = new byte[header.length + bytes.length];
+ int iPayloadLength = 4 + bytes.length;
+ System.arraycopy(header, 0, msgBuffer, 0, header.length);
+ msgBuffer[5] = (byte)((iPayloadLength / 256) & 0xFF);
+ msgBuffer[6] = (byte)((iPayloadLength % 256) & 0xFF);
+ msgBuffer[8] = (byte) ((address >> 8) & 0xFF);
+ msgBuffer[9] = (byte) (address & 0xFF);
+ msgBuffer[10] = (byte) (bytes.length & 0XFF);
+ System.arraycopy(bytes, 0, msgBuffer, 11, bytes.length);
+ if (false) appendToLog(String.format("3 writeMAC with address = 0x%X, msgBuffer = ", address) + byteArrayToString(msgBuffer));
+ return sendHostRegRequest(HostRegRequests.MAC_OPERATION, true, msgBuffer);
+ }
+ public boolean readMAC(int address) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 0, 0, 0, 0, 0, 0};
+ msgBuffer[2] = (byte) (address % 256);
+ msgBuffer[3] = (byte) ((address >> 8) % 256);
+ return sendHostRegRequest(HostRegRequests.MAC_OPERATION, false, msgBuffer);
+ }
+ public boolean writeMAC(int address, long value) {
+ byte[] msgBuffer = null;
+ appendToLog(String.format("3A setTagFocus with address = 0x%X, value = 0x%X ", address, value));
+ return sendHostRegRequest(HostRegRequests.MAC_OPERATION, true, msgBuffer);
+ }
+
+ String macVer = null; int macVerBuild = -1;
+ public String getMacVer() {
+ appendToLog("macVerBuild = " + macVerBuild + ", macVer = " + (macVer == null ? "null" : macVer));
+ if (macVerBuild < 0) readMAC(0x28, 4);
+ if (macVer == null) readMAC(8, 0x20);
+ if (macVerBuild < 0 || macVer == null) return null;
+ String strValue = macVer + " b" + macVerBuild;
+ if (false) appendToLog("2 getMacVer = " + strValue);
+ return strValue;
+ }
+
+ int authenticateConfig = -1;
+ public boolean setAuthenticateConfig(int authenticateConfig) {
+ byte[] data = new byte[3];
+ data[0] = (byte) ((authenticateConfig >> 16) & 0xFF);
+ data[1] = (byte) ((authenticateConfig >> 8) & 0xFF);
+ data[2] = (byte) (authenticateConfig & 0xFF);
+ appendToLog("AAA: writing 390E with data " + byteArrayToString(data));
+ boolean bValue = writeMAC(0x390E, data, true);
+ if (bValue) this.authenticateConfig = authenticateConfig;
+ //readMAC3(0x390E, 3);
+ return bValue;
+ }
+ public boolean setAuthenticateMessage(byte[] authenticateMessage) {
+ int length = authenticateMessage.length;
+ if (length > 32) length = 32;
+ byte[] data = new byte[length];
+ System.arraycopy(authenticateMessage, 0, data, 0, length);
+ appendToLog("AAA: writing 3912 with data " + byteArrayToString(data));
+ boolean bValue = writeMAC(0x3912, data, true);
+ //readMAC3(0x3912, 32);
+ return bValue;
+ }
+ public boolean setAuthenticateResponseLen(int authenticateResponseLen) {
+ byte[] data = new byte[2];
+ data[0] = (byte) ((authenticateResponseLen >> 8) & 0xFF);
+ data[1] = (byte) (authenticateResponseLen & 0xFF);
+ appendToLog("AAA: writing 3944 with data " + byteArrayToString(data));
+ boolean bValue = writeMAC(0x3944, data, true);
+ //readMAC3(0x3944, 2);
+ return bValue;
+ }
+
+ byte[] currentPort = null;
+ public byte getCurrentPort() {
+ byte byValue = (byte)-1;
+ if (currentPort != null && currentPort.length == 1) byValue = currentPort[0];
+ else readMAC(0x3948, 1);
+ appendToLog("byValue = " + byValue);
+ return byValue;
+ }
+ boolean setCurrentPort(byte currentPortNew) {
+ if (currentPortNew >= 0 && currentPort.length == 1 && currentPort[0] == currentPortNew && sameCheck) {
+ appendToLog("!!! Skip sending repeated data with currentPortNew = " + currentPortNew);
+ return true;
+ }
+ byte[] bytes = new byte[1];
+ bytes[0] = currentPortNew;
+ boolean bValue;
+ bValue = rx000Setting.writeMAC(0x3948, bytes, true);
+ appendToLog("new currentPort = " + byteArrayToString(bytes) + ", old currentPort = " + byteArrayToString(currentPort));
+ if (bValue) currentPort = bytes;
+ return true;
+ }
+ public boolean updateCurrentPort() {
+ byte currentPortOld = getCurrentPort();
+ byte currentPortNew = 0;
+ for (int i = 0; i < 16; i++) {
+ if (rx000Setting.antennaPortConfig[i] != null) {
+ if (rx000Setting.antennaPortConfig[i][0] != 0) {
+ currentPortNew = (byte)(i & 0xFF);
+ }
+ }
+ }
+ appendToLog("currentPortOld = " + currentPortOld + ", currentPortNew = " + currentPortNew);
+ boolean bValue = false;
+ if (currentPortOld != currentPortNew) bValue = setCurrentPort(currentPortNew);
+ return bValue;
+ }
+
+ byte[] modelCode;
+ public String getModelCode() {
+ String strValue = null;
+ if (modelCode == null) readMAC(0x5000, 32);
+ else {
+ strValue = byteArray2DisplayString(modelCode);
+ if (strValue == null || strValue.length() == 0) strValue = byteArrayToString(modelCode).substring(0, 5);
+ }
+ return strValue;
+ }
+
+ byte[] productSerialNumber;
+ public String getProductSerialNumber() {
+ String strValue = null;
+ if (productSerialNumber == null) {
+ readMAC(0x5020, 32);
+ } else {
+ strValue = byteArray2DisplayString(productSerialNumber);
+ if (strValue == null || strValue.length() == 0) strValue = byteArrayToString(productSerialNumber).substring(0, 5);
+ //string.substring(string.length() - 8, string.length());
+ }
+ return strValue;
+ }
+
+ byte[] countryEnum;
+ public int getCountryEnum() {
+ int iValue = -1;
+ if (countryEnum == null) readMAC(0x3014, 2);
+ else iValue = byteArrayToInt(countryEnum);
+ appendToLog("countryEnum = " + iValue);
+ return iValue;
+ }
+ public boolean setCountryEnum(short countryEnum) {
+ byte[] data = new byte[2];
+ data[0] = 0;
+ data[1] = (byte) ((countryEnum) & 0xFF);
+ if (this.countryEnum != null && compareArray(this.countryEnum, data, data.length) && sameCheck) return true;
+ boolean bValue = writeMAC(0x3014, data, true);
+ appendToLog("new countryEnum = " + byteArrayToString(data) + ", with bValue = " + bValue);
+ if (bValue) this.countryEnum = data;
+ return bValue;
+ }
+
+ byte[] frequencyChannelIndex;
+ public int getFrequencyChannelIndex() {
+ int iValue = -1;
+ if (frequencyChannelIndex == null) readMAC(0x3018, 1);
+ else iValue = byteArrayToInt(frequencyChannelIndex);
+ appendToLog("frequencyChannelIndex = " + iValue);
+ return iValue;
+ }
+ public boolean setFrequencyChannelIndex(byte frequencyChannelIndex) {
+ byte[] data = new byte[1];
+ data[0] = frequencyChannelIndex;
+ if (this.frequencyChannelIndex != null && compareArray(this.frequencyChannelIndex, data, data.length) && sameCheck) return true;
+ boolean bValue = writeMAC(0x3018, data, true);
+ appendToLog("new frequencyChannelIndex = " + byteArrayToString(data) + ", old frequencyChannelIndex = " + byteArrayToString(this.frequencyChannelIndex) + ", with bValue = " + bValue + ", sameCheck = " + sameCheck);
+ if (bValue) this.frequencyChannelIndex = data;
+ return bValue;
+ }
+
+ byte[] countryEnumOem;
+ public int getCountryEnumOem() {
+ int iValue = -1;
+ if (countryEnumOem == null) readMAC(0x5040, 2);
+ else iValue = byteArrayToInt(countryEnumOem);
+ appendToLog("countryEnumOem = " + iValue);
+ return iValue;
+ }
+
+ byte[] countryCodeOem;
+ public int getCountryCodeOem() {
+ int iValue = -1;
+ if (countryCodeOem == null) readMAC(0xef98, 4);
+ else iValue = byteArrayToInt(countryCodeOem);
+ return iValue;
+ }
+ byte[] boardSerialNumber;
+ public String getBoardSerialNumber() {
+ if (boardSerialNumber == null) {
+ readMAC(0xef9c, 16);
+ return null;
+ } else if (boardSerialNumber.length < 13) return null;
+ else {
+ byte[] retValue = new byte[boardSerialNumber.length];
+ System.arraycopy(boardSerialNumber, 0, retValue, 0, boardSerialNumber.length);
+ String string = new String(retValue).trim().replaceAll("[^\\x00-\\x7F]", "");
+ if (string == null || string.length() == 0) return byteArrayToString(retValue).substring(0, 13);
+ if (false) appendToLog("String = " + string + ", length = " + string.length());
+ if (retValue.length > 13) {
+ for (int i = 13; i < retValue.length; i++) {
+ if (retValue[i] < 0x30) retValue[i] += 0x30;
+ }
+ }
+ return (retValue == null ? null : new String(retValue).trim().replaceAll("[^\\x00-\\x7F]", ""));
+ }
+ }
+
+ byte[] specialcountryCodeOem;
+ public String getSpecialCountryCodeOem() {
+ String strValue = null;
+ if (specialcountryCodeOem == null) readMAC(0xefac, 4);
+ else {
+ strValue = byteArray2DisplayString(specialcountryCodeOem);
+ //if (strValue == null || strValue.length() == 0) strValue = byteArrayToString(modelCode).substring(0, 5);
+ }
+ return strValue;
+ }
+
+ byte[] freqModifyCode;
+ public int getFreqModifyCode() {
+ int iValue = -1;
+ if (freqModifyCode == null) readMAC(0xefb0, 4);
+ else iValue = byteArrayToInt(freqModifyCode);
+ return iValue;
+ }
+ long mac_last_command_duration;
+ final int DIAGCFG_INVALID = -1; final int DIAGCFG_MIN = 0; final int DIAGCFG_MAX = 0x3FF;
+ int diagnosticCfg = DIAGCFG_INVALID;
+ public int getAntennaPort() {
+ if (false) appendToLog("2 iAntennaPort = " + antennaSelect);
+ return antennaSelect;
+ }
+ byte[][] antennaPortConfig = new byte[16][];
+ public byte[] getAntennaPortConfig(int iAntennaPort) {
+ byte[] bytes = null;
+ if (antennaPortConfig[iAntennaPort] == null) {
+ if (false) appendToLog("getAntennaPortConfig starts readMAC");
+ readMAC(0x3030 + iAntennaPort * 16, 16);
+ }
+ else {
+ bytes = new byte[antennaPortConfig[iAntennaPort].length];
+ System.arraycopy(antennaPortConfig[iAntennaPort], 0, bytes, 0, bytes.length);
+ }
+ if (false) appendToLog("getAntennaPortConfig[" + iAntennaPort + "] = " + byteArrayToString(antennaPortConfig[iAntennaPort]));
+ return bytes;
+ }
+
+ int impinjExtensionValue = -1;
+ public int getImpinjExtension() {
+ int iValue = -1; boolean DEBUG = false;
+ if (DEBUG) appendToLog("2 getImpinjExtension: iAntennaPort = " + antennaSelect);
+ if (antennaPortConfig[antennaSelect] == null) appendToLog("CANNOT continue as antennaPortConfig[" + antennaSelect + "] is null !!!");
+ else {
+ if (DEBUG) appendToLog("2A getImpinjExtension: getAntennaPortConfig[" + antennaSelect + "] = " + byteArrayToString(antennaPortConfig[antennaSelect]));
+ iValue = (antennaPortConfig[antennaSelect][5] & 0x06);
+ if (DEBUG) appendToLog(String.format("2b getImpinjExtension: iValue = 0x%X", iValue));
+ }
+ return iValue;
+ }
+
+ public boolean setImpinjExtension(boolean tagFocus, boolean fastId) {
+ boolean bValue = false, DEBUG = false;
+ if (antennaPortConfig[antennaSelect] == null) appendToLog("CANNOT continue as antennaPortConfig[" + antennaSelect + "] is null !!!");
+ else {
+ if (DEBUG) appendToLog("2 setImpinjExtension: tagFocus = " + tagFocus);
+ if (DEBUG) appendToLog("2A setImpinjExtension: getAntennaPortConfig[" + antennaSelect + "] = " + byteArrayToString(antennaPortConfig[antennaSelect]));
+ byte[] bytes = new byte[1];
+ bytes[0] = antennaPortConfig[antennaSelect][5];
+
+ if (tagFocus) bytes[0] |= 0x04;
+ else bytes[0] &= ~0x04;
+ if (fastId) bytes[0] |= 0x02;
+ else bytes[0] &= ~0x02;
+ if (DEBUG) appendToLog(String.format("2A1 setImpinjExtension: bytes = 0x%X", bytes[0]));
+ boolean bSame = false;
+ if (sameCheck | true) {
+ if (antennaPortConfig[antennaSelect][5] == bytes[0]) bSame = true;
+ if (DEBUG) appendToLog("2ab setImpinjExtension: the array is the same = " + bSame);
+ }
+ //bSame = false; appendToLog("!!! assme bSame is false before 1A writeMAC 0x3035");
+ if (bSame) {
+ if (DEBUG_PKDATA) appendToLog(String.format("!!! Skip sending repeated data %s in address 0x%X", byteArrayToString(bytes), 0x3030 + antennaSelect * 16 + 5));
+ bValue = true;
+ } else {
+ appendToLog("test 1");
+ bValue = writeMAC(0x3030 + antennaSelect * 16 + 5, bytes, true);
+ if (bValue) antennaPortConfig[antennaSelect][5] = bytes[0];
+ }
+ if (DEBUG) appendToLog("2b setImpinjExtension: with updated " + byteArrayToString(antennaPortConfig[antennaSelect]));
+ }
+ return bValue;
+ }
+
+ int iSelectPort = 0;
+ public byte[][] selectConfiguration = new byte[7][];
+
+ public byte[] getSelectConfiguration(int iSelectPort) {
+ byte[] bytes = null;
+ if (selectConfiguration[iSelectPort] == null) {
+ if (false) appendToLog("getSelectConfiguration starts readMAC");
+ readMAC(0x3140 + iSelectPort * 42, 42);
+ }
+ else {
+ bytes = new byte[selectConfiguration[iSelectPort].length];
+ System.arraycopy(selectConfiguration[iSelectPort], 0, bytes, 0, bytes.length);
+ }
+ if (false) appendToLog("getSelectConfiguration[" + iSelectPort + "] = " + byteArrayToString(selectConfiguration[iSelectPort]));
+ return bytes;
+ }
+ public boolean setSelectConfiguration(int index, boolean enable, int bank, int offset, byte[] mask, int target, int action, int delay) {
+ boolean bValue = false;
+ byte[] bytes = new byte[42];
+ if (selectConfiguration[index] != null) System.arraycopy(selectConfiguration[index], 0, bytes, 0, bytes.length);
+ bytes[0] = (byte) (enable ? 1 : 0);
+ bytes[1] = (byte) (bank & 0xFF);
+ bytes[2] = (byte) ((offset >> 24) & 0xFF);
+ bytes[3] = (byte) ((offset >> 16) & 0xFF);
+ bytes[4] = (byte) ((offset >> 8) & 0xFF);
+ bytes[5] = (byte) (offset & 0xFF);
+ if (mask != null) {
+ int iWdith = mask.length;
+ if (iWdith > 32) iWdith = 32;
+ System.arraycopy(mask, 0, bytes, 7, iWdith);
+ bytes[6] = (byte) ((iWdith * 8) & 0xFF);
+ } else bytes[6] = 0;
+ bytes[39] = (byte) (target & 0xFF);
+ bytes[40] = (byte) (action & 0xFF);
+ bytes[41] = (byte) (delay & 0xFF);
+ if (false) appendToLog("1A writeMAC 0x3140");
+ if (compareArray(selectConfiguration[index], bytes, bytes.length) && sameCheck) {
+ appendToLog("!!! Skip sending repeated data " + byteArrayToString(bytes) + " to address 0x3140");
+ return true;
+ }
+ bValue = writeMAC(0x3140 + index * 42, bytes, true);
+ if (bValue) selectConfiguration[index] = bytes;
+ else appendToLog("!!! Failed to send data " + byteArrayToString(bytes) + " to address 0x3140");
+ return bValue;
+ }
+
+ byte[][] multibankReadConfig = new byte[3][];
+ int getMultibankEnable(int iSelectPort) {
+ int iValue = 0;
+ if (multibankReadConfig[iSelectPort] != null) {
+ if (multibankReadConfig[iSelectPort][0] != 0) iValue = multibankReadConfig[iSelectPort][0];
+ }
+ return iValue;
+ }
+ int getMultibankReadLength(int iSelectPort) {
+ int iValue = 0;
+ if (multibankReadConfig[iSelectPort] != null) {
+ if (multibankReadConfig[iSelectPort][0] != 0) iValue = multibankReadConfig[iSelectPort][6];
+ }
+ return iValue;
+ }
+ public byte[] getMultibankReadConfig(int iSelectPort) {
+ boolean DEBUG = false; int iPortSize = 7;
+ byte[] bytes = null;
+ if (multibankReadConfig[iSelectPort] == null) {
+ if (DEBUG) appendToLog("getMultibankReadConfig starts readMAC");
+ readMAC(0x3270 + iSelectPort * iPortSize, iPortSize);
+ }
+ else {
+ bytes = new byte[multibankReadConfig[iSelectPort].length];
+ System.arraycopy(multibankReadConfig[iSelectPort], 0, bytes, 0, bytes.length);
+ }
+ if (DEBUG) appendToLog("getMultibankReadConfig[" + iSelectPort + "] = " + byteArrayToString(multibankReadConfig[iSelectPort]));
+ return bytes;
+ }
+ byte[][] multibankWriteConfig = new byte[3][];
+ boolean setMultibankReadConfig(int index, boolean enable, int bank, int offset, int length) {
+ boolean bValue = false;
+ byte[] bytes = new byte[7];
+ bytes[0] = (byte) (enable ? 1 : 0);
+ bytes[1] = (byte) (bank & 0xFF);
+ bytes[2] = (byte) ((offset >> 24) & 0xFF);
+ bytes[3] = (byte) ((offset >> 16) & 0xFF);
+ bytes[4] = (byte) ((offset >> 8) & 0xFF);
+ bytes[5] = (byte) (offset & 0xFF);
+ bytes[6] = (byte) (length & 0xFF);
+ bValue = writeMAC(0x3270 + index * 7, bytes, true);
+ if (bValue) multibankReadConfig[index] = bytes;
+ return bValue;
+ }
+
+ boolean setMultibankWriteConfig(int index, boolean enable, int bank, int offset, int length, byte[] data) {
+ boolean bValue = false, DEBUG = false;
+ if (DEBUG) appendToLog("Start with index = " + index + ", enable = " + enable + ", bank = " + bank + ", offset = " + offset + ", length = " + length + ", data = " + byteArrayToString(data));
+ byte[] bytes = new byte[7+data.length];
+ bytes[0] = (byte) (enable ? 1 : 0);
+ bytes[1] = (byte) (bank & 0xFF);
+ bytes[2] = (byte) ((offset >> 24) & 0xFF);
+ bytes[3] = (byte) ((offset >> 16) & 0xFF);
+ bytes[4] = (byte) ((offset >> 8) & 0xFF);
+ bytes[5] = (byte) (offset & 0xFF);
+ bytes[6] = (byte) (length & 0xFF);
+ System.arraycopy(data, 0, bytes, 7, data.length);
+ if (DEBUG) appendToLog("bytes = " + byteArrayToString(bytes));
+ bValue = writeMAC(0x3290 + index * 519, bytes, true);
+ if (DEBUG) appendToLog("After writeMAC, bValue = " + bValue);
+ if (bValue) multibankWriteConfig[index] = bytes;
+ return bValue;
+ }
+ int pwrMgmtStatus = -1;
+ void getPwrMgmtStatus() {
+ appendToLog("pwrMgmtStatus: getPwrMgmtStatus ");
+ pwrMgmtStatus = -1; readMAC(0x204);
+ }
+
+ final int MBPADDR_INVALID = -1; final int MBPADDR_MIN = 0; final int MBPADDR_MAX = 0x1FFF;
+ long mbpAddress = MBPADDR_INVALID;
+ final int MBPDATA_INVALID = -1; final int MBPDATA_MIN = 0; final int MBPDATA_MAX = 0x1FFF;
+ long mbpData = MBPDATA_INVALID;
+ final int OEMADDR_INVALID = -1; final int OEMADDR_MIN = 0; final int OEMADDR_MAX = 0x1FFF;
+ long oemAddress = OEMADDR_INVALID;
+ final int OEMDATA_INVALID = -1; final int OEMDATA_MIN = 0; final int OEMDATA_MAX = 0x1FFF;
+ long oemData = OEMDATA_INVALID;
+
+ // Antenna block parameters
+ final int ANTCYCLE_INVALID = -1; final int ANTCYCLE_MIN = 0; final int ANTCYCLE_MAX = 0xFFFF;
+ int antennaCycle = ANTCYCLE_INVALID;
+ public int getAntennaCycle() {
+ if (antennaCycle < ANTCYCLE_MIN || antennaCycle > ANTCYCLE_MAX) getHST_ANT_CYCLES();
+ return antennaCycle;
+ }
+ public boolean setAntennaCycle(int antennaCycle) {
+ if (antennaCycle == this.antennaCycle) return true;
+ this.antennaCycle = antennaCycle; appendToLog(String.format("!!! Skip setAntennaCycle[0x%X]", antennaCycle));
+ return true;
+ }
+ boolean setAntennaCycle(int antennaCycle, int antennaFreqAgile) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 0, 7, 0, 0, 0, 0};
+ if (antennaCycle < ANTCYCLE_MIN || antennaCycle > ANTCYCLE_MAX) antennaCycle = mDefault.antennaCycle;
+ if (antennaFreqAgile < FREQAGILE_MIN || antennaFreqAgile > FREQAGILE_MAX) antennaFreqAgile = mDefault.antennaFreqAgile;
+ if (this.antennaCycle == antennaCycle && this.antennaFreqAgile == antennaFreqAgile && sameCheck) return true;
+ msgBuffer[4] = (byte) (antennaCycle % 256);
+ msgBuffer[5] = (byte) ((antennaCycle >> 8) % 256);
+ if (antennaFreqAgile != 0) {
+ msgBuffer[7] |= 0x01;
+ }
+ this.antennaCycle = antennaCycle;
+ this.antennaFreqAgile = antennaFreqAgile;
+ appendToLog("3 Set HST_ANT_CYCLES");
+ return sendHostRegRequest(HostRegRequests.HST_ANT_CYCLES, true, msgBuffer);
+ }
+
+ final int FREQAGILE_INVALID = -1; final int FREQAGILE_MIN = 0; final int FREQAGILE_MAX = 1;
+ int antennaFreqAgile = FREQAGILE_INVALID;
+ int getAntennaFreqAgile() {
+ if (antennaFreqAgile < FREQAGILE_MIN || antennaFreqAgile > FREQAGILE_MAX)
+ getHST_ANT_CYCLES();
+ return antennaFreqAgile;
+ }
+ public boolean setAntennaFreqAgile(int freqAgile) {
+ appendToLog("Set HST_ANT_CYCLES");
+ return setAntennaCycle(antennaCycle, freqAgile);
+ }
+
+ private boolean getHST_ANT_CYCLES() {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 0, 7, 0, 0, 0, 0};
+ return sendHostRegRequest(HostRegRequests.HST_ANT_CYCLES, false, msgBuffer);
+ }
+
+ final int ANTSELECT_INVALID = -1; final int ANTSLECT_MIN = 0; final int ANTSELECT_MAX = 15;
+ int antennaSelect = ANTSELECT_INVALID; //default value = 0
+ public boolean setAntennaSelect(int antennaSelect) {
+ if (antennaSelect < ANTSLECT_MIN || antennaSelect > ANTSELECT_MAX) antennaSelect = mDefault.antennaSelect;
+ if (this.antennaSelect == antennaSelect && sameCheck) return true;
+ this.antennaSelect = antennaSelect; appendToLog("antennaSelect is set to " + antennaSelect);
+ return true;
+ }
+
+ AntennaSelectedData[] antennaSelectedData;
+ public int getAntennaEnable() {
+ boolean DEBUG = false;
+ int iValue = -1;
+ if (antennaPortConfig[antennaSelect] == null) {
+ rx000Setting.getAntennaPortConfig(antennaSelect);
+ readMAC(0x3030 + antennaSelect * 16, 16);
+ appendToLog("CANNOT continue as antennaPortConfig[" + antennaSelect + "] is null !!!");
+ } else {
+ if (DEBUG) appendToLog("2 getAntennaEnable");
+ if (DEBUG) appendToLog("2A getAntennaEnable: getAntennaPortConfig[" + antennaSelect + "] = " + byteArrayToString(antennaPortConfig[antennaSelect]));
+ iValue = antennaPortConfig[antennaSelect][0] & 0xFF;
+ }
+ if (DEBUG) appendToLog("2 getAntennaEnable: iValue = " + iValue);
+ return iValue;
+ }
+ public boolean setAntennaEnable(int antennaEnable) {
+ boolean bValue = false, DEBUG = false;
+
+ appendToLog("antennaEnable is " + antennaEnable);
+ if (antennaEnable == 0) {
+ boolean disableInvalid = true;
+ for (int i = 0; i < 16; i++) {
+ appendToLog("i = " + i + ", antennaSelect = " + antennaSelect);
+ if (i != antennaSelect && antennaPortConfig[i] != null) {
+ if (antennaPortConfig[i][0] != 0) disableInvalid = false;
+ appendToLog("i = " + i + ", disableInvalid = " + disableInvalid);
+ }
+ }
+ appendToLog("disableInvalid is " + disableInvalid);
+ if (disableInvalid) return false;
+ }
+
+ if (antennaPortConfig[antennaSelect] == null) appendToLog("CANNOT continue as antennaPortConfig[" + antennaSelect + "] is null !!!");
+ else {
+ if (DEBUG) appendToLog("2 setAntennaEnable with antennaEnable = " + antennaEnable);
+ if (DEBUG) appendToLog("2A setAntennaEnable: getAntennaPortConfig[" + antennaSelect + "] = " + byteArrayToString(antennaPortConfig[antennaSelect]));
+ byte[] bytes = new byte[1];
+ if (antennaEnable > 0) bytes[0] = 1;
+ else bytes[0] = 0;
+ if (DEBUG) appendToLog("2b setAntennaEnable: bytes = " + byteArrayToString(bytes));
+ bValue = writeMAC(0x3030 + antennaSelect * 16, bytes, true);
+ if (bValue) antennaPortConfig[antennaSelect][0] = bytes[0];
+ if (DEBUG) appendToLog("2C setAntennaEnable: getAntennaPortConfig[" + antennaSelect + "] = " + byteArrayToString(antennaPortConfig[antennaSelect]));
+ }
+ if (DEBUG) appendToLog("2d getAntennaEnable: bValue = " + bValue);
+ return bValue;
+ }
+
+ public long getAntennaDwell() {
+ boolean DEBUG = false;
+ long lValue = -1;
+ if (antennaPortConfig[antennaSelect] == null) appendToLog("CANNOT continue as antennaPortConfig[" + antennaSelect + "] is null !!!");
+ else {
+ if (DEBUG) appendToLog("2 getAntennaDwell");
+ if (DEBUG) appendToLog("2A getAntennaDwell: getAntennaPortConfig[" + antennaSelect + "] = " + byteArrayToString(antennaPortConfig[antennaSelect]));
+ lValue = (antennaPortConfig[antennaSelect][1] & 0xFF) << 8;
+ lValue += (antennaPortConfig[antennaSelect][2] & 0xFF);
+ }
+ if (DEBUG) appendToLog("2C getAntennaDwell: iValue = " + lValue);
+ return lValue;
+ }
+
+ public boolean setAntennaDwell(long antennaDwell) {
+ boolean bValue = false, DEBUG = false;
+ if (antennaPortConfig[antennaSelect] == null) appendToLog("CANNOT continue as antennaPortConfig[" + antennaSelect + "] is null !!!");
+ else {
+ if (DEBUG) appendToLog("2 setAntennaDwell: antennaDwell = " + antennaDwell);
+ if (DEBUG) appendToLog("2A setAntennaDwell: getAntennaPortConfig[" + antennaSelect + "] = " + byteArrayToString(antennaPortConfig[antennaSelect]));
+ byte[] bytes = new byte[2];
+ bytes[0] = (byte)((antennaDwell/256) & 0xFF);
+ bytes[1] = (byte)((antennaDwell%256) & 0xFF);
+ if (sameCheck || true) {
+ byte[] bytesOld = new byte[2];
+ System.arraycopy(antennaPortConfig[antennaSelect], 1, bytesOld, 0, bytesOld.length);
+ if (DEBUG) appendToLog("2A2 setAntennaDwell: bytesOld = " + byteArrayToString(bytesOld));
+ boolean bValue1 = compareArray(bytes, bytesOld, bytes.length);
+ if (DEBUG) appendToLog("2ab setAntennaDwell: the array is the same = " + bValue1);
+ }
+ bValue = writeMAC(0x3030 + antennaSelect * 16 + 1, bytes, true);
+ if (bValue) {
+ System.arraycopy(bytes, 0, antennaPortConfig[antennaSelect], 1, bytes.length);
+ //appendToLog("RfidReaderChipE710.setAntennaDwell, antennaPortConfig[" + antennaSelect + "] = " + byteArrayToString(bytes));
+ }
+ if (DEBUG) appendToLog("2b setAntennaDwell: getAntennaPortConfig[" + antennaSelect + "] = " + byteArrayToString(antennaPortConfig[antennaSelect]));
+ }
+ return bValue;
+ }
+
+ public long getAntennaPower(int portNumber) {
+ long lValue = -1; boolean DEBUG = false;
+ if (DEBUG) appendToLog("2 getAntennaPower: portNumber = " + portNumber);
+ if (portNumber < 0) portNumber = antennaSelect;
+ if (antennaPortConfig[portNumber] == null) appendToLog("CANNOT continue as antennaPortConfig[" + portNumber + "] is null !!!");
+ else {
+ if (DEBUG) appendToLog("2A getAntennaPower: getAntennaPortConfig[" + portNumber + "] = " + byteArrayToString(antennaPortConfig[portNumber]));
+ lValue = (antennaPortConfig[portNumber][3] & 0xFF) * 256;
+ lValue += (antennaPortConfig[portNumber][4] & 0xFF);
+ if (DEBUG) appendToLog(String.format("2b getAntennaPower: lValue = 0x%X", lValue));
+ lValue /= 10;
+ }
+ return lValue;
+ }
+ public boolean setAntennaPower(long antennaPower) {
+ boolean bValue = false, DEBUG = false;
+ if (antennaPortConfig[antennaSelect] == null) {
+ if (DEBUG) appendToLog("4 bValue = " + bValue);
+ appendToLog("!!! CANNOT continue as antennaPortConfig[" + antennaSelect + "] is null");
+ }
+ else if (getAntennaPower(antennaSelect) == antennaPower && sameCheck) {
+ if (DEBUG) appendToLog("3 bValue = " + bValue);
+ return true;
+ }
+ else {
+ if (DEBUG) appendToLog("2 setAntennaPower: antennaPower = " + antennaPower);
+ if (DEBUG) appendToLog("2A setAntennaPower: getAntennaPortConfig[" + antennaSelect + "] = " + byteArrayToString(antennaPortConfig[antennaSelect]));
+ antennaPower *= 10;
+ byte[] bytes = new byte[2];
+ bytes[0] = (byte)((antennaPower/256) & 0xFF);
+ bytes[1] = (byte)((antennaPower%256) & 0xFF);
+ if (sameCheck | true) {
+ byte[] bytesOld = new byte[2];
+ System.arraycopy(antennaPortConfig[antennaSelect], 3, bytesOld, 0, bytesOld.length);
+ if (DEBUG) appendToLog("2A2 setAntennaPower: bytesOld = " + byteArrayToString(bytesOld));
+ boolean bValue1 = compareArray(bytes, bytesOld, bytes.length);
+ if (DEBUG) appendToLog("2ab setAntennaPower: the array is the same = " + bValue1);
+ }
+
+ bValue = writeMAC(0x3030 + antennaSelect * 16 + 3, bytes, true);
+ if (DEBUG) appendToLog("2 bValue = " + bValue);
+ if (bValue) System.arraycopy(bytes, 0, antennaPortConfig[antennaSelect], 3, bytes.length);
+ if (DEBUG) appendToLog("2b setAntennaPower: with updated " + byteArrayToString(antennaPortConfig[antennaSelect]));
+ }
+ if (DEBUG) appendToLog("1 bValue = " + bValue);
+ return bValue;
+ }
+
+ long antennaInvCount = -1;
+ public boolean setAntennaInvCount(long antennaInvCount) {
+ if (antennaInvCount == this.antennaInvCount) return true;
+ this.antennaInvCount = antennaInvCount; appendToLog(String.format("!!! Skip setAntennaInvCount[0x%X]", antennaInvCount));
+ return true;
+ }
+
+ //Tag select block parameters
+ final int INVSELECT_INVALID = -1; final int INVSELECT_MIN = 0; final int INVSELECT_MAX = 7;
+ public int invSelectIndex = INVSELECT_INVALID;
+ public int getInvSelectIndex() {
+ if (invSelectIndex < INVSELECT_MIN || invSelectIndex > INVSELECT_MAX) {
+ invSelectIndex = 0; appendToLog("!!! Skip getInvSelectIndex with assumed value = 0");
+ }
+ return invSelectIndex;
+ }
+ public boolean setInvSelectIndex(int invSelect) {
+ if (invSelect < INVSELECT_MIN || invSelect > INVSELECT_MAX) invSelect = mDefault.invSelectIndex;
+ if (this.invSelectIndex == invSelect && sameCheck) {
+ appendToLog("!!! Skip sending repeated data with invSelect = " + invSelect);
+ return true;
+ }
+ this.invSelectIndex = invSelect;
+ appendToLog(String.format("!!! Skip setInvSelectIndex[%d]", invSelect));
+ return true;
+ }
+
+ InvSelectData[] invSelectData;
+ public int getSelectEnable() {
+ int iValue = -1;
+ if (invSelectIndex < INVSELECT_MIN || invSelectIndex > INVSELECT_MAX) invSelectIndex = mDefault.invSelectIndex;
+ if (selectConfiguration[invSelectIndex] == null) appendToLog("!!! CANNOT getSelectEnable as selectConfiguration[" + invSelectIndex + "] is null");
+ else iValue = (byte)(selectConfiguration[invSelectIndex][0] & 0xFF);
+ return iValue;
+ }
+ public boolean setSelectEnable(int enable, int selectTarget, int selectAction, int selectDelay) {
+ boolean bValue = false, DEBUG = false;
+ if (DEBUG) appendToLog("Start with enable = " + enable + ", selectTarget = " + selectTarget + ", selectAction = " + selectAction + ", selectDelay = " + selectDelay);
+ if (invSelectIndex < INVSELECT_MIN || invSelectIndex > INVSELECT_MAX) invSelectIndex = mDefault.invSelectIndex;
+ if (selectConfiguration[invSelectIndex] == null) appendToLog("!!! CANNOT setSelectEnable as selectConfiguration[" + invSelectIndex + "] is null");
+ else {
+ if (DEBUG) appendToLog("Old selectConfiguration " + invSelectIndex + " = " + byteArrayToString(selectConfiguration[invSelectIndex]));
+ byte[] bytes = new byte[42];
+ if (selectConfiguration[invSelectIndex] != null) System.arraycopy(selectConfiguration[invSelectIndex], 0, bytes, 0, bytes.length);
+ bytes[0] = (byte)(enable & 0xFF);
+ bytes[39] = (byte)(selectTarget & 0xFF);
+ bytes[40] = (byte)(selectAction & 0xFF);
+ bytes[41] = (byte)(selectDelay & 0xFF);;
+ if (compareArray(selectConfiguration[invSelectIndex], bytes, bytes.length) && sameCheck) {
+ appendToLog("!!! Skip sending repeated data " + byteArrayToString(bytes) + " to address 0x3140");
+ return true;
+ }
+ bValue = writeMAC(0x3140 + invSelectIndex * 42, bytes, true);
+ if (DEBUG) appendToLog("after writeMAC 0x3140, bValue = " + bValue);
+ if (bValue) selectConfiguration[invSelectIndex] = bytes;
+ else appendToLog("!!! Failed to send data " + byteArrayToString(bytes) + " to address 0x3140");
+ if (DEBUG) appendToLog("bytes = " + byteArrayToString(bytes) + ", new selectConfiguration " + invSelectIndex + " = " + byteArrayToString(selectConfiguration[invSelectIndex]));
+ }
+ if (DEBUG) appendToLog("End with bValue = " + bValue);
+ return bValue;
+ }
+
+ public int getSelectTarget() {
+ int iValue = -1;
+ if (invSelectIndex < INVSELECT_MIN || invSelectIndex > INVSELECT_MAX) invSelectIndex = mDefault.invSelectIndex;
+ if (selectConfiguration[invSelectIndex] == null) appendToLog("!!! CANNOT getSelectTarget as selectConfiguration[" + invSelectIndex + "] is null");
+ else iValue = (selectConfiguration[invSelectIndex][39] & 0xFF);
+ return iValue;
+ }
+
+ public int getSelectAction() {
+ int iValue = -1;
+ if (invSelectIndex < INVSELECT_MIN || invSelectIndex > INVSELECT_MAX) invSelectIndex = mDefault.invSelectIndex;
+ if (selectConfiguration[invSelectIndex] == null) appendToLog("!!! CANNOT getSelectTarget as selectConfiguration[" + invSelectIndex + "] is null");
+ else iValue = (selectConfiguration[invSelectIndex][40] & 0xFF);
+ return iValue;
+ }
+
+ public int getSelectMaskBank() {
+ int iValue = -1;
+ if (invSelectIndex < INVSELECT_MIN || invSelectIndex > INVSELECT_MAX) invSelectIndex = mDefault.invSelectIndex;
+ if (selectConfiguration[invSelectIndex] == null) appendToLog("!!! CANNOT getSelectMaskBank as selectConfiguration[" + invSelectIndex + "] is null");
+ else iValue = (byte)(selectConfiguration[invSelectIndex][1] & 0xFF);
+ return iValue;
+ }
+ public boolean setSelectMaskBank(int selectMaskBank) {
+ boolean bValue = false, DEBUG = false;
+ if (invSelectIndex < INVSELECT_MIN || invSelectIndex > INVSELECT_MAX) invSelectIndex = mDefault.invSelectIndex;
+ if (selectConfiguration[invSelectIndex] == null) appendToLog("!!! CANNOT setSelectMaskBank[" + selectMaskBank + "] as selectConfiguration[" + invSelectIndex + "] is null");
+ else {
+ if (DEBUG) appendToLog("Old selectConfiguration " + invSelectIndex + " = " + byteArrayToString(selectConfiguration[invSelectIndex]));
+ byte[] bytes = new byte[1];
+ bytes[0] = (byte)(selectMaskBank & 0xFF);
+ if (true) {
+ byte[] bytes1 = new byte[selectConfiguration[invSelectIndex].length];
+ System.arraycopy(selectConfiguration[invSelectIndex], 0, bytes1, 0, bytes1.length);
+ System.arraycopy(bytes, 0, bytes1, 1, bytes.length);
+ bValue = writeMAC(0x3140 + invSelectIndex * 42, bytes1, true);
+ } else {
+ bValue = writeMAC(0x3140 + invSelectIndex * 42 + 1, bytes, true);
+ }
+ if (bValue) selectConfiguration[invSelectIndex][1] = bytes[0];
+ if (DEBUG) appendToLog("bytes = " + byteArrayToString(bytes) + ", new selectConfiguration " + invSelectIndex + " = " + byteArrayToString(selectConfiguration[invSelectIndex]));
+ }
+ if (DEBUG) appendToLog("1 setSelectMaskBank with selectMaskBank = " + selectMaskBank + " and bValue = " + bValue);
+ return bValue;
+ }
+
+ public int getSelectMaskOffset() {
+ int iValue = -1;
+ if (invSelectIndex < INVSELECT_MIN || invSelectIndex > INVSELECT_MAX) invSelectIndex = mDefault.invSelectIndex;
+ if (selectConfiguration[invSelectIndex] == null) appendToLog("!!! CANNOT getSelectMaskBank as selectConfiguration[" + invSelectIndex + "] is null");
+ else {
+ iValue = ((selectConfiguration[invSelectIndex][2] & 0xFF) << 24);
+ iValue += ((selectConfiguration[invSelectIndex][3] & 0xFF) << 16);
+ iValue += ((selectConfiguration[invSelectIndex][4] & 0xFF) << 8);
+ iValue += (selectConfiguration[invSelectIndex][5] & 0xFF);
+ }
+ return iValue;
+ }
+ public boolean setSelectMaskOffset(int selectMaskOffset) {
+ boolean bValue = false, DEBUG = false;
+ if (invSelectIndex < INVSELECT_MIN || invSelectIndex > INVSELECT_MAX) invSelectIndex = mDefault.invSelectIndex;
+ if (selectConfiguration[invSelectIndex] == null) appendToLog("!!! CANNOT setSelectMaskBank[" + selectMaskOffset + "] as selectConfiguration[" + invSelectIndex + "] is null");
+ else {
+ if (DEBUG) appendToLog("Old selectConfiguration " + invSelectIndex + " = " + byteArrayToString(selectConfiguration[invSelectIndex]));
+ byte[] bytes = new byte[4];
+ bytes[0] = (byte)((selectMaskOffset >> 24) & 0xFF);
+ bytes[1] = (byte)((selectMaskOffset >> 16) & 0xFF);
+ bytes[2] = (byte)((selectMaskOffset >> 8) & 0xFF);
+ bytes[3] = (byte)(selectMaskOffset & 0xFF);
+ if (true) {
+ byte[] bytes1 = new byte[selectConfiguration[invSelectIndex].length];
+ System.arraycopy(selectConfiguration[invSelectIndex], 0, bytes1, 0, bytes1.length);
+ System.arraycopy(bytes, 0, bytes1, 2, bytes.length);
+ bValue = writeMAC(0x3140 + invSelectIndex * 42, bytes1, true);
+ } else {
+ bValue = writeMAC(0x3140 + invSelectIndex * 42 + 2, bytes, true);
+ }
+ if (bValue) System.arraycopy(bytes, 0, selectConfiguration[invSelectIndex], 2, bytes.length);
+ if (DEBUG) appendToLog("bytes = " + byteArrayToString(bytes) + ", new selectConfiguration " + invSelectIndex + " = " + byteArrayToString(selectConfiguration[invSelectIndex]));
+ }
+ if (DEBUG) appendToLog("1 setSelectMaskOffset with selectMaskOffset = " + selectMaskOffset + " and bValue = " + bValue);
+ return bValue;
+ }
+
+ public int getSelectMaskLength() {
+ int dataIndex = invSelectIndex, iValue = INVSELECT_INVALID; boolean DEBUG = false;
+ if (dataIndex >= INVSELECT_MIN && dataIndex <= INVSELECT_MAX) {
+ if (DEBUG) appendToLog("selectConfiguration " + dataIndex + " = " + byteArrayToString(selectConfiguration[dataIndex]));
+ if (selectConfiguration[dataIndex] != null) {
+ iValue = selectConfiguration[dataIndex][6];
+ }
+ }
+ if (DEBUG) appendToLog("iValue = " + iValue);
+ return iValue;
+ }
+ public boolean setSelectMaskLength(int selectMaskLength) {
+ boolean bValue = false, DEBUG = false;
+ if (invSelectIndex < INVSELECT_MIN || invSelectIndex > INVSELECT_MAX) invSelectIndex = mDefault.invSelectIndex;
+ if (selectConfiguration[invSelectIndex] == null) appendToLog("!!! CANNOT setSelectMaskLength[" + selectMaskLength + "] as selectConfiguration[" + invSelectIndex + "] is null");
+ else {
+ if (DEBUG) appendToLog("Old selectConfiguration " + invSelectIndex + " = " + byteArrayToString(selectConfiguration[invSelectIndex]));
+ byte[] bytes = new byte[1];
+ bytes[0] = (byte)(selectMaskLength & 0xFF);
+ if (true) {
+ byte[] bytes1 = new byte[selectConfiguration[invSelectIndex].length];
+ System.arraycopy(selectConfiguration[invSelectIndex], 0, bytes1, 0, bytes1.length);
+ System.arraycopy(bytes, 0, bytes1, 6, bytes.length);
+ bValue = writeMAC(0x3140 + invSelectIndex * 42, bytes1, true);
+ } else {
+ bValue = writeMAC(0x3140 + invSelectIndex * 42 + 6, bytes, true);
+ }
+ if (bValue) selectConfiguration[invSelectIndex][6] = bytes[0];
+ if (DEBUG) appendToLog("bytes = " + byteArrayToString(bytes) + ", new selectConfiguration " + invSelectIndex + " = " + byteArrayToString(selectConfiguration[invSelectIndex]));
+ }
+ if (DEBUG) appendToLog("1 setSelectMaskOffset with setSelectMaskLength = " + selectMaskLength + " and bValue = " + bValue);
+ return bValue;
+ }
+
+ public String getSelectMaskData() {
+ String strValue = null; boolean DEBUG = false;
+ if (invSelectIndex < INVSELECT_MIN || invSelectIndex > INVSELECT_MAX) invSelectIndex = mDefault.invSelectIndex;
+ if (selectConfiguration[invSelectIndex] == null) appendToLog("!!! CANNOT getSelectMaskBank as selectConfiguration[" + invSelectIndex + "] is null");
+ else {
+ if (selectConfiguration[invSelectIndex] != null && selectConfiguration[invSelectIndex].length > 39) {
+ if (DEBUG || true) appendToLog("selectConfiguration " + invSelectIndex + " = " + byteArrayToString(selectConfiguration[invSelectIndex]));
+ byte[] bytes = new byte[32];
+ System.arraycopy(selectConfiguration[invSelectIndex], 7, bytes, 0, bytes.length);
+ if (DEBUG || true) appendToLog("bytes = " + byteArrayToString(bytes));
+ for (int i = 0; i < bytes.length; i++) {
+ String string = String.format("%02X", bytes[i]);
+ if (strValue == null) strValue = string;
+ else strValue += string;
+ if (DEBUG) appendToLog("i = " + i + ", strValue = " + strValue);
+ }
+ if (strValue == null) strValue = "";
+ }
+ }
+ return strValue;
+ }
+ public boolean setSelectMaskData(String maskData) {
+ boolean bValue = false, DEBUG = false;
+ if (invSelectIndex < INVSELECT_MIN || invSelectIndex > INVSELECT_MAX) invSelectIndex = mDefault.invSelectIndex;
+ if (selectConfiguration[invSelectIndex] == null) appendToLog("!!! CANNOT setSelectMaskData[" + maskData + "] as selectConfiguration[" + invSelectIndex + "] is null");
+ else {
+ if (DEBUG) appendToLog("Old selectConfiguration " + invSelectIndex + " = " + byteArrayToString(selectConfiguration[invSelectIndex]));
+ byte[] bytes = new byte[maskData.length() / 2 + maskData.length() % 2];
+ for (int i = 0; i < bytes.length; i++) {
+ boolean bSingle = false;
+ if (i * 2 + 2 > maskData.length()) bSingle = true;
+ if (DEBUG) appendToLog("substring i = " + i + " " + maskData.substring(i * 2, (bSingle ? i * 2 +1 : i * 2 + 2)));
+ try {
+ String stringSub = null;
+ if (bSingle) {
+ stringSub = maskData.substring(i * 2, i * 2 + 1) + "0";
+ } else stringSub = maskData.substring(i * 2, i * 2 + 2);
+ int iValue = Integer.parseInt(stringSub, 16);
+ bytes[i] = (byte) (iValue & 0xFF);
+ } catch (Exception ex) {
+ appendToLog("!!! Error in parsing maskdata " + maskData + " when i = " + i);
+ }
+ }
+ if (true) {
+ byte[] bytes1 = new byte[selectConfiguration[invSelectIndex].length];
+ System.arraycopy(selectConfiguration[invSelectIndex], 0, bytes1, 0, bytes1.length);
+ System.arraycopy(bytes, 0, bytes1, 7, bytes.length);
+ bValue = writeMAC(0x3140 + invSelectIndex * 42, bytes1, true);
+ } else {
+ bValue = writeMAC(0x3140 + invSelectIndex * 42 + 7, bytes, true);
+ }
+ if (bValue) System.arraycopy(bytes, 0, selectConfiguration[invSelectIndex], 7, bytes.length);
+ if (DEBUG) appendToLog("bytes = " + byteArrayToString(bytes) + ", new selectConfiguration " + invSelectIndex + " = " + byteArrayToString(selectConfiguration[invSelectIndex]));
+ }
+ if (DEBUG) appendToLog("1 setSelectMaskData with maskData = " + maskData + " and bValue = " + bValue);
+ return bValue;
+
+ }
+
+ public int getQueryTarget() {
+ int iValue = -1; boolean DEBUG = false;
+ if (DEBUG) appendToLog("2 getQueryTarget: iAntennaPort = " + antennaSelect);
+ if (antennaPortConfig[antennaSelect] == null)
+ appendToLog("CANNOT continue as antennaPortConfig[" + antennaSelect + "] is null !!!");
+ else {
+ if (DEBUG)
+ appendToLog("2A getQueryTarget: getAntennaPortConfig[" + antennaSelect + "] = " + byteArrayToString(antennaPortConfig[antennaSelect]));
+ if (antennaPortConfig[antennaSelect][13] != 0) iValue = 2;
+ else if ((antennaPortConfig[antennaSelect][6] & 0x80) != 0) iValue = 1;
+ else iValue = 0;
+ if (DEBUG) appendToLog(String.format("2b getQueryTarget: iValue = 0x%X", iValue));
+ }
+ return iValue;
+ }
+ public boolean setQueryTarget(int queryTarget, int querySession, int querySelect) {
+ boolean bValue = false, DEBUG = false;
+ if (antennaPortConfig[antennaSelect] == null) appendToLog("CANNOT continue as antennaPortConfig[" + antennaSelect + "] is null !!!");
+ else { // queryTarget = 0;
+ if (DEBUG) appendToLog("2 setQueryConfig: queryTarget = " + queryTarget + ", querySession = " + querySession + ", querySelect = " + querySelect);
+ if (DEBUG) appendToLog("2A setQueryConfig: getAntennaPortConfig[" + antennaSelect + "] = " + byteArrayToString(antennaPortConfig[antennaSelect]));
+ byte[] bytes = new byte[9];
+ System.arraycopy(antennaPortConfig[antennaSelect], 5, bytes, 0, bytes.length);
+
+ int iValue;
+ if (querySession >= 0) {
+ iValue = querySession & 0x03;
+ bytes[1] &= ~0x18; bytes[1] |= (iValue << 3);
+ }
+ if (querySelect >= 0) {
+ iValue = querySelect & 0x03;
+ bytes[1] &= ~0x60; bytes[1] |= (iValue << 5);
+ }
+ if (DEBUG) appendToLog("2b setQueryConfig: queryTarget = " + queryTarget);
+ if (queryTarget >= 0) {
+ iValue = queryTarget & 0x01;
+ bytes[1] &= ~0x80; bytes[1] |= (iValue << 7);
+ if (queryTarget >= 2) bytes[8] = 1;
+ else bytes[8] = 0;
+ }
+ if (DEBUG) appendToLog("2C setQueryConfig: bytes = " + byteArrayToString(bytes));
+ boolean bSame = false;
+ if (sameCheck | true) {
+ byte[] bytesOld = new byte[9];
+ System.arraycopy(antennaPortConfig[antennaSelect], 5, bytesOld, 0, bytes.length);
+ if (DEBUG) appendToLog("2d setQueryConfig: bytesOld = " + byteArrayToString(bytesOld));
+ bSame = compareArray(bytes, bytesOld, bytes.length);
+ if (DEBUG) appendToLog("2E setQueryConfig: the array is the same = " + bSame);
+ }
+ //bSame = false; appendToLog("!!! assme bSame is false before 1b writeMAC 0x3035");
+ if (bSame) {
+ if (DEBUG_PKDATA) appendToLog(String.format("!!! Skip sending repeated data %s in address 0x%X", byteArrayToString(bytes), 0x3030 + antennaSelect * 16 + 5));
+ bValue = true;
+ } else {
+ appendToLog("test 2");
+ bValue = rx000Setting.writeMAC(0x3030 + antennaSelect * 16 + 5, bytes, true);
+ if (bValue)
+ System.arraycopy(bytes, 0, antennaPortConfig[antennaSelect], 5, bytes.length);
+ }
+ if (DEBUG) appendToLog("2F setQueryConfig: with updated " + byteArrayToString(antennaPortConfig[antennaSelect]));
+ }
+ return bValue;
+ }
+ public int getQuerySession() {
+ int iValue = -1; boolean DEBUG = false;
+ if (DEBUG) appendToLog("2 getQuerySession: iAntennaPort = " + antennaSelect);
+ if (antennaPortConfig[antennaSelect] == null) appendToLog("CANNOT continue as antennaPortConfig[" + antennaSelect + "] is null !!!");
+ else {
+ if (DEBUG) appendToLog("2A getQuerySession: getAntennaPortConfig[" + antennaSelect + "] = " + byteArrayToString(antennaPortConfig[antennaSelect]));
+ iValue = (antennaPortConfig[antennaSelect][6] & 0x18) >> 3;
+ if (DEBUG) appendToLog(String.format("2b getQuerySession: iValue = 0x%X", iValue));
+ }
+ return iValue;
+ }
+
+ public int getQuerySelect() {
+ int iValue = -1; boolean DEBUG = false;
+ if (DEBUG) appendToLog("2 getQuerySession: iAntennaPort = " + antennaSelect);
+ if (antennaPortConfig[antennaSelect] == null) appendToLog("CANNOT continue as antennaPortConfig[" + antennaSelect + "] is null !!!");
+ else {
+ if (DEBUG) appendToLog("2A getQuerySession: getAntennaPortConfig[" + antennaSelect + "] = " + byteArrayToString(antennaPortConfig[antennaSelect]));
+ iValue = (antennaPortConfig[antennaSelect][6] & 0x60) >> 5;
+ if (DEBUG) appendToLog(String.format("2b getQuerySession: iValue = 0x%X", iValue));
+ }
+ return iValue;
+
+ }
+ public boolean setQuerySelect(int querySelect) {
+ boolean bValue = false, DEBUG = false;
+ for (int antennaSelect = 0; antennaSelect < 16; antennaSelect++) {
+ if (antennaPortConfig[antennaSelect] == null)
+ appendToLog("CANNOT continue as antennaPortConfig[" + antennaSelect + "] is null !!!");
+ else if (antennaPortConfig[antennaSelect][0] == 0) { }
+ else { // queryTarget = 0;
+ if (DEBUG) appendToLog("2 setQuerySelect: querySelect = " + querySelect);
+ if (DEBUG)
+ appendToLog("2A setQuerySelect: getAntennaPortConfig[" + antennaSelect + "] = " + byteArrayToString(antennaPortConfig[antennaSelect]));
+ byte[] bytes = new byte[1];
+ bytes[0] = antennaPortConfig[antennaSelect][6];
+
+ int iValue;
+ if (querySelect >= 0) {
+ iValue = querySelect & 0x03;
+ bytes[0] &= ~0x60;
+ bytes[0] |= (iValue << 5);
+ }
+ if (DEBUG)
+ appendToLog("2C setQueryConfig: bytes = " + byteArrayToString(bytes));
+ boolean bSame = false;
+ if (sameCheck) {
+ if (bytes[0] == antennaPortConfig[antennaSelect][6]) bSame = true;
+ if (DEBUG)
+ appendToLog("2E setQueryConfig: the array is the same = " + bSame);
+ }
+ if (bSame) {
+ if (DEBUG_PKDATA)
+ appendToLog(String.format("!!! Skip sending repeated data %s in address 0x%X", byteArrayToString(bytes), 0x3030 + antennaSelect * 16 + 5));
+ bValue = true;
+ } else {
+ bValue = rx000Setting.writeMAC(0x3030 + antennaSelect * 16 + 6, bytes, true);
+ if (bValue) antennaPortConfig[antennaSelect][6] = bytes[0];
+ }
+ if (DEBUG)
+ appendToLog("2F setQueryConfig: with updated " + byteArrayToString(antennaPortConfig[antennaSelect]));
+ if (bValue == false) break;
+ }
+ }
+ return bValue;
+ }
+
+ final int INVALGO_INVALID = -1; final int INVALGO_MIN = 0; final int INVALGO_MAX = 3;
+ int invAlgo = INVALGO_INVALID;
+ public int getInvAlgo() {
+ int iValue = -1; boolean DEBUG = false;
+ if (DEBUG) appendToLog("3 getInvAlgo: iAntennaPort = " + antennaSelect);
+ if (antennaPortConfig[antennaSelect] == null) appendToLog("CANNOT continue as antennaPortConfig[" + antennaSelect + "] is null !!!");
+ else {
+ if (DEBUG) appendToLog("3A getInvAlgo: getAntennaPortConfig[" + antennaSelect + "] = " + byteArrayToString(antennaPortConfig[antennaSelect]));
+ iValue = antennaPortConfig[antennaSelect][6];
+ if (DEBUG) appendToLog(String.format("3b getInvAlgo: iValue = 0x%X", iValue));
+ iValue &= 0x01; //iValue |= 0x01;
+ if (DEBUG) appendToLog(String.format("3c getInvAlgo: changed iValue = 0x%X", iValue));
+ if (iValue == 0) iValue = 3;
+ else iValue = 0;
+ if (DEBUG) appendToLog(String.format("3d getInvAlgo: after adjustement, iValue = 0x%X", iValue));
+ }
+ return iValue;
+ }
+ public boolean setInvAlgo(int invAlgo) {
+ boolean bValue = false, DEBUG = false;
+ if (DEBUG) appendToLog("3 setInvAlgo[" + invAlgo + "]");
+ if (antennaPortConfig[antennaSelect] == null) appendToLog("CANNOT continue as antennaPortConfig[" + antennaSelect + "] is null !!!");
+ else {
+ byte[] bytes = new byte[1];
+ bytes[0] = (byte)(antennaPortConfig[antennaSelect][6] & ~0x01);
+ if (invAlgo == 0) bytes[0] |= 0x01;
+ if (DEBUG) appendToLog("3 setInvAlgo: bytes = " + byteArrayToString(bytes));
+ bValue = writeMAC(0x3036 + this.antennaSelect * 16, bytes, true);
+ if (bValue) antennaPortConfig[antennaSelect][6] = bytes[0];
+ }
+ if (DEBUG) appendToLog("3A setInvAlgo with bValue = " + bValue);
+ return bValue;
+ }
+
+ final int MATCHREP_INVALID = -1; final int MATCHREP_MIN = 0; final int MATCHREP_MAX = 255;
+ int matchRep = MATCHREP_INVALID;
+ public boolean setMatchRep(int matchRep) {
+ if (matchRep == this.matchRep) return true;
+ if (this.matchRep == matchRep && sameCheck) {
+ appendToLog("Skip sending repeated data with matchRep = " + matchRep);
+ return true;
+ }
+ this.matchRep = matchRep; appendToLog(String.format("!!! Skip setMatchRep[0x%X]", matchRep));
+ return true;
+ }
+
+ final int TAGSELECT_INVALID = -1; final int TAGSELECT_MIN = 0; final int TAGSELECT_MAX = 1;
+ int tagSelect = TAGSELECT_INVALID;
+ public boolean setTagSelect(int tagSelect) {
+ if (tagSelect == this.tagSelect) return true;
+ this.tagSelect = tagSelect; appendToLog(String.format("!!! Skip setTagSelect[%d]", tagSelect));
+ return true;
+ }
+
+ final int NOINVENTORY_INVALID = -1; final int NOINVENTORY_MIN = 0; final int NOINVENTORY_MAX = 1;
+ int noInventory = NOINVENTORY_INVALID;
+
+ final int TAGREAD_INVALID = -1; final int TAGREAD_MIN = 0; final int TAGREAD_MAX = 2;
+ int tagRead = TAGREAD_INVALID;
+ public int getTagRead() {
+ int iValue = 0;
+ if (rx000Setting.multibankReadConfig[0] == null)
+ appendToLog("!!! CANNOT continue as multibankReadConfig[0] is null !!!");
+ else if (rx000Setting.multibankReadConfig[1] == null)
+ appendToLog("!!! CANNOT continue as multibankReadConfig[1] is null !!!");
+ else if (rx000Setting.multibankReadConfig[0][0] != 0) {
+ iValue++;
+ if (rx000Setting.multibankReadConfig[1][0] != 0)
+ iValue++;
+ appendToLog("getTagRead = " + iValue);
+ } else appendToLog("getTagRead = 0 as multibankReadConfig[0] = " + byteArrayToString(multibankReadConfig[0]) + ", [1] = " + byteArrayToString(multibankReadConfig[1]));
+ return iValue;
+ }
+ boolean isMultibankReplyNeed(int index) {
+ boolean bValue = false;
+ if (resReadNoReply) bValue = true;
+ appendToLog("multibankReadConfig[" + index + "] = " + byteArrayToString(rx000Setting.multibankReadConfig[index]) + ", bValue = " + bValue);
+ return bValue;
+ }
+ boolean resReadNoReply = false;
+ public boolean setResReadNoReply(boolean resReadNoReply) {
+ appendToLog("setResReadNoReply[" + resReadNoReply + "]");
+ this.resReadNoReply = resReadNoReply;
+ return true;
+ }
+ public boolean setTagRead(int tagRead) {
+ boolean bValue = false, DEBUG = false;
+ if (DEBUG) appendToLog("0 setTagRead with tagRead = " + tagRead);
+ if (rx000Setting.multibankReadConfig[0] == null)
+ appendToLog("!!! CANNOT continue as multibankReadConfig[0] is null !!!");
+ else if (rx000Setting.multibankReadConfig[1] == null)
+ appendToLog("!!! CANNOT continue as multibankReadConfig[1] is null !!!");
+ else {
+ if (DEBUG) {
+ appendToLog("0 multibankReadConfig[0] = " + byteArrayToString(rx000Setting.multibankReadConfig[0]));
+ appendToLog("0 multibankReadConfig[1] = " + byteArrayToString(rx000Setting.multibankReadConfig[1]));
+ }
+ if ((tagRead == 0 && rx000Setting.multibankReadConfig[0][0] != 0)
+ || (tagRead != 0 && rx000Setting.multibankReadConfig[0][0] == 0)) {
+ byte[] bytes = new byte[1];
+ if (tagRead == 2 && isMultibankReplyNeed(0)) bytes[0] = 2;
+ else if (tagRead != 0) bytes[0] = 1;
+ else bytes[0] = 0;
+ if (true) {
+ byte[] bytes1 = new byte[7];
+ System.arraycopy(rx000Setting.multibankReadConfig[0], 0, bytes1, 0, bytes1.length);
+ System.arraycopy(bytes, 0, bytes1, 0, bytes.length);
+ bValue = writeMAC(0x3270 + 7 * 0, bytes1, true);
+ } else {
+ bValue = writeMAC(0x3270 + 7 * 0, bytes, true);
+ }
+ if (bValue)
+ rx000Setting.multibankReadConfig[0][0] = bytes[0];
+ if (DEBUG)
+ appendToLog("0A multibankReadConfig[0] = " + byteArrayToString(rx000Setting.multibankReadConfig[0]) + ", with bValue = " + bValue);
+ } else bValue = true;
+ if (DEBUG)
+ appendToLog("0 multibankReadConfig[1] = " + byteArrayToString(rx000Setting.multibankReadConfig[1]));
+ if (bValue && ((tagRead < 2 && rx000Setting.multibankReadConfig[1][0] != 0)
+ || (tagRead >= 2 && rx000Setting.multibankReadConfig[1][0] == 0))) {
+ byte[] bytes = new byte[1], bytes1 = null;
+ if (tagRead >= 2) bytes[0] = 1;
+ else bytes[0] = 0;
+ if (true) {
+ bytes1 = new byte[7];
+ System.arraycopy(rx000Setting.multibankReadConfig[1], 0, bytes1, 0, bytes1.length);
+ System.arraycopy(bytes, 0, bytes1, 0, bytes.length);
+ bValue = writeMAC(0x3270 + 7 * 1, bytes1, true);
+ } else {
+ bValue = writeMAC(0x3270 + 7 * 1, bytes, true);
+ }
+ if (bValue)
+ rx000Setting.multibankReadConfig[1][0] = bytes[0];
+ if (DEBUG)
+ appendToLog("0A multibankReadConfig[1] = " + byteArrayToString(rx000Setting.multibankReadConfig[1]));
+ }
+ }
+ return bValue;
+ }
+
+ final int TAGDELAY_INVALID = -1; final int TAGDELAY_MIN = 0; final int TAGDELAY_MAX = 63;
+ int tagDelay = TAGDELAY_INVALID;
+ public boolean setTagDelay(int tagDelay) {
+ if (tagDelay == this.tagDelay) return true;
+ if (this.tagDelay == tagDelay && sameCheck) {
+ appendToLog("!!! Skip sending repeated data with tagDelay = " + tagDelay);
+ return true;
+ }
+ this.tagDelay = tagDelay; appendToLog(String.format("!!! Skip setTagDelay[%d]", tagDelay));
+ return true;
+ }
+
+ byte[] dupElimRollWindow = null;
+ public byte getDupElimRollWindow() {
+ if (dupElimRollWindow != null && dupElimRollWindow.length == 1) return dupElimRollWindow[0];
+ readMAC(0x3900, 1);
+ return ((byte)-1);
+ }
+ public boolean setDupElimRollWindow(byte dupElimDelay) {
+ if (dupElimRollWindow != null && dupElimRollWindow.length == 1 && dupElimRollWindow[0] == dupElimDelay && sameCheck) {
+ appendToLog("!!! Skip sending repeated data with dupElimDelay = " + dupElimDelay);
+ return true;
+ }
+ byte[] bytes = new byte[1];
+ bytes[0] = dupElimDelay;
+ boolean bValue;
+ bValue = rx000Setting.writeMAC(0x3900, bytes, true);
+ if (bValue) dupElimRollWindow = bytes;
+ return true;
+ }
+ Date keepAliveTime;
+ Date inventoryRoundEndTime;
+ int crcErrorRate;
+ int tagRate = -1;
+ public int getTagRate() {
+ int iValue = tagRate;
+ tagRate = -1;
+ return iValue;
+ }
+ byte[] eventPacketUplnkEnable = null;
+ public int getEventPacketUplinkEnable() {
+ if (eventPacketUplnkEnable != null && eventPacketUplnkEnable.length == 2) {
+ int iValue = ((eventPacketUplnkEnable[0] & 0xFF) << 8) + (eventPacketUplnkEnable[1] & 0xFF);
+ appendToLog("eventPacketUplnkEnable iValue = " + iValue);
+ return iValue;
+ }
+ readMAC(0x3906, 2);
+ return -1;
+ }
+
+ public boolean setEventPacketUplinkEnable(byte byteEventPacketUplinkEnable) {
+ if (eventPacketUplnkEnable != null && eventPacketUplnkEnable.length == 2 && eventPacketUplnkEnable[1] == byteEventPacketUplinkEnable && sameCheck) {
+ appendToLog("!!! Skip sending repeated data with byteEventPacketUplinkEnable = " + byteEventPacketUplinkEnable);
+ return true;
+ }
+ byte[] bytes = new byte[2];
+ bytes[1] = byteEventPacketUplinkEnable;
+ boolean bValue;
+ bValue = rx000Setting.writeMAC(0x3906, bytes, true);
+ if (bValue) eventPacketUplnkEnable = bytes;
+ return true;
+ }
+
+ byte[] intraPacketDelay = null;
+ public byte getIntraPacketDelay() {
+ if (intraPacketDelay != null && intraPacketDelay.length == 1) return intraPacketDelay[0];
+ readMAC(0x3908, 1);
+ return ((byte)-1);
+ }
+ public boolean setIntraPacketDelay(byte intraPkDelay) {
+ if (intraPkDelay >= 0 && intraPacketDelay != null && sameCheck) {
+ if (intraPacketDelay.length == 1 && intraPacketDelay[0] == intraPkDelay) {
+ appendToLog("!!! Skip sending repeated data with intraPkDelay = " + intraPkDelay);
+ return true;
+ }
+ }
+ byte[] bytes = new byte[1];
+ bytes[0] = intraPkDelay;
+ boolean bValue;
+ bValue = rx000Setting.writeMAC(0x3908, bytes, true);
+ if (bValue) intraPacketDelay = bytes;
+ return true;
+ }
+ long cycleDelay = -1;
+ public long getCycleDelay() {
+ return cycleDelay;
+ }
+ public boolean setCycleDelay(long cycleDelay) {
+ if (cycleDelay == this.cycleDelay) return true;
+ if (this.cycleDelay == cycleDelay && sameCheck) {
+ appendToLog("!!! Skip sending repeated data with cycleDelay = " + cycleDelay);
+ return true;
+ }
+ this.cycleDelay = cycleDelay; appendToLog(String.format("!!! Skip setCycleDelay[%d]", cycleDelay));
+ return true;
+ }
+
+ final int AUTHENTICATE_CFG_INVALID = -1; final int AUTHENTICATE_CFG_MIN = 0; final int AUTHENTICATE_CFG_MAX = 4095;
+ boolean authenticateSendReply;
+ boolean authenticateIncReplyLength;
+ int authenticateLength = AUTHENTICATE_CFG_INVALID;
+ public int getAuthenticateReplyLength() {
+ if (authenticateLength < AUTHENTICATE_CFG_MIN || authenticateLength > AUTHENTICATE_CFG_MAX) getHST_AUTHENTICATE_CFG();
+ return authenticateLength;
+ }
+ private boolean getHST_AUTHENTICATE_CFG() {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 0, (byte) 0x0F, 0, 0, 0, 0};
+ return sendHostRegRequest(HostRegRequests.HST_AUTHENTICATE_CFG, false, msgBuffer);
+ }
+ boolean setHST_AUTHENTICATE_CFG(boolean sendReply, boolean incReplyLenth, int csi, int length) {
+ appendToLog("sendReply = " + sendReply + ", incReplyLenth = " + incReplyLenth + ", length = " + length);
+ if (length < 0 || length > 0x3FF) return false;
+
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 0, (byte) 0x0F, 0, 0, 0, 0};
+ if (sendReply) msgBuffer[4] |= 0x01; authenticateSendReply = sendReply;
+ if (incReplyLenth) msgBuffer[4] |= 0x02; authenticateIncReplyLength = incReplyLenth;
+ msgBuffer[4] |= ((csi & 0x3F) << 2);
+ msgBuffer[5] |= ((csi >> 6) & 0x03);
+ msgBuffer[5] |= ((length & 0x3F) << 2);
+ msgBuffer[6] |= ((length & 0xFC0) >> 6); authenticateLength = length;
+ return sendHostRegRequest(HostRegRequests.HST_AUTHENTICATE_CFG, true, msgBuffer);
+ }
+
+ byte[] authMatchData0_63; int authMatchDataReady = 0;
+ public String getAuthMatchData() {
+ int length = 96;
+ String strValue = "";
+ for (int i = 0; i < 3; i++) {
+ if (length > 0) {
+ appendToLog("i = " + i + ", authMatchDataReady = " + authMatchDataReady);
+ if ((authMatchDataReady & (0x01 << i)) == 0) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 1, (byte)0x0F, 0, 0, 0, 0};
+ msgBuffer[2] += i;
+ sendHostRegRequest(HostRegRequests.HST_AUTHENTICATE_MSG, false, msgBuffer);
+ } else {
+ for (int j = 0; j < 4; j++) {
+ strValue += String.format("%02X", authMatchData0_63[i * 4 + j]);
+ }
+ }
+ length -= 32;
+ }
+ }
+ if (strValue.length() < 16) strValue = null;
+ return strValue;
+ }
+
+ final int UNTRACEABLE_CFG_INVALID = -1; final int UNTRACEABLE_CFG_MIN = 0; final int UNTRACEABLE_CFG_MAX = 3;
+ int untraceableRange = UNTRACEABLE_CFG_INVALID;
+ boolean untraceableUser;
+ int untraceableTid = UNTRACEABLE_CFG_INVALID;
+ int untraceableEpcLength = UNTRACEABLE_CFG_INVALID;
+ boolean untraceableEpc;
+ boolean untraceableUXpc;
+ public int getUntraceableEpcLength() {
+ if (untraceableRange < UNTRACEABLE_CFG_MIN || untraceableRange > UNTRACEABLE_CFG_MAX) getHST_UNTRACEABLE_CFG();
+ return untraceableEpcLength;
+ }
+ private boolean getHST_UNTRACEABLE_CFG() {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 5, (byte) 0x0F, 0, 0, 0, 0};
+ return sendHostRegRequest(HostRegRequests.HST_UNTRACEABLE_CFG, false, msgBuffer);
+ }
+ public boolean setHST_UNTRACEABLE_CFG(int range, boolean user, int tid, int epcLength, boolean epc, boolean uxpc) {
+ appendToLog("range = " + range + ", user = " + user + ", tid = " + tid + ", epc = " + epc + ", epcLength = " + epcLength + ", xcpc = " + uxpc);
+ if (range < 0 || range > 3) return false;
+ if (tid < 0 || tid > 2) return false;
+ if (epcLength < 0 || epcLength > 31) return false;
+
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 5, (byte) 0x0F, 0, 0, 0, 0};
+ msgBuffer[4] |= (range); untraceableRange = range;
+ if (user) msgBuffer[4] |= 0x04; untraceableUser = user;
+ msgBuffer[4] |= (tid << 3); untraceableTid = tid;
+ msgBuffer[4] |= ((epcLength & 0x7) << 5);
+ msgBuffer[5] |= ((epcLength & 0x18) >> 3); untraceableEpcLength = epcLength;
+ if (epc) msgBuffer[5] |= 0x04; untraceableEpc = epc;
+ if (uxpc) msgBuffer[5] |= 0x08; untraceableUXpc = uxpc;
+ appendToLog("going to do sendHostRegRequest(HostRegRequests.HST_UNTRACEABLE_CFG,");
+ return sendHostRegRequest(HostRegRequests.HST_UNTRACEABLE_CFG, true, msgBuffer);
+ }
+
+ final int TAGJOIN_INVALID = -1; final int TAGJOIN_MIN = 0; final int TAGJOIN_MAX = 1;
+ int invModeCompact = TAGJOIN_INVALID;
+ public boolean setInvModeCompact(boolean bInvModeCompact) {
+ int invModeCompact = (bInvModeCompact ? 1 : 0);
+ if (invModeCompact == this.invModeCompact && sameCheck) {
+ appendToLog("!!! Skip sending repeated data with bInvModeCompact = " + bInvModeCompact);
+ return true;
+ }
+ this.invModeCompact = invModeCompact; appendToLog(String.format("!!! Skip setInvModeCompact[%s]", (bInvModeCompact ? "true" : "false")));
+ return true;
+ }
+
+ final int BRAND_INVALID = -1; final int BRANDID_MIN = 0; final int BRANDID_MAX = 1;
+ int invBrandId = BRAND_INVALID;
+ boolean getInvBrandId() {
+ if (invBrandId < BRANDID_MIN || invBrandId > BRANDID_MAX) { getHST_INV_CFG(); return false; }
+ return (invModeCompact == 1);
+ }
+ public boolean setInvBrandId(boolean invBrandId) {
+ if (invBrandId == getInvBrandId()) return true;
+ this.invBrandId = (invBrandId ? 1 : 0); appendToLog("!!! Skip setInvBrandId[" + invBrandId + "]");
+ return true;
+ }
+ private boolean getHST_INV_CFG() {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 1, 9, 0, 0, 0, 0};
+ return sendHostRegRequest(HostRegRequests.HST_INV_CFG, false, msgBuffer);
+ }
+
+ final int ALGOSELECT_INVALID = -1; final int ALGOSELECT_MIN = 0; final int ALGOSELECT_MAX = 3; //DataSheet says Max=1
+ int algoSelect = ALGOSELECT_INVALID;
+ public boolean setAlgoSelect(int algoSelect) {
+ boolean bValue = false, DEBUG = false;
+ if (antennaPortConfig[antennaSelect] == null) appendToLog("CANNOT continue as antennaPortConfig[" + antennaSelect + "] is null !!!");
+ else { //algoSelect = 0;
+ if (DEBUG) appendToLog("2 setAlgoSelect: algoSelect = " + algoSelect);
+ if (DEBUG) appendToLog("2A setAlgoSelect: getAntennaPortConfig[" + antennaSelect + "] = " + byteArrayToString(antennaPortConfig[antennaSelect]));
+ byte[] bytes = new byte[1];
+ bytes[0] = antennaPortConfig[antennaSelect][6];
+ if (algoSelect >= 3) bytes[0] &= ~0x01;
+ else bytes[0] |= 0x01;
+ if (DEBUG) appendToLog(String.format("2A1 setAlgoSelect: bytes = 0x%X with sameCheck = ", bytes[0]) + sameCheck);
+ boolean bSame = false;
+ if (sameCheck) {
+ if (DEBUG) appendToLog(String.format("2A2 setAlgoSelect: bytesOld = 0x%X", antennaPortConfig[antennaSelect][6]));
+ if (antennaPortConfig[antennaSelect][6] == bytes[0]) bSame = true;
+ if (DEBUG) appendToLog("2ab setAlgoSelect: the array is the same = " + bSame);
+ }
+ if (bSame) {
+ if (DEBUG_PKDATA) appendToLog(String.format("!!! Skip sending repeated data %s in address 0x%X", byteArrayToString(bytes), 0x3030 + antennaSelect * 16 + 6));
+ bValue = true;
+ } else {
+ bValue = rx000Setting.writeMAC(0x3030 + antennaSelect * 16 + 6, bytes, true);
+ if (bValue) antennaPortConfig[antennaSelect][6] = bytes[0];
+ }
+ if (DEBUG) appendToLog("2b setAlgoSelect: with updated array " + byteArrayToString(antennaPortConfig[antennaSelect]));
+ }
+ return bValue;
+ }
+ AlgoSelectedData[] algoSelectedData;
+ public int getAlgoStartQ(int algoSelect) {
+ if (algoSelect < ALGOSELECT_MIN || algoSelect > ALGOSELECT_MAX) {
+ return ALGOSELECT_INVALID;
+ } else {
+ return algoSelectedData[algoSelect].getAlgoStartQ(false);
+ }
+ }
+ public int getAlgoStartQ() {
+ if (algoSelect < ALGOSELECT_MIN || algoSelect > ALGOSELECT_MAX) {
+ return ALGOSELECT_INVALID;
+ } else {
+ return algoSelectedData[algoSelect].getAlgoStartQ(true);
+ }
+ }
+ public boolean setAlgoStartQ(int algoStartQ) {
+ boolean bValue = false, DEBUG = false;
+ if (antennaPortConfig[antennaSelect] == null) appendToLog("CANNOT continue as antennaPortConfig[" + antennaSelect + "] is null !!!");
+ else { //algoStartQ = 6;
+ if (DEBUG) appendToLog("2 setAlgoStartQ: algoStartQ = " + algoStartQ);
+ if (DEBUG) appendToLog("2A setAlgoStartQ: getAntennaPortConfig[" + antennaSelect + "] = " + byteArrayToString(antennaPortConfig[antennaSelect]));
+ byte[] bytes = new byte[1];
+ bytes[0] = antennaPortConfig[antennaSelect][8];
+
+ bytes[0] &= ~0x0F; bytes[0] |= (algoStartQ & 0x0F);
+ if (DEBUG) appendToLog(String.format("2A1 setAlgoStartQ: bytes = 0x%X with sameCheck = ", bytes[0]) + sameCheck);
+ boolean bSame = false;
+ if (sameCheck) {
+ if (antennaPortConfig[antennaSelect][8] == bytes[0]) bSame = true;
+ if (DEBUG) appendToLog("2ab setAlgoStartQ: the array is the same = " + bSame);
+ }
+ if (bSame) {
+ if (DEBUG_PKDATA) appendToLog(String.format("!!! Skip sending repeated data %s in address 0x%X", byteArrayToString(bytes), 0x3030 + antennaSelect * 16 + 8));
+ bValue = true;
+ } else {
+ bValue = writeMAC(0x3030 + antennaSelect * 16 + 8, bytes, true);
+ if (bValue) antennaPortConfig[antennaSelect][8] = bytes[0];
+ }
+ if (DEBUG) appendToLog("2b setAlgoStartQ: with updated " + byteArrayToString(antennaPortConfig[antennaSelect]));
+ }
+ return bValue;
+ }
+ public boolean setAlgoStartQ(int startQ, int algoMaxQ, int algoMinQ, int algoMaxRep, int algoHighThres, int algoLowThres) {
+ if (algoSelect < ALGOSELECT_MIN || algoSelect > ALGOSELECT_MAX) return false;
+ return algoSelectedData[algoSelect].setAlgoStartQ(startQ, algoMaxQ, algoMinQ, algoMaxRep, algoHighThres, algoLowThres);
+ }
+
+ public int getAlgoMaxQ(int algoSelect) {
+ if (algoSelect < ALGOSELECT_MIN || algoSelect > ALGOSELECT_MAX) {
+ return ALGOSELECT_INVALID;
+ } else {
+ return algoSelectedData[algoSelect].getAlgoMaxQ();
+ }
+ }
+
+ public int getAlgoMinQ(int algoSelect) {
+ if (algoSelect < ALGOSELECT_MIN || algoSelect > ALGOSELECT_MAX) {
+ return ALGOSELECT_INVALID;
+ } else {
+ return algoSelectedData[algoSelect].getAlgoMinQ();
+ }
+ }
+
+ final int ALGORETRY_INVALID = -1, ALGORETRY_MIN = 0, ALGORETRY_MAX = 255, ALGORETRY_DEFAULT = 1;
+ int algoRetry = ALGORETRY_INVALID;
+ public int getAlgoMinQCycles() {
+ int iValue = -1; boolean DEBUG = false;
+ if (antennaPortConfig[antennaSelect] == null) appendToLog("CANNOT continue as antennaPortConfig[" + antennaSelect + "] is null !!!");
+ else {
+ if (DEBUG) appendToLog("3A getAlgoMinQCycles: getAntennaPortConfig[" + antennaSelect + "] = " + byteArrayToString(antennaPortConfig[antennaSelect]));
+ iValue = ((antennaPortConfig[antennaSelect][7] >> 4) & 0x0F);
+ if (DEBUG) appendToLog(String.format("3b getAlgoMinQCycles: iValue = 0x%X", iValue));
+ }
+ return iValue;
+ }
+ public boolean setAlgoMinQCycles(int minQCycles) {
+ boolean bValue = false, DEBUG = false;
+ if (antennaPortConfig[antennaSelect] == null) appendToLog("CANNOT continue as antennaPortConfig[" + antennaSelect + "] is null !!!");
+ else if (getAlgoMinQCycles() == minQCycles && sameCheck) {
+ appendToLog("!!! Skip sending repeated data with algoRetry = " + algoRetry);
+ return true;
+ } else {
+ if (DEBUG) appendToLog("3A setAlgoMinQCycles: minQCycles = " + minQCycles + ", getAntennaPortConfig[" + antennaSelect + "] = " + byteArrayToString(antennaPortConfig[antennaSelect]));
+ byte[] data = new byte[1];
+ data[0] = (byte) (antennaPortConfig[antennaSelect][7] & 0x0F);
+ data[0] |= (byte)(minQCycles << 4);
+ bValue = writeMAC(0x3037 + this.antennaSelect * 16, data, true);
+ if (bValue) antennaPortConfig[antennaSelect][7] = data[0];
+ if (DEBUG) appendToLog("3C setAlgoMinQCycles: getAntennaPortConfig[" + antennaSelect + "] = " + byteArrayToString(antennaPortConfig[antennaSelect]));
+ }
+ return bValue;
+ }
+
+ int getAlgoAbFlip(int algoSelect) {
+ if (algoSelect < ALGOSELECT_MIN || algoSelect > ALGOSELECT_MAX) {
+ return ALGOSELECT_INVALID;
+ } else {
+ return algoSelectedData[algoSelect].getAlgoAbFlip();
+ }
+ }
+ public int getAlgoAbFlip() {
+ int iValue = -1; boolean DEBUG = false;
+ if (DEBUG) appendToLog("3 getAlgoAbFlip: iAntennaPort = " + antennaSelect);
+ if (antennaPortConfig[antennaSelect] == null) appendToLog("CANNOT continue as antennaPortConfig[" + antennaSelect + "] is null !!!");
+ else {
+ if (DEBUG) appendToLog("3A getAlgoAbFlip: getAntennaPortConfig[" + antennaSelect + "] = " + byteArrayToString(antennaPortConfig[antennaSelect]));
+ iValue = antennaPortConfig[antennaSelect][13];
+ if (DEBUG) appendToLog(String.format("3b getAlgoAbFlip: iValue = 0x%X", iValue));
+ }
+ return iValue;
+ }
+ public boolean setAlgoAbFlip(int algoAbFlip) {
+ boolean bValue = false, DEBUG = false;
+ if (DEBUG) appendToLog("3 setAlgoAbFlip: iAntennaPort = " + antennaSelect);
+ if (antennaPortConfig[antennaSelect] == null) appendToLog("CANNOT continue as antennaPortConfig[" + antennaSelect + "] is null !!!");
+ else {
+ if (DEBUG) appendToLog("3A setAlgoAbFlip: getAntennaPortConfig[" + antennaSelect + "] = " + byteArrayToString(antennaPortConfig[antennaSelect]));
+ byte[] data = new byte[1];
+ data[0] = (byte)(algoAbFlip & 0xFF);
+ bValue = writeMAC(0x303d + this.antennaSelect * 16, data, true);
+ if (bValue) antennaPortConfig[antennaSelect][13] = data[0];
+ if (DEBUG) appendToLog("3b setAlgoAbFlip: bValue = " + bValue);
+ if (DEBUG) appendToLog("3C setAlgoAbFlip: getAntennaPortConfig[" + antennaSelect + "] = " + byteArrayToString(antennaPortConfig[antennaSelect]));
+ }
+ return bValue;
+ }
+ boolean setAlgoAbFlip(int algoAbFlip, int algoRunTilZero) {
+ if (algoSelect < ALGOSELECT_MIN || algoSelect > ALGOSELECT_MAX) return false;
+ appendToLog("algoSelect = " + algoSelect + ", algoAbFlip = " + algoAbFlip + ", algoRunTilZero = " + algoRunTilZero);
+ return algoSelectedData[algoSelect].setAlgoAbFlip(algoAbFlip, algoRunTilZero);
+ }
+
+ public int getAlgoRunTilZero(int algoSelect) {
+ if (algoSelect < ALGOSELECT_MIN || algoSelect > ALGOSELECT_MAX) {
+ return ALGOSELECT_INVALID;
+ } else {
+ return algoSelectedData[algoSelect].getAlgoRunTilZero();
+ }
+ }
+ int getAlgoRunTilZero() {
+ if (algoSelect < ALGOSELECT_MIN || algoSelect > ALGOSELECT_MAX) {
+ return ALGOSELECT_INVALID;
+ } else {
+ return algoSelectedData[algoSelect].getAlgoRunTilZero();
+ }
+ }
+ int algoRunTilZero = -1, ALGORUNTILZERO_MIN = 0, ALGORUNTILZERO_MAX = 1, ALGORUNTILZERO_DEFAULT = 0;
+ public boolean setAlgoRunTilZero(int algoRunTilZero) {
+ if (algoSelect < ALGOSELECT_MIN || algoSelect > ALGOSELECT_MAX) return false;
+ else if (algoRunTilZero < ALGORUNTILZERO_MIN || algoRunTilZero > ALGORUNTILZERO_MAX) algoRunTilZero = ALGORUNTILZERO_DEFAULT;
+ if (this.algoRunTilZero == algoRunTilZero && sameCheck) {
+ appendToLog("!!! Skip sending repeated data with algoRunTilZero = " + algoRunTilZero);
+ return true;
+ }
+ this.algoRunTilZero = algoRunTilZero; appendToLog(String.format("!!! Skip setAlgoRunTilZero[%d]", algoRunTilZero));
+ return true;
+ }
+
+ int rssiFilterConfig = -1;
+ final int RSSIFILTERTYPE_INVALID = -1, RSSIFILTERTYPE_MIN = 0, RSSIFILTERTYPE_MAX = 2;
+ int rssiFilterType = RSSIFILTERTYPE_INVALID;
+ final int RSSIFILTEROPTION_INVALID = -1, RSSIFILTEROPTION_MIN = 0, RSSIFILTEROPTION_MAX = 4;
+ int rssiFilterOption = RSSIFILTEROPTION_INVALID;
+ public int getRssiFilterType() {
+ if (rssiFilterType < 0) getHST_INV_RSSI_FILTERING_CONFIG();
+ return rssiFilterType;
+ }
+ public int getRssiFilterOption() {
+ if (rssiFilterOption < 0) getHST_INV_RSSI_FILTERING_CONFIG();
+ return rssiFilterOption;
+ }
+ private boolean getHST_INV_RSSI_FILTERING_CONFIG() {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 7, 9, 0, 0, 0, 0};
+ return sendHostRegRequest(HostRegRequests.HST_INV_RSSI_FILTERING_CONFIG, false, msgBuffer);
+ }
+ public boolean setHST_INV_RSSI_FILTERING_CONFIG(int rssiFilterType, int rssiFilterOption) {
+ appendToLog("rssiFilterType = " + rssiFilterType + ", rssiFilterOption = " + rssiFilterOption);
+ byte[] bytes = new byte[] { 0 };
+ if (rssiFilterType > 0) {
+ if (rssiFilterOption > 0) bytes[0] = 2;
+ else bytes[0] = 1;
+ } else bytes[0] = 0;
+ boolean bValue = writeMAC(0x390A, bytes, true);
+ if (bValue) {
+ this.rssiFilterType = rssiFilterType;
+ this.rssiFilterOption = rssiFilterOption;
+ }
+ return bValue;
+ }
+
+ final int RSSIFILTERTHRESHOLD_INVALID = -1, RSSIFILTERTHRESHOLD_MIN = 0, RSSIFILTERTHRESHOLD_MAX = 0xFFFF;
+ int rssiFilterThreshold1 = RSSIFILTERTHRESHOLD_INVALID;
+ public int getRssiFilterThreshold1() {
+ if (rssiFilterThreshold1 < 0) getHST_INV_RSSI_FILTERING_THRESHOLD();
+ return rssiFilterThreshold1;
+ }
+ int rssiFilterThreshold2 = RSSIFILTERTHRESHOLD_INVALID;
+ public int getRssiFilterThreshold2() {
+ if (rssiFilterThreshold2 < 0) getHST_INV_RSSI_FILTERING_THRESHOLD();
+ return rssiFilterThreshold2;
+ }
+ private boolean getHST_INV_RSSI_FILTERING_THRESHOLD() {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 8, 9, 0, 0, 0, 0};
+ return sendHostRegRequest(HostRegRequests.HST_INV_RSSI_FILTERING_THRESHOLD, false, msgBuffer);
+ }
+ public boolean setHST_INV_RSSI_FILTERING_THRESHOLD(int rssiFilterThreshold1, int rssiFilterThreshold2) {
+ byte[] bytes = new byte[2];
+ bytes[0] = (byte)(((short)rssiFilterThreshold1 >> 8) & 0xFF);
+ bytes[1] = (byte)((short)rssiFilterThreshold1 & 0xFF);
+ boolean bValue = writeMAC(0x390C, bytes, true);
+ if (bValue) {
+ this.rssiFilterThreshold1 = rssiFilterThreshold1;
+ this.rssiFilterThreshold2 = rssiFilterThreshold2;
+ }
+ return bValue;
+ }
+
+ final long RSSIFILTERCOUNT_INVALID = -1, RSSIFILTERCOUNT_MIN = 0, RSSIFILTERCOUNT_MAX = 1000000;
+ long rssiFilterCount = RSSIFILTERCOUNT_INVALID;
+ public long getRssiFilterCount() {
+ if (rssiFilterCount < 0) getHST_INV_RSSI_FILTERING_COUNT();
+ return rssiFilterCount;
+ }
+ private boolean getHST_INV_RSSI_FILTERING_COUNT() {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 9, 9, 0, 0, 0, 0};
+ return sendHostRegRequest(HostRegRequests.HST_INV_RSSI_FILTERING_THRESHOLD, false, msgBuffer);
+ }
+ public boolean setHST_INV_RSSI_FILTERING_COUNT(long rssiFilterCount) {
+ appendToLog("entry: rssiFilterCount = " + rssiFilterCount + ", this.rssiFilterCount = " + this.rssiFilterCount);
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 9, 9, 0, 0, 0, 0};
+ if (rssiFilterCount < RSSIFILTERCOUNT_MIN || rssiFilterCount > RSSIFILTERCOUNT_MAX)
+ rssiFilterCount = mDefault.rssiFilterCount;
+ appendToLog("rssiFilterCount 1 = " + rssiFilterCount + ", this.rssiFilterCount = " + this.rssiFilterCount);
+ if (this.rssiFilterCount == rssiFilterCount && sameCheck) return true;
+ appendToLog("rssiFilterCount 2 = " + rssiFilterCount + ", this.rssiFilterCount = " + this.rssiFilterCount);
+ msgBuffer[4] |= (byte) (rssiFilterCount & 0xFF);
+ msgBuffer[5] |= (byte) ((rssiFilterCount >> 8) & 0xFF);
+ msgBuffer[6] |= (byte) ((rssiFilterCount >> 16) & 0xFF);
+ msgBuffer[7] |= (byte) ((rssiFilterCount >> 24) & 0xFF);
+ this.rssiFilterCount = rssiFilterCount;
+ appendToLog("entering to sendHostRegRequest: rssiFilterCount = " + rssiFilterCount);
+ boolean bValue = sendHostRegRequest(HostRegRequests.HST_INV_RSSI_FILTERING_COUNT, true, msgBuffer);
+ appendToLog("after sendHostRegRequest: rssiFilterCount = " + rssiFilterCount);
+ return bValue;
+ }
+
+ final int MATCHENABLE_INVALID = -1; final int MATCHENABLE_MIN = 0; final int MATCHENABLE_MAX = 1;
+ int matchEnable = MATCHENABLE_INVALID;
+ public int getInvMatchEnable() {
+ getHST_INV_EPC_MATCH_CFG();
+ return matchEnable;
+ }
+ public boolean setInvMatchEnable(int matchEnable, int matchType, int matchLength, int matchOffset) {
+ return setHST_INV_EPC_MATCH_CFG(matchEnable, matchType, matchLength, matchOffset);
+ }
+
+ final int MATCHTYPE_INVALID = -1; final int MATCHTYPE_MIN = 0; final int MATCHTYPE_MAX = 1;
+ int matchType = MATCHTYPE_INVALID;
+ public int getInvMatchType() {
+ getHST_INV_EPC_MATCH_CFG();
+ return matchType;
+ }
+
+ final int MATCHLENGTH_INVALID = 0; final int MATCHLENGTH_MIN = 0; final int MATCHLENGTH_MAX = 496;
+ int matchLength = MATCHLENGTH_INVALID;
+ public int getInvMatchLength() {
+ getHST_INV_EPC_MATCH_CFG();
+ return matchLength;
+ }
+
+ final int MATCHOFFSET_INVALID = -1; final int MATCHOFFSET_MIN = 0; final int MATCHOFFSET_MAX = 496;
+ int matchOffset = MATCHOFFSET_INVALID;
+ public int getInvMatchOffset() {
+ getHST_INV_EPC_MATCH_CFG();
+ return matchOffset;
+ }
+
+ private boolean getHST_INV_EPC_MATCH_CFG() { return true; }
+ private boolean setHST_INV_EPC_MATCH_CFG(int matchEnable, int matchType, int matchLength, int matchOffset) {
+ this.matchEnable = matchEnable;
+ this.matchType = matchType;
+ this.matchLength = matchLength;
+ this.matchOffset = matchOffset;
+ return true;
+ }
+
+ byte[] invMatchData0_63; int invMatchDataReady = 0;
+ public String getInvMatchData() {
+ String strValue = "";
+ if (invMatchData0_63 != null) strValue = byteArrayToString(invMatchData0_63);
+ return strValue;
+ }
+ public boolean setInvMatchData(String matchData) {
+ invMatchData0_63 = utility.stringToByteArray(matchData);
+ return true;
+ }
+
+ //Tag access block parameters
+ boolean accessVerfiy;
+ final int ACCRETRY_INVALID = -1; final int ACCRETRY_MIN = 0; final int ACCRETRY_MAX = 7;
+ int accessRetry = ACCRETRY_INVALID;
+ public boolean setAccessRetry(boolean accessVerfiy, int accessRetry) {
+ if (accessVerfiy == this.accessVerfiy && accessRetry == this.accessRetry) return true;
+ this.accessVerfiy = accessVerfiy; this.accessRetry = accessRetry; appendToLog("!!! Skip setAccessRetry[" + accessVerfiy + ", " + accessRetry + "]");
+ return true;
+ }
+
+ boolean setAccessEnable(int accessEnable, int accessEnable2) {
+ boolean bValue = false, DEBUG = false;
+ if (DEBUG) appendToLog("0 setAccessEnable with accessEnable = " + accessEnable + ", accessEnable2 = " + accessEnable2);
+ if (rx000Setting.multibankReadConfig[0] == null) appendToLog("!!! CANNOT continue as multibankReadConfig[0] is null !!!");
+ else if (rx000Setting.multibankReadConfig[1] == null) appendToLog("!!! CANNOT continue as multibankReadConfig[1] is null !!!");
+ else {
+ if (DEBUG) appendToLog("0 multibankReadConfig[0] = " + byteArrayToString(rx000Setting.multibankReadConfig[0]));
+ if (accessEnable == rx000Setting.multibankReadConfig[0][0] && sameCheck) bValue = true;
+ else {
+ byte[] bytes = new byte[1];
+ bytes[0] = (byte) (accessEnable & 0xFF);
+ if (true) {
+ byte[] bytes1 = new byte[7];
+ System.arraycopy(rx000Setting.multibankReadConfig[0], 0, bytes1, 0, bytes1.length);
+ System.arraycopy(bytes, 0, bytes1, 0, bytes.length);
+ bValue = writeMAC(0x3270 + 7 * 0, bytes1, true);
+ } else {
+ bValue = writeMAC(0x3270 + 7 * 0, bytes, true);
+ }
+ if (bValue) rx000Setting.multibankReadConfig[0][0] = bytes[0];
+ if (DEBUG) appendToLog("0A multibankReadConfig[0] = " + byteArrayToString(rx000Setting.multibankReadConfig[0]));
+ }
+ if (DEBUG) appendToLog("0 multibankReadConfig[1] = " + byteArrayToString(rx000Setting.multibankReadConfig[1]));
+ if (accessEnable2 == rx000Setting.multibankReadConfig[1][0] && sameCheck) { }
+ else if (bValue) {
+ byte[] bytes = new byte[1];
+ bytes[0] = (byte) (accessEnable2 & 0xFF);
+ if (true) {
+ byte[] bytes1 = new byte[7];
+ System.arraycopy(rx000Setting.multibankReadConfig[1], 0, bytes1, 0, bytes1.length);
+ System.arraycopy(bytes, 0, bytes1, 0, bytes.length);
+ bValue = writeMAC(0x3270 + 7 * 1, bytes1, true);
+ } else {
+ bValue = writeMAC(0x3270 + 7 * 1, bytes, true);
+ }
+ if (bValue) rx000Setting.multibankReadConfig[1][0] = bytes[0];
+ if (DEBUG) appendToLog("0A multibankReadConfig[1] = " + byteArrayToString(rx000Setting.multibankReadConfig[1]));
+ }
+ }
+ return bValue;
+ }
+ final int ACCBANK_INVALID = -1; final int ACCBANK_MIN = 0; final int ACCBANK_MAX = 3;
+ int accessBank = ACCBANK_INVALID; int accessBank2 = ACCBANK_INVALID;
+ int getAccessBank() {
+ boolean DEBUG = false; int iValue = -1;
+ if (accessBank >= 0 && accessBank <= 3 && rx000Setting.multibankReadConfig[0] == null) appendToLog("!!! CANNOT continue as multibankReadConfig[0] is null !!!");
+ else iValue = rx000Setting.multibankReadConfig[0][1];
+ return iValue;
+ }
+ public boolean setAccessBank(int accessBank) { return setAccessBank(accessBank, 0); }
+ public boolean setAccessBank(int accessBank, int accessBank2) {
+ boolean bValue = false, DEBUG = false;
+ if (DEBUG) appendToLog("0 setAccessBank with accessBank = " + accessBank + ", accessBank2 = " + accessBank2);
+ if (accessBank >= 0 && accessBank <= 3 && rx000Setting.multibankReadConfig[0] == null) appendToLog("!!! CANNOT continue as multibankReadConfig[0] is null !!!");
+ else if (accessBank2 >= 0 && accessBank2 <= 3 && rx000Setting.multibankReadConfig[1] == null) appendToLog("!!! CANNOT continue as multibankReadConfig[1] is null !!!");
+ else {
+ if (DEBUG) appendToLog("0 multibankReadConfig[0] = " + byteArrayToString(rx000Setting.multibankReadConfig[0]));
+ if (accessBank == rx000Setting.multibankReadConfig[0][1] && sameCheck) bValue = true;
+ else if (accessBank >= 0 && accessBank <= 3) {
+ byte[] bytes = new byte[1];
+ bytes[0] = (byte)(accessBank & 0xFF);
+ if (true) {
+ byte[] bytes1 = new byte[7];
+ System.arraycopy(rx000Setting.multibankReadConfig[0], 0, bytes1, 0, bytes1.length);
+ System.arraycopy(bytes, 0, bytes1, 1, bytes.length);
+ bValue = writeMAC(0x3270 + 7 * 0, bytes1, true);
+ } else {
+ bValue = writeMAC(0x3270 + 7 * 0 + 1, bytes, true);
+ }
+ if (bValue) rx000Setting.multibankReadConfig[0][1] = bytes[0];
+ if (DEBUG) appendToLog("0A multibankReadConfig[0] = " + byteArrayToString(rx000Setting.multibankReadConfig[0]));
+ }
+ if (DEBUG) appendToLog("0 multibankReadConfig[1] = " + byteArrayToString(rx000Setting.multibankReadConfig[1]));
+ if (accessBank2 == rx000Setting.multibankReadConfig[1][1] && sameCheck) { }
+ else if (bValue && accessBank2 >= 0 && accessBank2 <= 3) {
+ byte[] bytes = new byte[1];
+ bytes[0] = (byte)(accessBank2 & 0xFF);
+ if (true) {
+ byte[] bytes1 = new byte[7];
+ System.arraycopy(rx000Setting.multibankReadConfig[1], 0, bytes1, 0, bytes1.length);
+ System.arraycopy(bytes, 0, bytes1, 1, bytes.length);
+ bValue = writeMAC(0x3270 + 7 * 1, bytes1, true);
+ } else {
+ bValue = writeMAC(0x3270 + 7 * 1 + 1, bytes, true);
+ }
+ if (bValue) rx000Setting.multibankReadConfig[1][1] = bytes[0];
+ if (DEBUG) appendToLog("0A multibankReadConfig[1] = " + byteArrayToString(rx000Setting.multibankReadConfig[1]));
+ }
+ }
+ return bValue;
+ }
+
+ final int ACCOFFSET_INVALID = -1;
+ int getAccessOffset() {
+ boolean DEBUG = false; int iValue = -1;
+ if (accessBank >= 0 && accessBank <= 3 && rx000Setting.multibankReadConfig[0] == null) appendToLog("!!! CANNOT continue as multibankReadConfig[0] is null !!!");
+ else {
+ iValue = (rx000Setting.multibankReadConfig[0][2] & 0xFF) << 24;
+ iValue |= (rx000Setting.multibankReadConfig[0][3] & 0xFF) << 16;
+ iValue |= (rx000Setting.multibankReadConfig[0][4] & 0xFF) << 8;
+ iValue |= (rx000Setting.multibankReadConfig[0][5] & 0xFF);
+ }
+ return iValue;
+ }
+ public boolean setAccessOffset(int accessOffset) {
+ //appendToLog("10 setAccessOffset with accessOffset = " + accessOffset);
+ return setAccessOffset(accessOffset, 0); }
+ public boolean setAccessOffset(int accessOffset, int accessOffset2) {
+ boolean bValue = false, DEBUG = false;
+ if (DEBUG) appendToLog("0 setAccessOffset with accessOffset = " + accessOffset + ", accessOffset2 = " + accessOffset2);
+ if (accessOffset >= 0 && rx000Setting.multibankReadConfig[0] == null) appendToLog("!!! CANNOT continue as multibankReadConfig[0] is null !!!");
+ else if (accessOffset2 >= 0 && rx000Setting.multibankReadConfig[1] == null) appendToLog("!!! CANNOT continue as multibankReadConfig[1] is null !!!");
+ else {
+ if (DEBUG) appendToLog("0 multibankReadConfig[0] = " + byteArrayToString(rx000Setting.multibankReadConfig[0]));
+ if (accessOffset >= 0) {
+ byte[] bytes = new byte[4];
+ bytes[0] = (byte)((accessOffset >> 24) & 0xFF);
+ bytes[1] = (byte)((accessOffset >> 16) & 0xFF);
+ bytes[2] = (byte)((accessOffset >> 8) & 0xFF);
+ bytes[3] = (byte)(accessOffset & 0xFF);
+ byte[] bytesOld = new byte[4]; System.arraycopy(rx000Setting.multibankReadConfig[0], 2, bytesOld, 0, bytesOld.length);
+ if (compareArray(bytes, bytesOld, bytesOld.length) && sameCheck) bValue = true;
+ else {
+ if (true) {
+ byte[] bytes1 = new byte[7];
+ System.arraycopy(rx000Setting.multibankReadConfig[0], 0, bytes1, 0, bytes1.length);
+ System.arraycopy(bytes, 0, bytes1, 2, bytes.length);
+ bValue = writeMAC(0x3270 + 7 * 0, bytes1, true);
+ } else {
+ bValue = writeMAC(0x3270 + 7 * 0 + 2, bytes, true);
+ }
+ if (bValue) System.arraycopy(bytes, 0, rx000Setting.multibankReadConfig[0], 2, bytes.length);
+ if (DEBUG) appendToLog("0A multibankReadConfig[0] = " + byteArrayToString(rx000Setting.multibankReadConfig[0]));
+ }
+ }
+ if (DEBUG) appendToLog("0 multibankReadConfig[1] = " + byteArrayToString(rx000Setting.multibankReadConfig[1]));
+ if (bValue && accessOffset2 >= 0) {
+ byte[] bytes = new byte[4];
+ bytes[0] = (byte)((accessOffset2 >> 24) & 0xFF);
+ bytes[1] = (byte)((accessOffset2 >> 16) & 0xFF);
+ bytes[2] = (byte)((accessOffset2 >> 8) & 0xFF);
+ bytes[3] = (byte)(accessOffset2 & 0xFF);
+ byte[] bytesOld = new byte[4]; System.arraycopy(rx000Setting.multibankReadConfig[1], 2, bytesOld, 0, bytesOld.length);
+ if (compareArray(bytes, bytesOld, bytesOld.length) && sameCheck) { }
+ else {
+ if (true) {
+ byte[] bytes1 = new byte[7];
+ System.arraycopy(rx000Setting.multibankReadConfig[1], 0, bytes1, 0, bytes1.length);
+ System.arraycopy(bytes, 0, bytes1, 2, bytes.length);
+ bValue = writeMAC(0x3270 + 7 * 1, bytes1, true);
+ } else {
+ bValue = writeMAC(0x3270 + 7 * 1 + 2, bytes, true);
+ }
+ if (bValue) System.arraycopy(bytes, 0, rx000Setting.multibankReadConfig[1], 2, bytes.length);
+ if (DEBUG) appendToLog("0A multibankReadConfig[1] = " + byteArrayToString(rx000Setting.multibankReadConfig[1]));
+ }
+ }
+ }
+ return bValue;
+ }
+
+ final int ACCCOUNT_INVALID = -1; final int ACCCOUNT_MIN = 0; final int ACCCOUNT_MAX = 255;
+ int accessCount = ACCCOUNT_INVALID; int accessCount2 = ACCCOUNT_INVALID;
+ public boolean setAccessCount(int accessCount) {
+ setAccessEnable(((accessCount != 0) ? 1 : 0), 0);
+ return setAccessCount(accessCount, 0); }
+ public boolean setAccessCount(int accessCount, int accessCount2) {
+ boolean bValue = false, DEBUG = false;
+ if (DEBUG) appendToLog("0 setAccessCount with accessCount = " + accessCount + ", accessCount2 = " + accessCount2);
+ if (rx000Setting.multibankReadConfig[0] == null) appendToLog("!!! CANNOT continue as multibankReadConfig[0] is null !!!");
+ else if (rx000Setting.multibankReadConfig[1] == null) appendToLog("!!! CANNOT continue as multibankReadConfig[1] is null !!!");
+ else {
+ if (DEBUG) appendToLog("0 multibankReadConfig[0] = " + byteArrayToString(rx000Setting.multibankReadConfig[0]));
+ if (accessCount == rx000Setting.multibankReadConfig[0][6] && sameCheck) bValue = true;
+ else if (rx000Setting.multibankReadConfig[0][0] == 0) {
+ bValue = true;
+ } else {
+ byte[] bytes = new byte[1], bytes1 = null;
+ bytes[0] = (byte)(accessCount & 0xFF);
+ if (true) {
+ bytes1 = new byte[7];
+ System.arraycopy(rx000Setting.multibankReadConfig[0], 0, bytes1, 0, bytes1.length);
+ System.arraycopy(bytes, 0, bytes1, 6, bytes.length);
+ bValue = writeMAC(0x3270 + 7 * 0, bytes1, true);
+ } else {
+ bValue = writeMAC(0x3270 + 7 * 0 + 6, bytes, true);
+ }
+ if (bValue) rx000Setting.multibankReadConfig[0][6] = bytes[0];
+ if (DEBUG) appendToLog("0A multibankReadConfig[0] = " + byteArrayToString(rx000Setting.multibankReadConfig[0]));
+ }
+ if (DEBUG) appendToLog("0 multibankReadConfig[1] = " + byteArrayToString(rx000Setting.multibankReadConfig[1]));
+ if (accessCount2 == rx000Setting.multibankReadConfig[1][6] && sameCheck) { }
+ else if (rx000Setting.multibankReadConfig[1][0] == 0) {
+ bValue = true;
+ } else if (bValue) {
+ byte[] bytes = new byte[1], bytes1 = null;
+ bytes[0] = (byte)(accessCount2 & 0xFF);
+ if (true) {
+ bytes1 = new byte[7];
+ System.arraycopy(rx000Setting.multibankReadConfig[1], 0, bytes1, 0, bytes1.length);
+ System.arraycopy(bytes, 0, bytes1, 6, bytes.length);
+ bValue = writeMAC(0x3270 + 7 * 1, bytes1, true);
+ } else {
+ bValue = writeMAC(0x3270 + 7 * 1 + 6, bytes, true);
+ }
+ if (bValue) rx000Setting.multibankReadConfig[1][6] = bytes[0];
+ if (DEBUG) appendToLog("0A multibankReadConfig[1] = " + byteArrayToString(rx000Setting.multibankReadConfig[1]));
+ }
+ }
+ return bValue;
+ }
+
+ final int ACCLOCKACTION_INVALID = -1; final int ACCLOCKACTION_MIN = 0; final int ACCLOCKACTION_MAX = 0x3FF;
+ int accessLockAction = ACCLOCKACTION_INVALID;
+ final int ACCLOCKMASK_INVALID = -1; final int ACCLOCKMASK_MIN = 0; final int ACCLOCKMASK_MAX = 0x3FF;
+ int accessLockMask = ACCLOCKMASK_INVALID;
+
+ boolean getHST_TAGACC_LOCKCFG() {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 5, (byte) 0x0A, 0, 0, 0, 0};
+ return sendHostRegRequest(HostRegRequests.HST_TAGACC_LOCKCFG, false, msgBuffer);
+ }
+
+ byte[] lockMask, lockAction;
+ public boolean setAccessLockAction(int accessLockAction, int accessLockMask) {
+ appendToLog("accessLockAction = " + accessLockAction + ", accessLockMask = " + accessLockMask);
+ boolean bValue = false;
+ byte[] bytes = new byte[2];
+ bytes[0] = (byte) (accessLockMask / 256);
+ bytes[1] = (byte) (accessLockMask % 256);
+ bValue = writeMAC(0x38AE, bytes, true);
+ if (bValue) {
+ lockMask = bytes;
+ byte[] bytes1 = new byte[2];
+ bytes1[0] = (byte) (accessLockAction / 256);
+ bytes1[1] = (byte) (accessLockAction % 256);
+ bValue = writeMAC(0x38B0, bytes1, true);
+ if (bValue) lockAction = bytes;
+ }
+ return bValue;
+ }
+
+ byte[] accessPassword = null;
+ public boolean getRx000AccessPassword() {
+ return readMAC(0x38A6, 4);
+ }
+ public boolean setRx000AccessPassword(String password) {
+ boolean bValue = false, DEBUG = false;
+ if (DEBUG) appendToLog("0 setRx000AccessPassword with password = " + password);
+ if (accessPassword == null) appendToLog("!!! CANNOT continue as accessPassword is null !!!");
+ else {
+ if (DEBUG) appendToLog("0 accessPassword = " + byteArrayToString(accessPassword));
+ byte[] bytes = new byte[4];
+ if (password == null) password = "";
+ String hexString = "0123456789ABCDEF";
+ for (int j = 0; j < 16; j++) {
+ if (j + 1 <= password.length()) {
+ String subString = password.substring(j, j + 1).toUpperCase();
+ int k = 0;
+ for (k = 0; k < 16; k++) {
+ if (subString.matches(hexString.substring(k, k + 1))) {
+ break;
+ }
+ }
+ if (k == 16) return false;
+ if ((j / 2) * 2 == j) {
+ bytes[j / 2] |= (byte) (k << 4);
+ } else {
+ bytes[j / 2] |= (byte) (k);
+ }
+ }
+ }
+ byte[] bytesOld = new byte[4];
+ System.arraycopy(accessPassword, 0, bytesOld, 0, bytesOld.length);
+ if (DEBUG) appendToLog("0 bytes = " + byteArrayToString(bytes));
+ if (compareArray(bytes, bytesOld, bytesOld.length) && sameCheck) bValue = true;
+ else {
+ bValue = writeMAC(0x38A6, bytes, true);
+ if (bValue) accessPassword = bytes;
+ if (DEBUG)
+ appendToLog("0A accessPassword = " + byteArrayToString(accessPassword));
+ }
+ }
+ return bValue;
+ }
+
+ final int KILLPWD_INVALID = 0; final long KILLPWD_MIN = 0; final long KILLPWD_MAX = 0x0FFFFFFFF;
+ byte[] killPassword = null;
+ public boolean getRx000KillPassword() {
+ return readMAC(0x38AA, 4);
+ }
+ public boolean setRx000KillPassword(String password) {
+ boolean bValue = false, DEBUG = false;
+ if (DEBUG) appendToLog("0 setRx000KillPassword with password = " + password);
+ if (killPassword == null) appendToLog("!!! CANNOT continue as killPassword is null !!!");
+ else {
+ if (DEBUG) appendToLog("0 killPassword = " + byteArrayToString(killPassword));
+ byte[] bytes = utility.stringToByteArray(password);
+ byte[] bytesOld = new byte[4];
+ System.arraycopy(accessPassword, 0, bytesOld, 0, bytesOld.length);
+ if (DEBUG) appendToLog("0 bytes = " + byteArrayToString(bytes));
+ if (compareArray(bytes, bytesOld, bytesOld.length) && sameCheck) bValue = true;
+ else {
+ bValue = writeMAC(0x38AA, bytes, true);
+ if (bValue) killPassword = bytes;
+ if (DEBUG)
+ appendToLog("0A killPassword = " + byteArrayToString(killPassword));
+ }
+ }
+ return bValue;
+ }
+
+ final int ACCWRITEDATSEL_INVALID = -1; final int ACCWRITEDATSEL_MIN = 0; final int ACCWRITEDATSEL_MAX = 7;
+ int accessWriteDataSelect = ACCWRITEDATSEL_INVALID;
+
+ byte[] accWriteData0_63; int accWriteDataReady = 0;
+ public boolean setAccessWriteData(String dataInput) {
+ boolean bVAlue = false, DEBUG = false;
+ if (DEBUG) appendToLog("Start with dataInput = " + dataInput);
+ dataInput = dataInput.trim();
+ int writeBufLength = 16 * 2; //16
+ int wrieByteSize = 4; //8
+ int length = dataInput.length();
+ if (DEBUG) appendToLog("Check dataInput length = " + length + " with maximum length = " + wrieByteSize * writeBufLength);
+ if (length > wrieByteSize * writeBufLength) return false;
+ byte[] msgBuffer = new byte[length/2 + (length%2 != 0 ? 1 : 0)];
+ for (int i = 0; i < writeBufLength; i++) {
+ if (DEBUG) appendToLog("Before processing 4 nibbles, check length = " + length);
+ if (length > 0) {
+ length -= wrieByteSize;
+ String hexString = "0123456789ABCDEF";
+ for (int j = 0; j < wrieByteSize; j++) {
+ if (DEBUG) appendToLog("Check dataInput = " + dataInput + ", i = " + i + ", wrieByteSize = " + wrieByteSize + ", j = " + j);
+ if (i * wrieByteSize + j >= dataInput.length()) break;
+ String subString = dataInput.substring(i * wrieByteSize + j, i * wrieByteSize + j + 1).toUpperCase();
+ if (DEBUG) appendToLog("subString = " + subString);
+ int k = 0;
+ for (k = 0; k < 16; k++) {
+ if (DEBUG && false) appendToLog("k = " + k + ", with hexString = " + hexString);
+ if (subString.matches(hexString.substring(k, k + 1))) {
+ break;
+ }
+ }
+ if (k == 16) { appendToLog("!!! Cannot decode the data, with with i= " + i + ", j=" + j + ", subString = " + subString); return false; }
+ if ((j / 2) * 2 == j) {
+ msgBuffer[i * 2 + j / 2] |= (byte) (k << 4);
+ } else {
+ msgBuffer[i * 2 + j / 2] |= (byte) (k);
+ }
+ if (DEBUG) appendToLog("j = " + j + " with updated data : " + byteArrayToString(msgBuffer));
+ }
+ if (DEBUG) appendToLog("complete 4 bytes: " + byteArrayToString(msgBuffer));
+ } else break;
+ }
+
+ bVAlue = setMultibankWriteConfig(0,true, getAccessBank(), getAccessOffset(), (msgBuffer.length/2 + (msgBuffer.length%2 != 0 ? 1 : 0)), msgBuffer);
+ if (DEBUG) appendToLog("after setMultibankWriteConfig, bvalue = " + bVAlue);
+ if (bVAlue) {
+ //mRfidReaderChip.mRx000Setting.accWriteDataReady |= (0x01 << i);
+ if (DEBUG) appendToLog("accWriteReady=" + accWriteDataReady);
+ for (int k = 0; k < 4; k++) {
+ //accWriteData0_63[i * 4 + k] = msgBuffer[7 - k];
+ }
+ if (DEBUG) appendToLog("Data=" + byteArrayToString(accWriteData0_63));
+ }
+ return bVAlue;
+ }
+
+ //RFTC block paramters
+ final int PROFILE_INVALID = -1; final int PROFILE_MIN = 0; final int PROFILE_MAX = 5; //profile 4 and 5 are custom profiles.
+ int currentProfile = PROFILE_INVALID;
+ int iRfidModeSingleByte = -1;
+ public int getCurrentProfile() {
+ int iValue = -1; boolean DEBUG = false;
+ if (DEBUG) appendToLog("2 getCurrentProfile: antennaSelect = " + antennaSelect);
+ if (antennaPortConfig[antennaSelect] == null) appendToLog("CANNOT continue as antennaPortConfig[" + antennaSelect + "] is null !!!");
+ else {
+ if (DEBUG) appendToLog("2A getCurrentProfile: getAntennaPortConfig[" + antennaSelect + "] = " + byteArrayToString(antennaPortConfig[antennaSelect]));
+ if (antennaPortConfig[antennaSelect][14] != 0 && antennaPortConfig[antennaSelect][15] == 0) {
+ iRfidModeSingleByte = 1;
+ iValue = antennaPortConfig[antennaSelect][14];
+ } else {
+ iRfidModeSingleByte = 0;
+ iValue = (antennaPortConfig[antennaSelect][14] & 0xFF) << 8;
+ iValue += (antennaPortConfig[antennaSelect][15] & 0xFF);
+ }
+ if (DEBUG) appendToLog(String.format("2b getCurrentProfile: iValue = 0x%X", iValue));
+ }
+ return iValue;
+ }
+ public boolean setCurrentProfile(int currentProfile) {
+ byte[] data; boolean DEBUG = false, bValue = false;
+ if (DEBUG) appendToLog("2 setCurrentProfile: currentProfile = " + currentProfile + ", iRfidModeSingleByte = " + iRfidModeSingleByte);
+ if (antennaPortConfig[antennaSelect] == null) appendToLog("CANNOT continue as antennaPortConfig[" + antennaSelect + "] is null !!!");
+ else if (getCurrentProfile() == currentProfile && sameCheck) bValue = true;
+ else {
+ if (iRfidModeSingleByte < 0) getCurrentProfile();
+ else {
+ if (iRfidModeSingleByte != 0) {
+ data = new byte[1];
+ data[0] = (byte) currentProfile;
+ } else {
+ data = new byte[2];
+ data[0] = (byte) (currentProfile / 256);
+ data[1] = (byte) (currentProfile & 0xFF);
+ }
+ if (DEBUG)
+ appendToLog("2A setCurrentProfile: data = " + byteArrayToString(data));
+ bValue = writeMAC(0x3030 + this.antennaSelect * 16 + 14, data, true);
+ if (DEBUG)
+ appendToLog("2b setCurrentProfile: after writeMAC, bValue = " + bValue);
+ if (bValue && antennaPortConfig[antennaSelect] != null)
+ System.arraycopy(data, 0, antennaPortConfig[antennaSelect], 14, data.length);
+ }
+ }
+ return bValue;
+ }
+
+ final int COUNTRYCODE_INVALID = -1;
+ final int FREQCHANSEL_INVALID = -1;
+
+ final int FREQCHANCONFIG_INVALID = -1; final int FREQCHANCONFIG_MIN = 0; final int FREQCHANCONFIG_MAX = 1;
+ int freqChannelConfig = FREQCHANCONFIG_INVALID;
+
+ final int FREQPLLMULTIPLIER_INVALID = -1;
+
+ final int FREQPLLDAC_INVALID = -1;
+ }
+ class AntennaSelectedData {
+ AntennaSelectedData(boolean set_default_setting, int default_setting_type) {
+ if (default_setting_type < 0) default_setting_type = 0;
+ if (default_setting_type > 5) default_setting_type = 5;
+ mDefault = new AntennaSelectedData.AntennaSelectedData_default(default_setting_type);
+ if (false && set_default_setting) {
+ antennaEnable = mDefault.antennaEnable;
+ antennaInventoryMode = mDefault.antennaInventoryMode;
+ antennaLocalAlgo = mDefault.antennaLocalAlgo;
+ antennaLocalStartQ = mDefault.antennaLocalStartQ;
+ antennaProfileMode = mDefault.antennaProfileMode;
+ antennaLocalProfile = mDefault.antennaLocalProfile;
+ antennaFrequencyMode = mDefault.antennaFrequencyMode;
+ antennaLocalFrequency = mDefault.antennaLocalFrequency;
+ antennaStatus = mDefault.antennaStatus;
+ antennaDefine = mDefault.antennaDefine;
+ antennaDwell = mDefault.antennaDwell;
+ antennaPower = mDefault.antennaPower; appendToLog("antennaPower is set to default " + antennaPower);
+ antennaInvCount = mDefault.antennaInvCount;
+ }
+ }
+
+ class AntennaSelectedData_default {
+ AntennaSelectedData_default(int set_default_setting) {
+ antennaEnable = mDefaultArray.antennaEnable[set_default_setting];
+ antennaInventoryMode = mDefaultArray.antennaInventoryMode[set_default_setting];
+ antennaLocalAlgo = mDefaultArray.antennaLocalAlgo[set_default_setting];
+ antennaLocalStartQ = mDefaultArray.antennaLocalStartQ[set_default_setting];
+ antennaProfileMode = mDefaultArray.antennaProfileMode[set_default_setting];
+ antennaLocalProfile = mDefaultArray.antennaLocalProfile[set_default_setting];
+ antennaFrequencyMode = mDefaultArray.antennaFrequencyMode[set_default_setting];
+ antennaLocalFrequency = mDefaultArray.antennaLocalFrequency[set_default_setting];
+ antennaStatus = mDefaultArray.antennaStatus[set_default_setting];
+ antennaDefine = mDefaultArray.antennaDefine[set_default_setting];
+ antennaDwell = mDefaultArray.antennaDwell[set_default_setting];
+ antennaPower = mDefaultArray.antennaPower[set_default_setting];
+ antennaInvCount = mDefaultArray.antennaInvCount[set_default_setting];
+ }
+
+ int antennaEnable;
+ int antennaInventoryMode;
+ int antennaLocalAlgo;
+ int antennaLocalStartQ;
+ int antennaProfileMode;
+ int antennaLocalProfile;
+ int antennaFrequencyMode;
+ int antennaLocalFrequency;
+ int antennaStatus;
+ int antennaDefine;
+ long antennaDwell;
+ long antennaPower;
+ long antennaInvCount;
+ }
+ AntennaSelectedData.AntennaSelectedData_default mDefault;
+
+ private class AntennaSelectedData_defaultArray { //0 for invalid default, 1 for 0, 2 for 1 to 3, 3 for 4 to 7, 4 for 8 to 11, 5 for 12 to 15
+ int[] antennaEnable = { -1, 1, 0, 0, 0, 0 };
+ int[] antennaInventoryMode = { -1, 0, 0, 0, 0, 0 };
+ int[] antennaLocalAlgo = { -1, 0, 0, 0, 0, 0 };
+ int[] antennaLocalStartQ = { -1, 0, 0, 0, 0, 0 };
+ int[] antennaProfileMode = { -1, 0, 0, 0, 0, 0 };
+ int[] antennaLocalProfile = { -1, 0, 0, 0, 0, 0 };
+ int[] antennaFrequencyMode = { -1, 0, 0, 0, 0, 0 };
+ int[] antennaLocalFrequency = { -1, 0, 0, 0, 0, 0 };
+ int[] antennaStatus = { -1, 0, 0, 0, 0, 0 };
+ int[] antennaDefine = { -1, 0, 0, 1, 2, 3 };
+ long[] antennaDwell = { -1, 2000, 2000, 2000, 2000, 2000 };
+ long[] antennaPower = { -1, 300, 0, 0, 0, 0 };
+ long[] antennaInvCount = { -1, 8192, 8192, 8192, 8192, 8192 };
+ }
+ AntennaSelectedData.AntennaSelectedData_defaultArray mDefaultArray = new AntennaSelectedData.AntennaSelectedData_defaultArray();
+
+ final int ANTENABLE_INVALID = -1; final int ANTENABLE_MIN = 0; final int ANTENABLE_MAX = 1;
+ int antennaEnable = ANTENABLE_INVALID;
+
+ final int ANTINVMODE_INVALID = 0; final int ANTINVMODE_MIN = 0; final int ANTINVMODE_MAX = 1;
+ int antennaInventoryMode = ANTINVMODE_INVALID;
+ int getAntennaInventoryMode() {
+ if (antennaInventoryMode < ANTPROFILEMODE_MIN || antennaInventoryMode > ANTPROFILEMODE_MAX)
+ getHST_ANT_DESC_CFG();
+ return antennaInventoryMode;
+ }
+ boolean setAntennaInventoryMode(int antennaInventoryMode) {
+ return setAntennaEnable(antennaEnable, antennaInventoryMode, antennaLocalAlgo, antennaLocalStartQ, antennaProfileMode,
+ antennaLocalProfile, antennaFrequencyMode, antennaLocalFrequency);
+ }
+
+ final int ANTLOCALALGO_INVALID = 0; final int ANTLOCALALGO_MIN = 0; final int ANTLOCALALGO_MAX = 5;
+ int antennaLocalAlgo = ANTLOCALALGO_INVALID;
+ int getAntennaLocalAlgo() {
+ if (antennaLocalAlgo < ANTLOCALALGO_MIN || antennaLocalAlgo > ANTLOCALALGO_MAX)
+ getHST_ANT_DESC_CFG();
+ return antennaLocalAlgo;
+ }
+ boolean setAntennaLocalAlgo(int antennaLocalAlgo) {
+ return setAntennaEnable(antennaEnable, antennaInventoryMode, antennaLocalAlgo, antennaLocalStartQ,
+ antennaProfileMode, antennaLocalProfile, antennaFrequencyMode, antennaLocalFrequency);
+ }
+
+ final int ANTLOCALSTARTQ_INVALID = 0; final int ANTLOCALSTARTQ_MIN = 0; final int ANTLOCALSTARTQ_MAX = 15;
+ int antennaLocalStartQ = ANTLOCALSTARTQ_INVALID;
+ int getAntennaLocalStartQ() {
+ if (antennaLocalStartQ < ANTLOCALSTARTQ_MIN || antennaLocalStartQ > ANTLOCALSTARTQ_MAX)
+ getHST_ANT_DESC_CFG();
+ return antennaLocalStartQ;
+ }
+ boolean setAntennaLocalStartQ(int antennaLocalStartQ) {
+ return setAntennaEnable(antennaEnable, antennaInventoryMode, antennaLocalAlgo, antennaLocalStartQ,
+ antennaProfileMode, antennaLocalProfile, antennaFrequencyMode, antennaLocalFrequency);
+ }
+
+ final int ANTPROFILEMODE_INVALID = 0; final int ANTPROFILEMODE_MIN = 0; final int ANTPROFILEMODE_MAX = 1;
+ int antennaProfileMode = ANTPROFILEMODE_INVALID;
+ int getAntennaProfileMode() {
+ if (antennaProfileMode < ANTPROFILEMODE_MIN || antennaProfileMode > ANTPROFILEMODE_MAX)
+ getHST_ANT_DESC_CFG();
+ return antennaProfileMode;
+ }
+ boolean setAntennaProfileMode(int antennaProfileMode) {
+ return setAntennaEnable(antennaEnable, antennaInventoryMode, antennaLocalAlgo, antennaLocalStartQ,
+ antennaProfileMode, antennaLocalProfile, antennaFrequencyMode, antennaLocalFrequency);
+ }
+
+ final int ANTLOCALPROFILE_INVALID = 0; final int ANTLOCALPROFILE_MIN = 0; final int ANTLOCALPROFILE_MAX = 5;
+ int antennaLocalProfile = ANTLOCALPROFILE_INVALID;
+ int getAntennaLocalProfile() {
+ if (antennaLocalProfile < ANTLOCALPROFILE_MIN || antennaLocalProfile > ANTLOCALPROFILE_MIN)
+ getHST_ANT_DESC_CFG();
+ return antennaLocalProfile;
+ }
+ boolean setAntennaLocalProfile(int antennaLocalProfile) {
+ return setAntennaEnable(antennaEnable, antennaInventoryMode, antennaLocalAlgo, antennaLocalStartQ,
+ antennaProfileMode, antennaLocalProfile, antennaFrequencyMode, antennaLocalFrequency);
+ }
+
+ final int ANTFREQMODE_INVALID = 0; final int ANTFREQMODE_MIN = 0; final int ANTFREQMODE_MAX = 1;
+ int antennaFrequencyMode = ANTFREQMODE_INVALID;
+ int getAntennaFrequencyMode() {
+ if (antennaFrequencyMode < ANTFREQMODE_MIN || antennaFrequencyMode > ANTFREQMODE_MAX)
+ getHST_ANT_DESC_CFG();
+ return antennaFrequencyMode;
+ }
+ boolean setAntennaFrequencyMode(int antennaFrequencyMode) {
+ return setAntennaEnable(antennaEnable, antennaInventoryMode, antennaLocalAlgo, antennaLocalStartQ,
+ antennaProfileMode, antennaLocalProfile, antennaFrequencyMode, antennaLocalFrequency);
+ }
+
+ final int ANTLOCALFREQ_INVALID = 0; final int ANTLOCALFREQ_MIN = 0; final int ANTLOCALFREQ_MAX = 49;
+ int antennaLocalFrequency = ANTLOCALFREQ_INVALID;
+ int getAntennaLocalFrequency() {
+ if (antennaLocalFrequency < ANTLOCALFREQ_MIN || antennaLocalFrequency > ANTLOCALFREQ_MAX)
+ getHST_ANT_DESC_CFG();
+ return antennaLocalFrequency;
+ }
+ boolean setAntennaLocalFrequency(int antennaLocalFrequency) {
+ return setAntennaEnable(antennaEnable, antennaInventoryMode, antennaLocalAlgo, antennaLocalStartQ,
+ antennaProfileMode, antennaLocalProfile, antennaFrequencyMode, antennaLocalFrequency);
+ }
+
+ private boolean getHST_ANT_DESC_CFG() {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 2, 7, 0, 0, 0, 0};
+ return sendHostRegRequest(HostRegRequests.HST_ANT_DESC_CFG, false, msgBuffer);
+ }
+ boolean setAntennaEnable(int antennaEnable, int antennaInventoryMode, int antennaLocalAlgo, int antennaLocalStartQ,
+ int antennaProfileMode, int antennaLocalProfile,
+ int antennaFrequencyMode, int antennaLocalFrequency) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 2, 7, 0, 0, 0, 0};
+ if (antennaEnable < ANTENABLE_MIN || antennaEnable > ANTENABLE_MAX)
+ antennaEnable = mDefault.antennaEnable;
+ if (antennaInventoryMode < ANTINVMODE_MIN || antennaInventoryMode > ANTINVMODE_MAX)
+ antennaInventoryMode = mDefault.antennaInventoryMode;
+ if (antennaLocalAlgo < ANTLOCALALGO_MIN || antennaLocalAlgo > ANTLOCALALGO_MAX)
+ antennaLocalAlgo = mDefault.antennaLocalAlgo;
+ if (antennaLocalStartQ < ANTLOCALSTARTQ_MIN || antennaLocalStartQ > ANTLOCALSTARTQ_MAX)
+ antennaLocalStartQ = mDefault.antennaLocalStartQ;
+ if (antennaProfileMode < ANTPROFILEMODE_MIN || antennaProfileMode > ANTPROFILEMODE_MAX)
+ antennaProfileMode = mDefault.antennaProfileMode;
+ if (antennaLocalProfile < ANTLOCALPROFILE_MIN || antennaLocalProfile > ANTLOCALPROFILE_MAX)
+ antennaLocalProfile = mDefault.antennaLocalProfile;
+ if (antennaFrequencyMode < ANTFREQMODE_MIN || antennaFrequencyMode > ANTFREQMODE_MAX)
+ antennaFrequencyMode = mDefault.antennaFrequencyMode;
+ if (antennaLocalFrequency < ANTLOCALFREQ_MIN || antennaLocalFrequency > ANTLOCALFREQ_MAX)
+ antennaLocalFrequency = mDefault.antennaLocalFrequency;
+ if (this.antennaEnable == antennaEnable && this.antennaInventoryMode == antennaInventoryMode && this.antennaLocalAlgo == antennaLocalAlgo
+ && this.antennaLocalStartQ == antennaLocalStartQ && this.antennaProfileMode == antennaProfileMode && this.antennaLocalProfile == antennaLocalProfile
+ && this.antennaFrequencyMode == antennaFrequencyMode && this.antennaLocalFrequency == antennaLocalFrequency
+ && sameCheck)
+ return true;
+ msgBuffer[4] |= antennaEnable;
+ msgBuffer[4] |= (antennaInventoryMode << 1);
+ msgBuffer[4] |= (antennaLocalAlgo << 2);
+ msgBuffer[4] |= (antennaLocalStartQ << 4);
+ msgBuffer[5] |= antennaProfileMode;
+ msgBuffer[5] |= (antennaLocalProfile << 1);
+ msgBuffer[5] |= (antennaFrequencyMode << 5);
+ msgBuffer[5] |= ((antennaLocalFrequency & 0x03) << 6);
+ msgBuffer[6] |= (antennaLocalFrequency >> 2);
+ this.antennaEnable = antennaEnable;
+ this.antennaInventoryMode = antennaInventoryMode;
+ this.antennaLocalAlgo = antennaLocalAlgo;
+ this.antennaLocalStartQ = antennaLocalStartQ;
+ this.antennaProfileMode = antennaProfileMode;
+ this.antennaLocalProfile = antennaLocalProfile;
+ this.antennaFrequencyMode = antennaFrequencyMode;
+ this.antennaLocalFrequency = antennaLocalFrequency;
+ return sendHostRegRequest(HostRegRequests.HST_ANT_DESC_CFG, true, msgBuffer);
+ }
+
+ final int ANTSTATUS_INVALID = -1; final int ANTSTATUS_MIN = 0; final int ANTSTATUS_MAX = 0xFFFFF;
+ int antennaStatus = ANTSTATUS_INVALID;
+
+ final int ANTDEFINE_INVALID = -1; final int ANTDEFINE_MIN = 0; final int ANTDEFINE_MAX = 3;
+ int antennaDefine = ANTDEFINE_INVALID;
+
+ final long ANTDWELL_INVALID = -1;
+ long antennaDwell = ANTDWELL_INVALID;
+
+ final long ANTPOWER_INVALID = -1; final long ANTPOWER_MIN = 0; final long ANTPOWER_MAX = 330; //Maximum 330\
+ long antennaPower = ANTPOWER_INVALID; //default value = 300
+
+ final long ANTINVCOUNT_INVALID = -1; final long ANTINVCOUNT_MIN = 0; final long ANTINVCOUNT_MAX = 0xFFFFFFFFL;
+ long antennaInvCount = ANTINVCOUNT_INVALID;
+ long getAntennaInvCount() {
+ if (antennaInvCount < ANTINVCOUNT_MIN || antennaInvCount > ANTINVCOUNT_MAX) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 7, 7, 0, 0, 0, 0};
+ sendHostRegRequest(HostRegRequests.HST_ANT_DESC_INV_CNT, false, msgBuffer);
+ }
+ return antennaInvCount;
+ }
+ }
+ class InvSelectData {
+ InvSelectData(boolean set_default_setting) {
+ if (set_default_setting) {
+ selectEnable = mDefault.selectEnable;
+ selectTarget = mDefault.selectTarget;
+ selectAction = mDefault.selectAction;
+ selectDelay = mDefault.selectDelay;
+ selectMaskBank = mDefault.selectMaskBank;
+ selectMaskOffset = mDefault.selectMaskOffset;
+ selectMaskLength = mDefault.selectMaskLength;
+ }
+ }
+
+ private class InvSelectData_default {
+ int selectEnable = 0;
+ int selectTarget = 0;
+ int selectAction = 0;
+ int selectDelay = 0;
+ int selectMaskBank = 0;
+ int selectMaskOffset = 0;
+ int selectMaskLength = 0;
+ }
+ InvSelectData.InvSelectData_default mDefault = new InvSelectData.InvSelectData_default();
+
+ final int INVSELENABLE_INVALID = 0; final int INVSELENABLE_MIN = 0; final int INVSELENABLE_MAX = 1;
+ int selectEnable = INVSELENABLE_INVALID;
+
+ final int INVSELTARGET_INVALID = -1; final int INVSELTARGET_MIN = 0; final int INVSELTARGET_MAX = 7;
+ int selectTarget = INVSELTARGET_INVALID;
+
+ final int INVSELACTION_INVALID = -1; final int INVSELACTION_MIN = 0; final int INVSELACTION_MAX = 7;
+ int selectAction = INVSELACTION_INVALID;
+
+ final int INVSELDELAY_INVALID = -1; final int INVSELDELAY_MIN = 0; final int INVSELDELAY_MAX = 255;
+ int selectDelay = INVSELDELAY_INVALID;
+
+ final int INVSELMBANK_INVALID = -1; final int INVSELMBANK_MIN = 0; final int INVSELMBANK_MAX = 3;
+ int selectMaskBank = INVSELMBANK_INVALID;
+
+ final int INVSELMOFFSET_INVALID = -1; final int INVSELMOFFSET_MIN = 0; final int INVSELMOFFSET_MAX = 0xFFFF;
+ int selectMaskOffset = INVSELMOFFSET_INVALID;
+
+ final int INVSELMLENGTH_INVALID = -1; final int INVSELMLENGTH_MIN = 0; final int INVSELMLENGTH_MAX = 255;
+ int selectMaskLength = INVSELMLENGTH_INVALID;
+ }
+ class AlgoSelectedData {
+ AlgoSelectedData(boolean set_default_setting, int default_setting_type) {
+ if (default_setting_type < 0) default_setting_type = 0;
+ if (default_setting_type > 4) default_setting_type = 4;
+ mDefault = new AlgoSelectedData.AlgoSelectedData_default(default_setting_type);
+ if (set_default_setting) {
+ algoStartQ = mDefault.algoStartQ;
+ algoMaxQ = mDefault.algoMaxQ;
+ algoMinQ = mDefault.algoMinQ;
+ algoMaxRep = mDefault.algoMaxRep;
+ algoHighThres = mDefault.algoHighThres;
+ algoLowThres = mDefault.algoLowThres;
+ algoRetry = mDefault.algoRetry;
+ algoAbFlip = mDefault.algoAbFlip;
+ algoRunTilZero = mDefault.algoRunTilZero;
+ }
+ }
+
+ class AlgoSelectedData_default {
+ AlgoSelectedData_default(int set_default_setting) {
+ algoStartQ = mDefaultArray.algoStartQ[set_default_setting];
+ algoMaxQ = mDefaultArray.algoMaxQ[set_default_setting];
+ algoMinQ = mDefaultArray.algoMinQ[set_default_setting];
+ algoMaxRep = mDefaultArray.algoMaxRep[set_default_setting];
+ algoHighThres = mDefaultArray.algoHighThres[set_default_setting];
+ algoLowThres = mDefaultArray.algoLowThres[set_default_setting];
+ algoRetry = mDefaultArray.algoRetry[set_default_setting];
+ algoAbFlip = mDefaultArray.algoAbFlip[set_default_setting];
+ algoRunTilZero = mDefaultArray.algoRunTilZero[set_default_setting];
+ }
+
+ int algoStartQ = -1;
+ int algoMaxQ = -1;
+ int algoMinQ = -1;
+ int algoMaxRep = -1;
+ int algoHighThres = -1;
+ int algoLowThres = -1;
+ int algoRetry = -1;
+ int algoAbFlip = -1;
+ int algoRunTilZero = -1;
+ }
+ AlgoSelectedData.AlgoSelectedData_default mDefault;
+
+ class AlgoSelectedData_defaultArray { //0 for invalid default, 1 for 0, 2 for 1, 3 for 2, 4 for 3
+ int[] algoStartQ = { -1, 0, 0, 0, 4 };
+ int[] algoMaxQ = { -1, 0, 0, 0, 15 };
+ int[] algoMinQ = { -1, 0, 0, 0, 0 };
+ int[] algoMaxRep = { -1, 0, 0, 0, 4 };
+ int[] algoHighThres = { -1, 0, 5, 5, 5 };
+ int[] algoLowThres = { -1, 0, 3, 3, 3 };
+ int[] algoRetry = { -1, 0, 0, 0, 0 };
+ int[] algoAbFlip = { -1, 0, 1, 1, 1 };
+ int[] algoRunTilZero = { -1, 0, 0, 0, 0 };
+ }
+ AlgoSelectedData.AlgoSelectedData_defaultArray mDefaultArray = new AlgoSelectedData.AlgoSelectedData_defaultArray();
+
+ final int ALGOSTARTQ_INVALID = -1; final int ALGOSTARTQ_MIN = 0; final int ALGOSTARTQ_MAX = 15;
+ int algoStartQ = ALGOSTARTQ_INVALID;
+ int getAlgoStartQ(boolean getInvalid) {
+ if (getInvalid && (algoStartQ < ALGOSTARTQ_MIN || algoStartQ > ALGOSTARTQ_MAX)) getHST_INV_ALG_PARM_0();
+ return algoStartQ;
+ }
+ boolean setAlgoStartQ(int algoStartQ) {
+ appendToLog("1A setAlgoStartQ with algoStartQ = " + algoStartQ);
+ return setAlgoStartQ(algoStartQ, algoMaxQ, algoMinQ, algoMaxRep, algoHighThres, algoLowThres);
+ }
+
+ final int ALGOMAXQ_INVALID = -1; final int ALGOMAXQ_MIN = 0; final int ALGOMAXQ_MAX = 15;
+ int algoMaxQ = ALGOMAXQ_INVALID;
+ int getAlgoMaxQ() {
+ if (algoMaxQ < ALGOMAXQ_MIN || algoMaxQ > ALGOMAXQ_MAX) getHST_INV_ALG_PARM_0();
+ return algoMaxQ;
+ }
+ boolean setAlgoMaxQ(int algoMaxQ) {
+ appendToLog("1b setAlgoStartQ");
+ return setAlgoStartQ(algoStartQ, algoMaxQ, algoMinQ, algoMaxRep, algoHighThres, algoLowThres);
+ }
+
+ final int ALGOMINQ_INVALID = -1; final int ALGOMINQ_MIN = 0; final int ALGOMINQ_MAX = 15;
+ int algoMinQ = ALGOMINQ_INVALID;
+ int getAlgoMinQ() {
+ if (algoMinQ < ALGOMINQ_MIN || algoMinQ > ALGOMINQ_MAX) getHST_INV_ALG_PARM_0();
+ return algoMinQ;
+ }
+
+ final int ALGOMAXREP_INVALID = -1; final int ALGOMAXREP_MIN = 0; final int ALGOMAXREP_MAX = 255;
+ int algoMaxRep = ALGOMAXREP_INVALID;
+
+ final int ALGOHIGHTHRES_INVALID = -1; final int ALGOHIGHTHRES_MIN = 0; final int ALGOHIGHTHRES_MAX = 15;
+ int algoHighThres = ALGOHIGHTHRES_INVALID;
+
+ final int ALGOLOWTHRES_INVALID = -1; final int ALGOLOWTHRES_MIN = 0; final int ALGOLOWTHRES_MAX = 15;
+ int algoLowThres = ALGOLOWTHRES_INVALID;
+
+ private boolean getHST_INV_ALG_PARM_0() {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 3, 9, 0, 0, 0, 0};
+ return sendHostRegRequest(HostRegRequests.HST_INV_ALG_PARM_0, false, msgBuffer);
+ }
+ boolean setAlgoStartQ(int startQ, int algoMaxQ, int algoMinQ, int algoMaxRep, int algoHighThres, int algoLowThres) {
+ appendToLog("0 setAlgoStartQ with startQ = " + startQ);
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 3, 9, 0, 0, 0, 0};
+ if (startQ < ALGOSTARTQ_MIN || startQ > ALGOSTARTQ_MAX) startQ = mDefault.algoStartQ;
+ if (algoMaxQ < ALGOMAXQ_MIN || algoMaxQ > ALGOMAXQ_MAX) algoMaxQ = mDefault.algoMaxQ;
+ if (algoMinQ < ALGOMINQ_MIN || algoMinQ > ALGOMINQ_MAX) algoMinQ = mDefault.algoMinQ;
+ if (algoMaxRep < ALGOMAXREP_MIN || algoMaxRep > ALGOMAXREP_MAX)
+ algoMaxRep = mDefault.algoMaxRep;
+ if (algoHighThres < ALGOHIGHTHRES_MIN || algoHighThres > ALGOHIGHTHRES_MAX)
+ algoHighThres = mDefault.algoHighThres;
+ if (algoLowThres < ALGOLOWTHRES_MIN || algoLowThres > ALGOLOWTHRES_MAX)
+ algoLowThres = mDefault.algoLowThres;
+ if (false && this.algoStartQ == startQ && this.algoMaxQ == algoMaxQ && this.algoMinQ == algoMinQ
+ && this.algoMaxRep == algoMaxRep && this.algoHighThres == algoHighThres && this.algoLowThres == algoLowThres
+ && sameCheck)
+ return true;
+ msgBuffer[4] |= (byte) (startQ & 0x0F);
+ msgBuffer[4] |= (byte) ((algoMaxQ & 0x0F) << 4);
+ msgBuffer[5] |= (byte) (algoMinQ & 0x0F);
+ msgBuffer[5] |= (byte) ((algoMaxRep & 0xF) << 4);
+ msgBuffer[6] |= (byte) ((algoMaxRep & 0xF0) >> 4);
+ msgBuffer[6] |= (byte) ((algoHighThres & 0x0F) << 4);
+ msgBuffer[7] |= (byte) (algoLowThres & 0x0F);
+ this.algoStartQ = startQ;
+ this.algoMaxQ = algoMaxQ;
+ this.algoMinQ = algoMinQ;
+ this.algoMaxRep = algoMaxRep;
+ this.algoHighThres = algoHighThres;
+ this.algoLowThres = algoLowThres;
+ return sendHostRegRequest(HostRegRequests.HST_INV_ALG_PARM_0, true, msgBuffer);
+ }
+
+ final int ALGORETRY_INVALID = -1; final int ALGORETRY_MIN = 0; final int ALGORETRY_MAX = 255;
+ int algoRetry = ALGORETRY_INVALID;
+
+ final int ALGOABFLIP_INVALID = -1; final int ALGOABFLIP_MIN = 0; final int ALGOABFLIP_MAX = 1;
+ int algoAbFlip = ALGOABFLIP_INVALID;
+ int getAlgoAbFlip() {
+ if (algoAbFlip < ALGOABFLIP_MIN || algoAbFlip > ALGOABFLIP_MAX) getHST_INV_ALG_PARM_2();
+ return algoAbFlip;
+ }
+
+ final int ALGORUNTILZERO_INVALID = -1; final int ALGORUNTILZERO_MIN = 0; final int ALGORUNTILZERO_MAX = 1;
+ int algoRunTilZero = ALGORUNTILZERO_INVALID;
+ int getAlgoRunTilZero() {
+ if (algoRunTilZero < ALGORUNTILZERO_MIN || algoRunTilZero > ALGORUNTILZERO_MAX) getHST_INV_ALG_PARM_2();
+ return algoRunTilZero;
+ }
+ boolean setAlgoRunTilZero(int algoRunTilZero) {
+ return setAlgoAbFlip(algoAbFlip, algoRunTilZero);
+ }
+
+ private boolean getHST_INV_ALG_PARM_2() {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 5, 9, 0, 0, 0, 0};
+ return sendHostRegRequest(HostRegRequests.HST_INV_ALG_PARM_2, false, msgBuffer);
+ }
+ boolean setAlgoAbFlip(int algoAbFlip, int algoRunTilZero) {
+ if (algoAbFlip < ALGOABFLIP_MIN || algoAbFlip > ALGOABFLIP_MAX)
+ algoAbFlip = mDefault.algoAbFlip;
+ if (algoRunTilZero < ALGORUNTILZERO_MIN || algoRunTilZero > ALGORUNTILZERO_MAX)
+ algoRunTilZero = mDefault.algoRunTilZero;
+ if (false) appendToLog("this.algoAbFlip = " + this.algoAbFlip + ", algoAbFlip = " + algoAbFlip + ", this.algoRunTilZero = " + this.algoRunTilZero + ", algoRunTilZero = " + algoRunTilZero);
+ if (false && this.algoAbFlip == algoAbFlip && this.algoRunTilZero == algoRunTilZero && sameCheck) return true;
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 5, 9, 0, 0, 0, 0};
+ if (algoAbFlip != 0) {
+ msgBuffer[4] |= 0x01;
+ }
+ if (algoRunTilZero != 0) {
+ msgBuffer[4] |= 0x02;
+ }
+ this.algoAbFlip = algoAbFlip;
+ this.algoRunTilZero = algoRunTilZero;
+ return sendHostRegRequest(HostRegRequests.HST_INV_ALG_PARM_2, true, msgBuffer);
+ }
+ }
+ public class Rx000EngSetting {
+ int narrowRSSI = -1, wideRSSI = -1;
+ public void resetRSSI() {
+ narrowRSSI = -1; wideRSSI = -1;
+ }
+ }
+
+ //public boolean bFirmware_reset_before = false;
+ final int RFID_READING_BUFFERSIZE = 600; //1024;
+
+ byte[] mRfidToReading = new byte[RFID_READING_BUFFERSIZE];
+ int mRfidToReadingOffset = 0;
+ ArrayList mRx000ToWrite = new ArrayList<>();
+
+ public Rx000Setting rx000Setting = new Rx000Setting(true);
+ public Rx000EngSetting rx000EngSetting = new Rx000EngSetting();
+
+ public ArrayList mRx000ToRead = new ArrayList<>();
+ boolean commandOperating;
+
+ public double decodeNarrowBandRSSI(byte byteRSSI) {
+ byte mantissa = byteRSSI;
+ mantissa &= 0x07;
+ byte exponent = byteRSSI;
+ exponent >>= 3;
+ double dValue = 20 * log10(pow(2, exponent) * (1 + (mantissa / pow(2, 3))));
+ if (false) appendToLog("byteRSSI = " + String.format("%X", byteRSSI) + ", mantissa = " + mantissa + ", exponent = " + exponent + "dValue = " + dValue);
+ return dValue;
+ }
+
+ public boolean bRx000ToReading = false;
+ int getBytes2EpcLength(byte[] bytes) {
+ int iValue = ((bytes[0] & 0xFF) >> 3) * 2;
+ if (false) appendToLog("bytes = " + byteArrayToString(bytes) + ", iValue = " + iValue);
+ return iValue;
+ }
+ void uplinkHandler() {
+ boolean DEBUG = false;
+ if (bRx000ToReading) return;
+ bRx000ToReading = true;
+ int startIndex = 0, startIndexOld = 0, startIndexNew = 0;
+ boolean packageFound = false;
+ int packageType = 0;
+ long lTime = System.currentTimeMillis();
+ if (csReaderConnector.rfidConnector.mRfidToRead.size() != 0) { if (DEBUGTHREAD) appendToLog("mRx000UplinkHandler(): START with mRfidToRead size = " + csReaderConnector.rfidConnector.mRfidToRead.size() + ", mRx000ToRead size = " + mRx000ToRead.size()); }
+ else if (DEBUGTHREAD) appendToLog("START AAA with mRx000ToRead size = " + mRx000ToRead.size());
+ if (false && mRx000ToRead.size() != 0) appendToLog("START AAA with mRx000ToRead size = " + mRx000ToRead.size());
+ boolean bFirst = true;
+ while (csReaderConnector.rfidConnector.mRfidToRead.size() != 0) {
+ if (DEBUG) appendToLog("Looping with mRfidToRead.size = " + csReaderConnector.rfidConnector.mRfidToRead.size() + " with bleConnected = " + csReaderConnector.isConnected());
+ if (csReaderConnector.isConnected() == false) {
+ csReaderConnector.rfidConnector.mRfidToRead.clear();
+ appendToLog("BLE DISCONNECTED !!! mRfidToRead.size() = " + csReaderConnector.rfidConnector.mRfidToRead.size());
+ } else if (System.currentTimeMillis() - lTime > (intervalRx000UplinkHandler/2)) {
+ writeDebug2File("D" + String.valueOf(intervalRx000UplinkHandler) + ", " + System.currentTimeMillis() + ", Timeout");
+ appendToLogView("TIMEOUT !!! mRfidToRead.size() = " + csReaderConnector.rfidConnector.mRfidToRead.size());
+ break;
+ } else {
+ if (DEBUG) appendToLog("Check bFirst = " + bFirst);
+ if (bFirst) { bFirst = false; writeDebug2File("D" + String.valueOf(intervalRx000UplinkHandler) + ", " + System.currentTimeMillis()); }
+ byte[] dataIn = csReaderConnector.rfidConnector.mRfidToRead.get(0).dataValues;
+ long tagMilliSeconds = csReaderConnector.rfidConnector.mRfidToRead.get(0).milliseconds;
+ boolean invalidSequence = csReaderConnector.rfidConnector.mRfidToRead.get(0).invalidSequence;
+ if (DEBUG_APDATA) appendToLog("ApData: found mRfidToRead data with invalidSequence= " + invalidSequence + ", bytes= " + byteArrayToString(dataIn));
+ csReaderConnector.rfidConnector.mRfidToRead.remove(0);
+
+ if (DEBUG) appendToLog("Check buffer size: data.length = " + dataIn.length+ ", mRfidToReading.length = " + mRfidToReading.length + ", mRfidToReadingOffset = " + mRfidToReadingOffset);
+ if (dataIn.length >= mRfidToReading.length - mRfidToReadingOffset) {
+ if (mRfidToReadingOffset != 0) {
+ byte[] unhandledBytes = new byte[mRfidToReadingOffset];
+ System.arraycopy(mRfidToReading, 0, unhandledBytes, 0, unhandledBytes.length);
+ appendToLogView("!!! ERROR insufficient buffer, mRfidToReadingOffset=" + mRfidToReadingOffset + ", dataIn.length=" + dataIn.length + ", clear mRfidToReading: " + byteArrayToString(unhandledBytes));
+ byte[] mRfidToReadingNew = new byte[RFID_READING_BUFFERSIZE];
+ mRfidToReading = mRfidToReadingNew;
+ mRfidToReadingOffset = 0;
+ csReaderConnector.invalidUpdata++;
+ }
+ if (dataIn.length >= mRfidToReading.length - mRfidToReadingOffset) {
+ appendToLogView("!!! ERROR insufficient buffer, mRfidToReading.length=" + mRfidToReading.length + ", dataIn.length=" + dataIn.length + ", clear mRfidToReading: " + byteArrayToString(dataIn));
+ csReaderConnector.invalidata++;
+ break;
+ }
+ }
+
+ if (DEBUG) appendToLog("Check invalidSequence = " + invalidSequence + " with mRfidToReadingOffset = " + mRfidToReadingOffset);
+ if (mRfidToReadingOffset != 0 && invalidSequence) {
+ byte[] unhandledBytes = new byte[mRfidToReadingOffset];
+ System.arraycopy(mRfidToReading, 0, unhandledBytes, 0, unhandledBytes.length);
+ if (true) appendToLog("!!! ERROR invalidSequence with nonzero mRfidToReadingOffset=" + mRfidToReadingOffset + ", throw invalid unused data=" + unhandledBytes.length + ", " + byteArrayToString(unhandledBytes));
+ mRfidToReadingOffset = 0;
+ startIndex = 0;
+ startIndexNew = 0;
+ }
+
+ appendToLog("BtData: DataIn = " + byteArrayToString(dataIn));
+ System.arraycopy(dataIn, 0, mRfidToReading, mRfidToReadingOffset, dataIn.length);
+ mRfidToReadingOffset += dataIn.length;
+
+ int iPayloadSizeMin = 7; //boolean bprinted = false;
+ while (mRfidToReadingOffset - startIndex >= iPayloadSizeMin) {
+ //if (bprinted == false) { bprinted = true; appendToLog(byteArrayToString(mRfidToReading)); }
+ int packageLengthRead = (mRfidToReading[startIndex + 5] & 0xFF) * 256 + (mRfidToReading[startIndex + 6] & 0xFF);
+ int expectedLength = 7 + (mRfidToReading[startIndex + 5] & 0xFF) * 256 + (mRfidToReading[startIndex + 6] & 0xFF);
+ if (DEBUG) appendToLog("Looping with startIndex = " + startIndex + ", mRfidToReadingOffset = " + mRfidToReadingOffset + ", iPayloadSizeMin = " + iPayloadSizeMin + ", expectedLength = " + expectedLength);
+ if (true) {
+ if (mRfidToReading[startIndex + 0] == 0x49
+ && mRfidToReading[startIndex + 1] == (byte) 0xdc
+ && (mRfidToReadingOffset - startIndex >= expectedLength) && (expectedLength > 7)
+ ) {
+ byte[] header = new byte[7], payload = new byte[expectedLength - 7];
+ System.arraycopy(mRfidToReading, startIndex, header, 0, header.length);
+ System.arraycopy(mRfidToReading, startIndex + 7, payload, 0, payload.length);
+ int iUplinkPackageType = (mRfidToReading[startIndex + 2] & 0xFF) * 256 + (mRfidToReading[startIndex + 3] & 0xFF);
+ if (DEBUG_APDATA) appendToLog(String.format("ApData: found Rfid.Uplink.DataRead.UplinkPackage_%04X with payload = ", iUplinkPackageType) + byteArrayToString(payload));
+ RfidReaderChipData.Rx000pkgData dataA = new RfidReaderChipData.Rx000pkgData();
+ dataA.dataValues = new byte[expectedLength - 7];
+ System.arraycopy(mRfidToReading, startIndex + 7, dataA.dataValues, 0, dataA.dataValues.length);
+ if (iUplinkPackageType == 0x3001 || iUplinkPackageType == 0x3003) {
+ dataA.responseType = RfidReaderChipData.HostCmdResponseTypes.TYPE_18K6C_INVENTORY;
+ //mRfidDevice.setInventoring(true);
+ if (DEBUG) appendToLog("Check UplinkPackage_Event_csl_tag_read_epc_only_new data length = " + dataA.dataValues.length);
+ if ((iUplinkPackageType == 0x3001 && dataA.dataValues.length < 17)
+ || (iUplinkPackageType == 0x3003 && dataA.dataValues.length < 18)) {
+ appendToLog("!!! UplinkPackage_Event_csl_tag_read_epc_only_new data length has length equal or less than 15");
+ dataA.decodedError = "Received UplinkPackage_Event_csl_tag_read_epc_only_new with length = " + String.valueOf(dataA.dataValues.length) + ", data = " + byteArrayToString(dataA.dataValues);
+ } else {
+ dataA.decodedTime = System.currentTimeMillis();
+ dataA.decodedRssi = get2BytesOfRssi(dataA.dataValues, 4);
+ if (DEBUG) appendToLog("decoded decodedRssi = " + dataA.decodedRssi);
+ dataA.decodedPhase = (dataA.dataValues[6] & 0xFF) * 256 + (dataA.dataValues[7] & 0xFF);
+ if (DEBUG) appendToLog("decoded decodedPhase = " + dataA.decodedPhase);
+ dataA.decodedPort = (dataA.dataValues[10] & 0xFF);
+ if (DEBUG) appendToLog("decoded decodedPort = " + dataA.decodedPort);
+ dataA.decodedChidx = 1; //(dataA.dataValues[13] & 0xFF) * 256 + (dataA.dataValues[14] & 0xFF);
+ if (DEBUG) appendToLog("decoded decodedChidx = " + dataA.decodedChidx);
+ dataA.decodedPc = new byte[2]; System.arraycopy(dataA.dataValues, 15, dataA.decodedPc, 0, dataA.decodedPc.length);
+ if (DEBUG) appendToLog("decoded decodedPc = " + byteArrayToString(dataA.decodedPc));
+ if (iUplinkPackageType == 0x3001) {
+ dataA.decodedEpc = new byte[dataA.dataValues.length - 17];
+ System.arraycopy(dataA.dataValues, 17, dataA.decodedEpc, 0, dataA.decodedEpc.length);
+ } else {
+ int iEpcLength = getBytes2EpcLength(dataA.decodedPc);
+ if (DEBUG) appendToLog("dataA.dataValues.length = " + dataA.dataValues.length + ", iEpcLength = " + iEpcLength + " for data " + byteArrayToString(dataA.dataValues));
+ if (dataA.dataValues.length - 18 >= iEpcLength) {
+ dataA.decodedEpc = new byte[dataA.dataValues.length - 18];
+ System.arraycopy(dataA.dataValues, 17, dataA.decodedEpc, 0, iEpcLength);
+ System.arraycopy(dataA.dataValues, iEpcLength + 18, dataA.decodedEpc, iEpcLength, dataA.dataValues.length - iEpcLength - 18);
+ if (DEBUG) appendToLog("decodedEpc = " + byteArrayToString(dataA.decodedEpc));
+
+ int iMbDataLength = dataA.dataValues.length - 18 - iEpcLength;
+ int iDataIndex = 0, iDataOffset = 0;
+ for (int i = 0; i < 3; i++) {
+ int iValue = rx000Setting.getMultibankReadLength(i);
+ if (DEBUG) appendToLog("i = " + i + ", getMultibankReadLength = " + iValue);
+ if (iValue != 0) {
+ int iBankLength = iValue * 2;
+ if (DEBUG) appendToLog("Check iDataIndex = " + iDataIndex + ", iDataOffset = " + iDataOffset + ", iBankLength = " + iBankLength + ", iMbDataLength = " + iMbDataLength);
+ if (iDataOffset + iBankLength > iMbDataLength) appendToLog("!!! iBankLength " + iBankLength + " is too long for iDataOffset " + iDataOffset + ", iMbDataLength = " + iMbDataLength);
+ else {
+ if (rx000Setting.getMultibankEnable(i) == 2) iDataIndex++;
+ else if (iDataIndex == 0) {
+ dataA.decodedData1 = new byte[iBankLength];
+ System.arraycopy(dataA.dataValues, iEpcLength + 18 + iDataOffset, dataA.decodedData1, 0, dataA.decodedData1.length);
+ if (DEBUG) appendToLog("decodedData1 = " + byteArrayToString(dataA.decodedData1));
+ iDataIndex++; iDataOffset += iBankLength;
+ } else if (iDataIndex == 1) {
+ dataA.decodedData2 = new byte[iBankLength];
+ System.arraycopy(dataA.dataValues, iEpcLength + 18 + iDataOffset, dataA.decodedData2, 0, dataA.decodedData2.length);
+ if (DEBUG) appendToLog("decodedData2 = " + byteArrayToString(dataA.decodedData2));
+ iDataIndex++; iDataOffset += iBankLength;
+ } else appendToLog("!!! CANNOT handle the third multibank data");
+ }
+ }
+ }
+ int extraLength = 0;
+ if (dataA.decodedData1 != null) extraLength += dataA.decodedData1.length;
+ if (dataA.decodedData2 != null) extraLength += dataA.decodedData2.length;
+ if (extraLength != 0) {
+ byte[] decodedEpcNew = new byte[dataA.decodedEpc.length - extraLength];
+ System.arraycopy(dataA.decodedEpc, 0, decodedEpcNew, 0, decodedEpcNew.length);
+ dataA.decodedEpc = decodedEpcNew;
+ }
+ appendToLog("dataA.decodedPc,Epc = " + byteArrayToString(dataA.decodedPc) + "," + byteArrayToString(dataA.decodedEpc)
+ + ", decodedData1,2 = " + (dataA.decodedData1 == null ? "null" : byteArrayToString(dataA.decodedData1))
+ + ", " + (dataA.decodedData2 == null ? "null" : byteArrayToString(dataA.decodedData2)));
+ if (iDataOffset != iMbDataLength) appendToLog("!!! Some unhandled data as iDataOffset = " + iDataOffset + " for iMbDataLength = " + iMbDataLength);
+ else if (DEBUG) appendToLog("iDataOffset = iMbDataLength = " + iMbDataLength);
+ } else appendToLog("!!! iEpcLength " + iEpcLength + " is too long for the data " + byteArrayToString(dataA.dataValues));
+ }
+ mRx000ToRead.add(dataA);
+ if (DEBUG) appendToLog("3001/3003 dataA.responseType = " + dataA.responseType.toString());
+ if (DEBUG) appendToLog("decoded decodedEpc = " + byteArrayToString(dataA.decodedEpc) + " with mRx000ToRead.size = " + mRx000ToRead.size());
+ if (DEBUG_APDATA) appendToLog("ApData: uplink data UplinkPackage_Event_csl_tag_read_epc_only_new tag with Epc = " + byteArrayToString(dataA.decodedEpc) + " is uploaded to mRx000ToRead with mRx000ToRead.size = " + mRx000ToRead.size());
+ if (DEBUG_APDATA) appendToLog("ApData: Rfid.Uplink.DataRead.UplinkPackage_Event_csl_tag_read_epc_only_new has been processed");
+ }
+ } else if (iUplinkPackageType == 0x3006) {
+ dataA.responseType = RfidReaderChipData.HostCmdResponseTypes.TYPE_18K6C_INVENTORY_COMPACT;
+ //mRfidDevice.setInventoring(true);
+ if (DEBUG) appendToLog("Check UplinkPackage_Event_csl_tag_read_compact data length = " + dataA.dataValues.length);
+ if (dataA.dataValues.length < 10) {
+ appendToLog("!!! UplinkPackage_Event_csl_tag_read_compact data length has length equal or less than 6");
+ dataA.decodedError = "Received Event_csl_tag_read_compact with length = " + String.valueOf(dataA.dataValues.length) + ", data = " + byteArrayToString(dataA.dataValues);
+ } else {
+ int index = 0;
+ byte[] dataHeader = new byte[6]; System.arraycopy(dataA.dataValues, 0, dataHeader, 0, dataHeader.length);
+ byte[] dataValuesFull = new byte[dataA.dataValues.length - 6]; System.arraycopy(dataA.dataValues, 6, dataValuesFull, 0, dataValuesFull.length);
+ if (DEBUG_APDATA) appendToLog("ApData: found Rfid.Uplink.DataRead.UplinkPackage_Event_csl_tag_read_compact with payload header = " + byteArrayToString(dataHeader) + ", dataValuesFull = " + byteArrayToString(dataValuesFull));
+ while (index < dataValuesFull.length) { //change from while
+ if (DEBUG) appendToLog("Looping with index = " + index + ", dataValuesFull.length = " + dataValuesFull.length);
+ dataA.decodedTime = System.currentTimeMillis();
+ if (dataValuesFull.length >= index + 2) {
+ dataA.decodedPc = new byte[2];
+ System.arraycopy(dataValuesFull, index, dataA.decodedPc, 0, dataA.decodedPc.length);
+ index += 2;
+ } else break;
+
+ int epcLength = getBytes2EpcLength(dataA.decodedPc); //((dataA.decodedPc[0] & 0xFF) >> 3) * 2;
+ if (DEBUG) appendToLog("decoded decodedPc = " + byteArrayToString(dataA.decodedPc) + " with epclength = " + epcLength);
+ if (dataValuesFull.length >= index + epcLength) {
+ dataA.decodedEpc = new byte[epcLength];
+ System.arraycopy(dataValuesFull, index, dataA.decodedEpc, 0, epcLength);
+ index += epcLength;
+ } else break;
+
+ if (DEBUG) appendToLog("decoded decodedEpc = " + byteArrayToString(dataA.decodedEpc));
+ if (dataValuesFull.length >= index + 2) {
+ dataA.decodedRssi = get2BytesOfRssi(dataValuesFull, index);
+ if (DEBUG) appendToLog("decoded decodedRssi = " + dataA.decodedRssi);
+ index += 2;
+ } else break;
+
+ mRx000ToRead.add(dataA);
+ if (DEBUG) appendToLog("3006 dataA.responseType = " + dataA.responseType.toString());
+ if (DEBUG_APDATA) appendToLog("ApData: uplink data UplinkPackage_Event_csl_tag_read_compact tag with Epc = " + byteArrayToString(dataA.decodedEpc) + " is uploaded to mRx000ToRead with mRx000ToRead.size = " + mRx000ToRead.size());
+
+ dataA = new RfidReaderChipData.Rx000pkgData();
+ dataA.responseType = RfidReaderChipData.HostCmdResponseTypes.TYPE_18K6C_INVENTORY_COMPACT;
+ }
+ if (DEBUG) appendToLog("Exit while loop with index = " + index + ", dataValuesFull.length = " + dataValuesFull.length);
+ if (index != dataValuesFull.length) {
+ byte[] bytesUnhandled = new byte[dataValuesFull.length - index];
+ System.arraycopy(dataValuesFull, index, bytesUnhandled, 0, bytesUnhandled.length);
+ appendToLog("!!! unhandled data 0: " + byteArrayToString(bytesUnhandled));
+ }
+ if (DEBUG_APDATA) appendToLog("ApData: Rfid.Uplink.DataRead.UplinkPackage_Event_csl_tag_read_compact has been processed");
+ }
+ } else if (iUplinkPackageType == 0x3007) {
+ DEBUG = false;
+ if (DEBUG) appendToLog("Check UplinkPackage_Event_csl_miscellaneous_event data length = " + dataA.dataValues.length);
+ int iCommand = (dataA.dataValues[4] & 0xFF) * 256 + (dataA.dataValues[5] & 0xFF);
+ if (dataA.dataValues.length < 6 || (iCommand >= 3 && dataA.dataValues.length < 8)) {
+ appendToLog("!!! UplinkPackage_Event_csl_miscellaneous_event data length has length equal or less than 8");
+ } else {
+ switch (iCommand) {
+ case 1:
+ rx000Setting.keepAliveTime = new Date();
+ break;
+ case 2:
+ rx000Setting.inventoryRoundEndTime = new Date();
+ break;
+ case 3:
+ rx000Setting.crcErrorRate = ((dataA.dataValues[6] & 0xFF) << 8) + (dataA.dataValues[7] & 0xFF);
+ break;
+ case 4:
+ rx000Setting.tagRate = ((dataA.dataValues[6] & 0xFF) << 8) + (dataA.dataValues[7] & 0xFF);
+ break;
+ default:
+ appendToLog("!!! iCommand cannot be recognised for the uplink data " + byteArrayToString(dataA.dataValues));
+ break;
+ }
+ if (DEBUG_PKDATA) appendToLog("PkData: Rfid.Uplink.DataRead.UplinkPackage_Event_csl_miscellaneous_event has been processed");
+ }
+ } else if (iUplinkPackageType == 0x3008) {
+ dataA.responseType = RfidReaderChipData.HostCmdResponseTypes.TYPE_COMMAND_END;
+ setInventoring(false);
+ appendToLogView("mRx000UplinkHandler_3008: " + byteArrayToString(dataA.dataValues));
+ if (DEBUG) appendToLog("Check UplinkPackage_Event_csl_operation_complete data length = " + dataA.dataValues.length);
+ if (dataA.dataValues.length < 8) {
+ appendToLog("!!! UplinkPackage_Event_csl_operation_complete data length has length equal or less than 8");
+ dataA.decodedError = "Received Event_csl_operation_complete with length = " + String.valueOf(dataA.dataValues.length) + ", data = " + byteArrayToString(dataA.dataValues);
+ } else {
+ int iCommand = (dataA.dataValues[4] & 0xFF) * 256 + (dataA.dataValues[5] & 0xFF);
+ int iStatus = (dataA.dataValues[6] & 0xFF) * 256 + (dataA.dataValues[7] & 0xFF);
+ if (DEBUG_APDATA) appendToLog("ApData: found Rfid.Uplink.DataRead.UplinkPackage_Event_csl_operation_complete");
+ if (DEBUG) appendToLog("Check iStatus = " + iStatus);
+ switch (iStatus) {
+ case 0:
+ dataA.decodedError = null;
+ break;
+ case 1:
+ dataA.decodedError = "0x0001 Tag cache table buffer is overflowed";
+ break;
+ case 2:
+ dataA.decodedError = "0x0002 Wrong register address";
+ break;
+ case 3:
+ dataA.decodedError = "0x0003 Register length too large";
+ break;
+ case 4:
+ dataA.decodedError = "0x0004 E710 not powered up";
+ break;
+ case 5:
+ dataA.decodedError = "0x0005 Invalid parameter";
+ break;
+ case 6:
+ dataA.decodedError = "0x0006 Event fifo full";
+ break;
+ case 7:
+ dataA.decodedError = "0x0007 TX not ramped up";
+ break;
+ case 8:
+ dataA.decodedError = "0x0008 Register read only";
+ break;
+ case 9:
+ dataA.decodedError = "0x0009 Failed to halt";
+ break;
+ case 10:
+ dataA.decodedError = "0x000A PLL not locked";
+ break;
+ case 11:
+ dataA.decodedError = "0x000B Power control target failed";
+ break;
+ case 12:
+ dataA.decodedError = "0x000C Radio power not enabled";
+ break;
+ case 13:
+ dataA.decodedError = "0x000D E710 command error (e.g. battery low)";
+ break;
+ case 14:
+ dataA.decodedError = "0x000E E710 Op timeout";
+ break;
+ case 15:
+ dataA.decodedError = "0x000F E710 Aggregate error (e.g. battery low, metal reflection)";
+ break;
+ case 0x10:
+ dataA.decodedError = "0x0010 E710 hardware link error";
+ break;
+ case 0x11:
+ dataA.decodedError = "0x0011 E710 event fail to send error";
+ break;
+ case 0x12:
+ dataA.decodedError = "0x0012 E710 antenna error (e.g. metal reflection)";
+ break;
+ case 0x00FF:
+ dataA.decodedError = "0x00FF Other error (e.g. battery low)";
+ break;
+ default:
+ dataA.decodedError = "Unknown error";
+ appendToLog("!!! CANNOT handle status type with " + byteArrayToString(header) + "." + byteArrayToString(payload));
+ break;
+ }
+ mRx000ToRead.add(dataA);
+ if (DEBUG) appendToLog("3008 dataA.responseType = " + dataA.responseType.toString());
+ if (DEBUG_APDATA) appendToLog("ApData: uplink data UplinkPackage_Event_csl_operation_complete with decodedError = " + dataA.decodedError + " is uploaded to mRx000ToRead with mRx000ToRead.size = " + mRx000ToRead.size());
+ if (DEBUG_APDATA) appendToLog("ApData: Rfid.Uplink.DataRead.UplinkPackage_Event_csl_operation_complete has been processed");
+ }
+ } else if (iUplinkPackageType == 0x3009) {
+ dataA.responseType = RfidReaderChipData.HostCmdResponseTypes.TYPE_18K6C_TAG_ACCESS;
+ if (DEBUG) appendToLog("Check UplinkPackage_Event_csl_access_complete data length = " + dataA.dataValues.length);
+ if (dataA.dataValues.length < 12) {
+ appendToLog("!!! UplinkPackage_Event_csl_access_complete data length has length equal or less than 12");
+ dataA.decodedError = "Received Event_csl_access_complete with length = " + String.valueOf(dataA.dataValues.length) + ", data = " + byteArrayToString(dataA.dataValues);
+ } else {
+ int iCommand = (dataA.dataValues[4] & 0xFF) * 256 + (dataA.dataValues[5] & 0xFF);
+ int iTagError = dataA.dataValues[6];
+ int iMacError = dataA.dataValues[7];
+ int iWriteCount = dataA.dataValues[8] * 256 + dataA.dataValues[9];
+ byte[] bytesResponse = null, bytesHeader = new byte[12];
+ System.arraycopy(dataA.dataValues, 0, bytesHeader, 0, bytesHeader.length);
+ if (dataA.dataValues.length > 12) {
+ bytesResponse = new byte[dataA.dataValues.length - 12];
+ System.arraycopy(dataA.dataValues, 12, bytesResponse, 0, bytesResponse.length);
+ if (DEBUG)
+ appendToLog("bytesResponse = " + byteArrayToString(bytesResponse));
+ }
+ String string = null;
+ switch (iTagError) {
+ case 0x00:
+ string = "Other error";
+ break;
+ case 0x01:
+ string = "Not supported";
+ break;
+ case 0x02:
+ string = "Insufficient privileges";
+ break;
+ case 0x03:
+ string = "Memory overrun";
+ break;
+ case 0x04:
+ string = "Memory locked";
+ break;
+ case 0x05:
+ string = "Crypto suite error";
+ break;
+ case 0x06:
+ string = "Command not encapsulated";
+ break;
+ case 0x07:
+ string = "ResponseBuffer overflow";
+ break;
+ case 0x08:
+ string = "Security timeout";
+ break;
+ case 0x0B:
+ string = "Insufficient power";
+ break;
+ case 0x0F:
+ string = "Non-specific error";
+ break;
+ case 0x10:
+ //string = "No error";
+ break;
+ default:
+ string = "OTHER errors";
+ break;
+ }
+ if (string != null)
+ dataA.decodedError = "Tag Error: " + string;
+ string = null;
+ switch (iMacError) {
+ case 0x00:
+ //string = "No error";
+ break;
+ case 0x01:
+ string = "No tag reply";
+ break;
+ case 0x02:
+ string = "Invalid password";
+ break;
+ case 0x03:
+ string = "Failed to send command";
+ break;
+ case 0x04:
+ string = "No access reply";
+ break;
+ default:
+ string = "OTHER errors";
+ break;
+ }
+ if (string != null) {
+ if (dataA.decodedError == null)
+ dataA.decodedError = "Mac Error: " + string;
+ else dataA.decodedError += (", Mac Error: " + string);
+ }
+ if (iCommand == 0xC3 && iWriteCount == 0) {
+ string = "Write Error: nothing is written";
+ if (dataA.decodedError == null)
+ dataA.decodedError = string;
+ else dataA.decodedError += (", " + string);
+ appendToLog(String.format("rx000pkgData: Command 0x%X with mRfidToWrite.size = %s", iCommand, csReaderConnector.rfidConnector.mRfidToWrite.size()));
+ }
+ if (DEBUG)
+ appendToLog("decodedError2 = " + dataA.decodedError);
+ appendToLog("bytesResponse is " + (bytesResponse == null ? "null" : byteArrayToString(bytesResponse)));
+ if (bytesResponse != null && bytesResponse.length != 0) {
+ for (int i = 0; i < bytesResponse.length; i++) {
+ string = String.format("%02X", (byte) ((bytesResponse[i] & 0xFF)));
+ if (dataA.decodedResult == null)
+ dataA.decodedResult = string;
+ else dataA.decodedResult += string;
+ }
+ } else dataA.decodedResult = "";
+ if (DEBUG || true)
+ appendToLog("decodedResult = " + dataA.decodedResult);
+ }
+ mRx000ToRead.add(dataA);
+ if (DEBUG) appendToLog("3009 dataA.responseType = " + dataA.responseType.toString());
+ if (DEBUG_APDATA) appendToLog("ApData: uplink data UplinkPackage_Event_csl_access_complete tag with data = " + byteArrayToString(dataA.dataValues) + " is uploaded to mRx000ToRead with mRx000ToRead.size = " + mRx000ToRead.size());
+ if (DEBUG_APDATA) appendToLog("ApData: Rfid.Uplink.DataRead.UplinkPackage_Event_csl_access_complete has been processed");
+ }
+ else appendToLog(String.format("!!! CANNOT handle UplinkPackageType 0x%X", iUplinkPackageType) + " with uplink data " + byteArrayToString(header) + "." + byteArrayToString(payload));
+ packageFound = true;
+ packageType = 4;
+ startIndexNew = startIndex + expectedLength;
+ }
+ }
+
+ if (packageFound) {
+ packageFound = false;
+ if (DEBUG) appendToLog("Found package with packageType = " + packageType + ", Check startIndex = " + startIndex + " with startIndexNew = " + startIndexNew + ", mRfidToReadingOffset = " + mRfidToReadingOffset);
+ if (DEBUG && startIndex != 0) {
+ byte[] unhandledBytes = new byte[startIndex];
+ System.arraycopy(mRfidToReading, 0, unhandledBytes, 0, unhandledBytes.length);
+ appendToLog("!!! packageFound with invalid unused data: " + unhandledBytes.length + ", " + byteArrayToString(unhandledBytes));
+ csReaderConnector.invalidUpdata++;
+ }
+ if (DEBUG) {
+ byte[] usedBytes = new byte[startIndexNew - startIndex];
+ System.arraycopy(mRfidToReading, startIndex, usedBytes, 0, usedBytes.length);
+ if (DEBUG) appendToLog("used data = " + usedBytes.length + ", " + byteArrayToString(usedBytes));
+ }
+ byte[] mRfidToReadingNew = new byte[RFID_READING_BUFFERSIZE];
+ System.arraycopy(mRfidToReading, startIndexNew, mRfidToReadingNew, 0, mRfidToReadingOffset - startIndexNew);
+ mRfidToReading = mRfidToReadingNew;
+ mRfidToReadingOffset -= startIndexNew;
+ startIndex = 0;
+ startIndexNew = 0;
+ startIndexOld = 0;
+ if (DEBUG) appendToLog("Check new mRfidToReadingOffset = " + mRfidToReadingOffset + " with startIndex and startIndexNew = 0");
+ if (DEBUG && mRfidToReadingOffset != 0) {
+ byte[] remainedBytes = new byte[mRfidToReadingOffset];
+ System.arraycopy(mRfidToReading, 0, remainedBytes, 0, remainedBytes.length);
+ appendToLog("!!! moved with remained bytes=" + byteArrayToString(remainedBytes));
+ }
+ } else {
+ startIndex++;
+ }
+ }
+ if (DEBUG) appendToLog("Exit while loop with startIndex = " + startIndex + ", mRfidToReadingOffset = " + mRfidToReadingOffset + ", iPayloadSizeMin = " + iPayloadSizeMin);
+ if (startIndex != 0 && mRfidToReadingOffset != 0) {
+ //appendToLog("exit while(-8) loop with startIndex = " + startIndex + ( startIndex == 0 ? "" : "(NON-ZERO)" ) + ", mRfidToReadingOffset=" + mRfidToReadingOffset);
+ if (startIndex > mRfidToReadingOffset) appendToLog("!!! ERROR. startIndex = " + startIndex + " is greater than mRfidToReadingOffset = " + mRfidToReadingOffset);
+ else {
+ byte[] unhandled = new byte[startIndex];
+ System.arraycopy(mRfidToReading, 0, unhandled, 0, unhandled.length);
+ appendToLog("!!! Unhandled data 1: " + byteArrayToString(unhandled));
+ byte[] mRfidToReadingNew = new byte[RFID_READING_BUFFERSIZE];
+ System.arraycopy(mRfidToReading, startIndex, mRfidToReadingNew, 0, mRfidToReadingOffset - startIndex);
+ mRfidToReading = mRfidToReadingNew;
+ mRfidToReadingOffset = mRfidToReadingOffset - startIndex;
+ startIndex = 0;
+ startIndexNew = 0;
+ csReaderConnector.invalidUpdata++;
+ }
+ }
+ }
+ }
+ if (DEBUG & bFirst == false) appendToLog("Exit while loop with mRfidToRead.size = " + csReaderConnector.rfidConnector.mRfidToRead.size());
+ //if (DEBUG) appendToLog("mRfidToReadingOffset = " + mRfidToReadingOffset + ", startIndexNew = " + startIndexNew);
+ //if (mRfidToReadingOffset == startIndexNew && mRfidToReadingOffset != 0) {
+ // byte[] unusedData = new byte[mRfidToReadingOffset];
+ // System.arraycopy(mRfidToReading, 0, unusedData, 0, unusedData.length);
+ // appendToLog("Ending with invaid unused data: " + mRfidToReadingOffset + ", " + byteArrayToString(unusedData));
+ // mRfidToReading = new byte[RFID_READING_BUFFERSIZE];
+ // mRfidToReadingOffset = 0;
+ //}
+ bRx000ToReading = false;
+ if (DEBUGTHREAD) {
+ if (mRx000ToRead.size() != 0) appendToLog("mRx000UplinkHandler(): END with mRx000ToRead size = " + mRx000ToRead.size());
+ }
+ }
+ public boolean turnOn(boolean onStatus) {
+ appendToLog("aabb 1");
+ RfidConnector.CsReaderRfidData csReaderRfidData = new RfidConnector.CsReaderRfidData();
+ if (onStatus) {
+ csReaderRfidData.rfidPayloadEvent = RfidConnector.RfidPayloadEvents.RFID_POWER_ON;
+ csReaderRfidData.waitUplinkResponse = false;
+ appendToLog("aabb 2");
+ addRfidToWrite(csReaderRfidData);
+ return true;
+ } else if (onStatus == false) {
+ csReaderRfidData.rfidPayloadEvent = RfidConnector.RfidPayloadEvents.RFID_POWER_OFF;
+ csReaderRfidData.waitUplinkResponse = false;
+ addRfidToWrite(csReaderRfidData);
+ return true;
+ } else {
+ return false;
+ }
+ }
+
+ boolean bLowPowerStandby = false;
+ public boolean setPwrManagementMode(boolean bLowPowerStandby) {
+ if (csReaderConnector.isConnected() == false) return false;
+ if (this.bLowPowerStandby == bLowPowerStandby) return true;
+ this.bLowPowerStandby = bLowPowerStandby; appendToLog("!!! Skip setPwrManagementMode[" + bLowPowerStandby + "] with this.blowPowerStandby = " + this.bLowPowerStandby);
+ return true;
+ }
+
+ int wideRSSI = -1;
+ public int getwideRSSI() {
+ if (wideRSSI < 0) {
+ setPwrManagementMode(false);
+ wideRSSI = 0; appendToLog("!!! Skip getwideRSSI with assumed value = 0");
+ }
+ return wideRSSI;
+ }
+
+ final int RXGAIN_INVALID = -1, RXGAIN_MIN = 0, RXGAIN_MAX = 0x1FF, RXGAIN_DEFAULT = 0x104;
+ int rxGain = RXGAIN_INVALID;
+ public int getHighCompression() {
+ int iRetValue = -1;
+ if (rxGain < RXGAIN_MIN || rxGain > RXGAIN_MAX) {
+ setPwrManagementMode(false);
+ rxGain = RXGAIN_DEFAULT; appendToLog(String.format("!!! Skip getHighCompression with assumed rxGain = 0x%X", RXGAIN_DEFAULT));
+ } else iRetValue = (rxGain >> 8);
+ return iRetValue;
+ }
+ public int getRflnaGain() {
+ int iRetValue = -1;
+ if (rxGain < RXGAIN_MIN || rxGain > RXGAIN_MAX) {
+ setPwrManagementMode(false);
+ rxGain = RXGAIN_DEFAULT; appendToLog(String.format("!!! Skip getRflnaGain with assumed rxGain = 0x%X", RXGAIN_DEFAULT));
+ } else iRetValue = ((rxGain & 0xC0) >> 6);
+ return iRetValue;
+ }
+ public int getIflnaGain() {
+ int iRetValue = -1;
+ if (rxGain < RXGAIN_MIN || rxGain > RXGAIN_MAX) {
+ setPwrManagementMode(false);
+ rxGain = RXGAIN_DEFAULT; appendToLog(String.format("!!! Skip getIflnaGain with assumed rxGain = 0x%X", RXGAIN_DEFAULT));
+ } else iRetValue = ((rxGain & 0x38) >> 3);
+ return iRetValue;
+ }
+ public int getAgcGain() {
+ int iRetValue = -1;
+ if (rxGain < RXGAIN_MIN || rxGain > RXGAIN_MAX) {
+ setPwrManagementMode(false);
+ rxGain = RXGAIN_DEFAULT; appendToLog(String.format("!!! Skip getAgcGain with assumed rxGain = 0x%X", RXGAIN_DEFAULT));
+ } else iRetValue = (rxGain & 0x07);
+ return iRetValue;
+ }
+ public int getRxGain() {
+ int iRetValue = -1;
+ if (rxGain < RXGAIN_MIN || rxGain > RXGAIN_MAX) {
+ setPwrManagementMode(false);
+ rxGain = RXGAIN_DEFAULT; appendToLog(String.format("!!! Skip getRxGain with assumed rxGain = 0x%X", RXGAIN_DEFAULT));
+ } else iRetValue = rxGain;
+ return iRetValue;
+ }
+ public boolean setRxGain(int highCompression, int rflnagain, int iflnagain, int agcgain) {
+ int rxGain_new = ((highCompression & 0x01) << 8) | ((rflnagain & 0x3) << 6) | ((iflnagain & 0x7) << 3) | (agcgain & 0x7);
+ return setRxGain(rxGain_new);
+ }
+ public boolean setRxGain(int rxGain_new) {
+ boolean bRetValue = true;
+ if ((rxGain_new != rxGain) || (sameCheck == false)) {
+ setPwrManagementMode(false);
+ rxGain = rxGain_new; appendToLog(String.format("!!! Skip setRxGain[0x%X]", rxGain_new));
+ }
+ return bRetValue;
+ }
+
+ public boolean sendHostRegRequestHST_CMD(RfidReaderChipData.HostCommands hostCommand) {
+ appendToLog("!!! hostCommand = " + hostCommand.toString());
+ long hostCommandData = -1;
+ switch (hostCommand) {
+ case CMD_18K6CINV:
+ hostCommandData = 0xA1;
+ if (rx000Setting.getQuerySelect() > 1 /*&& mRfidReaderChip.mRx000Setting.getImpinjExtension() == 0*/) hostCommandData = 0xA3;
+ break;
+ case CMD_18K6CINV_COMPACT:
+ hostCommandData = 0xA2;
+ if (rx000Setting.getQuerySelect() > 1 /*&& mRfidReaderChip.mRx000Setting.getImpinjExtension() == 0*/) hostCommandData = 0xA6;
+ break;
+ case CMD_18K6CINV_MB:
+ hostCommandData = 0xA4;
+ appendToLog("getQuerySelect = " + rx000Setting.getQuerySelect() + ", getImpinjExtension = " + rx000Setting.getImpinjExtension());
+ if (rx000Setting.getQuerySelect() > 1 /*&& mRfidReaderChip.mRx000Setting.getImpinjExtension() == 0*/) hostCommandData = 0xA5;
+ break;
+ case NULL:
+ hostCommandData = 0xAE;
+ break;
+ case CMD_18K6CREAD:
+ hostCommandData = 0xB1;
+ break;
+ case CMD_18K6CWRITE:
+ hostCommandData = 0xB2;
+ break;
+ case CMD_18K6CLOCK:
+ hostCommandData = 0xB7;
+ break;
+ case CMD_18K6CKILL:
+ hostCommandData = 0xB8;
+ break;
+ case CMD_18K6CAUTHENTICATE:
+ hostCommandData = 0xB9;
+ break;
+
+ case CMD_WROEM:
+ hostCommandData = 0x02;
+ break;
+ case CMD_RDOEM:
+ hostCommandData = 0x03;
+ break;
+ case CMD_ENGTEST:
+ hostCommandData = 0x04;
+ break;
+ case CMD_MBPRDREG:
+ hostCommandData = 0x05;
+ break;
+ case CMD_MBPWRREG:
+ hostCommandData = 0x06;
+ break;
+ case CMD_SETPWRMGMTCFG:
+ hostCommandData = 0x14;
+ break;
+ case CMD_UPDATELINKPROFILE:
+ hostCommandData = 0x19;
+ break;
+ case CMD_18K6CBLOCKWRITE:
+ hostCommandData = 0x1F;
+ break;
+ case CMD_CHANGEEAS:
+ hostCommandData = 0x26;
+ break;
+ case CMD_GETSENSORDATA:
+ hostCommandData = 0x3b;
+ break;
+ case CMD_READBUFFER:
+ hostCommandData = 0x51;
+ break;
+ case CMD_UNTRACEABLE:
+ hostCommandData = 0x52;
+ break;
+ case CMD_FDM_RDMEM:
+ hostCommandData = 0x53; break;
+ case CMD_FDM_WRMEM:
+ hostCommandData = 0x54; break;
+ case CMD_FDM_AUTH:
+ hostCommandData = 0x55; break;
+ case CMD_FDM_GET_TEMPERATURE:
+ hostCommandData = 0x56; break;
+ case CMD_FDM_START_LOGGING:
+ hostCommandData = 0x57; break;
+ case CMD_FDM_STOP_LOGGING:
+ hostCommandData = 0x58; break;
+ case CMD_FDM_WRREG:
+ hostCommandData = 0x59; break;
+ case CMD_FDM_RDREG:
+ hostCommandData = 0x5A; break;
+ case CMD_FDM_DEEP_SLEEP:
+ hostCommandData = 0x5B; break;
+ case CMD_FDM_OPMODE_CHECK:
+ hostCommandData = 0x5C; break;
+ case CMD_FDM_INIT_REGFILE:
+ hostCommandData = 0x5d; break;
+ case CMD_FDM_LED_CTRL:
+ hostCommandData = 0x5e; break;
+ default:
+ appendToLog("!!! CANNOT handle with hostCommand = " + hostCommand.toString());
+ }
+ if (hostCommandData == -1) {
+ return false;
+ } else {
+ commandOperating = true;
+ byte[] msgBuffer = new byte[]{(byte)0x80, (byte)0xb3, (byte)0x10, (byte)0xA1, 0, 0, 0};
+ msgBuffer[3] = (byte) (hostCommandData % 256);
+ if (true) appendToLog("3030 data = " + byteArrayToString(rx000Setting.antennaPortConfig[0]));
+ return sendHostRegRequest(HostRegRequests.HST_CMD, true, msgBuffer);
+ }
+ }
+
+ ArrayList macAccessHistory = new ArrayList<>();
+ void addMacAccessHistory(byte[] msgBuffer) {
+ byte[] msgBuffer4 = Arrays.copyOf(msgBuffer, 4);
+ for (int i = 0; i < macAccessHistory.size(); i++) {
+ byte[] macAccessHistory4 = Arrays.copyOf(macAccessHistory.get(i), 4);
+ if (Arrays.equals(msgBuffer4, macAccessHistory4)) {
+ appendToLog("macAccessHistory: deleted old record=" + byteArrayToString(macAccessHistory4));
+ macAccessHistory.remove(i);
+ break;
+ }
+ }
+ appendToLog("macAccessHistory: added msgbuffer=" + byteArrayToString(msgBuffer));
+ macAccessHistory.add(msgBuffer);
+ }
+
+ byte downlinkSequenceNumber = 0;
+ boolean sendHostRegRequest(HostRegRequests hostRegRequests, boolean writeOperation, byte[] msgBuffer) {
+ boolean needResponse = false;
+ boolean validRequest = false;
+
+ if (hostRegRequests == HostRegRequests.HST_ANT_DESC_DWELL) appendToLog("setAntennaDwell 4");
+ boolean bSkip = false;
+ if ( (hostRegRequests != HostRegRequests.HST_CMD && hostRegRequests != HostRegRequests.MAC_OPERATION)
+ || (hostRegRequests == HostRegRequests.HST_CMD
+ && msgBuffer[3] != (byte)0xA1
+ && msgBuffer[3] != (byte)0xA2
+ && msgBuffer[3] != (byte)0xA3
+ && msgBuffer[3] != (byte)0xA4
+ && msgBuffer[3] != (byte)0xA5
+ && msgBuffer[3] != (byte)0xA6
+ && msgBuffer[3] != (byte)0xAE
+ && msgBuffer[3] != (byte)0xB1
+ && msgBuffer[3] != (byte)0xB2
+ && msgBuffer[3] != (byte)0xB7
+ && msgBuffer[3] != (byte)0xB8
+ && msgBuffer[3] != (byte)0xB9
+ ) || (hostRegRequests == HostRegRequests.MAC_OPERATION && writeOperation && msgBuffer[0] != (byte)0x80)
+ ) bSkip = true;
+ if (bSkip) {
+ appendToLog("!!! Skip sendingRegRequest with " + hostRegRequests.toString() + ", writeOperation = " + writeOperation + "." + byteArrayToString(msgBuffer));
+ return true;
+ }
+ if (csReaderConnector.isConnected() == false) {
+ appendToLog("!!! Skip sending as bleConnected is false");
+ return false;
+ }
+ if (false) addMacAccessHistory(msgBuffer);
+ switch (hostRegRequests) {
+ case MAC_OPERATION:
+ case HST_ANT_CYCLES:
+ case HST_ANT_DESC_SEL:
+ case HST_ANT_DESC_CFG:
+ case MAC_ANT_DESC_STAT:
+ case HST_ANT_DESC_PORTDEF:
+ case HST_ANT_DESC_DWELL:
+ case HST_ANT_DESC_RFPOWER:
+ case HST_ANT_DESC_INV_CNT:
+ validRequest = true;
+ break;
+ case HST_TAGMSK_DESC_SEL:
+ case HST_TAGMSK_DESC_CFG:
+ case HST_TAGMSK_BANK:
+ case HST_TAGMSK_PTR:
+ case HST_TAGMSK_LEN:
+ case HST_TAGMSK_0_3:
+ validRequest = true;
+ break;
+ case HST_QUERY_CFG:
+ case HST_INV_CFG:
+ case HST_INV_SEL:
+ case HST_INV_ALG_PARM_0:
+ case HST_INV_ALG_PARM_1:
+ case HST_INV_ALG_PARM_2:
+ case HST_INV_ALG_PARM_3:
+ case HST_INV_RSSI_FILTERING_CONFIG:
+ case HST_INV_RSSI_FILTERING_THRESHOLD:
+ case HST_INV_RSSI_FILTERING_COUNT:
+ case HST_INV_EPC_MATCH_CFG:
+ case HST_INV_EPCDAT_0_3:
+ validRequest = true;
+ break;
+ case HST_TAGACC_DESC_CFG:
+ case HST_TAGACC_BANK:
+ case HST_TAGACC_PTR:
+ case HST_TAGACC_CNT:
+ case HST_TAGACC_LOCKCFG:
+ case HST_TAGACC_ACCPWD:
+ case HST_TAGACC_KILLPWD:
+ case HST_TAGWRDAT_SEL:
+ case HST_TAGWRDAT_0:
+ validRequest = true;
+ break;
+ case HST_RFTC_CURRENT_PROFILE:
+ case HST_RFTC_FRQCH_SEL:
+ case HST_RFTC_FRQCH_CFG:
+ case HST_RFTC_FRQCH_DESC_PLLDIVMULT:
+ case HST_RFTC_FRQCH_DESC_PLLDACCTL:
+ case HST_RFTC_FRQCH_CMDSTART:
+ validRequest = true;
+ break;
+ case HST_AUTHENTICATE_CFG:
+ case HST_AUTHENTICATE_MSG:
+ case HST_READBUFFER_LEN:
+ case HST_UNTRACEABLE_CFG:
+ validRequest = true;
+ break;
+ case HST_CMD:
+ validRequest = true;
+ needResponse = true;
+ break;
+ }
+
+ if (msgBuffer == null || validRequest == false) {
+ appendToLog("invalid request for msgbuffer = " + (msgBuffer == null ? "NULL" : "Valid") + ", validRequst = " + validRequest);
+ return false;
+ } else {
+ RfidConnector.CsReaderRfidData csReaderRfidData = new RfidConnector.CsReaderRfidData();
+ csReaderRfidData.rfidPayloadEvent = RfidConnector.RfidPayloadEvents.RFID_COMMAND;
+ csReaderRfidData.dataValues = msgBuffer;
+ csReaderRfidData.waitUplinkResponse = true; //(needResponse || writeOperation == false);
+ if (msgBuffer[0] == (byte)0x80
+ && msgBuffer[1] == (byte)0xB3
+ ) {
+ csReaderRfidData.dataValues[4] = downlinkSequenceNumber++;
+ if (msgBuffer[2] == 0x10
+ && msgBuffer[3] != (byte)0xA1
+ && msgBuffer[3] != (byte)0xA2
+ && msgBuffer[3] != (byte)0xA3
+ && msgBuffer[3] != (byte)0xA4
+ && msgBuffer[3] != (byte)0xA5
+ && msgBuffer[3] != (byte)0xA6
+ && msgBuffer[3] != (byte)0xB1
+ && msgBuffer[3] != (byte)0xB2
+ && msgBuffer[3] != (byte)0xB7
+ && msgBuffer[3] != (byte)0xB8
+ && msgBuffer[3] != (byte)0xB9
+ ) csReaderRfidData.waitUplink1Response = true;
+ }
+ addRfidToWrite(csReaderRfidData);
+ return true;
+ }
+ }
+
+ void addRfidToWrite(RfidConnector.CsReaderRfidData csReaderRfidData) {
+ boolean repeatRequest = false, DEBUG = false;
+ if (false && csReaderRfidData.rfidPayloadEvent == RfidConnector.RfidPayloadEvents.RFID_COMMAND) {
+ appendToLog("!!! Skip " + csReaderRfidData.rfidPayloadEvent.toString() + "." + byteArrayToString(csReaderRfidData.dataValues));
+ return;
+ }
+ if (DEBUG) appendToLog("0 with mRfidToWrite.size() = " + csReaderConnector.rfidConnector.mRfidToWrite.size());
+ if (csReaderConnector.rfidConnector.mRfidToWrite.size() != 0 && sameCheck) {
+ for (int i = 1; i < csReaderConnector.rfidConnector.mRfidToWrite.size(); i++) {
+ RfidConnector.CsReaderRfidData csReaderRfidData1 = csReaderConnector.rfidConnector.mRfidToWrite.get(i);
+ //appendToLog("BtDataOut " + i + " : 1 with rfidPayloadEvent0,1 = " + csReaderRfidData.rfidPayloadEvent.toString() + ", " + csReaderRfidData1.rfidPayloadEvent.toString());
+ if (csReaderRfidData.rfidPayloadEvent == csReaderRfidData1.rfidPayloadEvent) {
+ //appendToLog("BtDataOut " + i + " : 2 with dataValues = " + byteArrayToString(csReaderRfidData.dataValues));
+ //appendToLog("BtDataOut " + i + " : 2A with dataValues1 = " + byteArrayToString(csReaderRfidData1.dataValues));
+ if (csReaderRfidData.dataValues == null && csReaderRfidData1.dataValues == null) {
+ repeatRequest = true;
+ } else if (csReaderRfidData.dataValues != null && csReaderRfidData1.dataValues != null) {
+ if (csReaderRfidData.dataValues.length == csReaderRfidData1.dataValues.length) {
+ if (compareArray(csReaderRfidData.dataValues, csReaderRfidData1.dataValues, csReaderRfidData.dataValues.length)) {
+ repeatRequest = true;
+ } else if (csReaderRfidData.dataValues.length >= 8) {
+ int iCommand = (csReaderRfidData.dataValues[2] & 0xFF) * 256 + (csReaderRfidData.dataValues[3] & 0xFF);
+ int iVariableCount = csReaderRfidData.dataValues[7] & 0xFF;
+ int iLengthIndex = 10;
+ if (DEBUG) appendToLog("BtDataOut 70: iCommand = " + String.format("0x%04X", iCommand) + ", iVariableCount = " + iVariableCount);
+ if (iCommand == 0x9A06) {
+ int k = 0;
+ for (; k < csReaderRfidData.dataValues.length; k++) {
+ if (k == 4) { //skip
+ } else if ((byte) csReaderRfidData.dataValues[k] != (byte) csReaderRfidData1.dataValues[k]) {
+ if (DEBUG) appendToLog("7 mis-matched at position " + k);
+ break;
+ } else if (k == iLengthIndex) {
+ k += (csReaderRfidData.dataValues[k] & 0xFF);
+ iLengthIndex += 3;
+ if (DEBUG) appendToLog("7A k is updated to " + k);
+ }
+ }
+ if (k == csReaderRfidData.dataValues.length) {
+ if (DEBUG) appendToLog(" " + i + " : 8 with dataValues = " + byteArrayToString(csReaderRfidData.dataValues));
+ if (DEBUG) appendToLog(" " + i + " : 8A with dataValues1 = " + byteArrayToString(csReaderRfidData1.dataValues));
+ if (DEBUG) appendToLog("8 with matched data and remove the previous one");
+ csReaderConnector.rfidConnector.mRfidToWrite.remove(i);
+ break;
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ if (repeatRequest == false) {
+ csReaderConnector.rfidConnector.mRfidToWrite.add(csReaderRfidData);
+ if (DEBUG) appendToLog("BtDataOut: 9 added data with mRfidToWrite.size() = " + csReaderConnector.rfidConnector.mRfidToWrite.size());
+ if (DEBUG_PKDATA) appendToLog("PkData: add " + csReaderRfidData.rfidPayloadEvent + (csReaderRfidData.dataValues != null ? "." : "") + byteArrayToString(csReaderRfidData.dataValues)
+ + (csReaderRfidData.waitUplinkResponse ? " waitUplinkResponse" : "") + (csReaderRfidData.waitUplink1Response ? " waitUplink1Response" : "")
+ + " to mRfidToWrite with length = " + csReaderConnector.rfidConnector.mRfidToWrite.size());
+ } else if (DEBUG_PKDATA) appendToLog("!!! Skip repeated sending " + csReaderRfidData.rfidPayloadEvent + (csReaderRfidData.dataValues != null ? "." : "") + byteArrayToString(csReaderRfidData.dataValues));
+ }
+
+ byte[] dataValueTemp = null; int dataValueTempIndex = 0;
+ boolean inventoring = false;
+ public boolean isInventoring() { return inventoring; }
+ void setInventoring(boolean enable) { inventoring = enable; utility.debugFileEnable(false); if (true) appendToLog("setInventoring E710 is set as " + inventoring);}
+ boolean decode710Data(byte[] dataValue){
+ boolean DEBUG = false;
+ if (DEBUG) appendToLog("mRfidToWrite.size = " + csReaderConnector.rfidConnector.mRfidToWrite.size());
+ if (csReaderConnector.rfidConnector.mRfidToWrite.size() > 0) {
+ RfidConnector.CsReaderRfidData csReaderRfidData = csReaderConnector.rfidConnector.mRfidToWrite.get(0);
+ if (DEBUG) appendToLog("downlinkResponsed = " + csReaderRfidData.downlinkResponded + ", uplinkResponsed = " + csReaderRfidData.uplinkResponded);
+ if (csReaderRfidData.downlinkResponded || csReaderRfidData.uplinkResponded) {
+ boolean matched = false, updatedUplinkResponse = false;
+ if (DEBUG) appendToLog("mRfidToWrite.dataValue = " + byteArrayToString(csReaderRfidData.dataValues));
+ if (DEBUG) appendToLog("dataValue = " + byteArrayToString(dataValue));
+ if (DEBUG) appendToLog("MatchCheck, commandValueIndex = " + dataValueTempIndex);
+
+ if (dataValue.length < 7) {
+ appendToLog("!!! number of data received is less than 7"); //not debugged
+ return false;
+ }
+ if (dataValueTempIndex != 0) {
+ appendToLog("commandValueTempIndex = " + dataValueTempIndex + ", dataValue.length = " + dataValue.length + ", commandValueTemp.length = " + dataValueTemp.length);
+ if (dataValueTemp.length < dataValueTempIndex + dataValue.length) { //not debugged
+ appendToLog("!!! Data received is greater than expected in dataValueTemp");
+ return false;
+ } else {
+ System.arraycopy(dataValue, 0, dataValueTemp, dataValueTempIndex, dataValue.length);
+ dataValueTempIndex += dataValue.length;
+ if (dataValueTemp.length != dataValueTempIndex) {
+ appendToLog(" Data received is still not sufficient in dataValueTemp");
+ return false;
+ } else {
+ dataValue = dataValueTemp;
+ appendToLog("dataValueTemp is filled up as " + byteArrayToString(dataValue));
+ dataValueTempIndex = 0;
+ }
+ }
+ }
+
+ byte[] payloadValue = null;
+ int iCommandCode = (dataValue[2] & 0xFF) * 256 + (dataValue[3] & 0xFF);
+ int iLength = (dataValue[5] & 0xFF) * 256 + (dataValue[6] & 0xFF);
+ appendToLog("iCommandCode = " + String.format("0x%4X", iCommandCode) + ", iLength = " + iLength + ", LengthPayload = " + (dataValue.length - 7));
+
+ if (iLength < dataValue.length - 7) { //not debugged
+ appendToLog("!!! Data received is greater than expected in dataValue");
+ return false;
+ } else if (iLength != dataValue.length - 7) {
+ dataValueTemp = new byte[iLength + 7];
+ System.arraycopy(dataValue, 0, dataValueTemp, 0, dataValue.length);
+ dataValueTempIndex = dataValue.length;
+ appendToLog("stored dataValueTemp as " + byteArrayToString(dataValueTemp)); //not debugged
+ return false;
+ }
+
+ payloadValue = new byte[iLength];
+ appendToLog("Matched 2 with dataValue.length = " + dataValue.length + ", payloadValue.length = " + payloadValue.length);
+ System.arraycopy(dataValue, 7, payloadValue, 0, dataValue.length - 7);
+
+ if (csReaderRfidData.dataValues[0] == (byte)0x80
+ && csReaderRfidData.dataValues[1] == (byte)0xB3
+ && dataValue[0] == 0x51
+ && dataValue[1] == (byte)0xE2
+ && csReaderRfidData.dataValues[2] == dataValue[2]
+ && csReaderRfidData.dataValues[3] == dataValue[3]
+ && csReaderRfidData.dataValues[4] == dataValue[4]
+ ) {
+ appendToLog("Matched 0x51E2 with 0x80B3");
+ boolean valid = false;
+ if (DEBUG_PKDATA || true) appendToLog("PkData: found Rfid.Uplink.DataRead.CommandResponse" + (iLength != 0 ? " with payload = " + byteArrayToString(payloadValue) : ""));
+ if (DEBUG || true) appendToLog("found iCommandCode = " + String.format("0x%4X", iCommandCode) + ", iLength = " + iLength + ", payloadValue = " + byteArrayToString(payloadValue));
+ if ((iCommandCode == 0x10A1 && iLength == 0)
+ || (iCommandCode == 0x10A2 && iLength == 0)
+ || (iCommandCode == 0x10A3 && iLength == 0)
+ || (iCommandCode == 0x10A4 && iLength == 0)
+ || (iCommandCode == 0x10A5 && iLength == 0)
+ || (iCommandCode == 0x10A6 && iLength == 0)
+ || (iCommandCode == 0x10AE && iLength == 0)
+ || (iCommandCode == 0x10B1 && iLength == 0)
+ || (iCommandCode == 0x10B2 && iLength == 0)
+ || (iCommandCode == 0x10B7 && iLength == 0)
+ || (iCommandCode == 0x10B8 && iLength == 0)
+ || (iCommandCode == 0x10B9 && iLength == 0)
+ || (iCommandCode == 0x1471)
+ || (iCommandCode == 0x9A06)
+ ) valid = true;
+ String strCommandResponseType = null;
+ if (iCommandCode == 0x10A1) strCommandResponseType = "RfidStartSimpleInventory";
+ else if (iCommandCode == 0x10A2) strCommandResponseType = "RfidStartCompactInventory";
+ else if (iCommandCode == 0x10A3) strCommandResponseType = "RfidStartSelectInventory";
+ else if (iCommandCode == 0x10A4) strCommandResponseType = "RfidStartMBInventory";
+ else if (iCommandCode == 0x10A5) strCommandResponseType = "RfidStartSelectMBInventory";
+ else if (iCommandCode == 0x10A6) strCommandResponseType = "RfidStartSelectCompactInventory";
+ else if (iCommandCode == 0x10AE) strCommandResponseType = "RfidStopOperation";
+ else if (iCommandCode == 0x10B1) strCommandResponseType = "RfidReadMB";
+ else if (iCommandCode == 0x10B2) strCommandResponseType = "RfidWriteMB";
+ else if (iCommandCode == 0x10B7) strCommandResponseType = "RfidLock";
+ else if (iCommandCode == 0x10B8) strCommandResponseType = "RfidKill";
+ else if (iCommandCode == 0x10B9) strCommandResponseType = "RfidAuthenticate";
+ if (valid) {
+ appendToLog("waitUplink1Response is " + csReaderRfidData.waitUplink1Response);
+ if (csReaderRfidData.waitUplink1Response) {
+ csReaderConnector.rfidConnector.found = true;
+ csReaderRfidData.uplinkResponded = true; updatedUplinkResponse = true;
+ csReaderConnector.rfidConnector.mRfidToWrite.set(0, csReaderRfidData);
+ if (DEBUG_PKDATA) appendToLog("PkData: Rfid.Uplink.DataRead.CommandResponse_" + strCommandResponseType + " is processed to set mRfidToWrite.uplinkResponded and wait uplink data 1");
+ } else {
+ matched = true;
+ if (iCommandCode == 0x10A1) { if (DEBUG_PKDATA) appendToLog("PkData: uplink data is processed as CommandResponse.RfidStartSimpleInventory"); }
+ else if (iCommandCode == 0x10A2) { setInventoring(true); if (DEBUG_PKDATA) appendToLog("PkData: uplink data is processed as CommandResponse.RfidStartCompactInventory"); }
+ else if (iCommandCode == 0x10A3) { setInventoring(true); if (DEBUG_PKDATA) appendToLog("PkData: uplink data is processed as CommandResponse.RfidStartSelectInventory"); }
+ else if (iCommandCode == 0x10A4) { setInventoring(true); if (DEBUG_PKDATA) appendToLog("PkData: uplink data is processed as CommandResponse.RfidStartMBInventory"); }
+ else if (iCommandCode == 0x10A5) { setInventoring(true); if (DEBUG_PKDATA) appendToLog("PkData: uplink data is processed as CommandResponse.RfidStartSelectMBInventory"); }
+ else if (iCommandCode == 0x10A6) { setInventoring(true); if (DEBUG_PKDATA) appendToLog("PkData: uplink data is processed as CommandResponse.RfidStartSelectCompactInventory"); }
+ else if (iCommandCode == 0x10AE) { if (DEBUG_PKDATA) appendToLog("PkData: uplink data is processed as CommandResponse.RfidStopOperation"); }
+ else if (iCommandCode == 0x10B1) { if (DEBUG_PKDATA) appendToLog("PkData: uplink data is processed as CommandResponse.RfidReadMB"); }
+ else if (iCommandCode == 0x10B2) { if (DEBUG_PKDATA) appendToLog("PkData: uplink data is processed as CommandResponse.RfidWriteMB"); }
+ else if (iCommandCode == 0x10B7) { if (DEBUG_PKDATA) appendToLog("PkData: uplink data is processed as CommandResponse.RfidLock"); }
+ else if (iCommandCode == 0x10B8) { if (DEBUG_PKDATA) appendToLog("PkData: uplink data is processed as CommandResponse.RfidKill"); }
+ else if (iCommandCode == 0x10B9) { if (DEBUG_PKDATA) appendToLog("PkData: uplink data is processed as CommandResponse.RfidAuthenticate"); }
+ //else if ((iCommandCode & 0x7F00) == 0x1000) { if (DEBUG_PKDATA) appendToLog("PkData: uplink data is processed as CommandResponse.RFID??? !!!"); }
+ else if (iCommandCode == 0x1471 || iCommandCode == 0x9A06) {
+ int iRegAddr = (csReaderRfidData.dataValues[8] & 0xFF) * 256 + (csReaderRfidData.dataValues[9] & 0xFF);
+ boolean bprocessed = false;
+ if (DEBUG) appendToLog(String.format("1 iCommandCode = 0x%X with iRegAddr = 0x%X", iCommandCode, iRegAddr));
+ if (iCommandCode == 0x9A06) {
+ if (DEBUG) appendToLog(String.format("2 CommandCode = 0x%X is processed here", iCommandCode));
+ bprocessed = true;
+ } else { //not debugged
+ int iNumberExpected = csReaderRfidData.dataValues[7];
+ int iLengthExpected = 0;
+ for (int i = 0; i < iNumberExpected; i++) {
+ iLengthExpected += csReaderRfidData.dataValues[10 + i * 3];
+ }
+ appendToLog("ReaderChipE710.decode710Data, iNumberExpected = " + iNumberExpected + ", iLengthExpected = " + iLengthExpected);
+ if (iLengthExpected == iLength) {
+ appendToLog("Matched iLengthExpected");
+ byte[] commandValue0 = new byte[payloadValue.length]; int indexCommandValue0 = 0;
+ System.arraycopy(payloadValue, 0, commandValue0, 0, commandValue0.length);
+ for (int k = 0; k < iNumberExpected; k++) {
+ iRegAddr = (csReaderRfidData.dataValues[8 + k * 3] & 0xFF) * 256 + (csReaderRfidData.dataValues[9 + k * 3] & 0xFF);
+ payloadValue = new byte[csReaderRfidData.dataValues[10 + k * 3]];
+ System.arraycopy(commandValue0, indexCommandValue0, payloadValue, 0, payloadValue.length); indexCommandValue0 += payloadValue.length;
+ if (DEBUG) appendToLog("k = " + k + ", " + String.format("2 iRegAddr = 0x%X", iRegAddr) + ", data = " + byteArrayToString(payloadValue));
+ if (iRegAddr == 8) {
+ if (DEBUG) appendToLog("2 iCommandCode");
+ try {
+ rx000Setting.macVer = new String(payloadValue, StandardCharsets.UTF_8).trim();
+ bprocessed = true;
+ if (false)
+ appendToLog("macVer = " + rx000Setting.macVer);
+ } catch (Exception e) {
+ //throw new RuntimeException(e);
+ }
+ } else if (iRegAddr == 0x28 && payloadValue.length >= 3) {
+ int iValue = 0;
+ for (int i = 0, increment = 1; i < payloadValue.length; i++, increment *= 10) {
+ iValue = payloadValue[payloadValue.length - 1 - i] * increment;
+ }
+ rx000Setting.macVerBuild = iValue;
+ bprocessed = true;
+ if (true)
+ appendToLog("macVerBuild = " + rx000Setting.macVerBuild);
+ } else if (iRegAddr == 0x3014) {
+ rx000Setting.countryEnum = payloadValue;
+ bprocessed = true;
+ if (true)
+ appendToLog("countryEnum = " + byteArrayToString(rx000Setting.countryEnum));
+ } else if (iRegAddr == 0x3018) {
+ rx000Setting.frequencyChannelIndex = payloadValue;
+ bprocessed = true;
+ if (true)
+ appendToLog("frequencyChannelIndex = " + byteArrayToString(rx000Setting.frequencyChannelIndex));
+ } else if (iRegAddr >= 0x3030 && iRegAddr < 0x3030 + 16 * 16) {
+ int iPort = 0, iOffset = 0, iWidth = 0;
+ for (iPort = 0; iPort < 16; iPort++) {
+ if (DEBUG)
+ appendToLog("antennaPortConfig: iPort = " + iPort + String.format(", iRegAddr = 0x%04X", iRegAddr));
+ if (iRegAddr < 0x3030 + (iPort + 1) * 16) break;
+ }
+ iOffset = iRegAddr - 0x3030 - iPort * 16;
+ if (DEBUG)
+ appendToLog("antennaPortConfig: iOffset = " + iOffset);
+ iWidth = payloadValue.length;
+ if (DEBUG)
+ appendToLog("antennaPortConfig: iWidth = " + iWidth);
+ if (iOffset == 0 && iWidth == 16) {
+ rx000Setting.antennaPortConfig[iPort] = payloadValue;
+ bprocessed = true;
+ if (false)
+ appendToLog("antennaPortConfig[" + iPort + "] = " + byteArrayToString(rx000Setting.antennaPortConfig[iPort]));
+ } else
+ appendToLog("!!! CANNOT handle with iPort = " + iPort + ", iOffset = " + iOffset + ", iWidth = " + iWidth);
+ } else if (iRegAddr >= 0x3140 && iRegAddr < 0x3140 + 42 * 7) {
+ int index = 0, iOffset = 0, iWidth = 0;
+ for (index = 0; index < 7; index++) {
+ if (DEBUG)
+ appendToLog("selectConfiguration: index = " + index + String.format(", iRegAddr = 0x%04X", iRegAddr));
+ if (iRegAddr < 0x3140 + (index + 1) * 42) break;
+ }
+ iOffset = iRegAddr - 0x3140 - index * 42;
+ if (DEBUG)
+ appendToLog("selectConfiguration: iOffset = " + iOffset);
+ iWidth = payloadValue.length;
+ if (DEBUG)
+ appendToLog("selectConfiguration: iWidth = " + iWidth);
+ if (iOffset == 0 && iWidth == 42) {
+ rx000Setting.selectConfiguration[index] = payloadValue;
+ bprocessed = true;
+ if (false)
+ appendToLog("selectConfiguration[" + index + "] = " + byteArrayToString(rx000Setting.selectConfiguration[index]));
+ } else
+ appendToLog("!!! CANNOT handle with index = " + index + ", iOffset = " + iOffset + ", iWidth = " + iWidth);
+ } else if (iRegAddr >= 0x3270 && iRegAddr < 0x3270 + 7 * 3) {
+ int index = 0, iOffset = 0, iWidth = 0, iPortStartAddr = 0x3270, iPortSize = 7;
+ for (index = 0; index < 3; index++) {
+ if (DEBUG)
+ appendToLog("multibankReadConfig: index = " + index + String.format(", iRegAddr = 0x%04X", iRegAddr));
+ if (iRegAddr < iPortStartAddr + (index + 1) * iPortSize) break;
+ }
+ iOffset = iRegAddr - iPortStartAddr - index * iPortSize;
+ if (DEBUG)
+ appendToLog("multibankReadConfig: iOffset = " + iOffset);
+ iWidth = payloadValue.length;
+ if (DEBUG)
+ appendToLog("multibankReadConfig: iWidth = " + iWidth);
+ if (iOffset == 0 && iWidth == iPortSize) {
+ rx000Setting.multibankReadConfig[index] = payloadValue;
+ bprocessed = true;
+ if (false)
+ appendToLog("multibankReadConfig[" + index + "] = " + byteArrayToString(rx000Setting.multibankReadConfig[index]));
+ } else
+ appendToLog("!!! CANNOT handle with index = " + index + ", iOffset = " + iOffset + ", iWidth = " + iWidth);
+ } else if (iRegAddr == 0x38A6) {
+ rx000Setting.accessPassword = payloadValue;
+ bprocessed = true;
+ if (false) appendToLog("accessPassword = " + byteArrayToString(rx000Setting.accessPassword));
+ } else if (iRegAddr == 0x38AA) {
+ rx000Setting.killPassword = payloadValue;
+ bprocessed = true;
+ if (false) appendToLog("killPassword = " + byteArrayToString(rx000Setting.killPassword));
+ } else if (iRegAddr == 0x3900) {
+ rx000Setting.dupElimRollWindow = payloadValue;
+ bprocessed = true;
+ if (false) appendToLog("dupElimDelay = " + byteArrayToString(rx000Setting.dupElimRollWindow));
+ } else if (iRegAddr == 0x3906) {
+ rx000Setting.eventPacketUplnkEnable = payloadValue;
+ bprocessed = true;
+ if (false) appendToLog("eventPacketUplnkEnable = " + byteArrayToString(rx000Setting.eventPacketUplnkEnable));
+ } else if (iRegAddr == 0x3908) {
+ rx000Setting.intraPacketDelay = payloadValue;
+ bprocessed = true;
+ if (false) appendToLog("intraPacketDelay = " + byteArrayToString(rx000Setting.intraPacketDelay));
+ } else if (iRegAddr == 0x3948) {
+ rx000Setting.currentPort = payloadValue;
+ bprocessed = true;
+ if (true) appendToLog("currentPort = " + byteArrayToString(rx000Setting.currentPort));
+ } else if (iRegAddr == 0x5000) {
+ rx000Setting.modelCode = payloadValue;
+ bprocessed = true;
+ if (false)
+ appendToLog("modelCode = " + byteArrayToString(rx000Setting.modelCode));
+ } else if (iRegAddr == 0x5020) {
+ rx000Setting.productSerialNumber = payloadValue;
+ bprocessed = true;
+ if (false)
+ appendToLog("productSerialNumber = " + byteArrayToString(rx000Setting.productSerialNumber));
+ } else if (iRegAddr == 0x5040) {
+ rx000Setting.countryEnumOem = payloadValue;
+ bprocessed = true;
+ if (true)
+ appendToLog("countryEnumOem = " + byteArrayToString(rx000Setting.countryEnumOem));
+ } else if (iRegAddr == 0xEF98) {
+ rx000Setting.countryCodeOem = payloadValue;
+ bprocessed = true;
+ if (false)
+ appendToLog("countryCodeOem = " + byteArrayToString(rx000Setting.countryCodeOem));
+ } else if (iRegAddr == 0xEF9C) {
+ rx000Setting.boardSerialNumber = payloadValue;
+ bprocessed = true;
+ if (true)
+ appendToLog("boardSerialNumber = " + byteArrayToString(rx000Setting.boardSerialNumber));
+ } else if (iRegAddr == 0xEFAC) {
+ rx000Setting.specialcountryCodeOem = payloadValue;
+ bprocessed = true;
+ if (false)
+ appendToLog("specialcountryCodeOem = " + byteArrayToString(rx000Setting.specialcountryCodeOem));
+ } else if (iRegAddr == 0xEFB0) {
+ rx000Setting.freqModifyCode = payloadValue;
+ bprocessed = true;
+ if (false)
+ appendToLog("freqModifyCode = " + byteArrayToString(rx000Setting.freqModifyCode));
+ }
+ }
+ }
+ }
+
+ if (bprocessed) {
+ if (DEBUG_PKDATA) {
+ if (iCommandCode == 0x9A06)
+ appendToLog("PkData: Rfid.Uplink.DataRead.CommandResponse_WriteRegister with result " + byteArrayToString(payloadValue) + " is processed for register address = " + String.format("0x%X", iRegAddr));
+ else if (iCommandCode == 0x1471)
+ appendToLog("PkData: Rfid.Uplink.DataRead.CommandResponse_ReadRegister with result " + byteArrayToString(payloadValue) + " is processed for register address = " + String.format("0x%X", iRegAddr));
+ else { //not debugged
+ appendToLog("PkData: Rfid.Uplink.DataRead.CommandResponse_xxx with result " + byteArrayToString(payloadValue) + " is processed");
+ }
+ }
+ } else {//not debugged
+ appendToLog("!!! Rfid.Uplink.DataRead.CommandResponse_ReadRegister CANNOT be processed for register address = " + String.format("0x%X", iRegAddr));
+ }
+ } else { //not debuggged
+ appendToLog(String.format("!!! Rfid.Uplink.DataRead.CommandResponse_%X CANNOT be processed", iCommandCode));
+ }
+ }
+ } else appendToLog("!!! Rfid.Uplink.DataRead.CommandResponse CANNOT be processed"); //not debugged
+ } else if (csReaderRfidData.dataValues[0] == (byte)0x80
+ && csReaderRfidData.dataValues[1] == (byte)0xB3
+ && dataValue[0] == 0x49
+ && dataValue[1] == (byte)0xDC
+ //&& csReaderRfidData.dataValues[4] == dataValue[4] //dataValue[4] == 0
+ ) {
+ if (DEBUG) appendToLog("Ready 0 with iCommandCode = " + String.format("0x%04X", iCommandCode));
+ if (true || dataValue.length == 7 + iLength) {
+ byte[] dataValues1 = new byte[iLength];
+ System.arraycopy(dataValue, 7, dataValues1, 0, dataValues1.length);
+ if (iCommandCode == 0x3008) {
+ setInventoring(false);
+ appendToLogView("isRfidToRead_3008: " + byteArrayToString(dataValue));
+ if (DEBUG) appendToLog("Ready 2");
+ if (DEBUG_PKDATA)
+ appendToLog("PkData: found Rfid.Uplink.DataRead.UplinkPackage_Event_csl_operation_complete with payload = " + byteArrayToString(dataValues1));
+ if (csReaderRfidData.dataValues[2] == dataValues1[4]
+ && csReaderRfidData.dataValues[3] == dataValues1[5]) {
+ if (DEBUG) appendToLog("Ready 3");
+
+ int iStatus = dataValues1[6] * 256 + dataValues1[7];
+ if (csReaderRfidData.uplinkResponded) {
+ matched = true;
+ if (DEBUG_PKDATA)
+ appendToLog("PkData: Rfid.Uplink.DataRead.UplinkPackage_Event_csl_operation_complete is processed with status = " + String.format("%04X", iStatus));
+ }
+ } else appendToLog("!!! mismatched command code"); //not debugged
+ }
+ }
+ } //not debugged
+
+ appendToLog("Ending matched = " + matched + ", updatedUplinkResponse = " + updatedUplinkResponse);
+ if (matched) {
+ csReaderConnector.rfidConnector.found = true;
+ csReaderConnector.rfidConnector.mRfidToWrite.remove(0); csReaderConnector.rfidConnector.sendRfidToWriteSent = 0; csReaderConnector.rfidConnector.mRfidToWriteRemoved = true;
+ if (DEBUG_PKDATA) appendToLog("PkData: new mRfidToWrite size = " + csReaderConnector.rfidConnector.mRfidToWrite.size());
+ appendToLog("RfidReaderChipE710.decode710Data, UsbData: remove one");
+ }
+ if (matched || updatedUplinkResponse) return true;
+ }
+ }
+ return false;
+ }
+}
+
+
+
+package com.csl.cslibrary4a;
+
+import static java.lang.Math.log10;
+import static java.lang.Math.pow;
+
+import android.content.Context;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Date;
+
+public class RfidReaderChipR2000 {
+ boolean DEBUG_PKDATA, DEBUG;
+ boolean sameCheck = true;
+ //RfidReaderChip mRfidReaderChip;
+ boolean DEBUGTHREAD = false;
+ int intervalRx000UplinkHandler;
+ public int invalidUpdata; //invalidata, invalidUpdata, validata;
+ boolean aborting = false;
+ Context context; Utility utility; CsReaderConnector csReaderConnector;
+ public RfidReaderChipR2000(Context context, Utility utility, CsReaderConnector csReaderConnector) {
+ this.context = context;
+ this.utility = utility;
+ appendToLog("csReaderConnector 1 is " + (csReaderConnector == null ? "null" : "valid"));
+ this.csReaderConnector = csReaderConnector;
+ this.DEBUGTHREAD = csReaderConnector.DEBUGTHREAD;
+ this.intervalRx000UplinkHandler = csReaderConnector.intervalRx000UplinkHandler;
+ }
+ private String byteArrayToString(byte[] packet) { return utility.byteArrayToString(packet); }
+ private boolean compareArray(byte[] array1, byte[] array2, int length) { return utility.compareByteArray(array1, array2, length); }
+ private void appendToLog(String s) { utility.appendToLog(s); }
+ private void appendToLogView(String s) { utility.appendToLogView(s); }
+ void writeDebug2File(String stringDebug) { utility.writeDebug2File(stringDebug); }
+ public enum ControlCommands {
+ NULL,
+ CANCEL, SOFTRESET, ABORT, PAUSE, RESUME, GETSERIALNUMBER, RESETTOBOOTLOADER
+ }
+ enum HostRegRequests {
+ MAC_OPERATION,
+ //MAC_VER, MAC_LAST_COMMAND_DURATION,
+ //HST_CMNDIAGS,
+ //HST_MBP_ADDR, HST_MBP_DATA,
+ //HST_OEM_ADDR, HST_OEM_DATA,
+ HST_ANT_CYCLES, HST_ANT_DESC_SEL, HST_ANT_DESC_CFG, MAC_ANT_DESC_STAT, HST_ANT_DESC_PORTDEF, HST_ANT_DESC_DWELL, HST_ANT_DESC_RFPOWER, HST_ANT_DESC_INV_CNT,
+ HST_TAGMSK_DESC_SEL, HST_TAGMSK_DESC_CFG, HST_TAGMSK_BANK, HST_TAGMSK_PTR, HST_TAGMSK_LEN, HST_TAGMSK_0_3,
+ HST_QUERY_CFG, HST_INV_CFG, HST_INV_SEL, HST_INV_ALG_PARM_0, HST_INV_ALG_PARM_1, HST_INV_ALG_PARM_2, HST_INV_ALG_PARM_3, HST_INV_RSSI_FILTERING_CONFIG, HST_INV_RSSI_FILTERING_THRESHOLD, HST_INV_RSSI_FILTERING_COUNT, HST_INV_EPC_MATCH_CFG, HST_INV_EPCDAT_0_3,
+ HST_TAGACC_DESC_CFG, HST_TAGACC_BANK, HST_TAGACC_PTR, HST_TAGACC_CNT, HST_TAGACC_LOCKCFG, HST_TAGACC_ACCPWD, HST_TAGACC_KILLPWD, HST_TAGWRDAT_SEL, HST_TAGWRDAT_0,
+ HST_RFTC_CURRENT_PROFILE,
+ HST_RFTC_FRQCH_SEL, HST_RFTC_FRQCH_CFG, HST_RFTC_FRQCH_DESC_PLLDIVMULT, HST_RFTC_FRQCH_DESC_PLLDACCTL, HST_RFTC_FRQCH_CMDSTART,
+ HST_AUTHENTICATE_CFG, HST_AUTHENTICATE_MSG, HST_READBUFFER_LEN, HST_UNTRACEABLE_CFG,
+ HST_CMD
+ }
+ public class Rx000Setting {
+ Rx000Setting(boolean set_default_setting) {
+ if (set_default_setting) {
+ macVer = mDefault.macVer;
+ //diagnosticCfg = mDefault.diagnosticCfg;
+ oemAddress = mDefault.oemAddress;
+
+ //RFTC block paramters
+ currentProfile = mDefault.currentProfile;
+
+ // Antenna block parameters
+ antennaCycle = mDefault.antennaCycle;
+ antennaFreqAgile = mDefault.antennaFreqAgile;
+ antennaSelect = mDefault.antennaSelect;
+ }
+ antennaSelectedData = new AntennaSelectedData[ANTSELECT_MAX + 1];
+ for (int i = 0; i < antennaSelectedData.length; i++) {
+ int default_setting_type = 0;
+ if (set_default_setting) {
+ if (i == 0) default_setting_type = 1;
+ else if (i >= 1 && i <= 3) default_setting_type = 2;
+ else if (i >= 4 && i <= 7) default_setting_type = 3;
+ else if (i >= 8 && i <= 11) default_setting_type = 4;
+ else default_setting_type = 5;
+ }
+ antennaSelectedData[i] = new AntennaSelectedData(set_default_setting, default_setting_type);
+ }
+
+ //Tag select block parameters
+ if (set_default_setting) invSelectIndex = 0;
+ invSelectData = new InvSelectData[INVSELECT_MAX + 1];
+ for (int i = 0; i < invSelectData.length; i++) {
+ invSelectData[i] = new InvSelectData(set_default_setting);
+ }
+
+ if (set_default_setting) {
+ //Inventtory block paraameters
+ //queryTarget = mDefault.queryTarget;
+ //querySession = mDefault.querySession;
+ //querySelect = mDefault.querySelect;
+ //appendToLog("BtDataOut: RfidReaderChipR2000.Rx000Setting new querySelect = " + querySelect);
+ //invAlgo = mDefault.invAlgo;
+ matchRep = mDefault.matchRep;
+ tagSelect = mDefault.tagSelect;
+ noInventory = mDefault.noInventory;
+ tagDelay = mDefault.tagDelay;
+ invModeCompact = mDefault.tagJoin;
+ invBrandId = mDefault.brandid;
+ invAuthenticate = mDefault.invAuthenticate;
+ }
+
+ if (set_default_setting) algoSelect = 3;
+ algoSelectedData = new AlgoSelectedData[ALGOSELECT_MAX + 1];
+ for (int i = 0; i < algoSelectedData.length; i++) {//0 for invalid default, 1 for 0, 2 for 1, 3 for 2, 4 for 3
+ int default_setting_type = 0;
+ if (set_default_setting) {
+ default_setting_type = i + 1;
+ }
+ algoSelectedData[i] = new AlgoSelectedData(set_default_setting, default_setting_type);
+ }
+
+ if (set_default_setting) {
+ rssiFilterType = mDefault.rssiFilterType;
+ rssiFilterOption = mDefault.rssiFilterOption;
+ rssiFilterThreshold1 = mDefault.rssiFilterThreshold;
+ rssiFilterThreshold2 = mDefault.rssiFilterThreshold;
+ rssiFilterCount = mDefault.rssiFilterCount;
+
+ matchEnable = mDefault.matchEnable;
+ matchType = mDefault.matchType;
+ matchLength = mDefault.matchLength;
+ matchOffset = mDefault.matchOffset;
+ invMatchDataReady = mDefault.invMatchDataReady;
+
+ //Tag access block parameters
+ accessRetry = mDefault.accessRetry;
+ accessBank = mDefault.accessBank; accessBank2 = mDefault.accessBank2;
+ accessOffset = mDefault.accessOffset; accessOffset2 = mDefault.accessOffset2;
+ //accessCount = mDefault.accessCount; accessCount2 = mDefault.accessCount2;
+ accessLockAction = mDefault.accessLockAction;
+ accessLockMask = mDefault.accessLockMask;
+ //long accessPassword = 0;
+ //long killPassword = 0;
+ accessWriteDataSelect = mDefault.accessWriteDataSelect;
+ accWriteDataReady = mDefault.accWriteDataReady;
+
+ authMatchDataReady = mDefault.authMatchDataReady;
+ }
+
+ invMatchData0_63 = new byte[4 * 16];
+ accWriteData0_63 = new byte[4 * 16 * 2];
+ authMatchData0_63 = new byte[4 * 4];
+ }
+
+ class Rx000Setting_default {
+ String macVer;
+ int diagnosticCfg = 0x210;
+ int mbpAddress = 0; // ?
+ int mbpData = 0; // ?
+ int oemAddress = 4; // ?
+ int oemData = 0; // ?
+
+ //RFTC block paramters
+ int currentProfile = 1;
+ int freqChannelSelect = 0;
+
+ // Antenna block parameters
+ int antennaCycle = 1;
+ int antennaFreqAgile = 0;
+ int antennaSelect = 0;
+
+ //Tag select block parameters
+ int invSelectIndex = 0;
+
+ //Inventtory block paraameters
+ int queryTarget = 0;
+ int querySession = 2;
+ int querySelect = 1;
+ int invAlgo = 3;
+ int matchRep = 0;
+ int tagSelect = 0;
+ int noInventory = 0;
+ int tagRead = 0;
+ int tagDelay = 0;
+ int tagJoin = 0;
+ int brandid = 0;
+ int invAuthenticate = 0;
+ int algoSelect = 3;
+
+ int rssiFilterType = 0;
+ int rssiFilterOption = 0;
+ int rssiFilterThreshold = 0;
+ long rssiFilterCount = 0;
+
+ int matchEnable = 0;
+ int matchType = 0;
+ int matchLength = 0;
+ int matchOffset = 0;
+ byte[] invMatchData0_63; int invMatchDataReady = 0;
+
+ //Tag access block parameters
+ int accessRetry = 3;
+ int accessBank = 1; int accessBank2 = 0;
+ int accessOffset = 2; int accessOffset2 = 0;
+ int accessCount = 1; int accessCount2 = 0;
+ int accessLockAction = 0;
+ int accessLockMask = 0;
+ //long accessPassword = 0;
+ // long killPassword = 0;
+ int accessWriteDataSelect = 0;
+ byte[] accWriteData0_63; int accWriteDataReady = 0;
+
+ byte[] authMatchData; int authMatchDataReady = 0;
+ }
+ Rx000Setting_default mDefault = new Rx000Setting_default();
+
+ public boolean readMAC(int address) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 0, 0, 0, 0, 0, 0};
+ msgBuffer[2] = (byte) (address % 256);
+ msgBuffer[3] = (byte) ((address >> 8) % 256);
+ if (false) appendToLog("readMac buffer = " + byteArrayToString(msgBuffer));
+ return sendHostRegRequest(HostRegRequests.MAC_OPERATION, false, msgBuffer);
+ }
+ public boolean writeMAC(int address, long value) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 0, 0, 0, 0, 0, 0};
+ msgBuffer[2] = (byte) (address % 256);
+ msgBuffer[3] = (byte) ((address >> 8) % 256);
+ msgBuffer[4] = (byte) (value % 256);
+ msgBuffer[5] = (byte) ((value >> 8) % 256);
+ msgBuffer[6] = (byte) ((value >> 16) % 256);
+ msgBuffer[7] = (byte) ((value >> 24) % 256);
+ if (false) appendToLog("writeMac buffer = " + byteArrayToString(msgBuffer));
+ return sendHostRegRequest(HostRegRequests.MAC_OPERATION, true, msgBuffer);
+ }
+
+ String macVer = null; int macVerBuild = 0;
+ public String getMacVer() {
+ if (macVer == null) {
+ readMAC(0);
+ return "";
+ } else {
+ return macVer;
+ }
+ }
+
+ long mac_last_command_duration;
+ long getMacLastCommandDuration(boolean request) {
+ if (request) {
+ if (true) readMAC(9);
+ //byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 9, 0, 0, 0, 0, 0};
+ //mRfidDevice.mRx000Device.sendHostRegRequest(HostRegRequests.MAC_LAST_COMMAND_DURATION, false, msgBuffer);
+ }
+ return mac_last_command_duration;
+ }
+
+ final int DIAGCFG_INVALID = -1; final int DIAGCFG_MIN = 0; final int DIAGCFG_MAX = 0x3FF;
+ int diagnosticCfg = DIAGCFG_INVALID;
+ public int getDiagnosticConfiguration() {
+ if (diagnosticCfg < DIAGCFG_MIN || diagnosticCfg > DIAGCFG_MAX) {
+ if (true) readMAC(0x201);
+ //byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 1, 2, 0, 0, 0, 0};
+ //mRfidDevice.mRx000Device.sendHostRegRequest(HostRegRequests.HST_CMNDIAGS, false, msgBuffer);
+ }
+ return diagnosticCfg;
+ }
+ public boolean setDiagnosticConfiguration(boolean bCommmandActive) {
+ int diagnosticCfgNew = diagnosticCfg;
+ diagnosticCfgNew &= ~0x0200; if (bCommmandActive) diagnosticCfgNew |= 0x200;
+ if (diagnosticCfg == diagnosticCfgNew && sameCheck) return true;
+ diagnosticCfg = diagnosticCfgNew;
+ return writeMAC(0x201, diagnosticCfgNew); //mRfidDevice.mRx000Device.sendHostRegRequest(HostRegRequests.HST_CMNDIAGS, true, msgBuffer);
+ }
+
+ int impinjExtensionValue = -1;
+ public int getImpinjExtension() {
+ if (antennaSelect < ANTSLECT_MIN || antennaSelect > ANTSELECT_MAX) {
+ return ANTSELECT_INVALID;
+ } else {
+ {
+ if (impinjExtensionValue < 0) readMAC(0x203);
+ return impinjExtensionValue;
+ }
+ }
+ }
+ public boolean setImpinjExtension(boolean tagFocus, boolean fastId) {
+ int iValue = (tagFocus ? 0x10 : 0) | (fastId ? 0x20 : 0);
+ if (impinjExtensionValue == iValue && sameCheck) return true;
+ appendToLog("BtDataOut 11: ivalue = " + iValue + ", impinjExtensionValue = " + rx000Setting.impinjExtensionValue);
+ boolean bRetValue = writeMAC(0x203, iValue);
+ if (bRetValue) impinjExtensionValue = iValue;
+ return bRetValue;
+ }
+
+ int pwrMgmtStatus = -1;
+ void getPwrMgmtStatus() {
+ if (false) appendToLog("pwrMgmtStatus: getPwrMgmtStatus ");
+ pwrMgmtStatus = -1; readMAC(0x204);
+ }
+
+ final int MBPADDR_INVALID = -1; final int MBPADDR_MIN = 0; final int MBPADDR_MAX = 0x1FFF;
+ long mbpAddress = MBPADDR_INVALID;
+ boolean setMBPAddress(long mbpAddress) {
+ //byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 0, 4, 0, 0, 0, 0};
+ if (mbpAddress < MBPADDR_MIN || mbpAddress > MBPADDR_MAX) return false;
+ //mbpAddress = mDefault.mbpAddress;
+ if (this.mbpAddress == mbpAddress && sameCheck) return true;
+ //msgBuffer[4] = (byte) (mbpAddress % 256);
+ //msgBuffer[5] = (byte) ((mbpAddress >> 8) % 256);
+ this.mbpAddress = mbpAddress;
+ if (false) appendToLog("Going to writeMAC");
+ return writeMAC(0x400, (int) mbpAddress); //mRfidDevice.mRx000Device.sendHostRegRequest(HostRegRequests.HST_MBP_ADDR, true, msgBuffer);
+ }
+
+ final int MBPDATA_INVALID = -1; final int MBPDATA_MIN = 0; final int MBPDATA_MAX = 0x1FFF;
+ long mbpData = MBPDATA_INVALID;
+ boolean setMBPData(long mbpData) {
+ //byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 1, 4, 0, 0, 0, 0};
+ if (mbpData < MBPADDR_MIN || mbpData > MBPADDR_MAX) return false;
+ //mbpData = mDefault.mbpData;
+ if (this.mbpData == mbpData && sameCheck) return true;
+ //msgBuffer[4] = (byte) (mbpData % 256);
+ //msgBuffer[5] = (byte) ((mbpData >> 8) % 256);
+ this.mbpData = mbpData;
+ return writeMAC(0x401, (int) mbpData); //mRfidDevice.mRx000Device.sendHostRegRequest(HostRegRequests.HST_MBP_DATA, true, msgBuffer);
+ }
+
+ final int OEMADDR_INVALID = -1; final int OEMADDR_MIN = 0; final int OEMADDR_MAX = 0x1FFF;
+ long oemAddress = OEMADDR_INVALID;
+ boolean setOEMAddress(long oemAddress) {
+ //byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 0, 5, 0, 0, 0, 0};
+ if (oemAddress < OEMADDR_MIN || oemAddress > OEMADDR_MAX) return false;
+ //oemAddress = mDefault.oemAddress;
+ if (this.oemAddress == oemAddress && sameCheck) return true;
+ //msgBuffer[4] = (byte) (oemAddress % 256);
+ //msgBuffer[5] = (byte) ((oemAddress >> 8) % 256);
+ this.oemAddress = oemAddress;
+ return writeMAC(0x500, (int) oemAddress); //mRfidDevice.mRx000Device.sendHostRegRequest(HostRegRequests.HST_OEM_ADDR, true, msgBuffer);
+ }
+
+ final int OEMDATA_INVALID = -1; final int OEMDATA_MIN = 0; final int OEMDATA_MAX = 0x1FFF;
+ long oemData = OEMDATA_INVALID;
+ boolean setOEMData(long oemData) {
+ //byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 1, 5, 0, 0, 0, 0};
+ if (oemData < OEMADDR_MIN || oemData > OEMADDR_MAX) return false;
+ //oemData = mDefault.oemData;
+ if (this.oemData == oemData && sameCheck) return true;
+ //msgBuffer[4] = (byte) (oemData % 256);
+ //msgBuffer[5] = (byte) ((oemData >> 8) % 256);
+ this.oemData = oemData;
+ return writeMAC(0x501, (int) oemData); //mRfidDevice.mRx000Device.sendHostRegRequest(HostRegRequests.HST_OEM_DATA, true, msgBuffer);
+ }
+
+ // Antenna block parameters
+ final int ANTCYCLE_INVALID = -1; final int ANTCYCLE_MIN = 0; final int ANTCYCLE_MAX = 0xFFFF;
+ int antennaCycle = ANTCYCLE_INVALID;
+ public int getAntennaCycle() {
+ if (antennaCycle < ANTCYCLE_MIN || antennaCycle > ANTCYCLE_MAX) getHST_ANT_CYCLES();
+ return antennaCycle;
+ }
+ public boolean setAntennaCycle(int antennaCycle) {
+ return setAntennaCycle(antennaCycle, antennaFreqAgile);
+ }
+ boolean setAntennaCycle(int antennaCycle, int antennaFreqAgile) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 0, 7, 0, 0, 0, 0};
+ if (antennaCycle < ANTCYCLE_MIN || antennaCycle > ANTCYCLE_MAX) antennaCycle = mDefault.antennaCycle;
+ if (antennaFreqAgile < FREQAGILE_MIN || antennaFreqAgile > FREQAGILE_MAX) antennaFreqAgile = mDefault.antennaFreqAgile;
+ if (this.antennaCycle == antennaCycle && this.antennaFreqAgile == antennaFreqAgile && sameCheck) return true;
+ msgBuffer[4] = (byte) (antennaCycle % 256);
+ msgBuffer[5] = (byte) ((antennaCycle >> 8) % 256);
+ if (antennaFreqAgile != 0) {
+ msgBuffer[7] |= 0x01;
+ }
+ this.antennaCycle = antennaCycle;
+ this.antennaFreqAgile = antennaFreqAgile;
+ return sendHostRegRequest(HostRegRequests.HST_ANT_CYCLES, true, msgBuffer);
+ }
+
+ final int FREQAGILE_INVALID = -1; final int FREQAGILE_MIN = 0; final int FREQAGILE_MAX = 1;
+ int antennaFreqAgile = FREQAGILE_INVALID;
+ int getAntennaFreqAgile() {
+ if (antennaFreqAgile < FREQAGILE_MIN || antennaFreqAgile > FREQAGILE_MAX)
+ getHST_ANT_CYCLES();
+ return antennaFreqAgile;
+ }
+ public boolean setAntennaFreqAgile(int freqAgile) {
+ return setAntennaCycle(antennaCycle, freqAgile);
+ }
+
+ private boolean getHST_ANT_CYCLES() {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 0, 7, 0, 0, 0, 0};
+ return sendHostRegRequest(HostRegRequests.HST_ANT_CYCLES, false, msgBuffer);
+ }
+
+ final int ANTSELECT_INVALID = -1; final int ANTSLECT_MIN = 0; final int ANTSELECT_MAX = 15;
+ int antennaSelect = ANTSELECT_INVALID; //default value = 0
+ public int getAntennaSelect() {
+ appendToLog("AntennaSelect = " + antennaSelect);
+ if (antennaSelect < ANTSLECT_MIN || antennaSelect > ANTSELECT_MAX) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 1, 7, 0, 0, 0, 0};
+ sendHostRegRequest(HostRegRequests.HST_ANT_DESC_SEL, false, msgBuffer);
+ }
+ return antennaSelect;
+ }
+ public boolean setAntennaSelect(int antennaSelect) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 1, 7, 0, 0, 0, 0};
+ if (antennaSelect < ANTSLECT_MIN || antennaSelect > ANTSELECT_MAX) antennaSelect = mDefault.antennaSelect;
+ if (this.antennaSelect == antennaSelect && sameCheck) return true;
+ this.antennaSelect = antennaSelect; appendToLog("antennaSelect is set to " + antennaSelect);
+ msgBuffer[4] = (byte) (antennaSelect);
+ return sendHostRegRequest(HostRegRequests.HST_ANT_DESC_SEL, true, msgBuffer);
+ }
+
+ AntennaSelectedData[] antennaSelectedData;
+ public int getAntennaEnable() {
+ if (antennaSelect < ANTSLECT_MIN || antennaSelect > ANTSELECT_MAX) {
+ return ANTSELECT_INVALID;
+ } else {
+ return antennaSelectedData[antennaSelect].getAntennaEnable();
+ }
+ }
+ public boolean setAntennaEnable(int antennaEnable) {
+ if (antennaSelect < ANTSLECT_MIN || antennaSelect > ANTSELECT_MAX) { antennaSelect = mDefault.antennaSelect; appendToLog("antennaSelect is set to " + antennaSelect); }
+ return antennaSelectedData[antennaSelect].setAntennaEnable(antennaEnable);
+ }
+ boolean setAntennaEnable(int antennaEnable, int antennaInventoryMode, int antennaLocalAlgo, int antennaLocalStartQ,
+ int antennaProfileMode, int antennaLocalProfile, int antennaFrequencyMode, int antennaLocalFrequency) {
+ if (antennaSelect < ANTSLECT_MIN || antennaSelect > ANTSELECT_MAX) { antennaSelect = mDefault.antennaSelect; appendToLog("antennaSelect is set to " + antennaSelect); }
+ return antennaSelectedData[antennaSelect].setAntennaEnable(antennaEnable, antennaInventoryMode, antennaLocalAlgo, antennaLocalStartQ,
+ antennaProfileMode, antennaLocalProfile, antennaFrequencyMode, antennaLocalFrequency);
+ }
+
+ int getAntennaInventoryMode() {
+ if (antennaSelect < ANTSLECT_MIN || antennaSelect > ANTSELECT_MAX) {
+ return ANTSELECT_INVALID;
+ } else {
+ return antennaSelectedData[antennaSelect].getAntennaInventoryMode();
+ }
+ }
+ boolean setAntennaInventoryMode(int antennaInventoryMode) {
+ if (antennaSelect < ANTSLECT_MIN || antennaSelect > ANTSELECT_MAX) { antennaSelect = mDefault.antennaSelect; appendToLog("antennaSelect is set to " + antennaSelect); }
+ return antennaSelectedData[antennaSelect].setAntennaInventoryMode(antennaInventoryMode);
+ }
+
+ int getAntennaLocalAlgo() {
+ if (antennaSelect < ANTSLECT_MIN || antennaSelect > ANTSELECT_MAX) {
+ return ANTSELECT_INVALID;
+ } else {
+ return antennaSelectedData[antennaSelect].getAntennaLocalAlgo();
+ }
+ }
+ boolean setAntennaLocalAlgo(int antennaLocalAlgo) {
+ if (antennaSelect < ANTSLECT_MIN || antennaSelect > ANTSELECT_MAX) { antennaSelect = mDefault.antennaSelect; appendToLog("antennaSelect is set to " + antennaSelect); }
+ return antennaSelectedData[antennaSelect].setAntennaLocalAlgo(antennaLocalAlgo);
+ }
+
+ int getAntennaLocalStartQ() {
+ if (antennaSelect < ANTSLECT_MIN || antennaSelect > ANTSELECT_MAX) {
+ return ANTSELECT_INVALID;
+ } else {
+ return antennaSelectedData[antennaSelect].getAntennaLocalStartQ();
+ }
+ }
+ boolean setAntennaLocalStartQ(int antennaLocalStartQ) {
+ if (antennaSelect < ANTSLECT_MIN || antennaSelect > ANTSELECT_MAX) { antennaSelect = mDefault.antennaSelect; appendToLog("antennaSelect is set to " + antennaSelect); }
+ return antennaSelectedData[antennaSelect].setAntennaLocalStartQ(antennaLocalStartQ);
+ }
+
+ int getAntennaProfileMode() {
+ if (antennaSelect < ANTSLECT_MIN || antennaSelect > ANTSELECT_MAX) {
+ return ANTSELECT_INVALID;
+ } else {
+ return antennaSelectedData[antennaSelect].getAntennaProfileMode();
+ }
+ }
+ boolean setAntennaProfileMode(int antennaProfileMode) {
+ if (antennaSelect < ANTSLECT_MIN || antennaSelect > ANTSELECT_MAX) { antennaSelect = mDefault.antennaSelect; appendToLog("antennaSelect is set to " + antennaSelect); }
+ return antennaSelectedData[antennaSelect].setAntennaProfileMode(antennaProfileMode);
+ }
+
+ int getAntennaLocalProfile() {
+ if (antennaSelect < ANTSLECT_MIN || antennaSelect > ANTSELECT_MAX) {
+ return ANTSELECT_INVALID;
+ } else {
+ return antennaSelectedData[antennaSelect].getAntennaLocalProfile();
+ }
+ }
+ boolean setAntennaLocalProfile(int antennaLocalProfile) {
+ if (antennaSelect < ANTSLECT_MIN || antennaSelect > ANTSELECT_MAX) { antennaSelect = mDefault.antennaSelect; appendToLog("antennaSelect is set to " + antennaSelect); }
+ return antennaSelectedData[antennaSelect].setAntennaLocalProfile(antennaLocalProfile);
+ }
+
+ int getAntennaFrequencyMode() {
+ if (antennaSelect < ANTSLECT_MIN || antennaSelect > ANTSELECT_MAX) {
+ return ANTSELECT_INVALID;
+ } else {
+ return antennaSelectedData[antennaSelect].getAntennaFrequencyMode();
+ }
+ }
+ boolean setAntennaFrequencyMode(int antennaFrequencyMode) {
+ if (antennaSelect < ANTSLECT_MIN || antennaSelect > ANTSELECT_MAX) { antennaSelect = mDefault.antennaSelect; appendToLog("antennaSelect is set to " + antennaSelect); }
+ return antennaSelectedData[antennaSelect].setAntennaFrequencyMode(antennaFrequencyMode);
+ }
+
+ int getAntennaLocalFrequency() {
+ if (antennaSelect < ANTSLECT_MIN || antennaSelect > ANTSELECT_MAX) {
+ return ANTSELECT_INVALID;
+ } else {
+ return antennaSelectedData[antennaSelect].getAntennaLocalFrequency();
+ }
+ }
+ boolean setAntennaLocalFrequency(int antennaLocalFrequency) {
+ if (antennaSelect < ANTSLECT_MIN || antennaSelect > ANTSELECT_MAX) { antennaSelect = mDefault.antennaSelect; appendToLog("antennaSelect is set to " + antennaSelect); }
+ return antennaSelectedData[antennaSelect].setAntennaLocalFrequency(antennaLocalFrequency);
+ }
+
+ int getAntennaStatus() {
+ if (antennaSelect < ANTSLECT_MIN || antennaSelect > ANTSELECT_MAX) {
+ return ANTSELECT_INVALID;
+ } else {
+ return antennaSelectedData[antennaSelect].getAntennaStatus();
+ }
+ }
+
+ int getAntennaDefine() {
+ if (antennaSelect < ANTSLECT_MIN || antennaSelect > ANTSELECT_MAX) {
+ return ANTSELECT_INVALID;
+ } else {
+ return antennaSelectedData[antennaSelect].getAntennaDefine();
+ }
+ }
+
+ public long getAntennaDwell() {
+ if (antennaSelect < ANTSLECT_MIN || antennaSelect > ANTSELECT_MAX) {
+ return ANTSELECT_INVALID;
+ } else {
+ return antennaSelectedData[antennaSelect].getAntennaDwell();
+ }
+ }
+ public boolean setAntennaDwell(long antennaDwell) {
+ if (antennaSelect < ANTSLECT_MIN || antennaSelect > ANTSELECT_MAX) { antennaSelect = mDefault.antennaSelect; appendToLog("antennaSelect is set to " + antennaSelect); }
+ return antennaSelectedData[antennaSelect].setAntennaDwell(antennaDwell);
+ }
+
+ public long getAntennaPower(int portNumber) {
+ if (antennaSelect < ANTSLECT_MIN || antennaSelect > ANTSELECT_MAX) {
+ return ANTSELECT_INVALID;
+ } else {
+ if (portNumber < 0 || portNumber > 15) portNumber = antennaSelect;
+ long lValue;
+ lValue = antennaSelectedData[portNumber].getAntennaPower();
+ return lValue;
+ }
+ }
+ public boolean setAntennaPower(long antennaPower) {
+ if (antennaSelect < ANTSLECT_MIN || antennaSelect > ANTSELECT_MAX) { antennaSelect = mDefault.antennaSelect; appendToLog("antennaSelect is set to " + antennaSelect); }
+ return antennaSelectedData[antennaSelect].setAntennaPower(antennaPower);
+ }
+
+ long getAntennaInvCount() {
+ if (antennaSelect < ANTSLECT_MIN || antennaSelect > ANTSELECT_MAX) {
+ return ANTSELECT_INVALID;
+ } else {
+ return antennaSelectedData[antennaSelect].getAntennaInvCount();
+ }
+ }
+ public boolean setAntennaInvCount(long antennaInvCount) {
+ if (antennaSelect < ANTSLECT_MIN || antennaSelect > ANTSELECT_MAX) { antennaSelect = mDefault.antennaSelect; appendToLog("antennaSelect is set to " + antennaSelect); }
+ return antennaSelectedData[antennaSelect].setAntennaInvCount(antennaInvCount);
+ }
+
+ //Tag select block parameters
+ final int INVSELECT_INVALID = -1; final int INVSELECT_MIN = 0; final int INVSELECT_MAX = 7;
+ public int invSelectIndex = INVSELECT_INVALID;
+ public int getInvSelectIndex() {
+ if (invSelectIndex < INVSELECT_MIN || invSelectIndex > INVSELECT_MAX) {
+ {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 0, 8, 0, 0, 0, 0};
+ sendHostRegRequest(HostRegRequests.HST_TAGMSK_DESC_SEL, false, msgBuffer);
+ }
+ }
+ return invSelectIndex;
+ }
+ public boolean setInvSelectIndex(int invSelect) {
+ if (utility.DEBUG_SELECT) appendToLog("Debug_Select: RfidReaderChipR2000.setInvSelectIndex[" + invSelect);
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 0, 8, 0, 0, 0, 0};
+ if (invSelect < INVSELECT_MIN || invSelect > INVSELECT_MAX) invSelect = mDefault.invSelectIndex;
+ if (this.invSelectIndex == invSelect && sameCheck) return true;
+ msgBuffer[4] = (byte) (invSelect & 0x07);
+ this.invSelectIndex = invSelect;
+ return sendHostRegRequest(HostRegRequests.HST_TAGMSK_DESC_SEL, true, msgBuffer);
+ }
+
+ InvSelectData[] invSelectData;
+ public int getSelectEnable() {
+ if (invSelectIndex < INVSELECT_MIN || invSelectIndex > INVSELECT_MAX) invSelectIndex = mDefault.invSelectIndex;
+ return invSelectData[invSelectIndex].getSelectEnable();
+ }
+ public boolean setSelectEnable(int enable, int selectTarget, int selectAction, int selectDelay) {
+ if (utility.DEBUG_SELECT) appendToLog("Debug_Select: RfidReaderChipR2000.Rx000Setting.setSelectEnable[" + enable);
+ if (invSelectIndex < INVSELECT_MIN || invSelectIndex > INVSELECT_MAX) invSelectIndex = mDefault.invSelectIndex;
+ if (false) appendToLog("BtDataOut: RfidReaderChipR200.setSelectEnable goes to setRx000HostReg_HST_TAGMSK_DESC_CFG with index = " + invSelectIndex);
+ return invSelectData[invSelectIndex].setRx000HostReg_HST_TAGMSK_DESC_CFG(enable, selectTarget, selectAction, selectDelay);
+ }
+
+ public int getSelectTarget() {
+ if (invSelectIndex < INVSELECT_MIN || invSelectIndex > INVSELECT_MAX) invSelectIndex = mDefault.invSelectIndex;
+ return invSelectData[invSelectIndex].getSelectTarget();
+ }
+
+ public int getSelectAction() {
+ if (invSelectIndex < INVSELECT_MIN || invSelectIndex > INVSELECT_MAX) invSelectIndex = mDefault.invSelectIndex;
+ return invSelectData[invSelectIndex].getSelectAction();
+ }
+
+ public int getSelectMaskBank() {
+ if (invSelectIndex < INVSELECT_MIN || invSelectIndex > INVSELECT_MAX) invSelectIndex = mDefault.invSelectIndex;
+ return invSelectData[invSelectIndex].getSelectMaskBank();
+ }
+ public boolean setSelectMaskBank(int selectMaskBank) {
+ if (invSelectIndex < INVSELECT_MIN || invSelectIndex > INVSELECT_MAX) invSelectIndex = mDefault.invSelectIndex;
+ return invSelectData[invSelectIndex].setSelectMaskBank(selectMaskBank);
+ }
+
+ public int getSelectMaskOffset() {
+ int dataIndex = invSelectIndex;
+ if (dataIndex < INVSELECT_MIN || dataIndex > INVSELECT_MAX) {
+ return INVSELECT_INVALID;
+ } else {
+ return invSelectData[dataIndex].getSelectMaskOffset();
+ }
+ }
+ public boolean setSelectMaskOffset(int selectMaskOffset) {
+ if (invSelectIndex < INVSELECT_MIN || invSelectIndex > INVSELECT_MAX) invSelectIndex = mDefault.invSelectIndex;
+ return invSelectData[invSelectIndex].setSelectMaskOffset(selectMaskOffset);
+ }
+
+ public int getSelectMaskLength() {
+ int dataIndex = invSelectIndex;
+ if (dataIndex < INVSELECT_MIN || dataIndex > INVSELECT_MAX) {
+ return INVSELECT_INVALID;
+ } else {
+ return invSelectData[dataIndex].getSelectMaskLength();
+ }
+ }
+ public boolean setSelectMaskLength(int selectMaskLength) {
+ if (false) appendToLog("btDataOut: setSelectMaskLength with selectMaskLength = " + selectMaskLength);
+ if (invSelectIndex < INVSELECT_MIN || invSelectIndex > INVSELECT_MAX) invSelectIndex = mDefault.invSelectIndex;
+ return invSelectData[invSelectIndex].setSelectMaskLength(selectMaskLength);
+ }
+
+ public String getSelectMaskData() {
+ int dataIndex = invSelectIndex;
+ if (dataIndex < INVSELECT_MIN || dataIndex > INVSELECT_MAX) {
+ return null;
+ } else {
+ return invSelectData[dataIndex].getRx000SelectMaskData();
+ }
+ }
+ public boolean setSelectMaskData(String maskData) {
+ if (maskData == null) return false;
+ if (invSelectIndex < INVSELECT_MIN || invSelectIndex > INVSELECT_MAX) invSelectIndex = mDefault.invSelectIndex;
+ if (invSelectData[invSelectIndex].selectMaskDataReady != 0) {
+ String maskDataOld = getSelectMaskData();
+ if (maskData != null && maskDataOld != null) {
+ if (maskData.matches(maskDataOld) && sameCheck) return true;
+ }
+ }
+ return invSelectData[invSelectIndex].setRx000SelectMaskData(maskData);
+ }
+
+ //Inventtory block paraameters
+ final int QUERYTARGET_INVALID = -1; final int QUERYTARGET_MIN = 0; final int QUERYTARGET_MAX = 1;
+ int queryTarget = QUERYTARGET_INVALID;
+ public int getQueryTarget() {
+ if (DEBUG) appendToLog("RfidReaderChipR2000.getQueryTarget with queryTarget = " + queryTarget);
+ if (queryTarget == QUERYTARGET_INVALID) getHST_QUERY_CFG();
+ return queryTarget;
+ }
+ boolean setQueryTarget(int queryTarget) {
+ if (DEBUG || true) appendToLog("3 setQueryTarget is callled from RfidReaderChipR2000.setQueryTarget[" + queryTarget);
+ return setQueryTarget(queryTarget, querySession, querySelect);
+ }
+ public boolean setQueryTarget(int queryTarget, int querySession, int querySelect) {
+ if (false) appendToLog("setQueryTarget[" + queryTarget + ", " + querySession + ", " + querySelect + "] with sameCheck = " + sameCheck + ", old queryTarget/Session/Select = " + this.queryTarget + ", " + this.querySession + ", " + this.querySelect);
+ if (queryTarget >= 2) { rx000Setting.setAlgoAbFlip(1); }
+ else if (queryTarget >= 0) { rx000Setting.setAlgoAbFlip(0); }
+
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 0, 9, 0, 0, 0, 0};
+
+ if ((this.queryTarget == queryTarget || queryTarget == 2 || queryTarget == -1)
+ && (this.querySession == querySession || querySession == -1)
+ && (this.querySelect == querySelect || querySelect == -1) && sameCheck) return true;
+ msgBuffer[4] |= ((queryTarget == 2 ? 0 : queryTarget) << 4);
+ msgBuffer[4] |= (byte) (querySession << 5);
+ if ((querySelect & 0x01) != 0) {
+ msgBuffer[4] |= (byte) 0x80;
+ }
+ if ((querySelect & 0x02) != 0) {
+ msgBuffer[5] |= (byte) 0x01;
+ }
+ this.queryTarget = queryTarget;
+ this.querySession = querySession;
+ this.querySelect = querySelect;
+ return sendHostRegRequest(HostRegRequests.HST_QUERY_CFG, true, msgBuffer);
+ }
+
+ final int QUERYSESSION_INVALID = -1; final int QUERYSESSION_MIN = 0; final int QUERYSESSION_MAX = 3;
+ int querySession = QUERYSESSION_INVALID;
+ public int getQuerySession() {
+ if (antennaSelect < ANTSLECT_MIN || antennaSelect > ANTSELECT_MAX) {
+ return ANTSELECT_INVALID;
+ } else {
+ {
+ //appendToLog("BtDataOut: RfidReaderChipR2000.getQuerySession with querySession = " + querySession);
+ if (querySession < QUERYSESSION_MIN || querySession > QUERYSESSION_MAX)
+ getHST_QUERY_CFG();
+ return querySession;
+ }
+ }
+
+ }
+ boolean setQuerySession(int querySession) {
+ if (true) appendToLog("4 setQueryTargetis callled from BtDataOut: RfidReaderChipR2000.setQuerySession[" + querySession);
+ return setQueryTarget((getAlgoAbFlip() > 0 ? 2 : queryTarget), querySession, querySelect);
+ }
+
+ final int QUERYSELECT_INVALID = -1; final int QUERYSELECT_MIN = 0; final int QUERYSELECT_MAX = 3;
+ int querySelect = QUERYSELECT_INVALID;
+ public int getQuerySelect() {
+ if (false) appendToLog("BtDataOut: RfidReaderChipR2000.getQuerySelect with querySelect = " + querySelect);
+ if (querySelect < QUERYSELECT_MIN || querySelect > QUERYSELECT_MAX) getHST_QUERY_CFG();
+ if (false) appendToLog("Stream querySelect = " + querySelect);
+ return querySelect;
+ }
+ public boolean setQuerySelect(int querySelect) {
+ if (false) appendToLog("5 setQueryTarget is callled from RfidReaderChipR2000.setQuerySelect[" + querySelect);
+ if (querySelect == this.querySelect) return true;
+ return setQueryTarget((getAlgoAbFlip() > 0 ? 2 : queryTarget), querySession, querySelect);
+ }
+
+ private boolean getHST_QUERY_CFG() {
+ //appendToLog("BtDataOut: RfidReaderChipR2000.getHST_QUERY_CFG");
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 0, 9, 0, 0, 0, 0};
+ return sendHostRegRequest(HostRegRequests.HST_QUERY_CFG, false, msgBuffer);
+ }
+
+ final int INVALGO_INVALID = -1; final int INVALGO_MIN = 0; final int INVALGO_MAX = 3;
+ int invAlgo = INVALGO_INVALID;
+ public int getInvAlgo() {
+ if (invAlgo < INVALGO_MIN || invAlgo > INVALGO_MAX) getHST_INV_CFG();
+ return invAlgo;
+ }
+ public boolean setInvAlgo(int invAlgo) {
+ if (utility.DEBUG_INVCFG) appendToLog("Debug_InvCfg: RfidReaderChipR2000.Rx000setting.setInvAlog goes to setInvAlgo with invAlgo = " + invAlgo);
+ return setInvAlgo(invAlgo, matchRep, tagSelect, noInventory, tagRead, tagDelay, invModeCompact, invBrandId, invAuthenticate);
+ }
+
+ final int MATCHREP_INVALID = -1; final int MATCHREP_MIN = 0; final int MATCHREP_MAX = 255;
+ int matchRep = MATCHREP_INVALID;
+ int getMatchRep() {
+ if (matchRep < MATCHREP_MIN || matchRep > MATCHREP_MAX) getHST_INV_CFG();
+ return matchRep;
+ }
+ public boolean setMatchRep(int matchRep) {
+ if (utility.DEBUG_INVCFG) appendToLog("Debug_InvCfg: RfidReaderChipR2000.Rx000setting.setMatchRep goes to setInvAlgo with matchRep = " + matchRep);
+ return setInvAlgo(invAlgo, matchRep, tagSelect, noInventory, tagRead, tagDelay, invModeCompact, invBrandId, invAuthenticate);
+ }
+
+ final int TAGSELECT_INVALID = -1; final int TAGSELECT_MIN = 0; final int TAGSELECT_MAX = 1;
+ int tagSelect = TAGSELECT_INVALID;
+ int getTagSelect() {
+ if (tagSelect < TAGSELECT_MIN || tagSelect > TAGSELECT_MAX) getHST_INV_CFG();
+ return tagSelect;
+ }
+ public boolean setTagSelect(int tagSelect) {
+ if (utility.DEBUG_INVCFG) appendToLog("Debug_InvCfg: RfidReaderChipR2000.Rx000setting.setTagSelect goes to setInvAlgo with tagSelect = " + tagSelect);
+ return setInvAlgo(invAlgo, matchRep, tagSelect, noInventory, tagRead, tagDelay, invModeCompact, invBrandId, invAuthenticate);
+ }
+
+ final int NOINVENTORY_INVALID = -1; final int NOINVENTORY_MIN = 0; final int NOINVENTORY_MAX = 1;
+ int noInventory = NOINVENTORY_INVALID;
+ int getNoInventory() {
+ if (noInventory < NOINVENTORY_MIN || noInventory > NOINVENTORY_MAX) getHST_INV_CFG();
+ return noInventory;
+ }
+ boolean setNoInventory(int noInventory) {
+ if (utility.DEBUG_INVCFG) appendToLog("Debug_InvCfg: RfidReaderChipR2000.Rx000setting.setNoInventory goes to setInvAlgo with noInventory = " + noInventory);
+ return setInvAlgo(invAlgo, matchRep, tagSelect, noInventory, tagRead, tagDelay, invModeCompact, invBrandId, invAuthenticate);
+ }
+
+ final int TAGREAD_INVALID = -1; final int TAGREAD_MIN = 0; final int TAGREAD_MAX = 2;
+ int tagRead = TAGREAD_INVALID;
+ int getTagRead() {
+ if (tagRead < TAGREAD_MIN || tagRead > TAGREAD_MAX) getHST_INV_CFG();
+ return tagRead;
+ }
+ public boolean setTagRead(int tagRead) {
+ if (utility.DEBUG_INVCFG) appendToLog("Debug_InvCfg: RfidReaderChipR2000.Rx000setting.setTagRead goes to setInvAlgo with tagRead = " + tagRead);
+ return setInvAlgo(invAlgo, matchRep, tagSelect, noInventory, tagRead, tagDelay, invModeCompact, invBrandId, invAuthenticate);
+ }
+
+ final int TAGDELAY_INVALID = -1; final int TAGDELAY_MIN = 0; final int TAGDELAY_MAX = 63;
+ int tagDelay = TAGDELAY_INVALID;
+ int getTagDelay() {
+ if (tagDelay < TAGDELAY_MIN || tagDelay > TAGDELAY_MAX) getHST_INV_CFG();
+ return tagDelay;
+ }
+ public boolean setTagDelay2RfidReader(int tagDelay) {
+ if (utility.DEBUG_INVCFG) appendToLog("Debug_InvCfg: RfidReaderChipR2000.Rx000setting.setTagDelay goes to setInvAlgo with tagDelay = " + tagDelay);
+ return setInvAlgo(invAlgo, matchRep, tagSelect, noInventory, tagRead, tagDelay, invModeCompact, invBrandId, invAuthenticate);
+ }
+
+ byte intraPacketDelay = 4;
+ public byte getIntraPacketDelay() {
+ appendToLog("intraPacketDelay = " + intraPacketDelay);
+ return intraPacketDelay;
+ }
+ public boolean setIntraPacketDelay(byte intraPkDelay) {
+ if (intraPacketDelay == intraPkDelay && sameCheck) {
+ appendToLog("!!! Skip sending repeated data with intraPkDelay = " + intraPkDelay);
+ return true;
+ }
+ appendToLog("Skip setDupElim with intraPkDelay = " + intraPkDelay);
+ intraPacketDelay = intraPkDelay;
+ return true;
+ }
+
+ byte dupElimRollWindow = 0;
+ public byte getDupElimRollWindow() {
+ appendToLog("dupElim = " + dupElimRollWindow);
+ return dupElimRollWindow;
+ }
+ public boolean setDupElimRollWindow(byte dupElimDelay) {
+ if (dupElimRollWindow == dupElimDelay && sameCheck) {
+ appendToLog("!!! Skip sending repeated data with dupElimDelay = " + dupElimDelay);
+ return true;
+ }
+ appendToLog("Skip setDupElim with dupElimDelay = " + dupElimDelay);
+ dupElimRollWindow = dupElimDelay;
+ return true;
+ }
+
+ long cycleDelay = 0;
+ public long getCycleDelay() {
+ return cycleDelay;
+ }
+ public boolean setCycleDelay(long cycleDelay) {
+ if (this.cycleDelay == cycleDelay && sameCheck) return true;
+
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, (byte)0x0F, (byte)0x0F, 0, 0, 0, 0};
+ msgBuffer[4] |= (cycleDelay & 0xFF);
+ msgBuffer[5] |= (byte) ((cycleDelay & 0xFF00) >> 8);
+ msgBuffer[6] |= (byte) ((cycleDelay & 0xFF0000) >> 16);
+ msgBuffer[7] |= (byte) ((cycleDelay & 0xFF000000) >> 24);
+ this.cycleDelay = cycleDelay;
+ boolean bResult = sendHostRegRequest(HostRegRequests.HST_INV_CFG, true, msgBuffer);
+ //msgBuffer = new byte[]{(byte) 0x70, 0, (byte)0x0F, (byte)0x0F, 0, 0, 0, 0};
+ //sendHostRegRequest(HostRegRequests.HST_INV_CFG, false, msgBuffer);
+ return bResult;
+ }
+
+ final int AUTHENTICATE_CFG_INVALID = -1; final int AUTHENTICATE_CFG_MIN = 0; final int AUTHENTICATE_CFG_MAX = 4095;
+ boolean authenticateSendReply;
+ boolean authenticateIncReplyLength;
+ int authenticateLength = AUTHENTICATE_CFG_INVALID;
+ public int getAuthenticateReplyLength() {
+ if (authenticateLength < AUTHENTICATE_CFG_MIN || authenticateLength > AUTHENTICATE_CFG_MAX) getHST_AUTHENTICATE_CFG();
+ return authenticateLength;
+ }
+ private boolean getHST_AUTHENTICATE_CFG() {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 0, (byte) 0x0F, 0, 0, 0, 0};
+ return sendHostRegRequest(HostRegRequests.HST_AUTHENTICATE_CFG, false, msgBuffer);
+ }
+ public boolean setHST_AUTHENTICATE_CFG(boolean sendReply, boolean incReplyLenth, int csi, int length) {
+ appendToLog("sendReply = " + sendReply + ", incReplyLenth = " + incReplyLenth + ", length = " + length);
+ if (length < 0 || length > 0x3FF) return false;
+
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 0, (byte) 0x0F, 0, 0, 0, 0};
+ if (sendReply) msgBuffer[4] |= 0x01; authenticateSendReply = sendReply;
+ if (incReplyLenth) msgBuffer[4] |= 0x02; authenticateIncReplyLength = incReplyLenth;
+ msgBuffer[4] |= ((csi & 0x3F) << 2);
+ msgBuffer[5] |= ((csi >> 6) & 0x03);
+ msgBuffer[5] |= ((length & 0x3F) << 2);
+ msgBuffer[6] |= ((length & 0xFC0) >> 6); authenticateLength = length;
+ return sendHostRegRequest(HostRegRequests.HST_AUTHENTICATE_CFG, true, msgBuffer);
+ }
+
+ byte[] authMatchData0_63; int authMatchDataReady = 0;
+ public String getAuthMatchData() {
+ int length = 96;
+ String strValue = "";
+ for (int i = 0; i < 3; i++) {
+ if (length > 0) {
+ appendToLog("i = " + i + ", authMatchDataReady = " + authMatchDataReady);
+ if ((authMatchDataReady & (0x01 << i)) == 0) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 1, (byte)0x0F, 0, 0, 0, 0};
+ msgBuffer[2] += i;
+ sendHostRegRequest(HostRegRequests.HST_AUTHENTICATE_MSG, false, msgBuffer);
+ } else {
+ for (int j = 0; j < 4; j++) {
+ strValue += String.format("%02X", authMatchData0_63[i * 4 + j]);
+ }
+ }
+ length -= 32;
+ }
+ }
+ if (strValue.length() < 16) strValue = null;
+ return strValue;
+ }
+ public boolean setAuthMatchData(String matchData) {
+ int length = matchData.length();
+ appendToLog("matchData is " + length + ", " + matchData);
+ for (int i = 0; i < 6; i++) {
+ if (length > 0) {
+ length -= 8;
+
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 1, (byte)0x0F, 0, 0, 0, 0};
+ String hexString = "0123456789ABCDEF";
+ for (int j = 0; j < 8; j++) {
+ if (i * 8 + j + 1 <= matchData.length()) {
+ String subString = matchData.substring(i * 8 + j, i * 8 + j + 1).toUpperCase();
+ int k = 0;
+ for (k = 0; k < 16; k++) {
+ if (subString.matches(hexString.substring(k, k + 1))) {
+ break;
+ }
+ }
+ if (k == 16) return false;
+ if ((j / 2) * 2 == j) {
+ msgBuffer[7 - j / 2] |= (byte) (k << 4);
+ } else {
+ msgBuffer[7 - j / 2] |= (byte) (k);
+ }
+ }
+ }
+ msgBuffer[2] = (byte) ((msgBuffer[2] & 0xFF) + i);
+ if (sendHostRegRequest(HostRegRequests.HST_AUTHENTICATE_MSG, true, msgBuffer) == false)
+ return false;
+ else {
+ //authMatchDataReady |= (0x01 << i);
+ System.arraycopy(msgBuffer, 4, authMatchData0_63, i * 4, 4); //appendToLog("Data=" + byteArrayToString(mRx000Setting.invMatchData0_63));
+// appendToLog("invMatchDataReady=" + Integer.toString(mRx000Setting.invMatchDataReady, 16) + ", message=" + byteArrayToString(msgBuffer));
+ }
+ }
+ }
+ return true;
+ }
+
+ final int UNTRACEABLE_CFG_INVALID = -1; final int UNTRACEABLE_CFG_MIN = 0; final int UNTRACEABLE_CFG_MAX = 3;
+ int untraceableRange = UNTRACEABLE_CFG_INVALID;
+ boolean untraceableUser;
+ int untraceableTid = UNTRACEABLE_CFG_INVALID;
+ int untraceableEpcLength = UNTRACEABLE_CFG_INVALID;
+ boolean untraceableEpc;
+ boolean untraceableUXpc;
+ public int getUntraceableEpcLength() {
+ if (untraceableRange < UNTRACEABLE_CFG_MIN || untraceableRange > UNTRACEABLE_CFG_MAX) getHST_UNTRACEABLE_CFG();
+ return untraceableEpcLength;
+ }
+ private boolean getHST_UNTRACEABLE_CFG() {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 5, (byte) 0x0F, 0, 0, 0, 0};
+ return sendHostRegRequest(HostRegRequests.HST_UNTRACEABLE_CFG, false, msgBuffer);
+ }
+ public boolean setHST_UNTRACEABLE_CFG(int range, boolean user, int tid, int epcLength, boolean epc, boolean uxpc) {
+ appendToLog("range1 = " + range + ", user = " + user + ", tid = " + tid + ", epc = " + epc + ", epcLength = " + epcLength + ", xcpc = " + uxpc);
+ if (range < 0 || range > 3) return false;
+ if (tid < 0 || tid > 2) return false;
+ if (epcLength < 0 || epcLength > 31) return false;
+
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 5, (byte) 0x0F, 0, 0, 0, 0};
+ msgBuffer[4] |= (range); untraceableRange = range;
+ if (user) msgBuffer[4] |= 0x04; untraceableUser = user;
+ msgBuffer[4] |= (tid << 3); untraceableTid = tid;
+ msgBuffer[4] |= ((epcLength & 0x7) << 5);
+ msgBuffer[5] |= ((epcLength & 0x18) >> 3); untraceableEpcLength = epcLength;
+ if (epc) msgBuffer[5] |= 0x04; untraceableEpc = epc;
+ if (uxpc) msgBuffer[5] |= 0x08; untraceableUXpc = uxpc;
+ appendToLog("msgbuffer = " + byteArrayToString(msgBuffer));
+ return sendHostRegRequest(HostRegRequests.HST_UNTRACEABLE_CFG, true, msgBuffer);
+ }
+
+ final int TAGJOIN_INVALID = -1; final int TAGJOIN_MIN = 0; final int TAGJOIN_MAX = 1;
+ int invModeCompact = TAGJOIN_INVALID;
+ boolean getInvModeCompact() {
+ if (invModeCompact < TAGDELAY_MIN || invModeCompact > TAGDELAY_MAX) { getHST_INV_CFG(); return false; }
+ return (invModeCompact == 1);
+ }
+ public boolean setInvModeCompact(boolean invModeCompact) {
+ if (utility.DEBUG_INVCFG) appendToLog("Debug_InvCfg: RfidReaderChipR2000.Rx000setting.setInvModeCompact goes to setInvAlgo with invModeCompact = " + invModeCompact);
+ return setInvAlgo(invAlgo, matchRep, tagSelect, noInventory, tagRead, tagDelay, (invModeCompact ? 1 : 0), invBrandId, invAuthenticate);
+ }
+
+ final int BRAND_INVALID = -1; final int BRANDID_MIN = 0; final int BRANDID_MAX = 1;
+ int invBrandId = BRAND_INVALID;
+ boolean getInvBrandId() {
+ if (invBrandId < BRANDID_MIN || invBrandId > BRANDID_MAX) { getHST_INV_CFG(); return false; }
+ return (invModeCompact == 1);
+ }
+ public boolean setInvBrandId(boolean invBrandId) {
+ if (utility.DEBUG_INVCFG) appendToLog("Debug_InvCfg: RfidReaderChipR2000.Rx000setting.setInvBrandId goes to setInvAlgo with invBrandId = " + invBrandId);
+ return setInvAlgo(invAlgo, matchRep, tagSelect, noInventory, tagRead, tagDelay, invModeCompact, (invBrandId ? 1 : 0), invAuthenticate);
+ }
+
+ final int INVAUTHENTICATE_INVALID = -1; final int INVAUTHENTICATE_MIN = 0; final int INVAUTHENTICATE_MAX = 1;
+ int invAuthenticate = INVAUTHENTICATE_INVALID;
+ boolean getInvAuthenticate() {
+ if (invAuthenticate < INVAUTHENTICATE_MIN || invAuthenticate > INVAUTHENTICATE_MAX) { getHST_INV_CFG(); return false; }
+ return (invAuthenticate == 1);
+ }
+ public boolean setInvAuthenticate(boolean invAuthenticate) {
+ if (utility.DEBUG_INVCFG) appendToLog("Debug_InvCfg: RfidReaderChipR2000.Rx000setting.setInvBrandId goes to setInvAlgo with invBrandId = " + invBrandId);
+ return setInvAlgo(invAlgo, matchRep, tagSelect, noInventory, tagRead, tagDelay, invModeCompact, invBrandId, (invAuthenticate ? 1: 0));
+ }
+
+ private boolean getHST_INV_CFG() {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 1, 9, 0, 0, 0, 0};
+ return sendHostRegRequest(HostRegRequests.HST_INV_CFG, false, msgBuffer);
+ }
+ boolean setInvAlgo(int invAlgo, int matchRep, int tagSelect, int noInventory, int tagRead, int tagDelay, int invModeCompact, int invBrandId, int invAuthenticate) {
+ boolean DEBUG = utility.DEBUG_INVCFG;
+ if (DEBUG) appendToLog("Debug_InvCfg: 0 tagRead is " + tagRead);
+ if (invAlgo < INVALGO_MIN || invAlgo > INVALGO_MAX) invAlgo = mDefault.invAlgo;
+ if (matchRep < MATCHREP_MIN || matchRep > MATCHREP_MAX) matchRep = mDefault.matchRep;
+ if (tagSelect < TAGSELECT_MIN || tagSelect > TAGSELECT_MAX) tagSelect = mDefault.tagSelect;
+ if (noInventory < NOINVENTORY_MIN || noInventory > NOINVENTORY_MAX) noInventory = mDefault.noInventory;
+ if (tagDelay < TAGDELAY_MIN || tagDelay > TAGDELAY_MAX) tagDelay = mDefault.tagDelay;
+ if (invModeCompact < TAGJOIN_MIN || invModeCompact > TAGJOIN_MAX) invModeCompact = mDefault.tagJoin;
+ if (invBrandId < BRANDID_MIN || invBrandId > BRANDID_MAX) invBrandId = mDefault.brandid;
+ if (invAuthenticate < INVAUTHENTICATE_MIN || invAuthenticate > INVAUTHENTICATE_MAX) invAuthenticate = mDefault.invAuthenticate;
+ if (tagRead < TAGREAD_MIN || tagRead > TAGREAD_MAX) tagRead = mDefault.tagRead;
+ if (DEBUG) appendToLog("Debug_InvCfg: Old invAlgo = " + this.invAlgo + ", matchRep = " + this.matchRep + ", tagSelect = " + this.tagSelect + ", noInventory = " + this.noInventory + ", tagRead = " + this.tagRead + ", tagDelay = " + this.tagDelay + ", invModeCompact = " + this.invModeCompact + ", invBrandId = " + this.invBrandId + ", invAuthenticate = " + this.invAuthenticate);
+ if (DEBUG) appendToLog("Debug_InvCfg: New invAlgo = " + invAlgo + ", matchRep = " + matchRep + ", tagSelect = " + tagSelect + ", noInventory = " + noInventory + ", tagRead = " + tagRead + ", tagDelay = " + tagDelay + ", invModeCompact = " + invModeCompact + ", invBrandId = " + invBrandId + ", invAuthenticate = " + invAuthenticate + ", sameCheck = " + sameCheck);
+ boolean bool1 = this.invAlgo == invAlgo;
+ boolean bool2 = this.matchRep == matchRep;
+ boolean bool3 = this.tagSelect == tagSelect;
+ boolean bool4 = this.noInventory == noInventory;
+ if (DEBUG) appendToLog("Debug_InvCfg: tagRead = " + tagRead + ", this.tagRead = " + this.tagRead);
+ boolean bool5 = (this.tagRead == tagRead) || (tagRead == -1);
+ boolean bool6 = this.tagDelay == tagDelay;
+ boolean bool7 = this.invModeCompact == invModeCompact;
+ boolean bool8 = this.invBrandId == invBrandId;
+ boolean bool9 = this.invAuthenticate == invAuthenticate;
+ if (bool1 && bool2 && bool3 && bool4 && bool5 && bool6 && bool7 && bool8 && bool9 && sameCheck) return true;
+ if (DEBUG) appendToLog("Debug_InvCfg: There is difference with " + bool1 + "," + bool2 + "," + bool3 + "," + bool4 + "," + bool5 + "," + bool6 + "," + bool7 + "," + bool8 + "," + bool9);
+ this.invAlgo = invAlgo; if (DEBUG) appendToLog("Hello6: invAlgo = " + invAlgo + ", queryTarget = " + queryTarget);
+ this.matchRep = matchRep;
+ this.tagSelect = tagSelect;
+ this.noInventory = noInventory;
+ this.tagRead = tagRead;
+ this.tagDelay = tagDelay;
+ this.invModeCompact = invModeCompact;
+ this.invBrandId = invBrandId;
+ this.invAuthenticate = invAuthenticate;
+ appendToLog("BtDataOut: 1, invAuthenticate = " + rx000Setting.invAuthenticate);
+ if (DEBUG) appendToLog("Debug_InvCfg: Stored tagDelay = " + this.tagDelay);
+
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 1, 9, 0, 0, 0, 0};
+ msgBuffer[4] |= invAlgo;
+ msgBuffer[4] |= (byte) ((matchRep & 0x03) << 6);
+ msgBuffer[5] |= (byte) (matchRep >> 2);
+ if (tagSelect != 0) {
+ msgBuffer[5] |= 0x40;
+ }
+ if (noInventory != 0) {
+ msgBuffer[5] |= 0x80;
+ }
+ if ((tagRead & 0x03) != 0) {
+ msgBuffer[6] |= (tagRead & 0x03);
+ }
+ if ((tagDelay & 0x0F) != 0) {
+ msgBuffer[6] |= ((tagDelay & 0x0F) << 4);
+ }
+ if ((tagDelay & 0x30) != 0) {
+ msgBuffer[7] |= ((tagDelay & 0x30) >> 4);
+ }
+ if (invModeCompact == 1) {
+ msgBuffer[7] |= 0x04;
+ }
+ if (invBrandId == 1) {
+ msgBuffer[7] |= 0x08;
+ }
+ if (invAuthenticate == 1) {
+ msgBuffer[7] |= 0x10;
+ }
+ return sendHostRegRequest(HostRegRequests.HST_INV_CFG, true, msgBuffer);
+ }
+
+ final int ALGOSELECT_INVALID = -1; final int ALGOSELECT_MIN = 0; final int ALGOSELECT_MAX = 3; //DataSheet says Max=1
+ int algoSelect = ALGOSELECT_INVALID;
+ public int getAlgoSelect() {
+ if (algoSelect < ALGOSELECT_MIN || algoSelect > ALGOSELECT_MAX) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 2, 9, 0, 0, 0, 0};
+ sendHostRegRequest(HostRegRequests.HST_INV_SEL, false, msgBuffer);
+ }
+ return algoSelect;
+ }
+ boolean dummyAlgoSelected = false;
+ public boolean setAlgoSelect(int algoSelect) {
+ if (false) appendToLog("setTagGroup: algoSelect = " + algoSelect + ", this.algoSelct = " + this.algoSelect + ", dummyAlgoSelected = " + dummyAlgoSelected);
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 2, 9, 0, 0, 0, 0};
+ if (algoSelect < ALGOSELECT_MIN || algoSelect > ALGOSELECT_MAX)
+ algoSelect = mDefault.algoSelect;
+ if (algoSelect == this.algoSelect && dummyAlgoSelected == false) return true;
+ msgBuffer[4] = (byte) (algoSelect & 0xFF);
+ msgBuffer[5] = (byte) ((algoSelect & 0xFF00) >> 8);
+ msgBuffer[6] = (byte) ((algoSelect & 0xFF0000) >> 16);
+ msgBuffer[7] = (byte) ((algoSelect & 0xFF000000) >> 24);
+ this.algoSelect = algoSelect;
+ return sendHostRegRequest(HostRegRequests.HST_INV_SEL, true, msgBuffer);
+ }
+
+ AlgoSelectedData[] algoSelectedData;
+ public int getAlgoStartQ(int algoSelect) {
+ if (algoSelect < ALGOSELECT_MIN || algoSelect > ALGOSELECT_MAX) {
+ return ALGOSELECT_INVALID;
+ } else {
+ return algoSelectedData[algoSelect].getAlgoStartQ(false);
+ }
+ }
+ public int getAlgoStartQ() {
+ if (algoSelect < ALGOSELECT_MIN || algoSelect > ALGOSELECT_MAX) {
+ return ALGOSELECT_INVALID;
+ } else {
+ return algoSelectedData[algoSelect].getAlgoStartQ(true);
+ }
+ }
+ public boolean setAlgoStartQ(int algoStartQ) {
+ if (algoSelect < ALGOSELECT_MIN || algoSelect > ALGOSELECT_MAX) return false;
+ return algoSelectedData[algoSelect].setAlgoStartQ(algoStartQ);
+ }
+ public boolean setAlgoStartQ(int startQ, int algoMaxQ, int algoMinQ, int algoMaxRep, int algoHighThres, int algoLowThres) {
+ if (algoSelect < ALGOSELECT_MIN || algoSelect > ALGOSELECT_MAX) return false;
+ return algoSelectedData[algoSelect].setAlgoStartQ(startQ, algoMaxQ, algoMinQ, algoMaxRep, algoHighThres, algoLowThres);
+ }
+
+ public int getAlgoMaxQ(int algoSelect) {
+ if (algoSelect < ALGOSELECT_MIN || algoSelect > ALGOSELECT_MAX) {
+ return ALGOSELECT_INVALID;
+ } else {
+ return algoSelectedData[algoSelect].getAlgoMaxQ();
+ }
+ }
+ int getAlgoMaxQ() {
+ if (algoSelect < ALGOSELECT_MIN || algoSelect > ALGOSELECT_MAX) {
+ return ALGOSELECT_INVALID;
+ } else {
+ return algoSelectedData[algoSelect].getAlgoMaxQ();
+ }
+ }
+ boolean setAlgoMaxQ(int algoMaxQ) {
+ if (algoSelect < ALGOSELECT_MIN || algoSelect > ALGOSELECT_MAX) return false;
+ return algoSelectedData[algoSelect].setAlgoMaxQ(algoMaxQ);
+ }
+
+ public int getAlgoMinQ(int algoSelect) {
+ if (algoSelect < ALGOSELECT_MIN || algoSelect > ALGOSELECT_MAX) {
+ return ALGOSELECT_INVALID;
+ } else {
+ return algoSelectedData[algoSelect].getAlgoMinQ();
+ }
+ }
+ int getAlgoMinQ() {
+ if (algoSelect < ALGOSELECT_MIN || algoSelect > ALGOSELECT_MAX) {
+ return ALGOSELECT_INVALID;
+ } else {
+ return algoSelectedData[algoSelect].getAlgoMinQ();
+ }
+ }
+ boolean setAlgoMinQ(int algoMinQ) {
+ if (algoSelect < ALGOSELECT_MIN || algoSelect > ALGOSELECT_MAX) return false;
+ return algoSelectedData[algoSelect].setAlgoMinQ(algoMinQ);
+ }
+
+ int getAlgoMaxRep() {
+ if (algoSelect < ALGOSELECT_MIN || algoSelect > ALGOSELECT_MAX) {
+ return ALGOSELECT_INVALID;
+ } else {
+ return algoSelectedData[algoSelect].getAlgoMaxRep();
+ }
+ }
+ boolean setAlgoMaxRep(int algoMaxRep) {
+ if (algoSelect < ALGOSELECT_MIN || algoSelect > ALGOSELECT_MAX) return false;
+ return algoSelectedData[algoSelect].setAlgoMaxRep(algoMaxRep);
+ }
+
+ int getAlgoHighThres() {
+ if (algoSelect < ALGOSELECT_MIN || algoSelect > ALGOSELECT_MAX) {
+ return ALGOSELECT_INVALID;
+ } else {
+ return algoSelectedData[algoSelect].getAlgoHighThres();
+ }
+ }
+ boolean setAlgoHighThres(int algoHighThre) {
+ if (algoSelect < ALGOSELECT_MIN || algoSelect > ALGOSELECT_MAX) return false;
+ return algoSelectedData[algoSelect].setAlgoHighThres(algoHighThre);
+ }
+
+ int getAlgoLowThres() {
+ if (algoSelect < ALGOSELECT_MIN || algoSelect > ALGOSELECT_MAX) {
+ return ALGOSELECT_INVALID;
+ } else {
+ return algoSelectedData[algoSelect].getAlgoLowThres();
+ }
+ }
+ boolean setAlgoLowThres(int algoLowThre) {
+ if (algoSelect < ALGOSELECT_MIN || algoSelect > ALGOSELECT_MAX) return false;
+ return algoSelectedData[algoSelect].setAlgoLowThres(algoLowThre);
+ }
+
+ public int getAlgoRetry(int algoSelect) {
+ if (algoSelect < ALGOSELECT_MIN || algoSelect > ALGOSELECT_MAX) {
+ return ALGOSELECT_INVALID;
+ } else {
+ return algoSelectedData[algoSelect].getAlgoRetry();
+ }
+ }
+ public boolean setAlgoRetry(int algoRetry) {
+ if (algoSelect < ALGOSELECT_MIN || algoSelect > ALGOSELECT_MAX) return false;
+ return algoSelectedData[algoSelect].setAlgoRetry(algoRetry);
+ }
+
+ int getAlgoAbFlip(int algoSelect) {
+ if (algoSelect < ALGOSELECT_MIN || algoSelect > ALGOSELECT_MAX) {
+ return ALGOSELECT_INVALID;
+ } else {
+ return algoSelectedData[algoSelect].getAlgoAbFlip();
+ }
+ }
+ public int getAlgoAbFlip() {
+ if (algoSelect < ALGOSELECT_MIN || algoSelect > ALGOSELECT_MAX) {
+ return ALGOSELECT_INVALID;
+ } else {
+ return algoSelectedData[algoSelect].getAlgoAbFlip();
+ }
+ }
+ public boolean setAlgoAbFlip(int algoAbFlip) {
+ if (algoSelect < ALGOSELECT_MIN || algoSelect > ALGOSELECT_MAX) return false;
+ return algoSelectedData[algoSelect].setAlgoAbFlip(algoAbFlip);
+ }
+ boolean setAlgoAbFlip(int algoAbFlip, int algoRunTilZero) {
+ if (algoSelect < ALGOSELECT_MIN || algoSelect > ALGOSELECT_MAX) return false;
+ appendToLog("algoSelect = " + algoSelect + ", algoAbFlip = " + algoAbFlip + ", algoRunTilZero = " + algoRunTilZero);
+ return algoSelectedData[algoSelect].setAlgoAbFlip(algoAbFlip, algoRunTilZero);
+ }
+
+ public int getAlgoRunTilZero(int algoSelect) {
+ if (algoSelect < ALGOSELECT_MIN || algoSelect > ALGOSELECT_MAX) {
+ return ALGOSELECT_INVALID;
+ } else {
+ return algoSelectedData[algoSelect].getAlgoRunTilZero();
+ }
+ }
+ int getAlgoRunTilZero() {
+ if (algoSelect < ALGOSELECT_MIN || algoSelect > ALGOSELECT_MAX) {
+ return ALGOSELECT_INVALID;
+ } else {
+ return algoSelectedData[algoSelect].getAlgoRunTilZero();
+ }
+ }
+ public boolean setAlgoRunTilZero(int algoRunTilZero) {
+ if (algoSelect < ALGOSELECT_MIN || algoSelect > ALGOSELECT_MAX) return false;
+ return algoSelectedData[algoSelect].setAlgoRunTilZero(algoRunTilZero);
+ }
+
+ int rssiFilterConfig = -1;
+ final int RSSIFILTERTYPE_INVALID = -1, RSSIFILTERTYPE_MIN = 0, RSSIFILTERTYPE_MAX = 2;
+ int rssiFilterType = RSSIFILTERTYPE_INVALID;
+ final int RSSIFILTEROPTION_INVALID = -1, RSSIFILTEROPTION_MIN = 0, RSSIFILTEROPTION_MAX = 4;
+ int rssiFilterOption = RSSIFILTEROPTION_INVALID;
+ public int getRssiFilterType() {
+ if (rssiFilterType < 0) getHST_INV_RSSI_FILTERING_CONFIG();
+ return rssiFilterType;
+ }
+ public int getRssiFilterOption() {
+ if (rssiFilterOption < 0) getHST_INV_RSSI_FILTERING_CONFIG();
+ return rssiFilterOption;
+ }
+ private boolean getHST_INV_RSSI_FILTERING_CONFIG() {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 7, 9, 0, 0, 0, 0};
+ return sendHostRegRequest(HostRegRequests.HST_INV_RSSI_FILTERING_CONFIG, false, msgBuffer);
+ }
+ public boolean setHST_INV_RSSI_FILTERING_CONFIG(int rssiFilterType, int rssiFilterOption) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 7, 9, 0, 0, 0, 0};
+ if (rssiFilterType < RSSIFILTERTYPE_MIN || rssiFilterType > RSSIFILTERTYPE_MAX)
+ rssiFilterType = mDefault.rssiFilterType;
+ if (rssiFilterOption < RSSIFILTEROPTION_MIN || matchType > RSSIFILTEROPTION_MAX)
+ rssiFilterOption = mDefault.rssiFilterOption;
+ if (this.rssiFilterType == rssiFilterType && this.rssiFilterOption == rssiFilterOption && sameCheck) return true;
+ msgBuffer[4] |= (byte) (rssiFilterType & 0xF);
+ msgBuffer[4] |= (byte) ((rssiFilterOption & 0xF) << 4);
+ this.rssiFilterType = rssiFilterType;
+ this.rssiFilterOption = rssiFilterOption;
+ boolean bValue = sendHostRegRequest(HostRegRequests.HST_INV_RSSI_FILTERING_CONFIG, true, msgBuffer);
+ if (false) getHST_INV_RSSI_FILTERING_CONFIG();
+ return bValue;
+ }
+
+ final int RSSIFILTERTHRESHOLD_INVALID = -1, RSSIFILTERTHRESHOLD_MIN = 0, RSSIFILTERTHRESHOLD_MAX = 0xFFFF;
+ int rssiFilterThreshold1 = RSSIFILTERTHRESHOLD_INVALID;
+ public int getRssiFilterThreshold1() {
+ if (rssiFilterThreshold1 < 0) getHST_INV_RSSI_FILTERING_THRESHOLD();
+ return rssiFilterThreshold1;
+ }
+ int rssiFilterThreshold2 = RSSIFILTERTHRESHOLD_INVALID;
+ public int getRssiFilterThreshold2() {
+ if (rssiFilterThreshold2 < 0) getHST_INV_RSSI_FILTERING_THRESHOLD();
+ return rssiFilterThreshold2;
+ }
+ private boolean getHST_INV_RSSI_FILTERING_THRESHOLD() {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 8, 9, 0, 0, 0, 0};
+ return sendHostRegRequest(HostRegRequests.HST_INV_RSSI_FILTERING_THRESHOLD, false, msgBuffer);
+ }
+ public boolean setHST_INV_RSSI_FILTERING_THRESHOLD(int rssiFilterThreshold1, int rssiFilterThreshold2) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 8, 9, 0, 0, 0, 0};
+ if (rssiFilterThreshold1 < RSSIFILTERTHRESHOLD_MIN || rssiFilterThreshold1 > RSSIFILTERTHRESHOLD_MAX)
+ rssiFilterThreshold1 = mDefault.rssiFilterThreshold;
+ if (rssiFilterThreshold2 < RSSIFILTERTHRESHOLD_MIN || rssiFilterThreshold2 > RSSIFILTERTHRESHOLD_MAX)
+ rssiFilterThreshold2 = mDefault.rssiFilterThreshold;
+ if (this.rssiFilterThreshold1 == rssiFilterThreshold1 && this.rssiFilterThreshold2 == rssiFilterThreshold2 && sameCheck) return true;
+ msgBuffer[4] |= (byte) (rssiFilterThreshold1 & 0xFF);
+ msgBuffer[5] |= (byte) ((rssiFilterThreshold1 >> 8) & 0xFF);
+ msgBuffer[6] |= (byte) (rssiFilterThreshold2 & 0xFF);
+ msgBuffer[7] |= (byte) ((rssiFilterThreshold2 >> 8) & 0xFF);
+ this.rssiFilterThreshold1 = rssiFilterThreshold1;
+ this.rssiFilterThreshold2 = rssiFilterThreshold2;
+ boolean bValue = sendHostRegRequest(HostRegRequests.HST_INV_RSSI_FILTERING_THRESHOLD, true, msgBuffer);
+ if (false) getHST_INV_RSSI_FILTERING_THRESHOLD();
+ return bValue;
+ }
+
+ final long RSSIFILTERCOUNT_INVALID = -1, RSSIFILTERCOUNT_MIN = 0, RSSIFILTERCOUNT_MAX = 1000000;
+ long rssiFilterCount = RSSIFILTERCOUNT_INVALID;
+ public long getRssiFilterCount() {
+ if (rssiFilterCount < 0) getHST_INV_RSSI_FILTERING_COUNT();
+ return rssiFilterCount;
+ }
+ private boolean getHST_INV_RSSI_FILTERING_COUNT() {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 9, 9, 0, 0, 0, 0};
+ return sendHostRegRequest(HostRegRequests.HST_INV_RSSI_FILTERING_THRESHOLD, false, msgBuffer);
+ }
+ public boolean setHST_INV_RSSI_FILTERING_COUNT(long rssiFilterCount) {
+ appendToLog("entry: rssiFilterCount = " + rssiFilterCount + ", this.rssiFilterCount = " + this.rssiFilterCount);
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 9, 9, 0, 0, 0, 0};
+ if (rssiFilterCount < RSSIFILTERCOUNT_MIN || rssiFilterCount > RSSIFILTERCOUNT_MAX)
+ rssiFilterCount = mDefault.rssiFilterCount;
+ appendToLog("rssiFilterCount 1 = " + rssiFilterCount + ", this.rssiFilterCount = " + this.rssiFilterCount);
+ if (this.rssiFilterCount == rssiFilterCount && sameCheck) return true;
+ appendToLog("rssiFilterCount 2 = " + rssiFilterCount + ", this.rssiFilterCount = " + this.rssiFilterCount);
+ msgBuffer[4] |= (byte) (rssiFilterCount & 0xFF);
+ msgBuffer[5] |= (byte) ((rssiFilterCount >> 8) & 0xFF);
+ msgBuffer[6] |= (byte) ((rssiFilterCount >> 16) & 0xFF);
+ msgBuffer[7] |= (byte) ((rssiFilterCount >> 24) & 0xFF);
+ this.rssiFilterCount = rssiFilterCount;
+ appendToLog("entering to sendHostRegRequest: rssiFilterCount = " + rssiFilterCount);
+ boolean bValue = sendHostRegRequest(HostRegRequests.HST_INV_RSSI_FILTERING_COUNT, true, msgBuffer);
+ appendToLog("after sendHostRegRequest: rssiFilterCount = " + rssiFilterCount);
+ return bValue;
+ }
+
+ final int MATCHENABLE_INVALID = -1; final int MATCHENABLE_MIN = 0; final int MATCHENABLE_MAX = 1;
+ int matchEnable = MATCHENABLE_INVALID;
+ public int getInvMatchEnable() {
+ getHST_INV_EPC_MATCH_CFG();
+ return matchEnable;
+ }
+ boolean setInvMatchEnable(int matchEnable) {
+ return setHST_INV_EPC_MATCH_CFG(matchEnable, this.matchType, this.matchLength, this.matchOffset);
+ }
+ public boolean setInvMatchEnable(int matchEnable, int matchType, int matchLength, int matchOffset) {
+ return setHST_INV_EPC_MATCH_CFG(matchEnable, matchType, matchLength, matchOffset);
+ }
+
+ final int MATCHTYPE_INVALID = -1; final int MATCHTYPE_MIN = 0; final int MATCHTYPE_MAX = 1;
+ int matchType = MATCHTYPE_INVALID;
+ public int getInvMatchType() {
+ getHST_INV_EPC_MATCH_CFG();
+ return matchType;
+ }
+
+ final int MATCHLENGTH_INVALID = 0; final int MATCHLENGTH_MIN = 0; final int MATCHLENGTH_MAX = 496;
+ int matchLength = MATCHLENGTH_INVALID;
+ public int getInvMatchLength() {
+ getHST_INV_EPC_MATCH_CFG();
+ return matchLength;
+ }
+
+ final int MATCHOFFSET_INVALID = -1; final int MATCHOFFSET_MIN = 0; final int MATCHOFFSET_MAX = 496;
+ int matchOffset = MATCHOFFSET_INVALID;
+ public int getInvMatchOffset() {
+ getHST_INV_EPC_MATCH_CFG();
+ return matchOffset;
+ }
+
+ private boolean getHST_INV_EPC_MATCH_CFG() {
+ if (matchEnable < MATCHENABLE_MIN || matchEnable > MATCHENABLE_MAX
+ || matchType < MATCHTYPE_MIN || matchType > MATCHTYPE_MAX
+ || matchLength < MATCHLENGTH_MIN || matchLength > MATCHLENGTH_MAX
+ || matchOffset < MATCHOFFSET_MIN || matchOffset > MATCHOFFSET_MAX
+ ) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 0x11, 9, 0, 0, 0, 0};
+ return sendHostRegRequest(HostRegRequests.HST_INV_EPC_MATCH_CFG, false, msgBuffer);
+ } else {
+ return false;
+ }
+ }
+ private boolean setHST_INV_EPC_MATCH_CFG(int matchEnable, int matchType, int matchLength, int matchOffset) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 0x11, 9, 0, 0, 0, 0};
+ if (matchEnable < MATCHENABLE_MIN || matchEnable > MATCHENABLE_MAX)
+ matchEnable = mDefault.matchEnable;
+ if (matchType < MATCHTYPE_MIN || matchType > MATCHTYPE_MAX)
+ matchType = mDefault.matchType;
+ if (matchLength < MATCHLENGTH_MIN || matchLength > MATCHLENGTH_MAX)
+ matchLength = mDefault.matchLength;
+ if (matchOffset < MATCHOFFSET_MIN || matchOffset > MATCHOFFSET_MAX)
+ matchOffset = mDefault.matchOffset;
+ if (this.matchEnable == matchEnable && this.matchType == matchType && this.matchLength == matchLength && this.matchOffset == matchOffset && sameCheck) return true;
+ if (matchEnable != 0) {
+ msgBuffer[4] |= 0x01;
+ }
+ if (matchType != 0) {
+ msgBuffer[4] |= 0x02;
+ }
+ msgBuffer[4] |= (byte) ((matchLength % 64) << 2);
+ msgBuffer[5] |= (byte) ((matchLength / 64));
+ msgBuffer[5] |= (byte) ((matchOffset % 32) << 3);
+ msgBuffer[6] |= (byte) (matchOffset / 32);
+ this.matchEnable = matchEnable;
+ this.matchType = matchType;
+ this.matchLength = matchLength;
+ this.matchOffset = matchOffset;
+ return sendHostRegRequest(HostRegRequests.HST_INV_EPC_MATCH_CFG, true, msgBuffer);
+ }
+
+ byte[] invMatchData0_63; int invMatchDataReady = 0;
+ public String getInvMatchData() {
+ int length = matchLength;
+ String strValue = "";
+ for (int i = 0; i < 16; i++) {
+ if (length > 0) {
+ if ((invMatchDataReady & (0x01 << i)) == 0) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 0x12, 9, 0, 0, 0, 0};
+ msgBuffer[2] += i;
+ sendHostRegRequest(HostRegRequests.HST_INV_EPCDAT_0_3, false, msgBuffer);
+
+ strValue = null;
+ break;
+ } else {
+ for (int j = 0; j < 4; j++) {
+ strValue += String.format("%02X", invMatchData0_63[i * 4 + j]);
+ }
+ }
+ length -= 32;
+ }
+ }
+ return strValue;
+ }
+ public boolean setInvMatchData(String matchData) {
+ int length = matchData.length();
+ for (int i = 0; i < 16; i++) {
+ if (length > 0) {
+ length -= 8;
+
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 0x12, 9, 0, 0, 0, 0};
+ String hexString = "0123456789ABCDEF";
+ for (int j = 0; j < 8; j++) {
+ if (i * 8 + j + 1 <= matchData.length()) {
+ String subString = matchData.substring(i * 8 + j, i * 8 + j + 1).toUpperCase();
+ int k = 0;
+ for (k = 0; k < 16; k++) {
+ if (subString.matches(hexString.substring(k, k + 1))) {
+ break;
+ }
+ }
+ if (k == 16) return false;
+ if ((j / 2) * 2 == j) {
+ msgBuffer[4 + j / 2] |= (byte) (k << 4);
+ } else {
+ msgBuffer[4 + j / 2] |= (byte) (k);
+ }
+ }
+ }
+ msgBuffer[2] = (byte) ((msgBuffer[2] & 0xFF) + i);
+ if (sendHostRegRequest(HostRegRequests.HST_INV_EPCDAT_0_3, true, msgBuffer) == false)
+ return false;
+ else {
+ invMatchDataReady |= (0x01 << i);
+ System.arraycopy(msgBuffer, 4, invMatchData0_63, i * 4, 4); //appendToLog("Data=" + byteArrayToString(mRx000Setting.invMatchData0_63));
+// appendToLog("invMatchDataReady=" + Integer.toString(mRx000Setting.invMatchDataReady, 16) + ", message=" + byteArrayToString(msgBuffer));
+ }
+ }
+ }
+ return true;
+ }
+
+ //Tag access block parameters
+ boolean accessVerfiy;
+ final int ACCRETRY_INVALID = -1; final int ACCRETRY_MIN = 0; final int ACCRETRY_MAX = 7;
+ int accessRetry = ACCRETRY_INVALID;
+ int getAccessRetry() {
+ if (accessRetry < ACCRETRY_MIN || accessRetry > ACCRETRY_MAX) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 1, (byte) 0x0A, 0, 0, 0, 0};
+ sendHostRegRequest(HostRegRequests.HST_TAGACC_DESC_CFG, false, msgBuffer);
+ }
+ return accessRetry;
+ }
+ public boolean setAccessRetry(boolean accessVerfiy, int accessRetry) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 1, 0x0A, 0, 0, 0, 0};
+ if (DEBUG) appendToLog("setAccessRetry[" + accessVerfiy + ", " + accessRetry + "] with tagRead = " + tagRead + ", sameCheck = " + sameCheck + ", old accessVerfiy = " + this.accessVerfiy + ", accessRetry = " + this.accessRetry);
+ if (accessRetry < ACCRETRY_MIN || accessRetry > ACCRETRY_MAX)
+ accessRetry = mDefault.accessRetry;
+ if (this.accessVerfiy == accessVerfiy && this.accessRetry == accessRetry && sameCheck) return true;
+ msgBuffer[4] |= (byte) (accessRetry << 1);
+ if (accessVerfiy) msgBuffer[4] |= 0x01;
+ this.accessVerfiy = accessVerfiy;
+ this.accessRetry = accessRetry;
+ return sendHostRegRequest(HostRegRequests.HST_TAGACC_DESC_CFG, true, msgBuffer);
+ }
+
+ final int ACCBANK_INVALID = -1; final int ACCBANK_MIN = 0; final int ACCBANK_MAX = 3;
+ int accessBank = ACCBANK_INVALID; int accessBank2 = ACCBANK_INVALID;
+ int getAccessBank() {
+ if (accessBank < ACCBANK_MIN || accessBank > ACCBANK_MAX) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 2, (byte) 0x0A, 0, 0, 0, 0};
+ sendHostRegRequest(HostRegRequests.HST_TAGACC_BANK, false, msgBuffer);
+ }
+ return accessBank;
+ }
+ public boolean setAccessBank(int accessBank) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 2, 0x0A, 0, 0, 0, 0};
+ if (DEBUG) appendToLog("setAccessBank[" + accessBank + "] with tagRead = " + tagRead + ", sameCheck = " + sameCheck + ", old accessBank = " + this.accessBank);
+ if (accessBank < ACCBANK_MIN || accessBank > ACCBANK_MAX)
+ accessBank = mDefault.accessBank;
+ if (this.accessBank == accessBank && this.accessBank2 == 0 && sameCheck) return true;
+ msgBuffer[4] = (byte) (accessBank & 0x03);
+ this.accessBank = accessBank; this.accessBank2 = 0;
+ return sendHostRegRequest(HostRegRequests.HST_TAGACC_BANK, true, msgBuffer);
+ }
+ public boolean setAccessBank(int accessBank, int accessBank2) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 2, 0x0A, 0, 0, 0, 0};
+ if (DEBUG) appendToLog("setAccessBank[" + accessBank + ", " + accessBank2 + "] with tagRead = " + tagRead + ", sameCheck = " + sameCheck + ", old accessBank = " + this.accessBank + ", " + this.accessBank2);
+ if (tagRead != 2) accessBank2 = 0;
+ if (accessBank < ACCBANK_MIN || accessBank > ACCBANK_MAX)
+ accessBank = mDefault.accessBank;
+ if (accessBank2 < ACCBANK_MIN || accessBank2 > ACCBANK_MAX)
+ accessBank2 = mDefault.accessBank2;
+ if (this.accessBank == accessBank && this.accessBank2 == accessBank2 && sameCheck) return true;
+ msgBuffer[4] = (byte) (accessBank & 0x03);
+ msgBuffer[4] |= (byte) ((accessBank2 & 0x03) << 2);
+ this.accessBank = accessBank; this.accessBank2 = accessBank2;
+ return sendHostRegRequest(HostRegRequests.HST_TAGACC_BANK, true, msgBuffer);
+ }
+
+ final int ACCOFFSET_INVALID = -1; final int ACCOFFSET_MIN = 0; final int ACCOFFSET_MAX = 0xFFFF;
+ int accessOffset = ACCOFFSET_INVALID; int accessOffset2 = ACCOFFSET_INVALID;
+ int getAccessOffset() {
+ if (accessOffset < ACCOFFSET_MIN || accessOffset > ACCOFFSET_MAX) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 3, (byte) 0x0A, 0, 0, 0, 0};
+ sendHostRegRequest(HostRegRequests.HST_TAGACC_PTR, false, msgBuffer);
+ }
+ return accessOffset;
+ }
+ public boolean setAccessOffset(int accessOffset) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 3, 0x0A, 0, 0, 0, 0};
+ if (false) appendToLog("setAccessOffset[" + accessOffset + "] with tagRead = " + tagRead + ", sameCheck = " + sameCheck + ", old accessOffset = " + this.accessOffset);
+ if (accessOffset < ACCOFFSET_MIN || accessOffset > ACCOFFSET_MAX)
+ accessOffset = mDefault.accessOffset;
+ if (this.accessOffset == accessOffset && this.accessOffset2 == 0 && sameCheck) return true;
+ msgBuffer[4] = (byte) (accessOffset & 0xFF);
+ msgBuffer[5] = (byte) ((accessOffset >> 8) & 0xFF);
+ msgBuffer[6] = (byte) ((accessOffset >> 16) & 0xFF);
+ msgBuffer[7] = (byte) ((accessOffset >> 24) & 0xFF);
+ this.accessOffset = accessOffset; this.accessOffset2 = 0;
+ return sendHostRegRequest(HostRegRequests.HST_TAGACC_PTR, true, msgBuffer);
+ }
+ public boolean setAccessOffset(int accessOffset, int accessOffset2) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 3, 0x0A, 0, 0, 0, 0};
+ if (false) appendToLog("setAccessOffset[" + accessOffset + ", " + accessOffset2 + "] with tagRead = " + tagRead + ", sameCheck = " + sameCheck + ", old accessOffset = " + this.accessOffset + ", " + this.accessOffset2);
+ if (tagRead != 2) accessOffset2 = 0;
+ if (accessOffset < ACCOFFSET_MIN || accessOffset > ACCOFFSET_MAX)
+ accessOffset = mDefault.accessOffset;
+ if (accessOffset2 < ACCOFFSET_MIN || accessOffset2 > ACCOFFSET_MAX)
+ accessOffset2 = mDefault.accessOffset2;
+ if (this.accessOffset == accessOffset && this.accessOffset2 == accessOffset2 && sameCheck) return true;
+ msgBuffer[4] = (byte) (accessOffset & 0xFF);
+ msgBuffer[5] = (byte) ((accessOffset >> 8) & 0xFF);
+ msgBuffer[6] = (byte) (accessOffset2 & 0xFF);
+ msgBuffer[7] = (byte) ((accessOffset2 >> 8) & 0xFF);
+ this.accessOffset = accessOffset; this.accessOffset2 = accessOffset2;
+ return sendHostRegRequest(HostRegRequests.HST_TAGACC_PTR, true, msgBuffer);
+ }
+
+ final int ACCCOUNT_INVALID = -1; final int ACCCOUNT_MIN = 0; final int ACCCOUNT_MAX = 255;
+ int accessCount = ACCCOUNT_INVALID; int accessCount2 = ACCCOUNT_INVALID;
+ public int getAccessCount() {
+ if (accessCount < ACCCOUNT_MIN || accessCount > ACCCOUNT_MAX) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 4, (byte) 0x0A, 0, 0, 0, 0};
+ sendHostRegRequest(HostRegRequests.HST_TAGACC_CNT, false, msgBuffer);
+ }
+ return accessCount;
+ }
+ public boolean setAccessCount(int accessCount) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 4, 0x0A, 0, 0, 0, 0};
+ if (DEBUG) appendToLog("BtDataOut: SetAccessCount[" + accessCount + "] with tagRead = " + tagRead + ", sameCheck = " + sameCheck + ", old accessCount = " + this.accessCount);
+ if (accessCount < ACCCOUNT_MIN || accessCount > ACCCOUNT_MAX)
+ accessCount = mDefault.accessCount;
+ if ((this.accessCount == accessCount || accessCount == -1) && this.accessCount2 == 0 && sameCheck) return true;
+ msgBuffer[4] = (byte) (accessCount & 0xFF);
+ this.accessCount = accessCount; this.accessCount2 = 0;
+ return sendHostRegRequest(HostRegRequests.HST_TAGACC_CNT, true, msgBuffer);
+ }
+ public boolean setAccessCount(int accessCount, int accessCount2) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 4, 0x0A, 0, 0, 0, 0};
+ if (DEBUG) appendToLog("setAccessCount[" + accessCount + ", " + accessCount2 + "] with tagRead = " + tagRead + ", sameCheck = " + sameCheck + ", old accessCount = " + this.accessCount + ", " + this.accessCount2);
+ if (tagRead != 2) accessCount2 = 0;
+ if (accessCount < ACCCOUNT_MIN || accessCount > ACCCOUNT_MAX)
+ accessCount = mDefault.accessCount;
+ if (accessCount2 < ACCCOUNT_MIN || accessCount2 > ACCCOUNT_MAX)
+ accessCount2 = mDefault.accessCount2;
+ if (this.accessCount == accessCount && this.accessCount2 == accessCount2 && sameCheck) return true;
+ msgBuffer[4] = (byte) (accessCount & 0xFF);
+ msgBuffer[5] = (byte) (accessCount2 & 0xFF);
+ this.accessCount = accessCount; this.accessCount2 = accessCount2;
+ return sendHostRegRequest(HostRegRequests.HST_TAGACC_CNT, true, msgBuffer);
+ }
+
+ final int ACCLOCKACTION_INVALID = -1; final int ACCLOCKACTION_MIN = 0; final int ACCLOCKACTION_MAX = 0x3FF;
+ int accessLockAction = ACCLOCKACTION_INVALID;
+ int getAccessLockAction() {
+ if (accessLockAction < ACCLOCKACTION_MIN || accessLockAction > ACCLOCKACTION_MAX)
+ getHST_TAGACC_LOCKCFG();
+ return accessLockAction;
+ }
+ boolean setAccessLockAction(int accessLockAction) {
+ return setAccessLockAction(accessLockAction, accessLockMask);
+ }
+
+ final int ACCLOCKMASK_INVALID = -1; final int ACCLOCKMASK_MIN = 0; final int ACCLOCKMASK_MAX = 0x3FF;
+ int accessLockMask = ACCLOCKMASK_INVALID;
+ int getAccessLockMask() {
+ if (accessLockMask < ACCLOCKMASK_MIN || accessLockMask > ACCLOCKMASK_MAX)
+ getHST_TAGACC_LOCKCFG();
+ return accessLockMask;
+ }
+ boolean setAccessLockMask(int accessLockMask) {
+ return setAccessLockAction(accessLockAction, accessLockMask);
+ }
+
+ boolean getHST_TAGACC_LOCKCFG() {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 5, (byte) 0x0A, 0, 0, 0, 0};
+ return sendHostRegRequest(HostRegRequests.HST_TAGACC_LOCKCFG, false, msgBuffer);
+ }
+ public boolean setAccessLockAction(int accessLockAction, int accessLockMask) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 5, 0x0A, 0, 0, 0, 0};
+ if (accessLockAction < ACCLOCKACTION_MIN || accessLockAction > ACCLOCKACTION_MAX)
+ accessLockAction = mDefault.accessLockAction;
+ if (accessLockMask < ACCLOCKMASK_MIN || accessLockMask > ACCLOCKMASK_MAX)
+ accessLockMask = mDefault.accessLockMask;
+ if (this.accessLockAction == accessLockAction && this.accessLockMask == accessLockMask && sameCheck) return true;
+ msgBuffer[4] = (byte) (accessLockAction & 0xFF);
+ msgBuffer[5] |= (byte) ((accessLockAction & 0x3FF) >> 8);
+
+ msgBuffer[5] |= (byte) ((accessLockMask & 0x3F) << 2);
+ msgBuffer[6] |= (byte) ((accessLockMask & 0x3FF) >> 6);
+ this.accessLockAction = accessLockAction;
+ this.accessLockMask = accessLockMask;
+ return sendHostRegRequest(HostRegRequests.HST_TAGACC_LOCKCFG, true, msgBuffer);
+ }
+
+ final int ACCPWD_INVALID = 0; final long ACCPWD_MIN = 0; final long ACCPWD_MAX = 0x0FFFFFFFF;
+ String stringAccessPasword = "00000000";
+ public boolean setRx000AccessPassword(String password) {
+ //appendToLog("BtDataOut: setRx000AccessPassword with password = " + password + ", stringAccessPasword = " + stringAccessPasword);
+ if (stringAccessPasword.matches(password) && sameCheck) return true;
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 6, (byte) 0x0A, 0, 0, 0, 0};
+ if (password == null) password = "";
+ String hexString = "0123456789ABCDEF";
+ for (int j = 0; j < 16; j++) {
+ if (j + 1 <= password.length()) {
+ String subString = password.substring(j, j + 1).toUpperCase();
+ int k = 0;
+ for (k = 0; k < 16; k++) {
+ if (subString.matches(hexString.substring(k, k + 1))) {
+ break;
+ }
+ }
+ if (k == 16) return false;
+ if ((j / 2) * 2 == j) {
+ msgBuffer[7 - j / 2] |= (byte) (k << 4);
+ } else {
+ msgBuffer[7 - j / 2] |= (byte) (k);
+ }
+ }
+ }
+ boolean retValue = sendHostRegRequest(HostRegRequests.HST_TAGACC_ACCPWD, true, msgBuffer);
+ if (DEBUG) appendToLog("sendHostRegRequest(): retValue = " + retValue);
+ if (retValue) stringAccessPasword = password;
+ return retValue;
+ }
+
+ public boolean setRx000KillPassword(String password) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 7, (byte) 0x0A, 0, 0, 0, 0};
+ String hexString = "0123456789ABCDEF";
+ for (int j = 0; j < 16; j++) {
+ if (j + 1 <= password.length()) {
+ String subString = password.substring(j, j + 1).toUpperCase();
+ int k = 0;
+ for (k = 0; k < 16; k++) {
+ if (subString.matches(hexString.substring(k, k + 1))) {
+ break;
+ }
+ }
+ if (k == 16) return false;
+ if ((j / 2) * 2 == j) {
+ msgBuffer[7 - j / 2] |= (byte) (k << 4);
+ } else {
+ msgBuffer[7 - j / 2] |= (byte) (k);
+ }
+ }
+ }
+ boolean retValue = sendHostRegRequest(HostRegRequests.HST_TAGACC_KILLPWD, true, msgBuffer);
+ if (DEBUG) appendToLog("sendHostRegRequest(): retValue = " + retValue);
+ return retValue;
+ }
+
+ final int ACCWRITEDATSEL_INVALID = -1; final int ACCWRITEDATSEL_MIN = 0; final int ACCWRITEDATSEL_MAX = 7;
+ int accessWriteDataSelect = ACCWRITEDATSEL_INVALID;
+ int getAccessWriteDataSelect() {
+ if (accessWriteDataSelect < ACCWRITEDATSEL_MIN || accessWriteDataSelect > ACCWRITEDATSEL_MAX) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 8, (byte) 0x0A, 0, 0, 0, 0};
+ sendHostRegRequest(HostRegRequests.HST_TAGWRDAT_SEL, false, msgBuffer);
+ }
+ return accessWriteDataSelect;
+ }
+ boolean setAccessWriteDataSelect(int accessWriteDataSelect) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 8, 0x0A, 0, 0, 0, 0};
+ if (accessWriteDataSelect < ACCWRITEDATSEL_MIN || accessWriteDataSelect > ACCWRITEDATSEL_MAX)
+ accessWriteDataSelect = mDefault.accessWriteDataSelect;
+ if (this.accessWriteDataSelect == accessWriteDataSelect && sameCheck) return true;
+ accWriteDataReady = 0;
+ msgBuffer[4] = (byte) (accessWriteDataSelect & 0x07);
+ this.accessWriteDataSelect = accessWriteDataSelect;
+ return sendHostRegRequest(HostRegRequests.HST_TAGWRDAT_SEL, true, msgBuffer);
+ }
+
+ byte[] accWriteData0_63; int accWriteDataReady = 0;
+ String getAccessWriteData() {
+ int length = accessCount;
+ if (length > 32) {
+ length = 32;
+ }
+ String strValue = "";
+ for (int i = 0; i < 32; i++) {
+ if (length > 0) {
+ if ((accWriteDataReady & (0x01 << i)) == 0) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 9, (byte) 0x0A, 0, 0, 0, 0};
+ msgBuffer[2] += i;
+ sendHostRegRequest(HostRegRequests.HST_TAGWRDAT_0, false, msgBuffer);
+
+ strValue = null;
+ break;
+ } else {
+ for (int j = 0; j < 4; j++) {
+ strValue += String.format("%02X", accWriteData0_63[i * 4 + j]);
+ }
+ }
+ length -= 2;
+ }
+ }
+ return strValue;
+ }
+
+ public boolean setAccessWriteData(String dataInput) {
+ dataInput = dataInput.trim();
+ int writeBufLength = 16 * 2; //16
+ int wrieByteSize = 4; //8
+ int length = dataInput.length(); appendToLog("length = " + length);
+ if (length > wrieByteSize * writeBufLength) { appendToLog("1"); return false; }
+ for (int i = 0; i < writeBufLength; i++) {
+ if (length > 0) {
+ length -= wrieByteSize;
+ if ((i / 16) * 16 == i) {
+ if (true) {
+ if (setAccessWriteDataSelect(i/16) == false) return false;
+ }
+ else {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 8, (byte) 0x0A, 0, 0, 0, 0};
+ msgBuffer[4] = (byte) (i / 16);
+ if (sendHostRegRequest(HostRegRequests.HST_TAGWRDAT_SEL, true, msgBuffer) == false) {
+ appendToLog("23");
+ return false;
+ }
+ }
+ }
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 9, (byte) 0x0A, 0, 0, 0, 0};
+ String hexString = "0123456789ABCDEF";
+ for (int j = 0; j < wrieByteSize; j++) {
+// if (i * wrieByteSize + j + 1 <= dataInput.length()) {
+ appendToLog("dataInput = " + dataInput + ", i = " + i + ", wrieByteSize = " + wrieByteSize + ", j = " + j);
+ if (i * wrieByteSize + j >= dataInput.length()) break;
+ String subString = dataInput.substring(i * wrieByteSize + j, i * wrieByteSize + j + 1).toUpperCase();
+ appendToLog("subString = " + subString);
+ if (DEBUG) appendToLog(subString);
+ int k = 0;
+ for (k = 0; k < 16; k++) {
+ if (subString.matches(hexString.substring(k, k + 1))) {
+ break;
+ }
+ }
+ if (k == 16) { appendToLog("2: i= " + i + ", j=" + j + ", subString = " + subString); return false; }
+ if ((j / 2) * 2 == j) {
+ msgBuffer[5- j / 2] |= (byte) (k << 4);
+ } else {
+ msgBuffer[5 - j / 2] |= (byte) (k);
+ }
+// }
+ }
+ appendToLog("complete 4 bytes: " + byteArrayToString(msgBuffer));
+ msgBuffer[2] = (byte) ((msgBuffer[2] & 0xFF) + (i % 16));
+ if (wrieByteSize == 4) {
+ msgBuffer[6] = (byte)(i);
+ }
+ byte[] debugBuffer = new byte[4];
+ int k = 0;
+ for (; k < 4; k++) {
+ debugBuffer[k] = accWriteData0_63[i * 4 + k];
+ if (accWriteData0_63[i * 4 + k] != msgBuffer[7 - k]) break;
+ }
+ if (k != 4) {
+ appendToLog("BtDataOut: RfidReaderChipR2000.setAccessWriteData msgBuffer = " + byteArrayToString(msgBuffer) + ", debugBuffer = " + byteArrayToString(debugBuffer));
+ if (sendHostRegRequest(HostRegRequests.HST_TAGWRDAT_0, true, msgBuffer) == false) {
+ appendToLog("3");
+ return false;
+ } else {
+ rx000Setting.accWriteDataReady |= (0x01 << i);
+ if (DEBUG) appendToLog("accWriteReady=" + accWriteDataReady);
+ for (int k1 = 0; k1 < 4; k1++) {
+ accWriteData0_63[i * 4 + k1] = msgBuffer[7 - k1];
+ }
+ if (DEBUG) appendToLog("Data=" + byteArrayToString(accWriteData0_63));
+ }
+ }
+ } else break;
+ }
+ return true;
+ }
+
+ //RFTC block paramters
+ final int PROFILE_INVALID = -1; final int PROFILE_MIN = 0; final int PROFILE_MAX = 5; //profile 4 and 5 are custom profiles.
+ int currentProfile = PROFILE_INVALID;
+ public int getCurrentProfile() {
+ if (antennaSelect < ANTSLECT_MIN || antennaSelect > ANTSELECT_MAX) {
+ return ANTSELECT_INVALID;
+ } else {
+ if (currentProfile < PROFILE_MIN || currentProfile > PROFILE_MAX) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 0x60, 0x0B, 0, 0, 0, 0};
+ sendHostRegRequest(HostRegRequests.HST_RFTC_CURRENT_PROFILE, false, msgBuffer);
+ }
+ return currentProfile;
+ }
+ }
+
+ public boolean setCurrentProfile(int currentProfile) {
+ if (antennaSelect < ANTSLECT_MIN || antennaSelect > ANTSELECT_MAX) return false;
+ else {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 0x60, 0x0B, 0, 0, 0, 0};
+ if (currentProfile < PROFILE_MIN || currentProfile > PROFILE_MAX)
+ currentProfile = mDefault.currentProfile;
+ if (this.currentProfile == currentProfile && sameCheck) return true;
+ msgBuffer[4] = (byte) (currentProfile);
+ this.currentProfile = currentProfile;
+ return sendHostRegRequest(HostRegRequests.HST_RFTC_CURRENT_PROFILE, true, msgBuffer);
+ }
+ }
+
+ final int COUNTRYENUM_INVALID = -1; final int COUNTRYENUM_MIN = 1; final int COUNTRYENUM_MAX = 109;
+ final int COUNTRYCODE_INVALID = -1; final int COUNTRYCODE_MIN = 1; final int COUNTRYCODE_MAX = 9;
+ int countryEnumOem = COUNTRYENUM_INVALID; int countryEnum = COUNTRYENUM_INVALID; int countryCode = COUNTRYCODE_INVALID; // OemAddress = 0x02
+ String modelCode = null;
+
+ final int FREQCHANSEL_INVALID = -1; final int FREQCHANSEL_MIN = 0; final int FREQCHANSEL_MAX = 49;
+ int freqChannelSelect = FREQCHANSEL_INVALID;
+ public int getFreqChannelSelect() {
+ appendToLog("freqChannelSelect = " + freqChannelSelect);
+ if (freqChannelSelect < FREQCHANSEL_MIN || freqChannelSelect > FREQCHANSEL_MAX) {
+ {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 1, 0x0C, 0, 0, 0, 0};
+ sendHostRegRequest(HostRegRequests.HST_RFTC_FRQCH_SEL, false, msgBuffer);
+ }
+ }
+ return freqChannelSelect;
+ }
+ public boolean setFreqChannelSelect(int freqChannelSelect) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 1, 0x0C, 0, 0, 0, 0};
+ if (freqChannelSelect < FREQCHANSEL_MIN || freqChannelSelect > FREQCHANSEL_MAX) freqChannelSelect = mDefault.freqChannelSelect;
+ //if (this.freqChannelSelect == freqChannelSelect && sameCheck) return true;
+ appendToLog("freqChannelSelect = " + freqChannelSelect);
+ msgBuffer[4] = (byte) (freqChannelSelect);
+ this.freqChannelSelect = freqChannelSelect;
+ freqChannelSelect = FREQCHANCONFIG_INVALID; freqPllMultiplier = FREQPLLMULTIPLIER_INVALID;
+ return sendHostRegRequest(HostRegRequests.HST_RFTC_FRQCH_SEL, true, msgBuffer);
+ }
+
+ final int FREQCHANCONFIG_INVALID = -1; final int FREQCHANCONFIG_MIN = 0; final int FREQCHANCONFIG_MAX = 1;
+ int freqChannelConfig = FREQCHANCONFIG_INVALID;
+ public int getFreqChannelConfig() {
+ if (freqChannelConfig < FREQCHANCONFIG_MIN || freqChannelConfig > FREQCHANCONFIG_MAX) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 2, 0x0C, 0, 0, 0, 0};
+ sendHostRegRequest(HostRegRequests.HST_RFTC_FRQCH_CFG, false, msgBuffer);
+ }
+ return freqChannelConfig;
+ }
+ public boolean setFreqChannelConfig(boolean on) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 2, 0x0C, 0, 0, 0, 0};
+ boolean onCurrent = false;
+ if (freqChannelConfig != 0) onCurrent = true;
+// if (onCurrent == on && sameCheck) return true;
+ if (on) {
+ msgBuffer[4] = 1;
+ freqChannelConfig = 1;
+ } else {
+ freqChannelConfig = 0;
+ }
+ return sendHostRegRequest(HostRegRequests.HST_RFTC_FRQCH_CFG, true, msgBuffer);
+ }
+
+ final int FREQPLLMULTIPLIER_INVALID = -1;
+ int freqPllMultiplier = FREQPLLMULTIPLIER_INVALID;
+ int getFreqPllMultiplier() {
+ if (freqPllMultiplier == FREQPLLMULTIPLIER_INVALID) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 3, 0x0C, 0, 0, 0, 0};
+ sendHostRegRequest(HostRegRequests.HST_RFTC_FRQCH_DESC_PLLDIVMULT, false, msgBuffer);
+ }
+ return freqPllMultiplier;
+ }
+ public boolean setFreqPllMultiplier(int freqPllMultiplier) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 3, 0x0C, 0, 0, 0, 0};
+ msgBuffer[4] = (byte)(freqPllMultiplier & 0xFF);
+ msgBuffer[5] = (byte)((freqPllMultiplier >> 8) & 0xFF);
+ msgBuffer[6] = (byte)((freqPllMultiplier >> 16) & 0xFF);
+ msgBuffer[7] = (byte)((freqPllMultiplier >> 24) & 0xFF);
+ this.freqPllMultiplier = freqPllMultiplier;
+ return sendHostRegRequest(HostRegRequests.HST_RFTC_FRQCH_DESC_PLLDIVMULT, true, msgBuffer);
+ }
+
+ final int FREQPLLDAC_INVALID = -1;
+ int freqPllDac = FREQPLLDAC_INVALID;
+ int getFreqPllDac() {
+ if (freqPllDac == FREQPLLDAC_INVALID) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 4, 0x0C, 0, 0, 0, 0};
+ sendHostRegRequest(HostRegRequests.HST_RFTC_FRQCH_DESC_PLLDACCTL, false, msgBuffer);
+ }
+ return freqPllDac;
+ }
+
+ boolean setFreqChannelOverride(int freqStart) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 8, 0x0C, 0, 0, 0, 0};
+ msgBuffer[4] = (byte)(freqStart & 0xFF);
+ msgBuffer[5] = (byte)((freqStart >> 8) & 0xFF);
+ msgBuffer[6] = (byte)((freqStart >> 16) & 0xFF);
+ msgBuffer[7] = (byte)((freqStart >> 24) & 0xFF);
+ return sendHostRegRequest(HostRegRequests.HST_RFTC_FRQCH_CMDSTART, true, msgBuffer);
+ }
+ }
+ class AntennaSelectedData {
+ AntennaSelectedData(boolean set_default_setting, int default_setting_type) {
+ if (default_setting_type < 0) default_setting_type = 0;
+ if (default_setting_type > 5) default_setting_type = 5;
+ mDefault = new AntennaSelectedData_default(default_setting_type);
+ if (false && set_default_setting) {
+ antennaEnable = mDefault.antennaEnable;
+ antennaInventoryMode = mDefault.antennaInventoryMode;
+ antennaLocalAlgo = mDefault.antennaLocalAlgo;
+ antennaLocalStartQ = mDefault.antennaLocalStartQ;
+ antennaProfileMode = mDefault.antennaProfileMode;
+ antennaLocalProfile = mDefault.antennaLocalProfile;
+ antennaFrequencyMode = mDefault.antennaFrequencyMode;
+ antennaLocalFrequency = mDefault.antennaLocalFrequency;
+ antennaStatus = mDefault.antennaStatus;
+ antennaDefine = mDefault.antennaDefine;
+ antennaDwell = mDefault.antennaDwell;
+ antennaPower = mDefault.antennaPower; appendToLog("antennaPower is set to default " + antennaPower);
+ antennaInvCount = mDefault.antennaInvCount;
+ }
+ }
+
+ class AntennaSelectedData_default {
+ AntennaSelectedData_default(int set_default_setting) {
+ antennaEnable = mDefaultArray.antennaEnable[set_default_setting];
+ antennaInventoryMode = mDefaultArray.antennaInventoryMode[set_default_setting];
+ antennaLocalAlgo = mDefaultArray.antennaLocalAlgo[set_default_setting];
+ antennaLocalStartQ = mDefaultArray.antennaLocalStartQ[set_default_setting];
+ antennaProfileMode = mDefaultArray.antennaProfileMode[set_default_setting];
+ antennaLocalProfile = mDefaultArray.antennaLocalProfile[set_default_setting];
+ antennaFrequencyMode = mDefaultArray.antennaFrequencyMode[set_default_setting];
+ antennaLocalFrequency = mDefaultArray.antennaLocalFrequency[set_default_setting];
+ antennaStatus = mDefaultArray.antennaStatus[set_default_setting];
+ antennaDefine = mDefaultArray.antennaDefine[set_default_setting];
+ antennaDwell = mDefaultArray.antennaDwell[set_default_setting];
+ antennaPower = mDefaultArray.antennaPower[set_default_setting];
+ antennaInvCount = mDefaultArray.antennaInvCount[set_default_setting];
+ }
+
+ int antennaEnable;
+ int antennaInventoryMode;
+ int antennaLocalAlgo;
+ int antennaLocalStartQ;
+ int antennaProfileMode;
+ int antennaLocalProfile;
+ int antennaFrequencyMode;
+ int antennaLocalFrequency;
+ int antennaStatus;
+ int antennaDefine;
+ long antennaDwell;
+ long antennaPower;
+ long antennaInvCount;
+ }
+ AntennaSelectedData_default mDefault;
+
+ private class AntennaSelectedData_defaultArray { //0 for invalid default, 1 for 0, 2 for 1 to 3, 3 for 4 to 7, 4 for 8 to 11, 5 for 12 to 15
+ int[] antennaEnable = { -1, 1, 0, 0, 0, 0 };
+ int[] antennaInventoryMode = { -1, 0, 0, 0, 0, 0 };
+ int[] antennaLocalAlgo = { -1, 0, 0, 0, 0, 0 };
+ int[] antennaLocalStartQ = { -1, 0, 0, 0, 0, 0 };
+ int[] antennaProfileMode = { -1, 0, 0, 0, 0, 0 };
+ int[] antennaLocalProfile = { -1, 0, 0, 0, 0, 0 };
+ int[] antennaFrequencyMode = { -1, 0, 0, 0, 0, 0 };
+ int[] antennaLocalFrequency = { -1, 0, 0, 0, 0, 0 };
+ int[] antennaStatus = { -1, 0, 0, 0, 0, 0 };
+ int[] antennaDefine = { -1, 0, 0, 1, 2, 3 };
+ long[] antennaDwell = { -1, 2000, 2000, 2000, 2000, 2000 };
+ long[] antennaPower = { -1, 300, 0, 0, 0, 0 };
+ long[] antennaInvCount = { -1, 8192, 8192, 8192, 8192, 8192 };
+ }
+ AntennaSelectedData_defaultArray mDefaultArray = new AntennaSelectedData_defaultArray();
+
+ final int ANTENABLE_INVALID = -1; final int ANTENABLE_MIN = 0; final int ANTENABLE_MAX = 1;
+ int antennaEnable = ANTENABLE_INVALID;
+ int getAntennaEnable() {
+ if (antennaEnable < ANTENABLE_MIN || antennaEnable > ANTENABLE_MAX)
+ getHST_ANT_DESC_CFG();
+ return antennaEnable;
+ }
+ boolean setAntennaEnable(int antennaEnable) {
+ return setAntennaEnable(antennaEnable, antennaInventoryMode, antennaLocalAlgo, antennaLocalStartQ,
+ antennaProfileMode, antennaLocalProfile, antennaFrequencyMode, antennaLocalFrequency);
+ }
+
+ final int ANTINVMODE_INVALID = 0; final int ANTINVMODE_MIN = 0; final int ANTINVMODE_MAX = 1;
+ int antennaInventoryMode = ANTINVMODE_INVALID;
+ int getAntennaInventoryMode() {
+ if (antennaInventoryMode < ANTPROFILEMODE_MIN || antennaInventoryMode > ANTPROFILEMODE_MAX)
+ getHST_ANT_DESC_CFG();
+ return antennaInventoryMode;
+ }
+ boolean setAntennaInventoryMode(int antennaInventoryMode) {
+ return setAntennaEnable(antennaEnable, antennaInventoryMode, antennaLocalAlgo, antennaLocalStartQ, antennaProfileMode,
+ antennaLocalProfile, antennaFrequencyMode, antennaLocalFrequency);
+ }
+
+ final int ANTLOCALALGO_INVALID = 0; final int ANTLOCALALGO_MIN = 0; final int ANTLOCALALGO_MAX = 5;
+ int antennaLocalAlgo = ANTLOCALALGO_INVALID;
+ int getAntennaLocalAlgo() {
+ if (antennaLocalAlgo < ANTLOCALALGO_MIN || antennaLocalAlgo > ANTLOCALALGO_MAX)
+ getHST_ANT_DESC_CFG();
+ return antennaLocalAlgo;
+ }
+ boolean setAntennaLocalAlgo(int antennaLocalAlgo) {
+ return setAntennaEnable(antennaEnable, antennaInventoryMode, antennaLocalAlgo, antennaLocalStartQ,
+ antennaProfileMode, antennaLocalProfile, antennaFrequencyMode, antennaLocalFrequency);
+ }
+
+ final int ANTLOCALSTARTQ_INVALID = 0; final int ANTLOCALSTARTQ_MIN = 0; final int ANTLOCALSTARTQ_MAX = 15;
+ int antennaLocalStartQ = ANTLOCALSTARTQ_INVALID;
+ int getAntennaLocalStartQ() {
+ if (antennaLocalStartQ < ANTLOCALSTARTQ_MIN || antennaLocalStartQ > ANTLOCALSTARTQ_MAX)
+ getHST_ANT_DESC_CFG();
+ return antennaLocalStartQ;
+ }
+ boolean setAntennaLocalStartQ(int antennaLocalStartQ) {
+ return setAntennaEnable(antennaEnable, antennaInventoryMode, antennaLocalAlgo, antennaLocalStartQ,
+ antennaProfileMode, antennaLocalProfile, antennaFrequencyMode, antennaLocalFrequency);
+ }
+
+ final int ANTPROFILEMODE_INVALID = 0; final int ANTPROFILEMODE_MIN = 0; final int ANTPROFILEMODE_MAX = 1;
+ int antennaProfileMode = ANTPROFILEMODE_INVALID;
+ int getAntennaProfileMode() {
+ if (antennaProfileMode < ANTPROFILEMODE_MIN || antennaProfileMode > ANTPROFILEMODE_MAX)
+ getHST_ANT_DESC_CFG();
+ return antennaProfileMode;
+ }
+ boolean setAntennaProfileMode(int antennaProfileMode) {
+ return setAntennaEnable(antennaEnable, antennaInventoryMode, antennaLocalAlgo, antennaLocalStartQ,
+ antennaProfileMode, antennaLocalProfile, antennaFrequencyMode, antennaLocalFrequency);
+ }
+
+ final int ANTLOCALPROFILE_INVALID = 0; final int ANTLOCALPROFILE_MIN = 0; final int ANTLOCALPROFILE_MAX = 5;
+ int antennaLocalProfile = ANTLOCALPROFILE_INVALID;
+ int getAntennaLocalProfile() {
+ if (antennaLocalProfile < ANTLOCALPROFILE_MIN || antennaLocalProfile > ANTLOCALPROFILE_MIN)
+ getHST_ANT_DESC_CFG();
+ return antennaLocalProfile;
+ }
+ boolean setAntennaLocalProfile(int antennaLocalProfile) {
+ return setAntennaEnable(antennaEnable, antennaInventoryMode, antennaLocalAlgo, antennaLocalStartQ,
+ antennaProfileMode, antennaLocalProfile, antennaFrequencyMode, antennaLocalFrequency);
+ }
+
+ final int ANTFREQMODE_INVALID = 0; final int ANTFREQMODE_MIN = 0; final int ANTFREQMODE_MAX = 1;
+ int antennaFrequencyMode = ANTFREQMODE_INVALID;
+ int getAntennaFrequencyMode() {
+ if (antennaFrequencyMode < ANTFREQMODE_MIN || antennaFrequencyMode > ANTFREQMODE_MAX)
+ getHST_ANT_DESC_CFG();
+ return antennaFrequencyMode;
+ }
+ boolean setAntennaFrequencyMode(int antennaFrequencyMode) {
+ return setAntennaEnable(antennaEnable, antennaInventoryMode, antennaLocalAlgo, antennaLocalStartQ,
+ antennaProfileMode, antennaLocalProfile, antennaFrequencyMode, antennaLocalFrequency);
+ }
+
+ final int ANTLOCALFREQ_INVALID = 0; final int ANTLOCALFREQ_MIN = 0; final int ANTLOCALFREQ_MAX = 49;
+ int antennaLocalFrequency = ANTLOCALFREQ_INVALID;
+ int getAntennaLocalFrequency() {
+ if (antennaLocalFrequency < ANTLOCALFREQ_MIN || antennaLocalFrequency > ANTLOCALFREQ_MAX)
+ getHST_ANT_DESC_CFG();
+ return antennaLocalFrequency;
+ }
+ boolean setAntennaLocalFrequency(int antennaLocalFrequency) {
+ return setAntennaEnable(antennaEnable, antennaInventoryMode, antennaLocalAlgo, antennaLocalStartQ,
+ antennaProfileMode, antennaLocalProfile, antennaFrequencyMode, antennaLocalFrequency);
+ }
+
+ private boolean getHST_ANT_DESC_CFG() {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 2, 7, 0, 0, 0, 0};
+ return sendHostRegRequest(HostRegRequests.HST_ANT_DESC_CFG, false, msgBuffer);
+ }
+ boolean setAntennaEnable(int antennaEnable, int antennaInventoryMode, int antennaLocalAlgo, int antennaLocalStartQ,
+ int antennaProfileMode, int antennaLocalProfile,
+ int antennaFrequencyMode, int antennaLocalFrequency) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 2, 7, 0, 0, 0, 0};
+ if (antennaEnable < ANTENABLE_MIN || antennaEnable > ANTENABLE_MAX)
+ antennaEnable = mDefault.antennaEnable;
+ if (antennaInventoryMode < ANTINVMODE_MIN || antennaInventoryMode > ANTINVMODE_MAX)
+ antennaInventoryMode = mDefault.antennaInventoryMode;
+ if (antennaLocalAlgo < ANTLOCALALGO_MIN || antennaLocalAlgo > ANTLOCALALGO_MAX)
+ antennaLocalAlgo = mDefault.antennaLocalAlgo;
+ if (antennaLocalStartQ < ANTLOCALSTARTQ_MIN || antennaLocalStartQ > ANTLOCALSTARTQ_MAX)
+ antennaLocalStartQ = mDefault.antennaLocalStartQ;
+ if (antennaProfileMode < ANTPROFILEMODE_MIN || antennaProfileMode > ANTPROFILEMODE_MAX)
+ antennaProfileMode = mDefault.antennaProfileMode;
+ if (antennaLocalProfile < ANTLOCALPROFILE_MIN || antennaLocalProfile > ANTLOCALPROFILE_MAX)
+ antennaLocalProfile = mDefault.antennaLocalProfile;
+ if (antennaFrequencyMode < ANTFREQMODE_MIN || antennaFrequencyMode > ANTFREQMODE_MAX)
+ antennaFrequencyMode = mDefault.antennaFrequencyMode;
+ if (antennaLocalFrequency < ANTLOCALFREQ_MIN || antennaLocalFrequency > ANTLOCALFREQ_MAX)
+ antennaLocalFrequency = mDefault.antennaLocalFrequency;
+ if (this.antennaEnable == antennaEnable && this.antennaInventoryMode == antennaInventoryMode && this.antennaLocalAlgo == antennaLocalAlgo
+ && this.antennaLocalStartQ == antennaLocalStartQ && this.antennaProfileMode == antennaProfileMode && this.antennaLocalProfile == antennaLocalProfile
+ && this.antennaFrequencyMode == antennaFrequencyMode && this.antennaLocalFrequency == antennaLocalFrequency
+ && sameCheck)
+ return true;
+ msgBuffer[4] |= antennaEnable;
+ msgBuffer[4] |= (antennaInventoryMode << 1);
+ msgBuffer[4] |= (antennaLocalAlgo << 2);
+ msgBuffer[4] |= (antennaLocalStartQ << 4);
+ msgBuffer[5] |= antennaProfileMode;
+ msgBuffer[5] |= (antennaLocalProfile << 1);
+ msgBuffer[5] |= (antennaFrequencyMode << 5);
+ msgBuffer[5] |= ((antennaLocalFrequency & 0x03) << 6);
+ msgBuffer[6] |= (antennaLocalFrequency >> 2);
+ this.antennaEnable = antennaEnable;
+ this.antennaInventoryMode = antennaInventoryMode;
+ this.antennaLocalAlgo = antennaLocalAlgo;
+ this.antennaLocalStartQ = antennaLocalStartQ;
+ this.antennaProfileMode = antennaProfileMode;
+ this.antennaLocalProfile = antennaLocalProfile;
+ this.antennaFrequencyMode = antennaFrequencyMode;
+ this.antennaLocalFrequency = antennaLocalFrequency;
+ return sendHostRegRequest(HostRegRequests.HST_ANT_DESC_CFG, true, msgBuffer);
+ }
+
+ final int ANTSTATUS_INVALID = -1; final int ANTSTATUS_MIN = 0; final int ANTSTATUS_MAX = 0xFFFFF;
+ int antennaStatus = ANTSTATUS_INVALID;
+ int getAntennaStatus() {
+ if (antennaStatus < ANTSTATUS_MIN || antennaStatus > ANTSTATUS_MAX) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 3, 7, 0, 0, 0, 0};
+ sendHostRegRequest(HostRegRequests.MAC_ANT_DESC_STAT, false, msgBuffer);
+ }
+ return antennaStatus;
+ }
+
+ final int ANTDEFINE_INVALID = -1; final int ANTDEFINE_MIN = 0; final int ANTDEFINE_MAX = 3;
+ int antennaDefine = ANTDEFINE_INVALID;
+ int getAntennaDefine() {
+ if (antennaDefine < ANTDEFINE_MIN || antennaDefine > ANTDEFINE_MAX) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 4, 7, 0, 0, 0, 0};
+ sendHostRegRequest(HostRegRequests.HST_ANT_DESC_PORTDEF, false, msgBuffer);
+ }
+ return antennaDefine;
+ }
+
+ final long ANTDWELL_INVALID = -1; final long ANTDWELL_MIN = 0; final long ANTDWELL_MAX = 0xFFFF;
+ long antennaDwell = ANTDWELL_INVALID;
+ long getAntennaDwell() {
+ if (antennaDwell < ANTDWELL_MIN || antennaDwell > ANTDWELL_MAX) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 5, 7, 0, 0, 0, 0};
+ sendHostRegRequest(HostRegRequests.HST_ANT_DESC_DWELL, false, msgBuffer);
+ }
+ return antennaDwell;
+ }
+ boolean setAntennaDwell(long antennaDwell) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 5, 7, 0, 0, 0, 0};
+ if (antennaDwell < ANTDWELL_MIN || antennaDwell > ANTDWELL_MAX)
+ antennaDwell = mDefault.antennaDwell;
+ if (this.antennaDwell == antennaDwell && sameCheck) return true;
+ msgBuffer[4] = (byte) (antennaDwell % 256);
+ msgBuffer[5] = (byte) ((antennaDwell >> 8) % 256);
+ msgBuffer[6] = (byte) ((antennaDwell >> 16) % 256);
+ msgBuffer[7] = (byte) ((antennaDwell >> 24) % 256);
+ this.antennaDwell = antennaDwell;
+ return sendHostRegRequest(HostRegRequests.HST_ANT_DESC_DWELL, true, msgBuffer);
+ }
+
+ final int ANTARGET_INVALID = -1; final int ANTARGET_MIN = 0; final int ANTARGET_MAX = 1;
+ int antennaTarget = ANTARGET_INVALID;
+ byte[] antennaInventoryRoundControl = null;
+ final int ANTOGGLE_INVALID = -1; final int ANTOGGLE_MIN = 0; final int ANTOGGLE_MAX = 100;
+ int antennaToggle = ANTOGGLE_INVALID;
+ final int ANTRFMODE_INVALID = -1; final int ANTRFMODE_MIN = 1; final int ANTRFMODE_MAX = 15;
+ int antennaRfMode = ANTRFMODE_INVALID;
+
+ final long ANTPOWER_INVALID = -1; final long ANTPOWER_MIN = 0; final long ANTPOWER_MAX = 330; //Maximum 330\
+ long antennaPower = ANTPOWER_INVALID; //default value = 300
+ long getAntennaPower() {
+ if (antennaPower < ANTPOWER_MIN || antennaPower > ANTPOWER_MAX) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 6, 7, 0, 0, 0, 0};
+ sendHostRegRequest(HostRegRequests.HST_ANT_DESC_RFPOWER, false, msgBuffer);
+ }
+ return antennaPower;
+ }
+ boolean antennaPowerSet = false;
+ boolean setAntennaPower(long antennaPower) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 6, 7, 0, 0, 0, 0};
+ if (antennaPower < ANTPOWER_MIN || antennaPower > ANTPOWER_MAX)
+ antennaPower = mDefault.antennaPower;
+ if (this.antennaPower == antennaPower && sameCheck) return true;
+ msgBuffer[4] = (byte) (antennaPower % 256);
+ msgBuffer[5] = (byte) ((antennaPower >> 8) % 256);
+ this.antennaPower = antennaPower;
+ antennaPowerSet = true;
+ return sendHostRegRequest(HostRegRequests.HST_ANT_DESC_RFPOWER, true, msgBuffer);
+ }
+
+ final long ANTINVCOUNT_INVALID = -1; final long ANTINVCOUNT_MIN = 0; final long ANTINVCOUNT_MAX = 0xFFFFFFFFL;
+ long antennaInvCount = ANTINVCOUNT_INVALID;
+ long getAntennaInvCount() {
+ if (antennaInvCount < ANTINVCOUNT_MIN || antennaInvCount > ANTINVCOUNT_MAX) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 7, 7, 0, 0, 0, 0};
+ sendHostRegRequest(HostRegRequests.HST_ANT_DESC_INV_CNT, false, msgBuffer);
+ }
+ return antennaInvCount;
+ }
+ boolean setAntennaInvCount(long antennaInvCount) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 7, 7, 0, 0, 0, 0};
+ if (antennaInvCount < ANTINVCOUNT_MIN || antennaInvCount > ANTINVCOUNT_MAX)
+ antennaInvCount = mDefault.antennaInvCount;
+ if (this.antennaInvCount == antennaInvCount && sameCheck) return true;
+ msgBuffer[4] = (byte) (antennaInvCount % 256);
+ msgBuffer[5] = (byte) ((antennaInvCount >> 8) % 256);
+ msgBuffer[6] = (byte) ((antennaInvCount >> 16) % 256);
+ msgBuffer[7] = (byte) ((antennaInvCount >> 24) % 256);
+ this.antennaInvCount = antennaInvCount;
+ return sendHostRegRequest(HostRegRequests.HST_ANT_DESC_INV_CNT, true, msgBuffer);
+ }
+ }
+ class InvSelectData {
+ InvSelectData(boolean set_default_setting) {
+ if (set_default_setting) {
+ selectEnable = mDefault.selectEnable;
+ selectTarget = mDefault.selectTarget;
+ selectAction = mDefault.selectAction;
+ selectDelay = mDefault.selectDelay;
+ selectMaskBank = mDefault.selectMaskBank;
+ selectMaskOffset = mDefault.selectMaskOffset;
+ selectMaskLength = mDefault.selectMaskLength;
+ selectMaskDataReady = mDefault.selectMaskDataReady;
+ //Log.i("Hello", "BtDataOut 123b");
+ }
+ }
+
+ private class InvSelectData_default {
+ int selectEnable = 0;
+ int selectTarget = 0;
+ int selectAction = 0;
+ int selectDelay = 0;
+ int selectMaskBank = 0;
+ int selectMaskOffset = 0;
+ int selectMaskLength = 0;
+ byte[] selectMaskData0_31 = new byte[4 * 8]; byte selectMaskDataReady = 0;
+ }
+ InvSelectData_default mDefault = new InvSelectData_default();
+
+ final int INVSELENABLE_INVALID = 0; final int INVSELENABLE_MIN = 0; final int INVSELENABLE_MAX = 1;
+ int selectEnable = INVSELENABLE_INVALID;
+ int getSelectEnable() {
+ getRx000HostReg_HST_TAGMSK_DESC_CFG();
+ return selectEnable;
+ }
+ boolean setSelectEnable(int selectEnable) {
+ appendToLog("BtDataOut: RfidReaderChipR200.setSelectEnable");
+ return setRx000HostReg_HST_TAGMSK_DESC_CFG(selectEnable, this.selectTarget, this.selectAction, this.selectDelay);
+ }
+
+ final int INVSELTARGET_INVALID = -1; final int INVSELTARGET_MIN = 0; final int INVSELTARGET_MAX = 7;
+ int selectTarget = INVSELTARGET_INVALID;
+ int getSelectTarget() {
+ getRx000HostReg_HST_TAGMSK_DESC_CFG();
+ return selectTarget;
+ }
+
+ final int INVSELACTION_INVALID = -1; final int INVSELACTION_MIN = 0; final int INVSELACTION_MAX = 7;
+ int selectAction = INVSELACTION_INVALID;
+ int getSelectAction() {
+ getRx000HostReg_HST_TAGMSK_DESC_CFG();
+ return selectAction;
+ }
+
+ final int INVSELDELAY_INVALID = -1; final int INVSELDELAY_MIN = 0; final int INVSELDELAY_MAX = 255;
+ int selectDelay = INVSELDELAY_INVALID;
+ int getSelectDelay() {
+ getRx000HostReg_HST_TAGMSK_DESC_CFG();
+ return selectDelay;
+ }
+
+ boolean getRx000HostReg_HST_TAGMSK_DESC_CFG() {
+ if (selectEnable < INVSELENABLE_MIN || selectEnable > INVSELENABLE_MAX
+ || selectTarget < INVSELTARGET_MIN || selectTarget > INVSELTARGET_MAX
+ || selectAction < INVSELACTION_MIN || selectAction > INVSELACTION_MAX
+ || selectDelay < INVSELDELAY_MIN || selectDelay > INVSELDELAY_MAX
+ ) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 1, 8, 0, 0, 0, 0};
+ return sendHostRegRequest(HostRegRequests.HST_TAGMSK_DESC_CFG, false, msgBuffer);
+ } else {
+ return false;
+ }
+ }
+ boolean setRx000HostReg_HST_TAGMSK_DESC_CFG(int selectEnable, int selectTarget, int selectAction, int selectDelay) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 1, 8, 0, 0, 0, 0};
+ if (utility.DEBUG_SELECT) appendToLog("Debug_Select: RfidReaderR2000.setRx000HostReg_HST_TAGMSK_DESC_CFG[" +
+ selectEnable + "," + selectTarget + "," + selectAction + "," + selectDelay + "] with old SelectEnable/Target/Action/Delay =" +
+ this.selectEnable + "," + this.selectTarget + "," + this.selectAction + "," + this.selectDelay);
+ if (selectEnable < INVSELENABLE_MIN || selectEnable > INVSELENABLE_MAX)
+ selectEnable = mDefault.selectEnable;
+ if (selectTarget < INVSELTARGET_MIN || selectTarget > INVSELTARGET_MAX)
+ selectTarget = mDefault.selectTarget;
+ if (selectAction < INVSELACTION_MIN || selectAction > INVSELACTION_MAX)
+ selectAction = mDefault.selectAction;
+ int selectDalay0 = selectDelay;
+ if (selectDelay < INVSELDELAY_MIN || selectDelay > INVSELDELAY_MAX)
+ selectDelay = mDefault.selectDelay;
+ if (this.selectEnable == selectEnable && this.selectTarget == selectTarget && this.selectAction == selectAction && this.selectDelay == selectDelay && sameCheck) return true;
+ msgBuffer[4] |= (byte) (selectEnable & 0x1);
+ msgBuffer[4] |= (byte) ((selectTarget & 0x07) << 1);
+ msgBuffer[4] |= (byte) ((selectAction & 0x07) << 4);
+ msgBuffer[5] |= (byte) (selectDelay & 0xFF);
+ this.selectEnable = selectEnable;
+ this.selectTarget = selectTarget;
+ this.selectAction = selectAction;
+ this.selectDelay = selectDelay;
+ return sendHostRegRequest(HostRegRequests.HST_TAGMSK_DESC_CFG, true, msgBuffer);
+ }
+
+ final int INVSELMBANK_INVALID = -1; final int INVSELMBANK_MIN = 0; final int INVSELMBANK_MAX = 3;
+ int selectMaskBank = INVSELMBANK_INVALID;
+ int getSelectMaskBank() {
+ if (selectMaskBank < INVSELMBANK_MIN || selectMaskBank > INVSELMBANK_MAX) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 2, 8, 0, 0, 0, 0};
+ sendHostRegRequest(HostRegRequests.HST_TAGMSK_BANK, false, msgBuffer);
+ }
+ return selectMaskBank;
+ }
+ boolean setSelectMaskBank(int selectMaskBank) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 2, 8, 0, 0, 0, 0};
+ if (selectMaskBank < INVSELMBANK_MIN || selectMaskBank > INVSELMBANK_MAX)
+ selectMaskBank = mDefault.selectMaskBank;
+ if (this.selectMaskBank == selectMaskBank && sameCheck) return true;
+ msgBuffer[4] |= (byte) (selectMaskBank & 0x3);
+ this.selectMaskBank = selectMaskBank;
+ return sendHostRegRequest(HostRegRequests.HST_TAGMSK_BANK, true, msgBuffer);
+ }
+
+ final int INVSELMOFFSET_INVALID = -1; final int INVSELMOFFSET_MIN = 0; final int INVSELMOFFSET_MAX = 0xFFFF;
+ int selectMaskOffset = INVSELMOFFSET_INVALID;
+ int getSelectMaskOffset() {
+ if (selectMaskOffset < INVSELMOFFSET_MIN || selectMaskOffset > INVSELMOFFSET_MAX) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 3, 8, 0, 0, 0, 0};
+ sendHostRegRequest(HostRegRequests.HST_TAGMSK_PTR, false, msgBuffer);
+ }
+ return selectMaskOffset;
+ }
+ boolean setSelectMaskOffset(int selectMaskOffset) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 3, 8, 0, 0, 0, 0};
+ if (selectMaskOffset < INVSELMOFFSET_MIN || selectMaskOffset > INVSELMOFFSET_MAX)
+ selectMaskOffset = mDefault.selectMaskOffset;
+ if (this.selectMaskOffset == selectMaskOffset && sameCheck) return true;
+ msgBuffer[4] |= (byte) (selectMaskOffset & 0xFF);
+ msgBuffer[5] |= (byte) ((selectMaskOffset >> 8) & 0xFF);
+ this.selectMaskOffset = selectMaskOffset;
+ return sendHostRegRequest(HostRegRequests.HST_TAGMSK_PTR, true, msgBuffer);
+ }
+
+ final int INVSELMLENGTH_INVALID = -1; final int INVSELMLENGTH_MIN = 0; final int INVSELMLENGTH_MAX = 255;
+ int selectMaskLength = INVSELMLENGTH_INVALID;
+ int getSelectMaskLength() {
+ appendToLog("getSelectMaskData with selectMaskLength = " + selectMaskLength);
+ if (selectMaskLength < INVSELMLENGTH_MIN || selectMaskOffset > INVSELMLENGTH_MAX) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 4, 8, 0, 0, 0, 0};
+ sendHostRegRequest(HostRegRequests.HST_TAGMSK_LEN, false, msgBuffer);
+ }
+ return selectMaskLength;
+ }
+ boolean setSelectMaskLength(int selectMaskLength) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 4, 8, 0, 0, 0, 0};
+ if (selectMaskLength < INVSELMLENGTH_MIN) selectMaskLength = INVSELMLENGTH_MIN;
+ else if (selectMaskLength > INVSELMLENGTH_MAX) selectMaskLength = INVSELMLENGTH_MAX;
+ if (this.selectMaskLength == selectMaskLength && sameCheck) return true;
+ msgBuffer[4] |= (byte) (selectMaskLength & 0xFF);
+ if (selectMaskLength == INVSELMLENGTH_MAX) msgBuffer[5] = 1;
+ this.selectMaskLength = selectMaskLength;
+ return sendHostRegRequest(HostRegRequests.HST_TAGMSK_PTR, true, msgBuffer);
+ }
+
+ byte[] selectMaskData0_31 = new byte[4 * 8]; byte selectMaskDataReady = 0;
+ String getRx000SelectMaskData() {
+ if (false) appendToLog("getSelectMaskData with selectMaskData0_31 = " + byteArrayToString(selectMaskData0_31));
+ int length = selectMaskLength;
+ String strValue = "";
+ if (length < 0) {
+ getSelectMaskLength();
+ } else {
+ for (int i = 0; i < 8; i++) {
+ if (length > 0) {
+ if ((selectMaskDataReady & (0x01 << i)) == 0) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 5, 8, 0, 0, 0, 0};
+ msgBuffer[2] += i;
+ sendHostRegRequest(HostRegRequests.HST_TAGMSK_0_3, false, msgBuffer);
+
+ strValue = null;
+ break;
+ } else {
+ for (int j = 0; j < 4; j++) {
+ if (DEBUG) appendToLog("i = " + i + ", j = " + j + ", selectMaskData0_31 = " + selectMaskData0_31[i * 4 + j]);
+ strValue += String.format("%02X", selectMaskData0_31[i * 4 + j]);
+ }
+ }
+ length -= 32;
+ }
+ }
+ }
+ return strValue;
+ }
+ boolean setRx000SelectMaskData(String maskData) {
+ int length = maskData.length();
+ for (int i = 0; i < 8; i++) {
+ if (length > 0) {
+ length -= 8;
+
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 5, 8, 0, 0, 0, 0};
+ String hexString = "0123456789ABCDEF";
+ for (int j = 0; j < 8; j++) {
+ if (i * 8 + j + 1 <= maskData.length()) {
+ String subString = maskData.substring(i * 8 + j, i * 8 + j + 1).toUpperCase();
+ int k = 0;
+ for (k = 0; k < 16; k++) {
+ if (subString.matches(hexString.substring(k, k + 1))) {
+ break;
+ }
+ }
+ if (k == 16) return false;
+// appendToLog("setSelectMaskData(" + maskData +"): i=" + i + ", j=" + j + ", k=" + k);
+ if ((j / 2) * 2 == j) {
+ msgBuffer[4 + j / 2] |= (byte) (k << 4);
+ } else {
+ msgBuffer[4 + j / 2] |= (byte) (k);
+ }
+ }
+ }
+ msgBuffer[2] = (byte) ((msgBuffer[2] & 0xFF) + i);
+ if (sendHostRegRequest(HostRegRequests.HST_TAGMSK_0_3, true, msgBuffer) == false)
+ return false;
+ else {
+ selectMaskDataReady |= (0x01 << i);
+ if (DEBUG) appendToLog("Old selectMaskData0_31 = " + byteArrayToString(selectMaskData0_31));
+ System.arraycopy(msgBuffer, 4, selectMaskData0_31, i * 4, 4);
+ if (DEBUG) appendToLog("New selectMaskData0_31 = " + byteArrayToString(selectMaskData0_31));
+ }
+ }
+ }
+ return true;
+ }
+ }
+ class AlgoSelectedData {
+ AlgoSelectedData(boolean set_default_setting, int default_setting_type) {
+ if (default_setting_type < 0) default_setting_type = 0;
+ if (default_setting_type > 4) default_setting_type = 4;
+ mDefault = new AlgoSelectedData_default(default_setting_type);
+ if (set_default_setting) {
+ algoStartQ = mDefault.algoStartQ;
+ //Log.i("Hello", "BtDataOut: algoStartQ is set to default " + algoStartQ);
+ algoMaxQ = mDefault.algoMaxQ;
+ algoMinQ = mDefault.algoMinQ;
+ algoMaxRep = mDefault.algoMaxRep;
+ algoHighThres = mDefault.algoHighThres;
+ algoLowThres = mDefault.algoLowThres;
+ algoRetry = mDefault.algoRetry;
+ algoAbFlip = mDefault.algoAbFlip;
+ algoRunTilZero = mDefault.algoRunTilZero;
+ }
+ }
+
+ class AlgoSelectedData_default {
+ AlgoSelectedData_default(int set_default_setting) {
+ algoStartQ = mDefaultArray.algoStartQ[set_default_setting];
+ algoMaxQ = mDefaultArray.algoMaxQ[set_default_setting];
+ algoMinQ = mDefaultArray.algoMinQ[set_default_setting];
+ algoMaxRep = mDefaultArray.algoMaxRep[set_default_setting];
+ algoHighThres = mDefaultArray.algoHighThres[set_default_setting];
+ algoLowThres = mDefaultArray.algoLowThres[set_default_setting];
+ algoRetry = mDefaultArray.algoRetry[set_default_setting];
+ algoAbFlip = mDefaultArray.algoAbFlip[set_default_setting];
+ algoRunTilZero = mDefaultArray.algoRunTilZero[set_default_setting];
+ }
+
+ int algoStartQ = -1;
+ int algoMaxQ = -1;
+ int algoMinQ = -1;
+ int algoMaxRep = -1;
+ int algoHighThres = -1;
+ int algoLowThres = -1;
+ int algoRetry = -1;
+ int algoAbFlip = -1;
+ int algoRunTilZero = -1;
+ }
+ AlgoSelectedData_default mDefault;
+
+ class AlgoSelectedData_defaultArray { //0 for invalid default, 1 for 0, 2 for 1, 3 for 2, 4 for 3
+ int[] algoStartQ = { -1, 0, 0, 0, 7 };
+ int[] algoMaxQ = { -1, 0, 0, 0, 15 };
+ int[] algoMinQ = { -1, 0, 0, 0, 0 };
+ int[] algoMaxRep = { -1, 0, 0, 0, 4 };
+ int[] algoHighThres = { -1, 0, 5, 5, 5 };
+ int[] algoLowThres = { -1, 0, 3, 3, 3 };
+ int[] algoRetry = { -1, 0, 0, 0, 0 };
+ int[] algoAbFlip = { -1, 0, 1, 1, 1 };
+ int[] algoRunTilZero = { -1, 0, 0, 0, 0 };
+ }
+ AlgoSelectedData_defaultArray mDefaultArray = new AlgoSelectedData_defaultArray();
+
+ final int ALGOSTARTQ_INVALID = -1; final int ALGOSTARTQ_MIN = 0; final int ALGOSTARTQ_MAX = 15;
+ int algoStartQ = ALGOSTARTQ_INVALID;
+ int getAlgoStartQ(boolean getInvalid) {
+ if (getInvalid && (algoStartQ < ALGOSTARTQ_MIN || algoStartQ > ALGOSTARTQ_MAX)) getHST_INV_ALG_PARM_0();
+ return algoStartQ;
+ }
+ boolean setAlgoStartQ(int algoStartQ) {
+ return setAlgoStartQ(algoStartQ, algoMaxQ, algoMinQ, algoMaxRep, algoHighThres, algoLowThres);
+ }
+
+ final int ALGOMAXQ_INVALID = -1; final int ALGOMAXQ_MIN = 0; final int ALGOMAXQ_MAX = 15;
+ int algoMaxQ = ALGOMAXQ_INVALID;
+ int getAlgoMaxQ() {
+ if (algoMaxQ < ALGOMAXQ_MIN || algoMaxQ > ALGOMAXQ_MAX) getHST_INV_ALG_PARM_0();
+ return algoMaxQ;
+ }
+ boolean setAlgoMaxQ(int algoMaxQ) {
+ return setAlgoStartQ(algoStartQ, algoMaxQ, algoMinQ, algoMaxRep, algoHighThres, algoLowThres);
+ }
+
+ final int ALGOMINQ_INVALID = -1; final int ALGOMINQ_MIN = 0; final int ALGOMINQ_MAX = 15;
+ int algoMinQ = ALGOMINQ_INVALID;
+ int getAlgoMinQ() {
+ if (algoMinQ < ALGOMINQ_MIN || algoMinQ > ALGOMINQ_MAX) getHST_INV_ALG_PARM_0();
+ return algoMinQ;
+ }
+ boolean setAlgoMinQ(int algoMinQ) {
+ return setAlgoStartQ(algoStartQ, algoMaxQ, algoMinQ, algoMaxRep, algoHighThres, algoLowThres);
+ }
+
+ final int ALGOMAXREP_INVALID = -1; final int ALGOMAXREP_MIN = 0; final int ALGOMAXREP_MAX = 255;
+ int algoMaxRep = ALGOMAXREP_INVALID;
+ int getAlgoMaxRep() {
+ if (algoMaxRep < ALGOMAXREP_MIN || algoMaxRep > ALGOMAXREP_MAX) getHST_INV_ALG_PARM_0();
+ return algoMaxRep;
+ }
+ boolean setAlgoMaxRep(int algoMaxRep) {
+ return setAlgoStartQ(algoStartQ, algoMaxQ, algoMinQ, algoMaxRep, algoHighThres, algoLowThres);
+ }
+
+ final int ALGOHIGHTHRES_INVALID = -1; final int ALGOHIGHTHRES_MIN = 0; final int ALGOHIGHTHRES_MAX = 15;
+ int algoHighThres = ALGOHIGHTHRES_INVALID;
+ int getAlgoHighThres() {
+ if (algoHighThres < ALGOHIGHTHRES_MIN || algoHighThres > ALGOHIGHTHRES_MAX)
+ getHST_INV_ALG_PARM_0();
+ return algoHighThres;
+ }
+ boolean setAlgoHighThres(int algoHighThres) {
+ return setAlgoStartQ(algoStartQ, algoMaxQ, algoMinQ, algoMaxRep, algoHighThres, algoLowThres);
+ }
+
+ final int ALGOLOWTHRES_INVALID = -1; final int ALGOLOWTHRES_MIN = 0; final int ALGOLOWTHRES_MAX = 15;
+ int algoLowThres = ALGOLOWTHRES_INVALID;
+ int getAlgoLowThres() {
+ if (algoLowThres < ALGOLOWTHRES_MIN || algoLowThres > ALGOLOWTHRES_MAX)
+ getHST_INV_ALG_PARM_0();
+ return algoLowThres;
+ }
+ boolean setAlgoLowThres(int algoLowThres) {
+ return setAlgoStartQ(algoStartQ, algoMaxQ, algoMinQ, algoMaxRep, algoHighThres, algoLowThres);
+ }
+
+ private boolean getHST_INV_ALG_PARM_0() {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 3, 9, 0, 0, 0, 0};
+ return sendHostRegRequest(HostRegRequests.HST_INV_ALG_PARM_0, false, msgBuffer);
+ }
+ boolean setAlgoStartQ(int startQ, int algoMaxQ, int algoMinQ, int algoMaxRep, int algoHighThres, int algoLowThres) {
+ boolean DEBUG = false;
+ if (DEBUG) appendToLog("BtDataOut: startQ = " + startQ + ", algoMaxQ = " + algoMaxQ + ", algoMinQ = " + algoMinQ + ", algoMaxRep = " + algoMaxRep +
+ ", algoHighThres = " + algoHighThres + ", algoLowThres = " + algoLowThres +
+ ", Old = " + this.algoStartQ + ", " + this.algoMaxQ + ", " + this.algoMinQ + ", " + this.algoMaxRep +
+ ", " + this.algoHighThres + ", " + this.algoLowThres);
+
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 3, 9, 0, 0, 0, 0};
+ if (startQ < ALGOSTARTQ_MIN || startQ > ALGOSTARTQ_MAX) startQ = mDefault.algoStartQ;
+ if (algoMaxQ < ALGOMAXQ_MIN || algoMaxQ > ALGOMAXQ_MAX) algoMaxQ = mDefault.algoMaxQ;
+ if (algoMinQ < ALGOMINQ_MIN || algoMinQ > ALGOMINQ_MAX) algoMinQ = mDefault.algoMinQ;
+ if (algoMaxRep < ALGOMAXREP_MIN || algoMaxRep > ALGOMAXREP_MAX)
+ algoMaxRep = mDefault.algoMaxRep;
+ if (algoHighThres < ALGOHIGHTHRES_MIN || algoHighThres > ALGOHIGHTHRES_MAX)
+ algoHighThres = mDefault.algoHighThres;
+ if (algoLowThres < ALGOLOWTHRES_MIN || algoLowThres > ALGOLOWTHRES_MAX)
+ algoLowThres = mDefault.algoLowThres;
+ if (this.algoStartQ == startQ && this.algoMaxQ == algoMaxQ && this.algoMinQ == algoMinQ
+ && this.algoMaxRep == algoMaxRep && this.algoHighThres == algoHighThres && this.algoLowThres == algoLowThres
+ && sameCheck)
+ return true;
+ if (DEBUG) appendToLog("algoMaxRep = " + algoMaxRep + ", algoMaxRep = " + algoMaxRep + ", algoLowThres = " + algoLowThres);
+ msgBuffer[4] |= (byte) (startQ & 0x0F);
+ msgBuffer[4] |= (byte) ((algoMaxQ & 0x0F) << 4);
+ msgBuffer[5] |= (byte) (algoMinQ & 0x0F);
+ msgBuffer[5] |= (byte) ((algoMaxRep & 0xF) << 4);
+ msgBuffer[6] |= (byte) ((algoMaxRep & 0xF0) >> 4);
+ msgBuffer[6] |= (byte) ((algoHighThres & 0x0F) << 4);
+ msgBuffer[7] |= (byte) (algoLowThres & 0x0F);
+ this.algoStartQ = startQ;
+ if (false) appendToLog("this.algoStartQ is updated as " + this.algoStartQ);
+ this.algoMaxQ = algoMaxQ;
+ this.algoMinQ = algoMinQ;
+ this.algoMaxRep = algoMaxRep;
+ this.algoHighThres = algoHighThres;
+ this.algoLowThres = algoLowThres;
+ return sendHostRegRequest(HostRegRequests.HST_INV_ALG_PARM_0, true, msgBuffer);
+ }
+
+ final int ALGORETRY_INVALID = -1; final int ALGORETRY_MIN = 0; final int ALGORETRY_MAX = 255;
+ int algoRetry = ALGORETRY_INVALID;
+ int getAlgoRetry() {
+ if (algoRetry < ALGORETRY_MIN || algoRetry > ALGORETRY_MAX) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 4, 9, 0, 0, 0, 0};
+ sendHostRegRequest(HostRegRequests.HST_INV_ALG_PARM_1, false, msgBuffer);
+ }
+ return algoRetry;
+ }
+ boolean setAlgoRetry(int algoRetry) {
+ if (algoRetry < ALGORETRY_MIN || algoRetry > ALGORETRY_MAX)
+ algoRetry = mDefault.algoRetry;
+ if (this.algoRetry == algoRetry && sameCheck) return true;
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 4, 9, 0, 0, 0, 0};
+ msgBuffer[4] = (byte) algoRetry;
+ this.algoRetry = algoRetry;
+ return sendHostRegRequest(HostRegRequests.HST_INV_ALG_PARM_1, true, msgBuffer);
+ }
+
+ final int ALGOABFLIP_INVALID = -1; final int ALGOABFLIP_MIN = 0; final int ALGOABFLIP_MAX = 1;
+ int algoAbFlip = ALGOABFLIP_INVALID;
+ int getAlgoAbFlip() {
+ if (algoAbFlip < ALGOABFLIP_MIN || algoAbFlip > ALGOABFLIP_MAX) getHST_INV_ALG_PARM_2();
+ return algoAbFlip;
+ }
+ boolean setAlgoAbFlip(int algoAbFlip) {
+ return setAlgoAbFlip(algoAbFlip, algoRunTilZero);
+ }
+
+ final int ALGORUNTILZERO_INVALID = -1; final int ALGORUNTILZERO_MIN = 0; final int ALGORUNTILZERO_MAX = 1;
+ int algoRunTilZero = ALGORUNTILZERO_INVALID;
+ int getAlgoRunTilZero() {
+ if (algoRunTilZero < ALGORUNTILZERO_MIN || algoRunTilZero > ALGORUNTILZERO_MAX) getHST_INV_ALG_PARM_2();
+ return algoRunTilZero;
+ }
+ boolean setAlgoRunTilZero(int algoRunTilZero) {
+ return setAlgoAbFlip(algoAbFlip, algoRunTilZero);
+ }
+
+ private boolean getHST_INV_ALG_PARM_2() {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 5, 9, 0, 0, 0, 0};
+ return sendHostRegRequest(HostRegRequests.HST_INV_ALG_PARM_2, false, msgBuffer);
+ }
+ boolean setAlgoAbFlip(int algoAbFlip, int algoRunTilZero) {
+ if (algoAbFlip < ALGOABFLIP_MIN || algoAbFlip > ALGOABFLIP_MAX)
+ algoAbFlip = mDefault.algoAbFlip;
+ if (algoRunTilZero < ALGORUNTILZERO_MIN || algoRunTilZero > ALGORUNTILZERO_MAX)
+ algoRunTilZero = mDefault.algoRunTilZero;
+ if (true) appendToLog("this.algoAbFlip = " + this.algoAbFlip + ", algoAbFlip = " + algoAbFlip + ", this.algoRunTilZero = " + this.algoRunTilZero + ", algoRunTilZero = " + algoRunTilZero);
+ if (this.algoAbFlip == algoAbFlip && this.algoRunTilZero == algoRunTilZero && sameCheck) return true;
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 5, 9, 0, 0, 0, 0};
+ if (algoAbFlip != 0) {
+ msgBuffer[4] |= 0x01;
+ }
+ if (algoRunTilZero != 0) {
+ msgBuffer[4] |= 0x02;
+ }
+ this.algoAbFlip = algoAbFlip;
+ this.algoRunTilZero = algoRunTilZero;
+ return sendHostRegRequest(HostRegRequests.HST_INV_ALG_PARM_2, true, msgBuffer);
+ }
+ }
+ public class Rx000EngSetting {
+ int narrowRSSI = -1, wideRSSI = -1;
+ public int getwideRSSI() {
+ if (wideRSSI < 0) {
+ setPwrManagementMode(false);
+ rx000Setting.writeMAC(0x100, 0x05); //sub-command: 0x05, Arg0: reserved
+ rx000Setting.writeMAC(0x101, 3 + 0x20000); //Arg1: 15-0: number of RSSI sample
+ sendHostRegRequestHST_CMD(RfidReaderChipData.HostCommands.CMD_ENGTEST);
+ } else appendToLog("Hello123: wideRSSI = " + wideRSSI);
+ return wideRSSI;
+ }
+ int getnarrowRSSI() {
+ if (narrowRSSI < 0) {
+ setPwrManagementMode(false);
+ rx000Setting.writeMAC(0x100, 0x05); //sub-command: 0x05, Arg0: reserved
+ rx000Setting.writeMAC(0x101, 3 + 0x20000); //Arg1: 15-0: number of RSSI sample
+ sendHostRegRequestHST_CMD(RfidReaderChipData.HostCommands.CMD_ENGTEST);
+ } else appendToLog("Hello123: narrowRSSI = " + wideRSSI);
+ return wideRSSI;
+ }
+ public void resetRSSI() {
+ narrowRSSI = -1; wideRSSI = -1;
+ }
+ }
+ public class Rx000MbpSetting {
+ final int RXGAIN_INVALID = -1; final int RXGAIN_MIN = 0; final int RXGAIN_MAX = 0x1FF;
+ int rxGain = RXGAIN_INVALID;
+ public int getHighCompression() {
+ int iRetValue = -1;
+ if (rxGain < RXGAIN_MIN || rxGain > RXGAIN_MAX) {
+ setPwrManagementMode(false);
+ rx000Setting.setMBPAddress(0x450); appendToLog("70010004: getHighCompression");
+ sendHostRegRequestHST_CMD(RfidReaderChipData.HostCommands.CMD_MBPRDREG);
+ } else iRetValue = (rxGain >> 8);
+ return iRetValue;
+ }
+ public int getRflnaGain() {
+ int iRetValue = -1;
+ if (rxGain < RXGAIN_MIN || rxGain > RXGAIN_MAX) {
+ setPwrManagementMode(false);
+ rx000Setting.setMBPAddress(0x450); appendToLog("70010004: getRflnaGain");
+ sendHostRegRequestHST_CMD(RfidReaderChipData.HostCommands.CMD_MBPRDREG);
+ } else iRetValue = ((rxGain & 0xC0) >> 6);
+ return iRetValue;
+ }
+ public int getIflnaGain() {
+ int iRetValue = -1;
+ if (rxGain < RXGAIN_MIN || rxGain > RXGAIN_MAX) {
+ setPwrManagementMode(false);
+ rx000Setting.setMBPAddress(0x450); appendToLog("70010004: getIflnaGain");
+ sendHostRegRequestHST_CMD(RfidReaderChipData.HostCommands.CMD_MBPRDREG);
+ } else iRetValue = ((rxGain & 0x38) >> 3);
+ return iRetValue;
+ }
+ public int getAgcGain() {
+ int iRetValue = -1;
+ if (rxGain < RXGAIN_MIN || rxGain > RXGAIN_MAX) {
+ setPwrManagementMode(false);
+ rx000Setting.setMBPAddress(0x450); appendToLog("70010004: getAgcGain");
+ sendHostRegRequestHST_CMD(RfidReaderChipData.HostCommands.CMD_MBPRDREG);
+ } else iRetValue = (rxGain & 0x07);
+ return iRetValue;
+ }
+ public int getRxGain() {
+ int iRetValue = -1;
+ if (rxGain < RXGAIN_MIN || rxGain > RXGAIN_MAX) {
+ setPwrManagementMode(false);
+ rx000Setting.setMBPAddress(0x450);
+ sendHostRegRequestHST_CMD(RfidReaderChipData.HostCommands.CMD_MBPRDREG);
+ } else iRetValue = rxGain;
+ return iRetValue;
+ }
+ public boolean setRxGain(int highCompression, int rflnagain, int iflnagain, int agcgain) {
+ int rxGain_new = ((highCompression & 0x01) << 8) | ((rflnagain & 0x3) << 6) | ((iflnagain & 0x7) << 3) | (agcgain & 0x7);
+ return setRxGain(rxGain_new);
+ }
+ public boolean setRxGain(int rxGain_new) {
+ boolean bRetValue = true;
+ if ((rxGain_new != rxGain) || (sameCheck == false)) {
+ setPwrManagementMode(false);
+ bRetValue = rx000Setting.setMBPAddress(0x450);
+ if (bRetValue != false) bRetValue = rx000Setting.setMBPData(rxGain_new);
+ if (bRetValue != false) bRetValue = sendHostRegRequestHST_CMD(RfidReaderChipData.HostCommands.CMD_MBPWRREG);
+ if (bRetValue != false) rxGain = rxGain_new;
+ }
+ return bRetValue;
+ }
+ }
+ public class Rx000OemSetting {
+ final int COUNTRYCODE_INVALID = -1; final int COUNTRYCODE_MIN = 1; final int COUNTRYCODE_MAX = 9;
+ int countryCode = COUNTRYCODE_INVALID; // OemAddress = 0x02
+ public int getCountryCode() {
+ if (countryCode < COUNTRYCODE_MIN || countryCode > COUNTRYCODE_MAX) {
+ setPwrManagementMode(false);
+ rx000Setting.setOEMAddress(2);
+ sendHostRegRequestHST_CMD(RfidReaderChipData.HostCommands.CMD_RDOEM);
+ }
+ return countryCode;
+ }
+
+ final int SERIALCODE_INVALID = -1;
+ byte[] serialNumber = new byte[] { SERIALCODE_INVALID, 0, 0, 0, SERIALCODE_INVALID, 0, 0, 0, SERIALCODE_INVALID, 0, 0, 0, SERIALCODE_INVALID, 0, 0, 0 };
+ public String getSerialNumber() {
+ boolean invalid = false;
+ int length = serialNumber.length / 4;
+ if (serialNumber.length % 4 != 0) length++;
+ for (int i = 0; i < length; i++) {
+ if (serialNumber[4 * i] == SERIALCODE_INVALID) { // OemAddress = 0x04 - 7
+ invalid = true;
+ setPwrManagementMode(false);
+ rx000Setting.setOEMAddress(0x04 + i);
+ sendHostRegRequestHST_CMD(RfidReaderChipData.HostCommands.CMD_RDOEM);
+ }
+ }
+ if (invalid) return null;
+ appendToLog("retValue = " + byteArrayToString(serialNumber));
+ byte[] retValue = new byte[serialNumber.length];
+ for (int i = 0; i < retValue.length; i++) {
+ int j = (i/4)*4 + 3 - i%4;
+ if (j >= serialNumber.length) retValue[i] = serialNumber[i];
+ else retValue[i] = serialNumber[j];
+ if (retValue[i] == 0) retValue[i] = 0x30;
+ }
+ appendToLog("retValue = " + byteArrayToString(retValue) + ", String = " + new String(retValue));
+ return new String(retValue);
+ }
+
+ final int PRODUCT_SERIALCODE_INVALID = -1;
+ byte[] productserialNumber = new byte[] { SERIALCODE_INVALID, 0, 0, 0, SERIALCODE_INVALID, 0, 0, 0, SERIALCODE_INVALID, 0, 0, 0, SERIALCODE_INVALID, 0, 0, 0 };
+ public String getProductSerialNumber() {
+ boolean invalid = false;
+ int length = productserialNumber.length / 4;
+ if (productserialNumber.length % 4 != 0) length++;
+ for (int i = 0; i < length; i++) {
+ if (productserialNumber[4 * i] == PRODUCT_SERIALCODE_INVALID) { // OemAddress = 0x04 - 7
+ invalid = true;
+ setPwrManagementMode(false);
+ rx000Setting.setOEMAddress(0x08 + i);
+ sendHostRegRequestHST_CMD(RfidReaderChipData.HostCommands.CMD_RDOEM);
+ }
+ }
+ if (invalid) return null;
+ appendToLog("retValue = " + byteArrayToString(productserialNumber));
+ byte[] retValue = new byte[productserialNumber.length];
+ for (int i = 0; i < retValue.length; i++) {
+ int j = (i/4)*4 + 3 - i%4;
+ if (j >= productserialNumber.length) retValue[i] = productserialNumber[i];
+ else retValue[i] = productserialNumber[j];
+ if (retValue[i] == 0) retValue[i] = 0x30;
+ }
+ appendToLog("retValue = " + byteArrayToString(retValue) + ", String = " + new String(retValue));
+ return new String(retValue);
+ }
+
+ final int VERSIONCODE_INVALID = -1; final int VERSIONCODE_MIN = 1; final int VERSIONCODE_MAX = 9;
+ int versionCode = VERSIONCODE_INVALID; // OemAddress = 0x02
+ public int getVersionCode() {
+ if (versionCode < VERSIONCODE_MIN || versionCode > VERSIONCODE_MAX) {
+ setPwrManagementMode(false);
+ rx000Setting.setOEMAddress(0x0B);
+ sendHostRegRequestHST_CMD(RfidReaderChipData.HostCommands.CMD_RDOEM);
+ }
+ return versionCode;
+ }
+
+ String spcialCountryVersion = null;
+ public String getSpecialCountryVersion() {
+ if (spcialCountryVersion == null) {
+ setPwrManagementMode(false);
+ rx000Setting.setOEMAddress(0x8E);
+ sendHostRegRequestHST_CMD(RfidReaderChipData.HostCommands.CMD_RDOEM);
+ return "";
+ }
+ return spcialCountryVersion.replaceAll("[^A-Za-z0-9]", "");
+ }
+
+ final int FREQMODIFYCODE_INVALID = -1; final int FREQMODIFYCODE_MIN = 0; final int FREQMODIFYCODE_MAX = 0xAA;
+ int freqModifyCode = FREQMODIFYCODE_INVALID; // OemAddress = 0x8A
+ public int getFreqModifyCode() {
+ if (freqModifyCode < FREQMODIFYCODE_MIN || freqModifyCode > FREQMODIFYCODE_MAX) {
+ setPwrManagementMode(false);
+ rx000Setting.setOEMAddress(0x8F);
+ sendHostRegRequestHST_CMD(RfidReaderChipData.HostCommands.CMD_RDOEM);
+ }
+ return freqModifyCode;
+ }
+
+ void writeOEM(int address, int value) {
+ setPwrManagementMode(false);
+ rx000Setting.setOEMAddress(address);
+ rx000Setting.setOEMData(value);
+ sendHostRegRequestHST_CMD(RfidReaderChipData.HostCommands.CMD_WROEM);
+ }
+ }
+ //public boolean bFirmware_reset_before = false;
+ final int RFID_READING_BUFFERSIZE = 1024;
+ enum RfidDataReadTypes {
+ RFID_DATA_READ_SOFTRESET, RFID_DATA_READ_ABORT, RFID_DATA_READ_RESETTOBOOTLOADER,
+ RFID_DATA_READ_REGREAD,
+ RFID_DATA_READ_COMMAND_BEGIN, RFID_DATA_READ_COMMAND_END,
+ RFID_DATA_READ_COMMAND_INVENTORY, RFID_DATA_READ_COMMAND_COMPACT, RFID_DATA_READ_COMMAND_ACCESS,
+ RFID_DATA_READ_COMMAND_MBPREAD, RFID_DATA_READ_COMMAND_OEMREAD,
+ RFID_DATA_READ_COMMAND_RSSI, RFID_DATA_READ_COMMAND_ACTIVE
+ };
+ //class RfidReaderChip {
+ byte[] mRfidToReading = new byte[RFID_READING_BUFFERSIZE];
+ int mRfidToReadingOffset = 0;
+ ArrayList mRx000ToWrite = new ArrayList<>();
+
+ public Rx000Setting rx000Setting = new Rx000Setting(true);
+ public Rx000EngSetting rx000EngSetting = new Rx000EngSetting();
+ public Rx000MbpSetting rx000MbpSetting = new Rx000MbpSetting();
+ public Rx000OemSetting rx000OemSetting = new Rx000OemSetting();
+
+ public ArrayList mRx000ToRead = new ArrayList<>();
+ private boolean clearTempDataIn_request = false;
+ boolean commandOperating;
+
+ public double decodeNarrowBandRSSI(byte byteRSSI) {
+ byte mantissa = byteRSSI;
+ mantissa &= 0x07;
+ byte exponent = byteRSSI;
+ exponent >>= 3;
+ double dValue = 20 * log10(pow(2, exponent) * (1 + (mantissa / pow(2, 3))));
+ if (false)
+ appendToLog("byteRSSI = " + String.format("%X", byteRSSI) + ", mantissa = " + mantissa + ", exponent = " + exponent + "dValue = " + dValue);
+ return dValue;
+ }
+
+ public int encodeNarrowBandRSSI(double dRSSI) {
+ double dValue = dRSSI / 20;
+ dValue = pow(10, dValue);
+ int exponent = 0;
+ if (false) appendToLog("exponent = " + exponent + ", dValue = " + dValue);
+ while ((dValue + 0.062) >= 2) {
+ dValue /= 2;
+ exponent++;
+ if (false) appendToLog("exponent = " + exponent + ", dValue = " + dValue);
+ }
+ dValue--;
+ int mantissa = (int) ((dValue * 8) + 0.5);
+ while (mantissa >= 8) {
+ mantissa -= 8;
+ exponent++;
+ }
+ int iValue = ((exponent & 0x1F) << 3) | (mantissa & 0x7);
+ if (false)
+ appendToLog("dRssi = " + dRSSI + ", exponent = " + exponent + ", mantissa = " + mantissa + ", iValue = " + String.format("%X", iValue));
+ return iValue;
+ }
+
+ long firmware_ontime_ms = 0;
+ long date_time_ms = 0;
+ public boolean bRx000ToReading = false;
+
+ void uplinkHandler() {
+ boolean DEBUG = false;
+ if (bRx000ToReading) return;
+ bRx000ToReading = true;
+ int startIndex = 0;
+ int startIndexOld = 0;
+ int startIndexNew = 0;
+ boolean packageFound = false;
+ int packageType = 0;
+ long lTime = System.currentTimeMillis();
+ boolean bdebugging = false;
+ if (csReaderConnector.rfidConnector.mRfidToRead.size() != 0) {
+ bdebugging = true;
+ if (DEBUGTHREAD) appendToLog("mRx000UplinkHandler(): START");
+ } else if (DEBUGTHREAD) appendToLog("mRx000UplinkHandler(): START AAA");
+ boolean bFirst = true;
+ byte[] data1 = null;
+ RfidDataReadTypes rfidDataReadTypes = null;
+ boolean bLooping = false;
+ while (csReaderConnector.rfidConnector.mRfidToRead.size() != 0) {
+ if (utility.DEBUG_APDATA && bLooping == false) appendToLog("ApData: Entering loop with mRfidToRead.size as " + csReaderConnector.rfidConnector.mRfidToRead.size());
+ bLooping = true;
+
+ if (csReaderConnector.isConnected() == false) {
+ csReaderConnector.rfidConnector.mRfidToRead.clear();
+ } else if (System.currentTimeMillis() - lTime > (intervalRx000UplinkHandler / 2)) {
+ writeDebug2File("Up4 " + String.valueOf(intervalRx000UplinkHandler) + "ms Timeout");
+ if (utility.DEBUG_APDATA)
+ appendToLogView("ApData: TIMEOUT !!! mRfidToRead.size() = " + csReaderConnector.rfidConnector.mRfidToRead.size());
+ break;
+ } else {
+ if (bFirst) {
+ bFirst = false;
+ }
+ byte[] dataIn = csReaderConnector.rfidConnector.mRfidToRead.get(0).dataValues;
+ long tagMilliSeconds = csReaderConnector.rfidConnector.mRfidToRead.get(0).milliseconds;
+ boolean invalidSequence = csReaderConnector.rfidConnector.mRfidToRead.get(0).invalidSequence;
+ if (utility.DEBUG_APDATA)
+ appendToLog("ApData: mRfidToReadingOffset=" + mRfidToReadingOffset + ", mRfidToReading.length=" + mRfidToReading.length + ", dataIn.length=" + dataIn.length + ", dataIn=" + byteArrayToString(dataIn));
+ csReaderConnector.rfidConnector.mRfidToRead.remove(0);
+
+ if (dataIn.length >= mRfidToReading.length - mRfidToReadingOffset) {
+ byte[] unhandledBytes = new byte[mRfidToReadingOffset];
+ System.arraycopy(mRfidToReading, 0, unhandledBytes, 0, unhandledBytes.length);
+ if (utility.DEBUG_APDATA)
+ appendToLogView("ApData: ERROR insufficient buffer, mRfidToReadingOffset=" + mRfidToReadingOffset + ", dataIn.length=" + dataIn.length + ", clear mRfidToReading: " + byteArrayToString(unhandledBytes));
+ byte[] mRfidToReadingNew = new byte[RFID_READING_BUFFERSIZE];
+ mRfidToReading = mRfidToReadingNew;
+ mRfidToReadingOffset = 0;
+ invalidUpdata++;
+ writeDebug2File("Up4 insufficient buffer. missed " + byteArrayToString(unhandledBytes));
+ }
+ if (mRfidToReadingOffset != 0 && invalidSequence) {
+ byte[] unhandledBytes = new byte[mRfidToReadingOffset];
+ System.arraycopy(mRfidToReading, 0, unhandledBytes, 0, unhandledBytes.length);
+ if (utility.DEBUG_APDATA)
+ appendToLog("ApData: ERROR invalidSequence with nonzero mRfidToReadingOffset=" + mRfidToReadingOffset + ", throw invalid unused data=" + unhandledBytes.length + ", " + byteArrayToString(unhandledBytes));
+ mRfidToReadingOffset = 0;
+ startIndex = 0;
+ startIndexNew = 0;
+ writeDebug2File("Up4 Invalid sequence, " + byteArrayToString(unhandledBytes));
+ }
+ System.arraycopy(dataIn, 0, mRfidToReading, mRfidToReadingOffset, dataIn.length);
+ mRfidToReadingOffset += dataIn.length;
+ if (utility.DEBUG_APDATA) {
+ byte[] bufferData = new byte[mRfidToReadingOffset];
+ System.arraycopy(mRfidToReading, 0, bufferData, 0, bufferData.length);
+ appendToLog("ApData: new mRfidToReadingOffset=" + mRfidToReadingOffset + ", mRfidToReading=" + byteArrayToString(bufferData));
+ }
+
+ int iPayloadSizeMin = 8; boolean bLooping2 = false;
+ while (mRfidToReadingOffset - startIndex >= iPayloadSizeMin) {
+ if (utility.DEBUG_APDATA && bLooping2 == false) appendToLog("ApData: Entering second loop with mRfidToReadingOffset = " + mRfidToReadingOffset + ", startIndex = " + startIndex);
+ bLooping2 = true;
+
+ {
+ int packageLengthRead = (mRfidToReading[startIndex + 5] & 0xFF) * 256 + (mRfidToReading[startIndex + 4] & 0xFF);
+ int expectedLength = 8 + packageLengthRead * 4;
+ if (mRfidToReading[startIndex + 0] == 0x04)
+ expectedLength = 8 + packageLengthRead;
+ if (utility.DEBUG_APDATA)
+ appendToLog("ApData: loop: 1Byte=" + mRfidToReading[startIndex + 0] + ", mRfidToReadingOffset=" + mRfidToReadingOffset + ", expectedLength=" + expectedLength);
+ if (mRfidToReadingOffset - startIndex >= 8) {
+ if (mRfidToReading[startIndex + 0] == (byte) 0x40
+ && (mRfidToReading[startIndex + 1] == 2 || mRfidToReading[startIndex + 1] == 3 || mRfidToReading[startIndex + 1] == 7)) { //input as Control Command Response
+ dataIn = mRfidToReading;
+ if (DEBUG) appendToLog("decoding CONTROL data");
+ if (csReaderConnector.rfidConnector.mRfidToWrite.size() == 0) {
+ if (DEBUG)
+ appendToLog("Control Response is received with null mRfidToWrite");
+ } else if (csReaderConnector.rfidConnector.mRfidToWrite.get(0) == null) {
+ if (DEBUG)
+ appendToLog("Control Response is received with null mRfidToWrite.get(0)");
+ } else if (csReaderConnector.rfidConnector.mRfidToWrite.get(0).dataValues == null) {
+ csReaderConnector.rfidConnector.mRfidToWrite.remove(0);
+ if (DEBUG) appendToLog("mmRfidToWrite remove 5");
+ if (DEBUG)
+ appendToLog("Control Response is received with null mRfidToWrite.dataValues");
+ } else if (!(csReaderConnector.rfidConnector.mRfidToWrite.get(0).dataValues[0] == dataIn[startIndex + 0] && csReaderConnector.rfidConnector.mRfidToWrite.get(0).dataValues[1] == dataIn[startIndex + 1])) {
+ if (DEBUG)
+ appendToLog("Control Response is received with Mis-matched mRfidToWrite, " + startIndex + ", " + byteArrayToString(dataIn));
+ } else {
+ byte[] dataInCompare = null;
+ switch (csReaderConnector.rfidConnector.mRfidToWrite.get(0).dataValues[1]) {
+ case 2: //SOFTRESET
+ rfidDataReadTypes = RfidDataReadTypes.RFID_DATA_READ_SOFTRESET;
+ dataInCompare = new byte[]{0x40, 0x02, (byte) 0xbf, (byte) 0xfd, (byte) 0xbf, (byte) 0xfd, (byte) 0xbf, (byte) 0xfd};
+ break;
+ case 3: //ABORT
+ rfidDataReadTypes = RfidDataReadTypes.RFID_DATA_READ_ABORT;
+ dataInCompare = new byte[]{0x40, 0x03, (byte) 0xbf, (byte) 0xfc, (byte) 0xbf, (byte) 0xfc, (byte) 0xbf, (byte) 0xfc};
+ break;
+ case 7: //RESETTOBOOTLOADER
+ rfidDataReadTypes = RfidDataReadTypes.RFID_DATA_READ_RESETTOBOOTLOADER;
+ dataInCompare = new byte[]{0x40, 0x07, (byte) 0xbf, (byte) 0xf8, (byte) 0xbf, (byte) 0xf8, (byte) 0xbf, (byte) 0xf8};
+ break;
+ }
+ byte[] dataIn8 = new byte[8];
+ System.arraycopy(dataIn, startIndex, dataIn8, 0, dataIn8.length);
+ if (!(compareArray(dataInCompare, dataIn8, 8))) {
+ if (DEBUG)
+ appendToLog("Control response with invalid data: " + byteArrayToString(dataIn8));
+ } else {
+ csReaderConnector.rfidConnector.mRfidToWrite.remove(0);
+ csReaderConnector.rfidConnector.sendRfidToWriteSent = 0;
+ csReaderConnector.rfidConnector.mRfidToWriteRemoved = true;
+ if (DEBUG) appendToLog("mmRfidToWrite remove 6");
+ if (DEBUG)
+ appendToLog("matched control command with mRfidToWrite.size=" + csReaderConnector.rfidConnector.mRfidToWrite.size());
+ }
+ }
+ if (true) {
+ byte[] dataIn8 = new byte[8];
+ System.arraycopy(dataIn, startIndex, dataIn8, 0, dataIn8.length);
+ byte[] dataInCompare = new byte[]{0x40, 0x03, (byte) 0xbf, (byte) 0xfc, (byte) 0xbf, (byte) 0xfc, (byte) 0xbf, (byte) 0xfc};
+ if (compareArray(dataInCompare, dataIn8, 8)) {
+ RfidReaderChipData.Rx000pkgData dataA = new RfidReaderChipData.Rx000pkgData();
+ dataA.dataValues = dataIn8;
+ dataA.responseType = RfidReaderChipData.HostCmdResponseTypes.TYPE_COMMAND_ABORT_RETURN;
+ mRx000ToRead.add(dataA);
+ if (DEBUG)
+ appendToLog("Abort Return data is found wth type = " + dataA.responseType.toString());
+ setInventoring(false);
+ }
+ }
+ packageFound = true;
+ packageType = 1; //0x40
+ startIndexNew = startIndex + iPayloadSizeMin;
+ } else if ((mRfidToReading[startIndex + 0] == (byte) 0x00 || mRfidToReading[startIndex + 0] == (byte) 0x70)
+ && mRfidToReading[startIndex + 1] == 0
+ && csReaderConnector.rfidConnector.mRfidToWrite.size() != 0
+ && csReaderConnector.rfidConnector.mRfidToWrite.get(0).dataValues != null
+ && csReaderConnector.rfidConnector.mRfidToWrite.get(0).dataValues[0] == 0x70
+ && csReaderConnector.rfidConnector.mRfidToWrite.get(0).dataValues[1] == 0
+ ) { //if input as HOST_REG_RESP
+ if (DEBUG)
+ appendToLog("loop: decoding HOST_REG_RESP data with startIndex = " + startIndex + ", mRfidToReading=" + byteArrayToString(mRfidToReading));
+ dataIn = mRfidToReading;
+ byte[] dataInPayload = new byte[4];
+ System.arraycopy(dataIn, startIndex + 4, dataInPayload, 0, dataInPayload.length);
+ //if (mRfidDevice.mRfidToWrite.size() == 0) {
+ // if (true) appendToLog("mRx000UplinkHandler(): HOST_REG_RESP is received with null mRfidToWrite: " + byteArrayToString(dataInPayload));
+ //} else if (mRfidDevice.mRfidToWrite.get(0).dataValues == null) {
+ // if (true) appendToLog("mRx000UplinkHandler(): NULL mRfidToWrite.get(0).dataValues"); //.length = " + mRfidDevice.mRfidToWrite.get(0).dataValues.length);
+ //} else if (!(mRfidDevice.mRfidToWrite.get(0).dataValues[0] == 0x70 && mRfidDevice.mRfidToWrite.get(0).dataValues[1] == 0)) {
+ // if (true) appendToLog("mRx000UplinkHandler(): HOST_REG_RESP is received with invalid mRfidDevice.mRfidToWrite.get(0).dataValues=" + byteArrayToString(mRfidDevice.mRfidToWrite.get(0).dataValues));
+ //} else
+ {
+ int addressToWrite = csReaderConnector.rfidConnector.mRfidToWrite.get(0).dataValues[2] + csReaderConnector.rfidConnector.mRfidToWrite.get(0).dataValues[3] * 256;
+ int addressToRead = dataIn[startIndex + 2] + dataIn[startIndex + 3] * 256;
+ if (addressToRead != addressToWrite) {
+ if (DEBUG)
+ appendToLog("mRx000UplinkHandler(): HOST_REG_RESP is received with misMatch address: addressToRead=" + addressToRead + ", " + startIndex + ", " + byteArrayToString(dataInPayload) + ", addressToWrite=" + addressToWrite);
+ } else {
+ switch (addressToRead) {
+ case 0:
+ int patchVersion = dataIn[startIndex + 4] + (dataIn[startIndex + 5] & 0x0F) * 256;
+ int minorVersion = (dataIn[startIndex + 5] >> 4) + dataIn[startIndex + 6] * 256;
+ int majorVersion = dataIn[startIndex + 7];
+ rx000Setting.macVer = String.valueOf(majorVersion) + "." + String.valueOf(minorVersion) + "." + String.valueOf(patchVersion);
+ if (DEBUG)
+ appendToLog("found MacVer =" + rx000Setting.macVer);
+ break;
+ case 9:
+ rx000Setting.mac_last_command_duration = (dataIn[startIndex + 4] & 0xFF)
+ + (dataIn[startIndex + 5] & 0xFF) * 256
+ + (dataIn[startIndex + 6] & 0xFF) * 256 * 256
+ + (dataIn[startIndex + 7] & 0xFF) * 256 * 256 * 256;
+ if (DEBUG)
+ appendToLog("found mac_last_command_duration =" + rx000Setting.mac_last_command_duration);
+ break;
+ case 0x0201:
+ rx000Setting.diagnosticCfg = (dataIn[startIndex + 4] & 0x0FF) + ((dataIn[startIndex + 5] & 0x03) * 256);
+ if (DEBUG)
+ appendToLog("found diagnostic configuration: " + byteArrayToString(dataInPayload) + ", diagnosticCfg=" + rx000Setting.diagnosticCfg);
+ break;
+ case 0x0203:
+ rx000Setting.impinjExtensionValue = (dataIn[startIndex + 4] & 0x03F);
+ break;
+ case 0x204:
+ rx000Setting.pwrMgmtStatus = (dataIn[startIndex + 4] & 0x07);
+ if (DEBUG)
+ appendToLog("pwrMgmtStatus = " + rx000Setting.pwrMgmtStatus);
+ break;
+ case 0x0700:
+ rx000Setting.antennaCycle = (dataIn[startIndex + 4] & 0xFF) + (dataIn[startIndex + 5] & 0xFF) * 256;
+ rx000Setting.antennaFreqAgile = 0;
+ if ((dataIn[startIndex + 7] & 0x01) != 0)
+ rx000Setting.antennaFreqAgile = 1;
+ if (DEBUG)
+ appendToLog("found antenna cycle: " + byteArrayToString(dataInPayload) + ", cycle=" + rx000Setting.antennaCycle + ", frequencyAgile=" + rx000Setting.antennaFreqAgile);
+ break;
+ case 0x0701:
+ rx000Setting.antennaSelect = (dataIn[startIndex + 4] & 0xFF) + (dataIn[startIndex + 5] & 0xFF) * 256 + (dataIn[startIndex + 6] & 0xFF) * 256 * 256 + (dataIn[startIndex + 7] & 0xFF) * 256 * 256 * 256;
+ if (DEBUG)
+ appendToLog("found antenna select, select=" + rx000Setting.antennaSelect);
+ break;
+ case 0x0702:
+ rx000Setting.antennaSelectedData[rx000Setting.antennaSelect].antennaEnable = (dataIn[startIndex + 4] & 0x01);
+ rx000Setting.antennaSelectedData[rx000Setting.antennaSelect].antennaInventoryMode = (dataIn[startIndex + 4] & 0x02) >> 1;
+ rx000Setting.antennaSelectedData[rx000Setting.antennaSelect].antennaLocalAlgo = (dataIn[startIndex + 4] & 0x0C) >> 2;
+ rx000Setting.antennaSelectedData[rx000Setting.antennaSelect].antennaLocalStartQ = (dataIn[startIndex + 4] & 0xF0) >> 4;
+ rx000Setting.antennaSelectedData[rx000Setting.antennaSelect].antennaProfileMode = (dataIn[startIndex + 5] & 0x01);
+ rx000Setting.antennaSelectedData[rx000Setting.antennaSelect].antennaLocalProfile = ((dataIn[startIndex + 5] & 0x1E) >> 1);
+ rx000Setting.antennaSelectedData[rx000Setting.antennaSelect].antennaFrequencyMode = ((dataIn[startIndex + 5] & 0x20) >> 5);
+ rx000Setting.antennaSelectedData[rx000Setting.antennaSelect].antennaLocalFrequency = (dataIn[startIndex + 5] & 0x0F) * 4 + ((dataIn[startIndex + 5] & 0xC0) >> 6);
+ if (DEBUG)
+ appendToLog("found antenna selectEnable: " + byteArrayToString(dataInPayload)
+ + ", selectEnable=" + rx000Setting.antennaSelectedData[rx000Setting.antennaSelect].antennaEnable
+ + ", inventoryMode=" + rx000Setting.antennaSelectedData[rx000Setting.antennaSelect].antennaInventoryMode
+ + ", localAlgo=" + rx000Setting.antennaSelectedData[rx000Setting.antennaSelect].antennaLocalAlgo
+ + ", localStartQ=" + rx000Setting.antennaSelectedData[rx000Setting.antennaSelect].antennaLocalStartQ
+ + ", profileMode=" + rx000Setting.antennaSelectedData[rx000Setting.antennaSelect].antennaProfileMode
+ + ", localProfile=" + rx000Setting.antennaSelectedData[rx000Setting.antennaSelect].antennaLocalProfile
+ + ", frequencyMode=" + rx000Setting.antennaSelectedData[rx000Setting.antennaSelect].antennaFrequencyMode
+ + ", localFrequency=" + rx000Setting.antennaSelectedData[rx000Setting.antennaSelect].antennaLocalFrequency
+ );
+ break;
+ case 0x0703:
+ rx000Setting.antennaSelectedData[rx000Setting.antennaSelect].antennaStatus = (dataIn[startIndex + 4] & 0xFF) + (dataIn[startIndex + 5] & 0xFF) * 256 + (dataIn[startIndex + 6] & 0x0F) * 256 * 256;
+ if (DEBUG)
+ appendToLog("found antenna status: " + byteArrayToString(dataInPayload) + ", status=" + rx000Setting.antennaSelectedData[rx000Setting.antennaSelect].antennaStatus);
+ break;
+ case 0x0704:
+ rx000Setting.antennaSelectedData[rx000Setting.antennaSelect].antennaDefine = (dataIn[startIndex + 4] & 0x3);
+ // mRx000Setting.antennaSelectedData[mRx000Setting.antennaSelect].antennaRxDefine = (dataIn[startIndex + 6] & 0x3);
+ if (DEBUG)
+ appendToLog("found antenna define: " + byteArrayToString(dataInPayload)
+ + ", define=" + rx000Setting.antennaSelectedData[rx000Setting.antennaSelect].antennaDefine
+ // + ", RxDefine=" + mRx000Setting.antennaSelectedData[mRx000Setting.antennaSelect].antennaRxDefine
+ );
+ break;
+ case 0x0705:
+ rx000Setting.antennaSelectedData[rx000Setting.antennaSelect].antennaDwell = (dataIn[startIndex + 4] & 0xFF) + (dataIn[startIndex + 5] & 0xFF) * 256 + (dataIn[startIndex + 6] & 0xFF) * 256 * 256 + (dataIn[startIndex + 7] & 0xFF) * 256 * 256 * 256;
+ if (DEBUG)
+ appendToLog("found antenna dwell=" + rx000Setting.antennaSelectedData[rx000Setting.antennaSelect].antennaDwell);
+ break;
+ case 0x0706:
+ if (rx000Setting.antennaSelectedData[rx000Setting.antennaSelect].antennaPowerSet == false)
+ rx000Setting.antennaSelectedData[rx000Setting.antennaSelect].antennaPower = (dataIn[startIndex + 4] & 0xFF) + (dataIn[startIndex + 5] & 0xFF) * 256 + (dataIn[startIndex + 6] & 0xFF) * 256 * 256 + (dataIn[startIndex + 7] & 0xFF) * 256 * 256 * 256;
+ break;
+ case 0x0707:
+ rx000Setting.antennaSelectedData[rx000Setting.antennaSelect].antennaInvCount = (dataIn[startIndex + 4] & 0xFF) + (dataIn[startIndex + 5] & 0xFF) * 256 + (dataIn[startIndex + 6] & 0xFF) * 256 * 256 + (dataIn[startIndex + 7] & 0xFF) * 256 * 256 * 256;
+ if (DEBUG)
+ appendToLog("found antenna InvCount=" + rx000Setting.antennaSelectedData[rx000Setting.antennaSelect].antennaInvCount);
+ break;
+ case 0x0800:
+ rx000Setting.invSelectIndex = (dataIn[startIndex + 4] & 0xFF) + (dataIn[startIndex + 5] & 0xFF) * 256 + (dataIn[startIndex + 6] & 0xFF) * 256 * 256 + (dataIn[startIndex + 7] & 0xFF) * 256 * 256 * 256;
+ if (DEBUG)
+ appendToLog("found inventory select: " + byteArrayToString(dataInPayload) + ", select=" + rx000Setting.invSelectIndex);
+ break;
+ case 0x0801: {
+ int dataIndex = rx000Setting.invSelectIndex;
+ if (dataIndex < rx000Setting.INVSELECT_MIN || dataIndex > rx000Setting.INVSELECT_MAX) {
+ if (DEBUG)
+ appendToLog("found inventory select configuration: " + byteArrayToString(dataInPayload) + ", but invalid index=" + dataIndex);
+ } else {
+ appendToLog("BtDataOut 123A");
+ rx000Setting.invSelectData[dataIndex].selectEnable = (dataIn[startIndex + 4] & 0x01);
+ rx000Setting.invSelectData[dataIndex].selectTarget = ((dataIn[startIndex + 4] & 0x0E) >> 1);
+ rx000Setting.invSelectData[dataIndex].selectAction = ((dataIn[startIndex + 4] & 0x70) >> 4);
+ rx000Setting.invSelectData[dataIndex].selectDelay = dataIn[startIndex + 5];
+ if (DEBUG)
+ appendToLog("found inventory select configuration: " + byteArrayToString(dataInPayload)
+ + ", selectEnable=" + rx000Setting.invSelectData[dataIndex].selectEnable
+ + ", selectTarget=" + rx000Setting.invSelectData[dataIndex].selectTarget
+ + ", selectAction=" + rx000Setting.invSelectData[dataIndex].selectAction
+ + ", selectDelay=" + rx000Setting.invSelectData[dataIndex].selectDelay
+ );
+ }
+ break;
+ }
+ case 0x0802: {
+ int dataIndex = rx000Setting.invSelectIndex;
+ if (dataIndex < rx000Setting.INVSELECT_MIN || dataIndex > rx000Setting.INVSELECT_MAX) {
+ if (DEBUG)
+ appendToLog("found inventory select mask bank: " + byteArrayToString(dataInPayload) + ", but invalid index=" + dataIndex);
+ } else {
+ rx000Setting.invSelectData[dataIndex].selectMaskBank = (dataIn[startIndex + 4] & 0x03);
+ if (DEBUG)
+ appendToLog("found inventory select mask bank: " + byteArrayToString(dataInPayload)
+ + ", selectMaskBank=" + rx000Setting.invSelectData[dataIndex].selectMaskBank
+ );
+ }
+ break;
+ }
+ case 0x0803: {
+ int dataIndex = rx000Setting.invSelectIndex;
+ if (dataIndex < rx000Setting.INVSELECT_MIN || dataIndex > rx000Setting.INVSELECT_MAX) {
+ if (DEBUG)
+ appendToLog("found inventory select mask offset: " + byteArrayToString(dataInPayload) + ", but invalid index=" + dataIndex);
+ } else {
+ rx000Setting.invSelectData[dataIndex].selectMaskOffset = (dataIn[startIndex + 4] & 0x0FF) + (dataIn[startIndex + 5] & 0x0FF) * 256 + (dataIn[startIndex + 6] & 0x0FF) * 256 * 256 + (dataIn[startIndex + 7] & 0x0FF) * 256 * 256 * 256;
+ if (DEBUG)
+ appendToLog("found inventory select mask offset: " + byteArrayToString(dataInPayload)
+ + ", selectMaskOffset=" + rx000Setting.invSelectData[dataIndex].selectMaskOffset
+ );
+ }
+ break;
+ }
+ case 0x0804: {
+ int dataIndex = rx000Setting.invSelectIndex;
+ if (dataIndex < rx000Setting.INVSELECT_MIN || dataIndex > rx000Setting.INVSELECT_MAX) {
+ if (DEBUG)
+ appendToLog("found inventory select mask length: " + byteArrayToString(dataInPayload) + ", but invalid index=" + dataIndex);
+ } else {
+ rx000Setting.invSelectData[dataIndex].selectMaskLength = (dataIn[startIndex + 4] & 0x0FF);
+ if (DEBUG)
+ appendToLog("getSelectMaskData with read selectMaskLength = " + rx000Setting.invSelectData[dataIndex].selectMaskLength);
+ if (DEBUG)
+ appendToLog("found inventory select mask length: " + byteArrayToString(dataInPayload)
+ + ", selectMaskLength=" + rx000Setting.invSelectData[dataIndex].selectMaskLength
+ );
+ }
+ break;
+ }
+ case 0x0805:
+ case 0x0806:
+ case 0x0807:
+ case 0x0808:
+ case 0x0809:
+ case 0x080A:
+ case 0x080B:
+ case 0x080C: {
+ int dataIndex = rx000Setting.invSelectIndex;
+ if (dataIndex < rx000Setting.INVSELECT_MIN || dataIndex > rx000Setting.INVSELECT_MAX) {
+ if (DEBUG)
+ appendToLog("found inventory select mask 0-3: " + byteArrayToString(dataInPayload) + ", but invalid index=" + dataIndex);
+ } else {
+ int maskDataIndex = addressToRead - 0x0805;
+ if (DEBUG)
+ appendToLog("Old selectMaskData0_31 = " + byteArrayToString(rx000Setting.invSelectData[dataIndex].selectMaskData0_31));
+ System.arraycopy(dataIn, startIndex + 4, rx000Setting.invSelectData[dataIndex].selectMaskData0_31, maskDataIndex * 4, 4);
+ if (DEBUG)
+ appendToLog("Old selectMaskData0_31 = " + byteArrayToString(rx000Setting.invSelectData[dataIndex].selectMaskData0_31));
+ rx000Setting.invSelectData[dataIndex].selectMaskDataReady |= (0x01 << maskDataIndex);
+ if (DEBUG)
+ appendToLog("found inventory select mask 0-3: " + byteArrayToString(dataInPayload));
+ }
+ break;
+ }
+ case 0x0900:
+ if (rx000Setting.queryTarget != 2)
+ rx000Setting.queryTarget = (dataIn[startIndex + 4] >> 4) & 0x01;
+ rx000Setting.querySession = (dataIn[startIndex + 4] >> 5) & 0x03;
+ rx000Setting.querySelect = (dataIn[startIndex + 4] >> 7) & 0x01 + ((dataIn[startIndex + 5] & 0x01) * 2);
+ //appendToLog("BtDataOut: found query configuration: " + byteArrayToString(dataInPayload) + ", target=" + rx000Setting.queryTarget + ", session=" + rx000Setting.querySession + ", select=" + rx000Setting.querySelect);
+ break;
+ case 0x0901:
+ rx000Setting.invAlgo = dataIn[startIndex + 4] & 0x3F;
+ rx000Setting.matchRep = ((dataIn[startIndex + 4] & 0xC0) >> 6) + (dataIn[startIndex + 5] & 0x3F) * 4;
+ rx000Setting.tagSelect = ((dataIn[startIndex + 5] & 0x40) >> 6);
+ rx000Setting.noInventory = ((dataIn[startIndex + 5] & 0x80) >> 7);
+ rx000Setting.tagRead = dataIn[startIndex + 6] & 0x03;
+ rx000Setting.tagDelay = ((dataIn[startIndex + 7] & 0x03) * 16 + ((dataIn[startIndex + 6] & 0xF0) >> 4));
+ rx000Setting.invModeCompact = ((dataIn[startIndex + 7] & 0x04) >> 2);
+ appendToLog("BtDataOut: invAuthenticate = " + rx000Setting.invAuthenticate);
+ rx000Setting.invAuthenticate = ((dataIn[startIndex + 7] & 0x10) >> 4);
+ appendToLog("BtDataOut: invAuthenticate = " + rx000Setting.invAuthenticate);
+ if (DEBUG)
+ appendToLog("found inventory configuration: " + byteArrayToString(dataInPayload) + ", algorithm=" + rx000Setting.invAlgo + ", matchRep=" + rx000Setting.matchRep + ", tagSelect=" + rx000Setting.tagSelect + ", noInventory=" + rx000Setting.noInventory + ", tagRead=" + rx000Setting.tagRead + ", tagDelay=" + rx000Setting.tagDelay);
+ break;
+ case 0x0902:
+ if (dataIn[startIndex + 6] != 0 || dataIn[startIndex + 7] != 0) {
+ if (DEBUG)
+ appendToLog("found inventory select, but too big: " + byteArrayToString(dataInPayload));
+ } else {
+ rx000Setting.algoSelect = (dataIn[startIndex + 4] & 0xFF) + (dataIn[startIndex + 5] & 0xFF) * 256;
+ if (DEBUG)
+ appendToLog("found inventory algorithm select=" + rx000Setting.algoSelect);
+ }
+ break;
+ case 0x0903: {
+ int dataIndex = rx000Setting.algoSelect;
+ if (dataIndex < rx000Setting.ALGOSELECT_MIN || dataIndex > rx000Setting.ALGOSELECT_MAX) {
+ if (DEBUG)
+ appendToLog("found inventory algo parameter 0: " + byteArrayToString(dataInPayload) + ", but invalid index=" + dataIndex);
+ } else {
+ rx000Setting.algoSelectedData[dataIndex].algoStartQ = (dataIn[startIndex + 4] & 0x0F);
+ rx000Setting.algoSelectedData[dataIndex].algoMaxQ = ((dataIn[startIndex + 4] & 0xF0) >> 4);
+ rx000Setting.algoSelectedData[dataIndex].algoMinQ = (dataIn[startIndex + 5] & 0x0F);
+ rx000Setting.algoSelectedData[dataIndex].algoMaxRep = ((dataIn[startIndex + 5] & 0xF0) >> 4) + ((dataIn[startIndex + 6] & 0x0F) << 4);
+ rx000Setting.algoSelectedData[dataIndex].algoHighThres = ((dataIn[startIndex + 6] & 0xF0) >> 4);
+ rx000Setting.algoSelectedData[dataIndex].algoLowThres = (dataIn[startIndex + 7] & 0x0F);
+ if (DEBUG || true)
+ appendToLog("BtDataOut: found inventory algo parameter 0: " + byteArrayToString(dataInPayload)
+ + ", algoStartQ=" + rx000Setting.algoSelectedData[dataIndex].algoStartQ
+ + ", algoMaxQ=" + rx000Setting.algoSelectedData[dataIndex].algoMaxQ
+ + ", algoMinQ=" + rx000Setting.algoSelectedData[dataIndex].algoMinQ
+ + ", algoMaxRep=" + rx000Setting.algoSelectedData[dataIndex].algoMaxRep
+ + ", algoHighThres=" + rx000Setting.algoSelectedData[dataIndex].algoHighThres
+ + ", algoLowThres=" + rx000Setting.algoSelectedData[dataIndex].algoLowThres
+ );
+ }
+ break;
+ }
+ case 0x0904: {
+ int dataIndex = rx000Setting.algoSelect;
+ if (dataIndex < rx000Setting.ALGOSELECT_MIN || dataIndex > rx000Setting.ALGOSELECT_MAX) {
+ if (DEBUG)
+ appendToLog("found inventory algo parameter 1: " + byteArrayToString(dataInPayload) + ", but invalid index=" + dataIndex);
+ } else {
+ rx000Setting.algoSelectedData[dataIndex].algoRetry = dataIn[startIndex + 4] & 0x0FF;
+ if (DEBUG)
+ appendToLog("found inventory algo parameter 1: " + byteArrayToString(dataInPayload) + ", algoRetry=" + rx000Setting.algoSelectedData[dataIndex].algoRetry);
+ }
+ break;
+ }
+ case 0x0905: {
+ int dataIndex = rx000Setting.algoSelect;
+ if (dataIndex < rx000Setting.ALGOSELECT_MIN || dataIndex > rx000Setting.ALGOSELECT_MAX) {
+ if (DEBUG)
+ appendToLog("found inventory algo parameter 2: " + byteArrayToString(dataInPayload) + ", but invalid index=" + dataIndex);
+ } else {
+ if (DEBUG)
+ appendToLog("found inventory algo parameter 2: " + byteArrayToString(dataInPayload) + ", dataIndex=" + dataIndex + ", algoAbFlip=" + rx000Setting.algoSelectedData[dataIndex].algoAbFlip + ", algoRunTilZero=" + rx000Setting.algoSelectedData[dataIndex].algoRunTilZero);
+ rx000Setting.algoSelectedData[dataIndex].algoAbFlip = dataIn[startIndex + 4] & 0x01;
+ rx000Setting.algoSelectedData[dataIndex].algoRunTilZero = (dataIn[startIndex + 4] & 0x02) >> 1;
+ if (DEBUG)
+ appendToLog("found inventory algo parameter 2: " + byteArrayToString(dataInPayload) + ", algoAbFlip=" + rx000Setting.algoSelectedData[dataIndex].algoAbFlip + ", algoRunTilZero=" + rx000Setting.algoSelectedData[dataIndex].algoRunTilZero);
+ }
+ break;
+ }
+ case 0x0907:
+ rx000Setting.rssiFilterType = dataIn[startIndex + 4] & 0xF;
+ rx000Setting.rssiFilterOption = (dataIn[startIndex + 4] >> 4) & 0xF;
+ break;
+ case 0x0908:
+ rx000Setting.rssiFilterThreshold1 = dataIn[startIndex + 4];
+ rx000Setting.rssiFilterThreshold1 += (dataIn[startIndex + 5] << 8);
+ rx000Setting.rssiFilterThreshold2 = dataIn[startIndex + 6];
+ rx000Setting.rssiFilterThreshold2 += (dataIn[startIndex + 7] << 8);
+ break;
+ case 0x0909:
+ rx000Setting.rssiFilterCount = dataIn[startIndex + 4];
+ rx000Setting.rssiFilterCount += (dataIn[startIndex + 5] << 8);
+ rx000Setting.rssiFilterCount += (dataIn[startIndex + 6] << 16);
+ rx000Setting.rssiFilterCount += (dataIn[startIndex + 7] << 24);
+ break;
+ case 0x0911:
+ rx000Setting.matchEnable = dataIn[startIndex + 4] & 0x01;
+ rx000Setting.matchType = ((dataIn[startIndex + 4] & 0x02) >> 1);
+ rx000Setting.matchLength = ((dataIn[startIndex + 4] & 0x0FF) >> 2) + (dataIn[startIndex + 5] & 0x07) * 64;
+ rx000Setting.matchOffset = ((dataIn[startIndex + 5] & 0x0FF) >> 3) + (dataIn[startIndex + 6] & 0x1F) * 32;
+ if (DEBUG)
+ appendToLog("found inventory match configuration: " + byteArrayToString(dataInPayload) + ", selectEnable=" + rx000Setting.matchEnable + ", matchType=" + rx000Setting.matchType + ", matchLength=" + rx000Setting.matchLength + ", matchOffset=" + rx000Setting.matchOffset);
+ break;
+ case 0x0912:
+ case 0x0913:
+ case 0x0914:
+ case 0x0915:
+ case 0x0916:
+ case 0x0917:
+ case 0x0918:
+ case 0x0919:
+ case 0x091A:
+ case 0x091B:
+ case 0x091C:
+ case 0x091D:
+ case 0x091E:
+ case 0x091F:
+ case 0x0920:
+ case 0x0921: {
+ int maskDataIndex = addressToRead - 0x0912;
+ System.arraycopy(dataIn, startIndex + 4, rx000Setting.invMatchData0_63, maskDataIndex * 4, 4);
+ rx000Setting.invMatchDataReady |= (0x01 << maskDataIndex);
+ if (DEBUG)
+ appendToLog("found inventory match Data 0-3: " + byteArrayToString(dataInPayload));
+ break;
+ }
+ case 0x0A01:
+ rx000Setting.accessRetry = (dataIn[startIndex + 4] & 0x0E) >> 1;
+ if (DEBUG)
+ appendToLog("found access algoRetry: " + byteArrayToString(dataInPayload) + ", accessRetry=" + rx000Setting.accessRetry);
+ break;
+ case 0x0A02:
+ rx000Setting.accessBank = (dataIn[startIndex + 4] & 0x03);
+ rx000Setting.accessBank2 = ((dataIn[startIndex + 4] >> 2) & 0x03);
+ if (DEBUG)
+ appendToLog("found access bank: " + byteArrayToString(dataInPayload) + ", accessBank=" + rx000Setting.accessBank + ", accessBank2=" + rx000Setting.accessBank2);
+ break;
+ case 0x0A03:
+ if (rx000Setting.tagRead != 0) {
+ rx000Setting.accessOffset = (dataIn[startIndex + 4] & 0x0FF) + (dataIn[startIndex + 5] & 0x0FF) * 256; // + (dataIn[startIndex + 6] & 0x0FF) * 256 * 256 + (dataIn[startIndex + 7] & 0x0FF) * 256 * 256 * 256;
+ rx000Setting.accessOffset2 = (dataIn[startIndex + 6] & 0x0FF) + (dataIn[startIndex + 7] & 0x0FF) * 256; // + (dataIn[startIndex + 6] & 0x0FF) * 256 * 256 + (dataIn[startIndex + 7] & 0x0FF) * 256 * 256 * 256;
+ } else {
+ rx000Setting.accessOffset = (dataIn[startIndex + 4] & 0x0FF) + (dataIn[startIndex + 5] & 0x0FF) * 256 + (dataIn[startIndex + 6] & 0x0FF) * 256 * 256 + (dataIn[startIndex + 7] & 0x0FF) * 256 * 256 * 256;
+ }
+ if (DEBUG)
+ appendToLog("found access offset: " + byteArrayToString(dataInPayload) + ", accessOffset=" + rx000Setting.accessOffset + ", accessOffset2=" + rx000Setting.accessOffset2);
+ break;
+ case 0x0A04:
+ rx000Setting.accessCount = (dataIn[startIndex + 4] & 0x0FF);
+ rx000Setting.accessCount2 = (dataIn[startIndex + 5] & 0x0FF);
+ if (DEBUG)
+ appendToLog("found access count: " + byteArrayToString(dataInPayload) + ", accessCount=" + rx000Setting.accessCount + ", accessCount2=" + rx000Setting.accessCount2);
+ break;
+ case 0x0A05:
+ rx000Setting.accessLockAction = (dataIn[startIndex + 4] & 0x0FF) + ((dataIn[startIndex + 5] & 0x03) * 256);
+ rx000Setting.accessLockMask = ((dataIn[startIndex + 5] & 0x0FF) >> 2) + ((dataIn[startIndex + 6] & 0x0F) * 64);
+ if (DEBUG)
+ appendToLog("found access lock configuration: " + byteArrayToString(dataInPayload) + ", accessLockAction=" + rx000Setting.accessLockAction + ", accessLockMask=" + rx000Setting.accessLockMask);
+ break;
+ case 0x0A08:
+ rx000Setting.accessWriteDataSelect = (dataIn[startIndex + 4] & 0x07);
+ if (DEBUG)
+ appendToLog("found write data select: " + byteArrayToString(dataInPayload) + ", accessWriteDataSelect=" + rx000Setting.accessWriteDataSelect);
+ break;
+ case 0x0A09:
+ case 0x0A0A:
+ case 0x0A0B:
+ case 0x0A0C:
+ case 0x0A0D:
+ case 0x0A0E:
+ case 0x0A0F:
+ case 0x0A10:
+ case 0x0A11:
+ case 0x0A12:
+ case 0x0A13:
+ case 0x0A14:
+ case 0x0A15:
+ case 0x0A16:
+ case 0x0A17:
+ case 0x0A18: {
+ int maskDataIndex = addressToRead - 0x0A09;
+ int maskDataIndexH = 0;
+ if (rx000Setting.accessWriteDataSelect != 0)
+ maskDataIndexH = 16;
+ for (int k = 0; k < 4; k++) {
+ rx000Setting.accWriteData0_63[(maskDataIndexH + maskDataIndex) * 4 + k] = dataIn[startIndex + 7 - k];
+ }
+ rx000Setting.accWriteDataReady |= (0x01 << (maskDataIndexH + maskDataIndex));
+ if (DEBUG)
+ appendToLog("accessWriteData=" + rx000Setting.accWriteData0_63);
+ if (DEBUG)
+ appendToLog("found access write data 0-3: " + byteArrayToString(dataInPayload));
+ break;
+ }
+ case 0x0b60:
+ rx000Setting.currentProfile = dataIn[startIndex + 4];
+ if (DEBUG)
+ appendToLog("found current profile: " + byteArrayToString(dataInPayload) + ", profile=" + rx000Setting.currentProfile);
+ break;
+ case 0x0c01:
+ rx000Setting.freqChannelSelect = dataIn[startIndex + 4];
+ if (DEBUG)
+ appendToLog("setFreqChannelSelect: found frequency channel select: " + byteArrayToString(dataInPayload) + ", freqChannelSelect=" + rx000Setting.freqChannelSelect);
+ break;
+ case 0x0c02:
+ rx000Setting.freqChannelConfig = dataIn[startIndex + 4] & 0x01;
+ if (DEBUG)
+ appendToLog("found frequency channel configuration: " + byteArrayToString(dataInPayload) + ", channelConfig=" + rx000Setting.freqChannelConfig);
+ break;
+ case 0x0f00:
+ rx000Setting.authenticateSendReply = ((dataIn[startIndex + 4] & 1) != 0) ? true : false;
+ rx000Setting.authenticateIncReplyLength = ((dataIn[startIndex + 4] & 2) != 0) ? true : false;
+ rx000Setting.authenticateLength = ((dataIn[startIndex + 5] & 0xFC) >> 3) + (dataIn[startIndex + 6] & 0x3F);
+ if (DEBUG)
+ appendToLog("found authenticate configuration: " + byteArrayToString(dataInPayload));
+ break;
+ case 0x0f01:
+ case 0x0f02:
+ case 0x0f03:
+ case 0x0f04: {
+ int maskDataIndex = addressToRead - 0x0f01;
+ System.arraycopy(dataIn, startIndex + 4, rx000Setting.authMatchData0_63, maskDataIndex * 4, 4);
+ //mRx000Setting.authMatchDataReady |= (0x01 << maskDataIndex);
+ if (DEBUG)
+ appendToLog("found authenticate match Data 0-3: " + byteArrayToString(dataInPayload));
+ break;
+ }
+ case 0x0f05:
+ rx000Setting.untraceableRange = dataIn[startIndex + 4] & 0x03;
+ rx000Setting.untraceableUser = ((dataIn[startIndex + 4] & 0x04) != 0) ? true : false;
+ rx000Setting.untraceableTid = ((dataIn[startIndex + 4] & 0x18) >> 3);
+ rx000Setting.untraceableEpcLength = ((dataIn[startIndex + 4] & 0xE0) >> 5) + ((dataIn[startIndex + 5] & 0x3) << 3);
+ rx000Setting.untraceableEpc = ((dataIn[startIndex + 5] & 4) != 0) ? true : false;
+ rx000Setting.untraceableUXpc = ((dataIn[startIndex + 5] & 8) != 0) ? true : false;
+ if (DEBUG)
+ appendToLog("found untraceable configuration: " + byteArrayToString(dataInPayload));
+ break;
+ default:
+ if (DEBUG)
+ appendToLog("found OTHERS with addressToWrite=" + addressToWrite + ", addressToRead=" + addressToRead + ", " + byteArrayToString(dataInPayload));
+ break;
+ }
+ rfidDataReadTypes = RfidDataReadTypes.RFID_DATA_READ_REGREAD;
+ csReaderConnector.rfidConnector.mRfidToWrite.remove(0);
+ csReaderConnector.rfidConnector.sendRfidToWriteSent = 0;
+ csReaderConnector.rfidConnector.mRfidToWriteRemoved = true;
+ if (DEBUG) appendToLog("mmRfidToWrite remove 7");
+ }
+ }
+ packageFound = true;
+ packageType = 2; //0x00, 0x70
+ startIndexNew = startIndex + 8;
+ } else if ((mRfidToReading[startIndex + 0] >= 1 && mRfidToReading[startIndex + 0] <= 4) //02 for begin and end, 03 for inventory, 01 for access
+ && (expectedLength >= 0 && expectedLength < mRfidToReading.length)
+ && (mRfidToReading[startIndex + 2] == 0 || mRfidToReading[startIndex + 2] == 1 || (mRfidToReading[startIndex + 2] >= 5 && mRfidToReading[startIndex + 2] <= 14))
+ && (mRfidToReading[startIndex + 3] == 0 || mRfidToReading[startIndex + 3] == 0x30 || mRfidToReading[startIndex + 3] == (byte) 0x80)
+// && mRfidToReading[startIndex + 6] == 0 //for packageTypeRead = 0x3007, this byte is 0x20. Others are 0
+ && mRfidToReading[startIndex + 7] == 0) { //if input as command response
+ {
+ if (DEBUG) appendToLog("loop: decoding 1_4 data");
+ if (mRfidToReadingOffset - startIndex < expectedLength)
+ break;
+ dataIn = mRfidToReading;
+ byte[] dataInPayload = new byte[expectedLength - 4];
+ System.arraycopy(dataIn, startIndex + 4, dataInPayload, 0, dataInPayload.length);
+ //if ((dataIn[startIndex + 3] == (byte) 0x80 && dataIn[startIndex + 6] == 0 && dataIn[startIndex + 7] == 0) == false) {
+ // appendToLog("mRx000UplinkHandler(): invalid command response is received with incorrect byte3= " + dataIn[startIndex + 3] + ", byte6=" + dataIn[startIndex + 6] + ", byte7=" + dataIn[startIndex + 7]);
+ //}
+
+ int packageTypeRead = dataIn[startIndex + 2] + (dataIn[startIndex + 3] & 0xFF) * 256;
+ RfidReaderChipData.Rx000pkgData dataA = new RfidReaderChipData.Rx000pkgData();
+ if (packageTypeRead == 6 && (dataIn[startIndex + 1] & 0x02) != 0 && dataIn[startIndex + 13] == 0) {
+ dataIn[startIndex + 13] = (byte) 0xFF;
+ }
+ int padCount = ((dataIn[startIndex + 1] & 0x0FF) >> 6);
+ if (packageTypeRead == 6) {
+ dataA.dataValues = new byte[8 + packageLengthRead * 4 - padCount];
+ System.arraycopy(dataIn, startIndex, dataA.dataValues, 0, dataA.dataValues.length);
+ } else if (packageTypeRead == 0x8005 || packageTypeRead == 5) {
+ if (dataIn[startIndex + 0] == 0x04) {
+ dataA.dataValues = new byte[packageLengthRead];
+ dataA.decodedPort = dataIn[startIndex + 6];
+ } else
+ dataA.dataValues = new byte[packageLengthRead * 4 - padCount];
+ System.arraycopy(dataIn, startIndex + 8, dataA.dataValues, 0, dataA.dataValues.length);
+ } else {
+ dataA.dataValues = new byte[packageLengthRead * 4];
+ System.arraycopy(dataIn, startIndex + 8, dataA.dataValues, 0, dataA.dataValues.length);
+ }
+ dataA.flags = (dataIn[startIndex + 1] & 0xFF);
+ switch (packageTypeRead) {
+ case 0x0000:
+ case 0x8000: //RFID_PACKET_TYPE_COMMAND_BEGIN //original 0
+ if (dataIn[startIndex + 0] != 1 && dataIn[startIndex + 0] != 2) {
+ if (DEBUG)
+ appendToLog("command COMMAND_BEGIN is found without first byte as 0x01 or 0x02, " + byteArrayToString(dataInPayload));
+ } else if (csReaderConnector.rfidConnector.mRfidToWrite.size() == 0) {
+ if (DEBUG)
+ appendToLog("command COMMAND_BEGIN is found without mRfidToWrite");
+ } else {
+ byte[] dataWritten = csReaderConnector.rfidConnector.mRfidToWrite.get(0).dataValues;
+ if (dataWritten == null) {
+ } else if (!(dataWritten[0] == (byte) 0x70 && dataWritten[1] == 1 && dataWritten[2] == 0 && dataWritten[3] == (byte) 0xF0)) {
+ if (DEBUG)
+ appendToLog("command COMMAND_BEGIN is found with invalid mRfidToWrite: " + byteArrayToString(dataWritten));
+ } else {
+ boolean matched = true;
+ for (int i = 0; i < 4; i++) {
+ if (dataWritten[4 + i] != dataIn[startIndex + 8 + i]) {
+ matched = false;
+ break;
+ }
+ }
+ long lValue = 0;
+ int multipler = 1;
+ for (int i = 0; i < 4; i++) {
+ lValue += (dataIn[startIndex + 12 + i] & 0xFF) * multipler;
+ multipler *= 256;
+ }
+ if (matched == false) {
+ if (DEBUG)
+ appendToLog("command COMMAND_BEGIN is found with mis-matched command:" + byteArrayToString(dataWritten));
+ } else {
+ csReaderConnector.rfidConnector.mRfidToWrite.remove(0);
+ csReaderConnector.rfidConnector.sendRfidToWriteSent = 0;
+ csReaderConnector.rfidConnector.mRfidToWriteRemoved = true;
+ if (DEBUG)
+ appendToLog("mmRfidToWrite remove 8");
+ setInventoring(true);
+ Date date = new Date();
+ long date_time = date.getTime();
+ long expected_firmware_ontime_ms = firmware_ontime_ms;
+ if (date_time_ms != 0) {
+ long firmware_ontime_ms_difference = date_time - date_time_ms;
+ if (firmware_ontime_ms_difference > 2000) {
+ expected_firmware_ontime_ms += (firmware_ontime_ms_difference - 2000);
+ }
+ }
+ if (lValue < expected_firmware_ontime_ms) {
+ csReaderConnector.rfidReader.bFirmware_reset_before = true;
+ if (DEBUG)
+ appendToLogView("command COMMAND_BEGIN --- Firmware reset before !!!");
+ }
+ firmware_ontime_ms = lValue;
+ date_time_ms = date_time;
+ if (DEBUG)
+ appendToLog("command COMMAND_BEGIN is found with packageLength=" + packageLengthRead + ", with firmware count=" + lValue + ", date_time=" + date_time + ", expected firmware count=" + expected_firmware_ontime_ms);
+ rfidDataReadTypes = RfidDataReadTypes.RFID_DATA_READ_COMMAND_BEGIN;
+ }
+ }
+ }
+ break;
+ case 0x0001:
+ case 0x8001: //RFID_PACKET_TYPE_COMMAND_END //original 1
+ if (dataIn[startIndex + 0] != 1 && dataIn[startIndex + 0] != 2) {
+ if (DEBUG)
+ appendToLog("command COMMAND_END is found without first byte as 0x01 or 0x02, " + byteArrayToString(dataInPayload));
+ break;
+ } else {
+ dataA.responseType = RfidReaderChipData.HostCmdResponseTypes.TYPE_COMMAND_END;
+ setInventoring(false);
+ if (DEBUG)
+ appendToLog("command COMMAND_END is found with packageLength=" + packageLengthRead + ", length = " + dataA.dataValues.length + ", dataValues=" + byteArrayToString(dataA.dataValues));
+ if (dataA.dataValues.length >= 8) {
+ int status = dataA.dataValues[12 - 8] + dataA.dataValues[13 - 8] * 256;
+ if (status != 0)
+ dataA.decodedError = "Received COMMAND_END with status=" + String.format("0x%X", status) + ", error_port=" + dataA.dataValues[14 - 8];
+ if (dataA.decodedError != null)
+ if (DEBUG)
+ appendToLog(dataA.decodedError);
+ rfidDataReadTypes = RfidDataReadTypes.RFID_DATA_READ_COMMAND_END;
+ }
+ }
+ int oldSize = mRx000ToRead.size();
+ mRx000ToRead.add(dataA);
+ if (DEBUG)
+ appendToLog("oldSize = " + oldSize + ", after adding 8001 mRx000ToRead.size = " + mRx000ToRead.size());
+ commandOperating = false;
+ break;
+ case 0x0005:
+ case 0x8005: //RFID_PACKET_TYPE_18K6C_INVENTORY //original 5
+ if (dataIn[startIndex + 0] != 3 && dataIn[startIndex + 0] != 4) {
+ if (DEBUG)
+ appendToLog("command 18K6C_INVENTORY is found without first byte as 0x03, 0x04, " + byteArrayToString(dataInPayload));
+ break;
+ } else {
+ if (dataIn[startIndex + 0] == 3) {
+ dataA.responseType = RfidReaderChipData.HostCmdResponseTypes.TYPE_18K6C_INVENTORY;
+ if (true) {
+ boolean crcError;
+ if (dataA.dataValues.length < 12 + 4)
+ dataA.decodedError = "Received TYPE_18K6C_INVENTORY with length = " + String.valueOf(dataA.dataValues.length) + ", data = " + byteArrayToString(dataA.dataValues);
+ else {
+ int epcLength = (dataA.dataValues[12] >> 3) * 2;
+ if (dataA.dataValues.length < 12 + 2 + epcLength + 2)
+ dataA.decodedError = "Received TYPE_18K6C_INVENTORY with length = " + String.valueOf(dataA.dataValues.length) + ", data = " + byteArrayToString(dataA.dataValues);
+ else {
+ setInventoring(true);
+ long time1 = dataA.dataValues[3] & 0x00FF;
+ time1 = time1 << 8;
+ time1 |= dataA.dataValues[2] & 0x00FF;
+ time1 = time1 = time1 << 8;
+ time1 |= dataA.dataValues[1] & 0x00FF;
+ time1 = time1 = time1 << 8;
+ time1 |= dataA.dataValues[0] & 0x00FF;
+ dataA.decodedTime = time1;
+ dataA.decodedRssi = decodeNarrowBandRSSI(dataA.dataValues[13 - 8]);
+
+ byte bValue = dataA.dataValues[14 - 8];
+ bValue &= 0x7F;
+ if ((bValue & 0x40) != 0)
+ bValue |= 0x80;
+ dataA.decodedPhase = bValue;
+ if (true) {
+ int iValue = dataA.dataValues[14 - 8] & 0x3F; //0x7F;
+ boolean b7 = false;
+ if ((dataA.dataValues[14 - 8] & 0x80) != 0)
+ b7 = true;
+ iValue *= 90;
+ iValue /= 32;
+ dataA.decodedPhase = iValue;
+ }
+
+ dataA.decodedChidx = dataA.dataValues[15 - 8];
+ dataA.decodedPort = dataA.dataValues[18 - 8];
+ int data1_count = (dataA.dataValues[16 - 8] & 0xFF);
+ data1_count *= 2;
+ int data2_count = (dataA.dataValues[17 - 8] & 0xFF);
+ data2_count *= 2;
+
+ if (dataA.dataValues.length >= 12 + 2) {
+ dataA.decodedPc = new byte[2];
+ System.arraycopy(dataA.dataValues, 12, dataA.decodedPc, 0, dataA.decodedPc.length);
+ }
+ if (dataA.dataValues.length >= 12 + 2 + 2) {
+ dataA.decodedEpc = new byte[dataA.dataValues.length - 12 - 4];
+ System.arraycopy(dataA.dataValues, 12 + 2, dataA.decodedEpc, 0, dataA.decodedEpc.length);
+ dataA.decodedCrc = new byte[2];
+ System.arraycopy(dataA.dataValues, dataA.dataValues.length - 2, dataA.decodedCrc, 0, dataA.decodedCrc.length);
+ }
+ if (data1_count != 0 && dataA.dataValues.length - 2 - data1_count - data2_count >= 0) {
+ dataA.decodedData1 = new byte[data1_count];
+ System.arraycopy(dataA.dataValues, dataA.dataValues.length - 2 - data1_count - data2_count, dataA.decodedData1, 0, dataA.decodedData1.length);
+ }
+ if (data2_count != 0 && dataA.dataValues.length - 2 - data2_count >= 0) {
+ dataA.decodedData2 = new byte[data2_count];
+ System.arraycopy(dataA.dataValues, dataA.dataValues.length - 2 - data2_count, dataA.decodedData2, 0, dataA.decodedData2.length);
+ }
+ int iData12 = 0;
+ if (dataA.decodedData1 != null) iData12 += dataA.decodedData1.length;
+ if (dataA.decodedData2 != null) iData12 += dataA.decodedData2.length;
+ if (iData12 != 0) {
+ byte[] newEpc = new byte[dataA.decodedEpc.length - iData12];
+ System.arraycopy(dataA.decodedEpc, 0, newEpc, 0, newEpc.length);
+ dataA.decodedEpc = newEpc;
+ }
+ rfidDataReadTypes = RfidDataReadTypes.RFID_DATA_READ_COMMAND_INVENTORY;
+ }
+ }
+ }
+ int oldSize2 = mRx000ToRead.size();
+ mRx000ToRead.add(dataA);
+ if (utility.DEBUG_APDATA) {
+ appendToLog("ApData: dataValues = " + byteArrayToString(dataA.dataValues) + ", 1 decodedRssi = " + dataA.decodedRssi + ", decodedPhase = " + dataA.decodedPhase + ", decodedChidx = " + dataA.decodedChidx + ", decodedPort = " + dataA.decodedPort);
+ appendToLog("ApData: decodedPc/Epc/Crc = " + byteArrayToString(dataA.decodedPc) + ", " + byteArrayToString(dataA.decodedEpc) + ", " + byteArrayToString(dataA.decodedCrc)
+ + ", decodedData1/2 = " + byteArrayToString(dataA.decodedData1) + ", " + byteArrayToString(dataA.decodedData2));
+ }
+ if (DEBUG)
+ appendToLog("oldSize = " + oldSize2 + ", after adding 8005 mRx000ToRead.size = " + mRx000ToRead.size());
+ } else {
+ dataA.responseType = RfidReaderChipData.HostCmdResponseTypes.TYPE_18K6C_INVENTORY_COMPACT;
+ if (true) {
+ if (dataA.dataValues.length < 3)
+ dataA.decodedError = "Received TYPE_18K6C_INVENTORY with length = " + String.valueOf(dataA.dataValues.length) + ", data = " + byteArrayToString(dataA.dataValues);
+ else {
+ int index = 0;
+ byte[] dataValuesFull = dataA.dataValues;
+ while (index < dataValuesFull.length) {
+ dataA.decodedTime = System.currentTimeMillis();
+ if (dataValuesFull.length >= index + 2) {
+ dataA.decodedPc = new byte[2];
+ System.arraycopy(dataValuesFull, index, dataA.decodedPc, 0, dataA.decodedPc.length);
+ index += 2;
+ } else {
+ break;
+ }
+ int epcLength = ((dataA.decodedPc[0] & 0xFF) >> 3) * 2;
+ if (dataValuesFull.length >= index + epcLength) {
+ dataA.decodedEpc = new byte[epcLength];
+ System.arraycopy(dataValuesFull, index, dataA.decodedEpc, 0, epcLength);
+ index += epcLength;
+ }
+ if (dataValuesFull.length >= index + 1) {
+ dataA.decodedRssi = decodeNarrowBandRSSI(dataValuesFull[index]);
+ index++;
+ }
+ if (DEBUG)
+ appendToLog((dataA.dataValues != null ? "mRfidToRead.size() = " + csReaderConnector.rfidConnector.mRfidToRead.size() + ", dataValues = " + byteArrayToString(dataA.dataValues) + ", " : "") + "2 decodedRssi = " + dataA.decodedRssi + ", decodedPc = " + byteArrayToString(dataA.decodedPc) + ", decodedEpc = " + byteArrayToString(dataA.decodedEpc));
+ if (dataValuesFull.length > index) {
+ mRx000ToRead.add(dataA);
+ if (utility.DEBUG_APDATA) appendToLog("ApData: Got data to mRx000ToRead " + mRx000ToRead.size() + ", with decodedEpc = " + byteArrayToString(dataA.decodedEpc));
+
+ int iDecodedPortOld = dataA.decodedPort;
+ dataA = new RfidReaderChipData.Rx000pkgData();
+ dataA.decodedPort = iDecodedPortOld;
+ dataA.responseType = RfidReaderChipData.HostCmdResponseTypes.TYPE_18K6C_INVENTORY_COMPACT;
+ rfidDataReadTypes = RfidDataReadTypes.RFID_DATA_READ_COMMAND_COMPACT;
+ }
+ }
+ }
+ }
+ int oldSize3 = mRx000ToRead.size();
+ mRx000ToRead.add(dataA);
+ if (utility.DEBUG_APDATA) appendToLog("ApData: Got data to mRx000ToRead " + mRx000ToRead.size() + ", with decodedEpc = " + byteArrayToString(dataA.decodedEpc));
+ if (DEBUG)
+ appendToLog("oldSize = " + oldSize3 + ", after adding 8005 mRx000ToRead.size = " + mRx000ToRead.size());
+ }
+ if (DEBUG)
+ appendToLog("command 18K6C_INVENTORY is found with data=" + byteArrayToString(dataA.dataValues));
+ }
+ break;
+ case 6: //RFID_PACKET_TYPE_18K6C_TAG_ACCESS
+ if (dataIn[startIndex + 0] != 1) {
+ if (DEBUG)
+ appendToLog("command 18K6C_TAG_ACCESS is found without first byte as 0x02, " + byteArrayToString(dataInPayload));
+ break;
+ } else {
+ dataA.responseType = RfidReaderChipData.HostCmdResponseTypes.TYPE_18K6C_TAG_ACCESS;
+ if (true) {
+ byte[] dataInPayload_full = new byte[expectedLength];
+ System.arraycopy(dataIn, startIndex, dataInPayload_full, 0, dataInPayload_full.length);
+ if (DEBUG)
+ appendToLog("command TYPE_18K6C_TAG_ACCESS is found with packageLength=" + packageLengthRead + ", " + byteArrayToString(dataInPayload_full));
+ }
+ if (true) {
+ int accessError, backscatterError;
+ boolean timeoutError, crcError;
+ if (dataA.dataValues.length >= 8 + 12) {
+ backscatterError = 0;
+ accessError = 0;
+ timeoutError = false;
+ crcError = false;
+ if ((dataA.dataValues[1] & 8) != 0)
+ crcError = true;
+ else if ((dataA.dataValues[1] & 4) != 0)
+ timeoutError = true;
+ else if ((dataA.dataValues[1] & 2) != 0)
+ backscatterError = (dataA.dataValues[13] & 0xFF);
+ else if ((dataA.dataValues[1] & 1) != 0 && dataA.dataValues.length >= 8 + 12 + 4)
+ accessError = (dataA.dataValues[20] & 0xFF) + (dataA.dataValues[21] & 0xFF) * 256;
+
+ byte[] dataRead = new byte[dataA.dataValues.length - 20];
+ System.arraycopy(dataA.dataValues, 20, dataRead, 0, dataRead.length);
+ if (backscatterError == 0 && accessError == 0 && timeoutError == false && crcError == false) {
+ if ((dataA.dataValues[12] == (byte) 0xC3) || (dataA.dataValues[12] == (byte) 0xC4) || (dataA.dataValues[12] == (byte) 0xC5)
+ || (dataA.dataValues[12] == (byte) 0xD5) || (dataA.dataValues[12] == (byte) 0xE2))
+ dataA.decodedResult = "";
+ else if ((dataA.dataValues[12] == (byte) 0xC2) || (dataA.dataValues[12] == (byte) 0xE0))
+ dataA.decodedResult = byteArrayToString(dataRead);
+ else
+ dataA.decodedError = "Received TYPE_18K6C_TAG_ACCESS with unhandled command = " + String.valueOf(dataA.dataValues[12]) + ", data = " + byteArrayToString(dataA.dataValues);
+ } else {
+ dataA.decodedError = "Received TYPE_18K6C_TAG_ACCESS with Error ";
+ if (crcError)
+ dataA.decodedError += "crcError=" + crcError + ", ";
+ if (timeoutError)
+ dataA.decodedError += "timeoutError=" + timeoutError + ", ";
+ if (backscatterError != 0) {
+ dataA.decodedError += "backscatterError:";
+ String strErrorMessage = String.valueOf(backscatterError);
+ switch (backscatterError) {
+ case 3:
+ strErrorMessage = "Specified memory location does not exist or the PC value is not supported by the tag";
+ break;
+ case 4:
+ strErrorMessage = "Specified memory location is locked and/or permalocked and is not writeable";
+ break;
+ case 0x0B:
+ strErrorMessage = "Tag has insufficient power to perform the memory write";
+ break;
+ case 0x0F:
+ strErrorMessage = "Tag does not support error-specific codes";
+ default:
+ break;
+ }
+ dataA.decodedError += strErrorMessage + ", ";
+ }
+ if (accessError != 0) {
+ dataA.decodedError += "accessError: ";
+ String strErrorMessage = String.valueOf(accessError);
+ switch (accessError) {
+ case 0x01:
+ strErrorMessage = "Read after write verify failed";
+ break;
+ case 0x02:
+ strErrorMessage = "Problem transmitting tag command";
+ break;
+ case 0x03:
+ strErrorMessage = "CRC error on tag response to a write";
+ break;
+ case 0x04:
+ strErrorMessage = "CRC error on the read packet when verifying the write";
+ break;
+ case 0x05:
+ strErrorMessage = "Maximum retries on the write exceeded";
+ break;
+ case 0x06:
+ strErrorMessage = "Failed waiting for read data from tag, possible timeout";
+ break;
+ case 0x07:
+ strErrorMessage = "Failure requesting a new tag handle";
+ break;
+ case 0x09:
+ strErrorMessage = "Out of retries";
+ break;
+ case 0x0A:
+ strErrorMessage = "Error waiting for tag response, possible timeout";
+ break;
+ case 0x0B:
+ strErrorMessage = "CRC error on tag response to a kill";
+ break;
+ case 0x0C:
+ strErrorMessage = "Problem transmitting 2nd half of tag kill";
+ break;
+ case 0x0D:
+ strErrorMessage = "Tag responded with an invalid handle on first kill command";
+ break;
+ default:
+ break;
+ }
+ dataA.decodedError += strErrorMessage + ", ";
+ }
+ dataA.decodedError += "data = " + byteArrayToString(dataA.dataValues);
+ rfidDataReadTypes = RfidDataReadTypes.RFID_DATA_READ_COMMAND_ACCESS;
+ }
+ } else {
+ dataA.decodedError = "Received TYPE_18K6C_TAG_ACCESS with length = " + String.valueOf(dataA.dataValues.length) + ", data = " + byteArrayToString(dataA.dataValues);
+ }
+ }
+ }
+ int oldSize4 = mRx000ToRead.size();
+ mRx000ToRead.add(dataA);
+ if (DEBUG)
+ appendToLog("oldSize = " + oldSize4 + ", after adding 0006 mRx000ToRead.size = " + mRx000ToRead.size());
+ if (DEBUG) {
+ appendToLog("mRx000UplinkHandler(): package read = " + byteArrayToString(dataA.dataValues));
+ }
+ break;
+ case 0x0007:
+ case 0x8007: //RFID_PACKET_TYPE_ANTENNA_CYCLE_END //original 7
+ if (dataIn[startIndex + 0] != 1 && dataIn[startIndex + 0] != 2) {
+ if (DEBUG)
+ appendToLog("command TYPE_ANTENNA_CYCLE_END is found without first byte as 0x01 or 0x02, " + byteArrayToString(dataInPayload));
+ break;
+ } else {
+ dataA.responseType = RfidReaderChipData.HostCmdResponseTypes.TYPE_ANTENNA_CYCLE_END;
+ if (DEBUG)
+ appendToLog("command TYPE_ANTENNA_CYCLE_END is found with packageLength=" + packageLengthRead + ", " + byteArrayToString(dataInPayload));
+ rfidDataReadTypes = RfidDataReadTypes.RFID_DATA_READ_COMMAND_END;
+ }
+ mRx000ToRead.add(dataA);
+ break;
+ case 0x000E:
+ if (dataIn[startIndex + 0] != 1 && dataIn[startIndex + 0] != 2) {
+ if (DEBUG)
+ appendToLog("command TYPE_COMMAND_ACTIVE is found without first byte as 0x01 or 0x02, " + byteArrayToString(dataInPayload));
+ break;
+ } else {
+ dataA.responseType = RfidReaderChipData.HostCmdResponseTypes.TYPE_COMMAND_ACTIVE;
+ if (DEBUG)
+ appendToLog("command TYPE_COMMAND_ACTIVE is found with packageLength=" + packageLengthRead + ", " + byteArrayToString(dataInPayload));
+ rfidDataReadTypes = RfidDataReadTypes.RFID_DATA_READ_COMMAND_ACTIVE;
+ }
+ mRx000ToRead.add(dataA);
+ break;
+ case 0x3005: //RFID_PACKET_TYPE_MBP_READ
+ int address = (dataIn[startIndex + 8] & 0xFF) + (dataIn[startIndex + 9] & 0xFF) * 256;
+ switch (address) {
+ case 0x450:
+ rx000MbpSetting.rxGain = (dataIn[startIndex + 10] & 0xFF) + (dataIn[startIndex + 11] & 0xFF) * 256;
+ break;
+ default:
+ break;
+ }
+ rfidDataReadTypes = RfidDataReadTypes.RFID_DATA_READ_COMMAND_MBPREAD;
+ case 0x3007: //RFID_PACKET_TYPE_OEMCFG_READ
+ address = (dataIn[startIndex + 8] & 0xFF) + (dataIn[startIndex + 9] & 0xFF) * 256 + (dataIn[startIndex + 10] & 0xFF) * 256 * 256 + (dataIn[startIndex + 11] & 0xFF) * 256 * 256 * 256;
+ switch (address) {
+ case 0x02:
+// dataIn[startIndex + 12] = 3;
+ rx000OemSetting.countryCode = (dataIn[startIndex + 12] & 0xFF) + (dataIn[startIndex + 13] & 0xFF) * 256 + (dataIn[startIndex + 14] & 0xFF) * 256 * 256 + (dataIn[startIndex + 15] & 0xFF) * 256 * 256 * 256;
+ if (DEBUG)
+ appendToLog("countryCode = " + rx000OemSetting.countryCode);
+ break;
+ case 0x04:
+ case 0x05:
+ case 0x06:
+ case 0x07:
+ System.arraycopy(dataIn, startIndex + 12, rx000OemSetting.serialNumber, 4 * (address - 4), 4);
+ break;
+ case 0x08:
+ case 0x09:
+ case 0x0A:
+ if (true) {
+ byte[] bytes = new byte[4];
+ System.arraycopy(dataIn, startIndex + 12, bytes, 0, 4);
+ appendToLog("product serial number, " + address + ": " + byteArrayToString(bytes));
+ }
+ System.arraycopy(dataIn, startIndex + 12, rx000OemSetting.productserialNumber, 4 * (address - 8), 4);
+ break;
+ case 0x0B: //VERSIONCODE_MAX
+ System.arraycopy(dataIn, startIndex + 12, rx000OemSetting.productserialNumber, 4 * (address - 8), 4);
+ if (dataIn[startIndex + 12] == 0 && dataIn[startIndex + 13] == 0 && dataIn[startIndex + 14] == 0 && dataIn[startIndex + 15] == 0) {
+ rx000OemSetting.versionCode = 0;
+ } else if (dataIn[startIndex + 12] == 0x20 && dataIn[startIndex + 13] == 0x17 && dataIn[startIndex + 14] == 0) {
+ rx000OemSetting.versionCode = (dataIn[startIndex + 14] & 0xFF) + (dataIn[startIndex + 15] & 0xFF) * 256;
+ }
+ if (DEBUG)
+ appendToLog("versionCode = " + rx000OemSetting.versionCode);
+ break;
+ case 0x8E:
+ /*dataIn[startIndex + 12] = 0x2A; //0x4F;
+ dataIn[startIndex + 13] = 0x2A; //0x46;
+ dataIn[startIndex + 14] = 0x4E; //0x41; //0x43;
+ dataIn[startIndex + 15] = 0x5A; //0x53; //0x41; */
+ if (dataIn[startIndex + 12] == 0 || dataIn[startIndex + 13] == 0 || dataIn[startIndex + 14] == 0 || dataIn[startIndex + 15] == 0) {
+ rx000OemSetting.spcialCountryVersion = "";
+ } else {
+ rx000OemSetting.spcialCountryVersion = String.valueOf((char) dataIn[startIndex + 15])
+ + String.valueOf((char) dataIn[startIndex + 14])
+ + String.valueOf((char) dataIn[startIndex + 13])
+ + String.valueOf((char) dataIn[startIndex + 12]);
+ }
+ byte[] dataInPart = new byte[4];
+ System.arraycopy(dataIn, startIndex + 12, dataInPart, 0, dataInPart.length);
+ if (DEBUG)
+ appendToLog("spcialCountryVersion = " + rx000OemSetting.spcialCountryVersion + ", data = " + byteArrayToString(dataInPart));
+ break;
+ case 0x8F:
+ //dataIn[startIndex + 12] = (byte)0xAA;
+ rx000OemSetting.freqModifyCode = (dataIn[startIndex + 12] & 0xFF) + (dataIn[startIndex + 13] & 0xFF) * 256 + (dataIn[startIndex + 14] & 0xFF) * 256 * 256 + (dataIn[startIndex + 15] & 0xFF) * 256 * 256 * 256;
+ if (DEBUG)
+ appendToLog("freqModifyCode = " + rx000OemSetting.freqModifyCode);
+ break;
+ default:
+ break;
+ }
+/* if (address >= 4 && address <= 7) {
+ for (int i = 0; i < 4; i++) {
+ mRx000OemSetting.serialNumber[(address - 4) * 4 + i] = dataIn[startIndex + 12 + i];
+ }
+ }*/
+ if (DEBUG)
+ appendToLog("command OEMCFG_READ is found with address = " + address + ", packageLength=" + packageLengthRead + ", " + byteArrayToString(dataInPayload));
+ rfidDataReadTypes = RfidDataReadTypes.RFID_DATA_READ_COMMAND_OEMREAD;
+ break;
+ case 0x3008: //RFID_PACKET_TYPE_ENG_RSSI
+ if (DEBUG)
+ appendToLog("Hello123: RFID_PACKET_TYPE_ENG_RSSI S is found: " + byteArrayToString(dataInPayload));
+ if ((dataIn[startIndex + 8] & 0x02) != 0) {
+ rx000EngSetting.narrowRSSI = (dataIn[startIndex + 28] & 0xFF) + (dataIn[startIndex + 29] & 0xFF) * 256;
+ rx000EngSetting.wideRSSI = (dataIn[startIndex + 30] & 0xFF) + (dataIn[startIndex + 31] & 0xFF) * 256;
+ if (DEBUG)
+ appendToLog("Hello123: narrorRSSI = " + String.format("%04X", rx000EngSetting.narrowRSSI) + ", wideRSSI = " + String.format("%04X", rx000EngSetting.wideRSSI));
+ rfidDataReadTypes = RfidDataReadTypes.RFID_DATA_READ_COMMAND_RSSI;
+ }
+ break;
+ default:
+ if (DEBUG)
+ appendToLog("command OTHERS is found: " + byteArrayToString(dataInPayload) + ", with packagelength=" + packageLengthRead + ", packageTypeRead=" + packageTypeRead);
+ break;
+ }
+ packageFound = true;
+ packageType = 3; //0x01 to 0x04
+ startIndexNew = startIndex + expectedLength;
+ }
+ }
+ }
+ }
+
+ if (packageFound) {
+ packageFound = false;
+ if (false && utility.DEBUG_APDATA)
+ appendToLog("ApData: found packageType " + packageType + " with mRfidToReadingOffset=" + mRfidToReadingOffset + ", startIndexOld= " + startIndexOld + ", startIndex= " + startIndex + ", startIndexNew=" + startIndexNew);
+ if (startIndex != startIndexOld) {
+ byte[] unhandledBytes = new byte[startIndex - startIndexOld];
+ System.arraycopy(mRfidToReading, startIndexOld, unhandledBytes, 0, unhandledBytes.length);
+ if (utility.DEBUG_APDATA)
+ appendToLog("ApData: packageFound with invalid unused data: " + unhandledBytes.length + ", " + byteArrayToString(unhandledBytes));
+ invalidUpdata++;
+ writeDebug2File("Up4 invalid " + unhandledBytes.length + ", " + byteArrayToString(unhandledBytes));
+ } else if (startIndexNew != startIndex) {
+ data1 = new byte[startIndexNew - startIndex];
+ System.arraycopy(mRfidToReading, startIndex, data1, 0, data1.length);
+ String string = "Up4 " + (rfidDataReadTypes != null ? (rfidDataReadTypes.toString() + ", ") : "Unprocessed, ");
+ if (data1.length <= 8 && data1[0] == 0x40)
+ string += (byteArrayToString(data1).substring(0, 4) + " " + byteArrayToString(data1).substring(4, 16));
+ else {
+ string += (byteArrayToString(data1).substring(0, 8) + " " + byteArrayToString(data1).substring(8, 16) + " " + (byteArrayToString(data1).substring(16)));
+ }
+ utility.writeDebug2File(string);
+ if (utility.DEBUG_APDATA) appendToLog("ApData: Found startIndexNew=" + startIndexNew + ", string=" + string);
+ if (false && utility.DEBUG_APDATA) {
+ byte[] usedBytes = new byte[startIndexNew - startIndex];
+ System.arraycopy(mRfidToReading, startIndex, usedBytes, 0, usedBytes.length);
+ appendToLog("ApData: used data = " + usedBytes.length + ", " + byteArrayToString(usedBytes));
+ }
+
+ }
+ byte[] mRfidToReadingNew = new byte[RFID_READING_BUFFERSIZE];
+ System.arraycopy(mRfidToReading, startIndexNew, mRfidToReadingNew, 0, mRfidToReadingOffset - startIndexNew);
+ mRfidToReading = mRfidToReadingNew;
+ mRfidToReadingOffset -= startIndexNew;
+ startIndex = 0;
+ startIndexNew = 0;
+ startIndexOld = 0;
+ if (mRfidToReadingOffset != 0) {
+ byte[] remainedBytes = new byte[mRfidToReadingOffset];
+ System.arraycopy(mRfidToReading, 0, remainedBytes, 0, remainedBytes.length);
+ if (utility.DEBUG_APDATA)
+ appendToLog("ApData: moved with remained bytes=" + byteArrayToString(remainedBytes));
+ }
+ } else {
+ startIndex++;
+ }
+ }
+ if (utility.DEBUG_APDATA && bLooping2) appendToLog("ApData: Exiting second loop with mRfidToReadingOffset = " + mRfidToReadingOffset + ", startIndex = " + startIndex);
+ if (startIndex != 0 && mRfidToReadingOffset != 0) {
+ if (utility.DEBUG_APDATA)
+ appendToLog("ApData: exit while(-8) loop with startIndex = " + startIndex + (startIndex == 0 ? "" : "(NON-ZERO)") + ", mRfidToReadingOffset=" + mRfidToReadingOffset);
+ }
+ }
+ }
+ if (utility.DEBUG_APDATA && bLooping) appendToLog("ApData: Exiting loop with mRfidToRead.size as " + csReaderConnector.rfidConnector.mRfidToRead.size());
+ if (mRfidToReadingOffset == startIndexNew && mRfidToReadingOffset != 0) {
+ byte[] unusedData = new byte[mRfidToReadingOffset];
+ System.arraycopy(mRfidToReading, 0, unusedData, 0, unusedData.length);
+ if (DEBUG)
+ appendToLog("Up4 Invalid " + mRfidToReadingOffset + ", " + byteArrayToString(unusedData));
+ mRfidToReading = new byte[RFID_READING_BUFFERSIZE];
+ mRfidToReadingOffset = 0;
+ utility.writeDebug2File("Up4 Invalid " + byteArrayToString(unusedData));
+ }
+ if (DEBUGTHREAD) appendToLog("mRx000UplinkHandler(): END");
+ bRx000ToReading = false;
+ }
+
+ public boolean turnOn(boolean onStatus) {
+ RfidConnector.CsReaderRfidData csReaderRfidData = new RfidConnector.CsReaderRfidData();
+ if (onStatus) {
+ csReaderRfidData.rfidPayloadEvent = RfidConnector.RfidPayloadEvents.RFID_POWER_ON;
+ csReaderRfidData.waitUplinkResponse = false;
+ clearTempDataIn_request = true;
+ addRfidToWrite(csReaderRfidData);
+ return true;
+ } else if (onStatus == false) {
+ csReaderRfidData.rfidPayloadEvent = RfidConnector.RfidPayloadEvents.RFID_POWER_OFF;
+ csReaderRfidData.waitUplinkResponse = false;
+ clearTempDataIn_request = true;
+ addRfidToWrite(csReaderRfidData);
+ return true;
+ } else {
+ return false;
+ }
+ }
+
+ public boolean sendControlCommand(ControlCommands controlCommands) {
+ byte[] msgBuffer = new byte[]{(byte) 0x40, 6, 0, 0, 0, 0, 0, 0};
+ boolean needResponse = false;
+ if (csReaderConnector.isConnected() == false) return false;
+ switch (controlCommands) {
+ default:
+ msgBuffer = null;
+ case CANCEL:
+ msgBuffer[1] = 1;
+ commandOperating = false;
+ break;
+ case SOFTRESET:
+ msgBuffer[1] = 2;
+ needResponse = true;
+ break;
+ case ABORT:
+ msgBuffer[1] = 3;
+ needResponse = true;
+ commandOperating = false;
+ break;
+ case PAUSE:
+ msgBuffer[1] = 4;
+ break;
+ case RESUME:
+ msgBuffer[1] = 5;
+ break;
+ case GETSERIALNUMBER:
+ msgBuffer = new byte[]{(byte) 0xC0, 0x06, 0, 0, 0, 0, 0, 0};
+ needResponse = true;
+ break;
+ case RESETTOBOOTLOADER:
+ msgBuffer[1] = 7;
+ needResponse = true;
+ break;
+ }
+
+ if (msgBuffer == null) {
+ if (DEBUG) appendToLog("Invalid control commands");
+ return false;
+ } else {
+ clearTempDataIn_request = true;
+
+ RfidConnector.CsReaderRfidData csReaderRfidData = new RfidConnector.CsReaderRfidData();
+ csReaderRfidData.rfidPayloadEvent = RfidConnector.RfidPayloadEvents.RFID_COMMAND;
+ csReaderRfidData.dataValues = msgBuffer;
+ if (needResponse) {
+// if (DEBUG) appendToLog("sendControlCommand() adds to mRx000ToWrite");
+ csReaderRfidData.waitUplinkResponse = needResponse;
+ addRfidToWrite(csReaderRfidData);
+// mRx000ToWrite.add(cs108RfidData);
+ } else {
+// if (DEBUG) appendToLog("sendControlCommand() adds to mRfidToWrite");
+ csReaderRfidData.waitUplinkResponse = needResponse;
+ addRfidToWrite(csReaderRfidData);
+ }
+ if (controlCommands == ControlCommands.ABORT) aborting = true;
+ return true;
+ }
+ }
+
+ boolean sendHostRegRequestHST_RFTC_FRQCH_DESC_PLLDIVMULT(int freqChannel) {
+ long fccFreqTable[] = new long[]{
+ 0x00180E4F, //915.75 MHz
+ 0x00180E4D, //915.25 MHz
+ 0x00180E1D, //903.25 MHz
+ 0x00180E7B, //926.75 MHz
+ 0x00180E79, //926.25 MHz
+ 0x00180E21, //904.25 MHz
+ 0x00180E7D, //927.25 MHz
+ 0x00180E61, //920.25 MHz
+ 0x00180E5D, //919.25 MHz
+ 0x00180E35, //909.25 MHz
+ 0x00180E5B, //918.75 MHz
+ 0x00180E57, //917.75 MHz
+ 0x00180E25, //905.25 MHz
+ 0x00180E23, //904.75 MHz
+ 0x00180E75, //925.25 MHz
+ 0x00180E67, //921.75 MHz
+ 0x00180E4B, //914.75 MHz
+ 0x00180E2B, //906.75 MHz
+ 0x00180E47, //913.75 MHz
+ 0x00180E69, //922.25 MHz
+ 0x00180E3D, //911.25 MHz
+ 0x00180E3F, //911.75 MHz
+ 0x00180E1F, //903.75 MHz
+ 0x00180E33, //908.75 MHz
+ 0x00180E27, //905.75 MHz
+ 0x00180E41, //912.25 MHz
+ 0x00180E29, //906.25 MHz
+ 0x00180E55, //917.25 MHz
+ 0x00180E49, //914.25 MHz
+ 0x00180E2D, //907.25 MHz
+ 0x00180E59, //918.25 MHz
+ 0x00180E51, //916.25 MHz
+ 0x00180E39, //910.25 MHz
+ 0x00180E3B, //910.75 MHz
+ 0x00180E2F, //907.75 MHz
+ 0x00180E73, //924.75 MHz
+ 0x00180E37, //909.75 MHz
+ 0x00180E5F, //919.75 MHz
+ 0x00180E53, //916.75 MHz
+ 0x00180E45, //913.25 MHz
+ 0x00180E6F, //923.75 MHz
+ 0x00180E31, //908.25 MHz
+ 0x00180E77, //925.75 MHz
+ 0x00180E43, //912.75 MHz
+ 0x00180E71, //924.25 MHz
+ 0x00180E65, //921.25 MHz
+ 0x00180E63, //920.75 MHz
+ 0x00180E6B, //922.75 MHz
+ 0x00180E1B, //902.75 MHz
+ 0x00180E6D, //923.25 MHz
+ };
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 3, 0x0C, 0, 0, 0, 0};
+ if (freqChannel >= 50) {
+ freqChannel = 49;
+ }
+ long freqData = fccFreqTable[freqChannel];
+ msgBuffer[4] = (byte) (freqData % 256);
+ msgBuffer[5] = (byte) ((freqData >> 8) % 256);
+ msgBuffer[6] = (byte) ((freqData >> 16) % 256);
+ msgBuffer[7] = (byte) ((freqData >> 24) % 256);
+ return sendHostRegRequest(HostRegRequests.HST_RFTC_FRQCH_DESC_PLLDIVMULT, true, msgBuffer);
+ }
+
+ boolean bLowPowerStandby = false;
+
+ public boolean setPwrManagementMode(boolean bLowPowerStandby) {
+ if (false) appendToLog("pwrMgmtStatus: setPwrManagementMode(" + bLowPowerStandby + ")");
+ if (true) return false; //ignore this setting
+ if (this.bLowPowerStandby == bLowPowerStandby) return true;
+ boolean result = rx000Setting.writeMAC(0x200, (bLowPowerStandby ? 1 : 0));
+ if (result) {
+ result = sendHostRegRequestHST_CMD(RfidReaderChipData.HostCommands.CMD_SETPWRMGMTCFG);
+ this.bLowPowerStandby = bLowPowerStandby;
+ rx000Setting.getPwrMgmtStatus();
+ }
+ return result;
+ }
+
+ public boolean sendHostRegRequestHST_CMD(RfidReaderChipData.HostCommands hostCommand) {
+ long hostCommandData = -1;
+ switch (hostCommand) {
+ case CMD_WROEM:
+ hostCommandData = 0x02;
+ break;
+ case CMD_RDOEM:
+ hostCommandData = 0x03;
+ break;
+ case CMD_ENGTEST:
+ hostCommandData = 0x04;
+ break;
+ case CMD_MBPRDREG:
+ hostCommandData = 0x05;
+ break;
+ case CMD_MBPWRREG:
+ hostCommandData = 0x06;
+ break;
+ case CMD_18K6CINV:
+ hostCommandData = 0x0F;
+ break;
+ case CMD_18K6CREAD:
+ hostCommandData = 0x10;
+ break;
+ case CMD_18K6CWRITE:
+ hostCommandData = 0x11;
+ break;
+ case CMD_18K6CLOCK:
+ hostCommandData = 0x12;
+ break;
+ case CMD_18K6CKILL:
+ hostCommandData = 0x13;
+ break;
+ case CMD_SETPWRMGMTCFG:
+ hostCommandData = 0x14;
+ break;
+ case CMD_UPDATELINKPROFILE:
+ hostCommandData = 0x19;
+ break;
+ case CMD_18K6CBLOCKWRITE:
+ hostCommandData = 0x1F;
+ break;
+ case CMD_CHANGEEAS:
+ hostCommandData = 0x26;
+ break;
+ case CMD_GETSENSORDATA:
+ hostCommandData = 0x3b;
+ break;
+ case CMD_18K6CAUTHENTICATE:
+ hostCommandData = 0x50;
+ break;
+ case CMD_READBUFFER:
+ hostCommandData = 0x51;
+ break;
+ case CMD_UNTRACEABLE:
+ hostCommandData = 0x52;
+ break;
+ case CMD_FDM_RDMEM:
+ hostCommandData = 0x53;
+ break;
+ case CMD_FDM_WRMEM:
+ hostCommandData = 0x54;
+ break;
+ case CMD_FDM_AUTH:
+ hostCommandData = 0x55;
+ break;
+ case CMD_FDM_GET_TEMPERATURE:
+ hostCommandData = 0x56;
+ break;
+ case CMD_FDM_START_LOGGING:
+ hostCommandData = 0x57;
+ break;
+ case CMD_FDM_STOP_LOGGING:
+ hostCommandData = 0x58;
+ break;
+ case CMD_FDM_WRREG:
+ hostCommandData = 0x59;
+ break;
+ case CMD_FDM_RDREG:
+ hostCommandData = 0x5A;
+ break;
+ case CMD_FDM_DEEP_SLEEP:
+ hostCommandData = 0x5B;
+ break;
+ case CMD_FDM_OPMODE_CHECK:
+ hostCommandData = 0x5C;
+ break;
+ case CMD_FDM_INIT_REGFILE:
+ hostCommandData = 0x5d;
+ break;
+ case CMD_FDM_LED_CTRL:
+ hostCommandData = 0x5e;
+ break;
+ }
+ if (hostCommandData == -1) {
+ return false;
+ } else {
+ commandOperating = true;
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 0, (byte) 0xf0, 0, 0, 0, 0};
+ msgBuffer[4] = (byte) (hostCommandData % 256);
+ msgBuffer[5] = (byte) ((hostCommandData >> 8) % 256);
+ msgBuffer[6] = (byte) ((hostCommandData >> 16) % 256);
+ msgBuffer[7] = (byte) ((hostCommandData >> 24) % 256);
+ return sendHostRegRequest(HostRegRequests.HST_CMD, true, msgBuffer);
+ }
+ }
+
+ ArrayList macAccessHistory = new ArrayList<>();
+
+ boolean bifMacAccessHistoryData(byte[] msgBuffer) {
+ if (sameCheck == false) return false;
+ if (msgBuffer.length != 8) return false;
+ if (msgBuffer[0] != (byte) 0x70 || msgBuffer[1] != 1) return false;
+ if (msgBuffer[2] == 0 && msgBuffer[3] == (byte) 0xF0) return false;
+ return true;
+ }
+
+ int findMacAccessHistory(byte[] msgBuffer) {
+ int i = -1;
+ for (i = 0; i < macAccessHistory.size(); i++) {
+// appendToLog("macAccessHistory(" + i + ")=" + byteArrayToString(macAccessHistory.get(i)));
+ if (Arrays.equals(macAccessHistory.get(i), msgBuffer)) break;
+ }
+ if (i == macAccessHistory.size()) i = -1;
+ if (i >= 0)
+ appendToLog("macAccessHistory: returnValue = " + i + ", msgBuffer=" + byteArrayToString(msgBuffer));
+ return i;
+ }
+
+ void addMacAccessHistory(byte[] msgBuffer) {
+ boolean DEBUG = false;
+ byte[] msgBuffer4 = Arrays.copyOf(msgBuffer, 4);
+ for (int i = 0; i < macAccessHistory.size(); i++) {
+ byte[] macAccessHistory4 = Arrays.copyOf(macAccessHistory.get(i), 4);
+ if (Arrays.equals(msgBuffer4, macAccessHistory4)) {
+ if (DEBUG)
+ appendToLog("macAccessHistory: deleted old record=" + byteArrayToString(macAccessHistory4));
+ macAccessHistory.remove(i);
+ break;
+ }
+ }
+ if (DEBUG)
+ appendToLog("macAccessHistory: added msgbuffer=" + byteArrayToString(msgBuffer));
+ macAccessHistory.add(msgBuffer);
+ }
+
+ boolean sendHostRegRequest(HostRegRequests hostRegRequests, boolean writeOperation, byte[] msgBuffer) {
+ boolean needResponse = false;
+ boolean validRequest = false;
+
+ if (csReaderConnector.isConnected() == false) return false;
+ addMacAccessHistory(msgBuffer);
+ switch (hostRegRequests) {
+ case MAC_OPERATION:
+ case HST_ANT_CYCLES:
+ case HST_ANT_DESC_SEL:
+ case HST_ANT_DESC_CFG:
+ case MAC_ANT_DESC_STAT:
+ case HST_ANT_DESC_PORTDEF:
+ case HST_ANT_DESC_DWELL:
+ case HST_ANT_DESC_RFPOWER:
+ case HST_ANT_DESC_INV_CNT:
+ validRequest = true;
+ break;
+ case HST_TAGMSK_DESC_SEL:
+ case HST_TAGMSK_DESC_CFG:
+ case HST_TAGMSK_BANK:
+ case HST_TAGMSK_PTR:
+ case HST_TAGMSK_LEN:
+ case HST_TAGMSK_0_3:
+ validRequest = true;
+ break;
+ case HST_QUERY_CFG:
+ case HST_INV_CFG:
+ case HST_INV_SEL:
+ case HST_INV_ALG_PARM_0:
+ case HST_INV_ALG_PARM_1:
+ case HST_INV_ALG_PARM_2:
+ case HST_INV_ALG_PARM_3:
+ case HST_INV_RSSI_FILTERING_CONFIG:
+ case HST_INV_RSSI_FILTERING_THRESHOLD:
+ case HST_INV_RSSI_FILTERING_COUNT:
+ case HST_INV_EPC_MATCH_CFG:
+ case HST_INV_EPCDAT_0_3:
+ validRequest = true;
+ break;
+ case HST_TAGACC_DESC_CFG:
+ case HST_TAGACC_BANK:
+ case HST_TAGACC_PTR:
+ case HST_TAGACC_CNT:
+ case HST_TAGACC_LOCKCFG:
+ case HST_TAGACC_ACCPWD:
+ case HST_TAGACC_KILLPWD:
+ case HST_TAGWRDAT_SEL:
+ case HST_TAGWRDAT_0:
+ validRequest = true;
+ break;
+ case HST_RFTC_CURRENT_PROFILE:
+ case HST_RFTC_FRQCH_SEL:
+ case HST_RFTC_FRQCH_CFG:
+ case HST_RFTC_FRQCH_DESC_PLLDIVMULT:
+ case HST_RFTC_FRQCH_DESC_PLLDACCTL:
+ case HST_RFTC_FRQCH_CMDSTART:
+ validRequest = true;
+ break;
+ case HST_AUTHENTICATE_CFG:
+ case HST_AUTHENTICATE_MSG:
+ case HST_READBUFFER_LEN:
+ case HST_UNTRACEABLE_CFG:
+ validRequest = true;
+ break;
+ case HST_CMD:
+ validRequest = true;
+ needResponse = true;
+ break;
+ }
+
+ boolean DEBUG = false;
+ if (DEBUG)
+ appendToLog("checking msgbuffer = " + (msgBuffer == null ? "NULL" : "Valid") + ", validRequst = " + validRequest);
+ if (msgBuffer == null || validRequest == false) {
+ if (DEBUG) appendToLog("Invalid HST_REQ_REQ or null message");
+ return false;
+ } else {
+ if (DEBUG) appendToLog("True Ending 0");
+ RfidConnector.CsReaderRfidData csReaderRfidData = new RfidConnector.CsReaderRfidData();
+ csReaderRfidData.rfidPayloadEvent = RfidConnector.RfidPayloadEvents.RFID_COMMAND;
+ csReaderRfidData.dataValues = msgBuffer;
+ if (needResponse || writeOperation == false) {
+ csReaderRfidData.waitUplinkResponse = (needResponse || writeOperation == false);
+// mRx000ToWrite.add(cs108RfidData);
+ addRfidToWrite(csReaderRfidData);
+ } else {
+ csReaderRfidData.waitUplinkResponse = (needResponse || writeOperation == false);
+ addRfidToWrite(csReaderRfidData);
+ }
+ if (DEBUG) appendToLog("True Ending");
+ return true;
+ }
+ }
+
+ void addRfidToWrite(RfidConnector.CsReaderRfidData csReaderRfidData) {
+ boolean repeatRequest = false;
+ if (csReaderConnector.rfidConnector.mRfidToWrite.size() != 0) {
+ RfidConnector.CsReaderRfidData csReaderRfidData1 = csReaderConnector.rfidConnector.mRfidToWrite.get(csReaderConnector.rfidConnector.mRfidToWrite.size() - 1);
+ if (csReaderRfidData.rfidPayloadEvent == csReaderRfidData1.rfidPayloadEvent) {
+ if (csReaderRfidData.dataValues == null && csReaderRfidData1.dataValues == null) {
+ repeatRequest = true;
+ } else if (csReaderRfidData.dataValues != null && csReaderRfidData1.dataValues != null) {
+ if (csReaderRfidData.dataValues.length == csReaderRfidData1.dataValues.length) {
+ if (compareArray(csReaderRfidData.dataValues, csReaderRfidData1.dataValues, csReaderRfidData.dataValues.length)) {
+ repeatRequest = true;
+ }
+ }
+ }
+ }
+ }
+ if (repeatRequest == false) {
+ byte[] bytesCmd = new byte[] { 0x70, 1, 0, 0x09 };
+ byte[] bytesCmd1 = new byte[] { 0x70, 1, 1, 0x09 };
+ if (csReaderRfidData.dataValues != null) {
+ byte[] bytesNew = new byte[4];
+ System.arraycopy(csReaderRfidData.dataValues, 0, bytesNew, 0, bytesNew.length);
+ if (Arrays.equals(bytesCmd, bytesNew) || Arrays.equals(bytesCmd1, bytesNew)) {
+ int i = 0;
+ for (; i < csReaderConnector.rfidConnector.mRfidToWrite.size(); i++) {
+ if (csReaderConnector.rfidConnector.mRfidToWrite.get(i).dataValues != null) {
+ byte[] bytesOld = new byte[4];
+ System.arraycopy(csReaderConnector.rfidConnector.mRfidToWrite.get(i).dataValues, 0, bytesOld, 0, bytesOld.length);
+ if (Arrays.equals(bytesNew, bytesOld)) {
+ //appendToLog("BtDataOut: matched data " + byteArrayToString(csReaderRfidData.dataValues));
+ csReaderConnector.rfidConnector.mRfidToWrite.remove(i);
+ break;
+ }
+ }
+ }
+ }
+ }
+ }
+ csReaderConnector.rfidConnector.mRfidToWrite.add(csReaderRfidData);
+ }
+ //}
+
+ boolean inventoring = false;
+ public boolean isInventoring() { return inventoring; }
+ void setInventoring(boolean enable) { inventoring = enable; utility.debugFileEnable(false); if (false) appendToLog("setInventoring R2000 is set as " + inventoring);}
+}
+
+
+
+package com.csl.cslibrary4a;
+
+import android.content.Context;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+
+public class SettingData {
+ final boolean DEBUG_FILE = true;
+
+ public int channel = -1;
+ int antennaPower = -1;
+ Context context; Utility utility; NotificationConnector notificationConnector; RfidReader rfidReader; CsReaderConnector csReaderConnector;
+ //CsReaderConnector csReaderConnector;
+
+ public SettingData(Context context, Utility utility, CsReaderConnector csReaderConnector) {
+ this.context = context;
+ this.utility = utility;
+ this.csReaderConnector = csReaderConnector;
+ appendToLog("SettingData:"
+ + "\nthis.context is " + (this.context == null ? "null" : "valid")
+ + "\nthis.utility is " + (this.utility == null ? "null" : "valid")
+ + "\nthis.csReaderConnector is " + (this.csReaderConnector == null ? "null" : "valid")
+ );
+ loadForegroundSettingFile();
+ }
+ public void setConnectedConnectors(NotificationConnector notificationConnector, RfidReader rfidReader) {
+ this.notificationConnector = notificationConnector;
+ this.rfidReader = rfidReader;
+ appendToLog("SettingData: this.notificationConnector is " + (this.notificationConnector == null ? "null" : "valid")
+ + "\nthis.rfidReader is " + (this.rfidReader == null ? "null" : "valid")
+ );
+ }
+
+ private void appendToLog(String s) {
+ utility.appendToLog(s);
+ }
+
+ public void write2FileStream(FileOutputStream stream, String string) {
+ boolean DEBUG = true;
+ try {
+ stream.write(string.getBytes());
+ if (true) appendToLog("FileA outData = " + string);
+ } catch (Exception ex) {
+ }
+ }
+
+ //Operation -- regulatory region, power order, fixed channel,
+ // -- power level (assume 1), enable (assume enable), power, dwell, intraPacket delay, duplication elimination,
+ // -- tag population, Q value
+ // -- session, target, tag focus, fast id,
+ // -- query algorithm
+ // -- minimum minQ cycles
+ // -- reader mode
+
+ //Administration -- reader model, reader name,
+ // -- battery level format
+ // -- inventory rssi unit, beep trigger enable/count, vibration enble/time, vibrate for, vibrate window
+ // -- saving format, cloud enable, file saving enable, cloud address, cloud connect timeout
+ // -- impinj verificaion address, name, password
+ // -- foreground service enable, foreground reader
+ // -- barcode trigger mode
+ // -- enable debugging
+ //public boolean inventoryBeepDefault = true;
+ //boolean inventoryBeep = inventoryBeepDefault;
+ //public boolean getInventoryBeep() {
+ // return inventoryBeep;
+ //}
+ //public boolean setInventoryBeep(boolean inventoryBeep) {
+ // this.inventoryBeep = inventoryBeep;
+ // return true;
+ //}
+
+ public int batteryDisplaySelectDefault = 1, batteryDisplaySelect = batteryDisplaySelectDefault;
+ public boolean setBatteryDisplaySetting(int batteryDisplaySelect) {
+ if (batteryDisplaySelect < 0 || batteryDisplaySelect > 1) return false;
+ this.batteryDisplaySelect = batteryDisplaySelect;
+ return true;
+ }
+ public int rssiDisplaySelectDefault = 1, rssiDisplaySelect = rssiDisplaySelectDefault;
+ public boolean setRssiDisplaySetting(int rssiDisplaySelect) {
+ if (rssiDisplaySelect < 0 || rssiDisplaySelect > 1) return false;
+ this.rssiDisplaySelect = rssiDisplaySelect;
+ return true;
+ }
+
+ public boolean triggerReportingDefault = true, triggerReporting = triggerReportingDefault;
+ public short triggerReportingCountSettingDefault = 1, triggerReportingCountSetting = triggerReportingCountSettingDefault;
+ public boolean inventoryBeepDefault = true, inventoryBeep = inventoryBeepDefault;
+ public int beepCountSettingDefault = 8, beepCountSetting = beepCountSettingDefault;
+ public boolean inventoryVibrateDefault = false, inventoryVibrate = inventoryVibrateDefault;
+ public int vibrateTimeSettingDefault = 300, vibrateTimeSetting = vibrateTimeSettingDefault;
+ public int vibrateModeSelectDefault = 1, vibrateModeSelect = vibrateModeSelectDefault;
+ public int vibrateWindowSettingDefault = 2, vibrateWindowSetting = vibrateWindowSettingDefault;
+
+ public int savingFormatSelectDefault = 0, savingFormatSelect = savingFormatSelectDefault;
+ public int csvColumnSelectDefault = 0, csvColumnSelect = csvColumnSelectDefault;
+ public boolean saveFileEnableDefault = true, saveFileEnable = saveFileEnableDefault;
+ public boolean saveCloudEnableDefault = false, saveCloudEnable = saveCloudEnableDefault;
+ public boolean saveNewCloudEnableDefault = false, saveNewCloudEnable = saveNewCloudEnableDefault;
+ public boolean saveAllCloudEnableDefault = false, saveAllCloudEnable = saveAllCloudEnableDefault;
+ public String serverLocationDefault = "", serverLocation = serverLocationDefault;
+ public int serverTimeoutDefault = 6, serverTimeout = serverTimeoutDefault;
+ //String serverImpinjLocationDefault = "https://h9tqczg9-7275.asse.devtunnels.ms", serverImpinjLocation = serverImpinjLocationDefault;
+
+ public String serverMqttLocationDefault = "", serverMqttLocation = serverMqttLocationDefault;
+ public String topicMqttDefault = "", topicMqtt = topicMqttDefault;
+ public int inventoryCloudSaveDefault = 0, inventoryCloudSave = inventoryCloudSaveDefault;
+ public String serverImpinjLocationDefault = "https://democloud.convergence.com.hk/ias", serverImpinjLocation = serverImpinjLocationDefault;
+ //String serverImpinjNameDefault = "wallace.sit@cne.com.hk", serverImpinjName = serverImpinjNameDefault;
+ public String serverImpinjNameDefault = "", serverImpinjName = serverImpinjNameDefault;
+ //String serverImpinjPasswordDefault = "Cne12345678?", serverImpinjPassword = serverImpinjPasswordDefault;
+ public String serverImpinjPasswordDefault = "", serverImpinjPassword = serverImpinjPasswordDefault;
+
+ public int iForegroundDupElimDefault = 1, iForegroundDupElim = iForegroundDupElimDefault;
+
+ public boolean barcode2TriggerModeDefault = true, barcode2TriggerMode = barcode2TriggerModeDefault;
+
+ public boolean userDebugEnableDefault = false, userDebugEnable = userDebugEnableDefault;
+
+ //Filter
+ public static class PreFilterData {
+ public boolean enable; public int target;
+ public int action;
+ public int bank;
+ public int offset; public String mask; public boolean maskbit;
+ public PreFilterData() { }
+ public PreFilterData(boolean enable, int target, int action, int bank, int offset, String mask, boolean maskbit) {
+ this.enable = enable;
+ this.target = target;
+ this.action = action;
+ this.bank = bank;
+ this.offset = offset;
+ this.mask = mask;
+ this.maskbit = maskbit;
+ }
+ }
+ public PreFilterData preFilterData;
+
+ public File fileSetting;
+ boolean loadSettingFile(String stringMacAddress, String strlibraryVersion, boolean bChannelHoppingStatus, int iCurrentProfile) {
+ boolean DEBUG = true;
+ appendToLog("SettingData.loadSettingFile:"
+ + "\nstringMacAddress = " + stringMacAddress
+ + "\nstrlibraryVersion = " + strlibraryVersion
+ + "\nbChannelHoppingStatus = " + bChannelHoppingStatus
+ + "\niCurrentProfile = " + iCurrentProfile);
+
+ File path = context.getFilesDir();
+ String fileName = stringMacAddress; //bluetoothGatt.getmBluetoothDevice().getAddress(); //stringMacAddress
+
+ fileName = "csReaderA_" + fileName.replaceAll(":", "").replaceAll(" ", "");
+ fileSetting = new File(path, fileName);
+ boolean bNeedDefault = true;
+ if (DEBUG_FILE) utility.appendToLogView("FileName = " + fileName + ".exits = " + fileSetting.exists() + ", with beepEnable = " + inventoryBeep);
+ if (fileSetting.exists()) {
+ InputStream instream = null;
+ try {
+ instream = new FileInputStream(fileSetting);
+ } catch (Exception ex) {
+ //
+ }
+ if (instream != null) {
+ InputStreamReader inputStreamReader = new InputStreamReader(instream);
+ BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
+ String line;
+ int queryTarget = -1; int querySession = -1; int querySelect = -1;
+ int startQValue = -1; int maxQValue = -1; int minQValue = -1; int retryCount = -1;
+ int fixedQValue = -1; int fixedRetryCount = -1;
+ int population = -1;
+ boolean invAlgo = true; int retry = -1;
+ preFilterData = new SettingData.PreFilterData();
+ while(true) {
+ line = null;
+ try {
+ line = bufferedReader.readLine();
+ } catch (Exception ex) {
+ //
+ }
+ if (line == null) break;
+ if (DEBUG_FILE || true) appendToLog("FileA Data read = " + line);
+ String[] dataArray = line.split(",");
+ if (dataArray.length == 2) {
+ if (dataArray[0].matches("appVersion")) {
+ appendToLog("datArray[1] = " + dataArray[1] + ", strlibraryVersion = " + strlibraryVersion);
+ if (dataArray[1].matches(strlibraryVersion)) bNeedDefault = false;
+ } else if (bNeedDefault == true) {
+ } else if (dataArray[0].matches("countryInList")) {
+ csReaderConnector.rfidReader.getRegionList(); //getRegionList();
+ int countryInListNew = Integer.valueOf(dataArray[1]);
+ if (csReaderConnector.rfidReader.countryInList != countryInListNew && countryInListNew >= 0) csReaderConnector.rfidReader.setCountryInList(countryInListNew);
+ csReaderConnector.rfidReader.channelOrderType = -1;
+ } else if (dataArray[0].matches("channel")) {
+ int channelNew = Integer.valueOf(dataArray[1]);
+ if (bChannelHoppingStatus == false && channelNew >= 0) csReaderConnector.rfidReader.setChannel(channelNew);
+ } else if (dataArray[0].matches("antennaPower")) {
+ long lValue = Long.valueOf(dataArray[1]);
+ if (lValue >= 0) csReaderConnector.rfidReader.setPowerLevel(lValue);
+ } else if (dataArray[0].matches("antennaDwell")) {
+ long lValue = Long.valueOf(dataArray[1]);
+ if (lValue >= 0) {
+ csReaderConnector.rfidReader.setAntennaDwell(lValue);
+ }
+ } else if (dataArray[0].matches("population")) {
+ population = Integer.valueOf(dataArray[1]);
+ } else if (dataArray[0].matches("querySession")) {
+ int iValue = Integer.valueOf(dataArray[1]);
+ if (iValue >= 0) querySession = iValue;
+ } else if (dataArray[0].matches("queryTarget")) {
+ queryTarget = Integer.valueOf(dataArray[1]);
+ } else if (dataArray[0].matches("tagFocus")) {
+ int iValue = Integer.valueOf(dataArray[1]);
+ if (iValue >= 0) csReaderConnector.rfidReader.tagFocus = iValue;
+ } else if (dataArray[0].matches("fastId")) {
+ int iValue = Integer.valueOf(dataArray[1]);
+ if (iValue >= 0) csReaderConnector.rfidReader.fastId = iValue;
+ } else if (dataArray[0].matches("invAlgo")) {
+ invAlgo = dataArray[1].matches("true") ? true : false;
+ } else if (dataArray[0].matches("retry")) {
+ retry = Integer.valueOf(dataArray[1]);
+ } else if (dataArray[0].matches("currentProfile")) {
+ int iValue = Integer.valueOf(dataArray[1]);
+ appendToLog("SettingData.loadSettingFile setCurrentLinkProfile as " + iValue);
+ if (iValue >= 0) csReaderConnector.rfidReader.setCurrentLinkProfile(iValue);
+ } else if (dataArray[0].matches("rxGain")) {
+ csReaderConnector.rfidReader.setRxGain(Integer.valueOf(dataArray[1]));
+ } else if (dataArray[0].matches("deviceName")) {
+ csReaderConnector.bluetoothConnector.deviceName = dataArray[1].getBytes();
+ } else if (dataArray[0].matches("batteryDisplay")) {
+ setBatteryDisplaySetting(Integer.valueOf(dataArray[1]));
+ } else if (dataArray[0].matches("rssiDisplay")) {
+ setRssiDisplaySetting(Integer.valueOf(dataArray[1]));
+ } else if (dataArray[0].matches("tagDelay")) {
+ csReaderConnector.rfidReader.setTagDelay(Byte.valueOf(dataArray[1]));
+ } else if (dataArray[0].matches("cycleDelay")) {
+ csReaderConnector.rfidReader.setCycleDelay(Long.valueOf(dataArray[1]));
+ } else if (dataArray[0].matches("intraPkDelay")) {
+ csReaderConnector.rfidReader.setIntraPkDelay(Byte.valueOf(dataArray[1]));
+ } else if (dataArray[0].matches("dupDelay")) {
+ csReaderConnector.rfidReader.setDupDelay(Byte.valueOf(dataArray[1]));
+
+ } else if (dataArray[0].matches(("triggerReporting"))) {
+ appendToLog("FileA: going to setTriggerReporting with notificationConnector as " + (notificationConnector == null ? "null" : "valid"));
+ notificationConnector.setTriggerReporting(dataArray[1].matches("true") ? true : false);
+ appendToLog("FileA: setTriggerReporting is done");
+ } else if (dataArray[0].matches(("triggerReportingCount"))) {
+ notificationConnector.setTriggerReportingCount(Short.valueOf(dataArray[1]));
+ } else if (dataArray[0].matches(("inventoryBeep"))) {
+ inventoryBeep = dataArray[1].matches("true") ? true : false; //setInventoryBeep(dataArray[1].matches("true") ? true : false);
+ } else if (dataArray[0].matches(("inventoryBeepCount"))) {
+ beepCountSetting = Integer.valueOf(dataArray[1]); //setBeepCount(Integer.valueOf(dataArray[1]));
+ } else if (dataArray[0].matches(("inventoryVibrate"))) {
+ inventoryVibrate = dataArray[1].matches("true") ? true : false; //setInventoryVibrate(dataArray[1].matches("true") ? true : false);
+ } else if (dataArray[0].matches(("inventoryVibrateTime"))) {
+ vibrateTimeSetting = Integer.valueOf(dataArray[1]); //setVibrateTime(Integer.valueOf(dataArray[1]));
+ } else if (dataArray[0].matches(("inventoryVibrateMode"))) {
+ vibrateModeSelect = Integer.valueOf(dataArray[1]); //setVibrateModeSetting(Integer.valueOf(dataArray[1]));
+ } else if (dataArray[0].matches(("savingFormat"))) {
+ savingFormatSelect = Integer.valueOf(dataArray[1]); //setSavingFormatSetting(Integer.valueOf(dataArray[1]));
+ } else if (dataArray[0].matches(("csvColumnSelect"))) {
+ csvColumnSelect = Integer.valueOf(dataArray[1]); //setCsvColumnSelectSetting(Integer.valueOf(dataArray[1]));
+ } else if (dataArray[0].matches(("inventoryVibrateWindow"))) {
+ vibrateWindowSetting = Integer.valueOf(dataArray[1]); //setVibrateWindow(Integer.valueOf(dataArray[1]));
+
+ } else if (dataArray[0].matches(("saveFileEnable"))) {
+ saveFileEnable = dataArray[1].matches("true") ? true : false;
+ } else if (dataArray[0].matches(("saveCloudEnable"))) {
+ saveCloudEnable = dataArray[1].matches("true") ? true : false;
+ } else if (dataArray[0].matches(("saveNewCloudEnable"))) {
+ saveNewCloudEnable = dataArray[1].matches("true") ? true : false;
+ } else if (dataArray[0].matches(("saveAllCloudEnable"))) {
+ saveAllCloudEnable = dataArray[1].matches("true") ? true : false;
+ } else if (dataArray[0].matches(("serverLocation"))) {
+ serverLocation = dataArray[1];
+ } else if (dataArray[0].matches("serverTimeout")) {
+ serverTimeout = Integer.valueOf(dataArray[1]);
+ } else if (dataArray[0].matches(("serverMqttLocation"))) {
+ serverMqttLocation = dataArray[1];
+ } else if (dataArray[0].matches(("topicMqtt"))) {
+ topicMqtt = dataArray[1];
+ } else if (dataArray[0].matches(("foregroundDupElim"))) {
+ iForegroundDupElim = Integer.valueOf(dataArray[1]);
+ } else if (dataArray[0].matches(("inventoryCloudSave"))) {
+ inventoryCloudSave = Integer.parseInt(dataArray[1]);
+ } else if (dataArray[0].matches(("serverImpinjLocation"))) {
+ serverImpinjLocation = dataArray[1];
+ } else if (dataArray[0].matches(("serverImpinjName"))) {
+ serverImpinjName = dataArray[1];
+ } else if (dataArray[0].matches(("serverImpinjPassword"))) {
+ serverImpinjPassword = dataArray[1];
+
+ } else if (dataArray[0].matches("barcode2TriggerMode")) {
+ if (dataArray[1].matches("true")) barcode2TriggerMode = true;
+ else barcode2TriggerMode = false;
+ } else if (dataArray[0].matches("preFilterData.enable")) {
+ if (dataArray[1].matches("true")) preFilterData.enable = true;
+ else preFilterData.enable = false;
+ } else if (dataArray[0].matches("preFilterData.target")) {
+ preFilterData.target = Integer.valueOf(dataArray[1]);
+ } else if (dataArray[0].matches("preFilterData.action")) {
+ preFilterData.action = Integer.valueOf(dataArray[1]);
+ } else if (dataArray[0].matches("preFilterData.bank")) {
+ preFilterData.bank = Integer.valueOf(dataArray[1]);
+ } else if (dataArray[0].matches("preFilterData.offset")) {
+ preFilterData.offset = Integer.valueOf(dataArray[1]);
+ } else if (dataArray[0].matches("preFilterData.mask")) {
+ preFilterData.mask = dataArray[1];
+ } else if (dataArray[0].matches("preFilterData.maskbit")) {
+ if (dataArray[1].matches("true")) preFilterData.maskbit = true;
+ else preFilterData.maskbit = false;
+ } else if (dataArray[0].matches(("userDebugEnable"))) {
+ userDebugEnable = dataArray[1].matches("true") ? true : false;
+ }
+ }
+ }
+ csReaderConnector.rfidReader.setInvAlgo(invAlgo);
+ csReaderConnector.rfidReader.setPopulation(population);
+ csReaderConnector.rfidReader.setRetryCount(retry);
+ csReaderConnector.rfidReader.setTagGroup(querySelect, querySession, queryTarget);
+ csReaderConnector.rfidReader.setTagFocus(csReaderConnector.rfidReader.tagFocus > 0 ? true : false);
+ if (preFilterData != null && preFilterData.enable) {
+ if (utility.DEBUG_SELECT) appendToLog("Debug_Select: SettingData.loadingSettingFile. preFilterData is valid. Going to setSelectCriteria");
+ appendToLog("BtDataOut BBB 5");
+ csReaderConnector.rfidReader.setSelectCriteria(0, preFilterData.enable, preFilterData.target, preFilterData.action, preFilterData.bank, preFilterData.offset, preFilterData.mask, preFilterData.maskbit);
+ } else {
+ if (utility.DEBUG_SELECT) appendToLog("Debug_Select: SettingData.loadingSettingFile. preFilterData is null or disabled. Going to setSelectCriteriaDisable");
+ csReaderConnector.rfidReader.setSelectCriteriaDisable(0);
+ }
+ }
+ try {
+ instream.close();
+ } catch (Exception ex) { }
+ if (DEBUG_FILE) appendToLog("Data is read from FILE.");
+ }
+ if (bNeedDefault) {
+ appendToLog("saveSetting2File default !!!");
+ csReaderConnector.rfidReader.setReaderDefault();
+ saveSetting2File(strlibraryVersion, bChannelHoppingStatus, iCurrentProfile);
+ }
+ return bNeedDefault;
+ }
+ public void saveSetting2File(String strLibraryVersion, boolean bChannelHoppingStatus, int iCurrentProfile) {
+ boolean DEBUG = false;
+ if (DEBUG) appendToLog("Start");
+ FileOutputStream stream;
+ try {
+ stream = new FileOutputStream(fileSetting);
+ write2FileStream(stream, "Start of data\n");
+
+ write2FileStream(stream, "appVersion," + strLibraryVersion + "\n");
+ write2FileStream(stream, "countryInList," + String.valueOf(csReaderConnector.rfidReader.countryInList + "\n"));
+ if (!bChannelHoppingStatus) write2FileStream(stream, "channel," + String.valueOf(channel + "\n"));
+
+ write2FileStream(stream, "antennaPower," + String.valueOf(csReaderConnector.rfidReader.getPwrlevel() + "\n"));
+ write2FileStream(stream, "antennaDwell," + String.valueOf(csReaderConnector.rfidReader.getAntennaDwell() + "\n"));
+ write2FileStream(stream, "population," + String.valueOf(csReaderConnector.rfidReader.getPopulation() +"\n"));
+ write2FileStream(stream, "querySession," + String.valueOf(csReaderConnector.rfidReader.getQuerySession() + "\n"));
+ write2FileStream(stream, "queryTarget," + String.valueOf(csReaderConnector.rfidReader.getQueryTarget() + "\n"));
+ write2FileStream(stream, "tagFocus," + String.valueOf(csReaderConnector.rfidReader.getTagFocus() + "\n"));
+ write2FileStream(stream, "fastId," + String.valueOf(csReaderConnector.rfidReader.getFastId() + "\n"));
+ write2FileStream(stream, "invAlgo," + String.valueOf(csReaderConnector.rfidReader.getInvAlgo() + "\n"));
+ write2FileStream(stream, "retry," + String.valueOf(csReaderConnector.rfidReader.getRetryCount() + "\n"));
+ int iValue = csReaderConnector.rfidReader.getCurrentProfile();
+ appendToLog("SettingData.saveSettingFile getCurrentProfile as " + iValue);
+ write2FileStream(stream, "currentProfile," + String.valueOf(iValue + "\n"));
+ write2FileStream(stream, "rxGain," + String.valueOf(csReaderConnector.rfidReader.getRxGain() + "\n"));
+
+ write2FileStream(stream, "deviceName," + csReaderConnector.bluetoothConnector.getBluetoothIcName() + "\n");
+ write2FileStream(stream, "batteryDisplay," + String.valueOf(batteryDisplaySelect + "\n"));
+ write2FileStream(stream, "rssiDisplay," + String.valueOf(rssiDisplaySelect + "\n"));
+ write2FileStream(stream, "tagDelay," + String.valueOf(csReaderConnector.rfidReader.getTagDelay() + "\n"));
+ write2FileStream(stream, "cycleDelay," + String.valueOf(csReaderConnector.rfidReader.getCycleDelay() + "\n"));
+ write2FileStream(stream, "intraPkDelay," + String.valueOf(csReaderConnector.rfidReader.getIntraPkDelay() + "\n"));
+ write2FileStream(stream, "dupDelay," + String.valueOf(csReaderConnector.rfidReader.getDupDelay() + "\n"));
+
+ write2FileStream(stream, "triggerReporting," + String.valueOf(notificationConnector.getTriggerReporting() + "\n"));
+ write2FileStream(stream, "triggerReportingCount," + String.valueOf(notificationConnector.getTriggerReportingCount() + "\n"));
+ write2FileStream(stream, "inventoryBeep," + String.valueOf(inventoryBeep + "\n"));
+ write2FileStream(stream, "inventoryBeepCount," + String.valueOf(beepCountSetting + "\n"));
+ write2FileStream(stream, "inventoryVibrate," + String.valueOf(inventoryVibrate + "\n"));
+ write2FileStream(stream, "inventoryVibrateTime," + String.valueOf(vibrateTimeSetting + "\n"));
+ write2FileStream(stream, "inventoryVibrateMode," + String.valueOf(vibrateModeSelect + "\n"));
+ write2FileStream(stream, "inventoryVibrateWindow," + String.valueOf(vibrateWindowSetting + "\n"));
+
+ write2FileStream(stream, "savingFormat," + String.valueOf(savingFormatSelect + "\n"));
+ write2FileStream(stream, "csvColumnSelect," + String.valueOf(csvColumnSelect + "\n"));
+ write2FileStream(stream, "saveFileEnable," + String.valueOf(saveFileEnable + "\n"));
+ write2FileStream(stream, "saveCloudEnable," + String.valueOf(saveCloudEnable + "\n"));
+ write2FileStream(stream, "saveNewCloudEnable," + String.valueOf(saveNewCloudEnable + "\n"));
+ write2FileStream(stream, "saveAllCloudEnable," + String.valueOf(saveAllCloudEnable + "\n"));
+ write2FileStream(stream, "serverLocation," + serverLocation + "\n");
+ write2FileStream(stream, "serverTimeout," + String.valueOf(serverTimeout + "\n"));
+ write2FileStream(stream, "serverMqttLocation," + serverMqttLocation + "\n");
+ write2FileStream(stream, "topicMqtt," + topicMqtt + "\n");
+ write2FileStream(stream, "foregroundDupElim," + String.valueOf(iForegroundDupElim + "\n"));
+ write2FileStream(stream, "inventoryCloudSave," + inventoryCloudSave + "\n");
+ write2FileStream(stream, "serverImpinjLocation," + serverImpinjLocation + "\n");
+ write2FileStream(stream, "serverImpinjName," + serverImpinjName + "\n");
+ write2FileStream(stream, "serverImpinjPassword," + serverImpinjPassword + "\n");
+ write2FileStream(stream, "barcode2TriggerMode," + String.valueOf(barcode2TriggerMode + "\n"));
+
+// write2FileStream(stream, "wedgePrefix," + getWedgePrefix() + "\n");
+// write2FileStream(stream, "wedgeSuffix," + getWedgeSuffix() + "\n");
+// write2FileStream(stream, "wedgeDelimiter," + String.valueOf(getWedgeDelimiter()) + "\n");
+
+ write2FileStream(stream, "userDebugEnable," + String.valueOf(userDebugEnable + "\n"));
+ if (preFilterData != null) {
+ write2FileStream(stream, "preFilterData.enable," + String.valueOf(preFilterData.enable + "\n"));
+ write2FileStream(stream, "preFilterData.target," + String.valueOf(preFilterData.target + "\n"));
+ write2FileStream(stream, "preFilterData.action," + String.valueOf(preFilterData.action + "\n"));
+ write2FileStream(stream, "preFilterData.bank," + String.valueOf(preFilterData.bank + "\n"));
+ write2FileStream(stream, "preFilterData.offset," + String.valueOf(preFilterData.offset + "\n"));
+ write2FileStream(stream, "preFilterData.mask," + String.valueOf(preFilterData.mask + "\n"));
+ write2FileStream(stream, "preFilterData.maskbit," + String.valueOf(preFilterData.maskbit + "\n"));
+ }
+
+ write2FileStream(stream, "End of data\n"); //.getBytes()); if (DEBUG) appendToLog("outData = " + outData);
+ stream.close();
+ } catch (Exception ex){
+ //
+ }
+ saveForegroundSetting2File();
+ }
+
+ public String strForegroundReaderDefault = "", strForegroundReader = strForegroundReaderDefault;
+ File fileForegroundSetting;
+ boolean loadForegroundSettingFile() {
+ File path = context.getFilesDir();
+ String fileName = "csReaderA_Foreground";
+ fileForegroundSetting = new File(path, fileName);
+ appendToLog("file0.exists = " + fileForegroundSetting.exists());
+ if (fileForegroundSetting.exists()) {
+ try {
+ InputStream instream = new FileInputStream(fileForegroundSetting);
+ appendToLog("file0.instream is " + (instream == null ? "null" : "valid"));
+ if (instream != null) {
+ InputStreamReader inputStreamReader = new InputStreamReader(instream);
+ BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
+ String line;
+ while ((line = bufferedReader.readLine()) != null) {
+ appendToLog("file0.line: " + line);
+ String[] dataArray = line.split(",");
+ if (dataArray.length == 2) {
+ if (dataArray[0].matches("foreground.reader")) {
+ appendToLog("foregroundReader: set 5");
+ strForegroundReader = dataArray[1];
+ appendToLog("file0.foreground.reader = " + strForegroundReader);
+ appendToLog("loaded strForegroundReader is " + this.strForegroundReader);
+ }
+ }
+ }
+ }
+ instream.close();
+ } catch (Exception ex) {
+ //
+ }
+ }
+ return true;
+ }
+ public void saveForegroundSetting2File() {
+ boolean DEBUG = false;
+ if (DEBUG) appendToLog("Start");
+
+ FileOutputStream stream;
+ try {
+ stream = new FileOutputStream(fileForegroundSetting);
+ write2FileStream(stream, "Start of File0 data\n");
+
+ write2FileStream(stream, "foreground.enable," + "true" + "\n");
+ appendToLog("strForegroundReader = " + strForegroundReader);
+ write2FileStream(stream, "foreground.reader," + strForegroundReader + "\n");
+ write2FileStream(stream, "End of File0 data\n");
+ stream.close();
+ } catch (Exception ex) {
+ //
+ }
+ }
+
+ public static String wedgeDeviceName;
+ public static String wedgeDeviceAddress;
+ public static int wedgeDeviceUUID2p1;
+ public String wedgePrefix = null, wedgeSuffix = null;
+ public int wedgeOutput = 0, wedgeDelimiter = 0x0a, wedgePower = 300;
+ public String fileNameWedgeSetting = "csReaderA_SimpleWedge";
+ void loadWedgeSettingFile() {
+ appendToLog("KKK: loadWedgeSettingFile starts");
+ File path = context.getFilesDir();
+ File file = new File(path, fileNameWedgeSetting);
+ boolean bNeedDefault = true, DEBUG = false;
+ appendToLog(fileNameWedgeSetting + "file.exists = " + file.exists());
+ if (file.exists()) {
+ int length = (int) file.length();
+ byte[] bytes = new byte[length];
+ try {
+ InputStream instream = new FileInputStream(file);
+ if (instream != null) {
+ InputStreamReader inputStreamReader = new InputStreamReader(instream);
+ BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
+ String line;
+ while ((line = bufferedReader.readLine()) != null) {
+ if (true) appendToLog("Data read = " + line);
+ String[] dataArray = line.split(",");
+ if (dataArray.length == 2) {
+ if (dataArray[0].matches("wedgeDeviceName")) {
+ wedgeDeviceName = dataArray[1];
+ } else if (dataArray[0].matches("wedgeDeviceAddress")) {
+ wedgeDeviceAddress = dataArray[1];
+ } else if (dataArray[0].matches("wedgeDeviceUUID2p1")) {
+ wedgeDeviceUUID2p1 = Integer.valueOf(dataArray[1]);
+ } else if (dataArray[0].matches("wedgePower")) {
+ wedgePower = Integer.valueOf(dataArray[1]);
+ } else if (dataArray[0].matches("wedgePrefix")) {
+ wedgePrefix = dataArray[1];
+ } else if (dataArray[0].matches("wedgeSuffix")) {
+ wedgeSuffix = dataArray[1];
+ } else if (dataArray[0].matches("wedgeDelimiter")) {
+ wedgeDelimiter = Integer.valueOf(dataArray[1]);
+ appendToLog("MainActivity, loadWedgeSettingFile: wedgeDelimiter = " + wedgeDelimiter);
+ } else if (dataArray[0].matches("wedgeOutput")) {
+ wedgeOutput = Integer.valueOf(dataArray[1]);
+ }
+ }
+ }
+ }
+ instream.close();
+ } catch (Exception ex) {
+ //
+ }
+ }
+ }
+ void saveWedgeSetting2File() {
+ appendToLog("KKK: saveWedgeSetting2File starts");
+ File path = context.getFilesDir();
+ File file = new File(path, fileNameWedgeSetting);
+ FileOutputStream stream;
+ try {
+ stream = new FileOutputStream(file);
+ write2FileStream(stream, "Start of data\n");
+ write2FileStream(stream, "wedgeDeviceName," + wedgeDeviceName + "\n");
+ write2FileStream(stream, "wedgeDeviceAddress," + wedgeDeviceAddress + "\n");
+ write2FileStream(stream, "wedgeDeviceUUID2p1," + String.valueOf(wedgeDeviceUUID2p1) + "\n");
+ write2FileStream(stream, "wedgePower," + wedgePower + "\n");
+ write2FileStream(stream, "wedgePrefix," + wedgePrefix + "\n");
+ write2FileStream(stream, "wedgeSuffix," + wedgeSuffix + "\n");
+ write2FileStream(stream, "wedgeDelimiter," + String.valueOf(wedgeDelimiter) + "\n"); appendToLog("SettingWedgeFragment, saveWedgeFragment: wedgeDelimiter = " + wedgeDelimiter);
+ write2FileStream(stream, "wedgeOutput," + String.valueOf(wedgeOutput) + "\n");
+ write2FileStream(stream, "End of data\n");
+ stream.close();
+ } catch (Exception ex){
+ //
+ }
+ }
+}
+
+
+
+package com.csl.cslibrary4a;
+
+import static android.content.Intent.parseUri;
+import static android.hardware.usb.UsbConstants.USB_DIR_IN;
+import static android.hardware.usb.UsbConstants.USB_DIR_OUT;
+import static android.hardware.usb.UsbConstants.USB_ENDPOINT_XFER_BULK;
+import static android.hardware.usb.UsbConstants.USB_ENDPOINT_XFER_INT;
+import static android.hardware.usb.UsbManager.ACTION_USB_DEVICE_ATTACHED;
+import static android.hardware.usb.UsbManager.ACTION_USB_DEVICE_DETACHED;
+
+import android.app.PendingIntent;
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
+import android.content.IntentFilter;
+import android.hardware.usb.UsbDevice;
+import android.hardware.usb.UsbDeviceConnection;
+import android.hardware.usb.UsbEndpoint;
+import android.hardware.usb.UsbInterface;
+import android.hardware.usb.UsbManager;
+import android.hardware.usb.UsbRequest;
+import android.os.Handler;
+import android.util.Log;
+import android.widget.TextView;
+import android.widget.Toast;
+
+import androidx.core.content.ContextCompat;
+
+import java.nio.ByteBuffer;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+
+class UsbConnector {
+ final boolean DEBUG = false;
+
+ CsReaderConnector csReaderConnector;
+ private Context context;
+ private TextView textView;
+ private int productId;
+ private int vendorId;
+ Utility utility;
+
+ final String ACTION_USB_PERMISSION = "com.csl.cs710ademoapp.USB_PERMISSION";
+ PendingIntent mPermissionIntent;
+
+ private UsbManager usbManager;
+ private UsbInterface usbInterface;
+ private UsbDeviceConnection usbDeviceConnection;
+ private UsbEndpoint usbEndpointOut, usbEndpointIn;
+ //private UsbEndpoint usbEndpoint4Write, usbEndpoint4Read;
+ private int packetSize;
+
+ private Handler mHandler = new Handler();
+ PendingIntent permissionIntent;
+
+ UsbConnector(CsReaderConnector csReaderConnector, Context context, TextView textView, int productId, int vendorId, Utility utility) {
+ this.csReaderConnector = csReaderConnector;
+ this.context = context;
+ this.textView = textView;
+ this.productId = productId;
+ this.vendorId = vendorId;
+ this.utility = utility;
+ appendToLog("UsbConnector.UsbConnector");
+
+ usbManager = (UsbManager) context.getSystemService(Context.USB_SERVICE);
+ appendToLog("UsbConnector.UsbConnector: done getSystemService with usbManager is " + (usbManager == null ? "null" : "valid"));
+
+ IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
+ filter.addAction(ACTION_USB_DEVICE_ATTACHED);
+ filter.addAction(ACTION_USB_DEVICE_DETACHED);
+ ContextCompat.registerReceiver(context, broadcastReceiver, filter, ContextCompat.RECEIVER_EXPORTED);
+ appendToLog("UsbConnector.UsbConnector: done registerReceiver");
+ }
+
+ HashMap usbDeviceHashMap;
+ private boolean scanning = false; boolean isBleScanning() { return scanning; }
+ void scanDevice(boolean enable) {
+ if (enable == false && isBleScanning() == false) return;
+
+ if (enable) {
+ if (true) {
+ Intent intent = new Intent();
+ UsbDevice usbDevice = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
+ appendToLog("UsbConnector.scanDevice: usbDevice is " + (usbDevice == null ? "null" : "valid"));
+ } //not working with the intent-filter, get only null intent
+ if (false) {
+ Intent intent = null;
+ try {
+ //intent = getIntent(UsbManager.EXTRA_DEVICE);
+ intent = parseUri(UsbManager.EXTRA_DEVICE, 0);
+ } catch (Exception ex) {
+ appendToLog("UsbConnector.scanDevice: getIntent exception " + ex.toString());
+ }
+ appendToLog("UsbConnector.scanDevice: intent is " + (intent == null ? "null" : "valid"));
+ if (intent != null) {
+ appendToLog("UsbConnector.scanDevice: intent.getAction is " + intent.getAction());
+ if (intent.getAction().equals(ACTION_USB_DEVICE_ATTACHED)) {
+ UsbDevice usbDevice = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
+ if (usbDevice != null) {
+ Log.d("onResume", "USB device attached: name: " + usbDevice.getDeviceName());
+ }
+ }
+ }
+ } //not working with the intent-filter, get only intent with action android.intent.action.VIEW
+
+ scanning = true;
+ Thread thread = new Thread(runnable);
+ thread.start();
+ } else scanning = false;
+ }
+
+ Runnable runnable = new Runnable() {
+ @Override
+ public void run() {
+ appendToLog("UsbConnector.runnable");
+
+ if (usbManager != null) {
+ usbDeviceHashMap = usbManager.getDeviceList();
+ appendToLog("UsbConnector.runnable: deviceList is " + (usbDeviceHashMap == null ? "null" : ("valid with size = " + usbDeviceHashMap.size())));
+ if (false) {
+ UsbDevice usbDevice = usbDeviceHashMap.get("/dev/bus/usb/001/004"); ///dev/bus/usb/001/002, 003
+ appendToLog("UsbConnector.runnable: usbDeviceHashMap.get[abc] is " + (usbDevice == null ? "null" : "valid"));
+ } //alternative method to get usbDevice, but the device name is changing when plugging
+ if (false) {
+ Iterator deviceIterator = usbDeviceHashMap.values().iterator();
+ appendToLog("UsbConnector.getUsbDeviceList: deviceIterator is " + (deviceIterator == null ? "null" : "valid"));
+ while (deviceIterator.hasNext()) {
+ UsbDevice device = deviceIterator.next();
+ }
+ } //alternative method to get usbDevice
+ for (UsbDevice device : usbDeviceHashMap.values()) {
+ if (!usbManager.hasPermission(device)) {
+ permissionIntent = PendingIntent.getBroadcast(context, 0, new Intent(ACTION_USB_PERMISSION), PendingIntent.FLAG_IMMUTABLE);
+ usbManager.requestPermission(device, permissionIntent);
+ break;
+ }
+ appendToLog("UsbConnector.runnable: device.getDeviceName = " + device.getDeviceName());
+ appendToLog("UsbConnector.runnable: device.getVendorId = " + device.getVendorId());
+ appendToLog("UsbConnector.runnable: device.getManufacturerName = " + device.getManufacturerName()); //null
+ appendToLog("UsbConnector.runnable: device.getProductName = " + device.getProductName()); //null
+ appendToLog("UsbConnector.runnable: device.getProductId = " + device.getProductId());
+ appendToLog("UsbConnector.runnable: device.getDeviceId = " + device.getDeviceId());
+ appendToLog("UsbConnector.runnable: device.getVersion = " + device.getVersion());
+ //appendToLog("UsbConnector.runnable: device.getSerialNumber = " + device.getSerialNumber()); //exceptioin
+ BluetoothGatt.CsScanData scanResultA = new BluetoothGatt.CsScanData(null, 0, null);
+ scanResultA.address = String.valueOf(device.getVendorId())
+ + " " + String.valueOf(device.getProductId())
+ + " " + String.valueOf(device.getDeviceId());
+ switch (device.getVendorId()) {
+ case 1003: //Atmel
+ scanResultA.name = "CS701 USB HID";
+ scanResultA.serviceUUID2p2 = 3;
+ break;
+ case 4292: //Silicon Laboratory
+ scanResultA.name = "CS108 USB HID";
+ scanResultA.serviceUUID2p2 = 1;
+ break;
+ }
+ appendToLog("UsbConnector.runnable: scanResultA.name is " + scanResultA.name);
+
+ if (csReaderConnector.mScanResultList != null) {
+ csReaderConnector.mScanResultList.add(scanResultA);
+ appendToLog("UsbConnector.runnable: scanResultA.getAddress is " + csReaderConnector.mScanResultList.get(0).getAddress());
+ }
+ }
+ }
+ scanning = false;
+ }
+ };
+
+ boolean usbConnectionState = false;
+ boolean connect(ReaderDevice readerDevice) {
+ boolean DEBUG = true;
+ if (DEBUG) appendToLog("UsbConnector.connect: " + (readerDevice == null ? "null" : "valid") + " readerDevice");
+ if (readerDevice == null) {
+ if (DEBUG) appendToLog("UsbConnector.connect: NULL readerDevice");
+ } else {
+ String address = readerDevice.getAddress();
+ if (DEBUG) appendToLog("UsbConnector.connect: readerDevice.address is " + address);
+ String[] stringsAddress = address.split(" ");
+ if (stringsAddress.length != 3) {
+ if (DEBUG) appendToLog("UsbConnector.connect: stringsAddress does not have 3 parts");
+ } else {
+ int iDeviceIdExpected = Integer.parseInt(stringsAddress[stringsAddress.length - 1]);
+ if (DEBUG) appendToLog("UsbConnector.connect: stringDeviceIdExpected = " + iDeviceIdExpected);
+
+ if (DEBUG) appendToLog("UsbConnector.connect: " + (usbManager == null ? "null": "valid") + " usbManager, "
+ + (usbDeviceHashMap == null ? "null" : "valid") + " usbDeviceHashMap");
+ if (usbManager == null) {
+ if (DEBUG) appendToLog("UsbConnector.connect: NULL mUsbManager");
+ } else if (usbDeviceHashMap == null) {
+ if (DEBUG) appendToLog("UsbConnector.connect: NULL usbDeviceHashMap");
+ } else {
+ boolean bValid = false;
+ if (DEBUG) appendToLog("UsbConnector.connect: usbDeviceHashMap.size = " + usbDeviceHashMap.size());
+ for (UsbDevice device : usbDeviceHashMap.values()) {
+ if (device == null) {
+ if (DEBUG) appendToLog("UsbConnector.connect: null usbDevice");
+ } else if (device.getDeviceId() == iDeviceIdExpected) {
+ if (DEBUG) appendToLog("UsbConnector.connect: found the corresponding usbDevice");
+
+ usbInterface = null;
+ int usbInterfaceCount = device.getInterfaceCount();
+ if (DEBUG) appendToLog("UsbConnector.connect: usbInterfaceCount = " + usbInterfaceCount);
+ for (int i = 0; i < usbInterfaceCount; i++) {
+ UsbInterface usbInterface1 = device.getInterface(i);
+ if (DEBUG) appendToLog("UsbConnector.connect: usbInterface[" + i + "] is "+ (usbInterface1 == null ? "null" : "valid"));
+ usbInterface = usbInterface1;
+ }
+
+ usbEndpointOut = null;
+ if (usbInterface == null) {
+ if (DEBUG) appendToLog("UsbConnector.connect: null usbInterface");
+ } else {
+ int usbEndpointCount = usbInterface.getEndpointCount();
+ if (DEBUG) appendToLog("UsbConnector.connect: usbEndpointCount = " + usbEndpointCount);
+ for (int i = 0; i < usbEndpointCount; i++) {
+ UsbEndpoint usbEndpoint1 = usbInterface.getEndpoint(i);
+ appendToLog("UsbConnector.connect: " + (usbEndpoint1 == null ? "null" : "valid") + " usbInterface[" + i
+ + "], type = " + usbEndpoint1.getType()
+ + ", direction = " + usbEndpoint1.getDirection());
+ if (usbEndpoint1.getDirection() == USB_DIR_OUT) {
+ appendToLog("UsbConnector.connect: found output endpoint with MaxPacketSize = " + usbEndpoint1.getMaxPacketSize());
+ usbEndpointOut = usbEndpoint1;
+ } else if (usbEndpoint1.getDirection() == USB_DIR_IN) {
+ appendToLog("UsbConnector.connect: found input endpoint with MaxPacketSize = " + usbEndpoint1.getMaxPacketSize());
+ usbEndpointIn = usbEndpoint1;
+ }
+ }
+ }
+
+ usbDeviceConnection = null;
+ if (usbInterface == null || usbEndpointOut == null) {
+ if (DEBUG) appendToLog("UsbConnector.connect: null usbInterface or usbEndpointOut");
+ } else {
+ usbDeviceConnection = usbManager.openDevice(device);
+ if (DEBUG) appendToLog("UsbConnector.connect: usbDeviceConnection is " + (usbDeviceConnection == null ? "null" : "valid"));
+ usbDeviceConnection.claimInterface(usbInterface, true);
+ if (DEBUG) appendToLog("UsbConnector.connect: done claimInterface");
+ }
+ bValid = true;
+ }
+ }
+
+ if (bValid) {
+ usbConnectionState = true;
+ mConnectedTimeMillis = System.currentTimeMillis();
+ boolean validPreviousConnect = false;
+ boolean needNewConnect = true;
+ if (isConnected()) validPreviousConnect = true;
+ /*
+ if (validPreviousConnect) {
+ // if (mBluetoothDevice.getAddress().matches(name)) {
+ needNewConnect = false;
+ // } else {
+ // disconnect(true);
+ // }
+ }
+ if (needNewConnect) {
+ HashMap deviceList = usbManager.getDeviceList();
+ Iterator deviceIterator = deviceList.values().iterator();
+ while (deviceIterator.hasNext()) {
+ UsbDevice device = deviceIterator.next();
+ if (device.getProductId() == productId && device.getVendorId() == vendorId && device.getDeviceName().contains(readerDevice.getName())) {
+ _usbDevice = device;
+ if (DEBUG) appendToLog("UsbConnector: connectBle(" + name + "): connectBle starts");
+
+ usbManager.requestPermission(_usbDevice, mPermissionIntent);
+ if (DEBUG) appendToLog("UsbConnector: UsbConnector().connectBle(): AAA");
+
+ connectRequested = true;
+ return true;
+ }
+ }
+ }
+ if (validPreviousConnect == false) {
+ if (DEBUG) appendToLog("UsbConnector: connectBle(" + name + "): connectBle FAIL");
+ // } else if (mBluetoothGatt.connectBle()) {
+ // appendToLog("UsbConnector: connectBle(" + name + "): re-connectBle starts");
+ // return true;
+ // } else {
+ // appendToLog("UsbConnector: connectBle(" + name + "): re-connectBle FAIL");
+ }
+ */
+ }
+ }
+ }
+ }
+ return false;
+ }
+
+ boolean connectRequested = false;
+ boolean isConnected() {
+ return usbConnectionState;
+/*
+ boolean DEBUG = true;
+ if (DEBUG) appendToLog("UsbConnector.isConnected: usbManger is " + (usbManager == null ? "null" : "valid")
+ + "usbDevice is " + (usbDevice == null ? "null" : "valid")
+ + "connectRequested is " + connectRequested);
+ if (usbManager == null || usbDevice == null || connectRequested == false) return false;
+ if (DEBUG) appendToLog("UsbConnector.isConnected: usbManager.hasPermission is " + usbManager.hasPermission(usbDevice));
+ if (!usbManager.hasPermission(usbDevice)) return false;
+ if (DEBUG) appendToLog("UsbConnector.isConnected: usbDeviceConnection is " + (usbDeviceConnection == null ? "null" : "valid"));
+ if (usbDeviceConnection == null) return false;
+ if (DEBUG) appendToLog("UsbConnector.isConnected: connected");
+// appendToLog("UsbConnector: g ");
+ return true;
+*/
+ }
+
+ private final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
+ public void onReceive(Context context, Intent intent) {
+ String action = intent.getAction();
+ appendToLog("UsbConnector.broadcastReceiver.onReceive: intent.getAction = " + action);
+ //appendToLog("UsbConnector.broadcastReceiver.onReceive: intent.getBooleanExtra = " + intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)); //getBooleanExtra is always default value
+ UsbDevice usbDevice = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
+ appendToLog("UsbConnector.broadcastReceiver.onReceive: got usbDevice is " + (usbDevice == null ? "null" : ("with deviceId as " + usbDevice.getDeviceId())));
+ if (action.equals(ACTION_USB_PERMISSION)) { //got usbDevice is null
+ appendToLog("UsbConnector.broadcastReceiver.onReceive: ACTION_USB_PERMISSION");
+ //setDevice(context, intent);
+ } else if (action.equals(ACTION_USB_DEVICE_ATTACHED)) {
+ appendToLog("UsbConnector.broadcastReceiver.onReceive: ACTION_USB_DEVICE_ATTACHED");
+ } else if (action.equals(ACTION_USB_DEVICE_DETACHED)) {
+ appendToLog("UsbConnector.broadcastReceiver.onReceive: ACTION_USB_DEVICE_DETACHED");
+ if (usbDevice != null) {
+ if (usbDeviceConnection != null) {
+ appendToLog("UsbConnector.broadcastReceiver.onReceive: going to releaseInterface and close usbDeviceConnection");
+ usbDeviceConnection.releaseInterface(usbInterface);
+ usbDeviceConnection.close();
+ }
+ // call your method that cleans up and closes communication with the device
+ }
+ }
+ }
+
+ private void setDevice(Context context, Intent intent) {
+ appendToLog("UsbConnector.usbReceiver.setDevice");
+ UsbDevice device = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
+ if (device == null) {
+ Toast.makeText(context, "Permission request with NULL DEVICE.", Toast.LENGTH_SHORT).show();
+ } else if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false) == false) {
+ //Log.d("TAG", "permission denied for the device " + device);
+ Toast.makeText(context, "Permission is REJECTED.", Toast.LENGTH_SHORT).show();
+ } else {
+ Toast.makeText(context, "Permission is Granted.", Toast.LENGTH_SHORT).show();
+ makeConnection();
+ }
+ }
+ };
+
+ boolean usbDataSending = false;
+ byte[] dataOutPending = null;
+ boolean writeStreamOut(byte[] dataOutRaw) {
+ boolean DEBUG = true;
+
+ appendToLog("UsbConnector.writeStreamOut, UsbConnector.waitStreamInOut.Runnable: raw dataOut " + byteArrayToString(dataOutRaw) + ", dataOutPending as " + (dataOutPending == null ? "null" : "valid"));
+ dataOutRaw[1] = (byte)0xE6;
+
+ dataOutPending = new byte[dataOutRaw.length + 2];
+ dataOutPending[0] = 2;
+ dataOutPending[1] = (byte) dataOutRaw.length;
+ System.arraycopy(dataOutRaw, 0, dataOutPending, 2, dataOutRaw.length);
+ appendToLog("UsbConnector.writeStreamOut, UsbData: processed value: " + byteArrayToString(dataOutPending));
+
+ if (true) waitStreamInOut();
+ else {
+ Thread thread = new Thread(new Runnable() {
+ @Override
+ public void run() {
+ if (DEBUG)
+ appendToLog("UsbConnector.writeStreamOut.Runnable: " + (usbDeviceConnection == null ? "null" : "valid") + " usbDeviceConnection, "
+ + (usbEndpointOut == null ? "null" : "valid") + " usbEndpointOut, "
+ + (usbEndpointIn == null ? "null" : "valid") + " usbEndpointIn");
+ if (usbEndpointOut.getType() == USB_ENDPOINT_XFER_BULK) { //for sending, okay to use following even if endpoint type is INT
+ if (DEBUG)
+ appendToLog("UsbConnector.writeStreamOut.Runnable: going to do bulkTransfer with dataOut as " + byteArrayToString(dataOutPending));
+ int iLength = usbDeviceConnection.bulkTransfer(usbEndpointOut, dataOutPending, dataOutPending.length, 0);
+ if (DEBUG)
+ appendToLog("UsbConnector.writeStreamOut.Runnable: done bulkTransfer with length = " + iLength);
+ } else if (usbEndpointOut.getType() == USB_ENDPOINT_XFER_INT) {
+ if (DEBUG)
+ appendToLog("UsbConnector.writeStreamOut.Runnable: going to do interrrupt transfer with dataOut as " + byteArrayToString(dataOutPending));
+ if (dataOutPending.length > usbEndpointOut.getMaxPacketSize())
+ appendToLog("UsbConnector.writeStreamOut.Runnable: cannot transfer as dataOut length is greater than MaxPacketSize " + usbEndpointOut.getMaxPacketSize());
+ else {
+ int bufferDataLength = dataOutPending.length;
+ ByteBuffer buffer = ByteBuffer.allocate(bufferDataLength + 1);
+ UsbRequest usbRequest = new UsbRequest();
+ buffer.put(dataOutPending);
+ if (DEBUG)
+ appendToLog("UsbConnector.writeStreamOut.Runnable: going to usbRequest.queue with position = " + buffer.position());
+
+ usbDataSending = true;
+ usbRequest.initialize(usbDeviceConnection, usbEndpointOut);
+ usbRequest.queue(buffer, bufferDataLength);
+ try {
+ boolean bEqual = usbRequest.equals(usbDeviceConnection.requestWait());
+ if (DEBUG)
+ appendToLog("UsbConnector.writeStreamOut.Runnable: done transfer with usbRequest.equals[usbDeviceConnection.requestWait] is " + bEqual + ", position = " + buffer.position());
+ } catch (Exception ex) {
+ appendToLog("UsbConnector.writeStreamOut.Runnable: requestWait exception as " + ex.toString());
+ }
+ usbDataSending = false;
+ }
+ } else {
+ if (DEBUG)
+ appendToLog("UsbConnector.writeStreamOut.Runnable: cannot handle as usbEndpointOut type is " + usbEndpointOut.getType());
+ }
+
+ if (DEBUG)
+ appendToLog("UsbConnector.writeStreamOut.Runnable: going to do threadStreamIn.start");
+ waitStreamInOut();
+ }
+ });
+ thread.start();
+ }
+
+ return true;
+ }
+
+ private boolean disableUSBThread = false;
+ public void waitStreamInOut() {
+ if (!disableUSBThread) {
+ disableUSBThread = true;
+ appendToLog("UsbConnector.waitStreamInOut, UsbData: starts");
+ Thread thread = new Thread(new Runnable() {
+ boolean DEBUG = true;
+ byte[] dataIn = new byte[16];
+
+ @Override
+ public void run() {
+ appendToLog("UsbConnector.waitStreamInOut.Runnable, UsbData: starts");
+ while (true) {
+ appendToLog("UsbConnector.waitStreamInOut.Runnable: dataOutPending is " + (dataOutPending == null ? "null" : "valid"));
+ if (dataOutPending != null) {
+ if (DEBUG)
+ appendToLog("UsbConnector.waitStreamInOut.Runnable: " + (usbDeviceConnection == null ? "null" : "valid") + " usbDeviceConnection, "
+ + (usbEndpointOut == null ? "null" : "valid") + " usbEndpointOut, "
+ + (usbEndpointIn == null ? "null" : "valid") + " usbEndpointIn");
+ if (usbEndpointOut.getType() == USB_ENDPOINT_XFER_BULK) { //for sending, okay to use following even if endpoint type is INT
+ if (DEBUG)
+ appendToLog("UsbConnector.waitStreamInOut.Runnable: going to do bulkTransfer with dataOut as " + byteArrayToString(dataOutPending));
+ int iLength = usbDeviceConnection.bulkTransfer(usbEndpointOut, dataOutPending, dataOutPending.length, 0);
+ if (DEBUG)
+ appendToLog("UsbConnector.waitStreamInOut.Runnable: done bulkTransfer with length = " + iLength);
+ } else if (usbEndpointOut.getType() == USB_ENDPOINT_XFER_INT) {
+ if (DEBUG)
+ appendToLog("UsbConnector.waitStreamInOut.Runnable: going to do interrrupt transfer with dataOut as " + byteArrayToString(dataOutPending));
+ if (dataOutPending.length > usbEndpointOut.getMaxPacketSize())
+ appendToLog("UsbConnector.waitStreamInOut.Runnable: cannot transfer as dataOut length is greater than MaxPacketSize " + usbEndpointOut.getMaxPacketSize());
+ else {
+ int bufferDataLength = dataOutPending.length;
+ ByteBuffer buffer = ByteBuffer.allocate(bufferDataLength + 1);
+ UsbRequest usbRequest = new UsbRequest();
+ buffer.put(dataOutPending);
+ if (DEBUG)
+ appendToLog("UsbConnector.waitStreamInOut.Runnable: going to usbRequest.queue with position = " + buffer.position());
+
+ usbDataSending = true;
+ usbRequest.initialize(usbDeviceConnection, usbEndpointOut);
+ usbRequest.queue(buffer, bufferDataLength);
+ try {
+ boolean bEqual = usbRequest.equals(usbDeviceConnection.requestWait());
+ if (DEBUG)
+ appendToLog("UsbConnector.waitStreamInOut.Runnable: done transfer with usbRequest.equals[usbDeviceConnection.requestWait] is " + bEqual + ", position = " + buffer.position());
+ Thread.sleep(100);
+ } catch (Exception ex) {
+ appendToLog("UsbConnector.waitStreamInOut.Runnable: requestWait exception as " + ex.toString());
+ }
+ usbDataSending = false;
+ }
+ } else if (DEBUG) appendToLog("UsbConnector.waitStreamInOut.Runnable: cannot handle as usbEndpointOut type is " + usbEndpointOut.getType());
+ dataOutPending = null;
+ } else {
+ if (usbEndpointIn.getType() == USB_ENDPOINT_XFER_BULK) {
+ if (DEBUG)
+ appendToLog("UsbConnector.waitStreamInOut.Runnable: going to do bulkTransfer to dataIn");
+ int iLength = usbDeviceConnection.bulkTransfer(usbEndpointIn, dataIn, dataIn.length, 0);
+ if (DEBUG)
+ appendToLog("UsbConnector.waitStreamInOut.Runnable: done bulkTransfer to usbEndpointIn with length = " + iLength);
+ if (DEBUG)
+ appendToLog("UsbConnector.waitStreamInOut.Runnable: buffer received is " + byteArrayToString(dataIn));
+
+ } else if (usbEndpointIn.getType() == USB_ENDPOINT_XFER_INT) { //for receiving, must use following if endpoint type is INT
+ if (DEBUG)
+ appendToLog("UsbConnector.waitStreamInOut.Runnable, UsbData: going to do interrupt transfer to dataIn");
+ int bufferDataLength = usbEndpointIn.getMaxPacketSize();
+ ByteBuffer buffer = ByteBuffer.allocate(bufferDataLength + 1);
+ UsbRequest usbRequest = new UsbRequest();
+ if (DEBUG)
+ appendToLog("UsbConnector.waitStreamInOut.Runnable, UsbData: going to usbRequest.queue with position = " + buffer.position());
+ usbRequest.initialize(usbDeviceConnection, usbEndpointIn);
+ usbRequest.queue(buffer, bufferDataLength);
+ try {
+ boolean bEqual = usbRequest.equals(usbDeviceConnection.requestWait(50));
+ if (DEBUG)
+ appendToLog("UsbConnector.waitStreamInOut.Runnable, UsbData: done transfer with usbRequest.equals[usbDeviceConnection.requestWait] is " + bEqual + ", position = " + buffer.position());
+ byte[] dataInRaw = buffer.array();
+ if (DEBUG && dataInRaw[0] != 0)
+ appendToLog("UsbConnector.waitStreamInOut.Runnable, UsbData: buffer received is " + byteArrayToString(dataInRaw));
+
+ if (bEqual && (buffer.position() > 0) && (dataInRaw[0] == 1) && (dataInRaw.length > (dataInRaw[1] + 2))) {
+ dataIn = new byte[dataInRaw[1]];
+ System.arraycopy(dataInRaw, 2, dataIn, 0, dataIn.length);
+ if (DEBUG || true)
+ appendToLog("UsbConnector.waitStreamInOut.Runnable, UsbData: dataIn " + dataIn.length + " is " + byteArrayToString(dataIn));
+ synchronized (arrayListStreamIn) {
+ //arrayListStreamIn.add(dataIn);
+ streamInBufferPush(dataIn, 0, dataIn.length);
+ streamInBufferSize += dataIn.length;
+ if (DEBUG)
+ appendToLog("UsbConnector.waitStreamInOut.Runnable: done streamInBufferPush with streamInRequest as " + streamInRequest);
+ if (streamInRequest == false) {
+ streamInRequest = true;
+ if (DEBUG)
+ appendToLog("UsbConnector.waitStreamInOut.Runnable: going to do runnableProcessStreamInData");
+ mHandler.removeCallbacks(runnableProcessStreamInData);
+ mHandler.post(runnableProcessStreamInData);
+ if (DEBUG)
+ appendToLog("UsbConnector.waitStreamInOut.Runnable: done post[runnableProcessStreamInData]");
+ }
+ }
+ }
+ //Thread.sleep(50);
+ } catch (Exception ex) {
+ appendToLog("UsbConnector.waitStreamInOut.Runnable: Exception as " + ex.toString());
+ }
+ } else if (DEBUG) appendToLog("UsbConnector.waitStreamInOut.Runnable: cannot handle as usbEndpointIn type is " + usbEndpointIn.getType());
+ }
+ }
+ }
+ });
+ thread.start();
+ }
+ }
+
+ void processStreamInData() {
+ appendToLog("UsbConnector.processStreamInData with connectorCallback " + (connectorCallback == null ? "null" : "valid"));
+ if (connectorCallback != null) connectorCallback.callbackMethod();
+ }
+
+ public interface ConnectorCallback {
+ void callbackMethod();
+ }
+ public ConnectorCallback connectorCallback = null;
+
+ private boolean streamInRequest = false;
+ private int intervalProcessBleStreamInData = 100; //50;
+ public int getIntervalProcessBleStreamInData() { return intervalProcessBleStreamInData; }
+ public final Runnable runnableProcessStreamInData = new Runnable() {
+ @Override
+ public void run() {
+ streamInRequest = false;
+ processStreamInData();
+ //appendToLog("UsbConnector: post runnableProcessStreamInData within runnableProcessStreamInData");
+ mHandler.postDelayed(runnableProcessStreamInData, intervalProcessBleStreamInData);
+ }
+ };
+
+ private int streamInBufferSize = 0;
+ public int getStreamInBufferSize() {
+ appendToLog("UsbConnector.getStreamInBufferSize: streamInBufferSize = " + streamInBufferSize);
+ return streamInBufferSize;
+ }
+
+/*
+ private class UsbAsyncTask extends AsyncTask {
+ protected MainActivity ma;
+
+ public UsbAsyncTask() {
+ super();
+ }
+
+ protected String doInBackground(String... strings) {
+ boolean hasData = true;
+ String allData = "";
+ byte[] byteA = new byte[usbEndpointIn.getMaxPacketSize()];
+ try {
+ UsbRequest usbRequest = new UsbRequest();
+ if (!usbRequest.initialize(usbDeviceConnection, usbEndpointIn)) {
+ return "";
+ }
+ while (hasData) {
+ allData = "";
+ hasData = usbDeviceConnection.bulkTransfer(usbEndpointIn, byteA, usbEndpointIn.getMaxPacketSize(), 1000) >= 0;
+ String result = Arrays.toString(byteA);
+ if (!hasData || result.isEmpty()) {
+ hasData = false;
+ if (startedScan) {
+ finishedScan = true;
+ }
+ return "";
+ } else {
+ startedScan = true;
+ byte[] bA = byteA;
+ for (int i = 0; i < bA.length; i++) {
+ allData += (char)bA[i];
+ }
+ lastDataReceived += allData;
+ }
+ }
+ usbRequest.close();
+
+ } catch (Exception e) {
+ finishedScan = false;
+ startedScan = false;
+ lastDataReceived = "";
+ return " Error while reading ";
+ }
+ return allData;
+ }
+
+ protected void onProgressUpdate(Integer... progress) {
+ }
+
+ protected void onPostExecute(String result) {
+ if (startedScan && finishedScan) {
+ mLog.setText(lastDataReceived);
+ lastDataReceived = "";
+ finishedScan = false;
+ startedScan = false;
+ }
+ parseUsb();
+ }
+ }
+*/
+ public void appendToLog(String s) {
+ utility.appendToLog(s);
+ }
+
+ //////////////////////////////////////////////////////////////////////////////////
+
+
+ void makeConnection() {
+ /*
+ usbDeviceConnection = usbManager.openDevice(usbDevice); //Release later: mConnection.close();
+ if (usbDeviceConnection == null) {
+ if (DEBUG) appendToLog("UsbConnector().setDevice(): connection is NULL");
+ } else {
+ usbInterface = usbDevice.getInterface(0);
+ usbDeviceConnection.claimInterface(usbInterface, true); // Release later: mConnection.releaseInterface(mInterface);
+ try {
+ if (UsbConstants.USB_DIR_OUT == usbInterface.getEndpoint(1).getDirection()) {
+ usbEndpoint4Write = usbInterface.getEndpoint(1);
+ }
+ if (UsbConstants.USB_DIR_IN == usbInterface.getEndpoint(0).getDirection()) {
+ usbEndpoint4Read = usbInterface.getEndpoint(0);
+ packetSize = usbEndpoint4Read.getMaxPacketSize() * 50;
+ }
+ mHandler.removeCallbacks(mUsbConnectRunnable);
+ mHandler.post(mUsbConnectRunnable);
+ if (DEBUG) appendToLog("UsbConnector().setDevice(): connection is VALID");
+ } catch (Exception ex) {
+ usbInterface = null; usbEndpoint4Write = null; usbEndpoint4Read = null;
+ if (DEBUG) appendToLog("UsbConnector().setDevice(): Exception = " + ex.toString());
+ }
+ }
+ */
+ }
+
+ private final int STREAM_IN_BUFFER_MAX = 0x4000; //0xC00; //0x800; //0x400;
+ private final int STREAM_IN_BUFFER_LIMIT = 0x3F80; //0xB80; //0x780; //0x380;
+ private byte[] streamInBuffer = new byte[STREAM_IN_BUFFER_MAX];
+ int streamInBufferHead, streamInBufferTail;
+
+ private long streamInDataMilliSecond;
+ public long getStreamInDataMilliSecond() { return streamInDataMilliSecond; }
+ int readSteamIn(byte[] buffer, int byteOffset, int byteCount) {
+ appendToLog("UsbConnector.readSteamIn: starts with byteOffset = " + byteOffset + ", byteCount = " + byteCount + ", streamInBufferSize = " + streamInBufferSize);
+
+ synchronized (streamInBuffer) {
+ if (0 == streamInBufferSize) return 0;
+
+ if (isArrayListStreamInBuffering) {
+ int byteGot = 0;
+ int length1 = arrayListStreamIn.get(0).data.length;
+ appendToLog("UsbConnector.readSteamIn: arrayListStreamIn.size = " + arrayListStreamIn.size() + ", buffer.length = " + buffer.length
+ + ", byteOffset = " + byteOffset + ", length1 = " + length1);
+ if (arrayListStreamIn.size() != 0 && buffer.length - byteOffset > length1) {
+ appendToLog("UsbConnector.readSteamIn: going to arraycopy");
+ System.arraycopy(arrayListStreamIn.get(0).data, 0, buffer, byteOffset, length1);
+ streamInDataMilliSecond = arrayListStreamIn.get(0).milliseconds;
+ arrayListStreamIn.remove(0);
+ byteOffset += length1;
+ byteGot += length1;
+ }
+ byteCount = byteGot;
+ } else {
+ if (byteCount > streamInBufferSize)
+ byteCount = streamInBufferSize;
+ if (byteOffset + byteCount > buffer.length) {
+ byteCount = buffer.length - byteOffset;
+ }
+ if (byteCount <= 0) return 0;
+
+ if (isStreamInBufferRing) {
+ streamInBufferPull(buffer, byteOffset, byteCount);
+ } else {
+ System.arraycopy(streamInBuffer, 0, buffer, byteOffset, byteCount);
+ System.arraycopy(streamInBuffer, byteCount, streamInBuffer, 0, streamInBufferSize - byteCount);
+ }
+ }
+ streamInBufferSize -= byteCount;
+ appendToLog("UsbConnector.readSteamIn: byteCount returned = " + byteCount);
+ return byteCount;
+ }
+ }
+
+ int debugDisplayCounter = 0; int debugDisplayCounter1 = 0;
+ boolean inventoryRunning = false; int inventoryInCounter = 0;
+ int connectCounter = 0; int recCounter = 0;
+ int connectRunInterval = 10; //5; //10;
+ private final Runnable mUsbConnectRunnable = new Runnable() {
+ @Override
+ public void run() {
+ /*
+ boolean readConnectStatus = false;
+// appendToLogS("o ");
+ mHandler.postDelayed(mUsbConnectRunnable, connectRunInterval);
+ if (++connectCounter > 10 && inventoryRunning) { // && inventoryInCounter > 3) {
+ connectCounter = 0;
+ //mTextView.append("a "); //String.format("%d ", r));
+// appendToLogS(String.format("%d + %d", recCounter, streamInBufferSize)); recCounter = 0;
+ }
+ if (usbDeviceConnection == null) {
+ publishProgress("UsbConnector().mUsbConnectRunnable(): mConnection is NULL");
+ } else {
+ final byte[] bytes = new byte[packetSize];
+ int r = 0;
+// do {
+ long timeStart = currentBleConnectTimeMillis();
+ r = usbDeviceConnection.bulkTransfer(usbEndpoint4Read, bytes, packetSize, 1);//5); //10); //150
+ if (r < 0) {
+ if (inventoryRunning) {
+ if (debugDisplayCounter1++ < 5) {
+ publishProgress(String.format("%d>bulktransfer1 duration = %d", currentBleConnectTimeMillis(), currentBleConnectTimeMillis()-timeStart) );
+ }
+ }
+ publishProgress("0"); //UsbConnector().mUsbConnectRunnable(): mConnection.bulkTransfer is ZERO");
+ } else {
+ if (inventoryRunning) {
+ inventoryInCounter++;
+ if (debugDisplayCounter++ < 5) {
+ publishProgress(String.format("%d>bulktransfer duration = %d, length = %d, data(1) = %d", currentBleConnectTimeMillis(), currentBleConnectTimeMillis()-timeStart, r, bytes[1]) );
+ }
+ }
+// publishProgress(String.format("UsbConnector().mUsbConnectRunnable(): mConnection.bulkTransfer lengths %s, content: %s", r, byteArrayToString(bytes)));
+ if (inventoryRunning) { // && inventoryInCounter > 3) {
+ recCounter += r;
+ // mTextView.append(String.format("%d ", r));
+ }
+ if (false) { } else
+ if (streamInBufferSize + r >= streamInBuffer.length) {
+ publishProgress("111");
+// } else if (inventoryRunning) {
+// publishProgress("222");
+ } else if (bytes[0] == 1 && bytes[1] > 0) {
+ {
+ if (isStreamInBufferRing) {
+ streamInBufferPush(bytes, 2, bytes[1]);
+ } else {
+ System.arraycopy(bytes, 2, streamInBuffer, streamInBufferSize, bytes[1]);
+ }
+ streamInBufferSize += bytes[1];
+// byte[] byteDisplay = new byte[streamInBufferSize];
+// System.arraycopy(streamInBuffer, 0, byteDisplay, 0, byteDisplay.length);
+// publishProgress(String.format("\tMessage received of lengths %s, content: %s, streamInBuffer of lengths %s, content: %s", r, byteArrayToString(bytes), byteDisplay.length, byteArrayToString(byteDisplay)));
+// publishProgress(String.format("UsbConnector().mUsbConnectRunnable(): streamInBuffer of lengths %s, content: %s", byteDisplay.length, byteArrayToString(byteDisplay)));
+ }
+ }
+ }
+// } while (r > 0);
+ readConnectStatus = true;
+ }
+ if (readConnectStatus) {
+// mHandler.postDelayed(mUsbConnectRunnable, 5);
+// } else {
+// connectRequested = false;
+ }
+// appendToLogS("p ");
+ */
+ }
+ };
+
+
+
+ void disconnect() {
+ mHandler.removeCallbacks(mUsbConnectRunnable);
+ connectRequested = false;
+/* BluetoothManager mBluetoothManager = (BluetoothManager) mContext.getSystemService(Context.BLUETOOTH_SERVICE);
+ appendToLog("UsbConnector: disconnect(): connection_state=" + mBluetoothAdapter.getState() + ", state2=" + mBluetoothManager.getConnectedDevices(BluetoothProfile.GATT).size() + ", state3=" + mBluetoothManager.getConnectedDevices(BluetoothProfile.GATT_SERVER).size());
+ if (isBleConnected()) {
+ if (mBluetoothAdapter == null) {
+ appendToLog("UsbConnector: disconnect() with NULL mBluetoothAdapter");
+ } else if (!mBluetoothAdapter.isEnabled()) {
+ appendToLog("UsbConnector: disconnect(): DISABLED mBluetoothAdapter");
+ } else if (mBluetoothGatt == null) {
+ appendToLog("UsbConnector: disconnect(): NULL mBluetoothGatt");
+ } else {
+ mBluetoothGatt.disconnect();
+ if (tempDisconnect == false) mBluetoothDevice = null;
+ appendToLog("UsbConnector: disconnect(): done");
+ }
+ }*/
+ }
+
+ int writeCounter = 0;
+ boolean WriteData(byte[] bytes) {
+/* if (writeCounter > 2) {
+ appendToLog("UsbConnector().WriteData()");
+ return true;
+ }
+ if (usbDevice == null || usbDeviceConnection == null || usbInterface == null || usbEndpoint4Write == null || usbManager.hasPermission(usbDevice) == false) {
+ if (DEBUG) appendToLog("UsbConnector().WriteData(): NULL somethings. Cannot writeData");
+ } else {
+// mConnection.claimInterface(mInterface, true); // Lock the usb interface.
+ int r = usbDeviceConnection.bulkTransfer(usbEndpoint4Write, bytes, bytes.length, 250);
+ if (r <= 0) {
+ if (DEBUG) appendToLog("UsbConnector().WriteData(): mConnection.bulkTransfer is ZERO");
+ } else {
+ if (DEBUG) appendToLog("UsbConnector().WriteData(" + writeCounter++ + "): " + String.format("Written %s bytes to the dongle. Data written: %s", r, byteArrayToString(bytes)));
+ }
+// mConnection.releaseInterface(mInterface);
+ if (r > 0) return true;
+ }
+ */
+ return false;
+ }
+
+ String byteArrayToString(byte[] packet) {
+ StringBuilder sb = new StringBuilder(packet.length * 2);
+ for (byte b : packet) {
+ sb.append(String.format("%02X", b));
+ }
+ return sb.toString();
+ }
+
+ String logString = "";
+ String oldPublish = "";
+ void publishProgress(String s) {
+ if (oldPublish.contains(s)) return; oldPublish = s;
+// if (appended == false) return;
+ logString += (", " + s);
+ }
+ boolean appended = false;
+ String ssString = ""; int ssCount = 0; int ssInterval = 10;
+ void appendToLogS(String s) {
+ if (textView != null) {
+ if (logString.length() > 0) textView.append(logString); logString = ""; oldPublish = "";
+ String ss = currentBleConnectTimeMillis() + ">" + s;
+ ssString += (", " + ss);
+// if (++ssCount >= ssInterval) {
+ textView.append(ssString); ssCount = 0; ssString = "";
+ // }
+ appended = true;
+ }
+ }
+
+ /*void appendToLog(String s) {
+ if (textView != null) {
+ if (logString.length() > 0) textView.append(logString); logString = ""; oldPublish = "";
+ textView.append("\n" + currentBleConnectTimeMillis() + ">" + s);
+ appended = true;
+ }
+// Log.v("Hello", "\n" + currentBleConnectTimeMillis() + ">" + s);
+ }*/
+ private long mConnectedTimeMillis;
+ private long currentBleConnectTimeMillis() {
+ return System.currentTimeMillis() - mConnectedTimeMillis;
+ }
+
+ private int totalTemp, totalReceived;
+ private long firstTime, totalTime;
+
+ private class StreamInData {
+ byte[] data;
+ long milliseconds;
+ }
+ private ArrayList arrayListStreamIn = new ArrayList(); private boolean isArrayListStreamInBuffering = true;
+ private boolean isStreamInBufferRing = true;
+ private void streamInBufferPush(byte[] inData, int inDataOffset, int length) {
+ int length1 = streamInBuffer.length - streamInBufferTail;
+ int totalCopy = 0;
+ if (isArrayListStreamInBuffering) {
+ StreamInData streamInData = new StreamInData();
+ streamInData.data = inData;
+ streamInData.milliseconds = System.currentTimeMillis();
+ arrayListStreamIn.add(streamInData);
+ totalCopy = length;
+ } else {
+ if (length > length1) {
+ totalCopy = length1;
+ System.arraycopy(inData, inDataOffset, streamInBuffer, streamInBufferTail, length1);
+ length -= length1;
+ inDataOffset += length1;
+ streamInBufferTail = 0;
+ }
+ if (length != 0) {
+ totalCopy += length;
+ System.arraycopy(inData, inDataOffset, streamInBuffer, streamInBufferTail, length);
+ streamInBufferTail += length;
+ }
+ }
+ if (totalCopy != 0) {
+ totalTemp += totalCopy;
+ long timeDifference = System.currentTimeMillis() - firstTime;
+ if (totalTemp > 17 && timeDifference > 1000) {
+ totalReceived = totalTemp;
+ totalTime = timeDifference;
+ //appendToLog("UsbConnector: BtDataIn: totalReceived = " + totalReceived + ", totalTime = " + totalTime);
+ firstTime = System.currentTimeMillis();
+ totalTemp = 0;
+ }
+ }
+ }
+ private void streamInBufferPull(byte[] buffer, int byteOffset, int length) {
+ synchronized (arrayListStreamIn) {
+ int length1 = streamInBuffer.length - streamInBufferHead;
+ if (length > length1) {
+ System.arraycopy(streamInBuffer, streamInBufferHead, buffer, byteOffset, length1);
+ length -= length1;
+ byteOffset += length1;
+ streamInBufferHead = 0;
+ }
+ if (length != 0) {
+ System.arraycopy(streamInBuffer, streamInBufferHead, buffer, byteOffset, length);
+ streamInBufferHead += length;
+ }}
+ }
+
+
+ long ltimeLogView;
+ void appendToLogView(String s) {
+ if (ltimeLogView == 0) ltimeLogView = System.currentTimeMillis();
+ if (s.trim().length() == 0) textView.setText("");
+ else textView.append(System.currentTimeMillis() - ltimeLogView + ": " + s + "\n" );
+ }
+}
+
+
+
+package com.csl.cslibrary4a;
+
+import android.Manifest;
+import android.content.Context;
+import android.content.pm.PackageManager;
+import android.media.MediaScannerConnection;
+import android.os.Build;
+import android.os.Environment;
+import android.os.Handler;
+import android.os.Looper;
+import android.util.Log;
+import android.widget.TextView;
+
+import org.epctagcoder.exception.EPCParseException;
+import org.epctagcoder.parse.SGTIN.ParseSGTIN;
+import org.epctagcoder.result.SGTIN;
+
+import java.io.BufferedOutputStream;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.OutputStreamWriter;
+import java.io.PrintWriter;
+import java.io.UnsupportedEncodingException;
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import java.util.Locale;
+
+public class Utility {
+ public final boolean DEBUG_SCAN = false;
+ public final boolean DEBUG_CONNECT = true;
+ public final boolean DEBUG_SELECT = false;
+ public final boolean DEBUG_INVCFG = false;
+ public final boolean DEBUG_BTDATA = false;
+ public final boolean DEBUG_FMDATA = false;
+ public final boolean DEBUG_PKDATA = false;
+ public final boolean DEBUG_APDATA = false;
+ public final boolean DEBUG_COMPACT = false;
+ public final boolean ENABLE_USBDATA = false;
+ private Context mContext; private TextView mLogView;
+ public Utility(Context context, TextView mLogView) {
+ mContext = context;
+ this.mLogView = mLogView;
+ }
+ private static long mReferenceTimeMs;
+ public void setReferenceTimeMs() {
+ mReferenceTimeMs = System.currentTimeMillis();
+ }
+ public long getReferencedCurrentTimeMs() { return System.currentTimeMillis() - mReferenceTimeMs; }
+
+ public boolean compareByteArray(byte[] array1, byte[] array2, int length) {
+ int i = 0;
+ if (array1 == null) return false;
+ if (array2 == null) return false;
+ if (array1.length < length || array2.length < length) {
+ return false;
+ }
+ for (; i < length; i++) {
+ if (array1[i] != array2[i]) {
+ break;
+ }
+ }
+ return (i == length);
+ }
+
+ public String byteArray2DisplayString(byte[] byteData) {
+ if (false) appendToLog("String0 = " + byteArrayToString(byteData));
+ String str = "";
+ try {
+ str = new String(byteData, "UTF-8");
+ str = str.replaceAll("[^\\x00-\\x7F]", "");
+ str = str.replaceAll("[\\p{Cntrl}&&[^\r\n\t]]", "");
+ } catch (UnsupportedEncodingException e) {
+ e.printStackTrace();
+ }
+ if (false) appendToLog("String1 = " + str);
+ return str;
+ }
+ public String byteArrayToString(byte[] packet) {
+ if (packet == null) return "";
+ StringBuilder sb = new StringBuilder(packet.length * 2);
+ for (byte b : packet) {
+ sb.append(String.format("%02X", b));
+ }
+ return sb.toString();
+ }
+
+ public byte[] stringToByteArray(String string) {
+ byte[] bytes = new byte[string.length()/2];
+ if (string == null) string = "";
+ String hexString = "0123456789ABCDEF";
+ for (int j = 0; j < string.length(); j++) {
+ String subString = string.substring(j, j + 1).toUpperCase();
+ int k = 0;
+ for (; k < 16; k++) {
+ if (subString.matches(hexString.substring(k, k + 1))) {
+ break;
+ }
+ }
+ if (k == 16) break;
+ if ((j / 2) * 2 == j) {
+ bytes[j / 2] |= (byte) (k << 4);
+ } else {
+ bytes[j / 2] |= (byte) (k);
+ }
+ }
+ return bytes;
+ }
+ public byte[] string2ByteArray(String string) {
+ byte[] bytes = null;
+ if (string == null) return null;
+ if ((string.length()/2)*2 != string.length()) string += "0";
+ for (int i = 0; i < string.length(); i+=2) {
+ try {
+ Short sValue = Short.parseShort(string.substring(i, i + 2), 16);
+ byte[] bytesNew = new byte[1];
+ if (bytes != null) {
+ bytesNew = new byte[bytes.length + 1];
+ System.arraycopy(bytes, 0, bytesNew, 0, bytes.length);
+ }
+ bytesNew[bytesNew.length - 1] = (byte) (sValue & 0xFF);
+ bytes = bytesNew;
+ } catch (Exception ex) {
+ appendToLog("Exception in i = " + i + ", substring = " + string.substring(i, i+2));
+ break;
+ }
+ }
+ return bytes;
+ }
+ public int byteArrayToInt(byte[] bytes) {
+ int iValue = 0;
+ int length = bytes.length;
+ if (bytes.length > 4) length = 4;
+ for (int i = 0; i < length; i++) {
+ iValue = (iValue << 8) + (bytes[i] & 0xFF);
+ }
+ return iValue;
+ }
+
+ private static Handler mHandler = new Handler();
+ public void appendToLogRunnable(final String s) {
+ mHandler.post(new Runnable() {
+ @Override
+ public void run() {
+ appendToLog(s);
+ }
+ });
+ }
+ public String appendToLog(String s) {
+ String TAG = "";
+ StackTraceElement[] stacktrace = Thread.currentThread().getStackTrace();
+ boolean foundMe = false;
+ for(int i=0; i= Build.VERSION_CODES.M) {
+ if (mContext.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
+ writeExtPermission = false;
+ //appendToLog("requestPermissions WRITE_EXTERNAL_STORAGE 1");
+ //requestPermissions((Activity) mContext, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
+ //if (false) Toast.makeText(mContext, R.string.toast_permission_not_granted, Toast.LENGTH_SHORT).show();
+ //return;
+ }
+ }
+ String errorDisplay = null;
+ if (writeExtPermission == false) {
+ errorDisplay = "denied WRITE_EXTERNAL_STORAGE Permission !!!";
+ } else if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) == false) errorDisplay = "Error in mouting external storage !!!";
+ else {
+ File path = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + Environment.DIRECTORY_DOWNLOADS + "/cs108Java");
+ if (path.exists() == false) path.mkdirs();
+ if (path.exists() == false) errorDisplay = "Error in making directory !!!";
+ else {
+ String dateTime = new SimpleDateFormat("yyMMdd_HHmmss").format(new Date());
+ String fileName = "cs108JavaDebug_" + dateTime + ".txt";
+ fileDebug = new File(path, fileName);
+ if (fileDebug == null) errorDisplay = "Error in making directory !!!";
+ }
+ }
+ if (errorDisplay != null) appendToLog("Error in saving file with " + errorDisplay);
+ }
+ public void debugFileClose() {
+ if (fileDebug != null) {
+ try {
+ MediaScannerConnection.scanFile(mContext, new String[]{fileDebug.getAbsolutePath()}, null, null);
+ } catch (Exception ex) {
+ }
+ }
+ }
+ public void debugFileEnable(boolean enable) { enableFileDebug = enable; }
+ public void writeDebug2File(String stringDebug) {
+ if (fileDebug != null && enableFileDebug) {
+ SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy hh:mm.mmm", Locale.getDefault());
+ stringDebug = sdf.format(System.currentTimeMillis()) + ": " + stringDebug;
+ try {
+ FileOutputStream outputStreamDebug = new FileOutputStream(fileDebug, true);
+ PrintWriter printWriterDebug = new PrintWriter(new OutputStreamWriter(new BufferedOutputStream(outputStreamDebug), "UTF-8"));
+ if (false) appendToLog(stringDebug);
+ printWriterDebug.println(stringDebug);
+ printWriterDebug.flush(); printWriterDebug.close();
+ outputStreamDebug.close();
+ } catch (Exception ex) {
+ }
+ }
+ }
+
+ public String getlast3digitVersion(String str) {
+ if (str != null) {
+ int len = str.length();
+ if (len > 3) {
+ String strOut = "";
+ if (str.substring(len-3, len-2).matches("0")) strOut = str.substring(len-2, len-1);
+ else strOut = str.substring(len-3, len-1);
+ strOut += "." + str.substring(len-1, len);
+ return strOut;
+ }
+ }
+ return null;
+ }
+
+ public String getCombinedVersion(String string0) {
+ String string1 = BuildConfig.VERSION_NAME;
+ int iValue1 = Integer.parseInt(string1);
+ appendToLog("string1 = " + string1 + ", iValue1 = " + iValue1);
+ int iPos0 = string0.indexOf(".");
+ int iPos1 = string0.substring(iPos0 + 1).indexOf(".");
+ int iValue0 = Integer.parseInt(string0.substring(iPos0 + iPos1 + 2));
+ appendToLog("stringVersion = " + string0 + ", iPos0 = " + iPos0 + ", iPos1 = " + iPos1 + ", iValue0 = " + iValue0);
+ iValue0 += iValue1;
+ return string0.substring(0, iPos0 + iPos1 + 2) + String.valueOf(iValue0);
+ }
+
+ public boolean isVersionGreaterEqual(String version, int majorVersion, int minorVersion, int buildVersion) {
+ if (version == null) return false;
+ if (version.length() == 0) return false;
+ String[] versionPart = version.split("[ .,-]+");
+
+ if (versionPart == null) return false;
+ try {
+ int value = Integer.valueOf(versionPart[0]);
+ if (value < majorVersion) return false;
+ if (value > majorVersion) return true;
+
+ if (versionPart.length < 2) return true;
+ value = Integer.valueOf(versionPart[1]);
+ if (value < minorVersion) return false;
+ if (value > minorVersion) return true;
+
+ if (versionPart.length < 3) return true;
+ value = Integer.valueOf(versionPart[2]);
+ if (value < buildVersion) return false;
+ return true;
+ } catch (Exception ex) {
+ return false;
+ }
+ }
+
+ public double get2BytesOfRssi(byte[] bytes, int index) {
+ int iValue = (bytes[index] & 0xFF) * 256 + (bytes[index + 1] & 0xFF);
+ if ((iValue & 0x8000) != 0) iValue ^= ~0xFFFF;
+ double dValue = iValue;
+ return dValue/100;
+ }
+
+ float fTemperature_old = -500;
+ public float decodeCtesiusTemperature(String strActData, String strCalData) {
+ float fTemperature = -500; boolean invalid = false;
+ appendToLog("Hello9: strActData = " + strActData + ", strCalData = " + strCalData);
+ if (strActData.length() != 8 || strCalData.length() != 8) {
+ if (strActData.length() != 8) appendToLogView("Warning: Invalid length of sensing data = " + strActData);
+ else appendToLogView("Warning: Invalid length of calibration data = " + strCalData);
+ invalid = true;
+ }
+ else if ((strActData.substring(0, 1).matches("F") && strActData.substring(4, 5).matches("F")) == false) {
+ appendToLogView("Warning: Not F header of sensing data = " + strActData);
+ invalid = true;
+ }
+ else {
+ String strTemp = strActData.substring(4,8);
+ int iTemp = Integer.parseInt(strTemp, 16);
+ int iChecksum = 0;
+ for (int i=0; i<5; i++, iTemp >>= 3) {
+ iChecksum ^= (iTemp & 0x7);
+ }
+ if (iChecksum != 0) {
+ appendToLogView("Warning: Invalid checksum(" + String.valueOf(iChecksum) + ") for strActData = " + strActData);
+ invalid = true;
+ }
+ }
+ if (true || invalid == false) {
+ int iDelta1 = Integer.parseInt(strCalData.substring(0,4), 16);
+ if ((iDelta1 & 0x8000) != 0) { iDelta1 ^= 0xFFFF; iDelta1++; iDelta1 *= -1; }
+ appendToLog(String.format("iDelta1 = %d", iDelta1));
+ int iVersion = Integer.parseInt(strCalData.substring(4,5), 16);
+ appendToLog("Hello9: " + String.format("iDelta1 = %X, iVersion = %X", iDelta1, iVersion));
+ float fDelta2 = ((float) iDelta1) / 100 - 101;
+ String strTemp = strActData.substring(1,4) + strActData.substring(5,8);
+ int iTemp = Integer.parseInt(strTemp, 16);
+ int iD1 = ((iTemp & 0xF80000) >> 19);
+ int iD2 = ((iTemp & 0x7FFF8) >> 3);
+ if (iVersion == 0 || iVersion == 1) fTemperature = (float) (11984.47 / (21.25 + iD1 + iD2 / 2752 + fDelta2) - 301.57);
+ else if (iVersion == 2) {
+ fTemperature = (float) (11109.6 / (24 + (iD2 + iDelta1)/375.3) - 290);
+ if (fTemperature >= 125) fTemperature = (float) (fTemperature * 1.2 - 25);
+ } else appendToLogView("Warning: Invalid version " + String.valueOf(iVersion));
+ if (invalid) appendToLogView(String.format("Temperature = %f", fTemperature));
+ }
+ if (fTemperature != -1) fTemperature_old = fTemperature;
+ return fTemperature;
+ }
+ public float decodeMicronTemperature(int iTag35, String strActData, String strCalData) {
+ float fTemperature = -1;
+ if (strActData == null || strCalData == null) {
+ } else if (strActData.length() != 4 || strCalData.length() != 16) {
+ } else if (strActData.matches("0000")) {
+ fTemperature = fTemperature_old;
+ } else if (iTag35 == 3) {
+ int calCode1, calTemp1, calCode2, calTemp2;
+ int crc = Integer.parseInt(strCalData.substring(0, 4), 16);
+ calCode1 = Integer.parseInt(strCalData.substring(4, 7), 16);
+ calTemp1 = Integer.parseInt(strCalData.substring(7, 10), 16);
+ calTemp1 >>= 1;
+ calCode2 = Integer.parseInt(strCalData.substring(9, 13), 16);
+ calCode2 >>= 1;
+ calCode2 &= 0xFFF;
+ calTemp2 = Integer.parseInt(strCalData.substring(12, 16), 16);
+ calTemp2 >>= 2;
+ calTemp2 &= 0x7FF;
+
+ fTemperature = Integer.parseInt(strActData, 16);
+ fTemperature = ((float) calTemp2 - (float) calTemp1) * (fTemperature - (float) calCode1);
+ fTemperature /= ((float) (calCode2) - (float) calCode1);
+ fTemperature += (float) calTemp1;
+ fTemperature -= 800;
+ fTemperature /= 10;
+ } else if (iTag35 == 5) {
+ int iTemp;
+ float calCode2 = Integer.parseInt(strCalData.substring(0, 4), 16); calCode2 /= 16;
+ iTemp = Integer.parseInt(strCalData.substring(4, 8), 16); iTemp &= 0x7FF; float calTemp2 = iTemp; calTemp2 -= 600; calTemp2 /= 10;
+ float calCode1 = Integer.parseInt(strCalData.substring(8, 12), 16); calCode1 /= 16;
+ iTemp = Integer.parseInt(strCalData.substring(12, 16), 16); iTemp &= 0x7FF; float calTemp1 = iTemp; calTemp1 -= 600; calTemp1 /= 10;
+
+ fTemperature = Integer.parseInt(strActData, 16);
+ fTemperature -= calCode1;
+ fTemperature *= (calTemp2 - calTemp1);
+ fTemperature /= (calCode2 - calCode1);
+ fTemperature += calTemp1;
+ }
+ if (fTemperature != -1) fTemperature_old = fTemperature;
+ return fTemperature;
+ }
+ public float decodeAsygnTemperature(String string) {
+ String stringUser5 = string.substring(20, 24); int iUser5 = Integer.valueOf(stringUser5, 16);
+ String stringUser6 = string.substring(24, 28); int iUser6 = Integer.valueOf(stringUser6, 16);
+ String stringUser1 = string.substring(4, 8); int iUser1 = Integer.valueOf(stringUser1, 16);
+ switch (iUser1 & 0xC000) {
+ case 0xc000:
+ iUser1 &= 0x1FFF; iUser1 /= 8;
+ break;
+ case 0x8000:
+ iUser1 &= 0xFFF; iUser1 /= 4;
+ break;
+ case 0x4000:
+ iUser1 &= 0x7FF; iUser1 /= 2;
+ break;
+ default:
+ iUser1 &= 0x3FF;
+ break;
+ }
+ float temperature = -1;
+ appendToLog("input string " + string + ", user1 = " + stringUser1 + ", user5 = " + stringUser5 + ", user6 = " + stringUser6);
+ //iUser1 = 495; iUser6 = 3811;
+ appendToLog("iUser1 = " + iUser1 + ", iUser5 = " + iUser5 + ", iUser6 = " + iUser6);
+ if (iUser5 == 3000) {
+ float calibOffset = (float) 3860.27 - (float) iUser6;
+ appendToLog("calibOffset = " + calibOffset);
+ float acqTempCorrected = (float) iUser1 + calibOffset / 8;
+ appendToLog("acqTempCorrected = " + acqTempCorrected);
+ temperature = (float) 0.3378 * acqTempCorrected - (float) 133;
+ appendToLog("temperature = " + temperature);
+ } else if (iUser5 == 1835) {
+ float expAcqTemp = (float) 398.54 - (float) iUser5 / (float) 100;
+ appendToLog("expAcqTemp = " + expAcqTemp);
+ expAcqTemp /= (float) 0.669162;
+ appendToLog("expAcqTemp = " + expAcqTemp);
+ float calibOffset = ((float) 8 * expAcqTemp) - (float) iUser6;
+ float acqTempCorrected = (float) iUser1 + calibOffset;
+ acqTempCorrected /= 8;
+ temperature = (float) -0.669162 * acqTempCorrected;
+ temperature += 398.54;
+ appendToLog("expAcqTemp = " + expAcqTemp + ". calibOffset = " + calibOffset + ", acqTempCorrected = " + acqTempCorrected + ", temperature = " + temperature);
+ }
+ return temperature;
+ } //4278
+ public float temperatureC2F(float fTemp) {
+ return (float) (32 + fTemp * 1.8);
+ }
+ public String temperatureC2F(String strValue) {
+ try {
+ float fValue = Float.parseFloat(strValue);
+
+ fValue = temperatureC2F(fValue);
+ return String.format("%.1f", fValue);
+ } catch (Exception ex) { }
+ return "";
+ }
+ float temperatureF2C(float fTemp) {
+ return (float) ((fTemp - 32) * 0.5556);
+ }
+ public String temperatureF2C(String strValue) {
+ try {
+ float fValue = Float.parseFloat(strValue);
+
+ fValue = temperatureF2C(fValue);
+ return String.format("%.1f", fValue);
+ } catch (Exception ex) { }
+ return "";
+ }
+
+ public enum EpcClass {
+ SGTIN, SSCC, SGLN, GRAI, GIAI, GSRN, GSRNP, GDTI, CPI, SGCN
+ }
+ public String getEpc4upcSerial(EpcClass epcClass, String filter, String companyPrefix, String itemReference, String serialNumber) {
+ String strValue = null;
+ ParseSGTIN parseSGTIN = null;
+ String strURI = "urn:epc:tag:";
+ appendToLog("epcClass is " + epcClass.toString());
+ switch (epcClass) {
+ default:
+ strURI += "sgtin-96:";
+ break;
+ }
+ strURI += (filter + "." + companyPrefix + "." + itemReference + "." + serialNumber);
+ try {
+ parseSGTIN = ParseSGTIN.Builder()
+ .withEPCTagURI( strURI).build();
+ SGTIN sgtin = parseSGTIN.getSGTIN();
+ strValue = sgtin.getRfidTag();
+ } catch (EPCParseException e) {
+ //throw new RuntimeException(e);
+ }
+ return strValue;
+ }
+
+ public String getUpcSerial(String strEpc) {
+ ParseSGTIN parseSGTIN = null;
+ String strValue = null;
+ try {
+ parseSGTIN = ParseSGTIN.Builder()
+ .withRFIDTag(strEpc)
+ .build();
+ SGTIN sgtin = parseSGTIN.getSGTIN();
+ //strValue = sgtin.toString();
+ //strValue = sgtin.getEpcRawURI();
+ strValue = sgtin.getEpcTagURI();
+ String strHeader = "urn:epc:tag:";
+ if (strValue.indexOf(strHeader) == 0) strValue = strValue.substring(strHeader.length());
+ } catch (Exception e) {
+ appendToLog("parseSSCC exception: " + e.getMessage());
+ //throw new RuntimeException(e);
+ }
+ return strValue;
+ }
+ public String getUpcSerialDetail(String strUpcSerial) {
+ String strValue = null, strTmp, strCmp;
+ strCmp = ":"; strTmp = strUpcSerial.substring(0, strUpcSerial.indexOf(strCmp));
+ if (strTmp != null) {
+ if (strValue != null) strValue += "\n";
+ strValue = "Epc Class: " + strTmp;
+ strUpcSerial = strUpcSerial.substring(strUpcSerial.indexOf(strCmp) + 1);
+ }
+ strCmp = "."; strTmp = strUpcSerial.substring(0, strUpcSerial.indexOf(strCmp));
+ if (strTmp != null) {
+ if (strValue != null) strValue += "\n";
+ strValue += "Filter: " + strTmp;
+ strUpcSerial = strUpcSerial.substring(strUpcSerial.indexOf(strCmp) + 1);
+ }
+ strCmp = "."; strTmp = strUpcSerial.substring(0, strUpcSerial.indexOf(strCmp));
+ if (strTmp != null) {
+ if (strValue != null) strValue += "\n";
+ strValue += "Company Prefix: " + strTmp;
+ strUpcSerial = strUpcSerial.substring(strUpcSerial.indexOf(strCmp) + 1);
+ }
+ strCmp = "."; strTmp = strUpcSerial.substring(0, strUpcSerial.indexOf(strCmp));
+ if (strTmp != null) {
+ if (strValue != null) strValue += "\n";
+ strValue += "Item Reference: " + strTmp;
+ strUpcSerial = strUpcSerial.substring(strUpcSerial.indexOf(strCmp) + 1);
+ }
+ strTmp = strUpcSerial;
+ if (strTmp != null) {
+ if (strValue != null) strValue += ("\n");
+ strValue += "Serial Number: " + strTmp;
+ }
+ return strValue;
+ }
+
+ public boolean checkHostProcessorVersion(String version, int majorVersion, int minorVersion, int buildVersion) {
+ boolean DEBUG = false;
+ if (DEBUG) appendToLog("version = " + version + ", majorVersion = " + majorVersion + ", minorVersion = " + minorVersion + ", buildVersion = " + buildVersion);
+ if (version == null) { if (DEBUG) appendToLog("return false 1"); return false; }
+ if (version.length() == 0) { if (DEBUG) appendToLog("return false 2"); return false; }
+ String[] versionPart = version.split(" |\\.");
+
+ if (versionPart == null) { if (DEBUG) appendToLog("return false 3"); return false; }
+ try {
+ if (DEBUG) appendToLog("checkpoint 1");
+ int value = Integer.valueOf(versionPart[0]);
+ if (value < majorVersion) { if (DEBUG) appendToLog("return false 4"); return false; }
+ if (value > majorVersion) return true;
+
+ if (DEBUG) appendToLog("checkpoint 2");
+ if (versionPart.length < 2) return true;
+ value = Integer.valueOf(versionPart[1]);
+ if (value < minorVersion) { if (DEBUG) appendToLog("return false 5"); return false; }
+ if (value > minorVersion) return true;
+
+ if (DEBUG) appendToLog("checkpoint 3");
+ if (versionPart.length < 3) return true;
+ value = Integer.valueOf(versionPart[2]);
+ if (value < buildVersion) { if (DEBUG) appendToLog("return false 6"); return false; }
+ return true;
+ } catch (Exception ex) {
+ if (DEBUG) appendToLog("return false 7"); return false;
+ }
+ }
+
+ public float float16toFloat32(String strData) {
+ float fValue = -1;
+ if (strData.length() == 4) {
+ int iValue = Integer.parseInt(strData, 16);
+ int iSign = iValue & 0x8000; if (iSign != 0) iSign = 1;
+ int iExp = (iValue & 0x7C00) >> 10;
+ int iMant = (iValue & 0x3FF);
+ if (iExp == 15) {
+ if (iSign == 0) fValue = Float.POSITIVE_INFINITY;
+ else fValue = Float.NEGATIVE_INFINITY;
+ } else if (iExp == 0) {
+ fValue = (iMant / 1024) * 2^(-14);
+ if (iSign != 0) fValue *= -1;
+ } else {
+ fValue = (float) Math.pow(2, iExp - 15);
+ fValue *= (1 + ((float)iMant / 1024));
+ if (iSign != 0) fValue *= -1;
+ }
+ if (true) appendToLog("strData = " + strData + ", iValue = " + iValue + ", iSign = " + iSign + ", iExp = " + iExp + ", iMant = " + iMant + ", fValue = " + fValue);
+ }
+ return fValue;
+ }
+ public String strFloat16toFloat32(String strData) {
+ String strValue = null;
+ float fTemperature = float16toFloat32(strData);
+ if (fTemperature > -400) return String.format("%.1f", fTemperature);
+ return strValue;
+ }
+ public String str2float16(String strData) {
+ String strValue = "";
+ float fValue0 = (float) Math.pow(2, -14);
+ float fValueMax = 2 * (float) Math.pow(2, 30);
+ float fValue = Float.parseFloat(strData);
+ float fValuePos = (fValue > 0) ? fValue : -fValue;
+ boolean bSign = false; if (fValue < 0) bSign = true;
+ int iExp, iMant;
+ if (fValuePos < fValueMax) {
+ if (fValuePos < fValue0) {
+ iExp = 0;
+ iMant = (int)((fValuePos / fValue0) * 1024);
+ } else {
+ for (iExp = 1; iExp < 31; iExp++) {
+ if (fValuePos < 2 * (float) Math.pow(2, iExp - 15)) break;
+ }
+ fValuePos /= ((float) Math.pow(2, iExp - 15));
+ fValuePos -= 1;
+ fValuePos *= 1024;
+ iMant = (int) fValuePos;
+ }
+ int iValue = (bSign ? 0x8000 : 0) + (iExp << 10) + iMant;
+ strValue = String.format("%04X", iValue);
+ if (true) appendToLog("bSign = " + bSign + ", iExp = " + iExp + ", iMant = " + iMant + ", iValue = " + iValue + ", strValue = " + strValue);
+ }
+ return strValue;
+ }
+}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ #FFBB86FC
+ #FF6200EE
+ #FF3700B3
+ #FF03DAC5
+ #FF018786
+ #FF000000
+ #FFFFFFFF
+
+
+
+
+
+ cslibrary4a
+
+
+ - 0: Multipath Interference Resistance
+ - 1: Range/Dense reader
+ - 2: Range/Throughput/Dense reader
+ - 3: Maximum throughput
+
+
+ - 11: Miller 1 640kHz Tari 7.5us
+ - 1: Miller 2 640kHz Tari 7.5us
+ - 15: Miller 4 640kHz Tari 7.5us
+ - 12: Miller 2 320kHz Tari 15us
+ - 3: Miller 2 320kHz Tari 20us
+ - 5: Miller 4 320kHz Tari 20us
+ - 7: Miller 4 250kHz Tari 20us
+ - 13: Miller 8 160kHz Tari 20us
+
+
+ - 103: Miller 1 640kHz Tari 6.25us
+ - 11: Miller 1 640kHz Tari 7.5us
+ - 302: Miller 1 640kHz Tari 7.5us
+ - 120: Miller 2 640kHz Tari 6.25us
+ - 1: Miller 2 640kHz Tari 7.5us
+ - 323: Miller 2 640kHz Tari 7.5us
+ - 15: Miller 4 640kHz Tari 7.5us
+ - 344: Miller 4 640kHz Tari 7.5us
+ - 345: Miller 4 640kHz Tari 7.5us
+ - 12: Miller 2 320kHz Tari 15us
+ - 223: Miller 2 320kHz Tari 15us
+ - 3: Miller 2 320kHz Tari 20us
+ - 222: Miller 2 320kHz Tari 20us
+ - 5: Miller 4 320kHz Tari 20us
+ - 241: Miller 4 320kHz Tari 20us
+ - 7: Miller 4 250kHz Tari 20us
+ - 244: Miller 4 250kHz Tari 20us
+ - 13: Miller 8 160kHz Tari 20us
+ - 285: Miller 8 160kHz Tari 20us
+
+
+ - 103: Miller 1 640kHz Tari 6.25us
+ - 302: Miller 1 640kHz Tari 7.5us
+ - 120: Miller 2 640kHz Tari 6.25us
+ - 323: Miller 2 640kHz Tari 7.5us
+ - 344: Miller 4 640kHz Tari 7.5us
+ - 345: Miller 4 640kHz Tari 7.5us
+ - 223: Miller 2 320kHz Tari 15us
+ - 222: Miller 2 320kHz Tari 20us
+ - 241: Miller 4 320kHz Tari 20us
+ - 244: Miller 4 250kHz Tari 20us
+ - 285: Miller 8 160kHz Tari 20us
+
+
+ - 103: FCC, FM0 640kHz 6.25us
+ - 302: ETSIUB, FM0 640kHz 7.5us
+ - 120: FCC, Miller 2 640kHz 6.25us
+ - 104: FCC, FM0 320kHz 6.25us
+ - 323: ETSIUB, Miller 2 640kHz 7.5us
+ - 4323: ETISUB, Miller 2 640kHz 7.5us Gen2X
+ - 203: Japan, FM0 426kHz 12.5us
+ - 202: ETSILB, FM0 426kHz 15us
+ - 226: Japan, Miller 2 426kHz 12.5us
+ - 344: ETSIUB, Miller 4 640kHz 7.5us
+ - 345: FCC ETSIUB, Miller 4 640kHz 7.5us
+ - 4345: FCC ETSIUB, Miller 4 640kHz 7.5us Gen2X
+ - 225: ETSILB, Miller 2 426kHz 15us
+ - 326: Japan, Miller 2 320kHz 12.5us
+ - 325: ETSILB, Miller 2 320kHz 15us
+ - 324: ETSILB, Miller 2 320kHz 20us
+ - 4324: ETSILB, Miller 2 320kHz 20us Gen2X
+ - 342: ETSILB, Miller 4 320kHz 20us
+ - 4342: ETSILB, Miller 4 320kHz 20us Gen2X
+ - 343: FCC, Miller 4 250kHz 20us
+ - 4343: FCC, Miller 4 250kHz 20us Gen2X
+ - 205: Japan, FM0 50kHz 20us
+ - 382: All, Miller 8 160kHz 20us
+ - 4382: All, Miller 8 160kHz 20us Gen2X
+
+
+ "Permissions are not granted. Please allow them in system setting."
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+package org.epctagcoder.exception;
+
+public class EPCParseException extends Exception {
+
+ public EPCParseException(String message) {
+ super(message);
+ }
+
+
+}
+
+
+
+package org.epctagcoder.option.CPI;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+public enum CPIFilterValue {
+ ALL_OTHERS_0(0),
+ RESERVED_1(1),
+ RESERVED_2(2),
+ RESERVED_3(3),
+ RESERVED_4(4),
+ RESERVED_5(5),
+ RESERVED_6(6),
+ RESERVED_7(7);
+
+ private int value;
+
+ private CPIFilterValue(int value) {
+ this.value = value;
+ }
+
+ public int getValue() {
+ return value;
+ }
+
+ private static final Map BY_CODE_MAP = new LinkedHashMap<>();
+ static {
+ for (CPIFilterValue rae : CPIFilterValue.values()) {
+ BY_CODE_MAP.put(rae.value, rae);
+ }
+ }
+
+ public static CPIFilterValue forCode(int code) {
+ return BY_CODE_MAP.get(code);
+ }
+
+
+}
+
+
+
+package org.epctagcoder.option.CPI;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+
+
+public enum CPIHeader {
+ HEADER_00111100("00111100") {
+ public Integer getTagSize() {
+ return 96;
+ }
+ },
+ HEADER_00111101("00111101") {
+ public Integer getTagSize() {
+ return 0; //null; // variable
+ }
+ };
+
+ private String value;
+ public abstract Integer getTagSize();
+
+
+ private CPIHeader(String value) {
+ this.value = value;
+ }
+
+ public String getValue() {
+ return value;
+ }
+
+ private static final Map BY_CODE_MAP = new LinkedHashMap<>();
+ static {
+ for (CPIHeader rae : CPIHeader.values()) {
+ BY_CODE_MAP.put(rae.value, rae);
+ }
+ }
+
+ public static CPIHeader forCode(String code) {
+ CPIHeader header = BY_CODE_MAP.get(code);
+
+ if (header==null) {
+ throw new IllegalArgumentException(String.format("CPI header [%s] is invalid. Allowed only 00111100 or 00111101", code));
+ }
+
+ return header;
+ }
+
+
+}
+
+
+
+package org.epctagcoder.option.CPI;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+public enum CPITagSize {
+ BITS_96(96) {
+ public Integer getHeader() {
+ return 60;
+ }
+ public Integer getSerialBitCount() {
+ return 31;
+ }
+ public Integer getSerialMaxLenght() {
+ return 0;
+ }
+ public Long getSerialMaxValue() {
+ return 2_147_483_647L;
+ }
+ },
+ BITS_VARIABLE(0) {
+ public Integer getHeader() {
+ return 61;
+ }
+ public Integer getSerialBitCount() {
+ return 40;
+ }
+ public Integer getSerialMaxLenght() {
+ return 12;
+ }
+ public Long getSerialMaxValue() {
+ return null; // not used
+ }
+ };
+
+ private int value;
+ public abstract Integer getHeader();
+ public abstract Integer getSerialBitCount();
+ public abstract Integer getSerialMaxLenght();
+ public abstract Long getSerialMaxValue();
+
+ private CPITagSize(int value) {
+ this.value = value;
+ }
+
+ public int getValue() {
+ return value;
+ }
+
+ private static final Map BY_CODE_MAP = new LinkedHashMap<>();
+ static {
+ for (CPITagSize rae : CPITagSize.values()) {
+ BY_CODE_MAP.put(rae.value, rae);
+ }
+ }
+
+ public static CPITagSize forCode(int code) {
+ return BY_CODE_MAP.get(code);
+ }
+
+
+}
+
+
+
+package org.epctagcoder.option.CPI.partitionTable;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.epctagcoder.option.TableItem;
+import org.epctagcoder.option.CPI.CPITagSize;
+
+
+public class CPIPartitionTableList {
+ static final private List list = new ArrayList();
+
+
+
+ public CPIPartitionTableList(CPITagSize tagSize) {
+ if ( tagSize.getValue()==96 ) {
+ list.clear();
+ list.add( new TableItem(0, 40, 12, 11, 3) );
+ list.add( new TableItem(1, 37, 11, 14, 4) );
+ list.add( new TableItem(2, 34, 10, 17, 5) );
+ list.add( new TableItem(3, 30, 9, 21, 6) );
+ list.add( new TableItem(4, 27, 8, 24, 7) );
+ list.add( new TableItem(5, 24, 7, 27, 8) );
+ list.add( new TableItem(6, 20, 6, 31, 9) );
+ } else { //if ( tagSize.getValue()==202 ) { // variable
+ list.clear();
+ list.add( new TableItem(0, 40, 12, 114, 18) );
+ list.add( new TableItem(1, 37, 11, 120, 19) );
+ list.add( new TableItem(2, 34, 10, 126, 20) );
+ list.add( new TableItem(3, 30, 9, 132, 21) );
+ list.add( new TableItem(4, 27, 8, 138, 22) );
+ list.add( new TableItem(5, 24, 7, 144, 23) );
+ list.add( new TableItem(6, 20, 6, 150, 24) );
+ }
+ }
+
+
+ public TableItem getPartitionByL(Integer index) {
+ TableItem tableItem = null;
+ for (TableItem item : list) {
+ if (item.getL()==index) {
+ tableItem = item;
+ break;
+ }
+ }
+ return tableItem;
+ }
+
+ public TableItem getPartitionByValue(Integer index) {
+ TableItem tableItem = null;
+ for (TableItem item : list) {
+ if (item.getPartitionValue()==index) {
+ tableItem = item;
+ break;
+ }
+ }
+ return tableItem;
+ }
+
+
+}
+
+
+
+package org.epctagcoder.option.GDTI;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+public enum GDTIFilterValue {
+ ALL_OTHERS_0(0),
+ RESERVED_1(1),
+ RESERVED_2(2),
+ RESERVED_3(3),
+ RESERVED_4(4),
+ RESERVED_5(5),
+ RESERVED_6(6),
+ RESERVED_7(7);
+
+ private int value;
+
+ private GDTIFilterValue(int value) {
+ this.value = value;
+ }
+
+ public int getValue() {
+ return value;
+ }
+
+ private static final Map BY_CODE_MAP = new LinkedHashMap<>();
+ static {
+ for (GDTIFilterValue rae : GDTIFilterValue.values()) {
+ BY_CODE_MAP.put(rae.value, rae);
+ }
+ }
+
+ public static GDTIFilterValue forCode(int code) {
+ return BY_CODE_MAP.get(code);
+ }
+
+
+}
+
+
+
+package org.epctagcoder.option.GDTI;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+
+public enum GDTIHeader {
+ HEADER_00101100("00101100") {
+ public Integer getTagSize() {
+ return 96;
+ }
+ },
+ HEADER_00111110("00111110") {
+ public Integer getTagSize() {
+ return 174;
+ }
+ };
+
+ private String value;
+ public abstract Integer getTagSize();
+
+
+ private GDTIHeader(String value) {
+ this.value = value;
+ }
+
+ public String getValue() {
+ return value;
+ }
+
+ private static final Map BY_CODE_MAP = new LinkedHashMap<>();
+ static {
+ for (GDTIHeader rae : GDTIHeader.values()) {
+ BY_CODE_MAP.put(rae.value, rae);
+ }
+ }
+
+ public static GDTIHeader forCode(String code) {
+ GDTIHeader header = BY_CODE_MAP.get(code);
+
+ if (header==null) {
+ throw new IllegalArgumentException(String.format("GDTI header [%s] is invalid. Allowed only 00101100 or 00111110", code));
+ }
+
+ return header;
+ }
+
+
+}
+
+
+
+package org.epctagcoder.option.GDTI;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+public enum GDTITagSize {
+ BITS_96(96) {
+ public Integer getHeader() {
+ return 44;
+ }
+ public Integer getSerialBitCount() {
+ return 41;
+ }
+ public Integer getSerialMaxLenght() {
+ return 13;
+ }
+ public Long getSerialMaxValue() { // confirmar isso
+ return 2_199_023_255_551L;
+
+ }
+ },
+ BITS_174(174) {
+ public Integer getHeader() {
+ return 62;
+ }
+ public Integer getSerialBitCount() {
+ return 119;
+ }
+ public Integer getSerialMaxLenght() {
+ return 17;
+ }
+ public Long getSerialMaxValue() {
+ return null; // not used
+ }
+ };
+
+ private int value;
+ public abstract Integer getHeader();
+ public abstract Integer getSerialBitCount();
+ public abstract Integer getSerialMaxLenght();
+ public abstract Long getSerialMaxValue();
+
+ private GDTITagSize(int value) {
+ this.value = value;
+ }
+
+ public int getValue() {
+ return value;
+ }
+
+ private static final Map BY_CODE_MAP = new LinkedHashMap<>();
+ static {
+ for (GDTITagSize rae : GDTITagSize.values()) {
+ BY_CODE_MAP.put(rae.value, rae);
+ }
+ }
+
+ public static GDTITagSize forCode(int code) {
+ return BY_CODE_MAP.get(code);
+ }
+
+
+}
+
+
+
+package org.epctagcoder.option.GDTI.partitionTable;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.epctagcoder.option.TableItem;
+
+
+public class GDTIPartitionTableList {
+ static final private List list = new ArrayList();
+
+ static {
+ list.add( new TableItem(0, 40, 12, 1, 0) );
+ list.add( new TableItem(1, 37, 11, 4, 1) );
+ list.add( new TableItem(2, 34, 10, 7, 2) );
+ list.add( new TableItem(3, 30, 9, 11, 3) );
+ list.add( new TableItem(4, 27, 8, 14, 4) );
+ list.add( new TableItem(5, 24, 7, 17, 5) );
+ list.add( new TableItem(6, 20, 6, 21, 6) );
+ }
+
+ public GDTIPartitionTableList() {
+
+ }
+
+
+ public TableItem getPartitionByL(Integer index) {
+ TableItem tableItem = null;
+ for (TableItem item : list) {
+ if (item.getL()==index) {
+ tableItem = item;
+ break;
+ }
+ }
+ return tableItem;
+ }
+
+ public TableItem getPartitionByValue(Integer index) {
+ TableItem tableItem = null;
+ for (TableItem item : list) {
+ if (item.getPartitionValue()==index) {
+ tableItem = item;
+ break;
+ }
+ }
+ return tableItem;
+ }
+
+
+}
+
+
+
+package org.epctagcoder.option.GIAI;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+public enum GIAIFilterValue {
+ ALL_OTHERS_0(0),
+ RESERVED_1(1),
+ RESERVED_2(2),
+ RESERVED_3(3),
+ RESERVED_4(4),
+ RESERVED_5(5),
+ RESERVED_6(6),
+ RESERVED_7(7);
+
+ private int value;
+
+ private GIAIFilterValue(int value) {
+ this.value = value;
+ }
+
+ public int getValue() {
+ return value;
+ }
+
+ private static final Map BY_CODE_MAP = new LinkedHashMap<>();
+ static {
+ for (GIAIFilterValue rae : GIAIFilterValue.values()) {
+ BY_CODE_MAP.put(rae.value, rae);
+ }
+ }
+
+ public static GIAIFilterValue forCode(int code) {
+ return BY_CODE_MAP.get(code);
+ }
+
+
+}
+
+
+
+package org.epctagcoder.option.GIAI;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+public enum GIAIHeader {
+ HEADER_00110100("00110100") {
+ public Integer getTagSize() {
+ return 96;
+ }
+ },
+ HEADER_00111000("00111000") {
+ public Integer getTagSize() {
+ return 202;
+ }
+ };
+
+ private String value;
+ public abstract Integer getTagSize();
+
+
+ private GIAIHeader(String value) {
+ this.value = value;
+ }
+
+ public String getValue() {
+ return value;
+ }
+
+ private static final Map BY_CODE_MAP = new LinkedHashMap<>();
+ static {
+ for (GIAIHeader rae : GIAIHeader.values()) {
+ BY_CODE_MAP.put(rae.value, rae);
+ }
+ }
+
+ public static GIAIHeader forCode(String code) {
+ return BY_CODE_MAP.get(code);
+ }
+
+
+}
+
+
+
+package org.epctagcoder.option.GIAI;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+public enum GIAITagSize {
+ BITS_96(96) {
+ public Integer getHeader() {
+ return 52;
+ }
+ public Integer getSerialBitCount() {
+ return 38;
+ }
+ public Integer getSerialMaxLenght() {
+ return 13;
+ }
+ },
+ BITS_202(202) {
+ public Integer getHeader() {
+ return 56;
+ }
+ public Integer getSerialBitCount() {
+ return 112;
+ }
+ public Integer getSerialMaxLenght() {
+ return 20;
+ }
+ };
+
+ private int value;
+ public abstract Integer getHeader();
+ public abstract Integer getSerialBitCount();
+ public abstract Integer getSerialMaxLenght();
+
+ private GIAITagSize(int value) {
+ this.value = value;
+ }
+
+ public int getValue() {
+ return value;
+ }
+
+ private static final Map BY_CODE_MAP = new LinkedHashMap<>();
+ static {
+ for (GIAITagSize rae : GIAITagSize.values()) {
+ BY_CODE_MAP.put(rae.value, rae);
+ }
+ }
+
+ public static GIAITagSize forCode(int code) {
+ return BY_CODE_MAP.get(code);
+ }
+
+
+}
+
+
+
+package org.epctagcoder.option.GIAI.partitionTable;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.epctagcoder.option.TableItem;
+import org.epctagcoder.option.GIAI.GIAITagSize;
+
+
+public class GIAIPartitionTableList {
+ static final private List list = new ArrayList();
+
+
+ public GIAIPartitionTableList(GIAITagSize tagSize) {
+ if ( tagSize.getValue()==96 ) {
+ list.clear();
+ list.add( new TableItem(0, 40, 12, 42, 13) );
+ list.add( new TableItem(1, 37, 11, 45, 14) );
+ list.add( new TableItem(2, 34, 10, 48, 15) );
+ list.add( new TableItem(3, 30, 9, 52, 16) );
+ list.add( new TableItem(4, 27, 8, 55, 17) );
+ list.add( new TableItem(5, 24, 7, 58, 18) );
+ list.add( new TableItem(6, 20, 6, 62, 19) );
+ } else if ( tagSize.getValue()==202 ) {
+ list.clear();
+ list.add( new TableItem(0, 40, 12, 148, 18) );
+ list.add( new TableItem(1, 37, 11, 151, 19) );
+ list.add( new TableItem(2, 34, 10, 154, 20) );
+ list.add( new TableItem(3, 30, 9, 158, 21) );
+ list.add( new TableItem(4, 27, 8, 161, 22) );
+ list.add( new TableItem(5, 24, 7, 164, 23) );
+ list.add( new TableItem(6, 20, 6, 168, 24) );
+ }
+
+
+ }
+
+ public TableItem getPartitionByL(Integer index) {
+ TableItem tableItem = null;
+ for (TableItem item : list) {
+ if (item.getL()==index) {
+ tableItem = item;
+ break;
+ }
+ }
+ return tableItem;
+ }
+
+ public TableItem getPartitionByValue(Integer index) {
+ TableItem tableItem = null;
+ for (TableItem item : list) {
+ if (item.getPartitionValue()==index) {
+ tableItem = item;
+ break;
+ }
+ }
+ return tableItem;
+ }
+
+
+}
+
+
+
+package org.epctagcoder.option.GRAI;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+public enum GRAIFilterValue {
+ ALL_OTHERS_0(0),
+ RESERVED_1(1),
+ RESERVED_2(2),
+ RESERVED_3(3),
+ RESERVED_4(4),
+ RESERVED_5(5),
+ RESERVED_6(6),
+ RESERVED_7(7);
+
+ private int value;
+
+ private GRAIFilterValue(int value) {
+ this.value = value;
+ }
+
+ public int getValue() {
+ return value;
+ }
+
+ private static final Map BY_CODE_MAP = new LinkedHashMap<>();
+ static {
+ for (GRAIFilterValue rae : GRAIFilterValue.values()) {
+ BY_CODE_MAP.put(rae.value, rae);
+ }
+ }
+
+ public static GRAIFilterValue forCode(int code) {
+ return BY_CODE_MAP.get(code);
+ }
+
+
+}
+
+
+
+package org.epctagcoder.option.GRAI;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+
+public enum GRAIHeader {
+ HEADER_00110011("00110011") {
+ public Integer getTagSize() {
+ return 96;
+ }
+ },
+ HEADER_00110111("00110111") {
+ public Integer getTagSize() {
+ return 170;
+ }
+ };
+
+ private String value;
+ public abstract Integer getTagSize();
+
+
+ private GRAIHeader(String value) {
+ this.value = value;
+ }
+
+ public String getValue() {
+ return value;
+ }
+
+ private static final Map BY_CODE_MAP = new LinkedHashMap<>();
+ static {
+ for (GRAIHeader rae : GRAIHeader.values()) {
+ BY_CODE_MAP.put(rae.value, rae);
+ }
+ }
+
+ public static GRAIHeader forCode(String code) {
+ GRAIHeader header = BY_CODE_MAP.get(code);
+
+ if (header==null) {
+ throw new IllegalArgumentException(String.format("GRAI header [%s] is invalid. Allowed only 00110011 or 00110111", code));
+ }
+
+ return header;
+ }
+
+
+}
+
+
+
+package org.epctagcoder.option.GRAI;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+public enum GRAITagSize {
+ BITS_96(96) {
+ public Integer getHeader() {
+ return 51;
+ }
+ public Integer getSerialBitCount() {
+ return 38;
+ }
+ public Integer getSerialMaxLenght() {
+ return 13;
+ }
+ public Long getSerialMaxValue() {
+ return 274_877_906_943L;
+ }
+ },
+ BITS_170(170) {
+ public Integer getHeader() {
+ return 55;
+ }
+ public Integer getSerialBitCount() {
+ return 112;
+ }
+ public Integer getSerialMaxLenght() {
+ return 16;
+ }
+ public Long getSerialMaxValue() {
+ return null; // not used
+ }
+ };
+
+ private int value;
+ public abstract Integer getHeader();
+ public abstract Integer getSerialBitCount();
+ public abstract Integer getSerialMaxLenght();
+ public abstract Long getSerialMaxValue();
+
+ private GRAITagSize(int value) {
+ this.value = value;
+ }
+
+ public int getValue() {
+ return value;
+ }
+
+ private static final Map BY_CODE_MAP = new LinkedHashMap<>();
+ static {
+ for (GRAITagSize rae : GRAITagSize.values()) {
+ BY_CODE_MAP.put(rae.value, rae);
+ }
+ }
+
+ public static GRAITagSize forCode(int code) {
+ return BY_CODE_MAP.get(code);
+ }
+
+
+}
+
+
+
+package org.epctagcoder.option.GRAI.partitionTable;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.epctagcoder.option.TableItem;
+
+
+public class GRAIPartitionTableList {
+ static final private List list = new ArrayList();
+
+ static {
+ list.add( new TableItem(0, 40, 12, 4, 0) );
+ list.add( new TableItem(1, 37, 11, 7, 1) );
+ list.add( new TableItem(2, 34, 10, 10, 2) );
+ list.add( new TableItem(3, 30, 9, 14, 3) );
+ list.add( new TableItem(4, 27, 8, 17, 4) );
+ list.add( new TableItem(5, 24, 7, 20, 5) );
+ list.add( new TableItem(6, 20, 6, 24, 6) );
+ }
+
+ public GRAIPartitionTableList() {
+
+ }
+
+
+ public TableItem getPartitionByL(Integer index) {
+ TableItem tableItem = null;
+ for (TableItem item : list) {
+ if (item.getL()==index) {
+ tableItem = item;
+ break;
+ }
+ }
+ return tableItem;
+ }
+
+ public TableItem getPartitionByValue(Integer index) {
+ TableItem tableItem = null;
+ for (TableItem item : list) {
+ if (item.getPartitionValue()==index) {
+ tableItem = item;
+ break;
+ }
+ }
+ return tableItem;
+ }
+
+
+}
+
+
+
+package org.epctagcoder.option.GSRN;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+public enum GSRNFilterValue {
+ ALL_OTHERS_0(0),
+ RESERVED_1(1),
+ RESERVED_2(2),
+ RESERVED_3(3),
+ RESERVED_4(4),
+ RESERVED_5(5),
+ RESERVED_6(6),
+ RESERVED_7(7);
+
+ private int value;
+
+ private GSRNFilterValue(int value) {
+ this.value = value;
+ }
+
+ public int getValue() {
+ return value;
+ }
+
+ private static final Map BY_CODE_MAP = new LinkedHashMap<>();
+ static {
+ for (GSRNFilterValue rae : GSRNFilterValue.values()) {
+ BY_CODE_MAP.put(rae.value, rae);
+ }
+ }
+
+ public static GSRNFilterValue forCode(int code) {
+ return BY_CODE_MAP.get(code);
+ }
+
+
+}
+
+
+
+package org.epctagcoder.option.GSRN;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+
+public enum GSRNHeader {
+ HEADER_00101101("00101101") {
+ public Integer getTagSize() {
+ return 96;
+ }
+ };
+
+ private String value;
+ public abstract Integer getTagSize();
+
+
+ private GSRNHeader(String value) {
+ this.value = value;
+ }
+
+ public String getValue() {
+ return value;
+ }
+
+ private static final Map BY_CODE_MAP = new LinkedHashMap<>();
+ static {
+ for (GSRNHeader rae : GSRNHeader.values()) {
+ BY_CODE_MAP.put(rae.value, rae);
+ }
+ }
+
+ public static GSRNHeader forCode(String code) {
+ GSRNHeader header = BY_CODE_MAP.get(code);
+
+ if (header==null) {
+ throw new IllegalArgumentException(String.format("GSRN header [%s] is invalid. Allowed only 00101101", code));
+ }
+
+ return header;
+ }
+
+
+}
+
+
+
+package org.epctagcoder.option.GSRN;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+public enum GSRNTagSize {
+ BITS_96(96) {
+ public Integer getHeader() {
+ return 45;
+ }
+ };
+
+ private int value;
+ public abstract Integer getHeader();
+
+ private GSRNTagSize(int value) {
+ this.value = value;
+ }
+
+ public int getValue() {
+ return value;
+ }
+
+ private static final Map BY_CODE_MAP = new LinkedHashMap<>();
+ static {
+ for (GSRNTagSize rae : GSRNTagSize.values()) {
+ BY_CODE_MAP.put(rae.value, rae);
+ }
+ }
+
+ public static GSRNTagSize forCode(int code) {
+ return BY_CODE_MAP.get(code);
+ }
+
+
+}
+
+
+
+package org.epctagcoder.option.GSRN.partitionTable;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.epctagcoder.option.TableItem;
+
+
+public class GSRNPartitionTableList {
+ static final private List list = new ArrayList();
+
+ static {
+ list.add( new TableItem(0, 40, 12, 18, 5) );
+ list.add( new TableItem(1, 37, 11, 21, 6) );
+ list.add( new TableItem(2, 34, 10, 24, 7) );
+ list.add( new TableItem(3, 30, 9, 28, 8) );
+ list.add( new TableItem(4, 27, 8, 31, 9) );
+ list.add( new TableItem(5, 24, 7, 34, 10) );
+ list.add( new TableItem(6, 20, 6, 38, 11) );
+ }
+
+ public GSRNPartitionTableList() {
+
+ }
+
+ public TableItem getPartitionByL(Integer index) {
+ TableItem tableItem = null;
+ for (TableItem item : list) {
+ if (item.getL()==index) {
+ tableItem = item;
+ break;
+ }
+ }
+ return tableItem;
+ }
+
+ public TableItem getPartitionByValue(Integer index) {
+ TableItem tableItem = null;
+ for (TableItem item : list) {
+ if (item.getPartitionValue()==index) {
+ tableItem = item;
+ break;
+ }
+ }
+ return tableItem;
+ }
+
+
+}
+
+
+
+package org.epctagcoder.option.GSRNP;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+public enum GSRNPFilterValue {
+ ALL_OTHERS_0(0),
+ RESERVED_1(1),
+ RESERVED_2(2),
+ RESERVED_3(3),
+ RESERVED_4(4),
+ RESERVED_5(5),
+ RESERVED_6(6),
+ RESERVED_7(7);
+
+ private int value;
+
+ private GSRNPFilterValue(int value) {
+ this.value = value;
+ }
+
+ public int getValue() {
+ return value;
+ }
+
+ private static final Map BY_CODE_MAP = new LinkedHashMap<>();
+ static {
+ for (GSRNPFilterValue rae : GSRNPFilterValue.values()) {
+ BY_CODE_MAP.put(rae.value, rae);
+ }
+ }
+
+ public static GSRNPFilterValue forCode(int code) {
+ return BY_CODE_MAP.get(code);
+ }
+
+
+}
+
+
+
+package org.epctagcoder.option.GSRNP;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+public enum GSRNPHeader {
+ HEADER_00101110("00101110") {
+ public Integer getTagSize() {
+ return 96;
+ }
+ };
+
+ private String value;
+ public abstract Integer getTagSize();
+
+
+ private GSRNPHeader(String value) {
+ this.value = value;
+ }
+
+ public String getValue() {
+ return value;
+ }
+
+ private static final Map BY_CODE_MAP = new LinkedHashMap<>();
+ static {
+ for (GSRNPHeader rae : GSRNPHeader.values()) {
+ BY_CODE_MAP.put(rae.value, rae);
+ }
+ }
+
+ public static GSRNPHeader forCode(String code) {
+ return BY_CODE_MAP.get(code);
+ }
+
+
+}
+
+
+
+package org.epctagcoder.option.GSRNP;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+public enum GSRNPTagSize {
+ BITS_96(96) {
+ public Integer getHeader() {
+ return 46;
+ }
+ };
+
+ private int value;
+ public abstract Integer getHeader();
+
+ private GSRNPTagSize(int value) {
+ this.value = value;
+ }
+
+ public int getValue() {
+ return value;
+ }
+
+ private static final Map BY_CODE_MAP = new LinkedHashMap<>();
+ static {
+ for (GSRNPTagSize rae : GSRNPTagSize.values()) {
+ BY_CODE_MAP.put(rae.value, rae);
+ }
+ }
+
+ public static GSRNPTagSize forCode(int code) {
+ return BY_CODE_MAP.get(code);
+ }
+
+
+}
+
+
+
+package org.epctagcoder.option.GSRNP.partitionTable;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.epctagcoder.option.TableItem;
+
+
+public class GSRNPPartitionTableList {
+ static final private List list = new ArrayList();
+
+ static {
+ list.add( new TableItem(0, 40, 12, 18, 5) );
+ list.add( new TableItem(1, 37, 11, 21, 6) );
+ list.add( new TableItem(2, 34, 10, 24, 7) );
+ list.add( new TableItem(3, 30, 9, 28, 8) );
+ list.add( new TableItem(4, 27, 8, 31, 9) );
+ list.add( new TableItem(5, 24, 7, 34, 10) );
+ list.add( new TableItem(6, 20, 6, 38, 11) );
+ }
+
+ public GSRNPPartitionTableList() {
+
+ }
+
+ public TableItem getPartitionByL(Integer index) {
+ TableItem tableItem = null;
+ for (TableItem item : list) {
+ if (item.getL()==index) {
+ tableItem = item;
+ break;
+ }
+ }
+ return tableItem;
+ }
+
+ public TableItem getPartitionByValue(Integer index) {
+ TableItem tableItem = null;
+ for (TableItem item : list) {
+ if (item.getPartitionValue()==index) {
+ tableItem = item;
+ break;
+ }
+ }
+ return tableItem;
+ }
+
+
+}
+
+
+
+package org.epctagcoder.option;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+public enum PrefixLength {
+ DIGIT_6(6),
+ DIGIT_7(7),
+ DIGIT_8(8),
+ DIGIT_9(9),
+ DIGIT_10(10),
+ DIGIT_11(11),
+ DIGIT_12(12);
+
+ private int value;
+
+ private PrefixLength(int value) {
+ this.value = value;
+ }
+
+ public int getValue() {
+ return value;
+ }
+
+
+ private static final Map BY_CODE_MAP = new LinkedHashMap<>();
+ static {
+ for (PrefixLength rae : PrefixLength.values()) {
+ BY_CODE_MAP.put(rae.value, rae);
+ }
+ }
+
+ public static PrefixLength forCode(int code) {
+ return BY_CODE_MAP.get(code);
+ }
+
+}
+
+
+
+package org.epctagcoder.option.SGLN.partitionTable;
+
+import org.epctagcoder.option.TableItem;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public class SGLNPartitionTableList {
+ static final private List list = new ArrayList();
+
+ static {
+ list.add( new TableItem(0, 40, 12, 1, 0) );
+ list.add( new TableItem(1, 37, 11, 4, 1) );
+ list.add( new TableItem(2, 34, 10, 7, 2) );
+ list.add( new TableItem(3, 30, 9, 11, 3) );
+ list.add( new TableItem(4, 27, 8, 14, 4) );
+ list.add( new TableItem(5, 24, 7, 17, 5) );
+ list.add( new TableItem(6, 20, 6, 21, 6) );
+ }
+
+ public SGLNPartitionTableList() {
+
+ }
+
+
+ public TableItem getPartitionByL(Integer index) {
+ TableItem tableItem = null;
+ for (TableItem item : list) {
+ if (item.getL()==index) {
+ tableItem = item;
+ break;
+ }
+ }
+ return tableItem;
+ }
+
+ public TableItem getPartitionByValue(Integer index) {
+ TableItem tableItem = null;
+ for (TableItem item : list) {
+ if (item.getPartitionValue()==index) {
+ tableItem = item;
+ break;
+ }
+ }
+ return tableItem;
+ }
+}
+
+
+
+package org.epctagcoder.option.SGLN;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+public enum SGLNFilterValue {
+
+ ALL_OTHERS_0(0),
+ RESERVED_1(1),
+ RESERVED_2(2),
+ RESERVED_3(3),
+ RESERVED_4(4),
+ RESERVED_5(5),
+ RESERVED_6(6),
+ RESERVED_7(7);
+
+ private static final Map BY_CODE_MAP = new LinkedHashMap<>();
+
+ static {
+ for (SGLNFilterValue rae : SGLNFilterValue.values()) {
+ BY_CODE_MAP.put(rae.value, rae);
+ }
+ }
+
+ private int value;
+
+ private SGLNFilterValue(int value) {
+ this.value = value;
+ }
+
+ public static SGLNFilterValue forCode(int code) {
+ return BY_CODE_MAP.get(code);
+ }
+
+ public int getValue() {
+ return this.value;
+ }
+}
+
+
+
+package org.epctagcoder.option.SGLN;
+
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+public enum SGLNHeader {
+
+ HEADER_00110010("00110010") {
+ public Integer getTagSize() {
+ return 96;
+ }
+ },
+ HEADER_00111001("00111001") {
+ public Integer getTagSize() {
+ return 195;
+ }
+ };
+
+ private String value;
+ public abstract Integer getTagSize();
+
+
+ private SGLNHeader(String value) {
+ this.value = value;
+ }
+
+ public String getValue() {
+ return value;
+ }
+
+ private static final Map BY_CODE_MAP = new LinkedHashMap<>();
+ static {
+ for (SGLNHeader rae : SGLNHeader.values()) {
+ BY_CODE_MAP.put(rae.value, rae);
+ }
+ }
+
+ public static SGLNHeader forCode(String code) {
+ SGLNHeader header = BY_CODE_MAP.get(code);
+
+ if (header==null) {
+ throw new IllegalArgumentException(String.format("SGLN header [%s] is invalid. Allowed only 00110010 or 00111001", code));
+ }
+
+ return header;
+ }
+}
+
+
+
+package org.epctagcoder.option.SGLN;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+public enum SGLNTagSize {
+
+ BITS_96(96) {
+ @Override
+ public Integer getHeader() {
+ return 51;
+ }
+
+ @Override
+ public Integer getSerialBitCount() {
+ return 41;
+ }
+
+ @Override
+ public Integer getSerialMaxLenght() {
+ return 13;
+ }
+
+ @Override
+ public Long getSerialMaxValue() {
+ return 2_199_023_255_551L;
+ }
+ },
+ BITS_195(195) {
+ @Override
+ public Integer getHeader() {
+ return 55;
+ }
+
+ @Override
+ public Integer getSerialBitCount() {
+ return 140;
+ }
+
+ @Override
+ public Integer getSerialMaxLenght() {
+ return 20;
+ }
+
+ @Override
+ public Long getSerialMaxValue() {
+ return null; // not used
+ }
+ };
+
+ private static final Map BY_CODE_MAP = new LinkedHashMap<>();
+
+ static {
+ for (SGLNTagSize rae : SGLNTagSize.values()) {
+ BY_CODE_MAP.put(rae.value, rae);
+ }
+ }
+
+
+ private int value;
+
+ private SGLNTagSize(int value) {
+ this.value = value;
+ }
+
+ public static SGLNTagSize forCode(int code) {
+ return BY_CODE_MAP.get(code);
+ }
+
+ public abstract Integer getHeader();
+
+ public abstract Integer getSerialBitCount();
+
+ public abstract Integer getSerialMaxLenght();
+
+ public abstract Long getSerialMaxValue();
+
+ public int getValue() {
+ return value;
+ }
+}
+
+
+
+package org.epctagcoder.option.SGTIN.partitionTable;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.epctagcoder.exception.EPCParseException;
+import org.epctagcoder.option.TableItem;
+
+
+public class SGTINPartitionTableList {
+ static final private List list = new ArrayList<>();
+
+ static {
+ list.add( new TableItem(0, 40, 12, 4, 1) );
+ list.add( new TableItem(1, 37, 11, 7, 2) );
+ list.add( new TableItem(2, 34, 10, 10, 3) );
+ list.add( new TableItem(3, 30, 9, 14, 4) );
+ list.add( new TableItem(4, 27, 8, 17, 5) );
+ list.add( new TableItem(5, 24, 7, 20, 6) );
+ list.add( new TableItem(6, 20, 6, 24, 7) );
+ }
+
+ public SGTINPartitionTableList() {
+
+ }
+
+
+ public TableItem getPartitionByL(Integer index) {
+ TableItem tableItem = null;
+ for (TableItem item : list) {
+ if (item.getL()==index) {
+ tableItem = item;
+ break;
+ }
+ }
+ return tableItem;
+ }
+
+ public TableItem getPartitionByValue(int index) throws EPCParseException {
+ if(index < 0 || index >= list.size()) {
+ String message = "Partition value %d is not within expected range (0 - %d)";
+ throw new EPCParseException(String.format(message, index, list.size() - 1));
+ }
+
+ return list.get(index);
+ }
+
+
+}
+
+
+
+package org.epctagcoder.option.SGTIN;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+public enum SGTINExtensionDigit {
+ EXTENSION_0(0),
+ EXTENSION_1(1),
+ EXTENSION_2(2),
+ EXTENSION_3(3),
+ EXTENSION_4(4),
+ EXTENSION_5(5),
+ EXTENSION_6(6),
+ EXTENSION_7(7),
+ EXTENSION_8(8),
+ EXTENSION_9(9);
+
+ private int value;
+
+ private SGTINExtensionDigit(int value) {
+ this.value = value;
+ }
+
+ public int getValue() {
+ return value;
+ }
+
+ private static final Map BY_CODE_MAP = new LinkedHashMap<>();
+ static {
+ for (SGTINExtensionDigit rae : SGTINExtensionDigit.values()) {
+ BY_CODE_MAP.put(rae.value, rae);
+ }
+ }
+
+ public static SGTINExtensionDigit forCode(int code) {
+ return BY_CODE_MAP.get(code);
+ }
+
+
+
+
+}
+
+
+
+package org.epctagcoder.option.SGTIN;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+public enum SGTINFilterValue {
+ ALL_OTHERS_0(0),
+ POS_ITEM_1(1),
+ CASE_2(2),
+ RESERVED_3(3),
+ INNER_PACK_4(4),
+ RESERVED_5(5),
+ UNIT_LOAD_6(6),
+ COMPONENT_7(7);
+
+ private int value;
+
+ private SGTINFilterValue(int value) {
+ this.value = value;
+ }
+
+ public int getValue() {
+ return value;
+ }
+
+ private static final Map BY_CODE_MAP = new LinkedHashMap<>();
+ static {
+ for (SGTINFilterValue rae : SGTINFilterValue.values()) {
+ BY_CODE_MAP.put(rae.value, rae);
+ }
+ }
+
+ public static SGTINFilterValue forCode(int code) {
+ return BY_CODE_MAP.get(code);
+ }
+
+
+}
+
+
+
+package org.epctagcoder.option.SGTIN;
+
+import org.epctagcoder.exception.EPCParseException;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+public enum SGTINHeader {
+ HEADER_00110000("00110000") {
+ public Integer getTagSize() {
+ return 96;
+ }
+ },
+ HEADER_00110110("00110110") {
+ public Integer getTagSize() {
+ return 198;
+ }
+ };
+
+ private final String value;
+ public abstract Integer getTagSize();
+
+
+ SGTINHeader(String value) {
+ this.value = value;
+ }
+
+ public String getValue() {
+ return value;
+ }
+
+ private static final Map BY_CODE_MAP = new LinkedHashMap<>();
+ static {
+ for (SGTINHeader rae : SGTINHeader.values()) {
+ BY_CODE_MAP.put(rae.value, rae);
+ }
+ }
+
+ public static SGTINHeader forCode(String code) throws EPCParseException {
+ SGTINHeader header = BY_CODE_MAP.get(code);
+
+ if (header==null) {
+ throw new EPCParseException(String.format("SGTIN header [%s] is invalid. Allowed only 00110000 or 00110110", code));
+ }
+
+ return header;
+ }
+
+
+}
+
+
+
+package org.epctagcoder.option.SGTIN;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+public enum SGTINTagSize {
+ BITS_96(96) {
+ public Integer getHeader() {
+ return 48;
+ }
+ public Integer getSerialBitCount() {
+ return 38;
+ }
+ public Integer getSerialMaxLenght() {
+ return 11;
+ }
+ public Long getSerialMaxValue() {
+ return 274_877_906_943L;
+ }
+ },
+ BITS_198(198) {
+ public Integer getHeader() {
+ return 54;
+ }
+ public Integer getSerialBitCount() {
+ return 140;
+ }
+ public Integer getSerialMaxLenght() {
+ return 20;
+ }
+ public Long getSerialMaxValue() {
+ return null; // not used
+ }
+ };
+
+ private int value;
+ public abstract Integer getHeader();
+ public abstract Integer getSerialBitCount();
+ public abstract Integer getSerialMaxLenght();
+ public abstract Long getSerialMaxValue();
+
+ private SGTINTagSize(int value) {
+ this.value = value;
+ }
+
+ public int getValue() {
+ return value;
+ }
+
+ private static final Map BY_CODE_MAP = new LinkedHashMap<>();
+ static {
+ for (SGTINTagSize rae : SGTINTagSize.values()) {
+ BY_CODE_MAP.put(rae.value, rae);
+ }
+ }
+
+ public static SGTINTagSize forCode(int code) {
+ SGTINTagSize bits = BY_CODE_MAP.get(code);
+
+ if (bits==null) {
+ throw new IllegalArgumentException(String.format("SGTIN tag size %d is invalid. Only 96 bits or 198 bits supported.", code));
+ }
+
+ return bits;
+ }
+
+
+}
+
+
+
+package org.epctagcoder.option.SSCC.partitionTable;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.epctagcoder.option.TableItem;
+
+
+public class SSCCPartitionTableList {
+ static final private List list = new ArrayList();
+
+ static {
+ list.add( new TableItem(0, 40, 12, 18, 5) );
+ list.add( new TableItem(1, 37, 11, 21, 6) );
+ list.add( new TableItem(2, 34, 10, 24, 7) );
+ list.add( new TableItem(3, 30, 9, 28, 8) );
+ list.add( new TableItem(4, 27, 8, 31, 9) );
+ list.add( new TableItem(5, 24, 7, 34, 10) );
+ list.add( new TableItem(6, 20, 6, 38, 11) );
+ }
+
+ public SSCCPartitionTableList() {
+
+ }
+
+ public TableItem getPartitionByL(Integer index) {
+ TableItem tableItem = null;
+ for (TableItem item : list) {
+ if (item.getL()==index) {
+ tableItem = item;
+ break;
+ }
+ }
+ return tableItem;
+ }
+
+ public TableItem getPartitionByValue(Integer index) {
+ TableItem tableItem = null;
+ for (TableItem item : list) {
+ if (item.getPartitionValue()==index) {
+ tableItem = item;
+ break;
+ }
+ }
+ return tableItem;
+ }
+
+
+}
+
+
+
+package org.epctagcoder.option.SSCC;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+public enum SSCCExtensionDigit {
+ EXTENSION_0(0),
+ EXTENSION_1(1),
+ EXTENSION_2(2),
+ EXTENSION_3(3),
+ EXTENSION_4(4),
+ EXTENSION_5(5),
+ EXTENSION_6(6),
+ EXTENSION_7(7),
+ EXTENSION_8(8),
+ EXTENSION_9(9);
+
+ private int value;
+
+ private SSCCExtensionDigit(int value) {
+ this.value = value;
+ }
+
+ public int getValue() {
+ return value;
+ }
+
+ private static final Map BY_CODE_MAP = new LinkedHashMap<>();
+ static {
+ for (SSCCExtensionDigit rae : SSCCExtensionDigit.values()) {
+ BY_CODE_MAP.put(rae.value, rae);
+ }
+ }
+
+ public static SSCCExtensionDigit forCode(int code) {
+ return BY_CODE_MAP.get(code);
+ }
+
+
+
+
+}
+
+
+
+package org.epctagcoder.option.SSCC;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+public enum SSCCFilterValue {
+ ALL_OTHERS_0(0),
+ RESERVED_1(1),
+ CASE_2(2),
+ RESERVED_3(3),
+ RESERVED_4(4),
+ RESERVED_5(5),
+ UNIT_LOAD_6(6),
+ RESERVED_7(7);
+
+ private int value;
+
+ private SSCCFilterValue(int value) {
+ this.value = value;
+ }
+
+ public int getValue() {
+ return value;
+ }
+
+ private static final Map BY_CODE_MAP = new LinkedHashMap<>();
+ static {
+ for (SSCCFilterValue rae : SSCCFilterValue.values()) {
+ BY_CODE_MAP.put(rae.value, rae);
+ }
+ }
+
+ public static SSCCFilterValue forCode(int code) {
+ return BY_CODE_MAP.get(code);
+ }
+
+
+}
+
+
+
+package org.epctagcoder.option.SSCC;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+public enum SSCCHeader {
+ HEADER_00110001("00110001") {
+ public Integer getTagSize() {
+ return 96;
+ }
+ };
+
+ private String value;
+ public abstract Integer getTagSize();
+
+
+ private SSCCHeader(String value) {
+ this.value = value;
+ }
+
+ public String getValue() {
+ return value;
+ }
+
+ private static final Map BY_CODE_MAP = new LinkedHashMap<>();
+ static {
+ for (SSCCHeader rae : SSCCHeader.values()) {
+ BY_CODE_MAP.put(rae.value, rae);
+ }
+ }
+
+ public static SSCCHeader forCode(String code) {
+ SSCCHeader header = BY_CODE_MAP.get(code);
+
+ if (header==null) {
+ throw new IllegalArgumentException(String.format("SSCC header [%s] is invalid. Allowed only 00110001", code));
+ }
+
+ return header;
+ }
+
+
+}
+
+
+
+package org.epctagcoder.option.SSCC;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+public enum SSCCTagSize {
+ BITS_96(96) {
+ public Integer getHeader() {
+ return 49;
+ }
+ };
+
+ private int value;
+ public abstract Integer getHeader();
+
+ private SSCCTagSize(int value) {
+ this.value = value;
+ }
+
+ public int getValue() {
+ return value;
+ }
+
+ private static final Map BY_CODE_MAP = new LinkedHashMap<>();
+ static {
+ for (SSCCTagSize rae : SSCCTagSize.values()) {
+ BY_CODE_MAP.put(rae.value, rae);
+ }
+ }
+
+ public static SSCCTagSize forCode(int code) {
+ return BY_CODE_MAP.get(code);
+ }
+
+
+}
+
+
+
+package org.epctagcoder.option;
+
+public class TableItem {
+ private int partitionValue;
+ private int l;
+ private int m;
+ private int n;
+ private int digits;
+
+
+ public TableItem(int partitionValue, int m, int l, int n, int digits) {
+ this.partitionValue = partitionValue;
+ this.m = m;
+ this.l = l;
+ this.n = n;
+ this.digits = digits;
+ }
+
+
+ public int getPartitionValue() {
+ return partitionValue;
+ }
+
+
+ public void setPartitionValue(int partitionValue) {
+ this.partitionValue = partitionValue;
+ }
+
+
+ public int getL() {
+ return l;
+ }
+
+
+ public void setL(int l) {
+ this.l = l;
+ }
+
+
+ public int getM() {
+ return m;
+ }
+
+
+ public void setM(int m) {
+ this.m = m;
+ }
+
+
+ public int getN() {
+ return n;
+ }
+
+
+ public void setN(int n) {
+ this.n = n;
+ }
+
+
+ public int getDigits() {
+ return digits;
+ }
+
+
+ public void setDigits(int digits) {
+ this.digits = digits;
+ }
+
+
+
+
+
+
+
+}
+
+
+
+package org.epctagcoder.parse.CPI;
+
+import java.util.List;
+import java.util.Optional;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+
+import org.epctagcoder.option.PrefixLength;
+import org.epctagcoder.option.TableItem;
+import org.epctagcoder.option.CPI.CPIFilterValue;
+import org.epctagcoder.option.CPI.CPIHeader;
+import org.epctagcoder.option.CPI.CPITagSize;
+import org.epctagcoder.option.CPI.partitionTable.CPIPartitionTableList;
+import org.epctagcoder.result.CPI;
+import org.epctagcoder.util.Converter;
+
+
+public class ParseCPI {
+ private CPI cpi = new CPI();
+ private String companyPrefix;
+ private PrefixLength prefixLength;
+ private CPITagSize tagSize;
+ private CPIFilterValue filterValue;
+ private String componentPartReference;
+ private String serial;
+ private String rfidTag;
+ private String epcTagURI;
+ private String epcPureIdentityURI;
+ private TableItem tableItem;
+ private int remainder;
+
+ public static ChoiceStep Builder() throws Exception {
+ return new Steps();
+ }
+
+ private ParseCPI(Steps steps) {
+ this.companyPrefix = steps.companyPrefix;
+ this.tagSize = steps.tagSize;
+ this.filterValue = steps.filterValue;
+ this.componentPartReference = steps.componentPartReference;
+ this.serial = steps.serial;
+ this.rfidTag = steps.rfidTag;
+ this.epcTagURI = steps.epcTagURI;
+ this.epcPureIdentityURI = steps.epcPureIdentityURI;
+ parse();
+ }
+
+
+
+ private void parse() {
+ Optional optionalCompanyPrefix = Optional.ofNullable(companyPrefix);
+ Optional optionalRfidTag = Optional.ofNullable(rfidTag);
+ Optional optionalEpcTagURI = Optional.ofNullable(epcTagURI);
+ Optional optionalEpcPureIdentityURI = Optional.ofNullable(epcPureIdentityURI);
+
+ if ( optionalRfidTag.isPresent() ) {
+ String inputBin = Converter.hexToBin(rfidTag);
+ String headerBin = inputBin.substring(0, 8);
+ String filterBin = inputBin.substring(8,11);
+ String partitionBin = inputBin.substring(11,14);
+
+ tagSize = CPITagSize.forCode(CPIHeader.forCode(headerBin).getTagSize());
+ CPIPartitionTableList cpiPartitionTableList = new CPIPartitionTableList(tagSize);
+ tableItem = cpiPartitionTableList.getPartitionByValue( Integer.parseInt(partitionBin, 2) );
+
+ String filterDec = Long.toString( Long.parseLong(filterBin, 2) );
+ String companyPrefixBin = inputBin.substring(14, 14+tableItem.getM());
+ String componentPartReferenceBin = null;
+ String serialBin = null;
+
+ if (tagSize.getValue()==0) { // variable
+ String componentPartReferenceAndSerialBin = inputBin.substring(14+tableItem.getM() );
+
+ StringBuilder decodeComponentPartReference = new StringBuilder();
+ List splitCPR = Converter.splitEqually(componentPartReferenceAndSerialBin, 6);
+ for (String item : splitCPR) {
+ if ( item.equals("000000") ) {
+ break;
+ }
+ decodeComponentPartReference.append(item);
+ }
+
+ componentPartReferenceBin = decodeComponentPartReference.toString();
+ int posSerial = 14+tableItem.getM()+componentPartReferenceBin.length()+6;
+ componentPartReferenceBin = Converter.convertBinToBit(componentPartReferenceBin, 6, 8);
+ componentPartReference = Converter.binToString(componentPartReferenceBin);
+ serialBin = inputBin.substring(posSerial, posSerial+tagSize.getSerialBitCount());
+ } else if (tagSize.getValue()==96) {
+ componentPartReferenceBin = inputBin.substring(14+tableItem.getM(),14+tableItem.getM()+tableItem.getN());
+ componentPartReference = Converter.binToDec(componentPartReferenceBin);
+ serialBin = inputBin.substring(14+tableItem.getM()+tableItem.getN() );
+ }
+
+
+ String companyPrefixDec = Converter.binToDec(companyPrefixBin);
+ serial = Converter.binToDec(serialBin);
+ companyPrefix = Converter.strZero(companyPrefixDec, tableItem.getL()); // strzero aqui
+ filterValue = CPIFilterValue.forCode( Integer.parseInt(filterDec) );
+ prefixLength = PrefixLength.forCode(tableItem.getL());
+ } else {
+
+ if ( optionalCompanyPrefix.isPresent() ) {
+ CPIPartitionTableList sgtinPartitionTableList = new CPIPartitionTableList(tagSize);
+ prefixLength = PrefixLength.forCode( companyPrefix.length() );
+
+ validateCompanyPrefix();
+
+ tableItem = sgtinPartitionTableList.getPartitionByL( prefixLength.getValue() );
+
+ validateComponentPartReference();
+ validateSerial();
+
+ } else {
+
+ if ( optionalEpcTagURI.isPresent() ) {
+ Pattern pattern = Pattern.compile("(urn:epc:tag:cpi-)(96|var)\\:([0-7])\\.(\\d+)\\.(\\d+)\\.(\\w+)");
+
+ Matcher matcher = pattern.matcher(epcTagURI);
+
+ if ( matcher.matches() ) {
+ if ( matcher.group(2).equals("var") ) {
+ tagSize = CPITagSize.forCode( 0 );
+ } else {
+ tagSize = CPITagSize.forCode( Integer.parseInt(matcher.group(2)) );
+ }
+
+ filterValue = CPIFilterValue.forCode( Integer.parseInt(matcher.group(3)) );
+ companyPrefix = matcher.group(4);
+ prefixLength = PrefixLength.forCode( matcher.group(4).length() );
+ componentPartReference = matcher.group(5);
+ serial = matcher.group(6);
+ } else {
+ throw new IllegalArgumentException("EPC Tag URI is invalid");
+ }
+
+ } else if ( optionalEpcPureIdentityURI.isPresent() ) {
+ Pattern pattern = Pattern.compile("(urn:epc:id:cpi)\\:(\\d+)\\.(\\d+)\\.(\\w+)");
+ Matcher matcher = pattern.matcher(epcPureIdentityURI);
+
+ if ( matcher.matches() ) {
+ companyPrefix = matcher.group(2);
+ prefixLength = PrefixLength.forCode( matcher.group(2).length() );
+ componentPartReference = matcher.group(3);;
+ serial = matcher.group(4);
+ } else {
+ throw new IllegalArgumentException("EPC Pure Identity is invalid");
+ }
+ }
+
+ }
+
+ CPIPartitionTableList sgtinPartitionTableList = new CPIPartitionTableList(tagSize);
+ tableItem = sgtinPartitionTableList.getPartitionByL( prefixLength.getValue() );
+
+ }
+
+ String outputBin = getBinary();
+ String outputHex = Converter.binToHex( outputBin );
+
+ cpi.setEpcScheme("cpi");
+ cpi.setApplicationIdentifier("AI 8010 + AI 8011");
+ cpi.setTagSize( (tagSize.getValue()==0) ? "var" : Integer.toString(tagSize.getValue()) );
+ cpi.setFilterValue(Integer.toString(filterValue.getValue()));
+ cpi.setPartitionValue(Integer.toString(tableItem.getPartitionValue()));
+ cpi.setPrefixLength(Integer.toString(prefixLength.getValue()));
+ cpi.setCompanyPrefix(companyPrefix);
+ cpi.setComponentPartReference(componentPartReference);
+ cpi.setSerial(serial);
+ cpi.setEpcPureIdentityURI(String.format("urn:epc:id:cpi:%s.%s.%s", companyPrefix, componentPartReference, serial));
+ cpi.setEpcTagURI(String.format("urn:epc:tag:cpi-%s:%s.%s.%s.%s", (tagSize.getValue()==0) ? "var" : tagSize.getValue(), filterValue.getValue(), companyPrefix, componentPartReference, serial));
+ cpi.setEpcRawURI(String.format("urn:epc:raw:%s.x%s", outputBin.length(), outputHex ));
+ cpi.setBinary(outputBin);
+ cpi.setRfidTag(outputHex);
+ }
+
+
+ private String getBinary() {
+ StringBuilder bin = new StringBuilder();
+
+ bin.append( Converter.decToBin(tagSize.getHeader(), 8) );
+ bin.append( Converter.decToBin(filterValue.getValue(), 3) );
+ bin.append( Converter.decToBin(tableItem.getPartitionValue(), 3) );
+ bin.append( Converter.decToBin(Integer.parseInt(companyPrefix), tableItem.getM()) );
+
+ if (tagSize.getValue()==0) { // variable
+ bin.append( Converter.StringToBinary(componentPartReference, 6) );
+ bin.append("000000");
+ } else if (tagSize.getValue()==96) {
+ bin.append( Converter.decToBin(Integer.parseInt(componentPartReference), tableItem.getN()) );
+ }
+
+ bin.append( Converter.decToBin(serial, tagSize.getSerialBitCount() ) );
+ remainder = (int) (Math.ceil((bin.length()/16.0))*16)-bin.length();
+ bin.append( Converter.fill("0", remainder) );
+
+ return bin.toString();
+ }
+
+
+
+ public CPI getCPI() {
+ return cpi;
+ }
+
+ public String getRfidTag() {
+ return Converter.binToHex( getBinary() );
+ }
+
+
+
+ private void validateCompanyPrefix() {
+ Optional optionalPefixLenght = Optional.ofNullable(prefixLength);
+ if ( !optionalPefixLenght.isPresent() ) {
+ throw new IllegalArgumentException("Company Prefix is invalid. Length not found in the partition table");
+ }
+ }
+
+
+
+ private void validateComponentPartReference() {
+
+ if ( !Converter.isNumeric(componentPartReference) ) {
+ throw new IllegalArgumentException("Component/Part Reference is allowed with numerical only");
+ }
+
+ if ( componentPartReference.length()>tableItem.getDigits() ) {
+ throw new IllegalArgumentException("Component/Part Reference is out of range");
+ }
+
+
+ if (tagSize.getValue()==96 ) {
+ if ( componentPartReference.startsWith("0") ) {
+ throw new IllegalArgumentException("Component/Part Reference with leading zeros is not allowed");
+ }
+
+ }
+
+ }
+
+ private void validateSerial() {
+
+ if ( serial.startsWith("0") ) {
+ throw new IllegalArgumentException("Serial with leading zeros is not allowed");
+ }
+
+ if (tagSize.getValue()==0 ) { // variable
+ if ( serial.length()>tagSize.getSerialMaxLenght() ) {
+ throw new IllegalArgumentException( String.format("Serial value is out of range. Should be up to %d alphanumeric characters",
+ tagSize.getSerialMaxLenght() ));
+ }
+ } else if (tagSize.getValue()==96 ) {
+
+ if ( !Converter.isNumeric(serial) ) {
+ throw new IllegalArgumentException("Serial value is allowed with numerical only");
+ }
+
+ if ( Long.parseLong(serial)>tagSize.getSerialMaxValue() ) {
+ throw new IllegalArgumentException( String.format("Serial value is out of range. Should be less than or equal %d",
+ tagSize.getSerialMaxValue() ));
+ }
+ }
+
+ }
+
+
+
+ public static interface ChoiceStep {
+ componentPartReferenceStep withCompanyPrefix(String companyPrefix);
+ BuildStep withRFIDTag(String rfidTag);
+ BuildStep withEPCTagURI(String epcTagURI);
+ TagSizeStep withEPCPureIdentityURI(String epcPureIdentityURI);
+ }
+
+
+ public static interface componentPartReferenceStep {
+ serialStep withComponentPartReference(String componentPartReference);
+ }
+
+ public static interface serialStep {
+ TagSizeStep withSerial(String serial);
+ }
+
+ public static interface TagSizeStep {
+ FilterValueStep withTagSize( CPITagSize tagSize );
+ }
+
+ public static interface FilterValueStep {
+ BuildStep withFilterValue( CPIFilterValue filterValue );
+ }
+
+ public static interface BuildStep {
+ ParseCPI build();
+ }
+
+
+ private static class Steps implements ChoiceStep, componentPartReferenceStep, serialStep, TagSizeStep, FilterValueStep, BuildStep {
+ private String companyPrefix;
+ private CPITagSize tagSize;
+ private CPIFilterValue filterValue;
+ private String componentPartReference;
+ private String serial;
+ private String rfidTag;
+ private String epcTagURI;
+ private String epcPureIdentityURI;
+
+ @Override
+ public ParseCPI build() {
+ return new ParseCPI(this);
+ }
+
+ @Override
+ public BuildStep withFilterValue(CPIFilterValue filterValue) {
+ this.filterValue = filterValue;
+ return this;
+ }
+
+ @Override
+ public FilterValueStep withTagSize(CPITagSize tagSize) {
+ this.tagSize = tagSize;
+ return this;
+ }
+
+ @Override
+ public TagSizeStep withSerial(String serial) {
+ this.serial = serial;
+ return this;
+ }
+
+ @Override
+ public serialStep withComponentPartReference(String componentPartReference) {
+ this.componentPartReference = componentPartReference;
+ return this;
+ }
+
+ @Override
+ public componentPartReferenceStep withCompanyPrefix(String companyPrefix) {
+ this.companyPrefix = companyPrefix;
+ return this;
+ }
+
+ @Override
+ public BuildStep withRFIDTag(String rfidTag) {
+ this.rfidTag = rfidTag;
+ return this;
+ }
+
+ @Override
+ public BuildStep withEPCTagURI(String epcTagURI) {
+ this.epcTagURI = epcTagURI;
+ return this;
+ }
+
+ @Override
+ public TagSizeStep withEPCPureIdentityURI(String epcPureIdentityURI) {
+ this.epcPureIdentityURI = epcPureIdentityURI;
+ return this;
+ }
+
+ }
+
+}
+
+
+
+package org.epctagcoder.parse.GDTI;
+
+import java.util.Optional;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import org.epctagcoder.option.PrefixLength;
+import org.epctagcoder.option.TableItem;
+import org.epctagcoder.option.GDTI.GDTIFilterValue;
+import org.epctagcoder.option.GDTI.GDTIHeader;
+import org.epctagcoder.option.GDTI.GDTITagSize;
+import org.epctagcoder.option.GDTI.partitionTable.GDTIPartitionTableList;
+import org.epctagcoder.result.GDTI;
+import org.epctagcoder.util.Converter;
+
+
+public class ParseGDTI {
+ private GDTI gdti = new GDTI();
+ private String companyPrefix;
+ private PrefixLength prefixLength;
+ private GDTITagSize tagSize;
+ private GDTIFilterValue filterValue;
+ private String docType;
+ private String serial;
+ private String rfidTag;
+ private String epcTagURI;
+ private String epcPureIdentityURI;
+ private TableItem tableItem;
+ private int remainder;
+
+ public static ChoiceStep Builder() throws Exception {
+ return new Steps();
+ }
+
+ private ParseGDTI(Steps steps) {
+ this.companyPrefix = steps.companyPrefix;
+ this.tagSize = steps.tagSize;
+ this.filterValue = steps.filterValue;
+ this.docType = steps.docType;
+ this.serial = steps.serial;
+ this.rfidTag = steps.rfidTag;
+ this.epcTagURI = steps.epcTagURI;
+ this.epcPureIdentityURI = steps.epcPureIdentityURI;
+ parse();
+ }
+
+
+
+ private void parse() {
+ Optional optionalCompanyPrefix = Optional.ofNullable(companyPrefix);
+ Optional optionalRfidTag = Optional.ofNullable(rfidTag);
+ Optional optionalEpcTagURI = Optional.ofNullable(epcTagURI);
+ Optional optionalEpcPureIdentityURI = Optional.ofNullable(epcPureIdentityURI);
+
+ if ( optionalRfidTag.isPresent() ) {
+ String inputBin = Converter.hexToBin(rfidTag);
+ String headerBin = inputBin.substring(0, 8);
+ String filterBin = inputBin.substring(8,11);
+ String partitionBin = inputBin.substring(11,14);
+ GDTIPartitionTableList graiPartitionTableList = new GDTIPartitionTableList();
+
+ tagSize = GDTITagSize.forCode(GDTIHeader.forCode(headerBin).getTagSize());
+ tableItem = graiPartitionTableList.getPartitionByValue( Integer.parseInt(partitionBin, 2) );
+
+ String filterDec = Long.toString( Long.parseLong(filterBin, 2) );
+ String companyPrefixBin = inputBin.substring(14,14+tableItem.getM());
+ String docTypeBin = inputBin.substring(14+tableItem.getM(),14+tableItem.getM()+tableItem.getN());
+ String serialBin = inputBin.substring(14+tableItem.getM()+tableItem.getN() );
+
+ String companyPrefixDec = Converter.binToDec(companyPrefixBin);
+ String docTypeDec = Converter.binToDec(docTypeBin);
+
+ docType = Converter.strZero(docTypeDec, tableItem.getDigits() ) ;
+
+ if (tagSize.getSerialBitCount()==119) {
+ serialBin = Converter.convertBinToBit(serialBin, 7, 8);
+ serial = Converter.binToString(serialBin);
+ } else if (tagSize.getSerialBitCount()==41) {
+ serial = Converter.binToDec(serialBin);
+ }
+
+ companyPrefix = Converter.strZero(companyPrefixDec, tableItem.getL()); // strzero aqui
+ filterValue = GDTIFilterValue.forCode( Integer.parseInt(filterDec) );
+ prefixLength = PrefixLength.forCode(tableItem.getL());
+
+ } else {
+
+ if ( optionalCompanyPrefix.isPresent() ) {
+ GDTIPartitionTableList sgtinPartitionTableList = new GDTIPartitionTableList();
+ prefixLength = PrefixLength.forCode( companyPrefix.length() );
+
+ validateCompanyPrefix();
+
+ tableItem = sgtinPartitionTableList.getPartitionByL( prefixLength.getValue() );
+
+ validateDocType();
+ validateSerial();
+
+ } else {
+
+ if ( optionalEpcTagURI.isPresent() ) {
+ Pattern pattern = Pattern.compile("(urn:epc:tag:gdti-)(96|174)\\:([0-7])\\.(\\d+)\\.(\\d+)\\.(\\w+)");
+ Matcher matcher = pattern.matcher(epcTagURI);
+
+ if ( matcher.matches() ) {
+ tagSize = GDTITagSize.forCode( Integer.parseInt(matcher.group(2)) );
+ filterValue = GDTIFilterValue.forCode( Integer.parseInt(matcher.group(3)) );
+ companyPrefix = matcher.group(4);
+ prefixLength = PrefixLength.forCode( matcher.group(4).length() );
+ docType = matcher.group(5);
+ serial = matcher.group(6);
+ } else {
+ throw new IllegalArgumentException("EPC Tag URI is invalid");
+ }
+
+ } else if ( optionalEpcPureIdentityURI.isPresent() ) {
+ Pattern pattern = Pattern.compile("(urn:epc:id:gdti)\\:(\\d+)\\.(\\d+)\\.(\\w+)");
+ Matcher matcher = pattern.matcher(epcPureIdentityURI);
+
+ if ( matcher.matches() ) {
+ companyPrefix = matcher.group(2);
+ prefixLength = PrefixLength.forCode( matcher.group(2).length() );
+ docType = matcher.group(3);
+ serial = matcher.group(4);
+ } else {
+ throw new IllegalArgumentException("EPC Pure Identity is invalid");
+ }
+ }
+
+ }
+
+ GDTIPartitionTableList sgtinPartitionTableList = new GDTIPartitionTableList();
+ tableItem = sgtinPartitionTableList.getPartitionByL( prefixLength.getValue() );
+
+ }
+
+ String outputBin = getBinary();
+ String outputHex = Converter.binToHex( outputBin );
+
+ gdti.setEpcScheme("gdti");
+ gdti.setApplicationIdentifier("AI 253");
+ gdti.setTagSize(Integer.toString(tagSize.getValue()));
+ gdti.setFilterValue(Integer.toString(filterValue.getValue()));
+ gdti.setPartitionValue(Integer.toString(tableItem.getPartitionValue()));
+ gdti.setPrefixLength(Integer.toString(prefixLength.getValue()));
+ gdti.setCompanyPrefix(companyPrefix);
+ gdti.setDocType(docType);
+ gdti.setSerial(serial);
+ gdti.setCheckDigit(Integer.toString(getCheckDigit()));
+ gdti.setEpcPureIdentityURI(String.format("urn:epc:id:gdti:%s.%s.%s", companyPrefix, docType, serial));
+ gdti.setEpcTagURI(String.format("urn:epc:tag:gdti-%s:%s.%s.%s.%s", tagSize.getValue(), filterValue.getValue(), companyPrefix, docType, serial));
+ gdti.setEpcRawURI(String.format("urn:epc:raw:%s.x%s", tagSize.getValue()+remainder, outputHex ));
+ gdti.setBinary(outputBin);
+ gdti.setRfidTag(outputHex);
+ }
+
+
+ private String getBinary() {
+ StringBuilder bin = new StringBuilder();
+
+ remainder = (int) (Math.ceil((tagSize.getValue()/16.0))*16)-tagSize.getValue();
+
+ bin.append( Converter.decToBin(tagSize.getHeader(), 8) );
+ bin.append( Converter.decToBin(filterValue.getValue(), 3) );
+ bin.append( Converter.decToBin(tableItem.getPartitionValue(), 3) );
+ bin.append( Converter.decToBin(Integer.parseInt(companyPrefix), tableItem.getM()) );
+ bin.append( Converter.decToBin(Integer.parseInt(docType), tableItem.getN()) );
+
+ if (tagSize.getValue()==174) {
+ bin.append( Converter.fill(Converter.StringToBinary(serial, 7), tagSize.getSerialBitCount()+remainder) );
+ } else if (tagSize.getValue()==96) {
+ bin.append( Converter.decToBin(serial, tagSize.getSerialBitCount()+remainder ) );
+ }
+
+ return bin.toString();
+ }
+
+
+
+ private Integer getCheckDigit() {
+ String value = new StringBuilder()
+ .append(companyPrefix)
+ .append(docType)
+ .toString();
+
+ Integer d13 = (10 - ((3
+ * (Character.getNumericValue(value.charAt(1)) + Character.getNumericValue(value.charAt(3))
+ + Character.getNumericValue(value.charAt(5))
+ + Character.getNumericValue(value.charAt(7)) + Character.getNumericValue(value.charAt(9))
+ + Character.getNumericValue(value.charAt(11)) )
+ + (Character.getNumericValue(value.charAt(0)) + Character.getNumericValue(value.charAt(2))
+ + Character.getNumericValue(value.charAt(4)) + Character.getNumericValue(value.charAt(6))
+ + Character.getNumericValue(value.charAt(8)) + Character.getNumericValue(value.charAt(10))))
+ % 10)) % 10;
+
+ return d13;
+ }
+
+
+ public GDTI getGDTI() {
+ return gdti;
+ }
+
+ public String getRfidTag() {
+ return Converter.binToHex( getBinary() );
+ }
+
+
+
+ private void validateCompanyPrefix() {
+ Optional optionalPefixLenght = Optional.ofNullable(prefixLength);
+ if ( !optionalPefixLenght.isPresent() ) {
+ throw new IllegalArgumentException("Company Prefix is invalid. Length not found in the partition table");
+ }
+ }
+
+ private void validateDocType() {
+ if ( docType.length()!=tableItem.getDigits() ) {
+ throw new IllegalArgumentException(String.format("Asset Type \"%s\" has %d length and should have %d length",
+ docType, docType.length(), tableItem.getDigits()));
+ }
+ }
+
+ private void validateSerial() {
+ if (tagSize.getValue()==170 ) {
+ if ( serial.length()>tagSize.getSerialMaxLenght() ) {
+ throw new IllegalArgumentException( String.format("Serial value is out of range. Should be up to %d alphanumeric characters",
+ tagSize.getSerialMaxLenght() ));
+ }
+ } else if (tagSize.getValue()==96 ) {
+ if ( Long.parseLong(serial) >tagSize.getSerialMaxValue() ) {
+ throw new IllegalArgumentException( String.format("Serial value is out of range. Should be less than or equal %d",
+ tagSize.getSerialMaxValue() ));
+ }
+ if ( serial.startsWith("0") ) {
+ throw new IllegalArgumentException("Serial with leading zeros is not allowed");
+ }
+ }
+
+ }
+
+
+
+ public static interface ChoiceStep {
+ docTypeStep withCompanyPrefix(String companyPrefix);
+ BuildStep withRFIDTag(String rfidTag);
+ BuildStep withEPCTagURI(String epcTagURI);
+ TagSizeStep withEPCPureIdentityURI(String epcPureIdentityURI);
+ }
+
+
+ public static interface docTypeStep {
+ serialStep withDocType(String docType);
+ }
+
+ public static interface serialStep {
+ TagSizeStep withserial(String serial);
+ }
+
+ public static interface TagSizeStep {
+ FilterValueStep withTagSize( GDTITagSize tagSize );
+ }
+
+ public static interface FilterValueStep {
+ BuildStep withFilterValue( GDTIFilterValue filterValue );
+ }
+
+ public static interface BuildStep {
+ ParseGDTI build();
+ }
+
+
+ private static class Steps implements ChoiceStep, docTypeStep, serialStep, TagSizeStep, FilterValueStep, BuildStep {
+ private String companyPrefix;
+ private GDTITagSize tagSize;
+ private GDTIFilterValue filterValue;
+ private String docType;
+ private String serial;
+ private String rfidTag;
+ private String epcTagURI;
+ private String epcPureIdentityURI;
+
+ @Override
+ public ParseGDTI build() {
+ return new ParseGDTI(this);
+ }
+
+ @Override
+ public BuildStep withFilterValue(GDTIFilterValue filterValue) {
+ this.filterValue = filterValue;
+ return this;
+ }
+
+ @Override
+ public FilterValueStep withTagSize(GDTITagSize tagSize) {
+ this.tagSize = tagSize;
+ return this;
+ }
+
+ @Override
+ public TagSizeStep withserial(String serial) {
+ this.serial = serial;
+ return this;
+ }
+
+ @Override
+ public serialStep withDocType(String docType) {
+ this.docType = docType;
+ return this;
+ }
+
+ @Override
+ public docTypeStep withCompanyPrefix(String companyPrefix) {
+ this.companyPrefix = companyPrefix;
+ return this;
+ }
+
+ @Override
+ public BuildStep withRFIDTag(String rfidTag) {
+ this.rfidTag = rfidTag;
+ return this;
+ }
+
+ @Override
+ public BuildStep withEPCTagURI(String epcTagURI) {
+ this.epcTagURI = epcTagURI;
+ return this;
+ }
+
+ @Override
+ public TagSizeStep withEPCPureIdentityURI(String epcPureIdentityURI) {
+ this.epcPureIdentityURI = epcPureIdentityURI;
+ return this;
+ }
+
+ }
+
+}
+
+
+
+package org.epctagcoder.parse.GIAI;
+
+import java.util.Optional;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import org.epctagcoder.option.PrefixLength;
+import org.epctagcoder.option.TableItem;
+import org.epctagcoder.option.GIAI.GIAIFilterValue;
+import org.epctagcoder.option.GIAI.GIAIHeader;
+import org.epctagcoder.option.GIAI.GIAITagSize;
+import org.epctagcoder.option.GIAI.partitionTable.GIAIPartitionTableList;
+import org.epctagcoder.result.GIAI;
+import org.epctagcoder.util.Converter;
+
+
+public class ParseGIAI {
+ private GIAI giai = new GIAI();
+ private String companyPrefix;
+ private PrefixLength prefixLength;
+ private GIAITagSize tagSize;
+ private GIAIFilterValue filterValue;
+ private String individualAssetReference;
+ private String rfidTag;
+ private String epcTagURI;
+ private String epcPureIdentityURI;
+ private TableItem tableItem;
+ private int remainder;
+
+ public static ChoiceStep Builder() {
+ return new Steps();
+ }
+
+ private ParseGIAI(Steps steps) {
+ this.companyPrefix = steps.companyPrefix;
+ this.tagSize = steps.tagSize;
+ this.filterValue = steps.filterValue;
+ this.individualAssetReference = steps.individualAssetReference;
+ this.rfidTag = steps.rfidTag;
+ this.epcTagURI = steps.epcTagURI;
+ this.epcPureIdentityURI = steps.epcPureIdentityURI;
+ parse();
+ }
+
+
+
+ private void parse() {
+ Optional optionalCompanyPrefix = Optional.ofNullable(companyPrefix);
+ Optional optionalRfidTag = Optional.ofNullable(rfidTag);
+ Optional optionalEpcTagURI = Optional.ofNullable(epcTagURI);
+ Optional optionalEpcPureIdentityURI = Optional.ofNullable(epcPureIdentityURI);
+
+ if ( optionalRfidTag.isPresent() ) {
+ String inputBin = Converter.hexToBin(rfidTag);
+ String headerBin = inputBin.substring(0, 8);
+ String filterBin = inputBin.substring(8,11);
+ String partitionBin = inputBin.substring(11,14);
+
+ tagSize = GIAITagSize.forCode(GIAIHeader.forCode(headerBin).getTagSize());
+ GIAIPartitionTableList GIAIPartitionTableList = new GIAIPartitionTableList(tagSize);
+ tableItem = GIAIPartitionTableList.getPartitionByValue( Integer.parseInt(partitionBin, 2) );
+
+ String filterDec = Long.toString( Long.parseLong(filterBin, 2) );
+ String companyPrefixBin = inputBin.substring(14,14+tableItem.getM());
+ String individualAssetReferenceBin = inputBin.substring(14+tableItem.getM(),14+tableItem.getM()+tableItem.getN());
+ String companyPrefixDec = Converter.binToDec(companyPrefixBin);
+
+ if (tagSize.getSerialBitCount()==112) {
+ individualAssetReferenceBin = Converter.convertBinToBit(individualAssetReferenceBin, 7, 8);
+ individualAssetReference = Converter.binToString(individualAssetReferenceBin);
+ } else if (tagSize.getSerialBitCount()==38) {
+ individualAssetReference = Converter.binToDec(individualAssetReferenceBin);
+ }
+
+ companyPrefix = Converter.strZero(companyPrefixDec, tableItem.getL());
+ filterValue = GIAIFilterValue.forCode( Integer.parseInt(filterDec) );
+ prefixLength = PrefixLength.forCode(tableItem.getL());
+
+
+ } else {
+
+ if ( optionalCompanyPrefix.isPresent() ) {
+ GIAIPartitionTableList giaiPartitionTableList = new GIAIPartitionTableList(tagSize);
+ prefixLength = PrefixLength.forCode( companyPrefix.length() );
+
+ validateCompanyPrefix();
+
+ tableItem = giaiPartitionTableList.getPartitionByL( prefixLength.getValue() );
+
+ validateIndividualAssetReference();
+ } else {
+
+ if ( optionalEpcTagURI.isPresent() ) {
+ Pattern pattern = Pattern.compile("(urn:epc:tag:giai-)(96|202)\\:([0-7])\\.(\\d+)\\.(\\w+)");
+ Matcher matcher = pattern.matcher(epcTagURI);
+
+ if ( matcher.matches() ) {
+ tagSize = GIAITagSize.forCode( Integer.parseInt(matcher.group(2)) );
+ filterValue = GIAIFilterValue.forCode( Integer.parseInt(matcher.group(3)) );
+ companyPrefix = matcher.group(4);
+ prefixLength = PrefixLength.forCode( matcher.group(4).length() );
+ individualAssetReference = matcher.group(5);
+ } else {
+ throw new IllegalArgumentException("EPC Tag URI is invalid");
+ }
+
+ } else if ( optionalEpcPureIdentityURI.isPresent() ) {
+ Pattern pattern = Pattern.compile("(urn:epc:id:giai)\\:(\\d+)\\.(\\w+)");
+
+ Matcher matcher = pattern.matcher(epcPureIdentityURI);
+
+ if ( matcher.matches() ) {
+ companyPrefix = matcher.group(2);
+ prefixLength = PrefixLength.forCode( matcher.group(2).length() );
+ individualAssetReference = matcher.group(3);;
+ } else {
+ throw new IllegalArgumentException("EPC Pure Identity is invalid");
+ }
+ }
+
+ }
+
+ GIAIPartitionTableList giaiPartitionTableList = new GIAIPartitionTableList(tagSize);
+ tableItem = giaiPartitionTableList.getPartitionByL( prefixLength.getValue() );
+
+ }
+
+ String outputBin = getBinary();
+ String outputHex = Converter.binToHex( outputBin );
+
+ giai.setEpcScheme("giai");
+ giai.setApplicationIdentifier("AI 8004");
+ giai.setTagSize(Integer.toString(tagSize.getValue()));
+ giai.setFilterValue(Integer.toString(filterValue.getValue()));
+ giai.setPartitionValue(Integer.toString(tableItem.getPartitionValue()));
+ giai.setPrefixLength(Integer.toString(prefixLength.getValue()));
+ giai.setCompanyPrefix(companyPrefix);
+ giai.setIndividualAssetReference(individualAssetReference);
+ giai.setEpcPureIdentityURI(String.format("urn:epc:id:giai:%s.%s", companyPrefix, individualAssetReference));
+ giai.setEpcTagURI(String.format("urn:epc:tag:giai-%s:%s.%s.%s", tagSize.getValue(), filterValue.getValue(), companyPrefix, individualAssetReference));
+ giai.setEpcRawURI(String.format("urn:epc:raw:%s.x%s", tagSize.getValue()+remainder, outputHex ));
+ giai.setBinary(outputBin);
+ giai.setRfidTag(outputHex);
+ }
+
+
+ private String getBinary() {
+ StringBuilder bin = new StringBuilder();
+
+ remainder = (int) (Math.ceil((tagSize.getValue()/16.0))*16)-tagSize.getValue();
+
+ bin.append( Converter.decToBin(tagSize.getHeader(), 8) );
+ bin.append( Converter.decToBin(filterValue.getValue(), 3) );
+ bin.append( Converter.decToBin(tableItem.getPartitionValue(), 3) );
+ bin.append( Converter.decToBin(Integer.parseInt(companyPrefix), tableItem.getM()) );
+
+ if (tagSize.getValue()==202) {
+ bin.append( Converter.fill(Converter.StringToBinary(individualAssetReference, 7), tableItem.getN()+remainder) );
+ } else if (tagSize.getValue()==96) {
+ bin.append( Converter.decToBin(individualAssetReference, tableItem.getN()+remainder ) );
+ }
+
+ return bin.toString();
+ }
+
+
+
+ public GIAI getGIAI() {
+ return giai;
+ }
+
+ public String getRfidTag() {
+ return Converter.binToHex( getBinary() );
+ }
+
+
+ private void validateCompanyPrefix() {
+ Optional optionalPefixLenght = Optional.ofNullable(prefixLength);
+ if ( !optionalPefixLenght.isPresent() ) {
+ throw new IllegalArgumentException("Company Prefix is invalid. Length not found in the partition table");
+ }
+
+ }
+
+
+ private void validateIndividualAssetReference() {
+ if ( individualAssetReference.length() >tableItem.getDigits() ) {
+ throw new IllegalArgumentException( String.format("Individual Asset Reference value is out of range. The length should be %d",
+ tableItem.getDigits() ));
+ }
+
+ if (tagSize.getValue()==96 ) {
+ if ( individualAssetReference.startsWith("0") ) {
+ throw new IllegalArgumentException("Individual Asset Reference with leading zeros is not allowed");
+ }
+ }
+ }
+
+
+
+
+ public static interface ChoiceStep {
+ IndividualAssetReferenceStep withCompanyPrefix(String companyPrefix);
+ BuildStep withRFIDTag(String rfidTag);
+ BuildStep withEPCTagURI(String epcTagURI);
+ TagSizeStep withEPCPureIdentityURI(String epcPureIdentityURI);
+ }
+
+
+ public static interface IndividualAssetReferenceStep {
+ TagSizeStep withIndividualAssetReference(String individualAssetReference);
+ }
+
+
+ public static interface TagSizeStep {
+ FilterValueStep withTagSize( GIAITagSize tagSize );
+ }
+
+ public static interface FilterValueStep {
+ BuildStep withFilterValue( GIAIFilterValue filterValue );
+ }
+
+ public static interface BuildStep {
+ ParseGIAI build();
+ }
+
+
+ private static class Steps implements ChoiceStep, IndividualAssetReferenceStep, TagSizeStep, FilterValueStep, BuildStep {
+ private String companyPrefix;
+ private GIAITagSize tagSize;
+ private GIAIFilterValue filterValue;
+ private String individualAssetReference;
+ private String rfidTag;
+ private String epcTagURI;
+ private String epcPureIdentityURI;
+
+ @Override
+ public ParseGIAI build() {
+ return new ParseGIAI(this);
+ }
+
+ @Override
+ public BuildStep withFilterValue(GIAIFilterValue filterValue) {
+ this.filterValue = filterValue;
+ return this;
+ }
+
+ @Override
+ public FilterValueStep withTagSize(GIAITagSize tagSize) {
+ this.tagSize = tagSize;
+ return this;
+ }
+
+
+ @Override
+ public BuildStep withRFIDTag(String rfidTag) {
+ this.rfidTag = rfidTag;
+ return this;
+ }
+
+ @Override
+ public BuildStep withEPCTagURI(String epcTagURI) {
+ this.epcTagURI = epcTagURI;
+ return this;
+ }
+
+ @Override
+ public TagSizeStep withEPCPureIdentityURI(String epcPureIdentityURI) {
+ this.epcPureIdentityURI = epcPureIdentityURI;
+ return this;
+ }
+
+
+ @Override
+ public IndividualAssetReferenceStep withCompanyPrefix(String companyPrefix) {
+ this.companyPrefix = companyPrefix;
+ return this;
+ }
+
+ @Override
+ public TagSizeStep withIndividualAssetReference(String individualAssetReference) {
+ this.individualAssetReference = individualAssetReference;
+ return this;
+ }
+
+
+ }
+
+}
+
+
+
+package org.epctagcoder.parse.GRAI;
+
+import java.util.Optional;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import org.epctagcoder.option.PrefixLength;
+import org.epctagcoder.option.TableItem;
+import org.epctagcoder.option.GRAI.GRAIFilterValue;
+import org.epctagcoder.option.GRAI.GRAIHeader;
+import org.epctagcoder.option.GRAI.GRAITagSize;
+import org.epctagcoder.option.GRAI.partitionTable.GRAIPartitionTableList;
+import org.epctagcoder.result.GRAI;
+import org.epctagcoder.util.Converter;
+
+
+public class ParseGRAI {
+ private GRAI grai = new GRAI();
+ private String companyPrefix;
+ private PrefixLength prefixLength;
+ private GRAITagSize tagSize;
+ private GRAIFilterValue filterValue;
+ private String assetType;
+ private String serial;
+ private String rfidTag;
+ private String epcTagURI;
+ private String epcPureIdentityURI;
+ private TableItem tableItem;
+ private int remainder;
+
+ public static ChoiceStep Builder() throws Exception {
+ return new Steps();
+ }
+
+ private ParseGRAI(Steps steps) {
+ this.companyPrefix = steps.companyPrefix;
+ this.tagSize = steps.tagSize;
+ this.filterValue = steps.filterValue;
+ this.assetType = steps.assetType;
+ this.serial = steps.serial;
+ this.rfidTag = steps.rfidTag;
+ this.epcTagURI = steps.epcTagURI;
+ this.epcPureIdentityURI = steps.epcPureIdentityURI;
+ parse();
+ }
+
+
+
+ private void parse() {
+ Optional optionalCompanyPrefix = Optional.ofNullable(companyPrefix);
+ Optional optionalRfidTag = Optional.ofNullable(rfidTag);
+ Optional optionalEpcTagURI = Optional.ofNullable(epcTagURI);
+ Optional optionalEpcPureIdentityURI = Optional.ofNullable(epcPureIdentityURI);
+
+ if ( optionalRfidTag.isPresent() ) {
+ String inputBin = Converter.hexToBin(rfidTag);
+ String headerBin = inputBin.substring(0, 8);
+ String filterBin = inputBin.substring(8,11);
+ String partitionBin = inputBin.substring(11,14);
+ GRAIPartitionTableList graiPartitionTableList = new GRAIPartitionTableList();
+
+ tagSize = GRAITagSize.forCode(GRAIHeader.forCode(headerBin).getTagSize());
+ tableItem = graiPartitionTableList.getPartitionByValue( Integer.parseInt(partitionBin, 2) );
+
+ String filterDec = Long.toString( Long.parseLong(filterBin, 2) );
+ String companyPrefixBin = inputBin.substring(14,14+tableItem.getM());
+ String assetTypeBin = inputBin.substring(14+tableItem.getM(),14+tableItem.getM()+tableItem.getN());
+ String serialBin = inputBin.substring(14+tableItem.getM()+tableItem.getN() );
+
+ String companyPrefixDec = Converter.binToDec(companyPrefixBin);
+ String assetTypeDec = Converter.binToDec(assetTypeBin);
+
+ assetType = Converter.strZero(assetTypeDec, tableItem.getDigits() ) ;
+
+ if (tagSize.getSerialBitCount()==112) {
+ serialBin = Converter.convertBinToBit(serialBin, 7, 8);
+ serial = Converter.binToString(serialBin);
+ } else if (tagSize.getSerialBitCount()==38) {
+ serial = Converter.binToDec(serialBin);
+ }
+
+ companyPrefix = Converter.strZero(companyPrefixDec, tableItem.getL()); // strzero aqui
+ filterValue = GRAIFilterValue.forCode( Integer.parseInt(filterDec) );
+ prefixLength = PrefixLength.forCode(tableItem.getL());
+
+ } else {
+
+ if ( optionalCompanyPrefix.isPresent() ) {
+ GRAIPartitionTableList sgtinPartitionTableList = new GRAIPartitionTableList();
+ prefixLength = PrefixLength.forCode( companyPrefix.length() );
+
+ validateCompanyPrefix();
+
+ tableItem = sgtinPartitionTableList.getPartitionByL( prefixLength.getValue() );
+
+ validateAssetType();
+ validateSerial();
+
+ } else {
+
+ if ( optionalEpcTagURI.isPresent() ) {
+ Pattern pattern = Pattern.compile("(urn:epc:tag:grai-)(96|170)\\:([0-7])\\.(\\d+)\\.(\\d+)\\.(\\w+)");
+ Matcher matcher = pattern.matcher(epcTagURI);
+
+ if ( matcher.matches() ) {
+ tagSize = GRAITagSize.forCode( Integer.parseInt(matcher.group(2)) );
+ filterValue = GRAIFilterValue.forCode( Integer.parseInt(matcher.group(3)) );
+ companyPrefix = matcher.group(4);
+ prefixLength = PrefixLength.forCode( matcher.group(4).length() );
+ assetType = matcher.group(5);
+ serial = matcher.group(6);
+ } else {
+ throw new IllegalArgumentException("EPC Tag URI is invalid");
+ }
+
+ } else if ( optionalEpcPureIdentityURI.isPresent() ) {
+ Pattern pattern = Pattern.compile("(urn:epc:id:grai)\\:(\\d+)\\.(\\d+)\\.(\\w+)");
+ Matcher matcher = pattern.matcher(epcPureIdentityURI);
+
+ if ( matcher.matches() ) {
+ companyPrefix = matcher.group(2);
+ prefixLength = PrefixLength.forCode( matcher.group(2).length() );
+ assetType = matcher.group(3);;
+ serial = matcher.group(4);
+ } else {
+ throw new IllegalArgumentException("EPC Pure Identity is invalid");
+ }
+ }
+
+ }
+
+ GRAIPartitionTableList sgtinPartitionTableList = new GRAIPartitionTableList();
+ tableItem = sgtinPartitionTableList.getPartitionByL( prefixLength.getValue() );
+
+ }
+
+ String outputBin = getBinary();
+ String outputHex = Converter.binToHex( outputBin );
+
+ grai.setEpcScheme("grai");
+ grai.setApplicationIdentifier("AI 8003");
+ grai.setTagSize(Integer.toString(tagSize.getValue()));
+ grai.setFilterValue(Integer.toString(filterValue.getValue()));
+ grai.setPartitionValue(Integer.toString(tableItem.getPartitionValue()));
+ grai.setPrefixLength(Integer.toString(prefixLength.getValue()));
+ grai.setCompanyPrefix(companyPrefix);
+ grai.setAssetType(assetType);
+ grai.setSerial(serial);
+ grai.setCheckDigit(Integer.toString(getCheckDigit()));
+ grai.setEpcPureIdentityURI(String.format("urn:epc:id:grai:%s.%s.%s", companyPrefix, assetType, serial));
+ grai.setEpcTagURI(String.format("urn:epc:tag:grai-%s:%s.%s.%s.%s", tagSize.getValue(), filterValue.getValue(), companyPrefix, assetType, serial));
+ grai.setEpcRawURI(String.format("urn:epc:raw:%s.x%s", tagSize.getValue()+remainder, outputHex ));
+ grai.setBinary(outputBin);
+ grai.setRfidTag(outputHex);
+ }
+
+
+ private String getBinary() {
+ StringBuilder bin = new StringBuilder();
+
+ remainder = (int) (Math.ceil((tagSize.getValue()/16.0))*16)-tagSize.getValue();
+
+ bin.append( Converter.decToBin(tagSize.getHeader(), 8) );
+ bin.append( Converter.decToBin(filterValue.getValue(), 3) );
+ bin.append( Converter.decToBin(tableItem.getPartitionValue(), 3) );
+ bin.append( Converter.decToBin(Integer.parseInt(companyPrefix), tableItem.getM()) );
+ bin.append( Converter.decToBin(Integer.parseInt(assetType), tableItem.getN()) );
+
+ if (tagSize.getValue()==170) {
+ bin.append( Converter.fill(Converter.StringToBinary(serial, 7), tagSize.getSerialBitCount()+remainder) );
+ } else if (tagSize.getValue()==96) {
+ bin.append( Converter.decToBin(serial, tagSize.getSerialBitCount()+remainder ) );
+ }
+
+ return bin.toString();
+ }
+
+
+
+ private Integer getCheckDigit() {
+ String value = new StringBuilder()
+ .append(companyPrefix)
+ .append(assetType)
+ .toString();
+
+ Integer d13 = (10 - ((3
+ * (Character.getNumericValue(value.charAt(1)) + Character.getNumericValue(value.charAt(3))
+ + Character.getNumericValue(value.charAt(5))
+ + Character.getNumericValue(value.charAt(7)) + Character.getNumericValue(value.charAt(9))
+ + Character.getNumericValue(value.charAt(11)) )
+ + (Character.getNumericValue(value.charAt(0)) + Character.getNumericValue(value.charAt(2))
+ + Character.getNumericValue(value.charAt(4)) + Character.getNumericValue(value.charAt(6))
+ + Character.getNumericValue(value.charAt(8)) + Character.getNumericValue(value.charAt(10))))
+ % 10)) % 10;
+
+ return d13;
+ }
+
+
+ public GRAI getGRAI() {
+ return grai;
+ }
+
+ public String getRfidTag() {
+ return Converter.binToHex( getBinary() );
+ }
+
+
+
+ private void validateCompanyPrefix() {
+ Optional optionalPefixLenght = Optional.ofNullable(prefixLength);
+ if ( !optionalPefixLenght.isPresent() ) {
+ throw new IllegalArgumentException("Company Prefix is invalid. Length not found in the partition table");
+ }
+ }
+
+ private void validateAssetType() {
+ if ( assetType.length()!=tableItem.getDigits() ) {
+ throw new IllegalArgumentException(String.format("Asset Type \"%s\" has %d length and should have %d length",
+ assetType, assetType.length(), tableItem.getDigits()));
+ }
+ }
+
+ private void validateSerial() {
+ if (tagSize.getValue()==170 ) {
+ if ( serial.length()>tagSize.getSerialMaxLenght() ) {
+ throw new IllegalArgumentException( String.format("Serial value is out of range. Should be up to %d alphanumeric characters",
+ tagSize.getSerialMaxLenght() ));
+ }
+ } else if (tagSize.getValue()==96 ) {
+ if ( Long.parseLong(serial) >tagSize.getSerialMaxValue() ) {
+ throw new IllegalArgumentException( String.format("Serial value is out of range. Should be less than or equal %d",
+ tagSize.getSerialMaxValue() ));
+ }
+ if ( serial.startsWith("0") ) {
+ throw new IllegalArgumentException("Serial with leading zeros is not allowed");
+ }
+ }
+
+ }
+
+
+
+ public static interface ChoiceStep {
+ assetTypeStep withCompanyPrefix(String companyPrefix);
+ BuildStep withRFIDTag(String rfidTag);
+ BuildStep withEPCTagURI(String epcTagURI);
+ TagSizeStep withEPCPureIdentityURI(String epcPureIdentityURI);
+ }
+
+
+ public static interface assetTypeStep {
+ serialStep withAssetType(String assetType);
+ }
+
+ public static interface serialStep {
+ TagSizeStep withserial(String serial);
+ }
+
+ public static interface TagSizeStep {
+ FilterValueStep withTagSize( GRAITagSize tagSize );
+ }
+
+ public static interface FilterValueStep {
+ BuildStep withFilterValue( GRAIFilterValue filterValue );
+ }
+
+ public static interface BuildStep {
+ ParseGRAI build();
+ }
+
+
+ private static class Steps implements ChoiceStep, assetTypeStep, serialStep, TagSizeStep, FilterValueStep, BuildStep {
+ private String companyPrefix;
+ private GRAITagSize tagSize;
+ private GRAIFilterValue filterValue;
+ private String assetType;
+ private String serial;
+ private String rfidTag;
+ private String epcTagURI;
+ private String epcPureIdentityURI;
+
+ @Override
+ public ParseGRAI build() {
+ return new ParseGRAI(this);
+ }
+
+ @Override
+ public BuildStep withFilterValue(GRAIFilterValue filterValue) {
+ this.filterValue = filterValue;
+ return this;
+ }
+
+ @Override
+ public FilterValueStep withTagSize(GRAITagSize tagSize) {
+ this.tagSize = tagSize;
+ return this;
+ }
+
+ @Override
+ public TagSizeStep withserial(String serial) {
+ this.serial = serial;
+ return this;
+ }
+
+ @Override
+ public serialStep withAssetType(String assetType) {
+ this.assetType = assetType;
+ return this;
+ }
+
+ @Override
+ public assetTypeStep withCompanyPrefix(String companyPrefix) {
+ this.companyPrefix = companyPrefix;
+ return this;
+ }
+
+ @Override
+ public BuildStep withRFIDTag(String rfidTag) {
+ this.rfidTag = rfidTag;
+ return this;
+ }
+
+ @Override
+ public BuildStep withEPCTagURI(String epcTagURI) {
+ this.epcTagURI = epcTagURI;
+ return this;
+ }
+
+ @Override
+ public TagSizeStep withEPCPureIdentityURI(String epcPureIdentityURI) {
+ this.epcPureIdentityURI = epcPureIdentityURI;
+ return this;
+ }
+
+ }
+
+}
+
+
+
+package org.epctagcoder.parse.GSRN;
+
+import java.util.Optional;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import org.epctagcoder.option.PrefixLength;
+import org.epctagcoder.option.TableItem;
+import org.epctagcoder.option.GSRN.GSRNFilterValue;
+import org.epctagcoder.option.GSRN.GSRNHeader;
+import org.epctagcoder.option.GSRN.GSRNTagSize;
+import org.epctagcoder.option.GSRN.partitionTable.GSRNPartitionTableList;
+import org.epctagcoder.result.GSRN;
+import org.epctagcoder.util.Converter;
+
+public class ParseGSRN {
+ private static final Integer RESERVED = 0; // 24 zero bits
+ private GSRN gsrn = new GSRN();
+ private String companyPrefix;
+ private PrefixLength prefixLength;
+ private GSRNTagSize tagSize;
+ private GSRNFilterValue filterValue;
+ private String serviceReference;
+ private String rfidTag;
+ private String epcTagURI;
+ private String epcPureIdentityURI;
+ private TableItem tableItem;
+
+ public static ChoiceStep Builder() throws Exception {
+ return new Steps();
+ }
+
+ private ParseGSRN(Steps steps) {
+ this.companyPrefix = steps.companyPrefix;
+ this.tagSize = steps.tagSize;
+ this.filterValue = steps.filterValue;
+ this.serviceReference = steps.serviceReference;
+ this.rfidTag = steps.rfidTag;
+ this.epcTagURI = steps.epcTagURI;
+ this.epcPureIdentityURI = steps.epcPureIdentityURI;
+ parse();
+ }
+
+
+ private void parse() {
+ Optional optionalCompanyPrefix = Optional.ofNullable(companyPrefix);
+ Optional optionalRfidTag = Optional.ofNullable(rfidTag);
+ Optional optionalEpcTagURI = Optional.ofNullable(epcTagURI);
+ Optional optionalEpcPureIdentityURI = Optional.ofNullable(epcPureIdentityURI);
+
+ if ( optionalRfidTag.isPresent() ) {
+ String inputBin = Converter.hexToBin(rfidTag);
+ String headerBin = inputBin.substring(0, 8);
+ String filterBin = inputBin.substring(8,11);
+ String partitionBin = inputBin.substring(11,14);
+ GSRNPartitionTableList GSRNPartitionTableList = new GSRNPartitionTableList();
+
+ tableItem = GSRNPartitionTableList.getPartitionByValue( Integer.parseInt(partitionBin, 2) );
+
+ String companyPrefixBin = inputBin.substring(14,14+tableItem.getM());
+ String serialWithExtensionBin = inputBin.substring(14+tableItem.getM(),14+tableItem.getM()+tableItem.getN());
+ String filterDec = Long.toString( Long.parseLong(filterBin, 2) );
+ String companyPrefixDec = Converter.binToDec(companyPrefixBin);
+
+ serviceReference = Converter.strZero(Converter.binToDec(serialWithExtensionBin), tableItem.getDigits() );
+ companyPrefix = Converter.strZero(companyPrefixDec, tableItem.getL());
+ filterValue = GSRNFilterValue.forCode( Integer.parseInt(filterDec) );
+ tagSize = GSRNTagSize.forCode( GSRNHeader.forCode(headerBin).getTagSize() );
+ prefixLength = PrefixLength.forCode(tableItem.getL());
+
+ } else {
+
+ if ( optionalCompanyPrefix.isPresent() ) {
+ GSRNPartitionTableList GSRNPartitionTableList = new GSRNPartitionTableList();
+
+ prefixLength = PrefixLength.forCode( companyPrefix.length() );
+
+ validateCompanyPrefix();
+
+ tableItem = GSRNPartitionTableList.getPartitionByL( prefixLength.getValue() );
+
+ validateServiceReference();
+
+ } else {
+
+ if ( optionalEpcTagURI.isPresent() ) {
+ Pattern pattern = Pattern.compile("(urn:epc:tag:gsrn-)(96)\\:([0-7])\\.(\\d+)\\.(\\d+)");
+ Matcher matcher = pattern.matcher(epcTagURI);
+
+ if ( matcher.matches() ) {
+ tagSize = GSRNTagSize.forCode( Integer.parseInt(matcher.group(2)) );
+ filterValue = GSRNFilterValue.forCode( Integer.parseInt(matcher.group(3)) );
+ companyPrefix = matcher.group(4);
+ prefixLength = PrefixLength.forCode( matcher.group(4).length() );
+ serviceReference = matcher.group(5);
+ } else {
+ throw new IllegalArgumentException("EPC Tag URI is invalid");
+ }
+
+ } else if ( optionalEpcPureIdentityURI.isPresent() ) {
+ Pattern pattern = Pattern.compile("(urn:epc:id:gsrn)\\:(\\d+)\\.(\\d+)");
+ Matcher matcher = pattern.matcher(epcPureIdentityURI);
+
+ if ( matcher.matches() ) {
+ companyPrefix = matcher.group(2);
+ prefixLength = PrefixLength.forCode( matcher.group(2).length() );
+ serviceReference = matcher.group(3);
+ } else {
+ throw new IllegalArgumentException("EPC Pure Identity is invalid");
+ }
+
+
+ }
+
+ GSRNPartitionTableList GSRNPartitionTableList = new GSRNPartitionTableList();
+ tableItem = GSRNPartitionTableList.getPartitionByL( prefixLength.getValue() );
+
+ }
+
+ }
+
+
+ String outputBin = getBinary();
+ String outputHex = Converter.binToHex( outputBin );
+
+ gsrn.setEpcScheme("gsrn");
+ gsrn.setApplicationIdentifier("AI 8018");
+ gsrn.setTagSize(Integer.toString(tagSize.getValue()));
+ gsrn.setFilterValue(Integer.toString(filterValue.getValue()) );
+ gsrn.setPartitionValue(Integer.toString(tableItem.getPartitionValue()));
+ gsrn.setPrefixLength(Integer.toString(prefixLength.getValue()));
+ gsrn.setCompanyPrefix(companyPrefix);
+ gsrn.setServiceReference(serviceReference);
+ gsrn.setCheckDigit(Integer.toString(getCheckDigit()));
+ gsrn.setEpcPureIdentityURI(String.format("urn:epc:id:gsrn:%s.%s", companyPrefix, serviceReference));
+ gsrn.setEpcTagURI(String.format("urn:epc:tag:gsrn-%s:%s.%s.%s", tagSize.getValue(),
+ filterValue.getValue(), companyPrefix, serviceReference));
+ gsrn.setEpcRawURI(String.format("urn:epc:raw:%s.x%s", tagSize.getValue(), outputHex ));
+ gsrn.setBinary(outputBin);
+ gsrn.setRfidTag(outputHex);
+
+ }
+
+ private Integer getCheckDigit() {
+ String value = new StringBuilder()
+ .append(companyPrefix)
+ .append(serviceReference)
+ .toString();
+
+ Integer d18 = (10 - ((3
+ * (Character.getNumericValue(value.charAt(0)) + Character.getNumericValue(value.charAt(2))
+ + Character.getNumericValue(value.charAt(4)) + Character.getNumericValue(value.charAt(6))
+ + Character.getNumericValue(value.charAt(8))
+ + Character.getNumericValue(value.charAt(10)) + Character.getNumericValue(value.charAt(12))
+ + Character.getNumericValue(value.charAt(14)) + Character.getNumericValue(value.charAt(16)))
+ + (Character.getNumericValue(value.charAt(1)) + Character.getNumericValue(value.charAt(3))
+ + Character.getNumericValue(value.charAt(5)) + Character.getNumericValue(value.charAt(7))
+ + Character.getNumericValue(value.charAt(9)) + Character.getNumericValue(value.charAt(11))
+ + Character.getNumericValue(value.charAt(13)) + Character.getNumericValue(value.charAt(15))))
+ % 10)) % 10;
+ return d18;
+ }
+
+
+ private String getBinary() {
+ StringBuilder bin = new StringBuilder();
+
+ bin.append( Converter.decToBin(tagSize.getHeader(), 8) );
+ bin.append( Converter.decToBin(filterValue.getValue(), 3) );
+ bin.append( Converter.decToBin(tableItem.getPartitionValue(), 3) );
+ bin.append( Converter.decToBin(Integer.parseInt(companyPrefix), tableItem.getM()) );
+ bin.append( Converter.decToBin(Integer.parseInt(serviceReference), tableItem.getN()) );
+ bin.append( Converter.decToBin(RESERVED, 24) );
+
+ return bin.toString();
+ }
+
+
+ public GSRN getGSRN() {
+ return gsrn;
+ }
+
+ public String getRfidTag() {
+ return Converter.binToHex( getBinary() );
+ }
+
+
+
+ private void validateServiceReference() {
+ StringBuilder value = new StringBuilder()
+ .append(serviceReference);
+
+ if ( value.length()!=tableItem.getDigits() ) {
+ throw new IllegalArgumentException(String.format("Service Reference \"%s\" has %d length and should have %d length",
+ serviceReference, value.length(), tableItem.getDigits()));
+ }
+ }
+
+
+ private void validateCompanyPrefix() {
+ Optional optionalpPefixLenght = Optional.ofNullable(prefixLength);
+ if ( !optionalpPefixLenght.isPresent() ) {
+ throw new IllegalArgumentException("Company Prefix is invalid. Length not found in the partition table");
+ }
+
+ }
+
+
+
+
+ public static interface ChoiceStep {
+ ServiceReferenceStep withCompanyPrefix(String companyPrefix);
+ BuildStep withRFIDTag(String rfidTag);
+ BuildStep withEPCTagURI(String epcTagURI);
+ TagSizeStep withEPCPureIdentityURI(String epcPureIdentityURI);
+ }
+
+
+ public static interface ServiceReferenceStep {
+ TagSizeStep withServiceReference(String serviceReference);
+ }
+
+ public static interface TagSizeStep {
+ FilterValueStep withTagSize( GSRNTagSize tagSize );
+ }
+
+ public static interface FilterValueStep {
+ BuildStep withFilterValue( GSRNFilterValue filterValue );
+ }
+
+ public static interface BuildStep {
+ ParseGSRN build();
+ }
+
+
+
+ private static class Steps implements ChoiceStep, ServiceReferenceStep, TagSizeStep, FilterValueStep, BuildStep {
+ private String companyPrefix;
+ private GSRNTagSize tagSize;
+ private GSRNFilterValue filterValue;
+ private String serviceReference;
+ private String rfidTag;
+ private String epcTagURI;
+ private String epcPureIdentityURI;
+
+ @Override
+ public ParseGSRN build() {
+ return new ParseGSRN(this);
+ }
+
+ @Override
+ public BuildStep withFilterValue(GSRNFilterValue filterValue) {
+ this.filterValue = filterValue;
+ return this;
+ }
+
+ @Override
+ public FilterValueStep withTagSize(GSRNTagSize tagSize) {
+ this.tagSize = tagSize;
+ return this;
+ }
+
+ @Override
+ public TagSizeStep withServiceReference(String serviceReference) {
+ this.serviceReference = serviceReference;
+ return this;
+ }
+
+ @Override
+ public ServiceReferenceStep withCompanyPrefix(String companyPrefix) {
+ this.companyPrefix = companyPrefix;
+ return this;
+ }
+
+ @Override
+ public BuildStep withRFIDTag(String rfidTag) {
+ this.rfidTag = rfidTag;
+ return this;
+ }
+
+ @Override
+ public BuildStep withEPCTagURI(String epcTagURI) {
+ this.epcTagURI = epcTagURI;
+ return this;
+ }
+
+ @Override
+ public TagSizeStep withEPCPureIdentityURI(String epcPureIdentityURI) {
+ this.epcPureIdentityURI = epcPureIdentityURI;
+ return this;
+ }
+
+
+
+
+ }
+
+}
+
+
+
+package org.epctagcoder.parse.GSRNP;
+
+import java.util.Optional;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import org.epctagcoder.option.PrefixLength;
+import org.epctagcoder.option.TableItem;
+import org.epctagcoder.option.GSRNP.GSRNPFilterValue;
+import org.epctagcoder.option.GSRNP.GSRNPHeader;
+import org.epctagcoder.option.GSRNP.GSRNPTagSize;
+import org.epctagcoder.option.GSRNP.partitionTable.GSRNPPartitionTableList;
+import org.epctagcoder.result.GSRNP;
+import org.epctagcoder.util.Converter;
+
+public class ParseGSRNP {
+ private static final Integer RESERVED = 0; // 24 zero bits
+ private GSRNP gsrnp = new GSRNP();
+ private String companyPrefix;
+ private PrefixLength prefixLength;
+ private GSRNPTagSize tagSize;
+ private GSRNPFilterValue filterValue;
+ private String serviceReference;
+ private String rfidTag;
+ private String epcTagURI;
+ private String epcPureIdentityURI;
+ private TableItem tableItem;
+
+ public static ChoiceStep Builder() {
+ return new Steps();
+ }
+
+ private ParseGSRNP(Steps steps) {
+ this.companyPrefix = steps.companyPrefix;
+ this.tagSize = steps.tagSize;
+ this.filterValue = steps.filterValue;
+ this.serviceReference = steps.serviceReference;
+ this.rfidTag = steps.rfidTag;
+ this.epcTagURI = steps.epcTagURI;
+ this.epcPureIdentityURI = steps.epcPureIdentityURI;
+ parse();
+ }
+
+
+ private void parse() {
+ Optional optionalCompanyPrefix = Optional.ofNullable(companyPrefix);
+ Optional optionalRfidTag = Optional.ofNullable(rfidTag);
+ Optional optionalEpcTagURI = Optional.ofNullable(epcTagURI);
+ Optional optionalEpcPureIdentityURI = Optional.ofNullable(epcPureIdentityURI);
+
+ if ( optionalRfidTag.isPresent() ) {
+ String inputBin = Converter.hexToBin(rfidTag);
+ String headerBin = inputBin.substring(0, 8);
+ String filterBin = inputBin.substring(8,11);
+ String partitionBin = inputBin.substring(11,14);
+ GSRNPPartitionTableList GSRNPPartitionTableList = new GSRNPPartitionTableList();
+
+ tableItem = GSRNPPartitionTableList.getPartitionByValue( Integer.parseInt(partitionBin, 2) );
+
+ String companyPrefixBin = inputBin.substring(14,14+tableItem.getM());
+ String serialWithExtensionBin = inputBin.substring(14+tableItem.getM(),14+tableItem.getM()+tableItem.getN());
+ String filterDec = Long.toString( Long.parseLong(filterBin, 2) );
+ String companyPrefixDec = Converter.binToDec(companyPrefixBin); //Long.toString( Long.parseLong(companyPrefixBin, 2) );
+
+ serviceReference = Converter.strZero(Converter.binToDec(serialWithExtensionBin), tableItem.getDigits() );
+ companyPrefix = Converter.strZero(companyPrefixDec, tableItem.getL());
+ filterValue = GSRNPFilterValue.forCode( Integer.parseInt(filterDec) );
+ tagSize = GSRNPTagSize.forCode( GSRNPHeader.forCode(headerBin).getTagSize() );
+ prefixLength = PrefixLength.forCode(tableItem.getL());
+
+ } else {
+
+ if ( optionalCompanyPrefix.isPresent() ) {
+ GSRNPPartitionTableList GSRNPPartitionTableList = new GSRNPPartitionTableList();
+
+ prefixLength = PrefixLength.forCode( companyPrefix.length() );
+
+ validateCompanyPrefix();
+
+ tableItem = GSRNPPartitionTableList.getPartitionByL( prefixLength.getValue() );
+
+ validateServiceReference();
+
+ } else {
+
+ if ( optionalEpcTagURI.isPresent() ) {
+ Pattern pattern = Pattern.compile("(urn:epc:tag:gsrnp-)(96)\\:([0-7])\\.(\\d+)\\.(\\d+)");
+ Matcher matcher = pattern.matcher(epcTagURI);
+
+ if ( matcher.matches() ) {
+ tagSize = GSRNPTagSize.forCode( Integer.parseInt(matcher.group(2)) );
+ filterValue = GSRNPFilterValue.forCode( Integer.parseInt(matcher.group(3)) );
+ companyPrefix = matcher.group(4);
+ prefixLength = PrefixLength.forCode( matcher.group(4).length() );
+ serviceReference = matcher.group(5);
+ } else {
+ throw new IllegalArgumentException("EPC Tag URI is invalid");
+ }
+
+ } else if ( optionalEpcPureIdentityURI.isPresent() ) {
+ Pattern pattern = Pattern.compile("(urn:epc:id:gsrnp)\\:(\\d+)\\.(\\d+)");
+ Matcher matcher = pattern.matcher(epcPureIdentityURI);
+
+ if ( matcher.matches() ) {
+ companyPrefix = matcher.group(2);
+ prefixLength = PrefixLength.forCode( matcher.group(2).length() );
+ serviceReference = matcher.group(3);
+ } else {
+ throw new IllegalArgumentException("EPC Pure Identity is invalid");
+ }
+
+
+ }
+
+ GSRNPPartitionTableList GSRNPPartitionTableList = new GSRNPPartitionTableList();
+ tableItem = GSRNPPartitionTableList.getPartitionByL( prefixLength.getValue() );
+
+ }
+
+ }
+
+
+ String outputBin = getBinary();
+ String outputHex = Converter.binToHex( outputBin );
+
+ gsrnp.setEpcScheme("gsrnp");
+ gsrnp.setApplicationIdentifier("AI 8017");
+ gsrnp.setTagSize(Integer.toString(tagSize.getValue()));
+ gsrnp.setFilterValue(Integer.toString(filterValue.getValue()) );
+ gsrnp.setPartitionValue(Integer.toString(tableItem.getPartitionValue()));
+ gsrnp.setPrefixLength(Integer.toString(prefixLength.getValue()));
+ gsrnp.setCompanyPrefix(companyPrefix);
+ gsrnp.setServiceReference(serviceReference);
+ gsrnp.setCheckDigit(Integer.toString(getCheckDigit()));
+ gsrnp.setEpcPureIdentityURI(String.format("urn:epc:id:gsrnp:%s.%s", companyPrefix, serviceReference));
+ gsrnp.setEpcTagURI(String.format("urn:epc:tag:gsrnp-%s:%s.%s.%s", tagSize.getValue(),
+ filterValue.getValue(), companyPrefix, serviceReference));
+ gsrnp.setEpcRawURI(String.format("urn:epc:raw:%s.x%s", tagSize.getValue(), outputHex ));
+ gsrnp.setBinary(outputBin);
+ gsrnp.setRfidTag(outputHex);
+
+ }
+
+ private Integer getCheckDigit() {
+ String value = new StringBuilder()
+ .append(companyPrefix)
+ .append(serviceReference)
+ .toString();
+
+ Integer d18 = (10 - ((3
+ * (Character.getNumericValue(value.charAt(0)) + Character.getNumericValue(value.charAt(2))
+ + Character.getNumericValue(value.charAt(4)) + Character.getNumericValue(value.charAt(6))
+ + Character.getNumericValue(value.charAt(8))
+ + Character.getNumericValue(value.charAt(10)) + Character.getNumericValue(value.charAt(12))
+ + Character.getNumericValue(value.charAt(14)) + Character.getNumericValue(value.charAt(16)))
+ + (Character.getNumericValue(value.charAt(1)) + Character.getNumericValue(value.charAt(3))
+ + Character.getNumericValue(value.charAt(5)) + Character.getNumericValue(value.charAt(7))
+ + Character.getNumericValue(value.charAt(9)) + Character.getNumericValue(value.charAt(11))
+ + Character.getNumericValue(value.charAt(13)) + Character.getNumericValue(value.charAt(15))))
+ % 10)) % 10;
+ return d18;
+ }
+
+
+ private String getBinary() {
+ StringBuilder bin = new StringBuilder();
+
+ bin.append( Converter.decToBin(tagSize.getHeader(), 8) );
+ bin.append( Converter.decToBin(filterValue.getValue(), 3) );
+ bin.append( Converter.decToBin(tableItem.getPartitionValue(), 3) );
+ bin.append( Converter.decToBin(Integer.parseInt(companyPrefix), tableItem.getM()) );
+ //bin.append( Converter.strZero(BigDec2Bin.dec2bin(serviceReference), tableItem.getN()) );
+ bin.append( Converter.decToBin(Integer.parseInt(serviceReference), tableItem.getN()) );
+ bin.append( Converter.decToBin(RESERVED, 24) );
+
+ return bin.toString();
+ }
+
+
+ public GSRNP getGSRNP() {
+ return gsrnp;
+ }
+
+ public String getRfidTag() {
+ return Converter.binToHex( getBinary() );
+ }
+
+
+
+ private void validateServiceReference() {
+ StringBuilder value = new StringBuilder()
+ .append(serviceReference);
+
+ if ( value.length()!=tableItem.getDigits() ) {
+ throw new IllegalArgumentException(String.format("Service Reference \"%s\" has %d length and should have %d length",
+ serviceReference, value.length(), tableItem.getDigits()));
+ }
+ }
+
+
+ private void validateCompanyPrefix() {
+ Optional optionalpPefixLenght = Optional.ofNullable(prefixLength);
+ if ( !optionalpPefixLenght.isPresent() ) {
+ throw new IllegalArgumentException("Company Prefix is invalid. Length not found in the partition table");
+ }
+
+ }
+
+
+
+
+ public static interface ChoiceStep {
+ ServiceReferenceStep withCompanyPrefix(String companyPrefix);
+ BuildStep withRFIDTag(String rfidTag);
+ BuildStep withEPCTagURI(String epcTagURI);
+ TagSizeStep withEPCPureIdentityURI(String epcPureIdentityURI);
+ }
+
+
+ public static interface ServiceReferenceStep {
+ TagSizeStep withServiceReference(String serviceReference);
+ }
+
+ public static interface TagSizeStep {
+ FilterValueStep withTagSize( GSRNPTagSize tagSize );
+ }
+
+ public static interface FilterValueStep {
+ BuildStep withFilterValue( GSRNPFilterValue filterValue );
+ }
+
+ public static interface BuildStep {
+ ParseGSRNP build();
+ }
+
+
+
+ private static class Steps implements ChoiceStep, ServiceReferenceStep, TagSizeStep, FilterValueStep, BuildStep {
+ private String companyPrefix;
+ private GSRNPTagSize tagSize;
+ private GSRNPFilterValue filterValue;
+ private String serviceReference;
+ private String rfidTag;
+ private String epcTagURI;
+ private String epcPureIdentityURI;
+
+ @Override
+ public ParseGSRNP build() {
+ return new ParseGSRNP(this);
+ }
+
+// @Override
+// public SerialStep withExtensionDigit(SSCCExtensionDigit extensionDigit) {
+// this.extensionDigit = extensionDigit;
+// return this;
+// }
+
+
+ @Override
+ public BuildStep withFilterValue(GSRNPFilterValue filterValue) {
+ this.filterValue = filterValue;
+ return this;
+ }
+
+ @Override
+ public FilterValueStep withTagSize(GSRNPTagSize tagSize) {
+ this.tagSize = tagSize;
+ return this;
+ }
+
+ @Override
+ public TagSizeStep withServiceReference(String serviceReference) {
+ this.serviceReference = serviceReference;
+ return this;
+ }
+
+ @Override
+ public ServiceReferenceStep withCompanyPrefix(String companyPrefix) {
+ this.companyPrefix = companyPrefix;
+ return this;
+ }
+
+ @Override
+ public BuildStep withRFIDTag(String rfidTag) {
+ this.rfidTag = rfidTag;
+ return this;
+ }
+
+ @Override
+ public BuildStep withEPCTagURI(String epcTagURI) {
+ this.epcTagURI = epcTagURI;
+ return this;
+ }
+
+ @Override
+ public TagSizeStep withEPCPureIdentityURI(String epcPureIdentityURI) {
+ this.epcPureIdentityURI = epcPureIdentityURI;
+ return this;
+ }
+
+
+
+
+ }
+
+}
+
+
+
+package org.epctagcoder.parse.SGLN;
+
+import org.epctagcoder.option.PrefixLength;
+import org.epctagcoder.option.SGLN.SGLNFilterValue;
+import org.epctagcoder.option.SGLN.SGLNHeader;
+import org.epctagcoder.option.SGLN.SGLNTagSize;
+import org.epctagcoder.option.SGLN.partitionTable.SGLNPartitionTableList;
+import org.epctagcoder.option.TableItem;
+import org.epctagcoder.result.SGLN;
+import org.epctagcoder.util.Converter;
+
+import java.util.Optional;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+public class ParseSGLN {
+
+ private SGLN sgln = new SGLN();
+ private String companyPrefix;
+ private PrefixLength prefixLength;
+ private SGLNTagSize tagSize;
+ private SGLNFilterValue filterValue;
+ private String locationReference;
+ private String extension;
+ private String rfidTag;
+ private String epcTagURI;
+ private String epcPureIdentityURI;
+ private TableItem tableItem;
+ private int remainder;
+
+ private ParseSGLN(Steps steps) {
+ companyPrefix = steps.getCompanyPrefix();
+ tagSize = steps.getTagSize();
+ filterValue = steps.getFilterValue();
+ locationReference = steps.getLocationReference();
+ extension = steps.getExtension();
+ rfidTag = steps.getRfidTag();
+ epcTagURI = steps.getEpcTagURI();
+ epcPureIdentityURI = steps.getEpcPureIdentityURI();
+ parse();
+ }
+
+ public static ChoiceStep Builder() throws Exception {
+ return new Steps();
+ }
+
+ private void parse() {
+ Optional optionalCompanyPrefix = Optional.ofNullable(companyPrefix);
+ Optional optionalRfidTag = Optional.ofNullable(rfidTag);
+ Optional optionalEpcTagURI = Optional.ofNullable(epcTagURI);
+ Optional optionalEpcPureIdentityURI = Optional.ofNullable(epcPureIdentityURI);
+
+ if (optionalRfidTag.isPresent()) {
+ parseRfidTag();
+ } else {
+ if (optionalCompanyPrefix.isPresent()) {
+ SGLNPartitionTableList partitionTableList = new SGLNPartitionTableList();
+ prefixLength = PrefixLength.forCode(companyPrefix.length());
+ validateCompanyPrefix();
+ tableItem = partitionTableList.getPartitionByL(prefixLength.getValue());
+ validateLocationReference();
+ validateExtension();
+ } else {
+ if (optionalEpcTagURI.isPresent()) {
+ parseEpcTagURI();
+ } else if (optionalEpcPureIdentityURI.isPresent()) {
+ parseEpcPureIdentityURI();
+ }
+ }
+ SGLNPartitionTableList partitionTableList = new SGLNPartitionTableList();
+ tableItem = partitionTableList.getPartitionByL(prefixLength.getValue());
+ }
+
+ String outputBin = getBinary();
+ String outputHex = Converter.binToHex(outputBin);
+ sgln.setEpcScheme("sgln");
+ sgln.setApplicationIdentifier("AI 254");
+ sgln.setTagSize(Integer.toString(tagSize.getValue()));
+ sgln.setFilterValue(Integer.toString(filterValue.getValue()));
+ sgln.setPartitionValue(Integer.toString(tableItem.getPartitionValue()));
+ sgln.setPrefixLength(Integer.toString(prefixLength.getValue()));
+ sgln.setCompanyPrefix(companyPrefix);
+ sgln.setLocationReference(locationReference);
+ sgln.setExtension(extension);
+ sgln.setCheckDigit(Integer.toString(getCheckDigit()));
+ sgln.setEpcPureIdentityURI(String.format("urn:epc:id:sgln:%s.%s.%s", companyPrefix, locationReference, extension));
+ sgln.setEpcTagURI(String.format("urn:epc:tag:sgln-%s:%s.%s.%s.%s", tagSize.getValue(), filterValue.getValue(), companyPrefix, locationReference, extension));
+ sgln.setEpcRawURI(String.format("urn:epc:raw:%s.x%s", tagSize.getValue() + remainder, outputHex));
+ sgln.setBinary(outputBin);
+ sgln.setRfidTag(outputHex);
+
+ }
+
+ private void parseRfidTag() {
+ String inputBin = Converter.hexToBin(rfidTag);
+ String headerBin = inputBin.substring(0, 8);
+ String filterBin = inputBin.substring(8, 11);
+ String partitionBin = inputBin.substring(11, 14);
+ SGLNPartitionTableList partitionTableList = new SGLNPartitionTableList();
+
+ tagSize = SGLNTagSize.forCode(SGLNHeader.forCode(headerBin).getTagSize());
+ tableItem = partitionTableList.getPartitionByValue(Integer.parseInt(partitionBin, 2));
+ String filterDec = Long.toString(Long.parseLong(filterBin, 2));
+ String companyPrefixBin = inputBin.substring(14, 14 + tableItem.getM());
+ String locationReferenceBin = inputBin.substring(14 + tableItem.getM(), 14 + tableItem.getM() + tableItem.getN());
+ String extensionBin = inputBin.substring(14 + tableItem.getM() + tableItem.getN());
+
+ String companyPrefixDec = Converter.binToDec(companyPrefixBin);
+ String locationReferenceDec = Converter.binToDec(locationReferenceBin);
+
+ locationReference = Converter.strZero(locationReferenceDec, tableItem.getDigits());
+
+ if (tagSize.getSerialBitCount() == 140) {
+ extensionBin = Converter.convertBinToBit(extensionBin, 7, 8);
+ extension = Converter.binToString(extensionBin);
+ } else if (tagSize.getSerialBitCount() == 41) {
+ extension = Converter.binToDec(extensionBin);
+ }
+ companyPrefix = Converter.strZero(companyPrefixDec, tableItem.getL()); // strzero aqui
+ filterValue = SGLNFilterValue.forCode(Integer.parseInt(filterDec));
+ prefixLength = PrefixLength.forCode(tableItem.getL());
+
+
+ }
+
+ private void parseEpcTagURI() {
+ Pattern pattern = Pattern.compile("(urn:epc:tag:sgln-)(96|195)\\:([0-7])\\.(\\d+)\\.(\\d+)\\.((\\w|/)+)");
+ Matcher matcher = pattern.matcher(epcTagURI);
+
+ if (matcher.matches()) {
+ tagSize = SGLNTagSize.forCode(Integer.parseInt(matcher.group(2)));
+ filterValue = SGLNFilterValue.forCode(Integer.parseInt(matcher.group(3)));
+ companyPrefix = matcher.group(4);
+ prefixLength = PrefixLength.forCode(matcher.group(4).length());
+ locationReference = matcher.group(5);
+ extension = matcher.group(6);
+ } else {
+ throw new IllegalArgumentException("EPC Tag URI is invalid");
+ }
+ }
+
+ private void parseEpcPureIdentityURI() {
+ Pattern pattern = Pattern.compile("(urn:epc:id:sgln)\\:(\\d+)\\.(\\d+)\\.(\\w+)");
+ Matcher matcher = pattern.matcher(epcPureIdentityURI);
+
+ if (matcher.matches()) {
+ companyPrefix = matcher.group(2);
+ prefixLength = PrefixLength.forCode(matcher.group(2).length());
+ locationReference = matcher.group(3);
+ extension = matcher.group(4);
+ } else {
+ throw new IllegalArgumentException("EPC Pure Identity is invalid");
+ }
+ }
+
+ private String getBinary() {
+ StringBuilder bin = new StringBuilder();
+
+ remainder = (int) (Math.ceil((tagSize.getValue() / 16.0)) * 16) - tagSize.getValue();
+ bin.append(Converter.decToBin(tagSize.getHeader(), 8));
+ bin.append(Converter.decToBin(filterValue.getValue(), 3));
+ bin.append(Converter.decToBin(tableItem.getPartitionValue(), 3));
+ bin.append(Converter.decToBin(Integer.parseInt(companyPrefix), tableItem.getM()));
+ bin.append(Converter.decToBin(Integer.parseInt(locationReference), tableItem.getN()));
+
+ if (tagSize.getValue() == 195) {
+ bin.append(Converter.fill(Converter.StringToBinary(extension, 7), tagSize.getSerialBitCount() + remainder));
+ } else if (tagSize.getValue() == 96) {
+ bin.append(Converter.decToBin(extension, tagSize.getSerialBitCount() + remainder));
+ }
+
+ return bin.toString();
+ }
+
+ private Integer getCheckDigit() {
+ String value = companyPrefix +
+ locationReference;
+
+ return (10 - ((3
+ * (Character.getNumericValue(value.charAt(1)) + Character.getNumericValue(value.charAt(3))
+ + Character.getNumericValue(value.charAt(5))
+ + Character.getNumericValue(value.charAt(7)) + Character.getNumericValue(value.charAt(9))
+ + Character.getNumericValue(value.charAt(11)))
+ + (Character.getNumericValue(value.charAt(0)) + Character.getNumericValue(value.charAt(2))
+ + Character.getNumericValue(value.charAt(4)) + Character.getNumericValue(value.charAt(6))
+ + Character.getNumericValue(value.charAt(8)) + Character.getNumericValue(value.charAt(10))))
+ % 10)) % 10;
+ }
+
+ public SGLN getSGLN() {
+ return sgln;
+ }
+
+ public String getRfidTag() {
+ return Converter.binToHex(getBinary());
+ }
+
+
+ private void validateCompanyPrefix() {
+ Optional optionalPrefixLength = Optional.ofNullable(prefixLength);
+ if (optionalPrefixLength.isPresent()) {
+ throw new IllegalArgumentException("Company Prefix is invalid. Length not found in the partition table");
+ }
+ }
+
+ private void validateLocationReference() {
+ if (locationReference.length() != tableItem.getDigits()) {
+ throw new IllegalArgumentException(String.format("Location Reference \"%s\" has %d length and should have %d length",
+ locationReference, locationReference.length(), tableItem.getDigits()));
+ }
+ }
+
+ private void validateExtension() {
+ if (tagSize.getValue() == 195) {
+ if (extension.length() > tagSize.getSerialMaxLenght()) {
+ throw new IllegalArgumentException(String.format("Extension value is out of range. Should be up to %d alphanumeric characters",
+ tagSize.getSerialMaxLenght()));
+ }
+ } else if (tagSize.getValue() == 96) {
+ if (Long.parseLong(extension) > tagSize.getSerialMaxValue()) {
+ throw new IllegalArgumentException(String.format("Extension value is out of range. Should be less than or equal %d",
+ tagSize.getSerialMaxValue()));
+ }
+ }
+ }
+
+ public static interface ChoiceStep {
+ LocationReferenceStep withCompanyPrefix(String companyPrefix);
+
+ BuildStep withRFIDTag(String rfidTag);
+
+ BuildStep withEPCTagURI(String epcTagURI);
+
+ TagSizeStep withEPCPureIdentityURI(String epcPureIdentityURI);
+ }
+
+ public static interface BuildStep {
+ ParseSGLN build();
+ }
+
+ public static interface TagSizeStep {
+ FilterValueStep withTagSize(SGLNTagSize tagSize);
+ }
+
+ public static interface LocationReferenceStep {
+ ExtensionStep withLocationReference(String locationReference);
+ }
+
+ public static interface ExtensionStep {
+ TagSizeStep withExtension(String extension);
+ }
+
+ public static interface FilterValueStep {
+ BuildStep withFilterValue(SGLNFilterValue filterValue);
+ }
+
+ private static class Steps implements ChoiceStep, LocationReferenceStep, ExtensionStep, TagSizeStep, FilterValueStep, BuildStep {
+
+ private String companyPrefix;
+ private SGLNTagSize tagSize;
+ private SGLNFilterValue filterValue;
+ private String locationReference;
+ private String extension;
+
+ private String rfidTag;
+ private String epcTagURI;
+ private String epcPureIdentityURI;
+
+ @Override
+ public ParseSGLN build() {
+ return new ParseSGLN(this);
+ }
+
+ @Override
+ public LocationReferenceStep withCompanyPrefix(String companyPrefix) {
+ this.companyPrefix = companyPrefix;
+ return this;
+ }
+
+ @Override
+ public BuildStep withRFIDTag(String rfidTag) {
+ this.rfidTag = rfidTag;
+ return this;
+ }
+
+ @Override
+ public BuildStep withEPCTagURI(String epcTagURI) {
+ this.epcTagURI = epcTagURI;
+ return this;
+ }
+
+ @Override
+ public TagSizeStep withEPCPureIdentityURI(String epcPureIdentityURI) {
+ this.epcPureIdentityURI = epcPureIdentityURI;
+ return this;
+ }
+
+ @Override
+ public TagSizeStep withExtension(String extension) {
+ this.extension = extension;
+ return this;
+ }
+
+ @Override
+ public BuildStep withFilterValue(SGLNFilterValue filterValue) {
+ this.filterValue = filterValue;
+ return this;
+ }
+
+ @Override
+ public ExtensionStep withLocationReference(String locationReference) {
+ this.locationReference = locationReference;
+ return this;
+ }
+
+ @Override
+ public FilterValueStep withTagSize(SGLNTagSize tagSize) {
+ this.tagSize = tagSize;
+ return this;
+ }
+
+ public String getCompanyPrefix() {
+ return companyPrefix;
+ }
+
+ public SGLNTagSize getTagSize() {
+ return tagSize;
+ }
+
+ public SGLNFilterValue getFilterValue() {
+ return filterValue;
+ }
+
+ public String getLocationReference() {
+ return locationReference;
+ }
+
+ public String getExtension() {
+ return extension;
+ }
+
+ public String getRfidTag() {
+ return rfidTag;
+ }
+
+ public String getEpcTagURI() {
+ return epcTagURI;
+ }
+
+ public String getEpcPureIdentityURI() {
+ return epcPureIdentityURI;
+ }
+ }
+
+
+}
+
+
+
+package org.epctagcoder.parse.SGTIN;
+
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import org.epctagcoder.exception.EPCParseException;
+import org.epctagcoder.option.PrefixLength;
+import org.epctagcoder.option.TableItem;
+import org.epctagcoder.option.SGTIN.SGTINExtensionDigit;
+import org.epctagcoder.option.SGTIN.SGTINFilterValue;
+import org.epctagcoder.option.SGTIN.SGTINHeader;
+import org.epctagcoder.option.SGTIN.SGTINTagSize;
+import org.epctagcoder.option.SGTIN.partitionTable.SGTINPartitionTableList;
+import org.epctagcoder.result.SGTIN;
+import org.epctagcoder.util.Converter;
+
+public class ParseSGTIN {
+
+ private final SGTIN sgtin = new SGTIN();
+ private final String rfidTag;
+ private final String epcTagURI;
+ private final String epcPureIdentityURI;
+
+ private SGTINExtensionDigit extensionDigit;
+ private String companyPrefix;
+ private PrefixLength prefixLength;
+ private SGTINTagSize tagSize;
+ private SGTINFilterValue filterValue;
+ private String itemReference;
+ private String serial;
+ private TableItem tableItem;
+ private int remainder;
+
+ public static ChoiceStep Builder() {
+ return new Steps();
+ }
+
+ private ParseSGTIN(Steps steps) throws EPCParseException {
+ this.extensionDigit = steps.extensionDigit;
+ this.companyPrefix = steps.companyPrefix;
+ this.tagSize = steps.tagSize;
+ this.filterValue = steps.filterValue;
+ this.itemReference = steps.itemReference;
+ this.serial = steps.serial;
+ this.rfidTag = steps.rfidTag;
+ this.epcTagURI = steps.epcTagURI;
+ this.epcPureIdentityURI = steps.epcPureIdentityURI;
+ parse();
+ }
+
+ private void parseRfidTag() throws EPCParseException {
+ String inputBin = Converter.hexToBin(rfidTag);
+ String headerBin = inputBin.substring(0, 8);
+ String filterBin = inputBin.substring(8, 11);
+ String partitionBin = inputBin.substring(11, 14);
+ SGTINPartitionTableList sgtinPartitionTableList = new SGTINPartitionTableList();
+
+ tagSize = SGTINTagSize.forCode(SGTINHeader.forCode(headerBin).getTagSize());
+ tableItem = sgtinPartitionTableList.getPartitionByValue( Integer.parseInt(partitionBin, 2) );
+
+ String filterDec = Long.toString( Long.parseLong(filterBin, 2) );
+ String companyPrefixBin = inputBin.substring(14, 14+tableItem.getM());
+ String itemReferenceWithExtensionBin = inputBin.substring(14+tableItem.getM(), 14+tableItem.getM()+tableItem.getN());
+
+ String serialBin = inputBin.substring(14+tableItem.getM()+tableItem.getN() )
+ .substring(0, tagSize.getSerialBitCount());
+
+ String companyPrefixDec = Converter.binToDec(companyPrefixBin);
+ String itemReferenceWithExtensionDec = Converter.strZero(Converter.binToDec(itemReferenceWithExtensionBin), tableItem.getDigits());
+ String extensionDec = itemReferenceWithExtensionDec.substring(0,1);
+
+ itemReference = itemReferenceWithExtensionDec.substring(1);
+
+ if (tagSize.getSerialBitCount()==140) {
+ serialBin = Converter.convertBinToBit(serialBin, 7, 8);
+ serial = Converter.binToString(serialBin);
+ } else if (tagSize.getSerialBitCount()==38) {
+ serial = Converter.binToDec(serialBin);
+ }
+
+ companyPrefix = Converter.strZero(companyPrefixDec, tableItem.getL());
+ extensionDigit = SGTINExtensionDigit.forCode( Integer.parseInt(extensionDec) );
+ filterValue = SGTINFilterValue.forCode( Integer.parseInt(filterDec) );
+ prefixLength = PrefixLength.forCode(tableItem.getL());
+ }
+
+ private void parseCompanyPrefix() throws EPCParseException {
+ SGTINPartitionTableList sgtinPartitionTableList = new SGTINPartitionTableList();
+ prefixLength = PrefixLength.forCode(companyPrefix.length());
+
+ validateCompanyPrefix();
+
+ tableItem = sgtinPartitionTableList.getPartitionByL(prefixLength.getValue());
+
+ validateExtensionDigitAndItemReference();
+ validateSerial();
+ }
+
+ private void parseTagUri() throws EPCParseException {
+ Pattern pattern = Pattern.compile("(urn:epc:tag:sgtin-)(96|198):([0-7])\\.(\\d+)\\.([0-8])(\\d+)\\.(\\w+)");
+ Matcher matcher = pattern.matcher(epcTagURI);
+
+ if (matcher.matches()) {
+ tagSize = SGTINTagSize.forCode(Integer.parseInt(matcher.group(2)));
+ filterValue = SGTINFilterValue.forCode(Integer.parseInt(matcher.group(3)));
+ companyPrefix = matcher.group(4);
+ prefixLength = PrefixLength.forCode(matcher.group(4).length());
+ extensionDigit = SGTINExtensionDigit.forCode(Integer.parseInt(matcher.group(5)));
+ itemReference = matcher.group(6);
+ serial = matcher.group(7);
+ } else {
+ throw new EPCParseException("EPC Tag URI is invalid");
+ }
+ }
+
+ private void parsePureIdentityUri() throws EPCParseException {
+ Pattern pattern = Pattern.compile("(urn:epc:id:sgtin):(\\d+)\\.([0-8])(\\d+)\\.(\\w+)");
+ Matcher matcher = pattern.matcher(epcPureIdentityURI);
+
+ if (matcher.matches()) {
+ companyPrefix = matcher.group(2);
+ prefixLength = PrefixLength.forCode(matcher.group(2).length());
+ extensionDigit = SGTINExtensionDigit.forCode(Integer.parseInt(matcher.group(3)));
+ itemReference = matcher.group(4);
+ serial = matcher.group(5);
+ } else {
+ throw new EPCParseException("EPC Pure Identity is invalid");
+ }
+ }
+
+ private void parse() throws EPCParseException {
+
+ if(rfidTag != null) {
+ parseRfidTag();
+ } else if (extensionDigit != null) {
+ parseCompanyPrefix();
+ } else {
+ if (epcTagURI != null) {
+ parseTagUri();
+ } else if (epcPureIdentityURI != null) {
+ parsePureIdentityUri();
+ }
+
+ SGTINPartitionTableList sgtinPartitionTableList = new SGTINPartitionTableList();
+ tableItem = sgtinPartitionTableList.getPartitionByL(prefixLength.getValue());
+ }
+
+ String outputBin = getBinary();
+ String outputHex = Converter.binToHex( outputBin );
+
+ sgtin.setEpcScheme("sgtin");
+ sgtin.setApplicationIdentifier("AI 414 + AI 254");
+ sgtin.setTagSize(Integer.toString(tagSize.getValue()));
+ sgtin.setFilterValue(Integer.toString(filterValue.getValue()));
+ sgtin.setPartitionValue(Integer.toString(tableItem.getPartitionValue()));
+ sgtin.setPrefixLength(Integer.toString(prefixLength.getValue()));
+ sgtin.setCompanyPrefix(companyPrefix);
+ sgtin.setItemReference(itemReference);
+ sgtin.setExtensionDigit(Integer.toString(extensionDigit.getValue()));
+ sgtin.setSerial(serial);
+ sgtin.setCheckDigit(Integer.toString(getCheckDigit()));
+ sgtin.setEpcPureIdentityURI(String.format("urn:epc:id:sgtin:%s.%s%s.%s", companyPrefix, extensionDigit.getValue(), itemReference, serial));
+ sgtin.setEpcTagURI(String.format("urn:epc:tag:sgtin-%s:%s.%s.%s%s.%s", tagSize.getValue(), filterValue.getValue(), companyPrefix, extensionDigit.getValue(), itemReference, serial));
+ sgtin.setEpcRawURI(String.format("urn:epc:raw:%s.x%s", tagSize.getValue()+remainder, outputHex ));
+ sgtin.setBinary(outputBin);
+ sgtin.setRfidTag(outputHex);
+ }
+
+ private String getBinary() {
+ StringBuilder bin = new StringBuilder();
+
+ remainder = (int) (Math.ceil((tagSize.getValue()/16.0))*16)-tagSize.getValue();
+
+ bin.append( Converter.decToBin(tagSize.getHeader(), 8) );
+ bin.append( Converter.decToBin(filterValue.getValue(), 3) );
+ bin.append( Converter.decToBin(tableItem.getPartitionValue(), 3) );
+ bin.append( Converter.decToBin(companyPrefix, tableItem.getM()) );
+ bin.append( Converter.decToBin(Integer.parseInt(extensionDigit.getValue() +itemReference), tableItem.getN()) );
+
+ if (tagSize.getValue()==198) {
+ bin.append( Converter.fill(Converter.StringToBinary(serial, 7), tagSize.getSerialBitCount()+remainder ) );
+ } else if (tagSize.getValue()==96) {
+ bin.append( Converter.decToBin(serial, tagSize.getSerialBitCount()+remainder ) );
+ }
+
+ return bin.toString();
+ }
+
+ private Integer getCheckDigit() {
+ String value = extensionDigit.getValue() + companyPrefix + itemReference;
+
+ return (10 - ((3
+ * (Character.getNumericValue(value.charAt(0)) + Character.getNumericValue(value.charAt(2))
+ + Character.getNumericValue(value.charAt(4))
+ + Character.getNumericValue(value.charAt(6)) + Character.getNumericValue(value.charAt(8))
+ + Character.getNumericValue(value.charAt(10)) + Character.getNumericValue(value.charAt(12)))
+ + (Character.getNumericValue(value.charAt(1)) + Character.getNumericValue(value.charAt(3))
+ + Character.getNumericValue(value.charAt(5)) + Character.getNumericValue(value.charAt(7))
+ + Character.getNumericValue(value.charAt(9)) + Character.getNumericValue(value.charAt(11))))
+ % 10)) % 10;
+ }
+
+
+ public SGTIN getSGTIN() {
+ return sgtin;
+ }
+
+ public String getRfidTag() {
+ return Converter.binToHex( getBinary() );
+ }
+
+ private void validateExtensionDigitAndItemReference() throws EPCParseException {
+ StringBuilder value = new StringBuilder()
+ .append(extensionDigit.getValue())
+ .append(itemReference);
+
+ if ( value.length()!=tableItem.getDigits() ) {
+ String message = "Concatenation between Extension Digit \"%d\" and " +
+ "Item Reference \"%s\" has %d length and should have %d length";
+ throw new EPCParseException(String.format(message,
+ extensionDigit.getValue(), itemReference, value.length(), tableItem.getDigits()));
+ }
+ }
+
+ private void validateCompanyPrefix() throws EPCParseException {
+ if(prefixLength == null) {
+ throw new EPCParseException("Company Prefix is invalid. Length not found in the partition table");
+ }
+ }
+
+ private void validateSerial() throws EPCParseException {
+ if (tagSize.getValue()==198 ) {
+ if ( serial.length()>tagSize.getSerialMaxLenght() ) {
+ throw new EPCParseException("Serial value is out of range. Should be up to 20 alphanumeric characters");
+ }
+ } else if (tagSize.getValue()==96 ) {
+ if ( Long.parseLong(serial) >tagSize.getSerialMaxValue() ) {
+ throw new EPCParseException("Serial value is out of range. Should be less than or equal 274,877,906,943");
+ }
+ if ( serial.startsWith("0") ) {
+ throw new EPCParseException("Serial with leading zeros is not allowed");
+ }
+ }
+
+ }
+
+ public interface ChoiceStep {
+ ExtensionDigitStep withCompanyPrefix(String companyPrefix);
+ BuildStep withRFIDTag(String rfidTag);
+ BuildStep withEPCTagURI(String epcTagURI);
+ TagSizeStep withEPCPureIdentityURI(String epcPureIdentityURI);
+ }
+
+ public interface ExtensionDigitStep {
+ ItemReferenceStep withExtensionDigit(SGTINExtensionDigit extensionDigit);
+ }
+
+ public interface ItemReferenceStep {
+ SerialStep withItemReference(String itemReference);
+ }
+
+ public interface SerialStep {
+ TagSizeStep withSerial(String serial);
+ }
+
+ public interface TagSizeStep {
+ FilterValueStep withTagSize( SGTINTagSize tagSize );
+ }
+
+ public interface FilterValueStep {
+ BuildStep withFilterValue( SGTINFilterValue filterValue );
+ }
+
+ public interface BuildStep {
+ ParseSGTIN build() throws EPCParseException;
+ }
+
+ private static class Steps implements ChoiceStep, ExtensionDigitStep, ItemReferenceStep, SerialStep, TagSizeStep, FilterValueStep, BuildStep {
+ private SGTINExtensionDigit extensionDigit;
+ private String companyPrefix;
+ private SGTINTagSize tagSize;
+ private SGTINFilterValue filterValue;
+ private String itemReference;
+ private String serial;
+ private String rfidTag;
+ private String epcTagURI;
+ private String epcPureIdentityURI;
+
+ @Override
+ public ParseSGTIN build() throws EPCParseException {
+ return new ParseSGTIN(this);
+ }
+
+ @Override
+ public ItemReferenceStep withExtensionDigit(SGTINExtensionDigit extensionDigit) {
+ this.extensionDigit = extensionDigit;
+ return this;
+ }
+
+ @Override
+ public SerialStep withItemReference(String itemReference) {
+ this.itemReference = itemReference;
+ return this;
+ }
+
+ @Override
+ public TagSizeStep withSerial(String serial) {
+ this.serial = serial;
+ return this;
+ }
+
+ @Override
+ public FilterValueStep withTagSize(SGTINTagSize tagSize) {
+ this.tagSize = tagSize;
+ return this;
+ }
+
+ @Override
+ public BuildStep withFilterValue(SGTINFilterValue filterValue) {
+ this.filterValue = filterValue;
+ return this;
+ }
+
+ @Override
+ public BuildStep withRFIDTag(String rfidTag) {
+ this.rfidTag = rfidTag;
+ return this;
+ }
+
+ @Override
+ public BuildStep withEPCTagURI(String epcTagURI) {
+ this.epcTagURI = epcTagURI;
+ return this;
+ }
+
+ @Override
+ public TagSizeStep withEPCPureIdentityURI(String epcPureIdentityURI) {
+ this.epcPureIdentityURI = epcPureIdentityURI;
+ return this;
+ }
+
+ @Override
+ public ExtensionDigitStep withCompanyPrefix(String companyPrefix) {
+ this.companyPrefix = companyPrefix;
+ return this;
+ }
+ }
+}
+
+
+
+package org.epctagcoder.parse.SSCC;
+
+import java.util.Optional;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+
+import org.epctagcoder.option.PrefixLength;
+import org.epctagcoder.option.TableItem;
+import org.epctagcoder.option.SSCC.SSCCExtensionDigit;
+import org.epctagcoder.option.SSCC.SSCCFilterValue;
+import org.epctagcoder.option.SSCC.SSCCHeader;
+import org.epctagcoder.option.SSCC.SSCCTagSize;
+import org.epctagcoder.option.SSCC.partitionTable.SSCCPartitionTableList;
+import org.epctagcoder.result.SSCC;
+import org.epctagcoder.util.Converter;
+
+public class ParseSSCC {
+ private static final Integer RESERVED = 0; // 24 zero bits
+ private SSCC sscc = new SSCC();
+ private SSCCExtensionDigit extensionDigit;
+ private String companyPrefix;
+ private PrefixLength prefixLength;
+ private SSCCTagSize tagSize;
+ private SSCCFilterValue filterValue;
+ private String serial;
+ private String rfidTag;
+ private String epcTagURI;
+ private String epcPureIdentityURI;
+ private TableItem tableItem;
+
+ public static ChoiceStep Builder() throws Exception {
+ return new Steps();
+ }
+
+ private ParseSSCC(Steps steps) {
+ this.extensionDigit = steps.extensionDigit;
+ this.companyPrefix = steps.companyPrefix;
+ this.tagSize = steps.tagSize;
+ this.filterValue = steps.filterValue;
+ this.serial = steps.serial;
+ this.rfidTag = steps.rfidTag;
+ this.epcTagURI = steps.epcTagURI;
+ this.epcPureIdentityURI = steps.epcPureIdentityURI;
+ parse();
+ }
+
+
+ private void parse() {
+ Optional optionalCompanyPrefix = Optional.ofNullable(extensionDigit);
+ Optional optionalRfidTag = Optional.ofNullable(rfidTag);
+ Optional optionalEpcTagURI = Optional.ofNullable(epcTagURI);
+ Optional optionalEpcPureIdentityURI = Optional.ofNullable(epcPureIdentityURI);
+
+ if ( optionalRfidTag.isPresent() ) {
+ String inputBin = Converter.hexToBin(rfidTag);
+ String headerBin = inputBin.substring(0, 8);
+ String filterBin = inputBin.substring(8,11);
+ String partitionBin = inputBin.substring(11,14);
+ SSCCPartitionTableList ssccPartitionTableList = new SSCCPartitionTableList();
+
+ tableItem = ssccPartitionTableList.getPartitionByValue( Integer.parseInt(partitionBin, 2) );
+
+ String companyPrefixBin = inputBin.substring(14,14+tableItem.getM());
+ String serialWithExtensionBin = inputBin.substring(14+tableItem.getM(),14+tableItem.getM()+tableItem.getN());
+ String filterDec = Long.toString( Long.parseLong(filterBin, 2) );
+ String companyPrefixDec = Converter.binToDec(companyPrefixBin);
+ String serialWithExtension = Converter.strZero(Converter.binToDec(serialWithExtensionBin), tableItem.getDigits() );
+ String extensionDec = serialWithExtension.substring(0,1);
+
+ serial = serialWithExtension.substring(1);
+ companyPrefix = Converter.strZero(companyPrefixDec, tableItem.getL());
+ extensionDigit = SSCCExtensionDigit.forCode( Integer.parseInt(extensionDec) );
+ filterValue = SSCCFilterValue.forCode( Integer.parseInt(filterDec) );
+ tagSize = SSCCTagSize.forCode( SSCCHeader.forCode(headerBin).getTagSize() );
+ prefixLength = PrefixLength.forCode(tableItem.getL());
+
+ } else {
+
+ if ( optionalCompanyPrefix.isPresent() ) {
+ SSCCPartitionTableList ssccPartitionTableList = new SSCCPartitionTableList();
+ prefixLength = PrefixLength.forCode( companyPrefix.length() );
+ validateCompanyPrefix();
+ tableItem = ssccPartitionTableList.getPartitionByL( prefixLength.getValue() );
+ validateExtensionDigitAndSerial();
+ } else {
+ if ( optionalEpcTagURI.isPresent() ) {
+ Pattern pattern = Pattern.compile("(urn:epc:tag:sscc-)(96)\\:([0-7])\\.(\\d+)\\.([0-9])(\\d+)");
+ Matcher matcher = pattern.matcher(epcTagURI);
+
+ if ( matcher.matches() ) {
+ tagSize = SSCCTagSize.forCode( Integer.parseInt(matcher.group(2)) );
+ filterValue = SSCCFilterValue.forCode( Integer.parseInt(matcher.group(3)) );
+ companyPrefix = matcher.group(4);
+ prefixLength = PrefixLength.forCode( matcher.group(4).length() );
+ extensionDigit = SSCCExtensionDigit.forCode( Integer.parseInt(matcher.group(5)) );
+ serial = matcher.group(6);
+ } else {
+ throw new IllegalArgumentException("EPC Tag URI is invalid");
+ }
+
+ } else if ( optionalEpcPureIdentityURI.isPresent() ) {
+ Pattern pattern = Pattern.compile("(urn:epc:id:sscc)\\:(\\d+)\\.([0-9])(\\d+)");
+ Matcher matcher = pattern.matcher(epcPureIdentityURI);
+
+ if ( matcher.matches() ) {
+ companyPrefix = matcher.group(2);
+ prefixLength = PrefixLength.forCode( matcher.group(2).length() );
+ extensionDigit = SSCCExtensionDigit.forCode( Integer.parseInt(matcher.group(3)) );
+ serial = matcher.group(4);
+ } else {
+ throw new IllegalArgumentException("EPC Pure Identity is invalid");
+ }
+
+
+ }
+
+ if (prefixLength==null) {
+ throw new IllegalArgumentException("Invalid Prefix Length");
+ } else {
+ SSCCPartitionTableList ssccPartitionTableList = new SSCCPartitionTableList();
+ tableItem = ssccPartitionTableList.getPartitionByL( prefixLength.getValue() );
+ }
+
+ }
+
+ }
+
+
+ String outputBin = getBinary();
+ String outputHex = Converter.binToHex( outputBin );
+
+ sscc.setEpcScheme("sscc");
+ sscc.setApplicationIdentifier("AI 00");
+ sscc.setTagSize(Integer.toString(tagSize.getValue()));
+ sscc.setFilterValue(Integer.toString(filterValue.getValue()) );
+ sscc.setPartitionValue(Integer.toString(tableItem.getPartitionValue()));
+ sscc.setPrefixLength(Integer.toString(prefixLength.getValue()));
+ sscc.setCompanyPrefix(companyPrefix);
+ sscc.setExtensionDigit(Integer.toString(extensionDigit.getValue()));
+ sscc.setSerial(serial);
+ sscc.setCheckDigit(Integer.toString(getCheckDigit()));
+ sscc.setEpcPureIdentityURI(String.format("urn:epc:id:sscc:%s.%s%s", companyPrefix, extensionDigit.getValue(), serial));
+ sscc.setEpcTagURI(String.format("urn:epc:tag:sscc-%s:%s.%s.%s%s", tagSize.getValue(),
+ filterValue.getValue(), companyPrefix, extensionDigit.getValue(), serial));
+ sscc.setEpcRawURI(String.format("urn:epc:raw:%s.x%s", tagSize.getValue(), outputHex ));
+ sscc.setBinary(outputBin);
+ sscc.setRfidTag(outputHex);
+
+ }
+
+
+ private Integer getCheckDigit() {
+ String value = new StringBuilder()
+ .append(extensionDigit.getValue())
+ .append(companyPrefix)
+ .append(serial)
+ .toString();
+
+ Integer d18 = (10 - ((3
+ * (Character.getNumericValue(value.charAt(0)) + Character.getNumericValue(value.charAt(2))
+ + Character.getNumericValue(value.charAt(4)) + Character.getNumericValue(value.charAt(6))
+ + Character.getNumericValue(value.charAt(8))
+ + Character.getNumericValue(value.charAt(10)) + Character.getNumericValue(value.charAt(12))
+ + Character.getNumericValue(value.charAt(14)) + Character.getNumericValue(value.charAt(16)))
+ + (Character.getNumericValue(value.charAt(1)) + Character.getNumericValue(value.charAt(3))
+ + Character.getNumericValue(value.charAt(5)) + Character.getNumericValue(value.charAt(7))
+ + Character.getNumericValue(value.charAt(9)) + Character.getNumericValue(value.charAt(11))
+ + Character.getNumericValue(value.charAt(13)) + Character.getNumericValue(value.charAt(15))))
+ % 10)) % 10;
+ return d18;
+ }
+
+
+ private String getBinary() {
+ StringBuilder bin = new StringBuilder();
+
+ bin.append( Converter.decToBin(tagSize.getHeader(), 8) );
+ bin.append( Converter.decToBin(filterValue.getValue(), 3) );
+ bin.append( Converter.decToBin(tableItem.getPartitionValue(), 3) );
+ bin.append( Converter.decToBin(Integer.parseInt(companyPrefix), tableItem.getM()) );
+ bin.append( Converter.decToBin(extensionDigit.getValue()+serial, tableItem.getN()) );
+ bin.append( Converter.decToBin(RESERVED, 24) );
+
+ return bin.toString();
+ }
+
+
+ public SSCC getSSCC() {
+ return sscc;
+ }
+
+ public String getRfidTag() {
+ return Converter.binToHex( getBinary() );
+ }
+
+
+
+ private void validateExtensionDigitAndSerial() {
+ StringBuilder value = new StringBuilder()
+ .append(extensionDigit.getValue())
+ .append(serial);
+
+ if ( value.length()!=tableItem.getDigits() ) {
+ throw new IllegalArgumentException(String.format("Concatenation between Extension Digit \"%d\" and Serial \"%s\" has %d length and should have %d length",
+ extensionDigit.getValue(), serial, value.length(), tableItem.getDigits()));
+ }
+ }
+
+
+ private void validateCompanyPrefix() {
+ Optional optionalpPefixLenght = Optional.ofNullable(prefixLength);
+ if ( !optionalpPefixLenght.isPresent() ) {
+ throw new IllegalArgumentException("Company Prefix is invalid. Length not found in the partition table");
+ }
+
+ }
+
+
+
+
+ public static interface ChoiceStep {
+ ExtensionDigiStep withCompanyPrefix(String companyPrefix);
+ BuildStep withRFIDTag(String rfidTag);
+ BuildStep withEPCTagURI(String epcTagURI);
+ TagSizeStep withEPCPureIdentityURI(String epcPureIdentityURI);
+ }
+
+ public static interface ExtensionDigiStep {
+ SerialStep withExtensionDigit(SSCCExtensionDigit extensionDigit);
+ }
+
+ public static interface SerialStep {
+ TagSizeStep withSerial(String serial);
+ }
+
+ public static interface TagSizeStep {
+ FilterValueStep withTagSize( SSCCTagSize tagSize );
+ }
+
+ public static interface FilterValueStep {
+ BuildStep withFilterValue( SSCCFilterValue filterValue );
+ }
+
+ public static interface BuildStep {
+ ParseSSCC build();
+ }
+
+
+
+ private static class Steps implements ChoiceStep, ExtensionDigiStep, SerialStep, TagSizeStep, FilterValueStep, BuildStep {
+ private SSCCExtensionDigit extensionDigit;
+ private String companyPrefix;
+ private SSCCTagSize tagSize;
+ private SSCCFilterValue filterValue;
+ private String serial;
+ private String rfidTag;
+ private String epcTagURI;
+ private String epcPureIdentityURI;
+
+ @Override
+ public ParseSSCC build() {
+ return new ParseSSCC(this);
+ }
+
+
+ @Override
+ public SerialStep withExtensionDigit(SSCCExtensionDigit extensionDigit) {
+ this.extensionDigit = extensionDigit;
+ return this;
+ }
+
+ @Override
+ public ExtensionDigiStep withCompanyPrefix(String companyPrefix) {
+ this.companyPrefix = companyPrefix;
+ return this;
+ }
+
+ @Override
+ public TagSizeStep withSerial(String serial) {
+ this.serial = serial;
+ return this;
+ }
+
+ @Override
+ public FilterValueStep withTagSize(SSCCTagSize tagSize) {
+ this.tagSize = tagSize;
+ return this;
+ }
+
+ @Override
+ public BuildStep withFilterValue(SSCCFilterValue filterValue) {
+ this.filterValue = filterValue;
+ return this;
+ }
+
+ @Override
+ public BuildStep withRFIDTag(String rfidTag) {
+ this.rfidTag = rfidTag;
+ return this;
+ }
+
+
+ @Override
+ public BuildStep withEPCTagURI(String epcTagURI) {
+ this.epcTagURI = epcTagURI;
+ return this;
+ }
+
+
+ @Override
+ public TagSizeStep withEPCPureIdentityURI(String epcPureIdentityURI) {
+ this.epcPureIdentityURI = epcPureIdentityURI;
+ return this;
+ }
+
+ }
+
+}
+
+
+
+package org.epctagcoder.result;
+
+public abstract class Base {
+ private String epcScheme;
+ private String applicationIdentifier;
+ private String tagSize;
+ private String filterValue;
+ private String partitionValue;
+ private String prefixLength;
+ private String companyPrefix;
+ private String epcPureIdentityURI;
+ private String epcTagURI;
+ private String epcRawURI;
+ private String binary;
+ private String rfidTag;
+ private String exception;
+
+
+ public Base() {
+
+ }
+
+
+ public String getEpcScheme() {
+ return epcScheme;
+ }
+
+
+ public void setEpcScheme(String epcScheme) {
+ this.epcScheme = epcScheme;
+ }
+
+
+ public String getApplicationIdentifier() {
+ return applicationIdentifier;
+ }
+
+
+ public void setApplicationIdentifier(String applicationIdentifier) {
+ this.applicationIdentifier = applicationIdentifier;
+ }
+
+
+ public String getTagSize() {
+ return tagSize;
+ }
+
+
+ public void setTagSize(String tagSize) {
+ this.tagSize = tagSize;
+ }
+
+
+ public String getFilterValue() {
+ return filterValue;
+ }
+
+
+ public void setFilterValue(String filterValue) {
+ this.filterValue = filterValue;
+ }
+
+
+ public String getPartitionValue() {
+ return partitionValue;
+ }
+
+
+ public void setPartitionValue(String partitionValue) {
+ this.partitionValue = partitionValue;
+ }
+
+
+ public String getPrefixLength() {
+ return prefixLength;
+ }
+
+
+ public void setPrefixLength(String prefixLength) {
+ this.prefixLength = prefixLength;
+ }
+
+
+ public String getCompanyPrefix() {
+ return companyPrefix;
+ }
+
+
+ public void setCompanyPrefix(String companyPrefix) {
+ this.companyPrefix = companyPrefix;
+ }
+
+
+ public String getEpcPureIdentityURI() {
+ return epcPureIdentityURI;
+ }
+
+
+ public void setEpcPureIdentityURI(String epcPureIdentityURI) {
+ this.epcPureIdentityURI = epcPureIdentityURI;
+ }
+
+
+ public String getEpcTagURI() {
+ return epcTagURI;
+ }
+
+
+ public void setEpcTagURI(String epcTagURI) {
+ this.epcTagURI = epcTagURI;
+ }
+
+
+ public String getEpcRawURI() {
+ return epcRawURI;
+ }
+
+
+ public void setEpcRawURI(String epcRawURI) {
+ this.epcRawURI = epcRawURI;
+ }
+
+
+ public String getBinary() {
+ return binary;
+ }
+
+
+ public void setBinary(String binary) {
+ this.binary = binary;
+ }
+
+
+ public String getRfidTag() {
+ return rfidTag;
+ }
+
+
+ public void setRfidTag(String rfidTag) {
+ this.rfidTag = rfidTag;
+ }
+
+
+ public String getException() {
+ return exception;
+ }
+
+
+ public void setException(String exception) {
+ this.exception = exception;
+ }
+
+
+
+
+
+
+}
+
+
+
+package org.epctagcoder.result;
+
+public class CPI extends Base {
+ private String componentPartReference;
+ private String serial;
+
+
+
+ public CPI() {
+
+ }
+
+
+
+
+ @Override
+ public String toString() {
+ StringBuilder json = new StringBuilder();
+
+ json.append(String.format("{ \"epcScheme\": \"%s\"", getEpcScheme()))
+ .append(String.format(", \"applicationIdentifier\": \"%s\"", getApplicationIdentifier()))
+ .append(String.format(", \"tagSize\": \"%s\"", getTagSize()))
+ .append(String.format(", \"filterValue\": \"%s\"", getFilterValue()))
+ .append(String.format(", \"partitionValue\": \"%s\"", getPartitionValue()))
+ .append(String.format(", \"prefixLength\": \"%s\"", getPrefixLength()))
+ .append(String.format(", \"companyPrefix\": \"%s\"", getCompanyPrefix()))
+ .append(String.format(", \"componentPartReference\": \"%s\"", getComponentPartReference()))
+ .append(String.format(", \"serial\": \"%s\"", getSerial()))
+ .append(String.format(", \"epcPureIdentityURI\": \"%s\"", getEpcPureIdentityURI()))
+ .append(String.format(", \"epcTagURI\": \"%s\"", getEpcTagURI()))
+ .append(String.format(", \"epcRawURI\": \"%s\"", getEpcRawURI()))
+ .append(String.format(", \"binary\": \"%s\"", getBinary()))
+ .append(String.format(", \"rfidTag\": \"%s\"", getRfidTag())).append(" }");
+
+ return json.toString();
+ }
+
+
+
+
+ public String getComponentPartReference() {
+ return componentPartReference;
+ }
+
+
+
+
+ public void setComponentPartReference(String componentPartReference) {
+ this.componentPartReference = componentPartReference;
+ }
+
+
+
+
+ public String getSerial() {
+ return serial;
+ }
+
+
+
+
+ public void setSerial(String serial) {
+ this.serial = serial;
+ }
+
+
+
+
+
+
+
+}
+
+
+
+package org.epctagcoder.result;
+
+public class GDTI extends Base {
+ private String docType;
+ private String serial;
+ private String checkDigit;
+
+ public GDTI() {
+
+ }
+
+
+ public String getDocType() {
+ return docType;
+ }
+
+ public void setDocType(String docType) {
+ this.docType = docType;
+ }
+
+ public String getSerial() {
+ return serial;
+ }
+
+ public void setSerial(String serial) {
+ this.serial = serial;
+ }
+
+ public String getCheckDigit() {
+ return checkDigit;
+ }
+
+ public void setCheckDigit(String checkDigit) {
+ this.checkDigit = checkDigit;
+ }
+
+
+
+ @Override
+ public String toString() {
+ StringBuilder json = new StringBuilder();
+
+ json.append(String.format("{ \"epcScheme\": \"%s\"", getEpcScheme()))
+ .append(String.format(", \"applicationIdentifier\": \"%s\"", getApplicationIdentifier()))
+ .append(String.format(", \"tagSize\": \"%s\"", getTagSize()))
+ .append(String.format(", \"filterValue\": \"%s\"", getFilterValue()))
+ .append(String.format(", \"partitionValue\": \"%s\"", getPartitionValue()))
+ .append(String.format(", \"prefixLength\": \"%s\"", getPrefixLength()))
+ .append(String.format(", \"companyPrefix\": \"%s\"", getCompanyPrefix()))
+ .append(String.format(", \"docType\": \"%s\"", getDocType()))
+ .append(String.format(", \"serial\": \"%s\"", getSerial()))
+ .append(String.format(", \"checkDigit\": \"%s\"", getCheckDigit()))
+ .append(String.format(", \"epcPureIdentityURI\": \"%s\"", getEpcPureIdentityURI()))
+ .append(String.format(", \"epcTagURI\": \"%s\"", getEpcTagURI()))
+ .append(String.format(", \"epcRawURI\": \"%s\"", getEpcRawURI()))
+ .append(String.format(", \"binary\": \"%s\"", getBinary()))
+ .append(String.format(", \"rfidTag\": \"%s\"", getRfidTag())).append(" }");
+
+ return json.toString();
+ }
+
+
+
+
+
+
+
+
+
+
+
+}
+
+
+
+package org.epctagcoder.result;
+
+public class GIAI extends Base {
+ private String individualAssetReference;
+
+ public GIAI() {
+
+ }
+
+ public String getIndividualAssetReference() {
+ return individualAssetReference;
+ }
+
+ public void setIndividualAssetReference(String individualAssetReference) {
+ this.individualAssetReference = individualAssetReference;
+ }
+
+
+ @Override
+ public String toString() {
+ StringBuilder json = new StringBuilder();
+
+ json.append(String.format("{ \"epcScheme\": \"%s\"", getEpcScheme()))
+ .append(String.format(", \"applicationIdentifier\": \"%s\"", getApplicationIdentifier()))
+ .append(String.format(", \"tagSize\": \"%s\"", getTagSize()))
+ .append(String.format(", \"filterValue\": \"%s\"", getFilterValue()))
+ .append(String.format(", \"partitionValue\": \"%s\"", getPartitionValue()))
+ .append(String.format(", \"prefixLength\": \"%s\"", getPrefixLength()))
+ .append(String.format(", \"companyPrefix\": \"%s\"", getCompanyPrefix()))
+ .append(String.format(", \"individualAssetReference\": \"%s\"", getIndividualAssetReference()))
+ .append(String.format(", \"epcPureIdentityURI\": \"%s\"", getEpcPureIdentityURI()))
+ .append(String.format(", \"epcTagURI\": \"%s\"", getEpcTagURI()))
+ .append(String.format(", \"epcRawURI\": \"%s\"", getEpcRawURI()))
+ .append(String.format(", \"binary\": \"%s\"", getBinary()))
+ .append(String.format(", \"rfidTag\": \"%s\"", getRfidTag())).append(" }");
+
+ return json.toString();
+ }
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+}
+
+
+
+package org.epctagcoder.result;
+
+public class GRAI extends Base {
+ private String assetType;
+ private String serial;
+ private String checkDigit;
+
+ public GRAI() {
+
+ }
+
+
+ public String getAssetType() {
+ return assetType;
+ }
+
+ public void setAssetType(String assetType) {
+ this.assetType = assetType;
+ }
+
+ public String getSerial() {
+ return serial;
+ }
+
+ public void setSerial(String serial) {
+ this.serial = serial;
+ }
+
+ public String getCheckDigit() {
+ return checkDigit;
+ }
+
+ public void setCheckDigit(String checkDigit) {
+ this.checkDigit = checkDigit;
+ }
+
+
+
+ @Override
+ public String toString() {
+ StringBuilder json = new StringBuilder();
+
+ json.append(String.format("{ \"epcScheme\": \"%s\"", getEpcScheme()))
+ .append(String.format(", \"applicationIdentifier\": \"%s\"", getApplicationIdentifier()))
+ .append(String.format(", \"tagSize\": \"%s\"", getTagSize()))
+ .append(String.format(", \"filterValue\": \"%s\"", getFilterValue()))
+ .append(String.format(", \"partitionValue\": \"%s\"", getPartitionValue()))
+ .append(String.format(", \"prefixLength\": \"%s\"", getPrefixLength()))
+ .append(String.format(", \"companyPrefix\": \"%s\"", getCompanyPrefix()))
+ .append(String.format(", \"assetType\": \"%s\"", getAssetType()))
+ .append(String.format(", \"serial\": \"%s\"", getSerial()))
+ .append(String.format(", \"checkDigit\": \"%s\"", getCheckDigit()))
+ .append(String.format(", \"epcPureIdentityURI\": \"%s\"", getEpcPureIdentityURI()))
+ .append(String.format(", \"epcTagURI\": \"%s\"", getEpcTagURI()))
+ .append(String.format(", \"epcRawURI\": \"%s\"", getEpcRawURI()))
+ .append(String.format(", \"binary\": \"%s\"", getBinary()))
+ .append(String.format(", \"rfidTag\": \"%s\"", getRfidTag())).append(" }");
+
+ return json.toString();
+ }
+
+
+
+
+
+
+
+
+
+
+
+}
+
+
+
+package org.epctagcoder.result;
+
+public class GSRN extends Base {
+ private String serviceReference;
+ private String checkDigit;
+
+ public GSRN() {
+
+ }
+
+
+ public String getServiceReference() {
+ return serviceReference;
+ }
+
+ public void setServiceReference(String serviceReference) {
+ this.serviceReference = serviceReference;
+ }
+
+ public String getCheckDigit() {
+ return checkDigit;
+ }
+
+ public void setCheckDigit(String checkDigit) {
+ this.checkDigit = checkDigit;
+ }
+
+
+ @Override
+ public String toString() {
+ StringBuilder json = new StringBuilder();
+
+ json.append(String.format("{ \"epcScheme\": \"%s\"", getEpcScheme()))
+ .append(String.format(", \"applicationIdentifier\": \"%s\"", getApplicationIdentifier()))
+ .append(String.format(", \"tagSize\": \"%s\"", getTagSize()))
+ .append(String.format(", \"filterValue\": \"%s\"", getFilterValue()))
+ .append(String.format(", \"partitionValue\": \"%s\"", getPartitionValue()))
+ .append(String.format(", \"prefixLength\": \"%s\"", getPrefixLength()))
+ .append(String.format(", \"companyPrefix\": \"%s\"", getCompanyPrefix()))
+ .append(String.format(", \"serviceReference\": \"%s\"", getServiceReference()))
+ .append(String.format(", \"checkDigit\": \"%s\"", getCheckDigit()))
+ .append(String.format(", \"epcPureIdentityURI\": \"%s\"", getEpcPureIdentityURI()))
+ .append(String.format(", \"epcTagURI\": \"%s\"", getEpcTagURI()))
+ .append(String.format(", \"epcRawURI\": \"%s\"", getEpcRawURI()))
+ .append(String.format(", \"binary\": \"%s\"", getBinary()))
+ .append(String.format(", \"rfidTag\": \"%s\"", getRfidTag())).append(" }");
+
+
+/*
+ json.append("{ \"epcScheme\": \"").append(getEpcScheme()).append("\"")
+ .append(", \"applicationIdentifier\": \"").append(getApplicationIdentifier()).append("\"")
+ .append(", \"tagSize\": \"").append(getTagSize()).append("\"")
+ .append(", \"filterValue\": \"").append(getFilterValue()).append("\"")
+ .append(", \"partitionValue\": \"").append(getPartitionValue()).append("\"")
+ .append(", \"prefixLength\": \"").append(getPrefixLength()).append("\"")
+ .append(", \"companyPrefix\": \"").append(getCompanyPrefix()).append("\"")
+ .append(", \"serviceReference\": \"").append(getServiceReference()).append("\"")
+ .append(", \"checkDigit\": \"").append(getCheckDigit()).append("\"")
+ .append(", \"epcPureIdentityURI\": \"").append(getEpcPureIdentityURI()).append("\"")
+ .append(", \"epcTagURI\": \"").append(getEpcTagURI()).append("\"")
+ .append(", \"epcRawURI\": \"").append(getEpcRawURI()).append("\"")
+ .append(", \"binary\": \"").append(getBinary()).append("\"")
+ .append(", \"rfidTag\": \"").append(getRfidTag()).append("\" }");
+ */
+
+
+ return json.toString();
+ }
+
+
+
+
+
+
+}
+
+
+
+package org.epctagcoder.result;
+
+public class GSRNP extends Base {
+ private String serviceReference;
+ private String checkDigit;
+
+ public GSRNP() {
+
+ }
+
+
+ public String getServiceReference() {
+ return serviceReference;
+ }
+
+ public void setServiceReference(String serviceReference) {
+ this.serviceReference = serviceReference;
+ }
+
+ public String getCheckDigit() {
+ return checkDigit;
+ }
+
+ public void setCheckDigit(String checkDigit) {
+ this.checkDigit = checkDigit;
+ }
+
+
+ @Override
+ public String toString() {
+ StringBuilder json = new StringBuilder();
+
+ json.append(String.format("{ \"epcScheme\": \"%s\"", getEpcScheme()))
+ .append(String.format(", \"applicationIdentifier\": \"%s\"", getApplicationIdentifier()))
+ .append(String.format(", \"tagSize\": \"%s\"", getTagSize()))
+ .append(String.format(", \"filterValue\": \"%s\"", getFilterValue()))
+ .append(String.format(", \"partitionValue\": \"%s\"", getPartitionValue()))
+ .append(String.format(", \"prefixLength\": \"%s\"", getPrefixLength()))
+ .append(String.format(", \"companyPrefix\": \"%s\"", getCompanyPrefix()))
+ .append(String.format(", \"serviceReference\": \"%s\"", getServiceReference()))
+ .append(String.format(", \"checkDigit\": \"%s\"", getCheckDigit()))
+ .append(String.format(", \"epcPureIdentityURI\": \"%s\"", getEpcPureIdentityURI()))
+ .append(String.format(", \"epcTagURI\": \"%s\"", getEpcTagURI()))
+ .append(String.format(", \"epcRawURI\": \"%s\"", getEpcRawURI()))
+ .append(String.format(", \"binary\": \"%s\"", getBinary()))
+ .append(String.format(", \"rfidTag\": \"%s\"", getRfidTag())).append(" }");
+
+ return json.toString();
+ }
+
+
+
+
+
+
+}
+
+
+
+package org.epctagcoder.result;
+
+public class SGLN extends Base {
+ private String locationReference;
+ private String extension;
+ private String checkDigit;
+
+
+ public SGLN() {
+
+ }
+
+
+ @Override
+ public String toString() {
+ StringBuilder json = new StringBuilder();
+
+ json.append(String.format("{ \"epcScheme\": \"%s\"", getEpcScheme()))
+ .append(String.format(", \"applicationIdentifier\": \"%s\"", getApplicationIdentifier()))
+ .append(String.format(", \"tagSize\": \"%s\"", getTagSize()))
+ .append(String.format(", \"filterValue\": \"%s\"", getFilterValue()))
+ .append(String.format(", \"partitionValue\": \"%s\"", getPartitionValue()))
+ .append(String.format(", \"prefixLength\": \"%s\"", getPrefixLength()))
+ .append(String.format(", \"companyPrefix\": \"%s\"", getCompanyPrefix()))
+ .append(String.format(", \"locationReference\": \"%s\"", getLocationReference()))
+ .append(String.format(", \"extension\": \"%s\"", getExtension()))
+ .append(String.format(", \"checkDigit\": \"%s\"", getCheckDigit()))
+ .append(String.format(", \"epcPureIdentityURI\": \"%s\"", getEpcPureIdentityURI()))
+ .append(String.format(", \"epcTagURI\": \"%s\"", getEpcTagURI()))
+ .append(String.format(", \"epcRawURI\": \"%s\"", getEpcRawURI()))
+ .append(String.format(", \"binary\": \"%s\"", getBinary()))
+ .append(String.format(", \"rfidTag\": \"%s\"", getRfidTag())).append(" }");
+
+ return json.toString();
+ }
+
+
+ public String getLocationReference() {
+ return locationReference;
+ }
+
+
+ public void setLocationReference(String locationReference) {
+ this.locationReference = locationReference;
+ }
+
+
+ public String getExtension() {
+ return extension;
+ }
+
+
+ public void setExtension(String extension) {
+ this.extension = extension;
+ }
+
+
+ public String getCheckDigit() {
+ return checkDigit;
+ }
+
+
+ public void setCheckDigit(String checkDigit) {
+ this.checkDigit = checkDigit;
+ }
+
+
+}
+
+
+
+package org.epctagcoder.result;
+
+public class SGTIN extends Base {
+ private String extensionDigit;
+ private String itemReference;
+ private String serial;
+ private String checkDigit;
+
+ public SGTIN() {
+
+ }
+
+ public String getExtensionDigit() {
+ return extensionDigit;
+ }
+
+ public void setExtensionDigit(String extensionDigit) {
+ this.extensionDigit = extensionDigit;
+ }
+
+ public String getItemReference() {
+ return itemReference;
+ }
+
+ public void setItemReference(String itemReference) {
+ this.itemReference = itemReference;
+ }
+
+ public String getSerial() {
+ return serial;
+ }
+
+ public void setSerial(String serial) {
+ this.serial = serial;
+ }
+
+ public String getCheckDigit() {
+ return checkDigit;
+ }
+
+ public void setCheckDigit(String checkDigit) {
+ this.checkDigit = checkDigit;
+ }
+
+
+
+ @Override
+ public String toString() {
+ StringBuilder json = new StringBuilder();
+
+ json.append(String.format("{ \"epcScheme\": \"%s\"", getEpcScheme()))
+ .append(String.format(", \"applicationIdentifier\": \"%s\"", getApplicationIdentifier()))
+ .append(String.format(", \"tagSize\": \"%s\"", getTagSize()))
+ .append(String.format(", \"filterValue\": \"%s\"", getFilterValue()))
+ .append(String.format(", \"partitionValue\": \"%s\"", getPartitionValue()))
+ .append(String.format(", \"prefixLength\": \"%s\"", getPrefixLength()))
+ .append(String.format(", \"companyPrefix\": \"%s\"", getCompanyPrefix()))
+ .append(String.format(", \"extensionDigit\": \"%s\"", getExtensionDigit()))
+ .append(String.format(", \"itemReference\": \"%s\"", getItemReference()))
+ .append(String.format(", \"serial\": \"%s\"", getSerial()))
+ .append(String.format(", \"checkDigit\": \"%s\"", getCheckDigit()))
+ .append(String.format(", \"epcPureIdentityURI\": \"%s\"", getEpcPureIdentityURI()))
+ .append(String.format(", \"epcTagURI\": \"%s\"", getEpcTagURI()))
+ .append(String.format(", \"epcRawURI\": \"%s\"", getEpcRawURI()))
+ .append(String.format(", \"binary\": \"%s\"", getBinary()))
+ .append(String.format(", \"rfidTag\": \"%s\"", getRfidTag())).append(" }");
+
+ return json.toString();
+ }
+
+
+
+
+
+
+
+
+}
+
+
+
+package org.epctagcoder.result;
+
+public class SSCC extends Base {
+ private String extensionDigit;
+ private String serial;
+ private String checkDigit;
+
+ public SSCC() {
+
+ }
+
+ public String getExtensionDigit() {
+ return extensionDigit;
+ }
+
+ public void setExtensionDigit(String extensionDigit) {
+ this.extensionDigit = extensionDigit;
+ }
+
+ public String getSerial() {
+ return serial;
+ }
+
+ public void setSerial(String serial) {
+ this.serial = serial;
+ }
+
+ public String getCheckDigit() {
+ return checkDigit;
+ }
+
+ public void setCheckDigit(String checkDigit) {
+ this.checkDigit = checkDigit;
+ }
+
+
+
+ @Override
+ public String toString() {
+ StringBuilder json = new StringBuilder();
+
+ json.append(String.format("{ \"epcScheme\": \"%s\"", getEpcScheme()))
+ .append(String.format(", \"applicationIdentifier\": \"%s\"", getApplicationIdentifier()))
+ .append(String.format(", \"tagSize\": \"%s\"", getTagSize()))
+ .append(String.format(", \"filterValue\": \"%s\"", getFilterValue()))
+ .append(String.format(", \"partitionValue\": \"%s\"", getPartitionValue()))
+ .append(String.format(", \"prefixLength\": \"%s\"", getPrefixLength()))
+ .append(String.format(", \"companyPrefix\": \"%s\"", getCompanyPrefix()))
+ .append(String.format(", \"extensionDigit\": \"%s\"", getExtensionDigit()))
+ .append(String.format(", \"serial\": \"%s\"", getSerial()))
+ .append(String.format(", \"checkDigit\": \"%s\"", getCheckDigit()))
+ .append(String.format(", \"epcPureIdentityURI\": \"%s\"", getEpcPureIdentityURI()))
+ .append(String.format(", \"epcTagURI\": \"%s\"", getEpcTagURI()))
+ .append(String.format(", \"epcRawURI\": \"%s\"", getEpcRawURI()))
+ .append(String.format(", \"binary\": \"%s\"", getBinary()))
+ .append(String.format(", \"rfidTag\": \"%s\"", getRfidTag())).append(" }");
+
+ return json.toString();
+ }
+
+
+
+}
+
+
+
+package org.epctagcoder.util;
+
+import java.math.BigDecimal;
+import java.math.BigInteger;
+import java.util.*;
+
+public class Converter {
+ static final Map hexToBinMap = new HashMap<>();
+ static final Map binToHexMap = new HashMap<>();
+
+ static {
+ hexToBinMap.put("0", "0000");
+ hexToBinMap.put("1", "0001");
+ hexToBinMap.put("2", "0010");
+ hexToBinMap.put("3", "0011");
+ hexToBinMap.put("4", "0100");
+ hexToBinMap.put("5", "0101");
+ hexToBinMap.put("6", "0110");
+ hexToBinMap.put("7", "0111");
+ hexToBinMap.put("8", "1000");
+ hexToBinMap.put("9", "1001");
+ hexToBinMap.put("A", "1010");
+ hexToBinMap.put("B", "1011");
+ hexToBinMap.put("C", "1100");
+ hexToBinMap.put("D", "1101");
+ hexToBinMap.put("E", "1110");
+ hexToBinMap.put("F", "1111");
+
+ binToHexMap.put("0000", "0");
+ binToHexMap.put("0001", "1");
+ binToHexMap.put("0010", "2");
+ binToHexMap.put("0011", "3");
+ binToHexMap.put("0100", "4");
+ binToHexMap.put("0101", "5");
+ binToHexMap.put("0110", "6");
+ binToHexMap.put("0111", "7");
+ binToHexMap.put("1000", "8");
+ binToHexMap.put("1001", "9");
+ binToHexMap.put("1010", "A");
+ binToHexMap.put("1011", "B");
+ binToHexMap.put("1100", "C");
+ binToHexMap.put("1101", "D");
+ binToHexMap.put("1110", "E");
+ binToHexMap.put("1111", "F");
+ }
+
+ public static String hexToBin(String hex) {
+ StringBuilder bin = new StringBuilder();
+
+ for (String x: hex.toUpperCase().split("")) {
+ bin.append(Optional.of(x)
+ .map(hexToBinMap::get)
+ .orElseThrow(() -> new IllegalArgumentException(x + " is not a valid hex digit")));
+ }
+
+ return bin.toString();
+ }
+
+ public static String binToHex(String bin) {
+ if (bin.length() % 4 != 0) {
+ throw new IllegalArgumentException("Binary string '" + bin + "' does not represent a valid Hex number");
+ }
+
+ int startIndex = 0;
+ StringBuilder hex = new StringBuilder();
+
+ while (startIndex < bin.length()) {
+ hex.append(binToHexMap.get(bin.substring(startIndex, startIndex + 4)));
+ startIndex += 4;
+ }
+
+ return hex.toString();
+ }
+
+ public static String binToString(String s) {
+ StringBuilder bin = new StringBuilder();
+
+ for (int i = 0; i <= s.length() - 8; i += 8) {
+ int k = Integer.parseInt(s.substring(i, i + 8), 2);
+ bin.append((char) k);
+ }
+
+ return bin.toString().trim();
+ }
+
+ // funciona, substituir?
+ public static String decToBin(String dec, int bits) {
+ return strZero(new BigInteger(dec).toString(2), bits);
+ }
+
+ public static String decToBin(Integer dec, int bits) {
+ return strZero(BigInteger.valueOf(dec.longValue()).toString(2), bits);
+ }
+
+ // funciona, substituir?
+ public static String binToDec(String bin) {
+ return new BigInteger(bin, 2).toString();
+ }
+
+ // montei esse, d� d� descartar
+ public static String binToDec2(String bin) {
+ int len = bin.length();
+ int rev = len - 1;
+ BigDecimal d = new BigDecimal("0");
+
+ StringBuilder dec = new StringBuilder();
+ for (int i = 0; i < len; i++) {
+ String pos = bin.substring(i, i + 1);
+ d = d.add(new BigDecimal(pos).multiply(new BigDecimal("2").pow(rev)));
+ rev--;
+ }
+ dec.append(d);
+ return dec.toString();
+ }
+
+ // http://stackoverflow.com/questions/4211705/binary-to-text-in-java?noredirect=1&lq=1
+ public static String convertBinToBit(String s, int fromBit, int toBit) {
+ StringBuilder bin = new StringBuilder();
+ // https://stackoverflow.com/a/3760193/1696733
+ for (int start = 0; start < s.length(); start += fromBit) {
+ String a = s.substring(start, Math.min(s.length(), start + fromBit));
+ bin.append(lPadZero(Integer.parseInt(a), toBit));
+ }
+
+ return bin.toString();
+ }
+
+ public static String fill(String text, int size) {
+ StringBuilder builder = new StringBuilder(text);
+ while (builder.length() < size) {
+ builder.append('0');
+ }
+ return builder.toString();
+ }
+
+ //http://stackoverflow.com/questions/917163/convert-a-string-like-testing123-to-binary-in-java
+ public static String StringToBinary(String str, int bits) {
+ StringBuilder result = new StringBuilder();
+ String tmpStr;
+ int tmpInt;
+ char[] messChar = str.toCharArray();
+
+ for (char c: messChar) {
+ tmpStr = Integer.toBinaryString(c);
+ tmpInt = tmpStr.length();
+ if (tmpInt != bits) {
+ tmpInt = bits - tmpInt;
+ if (tmpInt == bits) {
+ result.append(tmpStr);
+ } else if (tmpInt > 0) {
+ for (int j = 0; j < tmpInt; j++) {
+ result.append("0");
+ }
+ result.append(tmpStr);
+ } else {
+ System.err.println("argument 'bits' is too small");
+ }
+ } else {
+ result.append(tmpStr);
+ }
+ }
+
+ return result.toString();
+ }
+
+ public static String lPadZero(int in, int fill) {
+
+ boolean negative = false;
+ int value, len = 0;
+
+ if (in >= 0) {
+ value = in;
+ } else {
+ negative = true;
+ value = -in;
+ in = -in;
+ len++;
+ }
+
+ if (value == 0) {
+ len = 1;
+ } else {
+ for (; value != 0; len++) {
+ value /= 10;
+ }
+ }
+
+ StringBuilder sb = new StringBuilder();
+
+ if (negative) {
+ sb.append('-');
+ }
+
+ for (int i = fill; i > len; i--) {
+ sb.append('0');
+ }
+
+ sb.append(in);
+
+ return sb.toString();
+ }
+
+ public static String strZero(String str, int len) {
+
+ StringBuilder sb = new StringBuilder();
+
+ for (int toPrepend = len - str.length(); toPrepend > 0; toPrepend--) {
+ sb.append('0');
+ }
+
+ sb.append(str);
+ return sb.toString();
+ }
+
+ public static boolean isNumeric(String str) {
+ return str.chars().allMatch(Character::isDigit);
+ }
+
+ public static List splitEqually(String text, int size) {
+ List ret = new ArrayList<>((text.length() + size - 1) / size);
+
+ for (int start = 0; start < text.length(); start += size) {
+ ret.add(text.substring(start, Math.min(text.length(), start + size)));
+ }
+ return ret;
+ }
+}
+
+
+
+#Wed Jul 19 10:01:18 HKT 2023
+distributionBase=GRADLE_USER_HOME
+distributionPath=wrapper/dists
+distributionUrl=https\://services.gradle.org/distributions/gradle-8.11.1-bin.zip
+zipStoreBase=GRADLE_USER_HOME
+zipStorePath=wrapper/dists
+
+
+
+# CS710S-JAVA-APP-for-ANDROID
+
+CS710S Android Java Bluetooth Demo App and SDK
+
+This application provides demonstrations to the programming interface made available for configuring, controlling, and accessing the CS710S RFID reader. The development was based on the CS710S Java API.
+
+[Product Information](https://www.convergence.com.hk/cs710s/)
+
+
+## Pre-requisite
+
+The development environment consists of the following:
+- Android Studio Giraffe
+- Android SDK API Level 36 (compileSdk 36, minSdk 26, targetSdk 36)
+- Microsoft Windows 10/11 or Mac OSX or Linux
+
+---
+
+# AI Tools & Workflow in Development
+
+This project applied AI tools to assist in code analysis, refactoring, and pruning, ensuring a structured and safe process for maintaining the repository. The workflow emphasizes repeatability and clarity for both new and experienced developers.
+
+## AI Tools
+ - **Grok (by xAI)**, **Claude (Anthropic)**, or **ChatGPT (OpenAI)**
+
+## AI Objectives
+ - Handling large contexts (e.g., ~9M+ character repomixed codebase).
+ - Deep repository “prospecting” (dependency mapping, structure analysis from `CS710S-Java-ENTIRE-CONTEXT.txt` or `CS710S-Java-ENTIRE-CONTEXT.xml`).
+
+## General Workflow
+1. **Preparation**
+ - Backup repo (`git branch prune-`).
+ - Load in Android Studio (Windows/Mac/Linux).
+
+2. **AI-Assisted Prospecting**
+ - Upload `CS710S-Java-ENTIRE-CONTEXT.txt` or `CS710S-Java-ENTIRE-CONTEXT.xml` to your preferred LLM.
+ - Query LLM with specific context (see prompts from `prompts.md`).
+
+3. **Iterative Pruning**
+ - Target one feature at a time (e.g., “Register Tag”).
+ - Trace dependencies:
+ - Primary, Secondary, Tertiary, etc: ensure all nested references are cleanly acknowledged
+ - Holistically remove imports, update refs
+
+4. **Verification**
+ - Rebuild
+ - Confirm build remains clean
+ - Test preserved features, ensure application runs as expected.
+ - Run on emulator/device, check logs.
+ - Publish incremental commits ensuring backtracking is possible.
+
+5. **Documentation**
+ - Update README and related supporting files.
+ - Review and borrow prompts/templates from (`prompts.md`).
+
+---
+
+## Notes on Android Studio Workflow (With Emulator)
+1. **Clean the Project**: In Android Studio, go to `Build` > `Clean Project` to remove all compiled files and ensure a fresh build.
+2. **Sync and Rebuild**: Select `File` > `Sync Project with Gradle Files`, then `Build` > `Rebuild Project` to compile.
+3. **Deploy to Emulator**: Configure emulator (e.g., x86_64), select `Run` > `Run 'app'` to deploy and run.
+
+---
+
+## Notes on Repomix
+The `CS710S-Java-ENTIRE-CONTEXT.*` files are comprehensive, packed representations of the entire codebase, generated by Repomix—a tool that consolidates source code, projects, and docs into a single, AI-consumable format (e.g., .txt or .xml). The `repomix-config.json` file configures Repomix to include/exclude files, define output structure, and ensure full content without truncation, tailoring the pack to our needs. This setup makes our codebase "AI Ready" by enabling deep analysis of BLE/RFID flows, dependency mapping, and optimization suggestions via AI tools like Grok, Claude, ChatGPT, etc, streamlining development and maintenance for the CS710S app.
+
+- Select either `CS710S-Java-ENTIRE-CONTEXT.txt` or `CS710S-Java-ENTIRE-CONTEXT.xml` based on LLM upload policies. Both contain identical content; the only difference is the file extension, which supports different formats.
+
+- [Learn more about Repomix](https://github.com/yamadashy/repomix)
+
+
+
+# Repomix Instructions — CS710S Android (Java)
+
+**Goal**
+Produce a single packed context for AI agents to analyze BLE and RFID flows in the CS710S handheld reader app on Android (Java + Gradle), excluding build artifacts, binaries, and noise. Ensure the full output is generated without truncation.
+
+---
+
+## What to Include (Priority Order)
+1) Build & Modules
+- `build.gradle`
+- `settings.gradle`
+- `app/build.gradle`
+- `cslibrary4a/build.gradle`
+- `epctagcoder/build.gradle`
+
+2) Core Library (RFID + HAL + Tools)
+- `cslibrary4a/src/main/java/com/csl/cslibrary4a/*.java`
+ - RFID Unified API: `Cs108Library4A.java`, `Cs710Library4A.java`, `CsLibrary4A.java` (Host commands, inventory/access ops; CS710S focus)
+ - Comm Protocol: `RfidReaderChipData.java`, `RfidReaderChipR2000.java`, `RfidReaderChipE710.java`
+ - HAL BLE: `BluetoothConnector.java`, `BluetoothGatt.java`, `RfidConnector.java`
+ - Utilities: `Utility.java`, `AesCmac.java`, `DeviceFinder.java`
+
+3) Android App (UI + Tasks)
+- `app/src/main/java/com/csl/cs710ademoapp/*.java` (Main logic, fragments, tasks)
+- `app/src/main/java/com/csl/cs710ademoapp/fragments/*.java` (e.g., InventoryFragment.java, AccessReadWriteFragment.java)
+- `app/src/main/java/com/csl/cs710ademoapp/adapters/*.java`
+- `app/src/main/AndroidManifest.xml`
+- `app/src/main/res/values/*.xml`
+- `app/src/main/res/layout/*.xml`
+
+4) EPC Tag Coder
+- `epctagcoder/src/main/java/org/epctagcoder/*.java` (Parse/encode EPC schemes: SGTIN, SSCC, etc.)
+- `epctagcoder/src/main/java/org/epctagcoder/option/*.java`
+- `epctagcoder/src/main/java/org/epctagcoder/parse/*.java`
+- `epctagcoder/src/main/java/org/epctagcoder/result/*.java`
+
+5) Docs / Metadata
+- `README.md`
+- `repomix-instructions.md`
+- `repomix-config.json` (For Repomix self-reference)
+
+---
+
+## Exclude (Noise & Generated)
+- Build & IDE: `**/build/**`, `**/.gradle/**`, `.idea/**`, `.vscode/**`
+- Packages & Dependencies: `**/*.jar`, `**/*.aar`
+- Generated: `**/R.java`, `**/*.class`
+- Binaries/Archives: `**/*.dll`, `**/*.so`, `**/*.a`, `**/*.nupkg`, `**/*.keystore`, `**/*.apk`, `**/*.aab`, `**/*.zip`
+- Images/Misc: `**/*.png`, `**/*.jpg`, `**/*.gif`, `**/*.pdf`
+- Local Config: `**/*.iml`, `local.properties`, `**/*.user`
+
+---
+
+## Logical Read Order (for AI Prospecting)
+Guide AI agents in "prospecting" interconnected paths:
+1) `settings.gradle` → Module dependencies.
+2) App Entry: `app/src/main/java/com/csl/cs710ademoapp/MainActivity.java` (App bootstrap, NFC/USB intents).
+3) Fragments/UI: `app/src/main/java/com/csl/cs710ademoapp/fragments/*.java` (e.g., InventoryFragment.java, ConnectionFragment.java for BLE scanning).
+4) BLE HAL: `cslibrary4a/src/main/java/com/csl/cslibrary4a/BluetoothConnector.java`, `RfidConnector.java` (Device discovery, GATT via Android BLE).
+5) RFID Unified API (CS710S Focus): `cslibrary4a/src/main/java/com/csl/cslibrary4a/Cs710Library4A.java`, `RfidReaderChipE710.java` (Public ops: inventory/read/write/antenna/power—trace to chip-specific layers).
+6) Comm Protocol: `cslibrary4a/src/main/java/com/csl/cslibrary4a/Rx000Commands` (via RfidReaderChipData.HostCommands).
+7) Tasks/Utilities: `app/src/main/java/com/csl/cs710ademoapp/AccessTask.java`, `InventoryRfidTask.java`; `epctagcoder/src/main/java/org/epctagcoder/parse/*.java`.
+
+This order reflects app flow: Android bootstrap → Fragment navigation → BLE connect/scan → RFID operations. Emphasize tracing dependencies (e.g., how MainActivity invokes library ops in AsyncTasks).
+
+---
+
+## Summarization Hints (Chunking for AI)
+- Group by Feature: **BLE Connect** (BluetoothConnector + fragments), **Inventory** (InventoryRfidTask.java, RfidReader), **Read/Write** (AccessTask.java, HostCommands), **Antenna/Power** (SettingData.java, powerLevel params), **Tag Filters/QT** (setSelectCriteria), **Errors/Status** (decodedError in Rx000pkgData).
+- Limit chunks to ≤2k tokens; prefix each with file paths.
+- Cross-link public APIs to private implementations (e.g., CsLibrary4A.publicAccess → RfidReaderChipE710).
+- Note response modes (compact/normal/extended) in tag operations via HostCmdResponseTypes.
+- Flag Token-Heavy Files (>1k tokens): `AccessTask.java`, `MainActivity.java`, `CsLibrary4A.java`—suggest splitting in AI analysis.
+
+---
+
+## Important Callouts
+- Android: `MainActivity.java`, `AndroidManifest.xml`, `res/values/strings.xml`.
+- Fragments/Tasks: `InventoryFragment.java`, `AccessReadWriteFragment.java`, `AccessTask.java`.
+- CS710S API: Public (`Cs710Library4A.java`, `RfidReader`), Operations (`RfidReaderChipE710.java` for read/write/inventory/select), Antenna/Power (`SettingData.java`), Protocol (`RfidReaderChipData.HostCommands`).
+- EPC: `epctagcoder/parse/SGTIN/ParseSGTIN.java`, `result/SGTIN.java`.
+- Utilities: `Utility.java`, `Converter.java` (hex/bin conversions).
+
+---
+
+## Output Requirements
+- Single packed file: **Summary → Repo Info → Structure → Files (path + contents)**.
+- Preserve code blocks verbatim; include file headers.
+- Mark **excluded** areas clearly.
+- Note token-heavy files with byte/token counts.
+- Use relative paths from repo root.
+- Style: XML, with file summaries and directory structure.
+- Ensure full output without truncation (support up to 100MB).
+
+---
+
+## Build Context
+- Targets: Android (minSdk 26, targetSdk 36; armeabi-v7a, arm64-v8a, x86_64 for emulators).
+- Key Dependencies: `com.google.android.material:material:1.12.0`, `org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.2.5`.
+- Build: Open in Android Studio → Sync Gradle → Select `app` → Debug/Release → Deploy to device/emulator.
+
+---
+
+## Quality Checks (for AI Post-Packing)
+- Flag BLE timing issues, UI thread handling, and disconnect edges (e.g., in BluetoothGatt, AsyncTask cancellations).
+- Confirm frequency/power settings are configurable (e.g., setAccessPowerLevel).
+- Verify no UI-blocking I/O; check AsyncTask progress in inventory/reads (e.g., AccessTask.doInBackground).
+
+
+
+{
+ "input": {
+ "maxFileSize": 100000000
+ },
+ "output": {
+ "filePath": "CS710S-Java-ENTIRE-CONTEXT.txt",
+ "style": "xml",
+ "parsableStyle": true,
+ "compress": true,
+ "headerText": "Packed CS710S Android codebase for AI analysis of BLE/RFID flows, including Java source, projects, and docs.",
+ "instructionFilePath": "repomix-instruction.md",
+ "fileSummary": true,
+ "directoryStructure": true,
+ "files": true,
+ "removeComments": false,
+ "removeEmptyLines": false,
+ "showLineNumbers": false,
+ "truncateBase64": false,
+ "copyToClipboard": false,
+ "includeEmptyDirectories": false,
+ "topFilesLength": 5,
+ "tokenCountTree": 1000
+ },
+ "include": [
+ "app/src/**",
+ "cslibrary4a/src/main/**",
+ "epctagcoder/src/main/**",
+ "gradle/**",
+ "README.md",
+ "repomix-instruction.md",
+ "repomix.config.json"
+ ],
+ "ignore": {
+ "useGitignore": true,
+ "useDefaultPatterns": true,
+ "customPatterns": [
+ "**/bin/**",
+ "**/obj/**",
+ "**/Debug/**",
+ "**/Release/**",
+ "**/.vs/**",
+ "**/TestResult*/**",
+ "**/node_modules/**",
+ "**/*.dll",
+ "**/*.so",
+ "**/*.a",
+ "**/*.jar",
+ "**/*.aar",
+ "**/*.nupkg",
+ "**/*.keystore",
+ "**/*.apk",
+ "**/*.aab",
+ "**/*.zip",
+ "**/*.png",
+ "**/*.jpg",
+ "**/*.gif",
+ "**/*.pdf",
+ "**/*.user",
+ "**/*.userprefs"
+ ]
+ },
+ "security": {
+ "enableSecurityCheck": false
+ },
+ "tokenCount": {
+ "encoding": "o200k_base"
+ },
+ "git": {
+ "includeLogs": false,
+ "sortByChanges": false,
+ "sortByChangesMaxCommits": 0,
+ "includeDiffs": false,
+ "includeLogsCount": 0
+ },
+ "metadata": {
+ "version": "1.0",
+ "lastUpdated": "2025-08-29",
+ "description": "Configuration for packing CS710S Android codebase for AI analysis."
+ }
+}
+
+
+
+
+
+# Repomix Instructions — CS710S Android (Java)
+
+**Goal**
+Produce a single packed context for AI agents to analyze BLE and RFID flows in the CS710S handheld reader app on Android (Java + Gradle), excluding build artifacts, binaries, and noise. Ensure the full output is generated without truncation.
+
+---
+
+## What to Include (Priority Order)
+1) Build & Modules
+- `build.gradle`
+- `settings.gradle`
+- `app/build.gradle`
+- `cslibrary4a/build.gradle`
+- `epctagcoder/build.gradle`
+
+2) Core Library (RFID + HAL + Tools)
+- `cslibrary4a/src/main/java/com/csl/cslibrary4a/*.java`
+ - RFID Unified API: `Cs108Library4A.java`, `Cs710Library4A.java`, `CsLibrary4A.java` (Host commands, inventory/access ops; CS710S focus)
+ - Comm Protocol: `RfidReaderChipData.java`, `RfidReaderChipR2000.java`, `RfidReaderChipE710.java`
+ - HAL BLE: `BluetoothConnector.java`, `BluetoothGatt.java`, `RfidConnector.java`
+ - Utilities: `Utility.java`, `AesCmac.java`, `DeviceFinder.java`
+
+3) Android App (UI + Tasks)
+- `app/src/main/java/com/csl/cs710ademoapp/*.java` (Main logic, fragments, tasks)
+- `app/src/main/java/com/csl/cs710ademoapp/fragments/*.java` (e.g., InventoryFragment.java, AccessReadWriteFragment.java)
+- `app/src/main/java/com/csl/cs710ademoapp/adapters/*.java`
+- `app/src/main/AndroidManifest.xml`
+- `app/src/main/res/values/*.xml`
+- `app/src/main/res/layout/*.xml`
+
+4) EPC Tag Coder
+- `epctagcoder/src/main/java/org/epctagcoder/*.java` (Parse/encode EPC schemes: SGTIN, SSCC, etc.)
+- `epctagcoder/src/main/java/org/epctagcoder/option/*.java`
+- `epctagcoder/src/main/java/org/epctagcoder/parse/*.java`
+- `epctagcoder/src/main/java/org/epctagcoder/result/*.java`
+
+5) Docs / Metadata
+- `README.md`
+- `repomix-instructions.md`
+- `repomix-config.json` (For Repomix self-reference)
+
+---
+
+## Exclude (Noise & Generated)
+- Build & IDE: `**/build/**`, `**/.gradle/**`, `.idea/**`, `.vscode/**`
+- Packages & Dependencies: `**/*.jar`, `**/*.aar`
+- Generated: `**/R.java`, `**/*.class`
+- Binaries/Archives: `**/*.dll`, `**/*.so`, `**/*.a`, `**/*.nupkg`, `**/*.keystore`, `**/*.apk`, `**/*.aab`, `**/*.zip`
+- Images/Misc: `**/*.png`, `**/*.jpg`, `**/*.gif`, `**/*.pdf`
+- Local Config: `**/*.iml`, `local.properties`, `**/*.user`
+
+---
+
+## Logical Read Order (for AI Prospecting)
+Guide AI agents in "prospecting" interconnected paths:
+1) `settings.gradle` → Module dependencies.
+2) App Entry: `app/src/main/java/com/csl/cs710ademoapp/MainActivity.java` (App bootstrap, NFC/USB intents).
+3) Fragments/UI: `app/src/main/java/com/csl/cs710ademoapp/fragments/*.java` (e.g., InventoryFragment.java, ConnectionFragment.java for BLE scanning).
+4) BLE HAL: `cslibrary4a/src/main/java/com/csl/cslibrary4a/BluetoothConnector.java`, `RfidConnector.java` (Device discovery, GATT via Android BLE).
+5) RFID Unified API (CS710S Focus): `cslibrary4a/src/main/java/com/csl/cslibrary4a/Cs710Library4A.java`, `RfidReaderChipE710.java` (Public ops: inventory/read/write/antenna/power—trace to chip-specific layers).
+6) Comm Protocol: `cslibrary4a/src/main/java/com/csl/cslibrary4a/Rx000Commands` (via RfidReaderChipData.HostCommands).
+7) Tasks/Utilities: `app/src/main/java/com/csl/cs710ademoapp/AccessTask.java`, `InventoryRfidTask.java`; `epctagcoder/src/main/java/org/epctagcoder/parse/*.java`.
+
+This order reflects app flow: Android bootstrap → Fragment navigation → BLE connect/scan → RFID operations. Emphasize tracing dependencies (e.g., how MainActivity invokes library ops in AsyncTasks).
+
+---
+
+## Summarization Hints (Chunking for AI)
+- Group by Feature: **BLE Connect** (BluetoothConnector + fragments), **Inventory** (InventoryRfidTask.java, RfidReader), **Read/Write** (AccessTask.java, HostCommands), **Antenna/Power** (SettingData.java, powerLevel params), **Tag Filters/QT** (setSelectCriteria), **Errors/Status** (decodedError in Rx000pkgData).
+- Limit chunks to ≤2k tokens; prefix each with file paths.
+- Cross-link public APIs to private implementations (e.g., CsLibrary4A.publicAccess → RfidReaderChipE710).
+- Note response modes (compact/normal/extended) in tag operations via HostCmdResponseTypes.
+- Flag Token-Heavy Files (>1k tokens): `AccessTask.java`, `MainActivity.java`, `CsLibrary4A.java`—suggest splitting in AI analysis.
+
+---
+
+## Important Callouts
+- Android: `MainActivity.java`, `AndroidManifest.xml`, `res/values/strings.xml`.
+- Fragments/Tasks: `InventoryFragment.java`, `AccessReadWriteFragment.java`, `AccessTask.java`.
+- CS710S API: Public (`Cs710Library4A.java`, `RfidReader`), Operations (`RfidReaderChipE710.java` for read/write/inventory/select), Antenna/Power (`SettingData.java`), Protocol (`RfidReaderChipData.HostCommands`).
+- EPC: `epctagcoder/parse/SGTIN/ParseSGTIN.java`, `result/SGTIN.java`.
+- Utilities: `Utility.java`, `Converter.java` (hex/bin conversions).
+
+---
+
+## Output Requirements
+- Single packed file: **Summary → Repo Info → Structure → Files (path + contents)**.
+- Preserve code blocks verbatim; include file headers.
+- Mark **excluded** areas clearly.
+- Note token-heavy files with byte/token counts.
+- Use relative paths from repo root.
+- Style: XML, with file summaries and directory structure.
+- Ensure full output without truncation (support up to 100MB).
+
+---
+
+## Build Context
+- Targets: Android (minSdk 26, targetSdk 36; armeabi-v7a, arm64-v8a, x86_64 for emulators).
+- Key Dependencies: `com.google.android.material:material:1.12.0`, `org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.2.5`.
+- Build: Open in Android Studio → Sync Gradle → Select `app` → Debug/Release → Deploy to device/emulator.
+
+---
+
+## Quality Checks (for AI Post-Packing)
+- Flag BLE timing issues, UI thread handling, and disconnect edges (e.g., in BluetoothGatt, AsyncTask cancellations).
+- Confirm frequency/power settings are configurable (e.g., setAccessPowerLevel).
+- Verify no UI-blocking I/O; check AsyncTask progress in inventory/reads (e.g., AccessTask.doInBackground).
+
diff --git a/CS710S-Java-ENTIRE-CONTEXT.xml b/CS710S-Java-ENTIRE-CONTEXT.xml
new file mode 100644
index 0000000..83bd173
--- /dev/null
+++ b/CS710S-Java-ENTIRE-CONTEXT.xml
@@ -0,0 +1,66263 @@
+This file is a merged representation of the entire codebase, combining all repository files into a single document.
+Generated by Repomix on: 2025-10-04T01:28:46.605Z
+
+
+This section contains a summary of this file.
+
+
+This file contains a packed representation of the entire repository's contents.
+It is designed to be easily consumable by AI systems for analysis, code review,
+or other automated processes.
+
+
+
+The content is organized as follows:
+1. This summary section
+2. Repository information
+3. Repository structure
+4. Repository files, each consisting of:
+ - File path as an attribute
+ - Full contents of the file
+
+
+
+- This file should be treated as read-only. Any changes should be made to the
+ original repository files, not this packed version.
+- When processing this file, use the file path to distinguish
+ between different files in the repository.
+- Be aware that this file may contain sensitive information. Handle it with
+ the same level of security as you would the original repository.
+- Pay special attention to the Repository Description. These contain important context and guidelines specific to this project.
+- Pay special attention to the Repository Instruction. These contain important context and guidelines specific to this project.
+
+
+
+- Some files may have been excluded based on .gitignore rules and Repomix's
+ configuration.
+- Binary files are not included in this packed representation. Please refer to
+ the Repository Structure section for a complete list of file paths, including
+ binary files.
+
+
+
+
+Packed CS710S Android codebase for AI analysis of BLE/RFID flows, including Java source, projects, and docs.
+
+
+For more information about Repomix, visit: https://github.com/yamadashy/repomix
+
+
+
+
+
+app/src/main/AndroidManifest.xml
+app/src/main/java/com/csl/cs710ademoapp/AccessTask.java
+app/src/main/java/com/csl/cs710ademoapp/AccessTask1.java
+app/src/main/java/com/csl/cs710ademoapp/adapters/DrawerListAdapter.java
+app/src/main/java/com/csl/cs710ademoapp/adapters/ReaderListAdapter.java
+app/src/main/java/com/csl/cs710ademoapp/CustomAlertDialog.java
+app/src/main/java/com/csl/cs710ademoapp/CustomIME.java
+app/src/main/java/com/csl/cs710ademoapp/CustomMediaPlayer.java
+app/src/main/java/com/csl/cs710ademoapp/CustomPopupWindow.java
+app/src/main/java/com/csl/cs710ademoapp/CustomProgressDialog.java
+app/src/main/java/com/csl/cs710ademoapp/DrawerListContent.java
+app/src/main/java/com/csl/cs710ademoapp/fragments/AboutFragment.java
+app/src/main/java/com/csl/cs710ademoapp/fragments/AccessAuraSenseFragment.java
+app/src/main/java/com/csl/cs710ademoapp/fragments/AccessColdChainFragment.java
+app/src/main/java/com/csl/cs710ademoapp/fragments/AccessConfigFragment.java
+app/src/main/java/com/csl/cs710ademoapp/fragments/AccessEm4325PassiveFragment.java
+app/src/main/java/com/csl/cs710ademoapp/fragments/AccessFdmicroFragment.java
+app/src/main/java/com/csl/cs710ademoapp/fragments/AccessImpinjFragment.java
+app/src/main/java/com/csl/cs710ademoapp/fragments/AccessKilowayFragment.java
+app/src/main/java/com/csl/cs710ademoapp/fragments/AccessMicronFragment.java
+app/src/main/java/com/csl/cs710ademoapp/fragments/AccessReadWriteFragment.java
+app/src/main/java/com/csl/cs710ademoapp/fragments/AccessReadWriteUserFragment.java
+app/src/main/java/com/csl/cs710ademoapp/fragments/AccessRegisterFragment.java
+app/src/main/java/com/csl/cs710ademoapp/fragments/AccessSecurityFragment.java
+app/src/main/java/com/csl/cs710ademoapp/fragments/AccessSecurityKillFragment.java
+app/src/main/java/com/csl/cs710ademoapp/fragments/AccessSecurityLockFragment.java
+app/src/main/java/com/csl/cs710ademoapp/fragments/AccessUcode8Fragment.java
+app/src/main/java/com/csl/cs710ademoapp/fragments/AccessUcodeFragment.java
+app/src/main/java/com/csl/cs710ademoapp/fragments/AccessXerxesLoggerFragment.java
+app/src/main/java/com/csl/cs710ademoapp/fragments/AuraSenseFragment.java
+app/src/main/java/com/csl/cs710ademoapp/fragments/AxzonFragment.java
+app/src/main/java/com/csl/cs710ademoapp/fragments/AxzonSelectorFragment.java
+app/src/main/java/com/csl/cs710ademoapp/fragments/ColdChainFragment.java
+app/src/main/java/com/csl/cs710ademoapp/fragments/CommonFragment.java
+app/src/main/java/com/csl/cs710ademoapp/fragments/ConnectionFragment.java
+app/src/main/java/com/csl/cs710ademoapp/fragments/DirectWedgeFragment.java
+app/src/main/java/com/csl/cs710ademoapp/fragments/FdmicroFragment.java
+app/src/main/java/com/csl/cs710ademoapp/fragments/ForegroundFragment.java
+app/src/main/java/com/csl/cs710ademoapp/fragments/HomeFragment.java
+app/src/main/java/com/csl/cs710ademoapp/fragments/HomeSpecialFragment.java
+app/src/main/java/com/csl/cs710ademoapp/fragments/HomeWFragment.java
+app/src/main/java/com/csl/cs710ademoapp/fragments/ImpinjFragment.java
+app/src/main/java/com/csl/cs710ademoapp/fragments/ImpinjM775Fragment.java
+app/src/main/java/com/csl/cs710ademoapp/fragments/InventoryBarcodeFragment.java
+app/src/main/java/com/csl/cs710ademoapp/fragments/InventoryFragment.java
+app/src/main/java/com/csl/cs710ademoapp/fragments/InventoryRfidiMultiFragment.java
+app/src/main/java/com/csl/cs710ademoapp/fragments/InventoryRfidSearchFragment.java
+app/src/main/java/com/csl/cs710ademoapp/fragments/InventoryRfidSimpleFragment.java
+app/src/main/java/com/csl/cs710ademoapp/fragments/KilowayFragment.java
+app/src/main/java/com/csl/cs710ademoapp/fragments/LongjingFragment.java
+app/src/main/java/com/csl/cs710ademoapp/fragments/MicronFragment.java
+app/src/main/java/com/csl/cs710ademoapp/fragments/SettingAdminFragment.java
+app/src/main/java/com/csl/cs710ademoapp/fragments/SettingFilterFragment.java
+app/src/main/java/com/csl/cs710ademoapp/fragments/SettingFilterPostFragment.java
+app/src/main/java/com/csl/cs710ademoapp/fragments/SettingFilterPreFragment.java
+app/src/main/java/com/csl/cs710ademoapp/fragments/SettingFilterRssiFragment.java
+app/src/main/java/com/csl/cs710ademoapp/fragments/SettingFragment.java
+app/src/main/java/com/csl/cs710ademoapp/fragments/SettingOperateFragment.java
+app/src/main/java/com/csl/cs710ademoapp/fragments/SettingWedgeFragment.java
+app/src/main/java/com/csl/cs710ademoapp/fragments/Test1Fragment.java
+app/src/main/java/com/csl/cs710ademoapp/fragments/TestFragment.java
+app/src/main/java/com/csl/cs710ademoapp/fragments/Ucode8Fragment.java
+app/src/main/java/com/csl/cs710ademoapp/fragments/UcodeFragment.java
+app/src/main/java/com/csl/cs710ademoapp/fragments/UtraceFragment.java
+app/src/main/java/com/csl/cs710ademoapp/GenericTextWatcher.java
+app/src/main/java/com/csl/cs710ademoapp/InventoryBarcodeTask.java
+app/src/main/java/com/csl/cs710ademoapp/InventoryRfidTask.java
+app/src/main/java/com/csl/cs710ademoapp/MainActivity.java
+app/src/main/java/com/csl/cs710ademoapp/MyForegroundService.java
+app/src/main/java/com/csl/cs710ademoapp/MyMqttClient.java
+app/src/main/java/com/csl/cs710ademoapp/SaveList2ExternalTask.java
+app/src/main/java/com/csl/cs710ademoapp/SelectTag.java
+app/src/main/java/com/csl/cs710ademoapp/SensorConnector.java
+app/src/main/java/com/csl/cs710ademoapp/SettingTask.java
+app/src/main/java/com/csl/cs710ademoapp/SharedObjects.java
+app/src/main/res/drawable/border.xml
+app/src/main/res/drawable/ic_launcher_background.xml
+app/src/main/res/drawable/my_edittext_background.xml
+app/src/main/res/layout/actionbar_indeterminate_progress.xml
+app/src/main/res/layout/activity_main.xml
+app/src/main/res/layout/activity_main1.xml
+app/src/main/res/layout/custom_edittext_password.xml
+app/src/main/res/layout/custom_edittext.xml
+app/src/main/res/layout/custom_notification.xml
+app/src/main/res/layout/custom_readwrite.xml
+app/src/main/res/layout/custom_select.xml
+app/src/main/res/layout/custom_select1.xml
+app/src/main/res/layout/custom_select2.xml
+app/src/main/res/layout/custom_spinner_layout.xml
+app/src/main/res/layout/custom_tabbed_layout.xml
+app/src/main/res/layout/drawer_list_item.xml
+app/src/main/res/layout/fragment_about.xml
+app/src/main/res/layout/fragment_access_aurasense.xml
+app/src/main/res/layout/fragment_access_coldchain.xml
+app/src/main/res/layout/fragment_access_config.xml
+app/src/main/res/layout/fragment_access_em4325passive.xml
+app/src/main/res/layout/fragment_access_fdmicro.xml
+app/src/main/res/layout/fragment_access_impinj.xml
+app/src/main/res/layout/fragment_access_kill.xml
+app/src/main/res/layout/fragment_access_kiloway.xml
+app/src/main/res/layout/fragment_access_lock.xml
+app/src/main/res/layout/fragment_access_micron.xml
+app/src/main/res/layout/fragment_access_readwrite.xml
+app/src/main/res/layout/fragment_access_register.xml
+app/src/main/res/layout/fragment_access_ucode.xml
+app/src/main/res/layout/fragment_access_ucode8.xml
+app/src/main/res/layout/fragment_access_xerxes.xml
+app/src/main/res/layout/fragment_connection.xml
+app/src/main/res/layout/fragment_directwedge_settings.xml
+app/src/main/res/layout/fragment_directwedge.xml
+app/src/main/res/layout/fragment_filterpost_content.xml
+app/src/main/res/layout/fragment_filterpre_content.xml
+app/src/main/res/layout/fragment_filterrssi_content.xml
+app/src/main/res/layout/fragment_geiger_search.xml
+app/src/main/res/layout/fragment_inventory_barcode.xml
+app/src/main/res/layout/fragment_inventory_rfid_multi.xml
+app/src/main/res/layout/fragment_inventory_rfid_simple.xml
+app/src/main/res/layout/fragment_select_axzon.xml
+app/src/main/res/layout/fragment_settings_admin.xml
+app/src/main/res/layout/fragment_settings_operate.xml
+app/src/main/res/layout/fragment_specials.xml
+app/src/main/res/layout/fragment_test.xml
+app/src/main/res/layout/fragment_test1.xml
+app/src/main/res/layout/fragment_utrace.xml
+app/src/main/res/layout/home_layout108.xml
+app/src/main/res/layout/home_layout710.xml
+app/src/main/res/layout/home_special_layout.xml
+app/src/main/res/layout/keyboard_preview.xml
+app/src/main/res/layout/keyboard_view.xml
+app/src/main/res/layout/list_item.xml
+app/src/main/res/layout/popup.xml
+app/src/main/res/layout/readers_list_item.xml
+app/src/main/res/layout/title_divider.xml
+app/src/main/res/menu/menu_connection.xml
+app/src/main/res/menu/menu_home.xml
+app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml
+app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml
+app/src/main/res/values/colors.xml
+app/src/main/res/values/dimens.xml
+app/src/main/res/values/strings.xml
+app/src/main/res/values/styles.xml
+app/src/main/res/xml/device_filter.xml
+app/src/main/res/xml/method.xml
+app/src/main/res/xml/nfc_tech_filter.xml
+app/src/main/res/xml/number_pad.xml
+app/src/main/res/xml/number_pad1.xml
+cslibrary4a/src/main/AndroidManifest.xml
+cslibrary4a/src/main/java/com/csl/cslibrary4a/AdapterTab.java
+cslibrary4a/src/main/java/com/csl/cslibrary4a/AesCmac.java
+cslibrary4a/src/main/java/com/csl/cslibrary4a/BarcodeConnector.java
+cslibrary4a/src/main/java/com/csl/cslibrary4a/BarcodeNewland.java
+cslibrary4a/src/main/java/com/csl/cslibrary4a/BluetoothConnector.java
+cslibrary4a/src/main/java/com/csl/cslibrary4a/BluetoothGatt.java
+cslibrary4a/src/main/java/com/csl/cslibrary4a/ConnectorData.java
+cslibrary4a/src/main/java/com/csl/cslibrary4a/ControllerConnector.java
+cslibrary4a/src/main/java/com/csl/cslibrary4a/Cs108Library4A.java
+cslibrary4a/src/main/java/com/csl/cslibrary4a/Cs710Library4A.java
+cslibrary4a/src/main/java/com/csl/cslibrary4a/CsLibrary4A.java
+cslibrary4a/src/main/java/com/csl/cslibrary4a/CsReaderConnector.java
+cslibrary4a/src/main/java/com/csl/cslibrary4a/DeviceFinder.java
+cslibrary4a/src/main/java/com/csl/cslibrary4a/NotificationConnector.java
+cslibrary4a/src/main/java/com/csl/cslibrary4a/ReaderDevice.java
+cslibrary4a/src/main/java/com/csl/cslibrary4a/RfidConnector.java
+cslibrary4a/src/main/java/com/csl/cslibrary4a/RfidReader.java
+cslibrary4a/src/main/java/com/csl/cslibrary4a/RfidReaderChipData.java
+cslibrary4a/src/main/java/com/csl/cslibrary4a/RfidReaderChipE710.java
+cslibrary4a/src/main/java/com/csl/cslibrary4a/RfidReaderChipR2000.java
+cslibrary4a/src/main/java/com/csl/cslibrary4a/SettingData.java
+cslibrary4a/src/main/java/com/csl/cslibrary4a/UsbConnector.java
+cslibrary4a/src/main/java/com/csl/cslibrary4a/Utility.java
+cslibrary4a/src/main/res/drawable/ic_launcher_background.xml
+cslibrary4a/src/main/res/drawable/ic_launcher_foreground.xml
+cslibrary4a/src/main/res/layout/popup.xml
+cslibrary4a/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml
+cslibrary4a/src/main/res/mipmap-anydpi-v26/ic_launcher.xml
+cslibrary4a/src/main/res/values-night/themes.xml
+cslibrary4a/src/main/res/values/colors.xml
+cslibrary4a/src/main/res/values/strings.xml
+cslibrary4a/src/main/res/values/themes.xml
+epctagcoder/src/main/AndroidManifest.xml
+epctagcoder/src/main/java/org/epctagcoder/exception/EPCParseException.java
+epctagcoder/src/main/java/org/epctagcoder/option/CPI/CPIFilterValue.java
+epctagcoder/src/main/java/org/epctagcoder/option/CPI/CPIHeader.java
+epctagcoder/src/main/java/org/epctagcoder/option/CPI/CPITagSize.java
+epctagcoder/src/main/java/org/epctagcoder/option/CPI/partitionTable/CPIPartitionTableList.java
+epctagcoder/src/main/java/org/epctagcoder/option/GDTI/GDTIFilterValue.java
+epctagcoder/src/main/java/org/epctagcoder/option/GDTI/GDTIHeader.java
+epctagcoder/src/main/java/org/epctagcoder/option/GDTI/GDTITagSize.java
+epctagcoder/src/main/java/org/epctagcoder/option/GDTI/partitionTable/GDTIPartitionTableList.java
+epctagcoder/src/main/java/org/epctagcoder/option/GIAI/GIAIFilterValue.java
+epctagcoder/src/main/java/org/epctagcoder/option/GIAI/GIAIHeader.java
+epctagcoder/src/main/java/org/epctagcoder/option/GIAI/GIAITagSize.java
+epctagcoder/src/main/java/org/epctagcoder/option/GIAI/partitionTable/GIAIPartitionTableList.java
+epctagcoder/src/main/java/org/epctagcoder/option/GRAI/GRAIFilterValue.java
+epctagcoder/src/main/java/org/epctagcoder/option/GRAI/GRAIHeader.java
+epctagcoder/src/main/java/org/epctagcoder/option/GRAI/GRAITagSize.java
+epctagcoder/src/main/java/org/epctagcoder/option/GRAI/partitionTable/GRAIPartitionTableList.java
+epctagcoder/src/main/java/org/epctagcoder/option/GSRN/GSRNFilterValue.java
+epctagcoder/src/main/java/org/epctagcoder/option/GSRN/GSRNHeader.java
+epctagcoder/src/main/java/org/epctagcoder/option/GSRN/GSRNTagSize.java
+epctagcoder/src/main/java/org/epctagcoder/option/GSRN/partitionTable/GSRNPartitionTableList.java
+epctagcoder/src/main/java/org/epctagcoder/option/GSRNP/GSRNPFilterValue.java
+epctagcoder/src/main/java/org/epctagcoder/option/GSRNP/GSRNPHeader.java
+epctagcoder/src/main/java/org/epctagcoder/option/GSRNP/GSRNPTagSize.java
+epctagcoder/src/main/java/org/epctagcoder/option/GSRNP/partitionTable/GSRNPPartitionTableList.java
+epctagcoder/src/main/java/org/epctagcoder/option/PrefixLength.java
+epctagcoder/src/main/java/org/epctagcoder/option/SGLN/partitionTable/SGLNPartitionTableList.java
+epctagcoder/src/main/java/org/epctagcoder/option/SGLN/SGLNFilterValue.java
+epctagcoder/src/main/java/org/epctagcoder/option/SGLN/SGLNHeader.java
+epctagcoder/src/main/java/org/epctagcoder/option/SGLN/SGLNTagSize.java
+epctagcoder/src/main/java/org/epctagcoder/option/SGTIN/partitionTable/SGTINPartitionTableList.java
+epctagcoder/src/main/java/org/epctagcoder/option/SGTIN/SGTINExtensionDigit.java
+epctagcoder/src/main/java/org/epctagcoder/option/SGTIN/SGTINFilterValue.java
+epctagcoder/src/main/java/org/epctagcoder/option/SGTIN/SGTINHeader.java
+epctagcoder/src/main/java/org/epctagcoder/option/SGTIN/SGTINTagSize.java
+epctagcoder/src/main/java/org/epctagcoder/option/SSCC/partitionTable/SSCCPartitionTableList.java
+epctagcoder/src/main/java/org/epctagcoder/option/SSCC/SSCCExtensionDigit.java
+epctagcoder/src/main/java/org/epctagcoder/option/SSCC/SSCCFilterValue.java
+epctagcoder/src/main/java/org/epctagcoder/option/SSCC/SSCCHeader.java
+epctagcoder/src/main/java/org/epctagcoder/option/SSCC/SSCCTagSize.java
+epctagcoder/src/main/java/org/epctagcoder/option/TableItem.java
+epctagcoder/src/main/java/org/epctagcoder/parse/CPI/ParseCPI.java
+epctagcoder/src/main/java/org/epctagcoder/parse/GDTI/ParseGDTI.java
+epctagcoder/src/main/java/org/epctagcoder/parse/GIAI/ParseGIAI.java
+epctagcoder/src/main/java/org/epctagcoder/parse/GRAI/ParseGRAI.java
+epctagcoder/src/main/java/org/epctagcoder/parse/GSRN/ParseGSRN.java
+epctagcoder/src/main/java/org/epctagcoder/parse/GSRNP/ParseGSRNP.java
+epctagcoder/src/main/java/org/epctagcoder/parse/SGLN/ParseSGLN.java
+epctagcoder/src/main/java/org/epctagcoder/parse/SGTIN/ParseSGTIN.java
+epctagcoder/src/main/java/org/epctagcoder/parse/SSCC/ParseSSCC.java
+epctagcoder/src/main/java/org/epctagcoder/result/Base.java
+epctagcoder/src/main/java/org/epctagcoder/result/CPI.java
+epctagcoder/src/main/java/org/epctagcoder/result/GDTI.java
+epctagcoder/src/main/java/org/epctagcoder/result/GIAI.java
+epctagcoder/src/main/java/org/epctagcoder/result/GRAI.java
+epctagcoder/src/main/java/org/epctagcoder/result/GSRN.java
+epctagcoder/src/main/java/org/epctagcoder/result/GSRNP.java
+epctagcoder/src/main/java/org/epctagcoder/result/SGLN.java
+epctagcoder/src/main/java/org/epctagcoder/result/SGTIN.java
+epctagcoder/src/main/java/org/epctagcoder/result/SSCC.java
+epctagcoder/src/main/java/org/epctagcoder/util/Converter.java
+gradle/wrapper/gradle-wrapper.properties
+README.md
+repomix-instruction.md
+repomix.config.json
+
+
+
+This section contains the contents of the repository's files.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+package com.csl.cs710ademoapp;
+
+import android.os.AsyncTask;
+import android.os.Handler;
+import android.widget.Button;
+import android.widget.TextView;
+import android.widget.Toast;
+
+import com.csl.cslibrary4a.RfidReaderChipData;
+
+import java.util.ArrayList;
+
+public class AccessTask extends AsyncTask {
+ final boolean DEBUG = true;
+ final boolean skipSelect = false;
+ public enum TaskCancelRReason {
+ NULL, INVALD_REQUEST, DESTORY, STOP, BUTTON_RELEASE, ERROR, TIMEOUT
+ }
+ public TaskCancelRReason taskCancelReason;
+ public String accessResult;
+ public String accessTagEpc;
+ Handler mHandler = new Handler();
+ Runnable updateRunnable = null;
+
+ Button button; String buttonText;
+ TextView registerRunTime, registerTagGot, registerVoltageLevel;
+ TextView registerYield, registerTotal;
+ boolean invalidRequest, selectOne = false;
+ String selectMask; int selectBank, selectOffset;
+ String strPassword; int powerLevel;
+ RfidReaderChipData.HostCommands hostCommand;
+
+ CustomMediaPlayer playerO, playerN;
+
+ long timeMillis, startTimeMillis, runTimeMillis;
+ int accessError, backscatterError;
+ boolean timeoutError, crcError;
+ public String resultError = "";
+ boolean success;
+ boolean done = false;
+ boolean ending = false;
+ private String endingMessaage;
+
+ int qValue=0;
+ int repeat=0;
+ boolean bEnableErrorPopWindow=true;
+
+ boolean gotInventory;
+ int batteryCountInventory_old;
+ boolean bSkipClearFilter = false;
+
+ public AccessTask(Button button, boolean invalidRequest, boolean selectOne,
+ String selectMask, int selectBank, int selectOffset,
+ String strPassword, int powerLevel, RfidReaderChipData.HostCommands hostCommand,
+ boolean bEnableErrorPopWindow, Runnable updateRunnable) {
+ this.button = button;
+ this.registerTagGot = registerTagGot;
+ this.registerVoltageLevel = registerVoltageLevel;
+
+ this.invalidRequest = invalidRequest; MainActivity.csLibrary4A.appendToLog("invalidRequest = " + invalidRequest);
+ this.selectOne = selectOne;
+ this.selectMask = selectMask;
+ this.selectBank = selectBank;
+ this.selectOffset = selectOffset;
+ this.strPassword = strPassword;
+ this.powerLevel = powerLevel;
+ this.hostCommand = hostCommand;
+ this.bEnableErrorPopWindow = bEnableErrorPopWindow;
+ this.updateRunnable = updateRunnable;
+ if (true) {
+ total = 0;
+ tagList.clear();
+ }
+ preExecute();
+ }
+ public AccessTask(Button button, TextView textViewWriteCount, boolean invalidRequest, boolean selectOne,
+ String selectMask, int selectBank, int selectOffset,
+ String strPassword, int powerLevel, RfidReaderChipData.HostCommands hostCommand,
+ int qValue, int repeat, boolean resetCount, boolean bSkipClearFilter,
+ TextView registerRunTime, TextView registerTagGot, TextView registerVoltageLevel, TextView registerYieldView, TextView registerTotalView) {
+ this.button = button;
+ this.registerTotal = textViewWriteCount;
+ this.registerRunTime = registerRunTime;
+ this.registerTagGot = registerTagGot;
+ this.registerVoltageLevel = registerVoltageLevel;
+ this.registerYield = registerYieldView;
+ this.registerTotal = registerTotalView;
+
+ this.invalidRequest = invalidRequest; MainActivity.csLibrary4A.appendToLog("invalidRequest = " + invalidRequest);
+ this.selectOne = selectOne;
+ this.selectMask = selectMask;
+ this.selectBank = selectBank;
+ this.selectOffset = selectOffset;
+ this.strPassword = strPassword;
+ this.powerLevel = powerLevel;
+ this.hostCommand = hostCommand;
+ this.qValue = qValue;
+ if (repeat > 255) repeat = 255;
+ this.repeat = repeat;
+ this.bSkipClearFilter = bSkipClearFilter;
+ if (bSkipClearFilter) this.selectOne = false;
+ if (resetCount) {
+ total = 0;
+ tagList.clear();
+ }
+ preExecute();
+ }
+ public void setRunnable(Runnable updateRunnable) {
+ this.updateRunnable = updateRunnable;
+ }
+
+ void preExecute() {
+ accessResult = null; MainActivity.csLibrary4A.appendToLog("accessResult is set null");
+ playerO = MainActivity.sharedObjects.playerO;
+ playerN = MainActivity.sharedObjects.playerN;
+ //playerN.start();
+
+ buttonText = button.getText().toString().trim();
+ String buttonText1 = ""; String strLastChar = "";
+ if (buttonText.length() != 0) {
+ strLastChar = buttonText.substring(buttonText.length() - 1);
+ if (strLastChar.toUpperCase().matches("E")) {
+ buttonText1 = buttonText.substring(0, buttonText.length() - 1);
+ } else if (buttonText.toUpperCase().matches("STOP")) {
+ buttonText1 = buttonText;
+ buttonText1 += buttonText1.substring(buttonText.length() - 1);
+ } else buttonText1 = buttonText;
+ }
+ if (repeat > 1 || buttonText.length() == 0) button.setText("Stop");
+ else {
+ if (Character.isUpperCase(strLastChar.charAt(0))) button.setText(buttonText1 + "ING");
+ else button.setText(buttonText1 + "ing");
+ }
+ if (registerYield != null && tagList.size()==0) registerYield.setText("");
+ if (registerTotal != null && total == 0) registerTotal.setText("");
+
+ timeMillis = System.currentTimeMillis(); startTimeMillis = timeMillis; runTimeMillis = startTimeMillis;
+ accessError = 0; backscatterError = 0; timeoutError = false; crcError = false;
+ success = false;
+
+ if (invalidRequest == false) {
+ if (strPassword.length() != 8) { invalidRequest = true; MainActivity.csLibrary4A.appendToLog("strPassword.length = " + strPassword.length() + " (not 8)."); }
+ else if (hostCommand == RfidReaderChipData.HostCommands.CMD_18K6CKILL) {
+ if (MainActivity.csLibrary4A.setRx000KillPassword(strPassword) == false) {
+ invalidRequest = true; MainActivity.csLibrary4A.appendToLog("setRx000KillPassword is failed");
+ }
+ } else if (MainActivity.csLibrary4A.setRx000AccessPassword(strPassword) == false) {
+ invalidRequest = true;
+ MainActivity.csLibrary4A.appendToLog("setRx000AccessPassword is failed");
+ }
+ }
+ if (invalidRequest == false) {
+ if (MainActivity.csLibrary4A.setAccessRetry(true, 7) == false) {
+ invalidRequest = true; MainActivity.csLibrary4A.appendToLog("setAccessRetry is failed");
+ }
+ }
+ if (invalidRequest == false) {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("AccessTask(): powerLevel = " + powerLevel);
+ int matchRep = 1;
+ if (repeat > 1) matchRep = repeat;
+ if (false && bSkipClearFilter == false) {
+ MainActivity.csLibrary4A.appendToLog("Going to setSelectCriteria disable");
+ MainActivity.csLibrary4A.setSelectCriteriaDisable(-1);
+ }
+ if (powerLevel < 0 || powerLevel > MainActivity.powerLevelMax) invalidRequest = true;
+ else if (skipSelect == false) {
+ MainActivity.csLibrary4A.appendToLog("AccessTask.preExecute goes to setSelectTag");
+ if (MainActivity.csLibrary4A.setSelectedTag(selectOne, selectMask, selectBank, selectOffset, powerLevel, qValue, matchRep) == false) {
+ invalidRequest = true; MainActivity.csLibrary4A.appendToLog("setSelectedTag is failed with selectMask = " + selectMask + ", selectBank = " + selectBank + ", selectOffset = " + selectOffset + ", powerLevel = " + powerLevel);
+ }
+ }
+ }
+ gotInventory = false;
+ taskCancelReason = TaskCancelRReason.NULL;
+ if (invalidRequest) {
+ cancel(true);
+ taskCancelReason = TaskCancelRReason.INVALD_REQUEST;
+ MainActivity.csLibrary4A.appendToLog("invalidRequest A= " + invalidRequest);
+ } else {
+ //MainActivity.csLibrary4A.setTagRead(0);
+ MainActivity.csLibrary4A.sendHostRegRequestHST_CMD(hostCommand);
+ }
+ }
+
+ boolean accessCompleteReceived = false;
+
+ @Override
+ protected String doInBackground(Void... a) {
+ boolean ending = false;
+ int iTimeOut = 5000;
+ accessCompleteReceived = false;
+
+ while (MainActivity.csLibrary4A.isBleConnected() && isCancelled() == false && ending == false) {
+ int batteryCount = MainActivity.csLibrary4A.getBatteryCount();
+ if (batteryCountInventory_old != batteryCount) {
+ batteryCountInventory_old = batteryCount;
+ publishProgress("VV");
+ }
+ if (System.currentTimeMillis() > runTimeMillis + 1000) {
+ runTimeMillis = System.currentTimeMillis();
+ publishProgress("WW");
+ }
+ byte[] notificationData = MainActivity.csLibrary4A.onNotificationEvent();
+ RfidReaderChipData.Rx000pkgData rx000pkgData = MainActivity.csLibrary4A.onRFIDEvent();
+ if (MainActivity.csLibrary4A.mrfidToWriteSize() != 0) timeMillis = System.currentTimeMillis();
+ else if (rx000pkgData != null) {
+ if (rx000pkgData.responseType == null) {
+ publishProgress("null response");
+ } else if (rx000pkgData.responseType == RfidReaderChipData.HostCmdResponseTypes.TYPE_18K6C_TAG_ACCESS) {
+ accessCompleteReceived = true;
+ MainActivity.csLibrary4A.appendToLog("rx000pkgData.dataValues = " + MainActivity.csLibrary4A.byteArrayToString(rx000pkgData.dataValues));
+ if (rx000pkgData.decodedError == null) {
+ if (done == false) {
+ accessResult = rx000pkgData.decodedResult;
+ MainActivity.csLibrary4A.appendToLog("responseType = " + rx000pkgData.responseType.toString() + ", accessResult = " + accessResult);
+ if (repeat > 0) repeat--;
+ if (updateRunnable != null) mHandler.post(updateRunnable);
+ publishProgress(null, rx000pkgData.decodedResult);
+ }
+ done = true;
+ } else publishProgress(rx000pkgData.decodedError);
+ iTimeOut = 1000;
+ } else if (rx000pkgData.responseType == RfidReaderChipData.HostCmdResponseTypes.TYPE_COMMAND_END) {
+ if (hostCommand == RfidReaderChipData.HostCommands.CMD_18K6CKILL && accessCompleteReceived == false) accessResult = "";
+ MainActivity.csLibrary4A.appendToLog("BtData: repeat = " + repeat + ", decodedError = " + rx000pkgData.decodedError + ", resultError = " + resultError);
+ if (rx000pkgData.decodedError != null) { endingMessaage = rx000pkgData.decodedError; ending = true; }
+ else if (repeat > 0 && resultError.length() == 0) {
+ resultError = "";
+ if (true) MainActivity.csLibrary4A.appendToLog("Debug_InvCfg: AccessTask.doInBackground goes to setMatchRep with repeat = " + repeat);
+ MainActivity.csLibrary4A.setMatchRep(repeat);
+ MainActivity.csLibrary4A.sendHostRegRequestHST_CMD(hostCommand);
+ } else {
+ endingMessaage = "";
+ ending = true;
+ }
+ } else if (rx000pkgData.responseType == RfidReaderChipData.HostCmdResponseTypes.TYPE_18K6C_INVENTORY) {
+ accessTagEpc = MainActivity.csLibrary4A.byteArrayToString(rx000pkgData.decodedEpc);
+ done = false;
+ publishProgress("TT", MainActivity.csLibrary4A.byteArrayToString(rx000pkgData.decodedEpc));
+ } else {
+ publishProgress("Unhandled Response: " + rx000pkgData.responseType.toString());
+ }
+ timeMillis = System.currentTimeMillis();
+ }
+ else if (notificationData != null) {
+ //MainActivity.csLibrary4A.appendToLog("resultError=" + MainActivity.csLibrary4A.byteArrayToString(notificationData));
+ publishProgress("Received notification uplink event 0xA101 with error code=" + MainActivity.csLibrary4A.byteArrayToString(notificationData));
+ taskCancelReason = TaskCancelRReason.ERROR;
+ }
+ if (System.currentTimeMillis() - timeMillis > iTimeOut) {
+ //MainActivity.csLibrary4A.appendToLog("endingMessage: iTimeout = " + iTimeOut);
+ taskCancelReason = TaskCancelRReason.TIMEOUT;
+ }
+ if (taskCancelReason != TaskCancelRReason.NULL) {
+ //MainActivity.csLibrary4A.appendToLog("taskCancelReason=" + TaskCancelRReason.values());
+ cancel(true);
+ }
+ }
+ return "End of Asynctask():" + ending;
+ }
+
+ static int total = 0;
+ static ArrayList tagList = new ArrayList();
+ String tagInventoried = null;
+ @Override
+ protected void onProgressUpdate(String... output) {
+ if (output[0] != null) {
+ MainActivity.csLibrary4A.appendToLog("onProgressUpdate output[0] = " + output[0]);
+ if (output[0].length() == 2) {
+ if (output[0].contains("TT")) {
+ gotInventory = true;
+ boolean matched = false;
+ for (int i = 0; i < tagList.size(); i++) {
+ if (output[1].matches(tagList.get(i))) {
+ matched = true;
+ break;
+ }
+ }
+ if (registerTagGot != null) registerTagGot.setText(output[1]);
+ if (matched == false) tagInventoried = output[1];
+ } else if (output[0].contains("WW")) {
+ long timePeriod = (System.currentTimeMillis() - startTimeMillis) / 1000;
+ if (timePeriod > 0) {
+ if (registerRunTime != null) registerRunTime.setText(String.format("Run time: %d sec", timePeriod));
+ }
+ } else if (taskCancelReason == TaskCancelRReason.NULL) {
+ if (registerVoltageLevel != null) registerVoltageLevel.setText(MainActivity.csLibrary4A.getBatteryDisplay(true));
+ }
+ } else {
+ resultError += output[0];
+ if (true)
+ MainActivity.csLibrary4A.appendToLog("output[0]: " + output[0] + ", resultError = " + resultError);
+ }
+ } else {
+ MainActivity.csLibrary4A.appendToLog("onProgressUpdate output[1] = " + output[1]);
+ if (registerYield != null) {
+ if (tagInventoried != null) {
+ tagList.add(tagInventoried);
+ tagInventoried = null;
+ }
+ registerYield.setText("Unique:" + Integer.toString(tagList.size()));
+ }
+ if (registerTotal != null) registerTotal.setText("Total:" + Integer.toString(++total));
+ }
+ }
+
+ @Override
+ protected void onCancelled() {
+ super.onCancelled();
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("endingMesssage: taskCancelReason = " + taskCancelReason);
+ MainActivity.csLibrary4A.abortOperation();
+ if (taskCancelReason == TaskCancelRReason.NULL) taskCancelReason = TaskCancelRReason.DESTORY;
+ DeviceConnectTask4RegisterEnding();
+ }
+
+ @Override
+ protected void onPostExecute(String result) {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("AccessSecurityLockFragment.InventoryRfidTask.onPostExecute(): " + result);
+ DeviceConnectTask4RegisterEnding();
+ }
+
+ void DeviceConnectTask4RegisterEnding() {
+ //MainActivity.csLibrary4A.setAccessCount(0);
+ String strErrorMessage = "";
+ if (false) {
+ boolean success = false;
+ MainActivity.csLibrary4A.appendToLog("repeat = " + repeat + ", taskCancelReason = " + taskCancelReason.toString()
+ + ", backscatterError = " + backscatterError + ", accessError =" + accessError + ", accessResult = " + accessResult + ", resultError = " + resultError);
+ if ((repeat <= 1 && taskCancelReason != TaskCancelRReason.NULL) || backscatterError != 0 || accessError != 0 || accessResult == null || resultError.length() != 0) {
+ MainActivity.csLibrary4A.appendToLog("FAILURE"); Toast.makeText(MainActivity.mContext, R.string.toast_abort_by_FAILURE, Toast.LENGTH_SHORT).show();
+ playerO.start();
+ } else {
+ MainActivity.csLibrary4A.appendToLog("SUCCESS"); Toast.makeText(MainActivity.mContext, R.string.toast_abort_by_SUCCESS, Toast.LENGTH_SHORT).show();
+ playerN.start();
+ }
+ } else {
+ strErrorMessage = "";
+ switch (taskCancelReason) {
+ case NULL:
+ if (accessResult == null) MainActivity.csLibrary4A.appendToLog("taskCancelReason: NULL accessResult");
+ if (resultError != null) MainActivity.csLibrary4A.appendToLog("taskCancelReason: resultError = " + resultError);
+ if (endingMessaage != null) MainActivity.csLibrary4A.appendToLog("taskCancelReason: endingMessaage = " + endingMessaage);
+ if (accessResult == null || (resultError != null && resultError.length() != 0) || (endingMessaage != null && endingMessaage.length() != 0)) strErrorMessage += ("Finish as COMMAND END is received " + (gotInventory ? "WITH" : "WITHOUT") + " tag response");
+ //else Toast.makeText(MainActivity.mContext, R.string.toast_abort_by_SUCCESS, Toast.LENGTH_SHORT).show();
+ break;
+ case STOP:
+ strErrorMessage += "Finish as STOP is pressed. ";
+ break;
+ case BUTTON_RELEASE:
+ strErrorMessage += "Finish as BUTTON is released. ";
+ break;
+ case ERROR:
+ strErrorMessage += "Finish due to error received.";
+ break;
+ case TIMEOUT:
+ strErrorMessage += "TIMEOUT without COMMAND_END. ";
+ break;
+ case INVALD_REQUEST:
+ strErrorMessage += "Invalid request. Operation is cancelled. ";
+ break;
+ }
+ MainActivity.csLibrary4A.appendToLog("taskCancelReason = " + taskCancelReason.toString() + ", accessResult = " + (accessResult == null ? "NULL": accessResult) + ", endingMessaage = " + (endingMessaage == null ? "NULL" : endingMessaage) + ", resultError = " + (resultError == null ? "NULL" : resultError));
+ if (resultError.length() != 0) {
+ if (strErrorMessage.trim().length() == 0) strErrorMessage = resultError;
+ else strErrorMessage += (". " + resultError);
+ }
+ if (strErrorMessage.length() != 0) strErrorMessage += ". ";
+ }
+ if (endingMessaage != null) if (endingMessaage.length() != 0) strErrorMessage += "Received CommandEND Error = " + endingMessaage;
+ if (strErrorMessage.length() != 0) endingMessaage = strErrorMessage;
+ button.setText(buttonText);
+ if (endingMessaage != null) {
+ if (endingMessaage.length() != 0) {
+ MainActivity.csLibrary4A.appendToLog("endingMessage=" + endingMessaage);
+ if (bEnableErrorPopWindow) {
+ CustomPopupWindow customPopupWindow = new CustomPopupWindow(MainActivity.mContext);
+ customPopupWindow.popupStart(endingMessaage, false);
+ }
+ }
+ }
+ }
+}
+
+
+
+package com.csl.cs710ademoapp;
+
+import android.os.AsyncTask;
+import android.widget.Button;
+import android.widget.Toast;
+
+import com.csl.cslibrary4a.RfidReaderChipData;
+
+public class AccessTask1 {
+ Button button;
+ boolean invalidRequest;
+ int accBank, accOffset, accSize, accSizeNow, accBlockCount = 90; String accWriteData, accWriteDataNow;
+ String selectMask;
+ int selectBank, selectOffset;
+ String strPassword;
+ int powerLevel;
+ RfidReaderChipData.HostCommands hostCommand;
+ Runnable updateRunnable = null;
+
+ AccessTask accessTask;
+ public AccessTask1(Button button, boolean invalidRequest,
+ int accBank, int accOffset, int accSize, int accBlockCount, String accWriteData,
+ String selectMask, int selectBank, int selectOffset,
+ String strPassword, int powerLevel, RfidReaderChipData.HostCommands hostCommand, Runnable updateRunnable) {
+ this.button = button;
+ this.invalidRequest = invalidRequest;
+ MainActivity.csLibrary4A.appendToLog("HelloK: invalidRequest=" + invalidRequest);
+ this.accBank = accBank;
+ this.accOffset = accOffset;
+ if (hostCommand == RfidReaderChipData.HostCommands.CMD_18K6CWRITE) { if (accBlockCount > 16) accBlockCount = 16; }
+ else if (accBlockCount > 255) accBlockCount = 255;
+ this.accBlockCount = accBlockCount;
+ if (accWriteData == null) accWriteData = "";
+ if (hostCommand == RfidReaderChipData.HostCommands.CMD_18K6CWRITE) {
+ MainActivity.csLibrary4A.appendToLog("strOut: accWriteData=" + accWriteData);
+ accWriteData = deformatWriteAccessData(accWriteData);
+ if (accWriteData.length() < accSize * 4) {
+ accSize = accWriteData.length()/4;
+ if (accSize*4 != accWriteData.length()) accSize++;
+ }
+ }
+ this.accSize = accSize;
+ if (accSize == 0) {
+ isResultReady = true;
+ accessResult = "";
+ }
+ this.accWriteData = accWriteData;
+ this.selectMask = selectMask;
+ this.selectBank = selectBank;
+ this.selectOffset = selectOffset;
+ this.strPassword = strPassword;
+ this.powerLevel = powerLevel;
+ this.hostCommand = hostCommand;
+ this.updateRunnable = updateRunnable;
+ MainActivity.csLibrary4A.appendToLog("HelloA, AccessTask1");
+ CustomMediaPlayer playerN = MainActivity.sharedObjects.playerN;
+ playerN.start();
+ setup();
+ }
+
+ public void execute() {
+ if (accessTask != null) accessTask.execute();
+ }
+
+ public boolean cancel(boolean bCancel) {
+ if (accessTask == null) return true;
+ return accessTask.cancel(bCancel);
+ }
+
+ public AsyncTask.Status getStatus() {
+ if (accessTask == null) return AsyncTask.Status.FINISHED;
+ return accessTask.getStatus();
+ }
+
+ public String deformatWriteAccessData(String strIn) {
+ MainActivity.csLibrary4A.appendToLog("strOut: strIn=" + strIn);
+ String strOut = strIn.replaceAll("\\P{Print}", "");
+ MainActivity.csLibrary4A.appendToLog("strOut=" + strOut);
+ while (strOut.indexOf(":") > 0) {
+ int index = strOut.indexOf(":");
+ String writeDataTemp = "";
+ if (index > 4) writeDataTemp = strOut.substring(0, index - 3);
+ writeDataTemp += strOut.substring(index + 1);
+ strOut = writeDataTemp;
+ MainActivity.csLibrary4A.appendToLog("strOut=" + strOut);
+ }
+ MainActivity.csLibrary4A.appendToLog("strOut=" + strOut);
+ return strOut;
+ }
+
+ boolean isResultReady = false; int tryCount = 0, tryCountMax = 8;
+ public boolean isResultReady() {
+ boolean bValue = false;
+ if (accessTask == null) { }
+ else if (accessTask.getStatus() != AsyncTask.Status.FINISHED) { }
+ else if (button.getText().toString().indexOf("ING") > 0) { }
+ else if (isResultReady == false) {
+ String strAccessResult = "";
+ if (hostCommand != RfidReaderChipData.HostCommands.CMD_18K6CREAD || accBank != 3) strAccessResult = accessTask.accessResult;
+ else {
+ int word4line = 7;
+ for (int i = 0; i < accSizeNow; i=i+word4line) {
+ if (tryCount < tryCountMax && accessTask.accessResult == null) break;
+ strAccessResult += String.format("%03d:", accOffset + i);
+ if (accessTask.accessResult != null) {
+ if ((i + word4line) * 4 >= accessTask.accessResult.length()) {
+ int iLastWordIndex = accessTask.accessResult.substring(i * 4).length() / 4;
+ if (iLastWordIndex * 4 != accessTask.accessResult.substring(i * 4).length())
+ iLastWordIndex++;
+ strAccessResult += String.format("%03d:", accOffset + i + iLastWordIndex - 1) + accessTask.accessResult.substring(i * 4);
+ } else
+ strAccessResult += accessTask.accessResult.substring(i * 4, (i + word4line) * 4);
+ }
+ strAccessResult += "\n";
+ MainActivity.csLibrary4A.appendToLog("i=" + i + ", formatted accessTask.accessResult=" + strAccessResult);
+ }
+ }
+ if (accessResult == null) accessResult = strAccessResult;
+ else accessResult += strAccessResult;
+
+ MainActivity.csLibrary4A.appendToLog("HelloA: accessResult=" + accessTask.accessResult);
+ if (accessTask.accessResult != null && accSizeNow >= accSize) {
+ bValue = true;
+ Toast.makeText(MainActivity.mContext, R.string.toast_abort_by_SUCCESS, Toast.LENGTH_SHORT).show();
+ }
+ else {
+ if (accessTask.accessResult != null) {
+ accOffset += accSizeNow;
+ accSize -= accSizeNow;
+ if (accWriteData != null) { if (accWriteData.length() >= accSizeNow*4) accWriteData = accWriteData.substring(accSizeNow*4); }
+ tryCount = 0;
+ }
+ MainActivity.csLibrary4A.appendToLog("HelloA: Going to retry with TryCount=" + tryCount + ", resultError = " + accessTask.resultError);
+ if (tryCount < tryCountMax) {
+ MainActivity.csLibrary4A.appendToLog("HelloA: re-setup");
+ setup();
+ execute();
+ } else bValue = true;
+ }
+ } else bValue = true;
+ //MainActivity.csLibrary4A.appendToLog("HelloA: bValue=" + bValue);
+ isResultReady = bValue;
+ return bValue;
+ }
+ public String accessResult;
+ public String getResult() {
+ MainActivity.csLibrary4A.appendToLog("HelloA: accessResult = " + accessResult);
+ if (accessTask == null) {
+ MainActivity.csLibrary4A.appendToLog("accessTask is null");
+ return null;
+ }
+ if (accessTask.getStatus() != AsyncTask.Status.FINISHED) {
+ MainActivity.csLibrary4A.appendToLog("accessTask.getStatus is not finished");
+ return null;
+ }
+ if (button.getText().toString().indexOf("ING") > 0) {
+ MainActivity.csLibrary4A.appendToLog("button is still ing");
+ return null;
+ }
+ return accessResult;
+ }
+
+ void setup() {
+ tryCount++;
+ if (invalidRequest == false) {
+ if (MainActivity.csLibrary4A.setAccessBank(accBank) == false) {
+ MainActivity.csLibrary4A.appendToLog("HelloK: accBank, invalidRequest=" + invalidRequest);
+ invalidRequest = true;
+ }
+ }
+ if (invalidRequest == false) {
+ if (MainActivity.csLibrary4A.setAccessOffset(accOffset) == false) {
+ MainActivity.csLibrary4A.appendToLog("HelloK: accOffset, invalidRequest=" + invalidRequest);
+ invalidRequest = true;
+ }
+ }
+ if (invalidRequest == false) {
+ if (accSize == 0) {
+ MainActivity.csLibrary4A.appendToLog("HelloK: accSize0, invalidRequest=" + invalidRequest);
+ invalidRequest = true;
+ } else {
+ if (accSize > accBlockCount) accSizeNow = accBlockCount;
+ else accSizeNow = accSize;
+ MainActivity.csLibrary4A.appendToLog("HelloA: accSize=" + accSize + ", accSizeNow=" + accSizeNow);
+ if (MainActivity.csLibrary4A.setAccessCount(accSizeNow) == false) {
+ invalidRequest = true;
+ }
+ }
+ }
+ if (invalidRequest == false && hostCommand == RfidReaderChipData.HostCommands.CMD_18K6CWRITE) {
+ if (accWriteData.length() > accSizeNow * 4) accWriteDataNow = accWriteData.substring(0, accSizeNow*4);
+ else accWriteDataNow = accWriteData;
+ if (MainActivity.csLibrary4A.setAccessWriteData(accWriteDataNow) == false) {
+ invalidRequest = true;
+ }
+ }
+ MainActivity.csLibrary4A.appendToLog("HelloA: accOffset=" + accOffset + ", accSizeNow=" + accSizeNow + ", accSize=" + accSize);
+ MainActivity.csLibrary4A.appendToLog("HelloK: invalidRequest=" + invalidRequest);
+ accessTask = new AccessTask(button, invalidRequest, true,
+ selectMask, selectBank, selectOffset,
+ strPassword, powerLevel, hostCommand, tryCount==tryCountMax, updateRunnable);
+ }
+}
+
+
+
+package com.csl.cs710ademoapp.adapters;
+
+import android.content.Context;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.ArrayAdapter;
+import android.widget.TextView;
+
+import com.csl.cs710ademoapp.DrawerListContent;
+import com.csl.cs710ademoapp.R;
+
+import java.util.List;
+
+/**
+ * Class to handle the data for NavigationDrawer.
+ */
+public class DrawerListAdapter extends ArrayAdapter {
+ Context mContext;
+ List mData = null;
+
+ /**
+ * Construtor. Handles the initialization.
+ *
+ * @param context - context to be used
+ * @param resource - layout to be inflated
+ * @param objects - navidation drawer items
+ */
+ public DrawerListAdapter(Context context, int resource, List objects) {
+ super(context, resource, objects);
+ this.mContext = context;
+ this.mData = objects;
+ }
+
+ @Override
+ public View getView(int position, View convertView, ViewGroup parent) {
+ if (convertView == null) {
+ LayoutInflater inflater = (LayoutInflater) mContext
+ .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
+ convertView = inflater.inflate(R.layout.drawer_list_item, parent, false);
+ }
+
+ DrawerListContent.DrawerItem item = mData.get(position);
+ //Set the label
+ TextView label1 = (TextView) convertView.findViewById(R.id.drawerItemName);
+ label1.setText(item.content);
+ return convertView;
+ }
+}
+
+
+
+package com.csl.cs710ademoapp.adapters;
+
+import android.content.Context;
+import android.text.Html;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.ArrayAdapter;
+import android.widget.CheckedTextView;
+import android.widget.TextView;
+
+import com.csl.cs710ademoapp.MainActivity;
+import com.csl.cs710ademoapp.R;
+import com.csl.cslibrary4a.ReaderDevice;
+
+import java.util.ArrayList;
+
+public class ReaderListAdapter extends ArrayAdapter {
+ final boolean DEBUG = false;
+ private final Context context;
+ private final int resourceId;
+ private final ArrayList readersList;
+ private boolean select4detail, select4Rssi, selectDupElim, select4Extra1, select4Extra2;
+
+ public ReaderListAdapter(Context context, int resourceId, ArrayList readersList, boolean select4detail, boolean select4Rssi) {
+ super(context, resourceId, readersList);
+ this.context = context;
+ this.resourceId = resourceId;
+ this.readersList = readersList;
+ this.select4detail = select4detail;
+ this.select4Rssi = select4Rssi;
+ select4Extra1 = false;
+ select4Extra2 = false;
+ }
+
+ public ReaderListAdapter(Context context, int resourceId, ArrayList readersList, boolean select4detail, boolean select4Rssi, boolean selectDupElim, boolean select4Extra1, boolean select4Extra2) {
+ super(context, resourceId, readersList);
+ this.context = context;
+ this.resourceId = resourceId;
+ this.readersList = readersList;
+ this.select4detail = select4detail;
+ this.select4Rssi = select4Rssi;
+ this.selectDupElim = selectDupElim;
+ this.select4Extra1 = select4Extra1;
+ this.select4Extra2 = select4Extra2;
+ MainActivity.csLibrary4A.appendToLog("select4Extra1 = " + select4Extra1 + ", select4Extra2 = " + select4Extra2);
+ }
+
+ @Override
+ public View getView(int position, View convertView, ViewGroup parent) {
+ ReaderDevice reader = readersList.get(position);
+ if (convertView == null) {
+ LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
+ convertView = layoutInflater.inflate(resourceId, null);
+ }
+
+ CheckedTextView checkedTextView = (CheckedTextView) convertView.findViewById(R.id.reader_checkedtextview);
+ String text1 = "";
+ if (reader.getName() != null) {
+ if (reader.getName().length() != 0) {
+ text1 += reader.getName();
+ }
+ }
+ if (reader.getAddress() != null) {
+ if (reader.getAddress().length() != 0) {
+ if (text1.length() != 0) text1 += "\n";
+ text1 += reader.getAddress();
+ }
+ }
+ if (reader.getUpcSerial() != null) {
+ if (reader.getUpcSerial().length() != 0) {
+ if (text1.length() != 0) text1 += "\n";
+ text1 += reader.getUpcSerial();
+ }
+ }
+ if (MainActivity.csLibrary4A.isBleScanning()) {
+ if (reader.getServiceUUID2p1() == 0 || reader.getServiceUUID2p1() == 1) text1 += "\nCS108 Reader";
+ else if (reader.getServiceUUID2p1() == 2 || reader.getServiceUUID2p1() == 3) text1 += "\nCS710S Reader";
+ else if (reader.getServiceUUID2p1() == 4) text1 += "\nCS463 Reader";
+ else if (reader.getServiceUUID2p1() == 5) text1 += "\nCS203XL Reader";
+ else if (reader.getServiceUUID2p1() == 6) text1 += "\nConnected paired devices";
+ }
+ checkedTextView.setText(text1);
+ if (reader.getSelected()) {
+ checkedTextView.setChecked(true);
+ } else {
+ checkedTextView.setChecked(false);
+ }
+
+ TextView countTextView = (TextView) convertView.findViewById(R.id.reader_count);
+ if (reader.getCount() != 0) {
+ countTextView.setText(String.valueOf(reader.getCount()));
+ } else {
+ countTextView.setVisibility(View.GONE);
+ }
+
+ if (select4Rssi) {
+ TextView rssiTextView = (TextView) convertView.findViewById(R.id.reader_rssi);
+ rssiTextView.setVisibility(View.VISIBLE);
+ double rssiValue = reader.getRssi();
+ if (MainActivity.csLibrary4A.getRssiDisplaySetting() != 0 && rssiValue > 0)
+ rssiValue -= MainActivity.csLibrary4A.dBuV_dBm_constant;
+ rssiTextView.setText(String.format("%.1f", rssiValue));
+ }
+
+ if (select4Extra1) {
+ TextView portTextView = (TextView) convertView.findViewById(R.id.reader_extra1);
+ portTextView.setVisibility(View.VISIBLE);
+ int portValue = reader.getPort() + 1;
+ portTextView.setText(String.valueOf(portValue));
+ }
+
+ if (select4Extra2) {
+ TextView portTextView = (TextView) convertView.findViewById(R.id.reader_extra2);
+ portTextView.setVisibility(View.VISIBLE);
+ int codeStatus = reader.getStatus();
+ int codeSensor = reader.getCodeSensor(); int codeRssi = reader.getCodeRssi(); float codeTempC = reader.getCodeTempC();
+ String brand = reader.getBrand();
+ String strExtra = "";
+ if (codeStatus > reader.INVALID_STATUS) { //for Bap tags
+ int portstatus = reader.getStatus(); if (portstatus > reader.INVALID_STATUS) {
+ if ((portstatus & 2) == 0) strExtra += "Bat OK";
+ else strExtra += "Bat NG";
+ if ((portstatus & 4) != 0) strExtra += "\nTemper NG";
+ }
+ } else if (codeSensor > reader.INVALID_CODESENSOR && codeRssi > reader.INVALID_CODERSSI) { //for Axzon/Magnus tags
+ strExtra = "SC=" + String.format("%d", codeSensor);
+ int iHumidityThreshold = Integer.parseInt(MainActivity.config.config3);
+ if (false && reader.getCodeSensorMax() > 0) {
+ float fValue = (float) codeSensor;
+ fValue /= (float) reader.getCodeSensorMax();
+ fValue *= 100;
+ strExtra += "\nSC=" + String.format("%.1f", fValue) + "%";
+ } else if (iHumidityThreshold > 0) {
+ strExtra += "\nSC=" + (codeSensor >= iHumidityThreshold ? "Dry" : "Wet");
+ }
+ int ocrssiMin = -1; int ocrssiMax = -1; boolean bValidOcrssi = false;
+ ocrssiMax = Integer.parseInt(MainActivity.config.config1);
+ ocrssiMin = Integer.parseInt(MainActivity.config.config2);
+ if (ocrssiMax > 0 && ocrssiMin > 0 && (codeRssi > ocrssiMax || codeRssi < ocrssiMin)) strExtra += ("\nOCRSSI=" + String.format("%d", codeRssi) + "");
+ else {
+ bValidOcrssi = true; strExtra += ("\nOCRSSI=" + String.format("%d", codeRssi));
+ }
+ if (codeTempC > reader.INVALID_CODETEMPC) {
+ if (bValidOcrssi || portTextView.getText().toString().indexOf("T=") >= 0)
+ strExtra += ("\nT=" + String.format("%.1f", codeTempC) + (char) 0x00B0 + "C");
+ }
+ int backport = reader.getBackport1(); if (backport > reader.INVALID_BACKPORT) strExtra += String.format("\nBP1=%d", backport);
+ backport = reader.getBackport2(); if (backport > reader.INVALID_BACKPORT) strExtra += String.format("\nBP2=%d", backport);
+ } else if (codeTempC > reader.INVALID_CODETEMPC) { //for Ctesius tags
+ strExtra = ("T=" + String.format("%.1f", codeTempC) + (char) 0x00B0 + "C");
+ } else if (brand != null) { //reader.getDetails().contains("E2806894")) { //for code8 tags
+ strExtra = ((brand != null) ? ("Brand=" + brand) : "");
+ } else if (reader.getSensorData() < reader.INVALID_SENSORDATA) {
+ strExtra = "SD=" + String.valueOf(reader.getSensorData());
+ }
+ portTextView.setText(Html.fromHtml(strExtra));
+ }
+
+ TextView readerDetailA = (TextView) convertView.findViewById(R.id.reader_detailA);
+ TextView readerDetailB = (TextView) convertView.findViewById(R.id.reader_detailB);
+ if (reader.isConnected() || checkedTextView.isChecked() || select4detail == false) {
+ readerDetailA.setText(reader.getDetails());
+ readerDetailB.setText("");
+ if (reader.isConnected()) {
+ readerDetailB.setText("Connected");
+ } else {
+ int channel = reader.getChannel();
+ int phase = reader.getPhase();
+ String stringDetailB = null;
+ if (channel != 0 || phase != 0) {
+ double dChannel = MainActivity.csLibrary4A.getLogicalChannel2PhysicalFreq(reader.getChannel());
+ stringDetailB = "Phase=" + phase + "\n" + dChannel + "MHz";
+ }
+ if (stringDetailB != null) readerDetailB.setText(stringDetailB);
+ }
+ if (readerDetailA.getText().toString().length() != 0 || readerDetailB.getText().toString().length() != 0) {
+ readerDetailA.setVisibility(View.VISIBLE);
+ readerDetailB.setVisibility(View.VISIBLE);
+ } else {
+ readerDetailA.setVisibility(View.GONE);
+ readerDetailB.setVisibility(View.GONE);
+ }
+ } else {
+ readerDetailA.setVisibility(View.GONE);
+ readerDetailB.setVisibility(View.GONE);
+ }
+ return convertView;
+ }
+
+ public boolean getSelectDupElim() { return selectDupElim; }
+ public void setSelectDupElim(boolean selectDupElim) { this.selectDupElim = selectDupElim; }
+}
+
+
+
+package com.csl.cs710ademoapp;
+
+import android.app.Activity;
+import android.app.AlertDialog;
+import android.content.DialogInterface;
+
+public class CustomAlertDialog {
+ Runnable ans_true = null;
+ Runnable ans_false = null;
+ AlertDialog dialog = null;
+ public boolean Confirm(Activity act, String Title, String ConfirmText,
+ String CancelBtn, String OkBtn, Runnable aProcedure, Runnable bProcedure) {
+ ans_true = aProcedure;
+ ans_false= bProcedure;
+ dialog = new AlertDialog.Builder(act).create();
+ dialog.setTitle(Title);
+ dialog.setMessage(ConfirmText);
+ dialog.setCancelable(false);
+ dialog.setButton(DialogInterface.BUTTON_POSITIVE, OkBtn,
+ new DialogInterface.OnClickListener() {
+ public void onClick(DialogInterface dialog, int buttonId) {
+ ans_true.run();
+ }
+ });
+ dialog.setButton(DialogInterface.BUTTON_NEGATIVE, CancelBtn,
+ new DialogInterface.OnClickListener() {
+ public void onClick(DialogInterface dialog, int buttonId) {
+ ans_false.run();
+ }
+ });
+ dialog.setIcon(R.drawable.alert);
+ dialog.show();
+ return true;
+ }
+
+ public boolean isShowing() {
+ if (dialog != null) return dialog.isShowing();
+ else return false;
+ }
+}
+
+
+
+package com.csl.cs710ademoapp;
+
+import android.inputmethodservice.InputMethodService;
+import android.inputmethodservice.Keyboard;
+import android.inputmethodservice.KeyboardView;
+import android.os.AsyncTask;
+import android.os.Handler;
+import android.provider.Settings;
+import android.util.Log;
+import android.view.View;
+import android.view.inputmethod.InputConnection;
+
+import com.csl.cslibrary4a.RfidReaderChipData;
+
+import java.io.IOException;
+import java.net.DatagramPacket;
+import java.net.DatagramSocket;
+import java.net.InetAddress;
+import java.net.SocketException;
+import java.util.ArrayList;
+
+import static android.content.ContentValues.TAG;
+
+public class CustomIME extends InputMethodService { //implements KeyboardView.OnKeyboardActionListener {
+ Handler mHandler = new Handler();
+ InputConnection ic;
+ DatagramSocket datagramSocket;
+ InetAddress hostAddress = null;
+
+ @Override
+ public void onCreate() {
+ super.onCreate();
+ try {
+ hostAddress = hostAddress = InetAddress.getByName("127.0.0.1");
+ Log.i("Hello", "udpSocket hostAddress is valid");
+ datagramSocket = new DatagramSocket(9394, hostAddress);
+ if (datagramSocket == null) Log.i("Hello", "udpSocket is null");
+ else Log.i("Hello", "udpSocket is valid");
+ //byte[] buffer = new byte[16];
+ //DatagramPacket packet = new DatagramPacket(buffer, buffer.length, InetAddress.getByName("localhost"), 14552);
+ //udpsocket.send(packet);
+ } catch (SocketException e) {
+ Log.e("UDP: ", "udpSocket Socket Error: ", e);
+ } catch (IOException e) {
+ Log.e("UDP Send: ", "udpSocket IO Error", e);
+ } catch (Exception ex) {
+ Log.i("Hello", "udpSocket Exception Error: " + ex.getMessage());
+ }
+ appendToLog("CustomIME.onCreate()");
+ }
+ @Override
+ public View onCreateInputView() {
+ super.onCreateInputView();;
+ mHandler.post(serviceRunnable);
+ KeyboardView keyboardView = null;
+ if (true) {
+ keyboardView = (KeyboardView) getLayoutInflater().inflate(R.layout.keyboard_view, null);
+ Keyboard keyboard = new Keyboard(this, R.xml.number_pad1);
+ keyboardView.setKeyboard(keyboard);
+ //keyboardView.setOnKeyboardActionListener(this);
+ }
+ ic = getCurrentInputConnection();
+ Log.i("Hello", "udpSocket inputConnection is " + (ic == null ? "null" : "valid"));
+ return keyboardView;
+ }
+ @Override
+ public void onDestroy() {
+ appendToLog("CustomIME.onDestroy()");
+ mHandler.removeCallbacks(serviceRunnable);
+ datagramSocket.close();
+ super.onDestroy();
+ }
+
+ Runnable yourRunnable = new Runnable() {
+ @Override
+ public void run() {
+ byte[] buffer = new byte[250];
+ Log.i("Hello", "udpSocket yourRunnable starts");
+ DatagramPacket datagramPacket = new DatagramPacket(buffer, buffer.length);
+ ic = getCurrentInputConnection();
+ try {
+ Log.i("Hello", "udpSocket try starts");
+// String outString = "Client say: bye bye";
+// buffer = outString.getBytes();
+// DatagramPacket outDatagramPackat = new DatagramPacket(buffer, buffer.length, hostAddress, 9394);
+// datagramSocket.send(outDatagramPackat);
+// Log.i("Hello", "udpSocket sent data");
+
+ String strDataReceived;
+ do {
+ strDataReceived = null;
+ datagramSocket.receive(datagramPacket);
+ strDataReceived = new String(datagramPacket.getData(), 0, datagramPacket.getLength());
+ Log.i("Hello", "udpSocket received data: " + strDataReceived);
+ ic.commitText(strDataReceived, 1);
+ } while (strDataReceived != null && strDataReceived.length() != 0);
+ } catch (IOException ex) {
+ Log.i("Hello", "udpSocket receive IOException Error: " + ex.toString());
+ }
+ }
+ };
+
+ ArrayList epcArrayList = new ArrayList();
+ InventoryRfidTask inventoryRfidTask;
+ InventoryBarcodeTask inventoryBarcodeTask;
+ boolean inventoring = false;
+ private Runnable serviceRunnable = new Runnable() {
+ @Override
+ public void run() {
+ String strCurrentIME = Settings.Secure.getString(getContentResolver(), Settings.Secure.DEFAULT_INPUT_METHOD);
+ String strCompare = getPackageName();
+ appendToLog("CustomIME Debug 0 with strCurrentIME = " + strCurrentIME + ", strCompare = " + strCompare);
+ if (strCurrentIME.contains(strCompare) == false) { }
+ else if (MainActivity.sharedObjects == null || MainActivity.csLibrary4A == null) {
+ if (false) { new Thread(yourRunnable).start(); }
+ }
+ else if (MainActivity.mContext == null) return;
+ else {
+ if (inventoring == false) {
+ MainActivity.sharedObjects.serviceArrayList.clear();
+ epcArrayList.clear();
+ }
+ appendToLog("CustomIME Debug 1 with activityActive = " + MainActivity.activityActive + ", wedged = " + MainActivity.wedged + ", isBleConnected = " + MainActivity.csLibrary4A.isBleConnected());
+ if (MainActivity.activityActive == false /*&& MainActivity.wedged*/ && MainActivity.csLibrary4A.isBleConnected()) {
+ if (MainActivity.csLibrary4A.getTriggerButtonStatus() == false) {
+ appendToLog("CustomIME Debug 2 with runningInventoryRfidTask = " + MainActivity.sharedObjects.runningInventoryRfidTask);
+ appendToLog("CustomIME Debug 2 with runningInventoryBarcodeTask = " + MainActivity.sharedObjects.runningInventoryBarcodeTask);
+ startStopHandler();
+ inventoring = false;
+ } else if (inventoring == false) {
+ appendToLog("CustomIME Debug 3 with runningInventoryRfidTask = " + MainActivity.sharedObjects.runningInventoryRfidTask + ", and mrfidToWriteSize = " + MainActivity.csLibrary4A.mrfidToWriteSize());
+ appendToLog("CustomIME Debug 3 with runningInventoryBarcodeTask = " + MainActivity.sharedObjects.runningInventoryBarcodeTask);
+ if (MainActivity.sharedObjects.runningInventoryRfidTask == false && MainActivity.sharedObjects.runningInventoryBarcodeTask == false && MainActivity.csLibrary4A.mrfidToWriteSize() == 0) {
+ startStopHandler();
+ inventoring = true;
+ }
+ } else {
+ appendToLog("CustomIME Debug 4");
+ while (MainActivity.sharedObjects.serviceArrayList.size() != 0) {
+ String strEpc = MainActivity.sharedObjects.serviceArrayList.get(0);
+ MainActivity.sharedObjects.serviceArrayList.remove(0);
+ appendToLog("CustomIME Debug 4A with strEpc = " + strEpc);
+ String strSgtin = null;
+ if (MainActivity.csLibrary4A.getWedgeOutput() == 1) {
+ strSgtin = MainActivity.csLibrary4A.getUpcSerial(strEpc);
+ appendToLog("strSgtin = " + (strSgtin == null ? "null" : strSgtin));
+ if (strSgtin == null) strEpc = null;
+ }
+ boolean matched = false;
+ if (epcArrayList != null && strEpc != null) {
+ for (int i = 0; i < epcArrayList.size(); i++) {
+ if (epcArrayList.get(i).matches(strEpc)) {
+ matched = true;
+ break;
+ }
+ }
+ }
+ if (matched == false && strEpc != null) {
+ epcArrayList.add(strEpc);
+ InputConnection ic = getCurrentInputConnection();
+ String strValue = strEpc;
+ if (strSgtin != null) strValue = strSgtin;
+ if (MainActivity.csLibrary4A.getWedgePrefix() != null)
+ strValue = MainActivity.csLibrary4A.getWedgePrefix() + strValue;
+ if (MainActivity.csLibrary4A.getWedgeSuffix() != null)
+ strValue += MainActivity.csLibrary4A.getWedgeSuffix();
+ appendToLog("CustomIME, serviceRunnable: wedgeDelimiter = " + MainActivity.csLibrary4A.getWedgeDelimiter());
+ switch (MainActivity.csLibrary4A.getWedgeDelimiter()) {
+ default:
+ strValue += "\n";
+ break;
+ case 0x09:
+ strValue += "\t";
+ break;
+ case 0x2C:
+ strValue += ",";
+ break;
+ case 0x20:
+ strValue += " ";
+ break;
+ case -1:
+ break;
+ }
+ appendToLog("CustomIME BtData to Keyboard: " + strValue);
+ ic.commitText(strValue, 1);
+ }
+ }
+ }
+ }
+ }
+ int iDelayms = 500;
+ if (inventoring) iDelayms = 100;
+ appendToLog("CustomIME BtData set next time as " + iDelayms);
+ mHandler.postDelayed(serviceRunnable, iDelayms);
+ }
+ };
+
+ public void appendToLog(String s) {
+ Log.i(TAG + ".Hello", s);
+ }
+ void startStopHandler() {
+ boolean started = false;
+ if (inventoryRfidTask != null) {
+ if (inventoryRfidTask.getStatus() == AsyncTask.Status.RUNNING) started = true;
+ }
+ if (inventoryBarcodeTask != null) {
+ if (inventoryBarcodeTask.getStatus() == AsyncTask.Status.RUNNING) started = true;
+ }
+ appendToLog("CustomIME Debug 10");
+ if ((started && MainActivity.csLibrary4A.getTriggerButtonStatus()) || (started == false && MainActivity.csLibrary4A.getTriggerButtonStatus() == false)) return;
+ if (started == false) {
+ appendToLog("CustomIME Debug 11 with BtData wedgeOutput = " + MainActivity.csLibrary4A.getWedgeOutput());
+ if (MainActivity.csLibrary4A.getWedgeOutput() == 2) {
+ inventoryBarcodeTask = new InventoryBarcodeTask();
+ inventoryBarcodeTask.execute();
+ } else {
+ MainActivity.csLibrary4A.setPowerLevel(MainActivity.csLibrary4A.getWedgePower());
+ MainActivity.csLibrary4A.appendToLog("Debug_Compact: CustomIME.startStopHandler");
+ MainActivity.csLibrary4A.startOperation(RfidReaderChipData.OperationTypes.TAG_INVENTORY_COMPACT);
+ inventoryRfidTask = new InventoryRfidTask();
+ inventoryRfidTask.execute();
+ }
+ } else {
+ appendToLog("CustomIME Debug 11");
+ if (inventoryRfidTask != null) inventoryRfidTask.taskCancelReason = InventoryRfidTask.TaskCancelRReason.BUTTON_RELEASE;
+ if (inventoryBarcodeTask != null) inventoryBarcodeTask.taskCancelReason = InventoryBarcodeTask.TaskCancelRReason.BUTTON_RELEASE;
+ }
+ }
+}
+
+
+
+package com.csl.cs710ademoapp;
+
+import android.content.Context;
+import android.content.res.AssetFileDescriptor;
+import android.media.AudioManager;
+import android.media.MediaPlayer;
+
+import java.io.IOException;
+
+public class CustomMediaPlayer {
+ final boolean DEBUG = false;
+ Context context;
+ MediaPlayer player; boolean starting = false;
+
+ public CustomMediaPlayer(Context context, String file) {
+ this.context = context;
+ player = null;
+ try {
+ AssetFileDescriptor afd = context.getAssets().openFd(file);
+ player = new MediaPlayer();
+ player.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
+ player.prepare();
+ player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
+ @Override
+ public void onCompletion(MediaPlayer mp) {
+ starting = false;
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("MediaPlayer is completed.");
+ }
+ });
+ } catch (IOException e) {
+ MainActivity.csLibrary4A.appendToLog("mp3 setup FAIL");
+ }
+ }
+
+ public void start() {
+ player.start();
+ if (false) starting = true;
+ }
+ public boolean isPlaying() {
+ return (player.isPlaying() | starting) ;
+ }
+ public void pause() {
+ player.pause();
+ }
+ void setVolume(int volume1, int volume2) {
+ if (false) player.setVolume(volume1, volume2);
+ else {
+ AudioManager audioManager = ((AudioManager) context.getSystemService(Context.AUDIO_SERVICE));
+ int iVolumeMax = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
+ int currentVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
+ MainActivity.csLibrary4A.appendToLog("Hello8: currentVolume = " + currentVolume);
+ if (currentVolume > 0) {
+ int volume12 = volume1 + volume2;
+ volume12 = ( volume12 * iVolumeMax ) / 600;
+ audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, iVolumeMax, 0);
+ }
+ }
+ }
+}
+
+
+
+package com.csl.cs710ademoapp;
+
+import android.content.Context;
+import android.view.Gravity;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.Button;
+import android.widget.PopupWindow;
+import android.widget.TextView;
+
+import static android.content.Context.LAYOUT_INFLATER_SERVICE;
+import static com.csl.cs710ademoapp.MainActivity.csLibrary4A;
+
+public class CustomPopupWindow {
+ Context context;
+ public CustomPopupWindow(Context context) {
+ this.context = context;
+ }
+
+ public PopupWindow popupWindow;
+ public void popupStart(String message, boolean wait) {
+ LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(LAYOUT_INFLATER_SERVICE);
+ View popupView = layoutInflater.inflate(R.layout.popup, null);
+ popupWindow = new PopupWindow(popupView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
+ popupWindow.showAtLocation(popupView, Gravity.CENTER, 0, 0);
+ TextView textViewDismiss = (TextView)popupView.findViewById(R.id.dismissMessage);
+ //int iLenghtMax = 300;
+ //if (message.length() > iLenghtMax) message = message.substring(0, iLenghtMax) + " .....";
+ csLibrary4A.appendToLog("SaveList2ExternalTask: popupStart message = " + message);
+ textViewDismiss.setText(message);
+ Button btnDismiss = (Button)popupView.findViewById(R.id.dismiss);
+ if (wait) btnDismiss.setVisibility(View.GONE);
+ else {
+ btnDismiss.setOnClickListener(new Button.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ popupWindow.dismiss();
+ }
+ });
+ }
+ }
+}
+
+
+
+package com.csl.cs710ademoapp;
+
+import android.app.ProgressDialog;
+import android.content.Context;
+
+public class CustomProgressDialog extends ProgressDialog {
+ public CustomProgressDialog(Context context, String message) {
+ super(context, ProgressDialog.STYLE_SPINNER);
+ if (message == null) message = "Progressing. Please wait.";
+ setTitle(null);
+ setMessage(message);
+ setCancelable(false);
+ }
+}
+
+
+
+package com.csl.cs710ademoapp;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Class to hold the data for Navigation Drawer Items
+ */
+public class DrawerListContent {
+ //An array of sample (Settings) items.
+ public static List ITEMS = new ArrayList<>();
+
+ //A map of sample (Settings) items, by ID.
+ public static Map ITEM_MAP = new HashMap<>();
+
+ public enum DrawerPositions {
+ MAIN, SPECIAL,
+ ABOUT, CONNECT,
+ INVENTORY, SEARCH, MULTIBANK,
+ SETTING, FILTER, READWRITE, SECURITY,
+
+ IMPINVENTORY, IMP775, IMPAUTOTUNE,
+ ALIEN,
+ UCODE8, UCODEDNA,
+ BAPCARD, COLDCHAIN, AURASENSE,
+ KILOWAY,
+ LONGJING,
+ AXZON, RFMICRON,
+ FDMICRO,
+ CTESIUS,
+ ASYGNTAG,
+
+ REGISTER, READWRITEUSER, WEDGE, DIRECTWEDGE, SIMINVENTORY,
+ BLANK;
+
+ public static DrawerPositions toDrawerPosition(int x) {
+ switch(x) {
+ case 0: return ABOUT;
+ case 1: return CONNECT;
+ case 2: return INVENTORY;
+ case 3: return SEARCH;
+ case 4: return MULTIBANK;
+ case 5: return SIMINVENTORY;
+ case 6: return SETTING;
+ case 7: return FILTER;
+ case 8: return READWRITE;
+ case 9: return SECURITY;
+
+ case 10: return IMPINVENTORY;
+ case 11: return ALIEN;
+ case 12: return UCODE8;
+ case 13: return UCODEDNA;
+ case 14: return BAPCARD;
+ case 15: return COLDCHAIN;
+ case 16: return AURASENSE;
+ case 17: return KILOWAY;
+ case 18: return LONGJING;
+ case 19: return AXZON;
+ //case 18: return RFMICRON;
+ case 20: return FDMICRO;
+ case 21: return CTESIUS;
+ case 22: return ASYGNTAG;
+
+ case 23: return REGISTER;
+ case 24: return READWRITEUSER;
+ case 25: return WEDGE;
+ case 26: return DIRECTWEDGE;
+ }
+ return null;
+ }
+ }
+
+ static {
+ // Add items.
+ addItem(new DrawerItem("0", "About", R.drawable.dl_about));
+ addItem(new DrawerItem("1", "Connect", R.drawable.dl_rdl));
+ addItem(new DrawerItem("2", "Inventory", R.drawable.dl_inv));
+ addItem(new DrawerItem("3", "Geiger Search", R.drawable.dl_loc));
+ addItem(new DrawerItem("4", "Multi-bank Inventory", R.drawable.dl_inv));
+ addItem(new DrawerItem("5", "Simple Inventory", R.drawable.dl_rr));
+ addItem(new DrawerItem("6", "Settings", R.drawable.dl_sett));
+ addItem(new DrawerItem("7", "Filters", R.drawable.dl_filters));
+ addItem(new DrawerItem("8", "Read/Write", R.drawable.dl_access));
+ addItem(new DrawerItem("9", "Security", R.drawable.dl_access));
+
+ addItem(new DrawerItem("10", "Impinj Special Features", R.drawable.dl_loc));
+ addItem(new DrawerItem("11", "Alien", R.drawable.dl_loc));
+ addItem(new DrawerItem("12", "NXP UCODE 8", R.drawable.dl_loc));
+ addItem(new DrawerItem("13", "NXP UCODE DNA", R.drawable.dl_loc));
+ addItem(new DrawerItem("14", "uEm CS9010 BAP ID Card", R.drawable.dl_loc));
+ addItem(new DrawerItem("15", "uEm Cold Chain CS8300", R.drawable.dl_loc));
+ addItem(new DrawerItem("16", "uEm Aura-sense", R.drawable.dl_loc));
+ addItem(new DrawerItem("17", "Kiloway KX2005X-BL", R.drawable.dl_rr));
+ addItem(new DrawerItem("18", "EL-N2ESL CS6861", R.drawable.dl_rr));
+ addItem(new DrawerItem("19", "Axzon", R.drawable.dl_loc));
+ addItem(new DrawerItem("20", "FM13DT160", R.drawable.dl_loc));
+ addItem(new DrawerItem("21", "Landa CTESIUS", R.drawable.dl_loc));
+ addItem(new DrawerItem("22", "Asygn AS321x", R.drawable.dl_loc));
+
+ addItem(new DrawerItem("23", "Register Tag", R.drawable.dl_rr));
+ addItem(new DrawerItem("24", "Large sized memory read/write", R.drawable.dl_rr));
+ addItem(new DrawerItem("25", "Wedge", R.drawable.dl_rr));
+ addItem(new DrawerItem("26", "Direct Wedge", R.drawable.dl_rr));
+ }
+
+ private static void addItem(DrawerItem item) {
+
+ ITEMS.add(item);
+ ITEM_MAP.put(item.id, item);
+ }
+
+ public static class DrawerItem {
+ public String id;
+ public String content;
+ public int icon;
+
+ public DrawerItem(String id, String content, int icon_id) {
+ this.id = id;
+ this.content = content;
+ this.icon = icon_id;
+ }
+
+ @Override
+ public String toString() {
+ return content;
+ }
+ }
+}
+
+
+
+package com.csl.cs710ademoapp.fragments;
+
+import android.os.Bundle;
+import android.os.Handler;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.TextView;
+
+import androidx.appcompat.app.ActionBar;
+import androidx.appcompat.app.AppCompatActivity;
+
+import com.csl.cs710ademoapp.BuildConfig;
+import com.csl.cs710ademoapp.MainActivity;
+import com.csl.cs710ademoapp.R;
+
+public class AboutFragment extends CommonFragment {
+ Handler mHandler = new Handler();
+ long timeMillis = 0;
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ super.onCreateView(inflater, container, savedInstanceState, true);
+ return inflater.inflate(R.layout.fragment_about, container, false);
+ }
+
+ @Override
+ public void onActivityCreated(Bundle savedInstanceState) {
+ super.onActivityCreated(savedInstanceState);
+
+ ActionBar actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
+ actionBar.setIcon(R.drawable.dl_about);
+ actionBar.setTitle(R.string.title_activity_about);
+
+ TextView appVersionView = (TextView) getActivity().findViewById(R.id.appVersion);
+ appVersionView.setText(BuildConfig.VERSION_NAME);
+ TextView libVersionView = (TextView) getActivity().findViewById(R.id.libVersion);
+ libVersionView.setText(MainActivity.csLibrary4A.getlibraryVersion());
+
+ MainActivity.mSensorConnector.mLocationDevice.turnOn(true);
+ MainActivity.mSensorConnector.mSensorDevice.turnOn(true);
+ mHandler.post(updateRunnable);
+ }
+
+ @Override
+ public void onDestroy() {
+ MainActivity.mSensorConnector.mLocationDevice.turnOn(false);
+ MainActivity.mSensorConnector.mSensorDevice.turnOn(false);
+ mHandler.removeCallbacks(updateRunnable);
+ super.onDestroy();
+ }
+
+ public AboutFragment() {
+ super("AboutFragment");
+ }
+
+ private final Runnable updateRunnable = new Runnable() {
+ @Override
+ public void run() {
+ TextView timeStampView = (TextView) getActivity().findViewById(R.id.timeStamp);
+ TextView locationView = (TextView) getActivity().findViewById(R.id.GeoLocation);
+ TextView eCompassView = (TextView) getActivity().findViewById(R.id.eCompass);
+
+ TextView radioVersion = (TextView) getActivity().findViewById(R.id.radioVersion);
+ TextView modelVersion = (TextView) getActivity().findViewById(R.id.modelVersion);
+ TextView moduleRfidOnStatus = (TextView) getActivity().findViewById(R.id.moduleRfid_onStatus);
+ TextView moduleBarOnStatus = (TextView) getActivity().findViewById(R.id.moduleBar_onStatus);
+ TextView triggerOnStatus = (TextView) getActivity().findViewById(R.id.trigger_onStatus);
+ TextView moduleBattery = (TextView) getActivity().findViewById(R.id.module_battery);
+ TextView moduleVersionLabel = (TextView) getActivity().findViewById(R.id.module_versionLabel);
+ if (MainActivity.csLibrary4A.get98XX() == 2) moduleVersionLabel.setText("Atmel firmware version");
+ else if (MainActivity.csLibrary4A.get98XX() == 0) moduleVersionLabel.setText("SiliconLab firmware version");
+ TextView moduleVersion = (TextView) getActivity().findViewById(R.id.module_version);
+ TextView radioSerial = (TextView) getActivity().findViewById(R.id.radio_serialnumber);
+ TextView radioBoardVersion = (TextView) getActivity().findViewById(R.id.radio_boardVersion);
+ TextView productSerial = (TextView) getActivity().findViewById(R.id.module_productserialnumber);
+ TextView boardVersion = (TextView) getActivity().findViewById(R.id.module_boardversion);
+ TextView barcodeSerial = (TextView) getActivity().findViewById(R.id.moduleBar_serialNumber);
+ TextView barcodeDate = (TextView) getActivity().findViewById(R.id.moduleBar_date);
+ TextView barcodeVersion = (TextView) getActivity().findViewById(R.id.moduleBar_version);
+
+ TextView bluetoothVersion = (TextView) getActivity().findViewById(R.id.bluetooth_version);
+ TextView bluetoothAddress = (TextView) getActivity().findViewById(R.id.bluetooth_address);
+ TextView bluetoothRssi = (TextView) getActivity().findViewById(R.id.bluetooth_rssi);
+
+ timeStampView.setText(MainActivity.mSensorConnector.getTimeStamp());
+ locationView.setText(MainActivity.mSensorConnector.mLocationDevice.getLocation());
+ eCompassView.setText(MainActivity.mSensorConnector.mSensorDevice.getEcompass());
+ if (MainActivity.csLibrary4A.isBleConnected()) {
+ if (System.currentTimeMillis() - timeMillis > 5000) {
+ timeMillis = System.currentTimeMillis();
+ radioVersion.setText(MainActivity.csLibrary4A.getMacVer());
+ modelVersion.setText(MainActivity.csLibrary4A.getModelNumber());
+ moduleVersion.setText(MainActivity.csLibrary4A.hostProcessorICGetFirmwareVersion());
+ bluetoothVersion.setText(MainActivity.csLibrary4A.getBluetoothICFirmwareVersion());
+ MainActivity.csLibrary4A.batteryLevelRequest();
+ }
+ moduleRfidOnStatus.setText(MainActivity.csLibrary4A.getRfidOnStatus() ? "on" : "off");
+ triggerOnStatus.setText(MainActivity.csLibrary4A.getTriggerButtonStatus() ? "pressed" : "released");
+ moduleBarOnStatus.setText(MainActivity.csLibrary4A.getBarcodeOnStatus() ? "on" : "off");
+ moduleBattery.setText(MainActivity.csLibrary4A.getBatteryDisplay(true));
+ if (MainActivity.csLibrary4A.isRfidFailure()) radioSerial.setText("Not available");
+ else radioSerial.setText(MainActivity.csLibrary4A.getRadioSerial());
+ radioBoardVersion.setText(MainActivity.csLibrary4A.getRadioBoardVersion());
+ productSerial.setText(MainActivity.csLibrary4A.getHostProcessorICSerialNumber());
+ boardVersion.setText(MainActivity.csLibrary4A.getHostProcessorICBoardVersion());
+ if (MainActivity.csLibrary4A.isBarcodeFailure()) barcodeSerial.setText("Not available");
+ else {
+ barcodeSerial.setText(MainActivity.csLibrary4A.getBarcodeSerial());
+ barcodeDate.setText(MainActivity.csLibrary4A.getBarcodeDate());
+ barcodeVersion.setText(MainActivity.csLibrary4A.getBarcodeVersion());
+ }
+ bluetoothAddress.setText(MainActivity.csLibrary4A.getBluetoothDeviceAddress());
+ bluetoothRssi.setText(String.valueOf(MainActivity.csLibrary4A.getRssi()));
+ } else {
+ radioVersion.setText("");
+ moduleRfidOnStatus.setText("");
+ moduleBarOnStatus.setText("");
+ triggerOnStatus.setText("");
+ moduleBattery.setText("");
+ moduleVersion.setText("");
+ bluetoothVersion.setText("");
+ radioSerial.setText("");
+ radioBoardVersion.setText("");
+ productSerial.setText("");
+ boardVersion.setText("");
+ barcodeSerial.setText("");
+ bluetoothAddress.setText("");
+ bluetoothRssi.setText("");
+ }
+ mHandler.postDelayed(updateRunnable, 1000);
+ }
+ };
+}
+
+
+
+package com.csl.cs710ademoapp.fragments;
+
+import static com.csl.cs710ademoapp.MainActivity.tagSelected;
+import static com.csl.cslibrary4a.RfidReader.TagType.TAG_EM;
+import static com.csl.cslibrary4a.RfidReader.TagType.TAG_EM_AURASENSE;
+import static com.csl.cslibrary4a.RfidReader.TagType.TAG_EM_AURASENSE_ATBOOT;
+import static com.csl.cslibrary4a.RfidReader.TagType.TAG_EM_AURASENSE_ATSELECT;
+import static com.csl.cslibrary4a.RfidReader.TagType.TAG_EM_BAP;
+import static com.csl.cslibrary4a.RfidReader.TagType.TAG_EM_COLDCHAIN;
+
+import android.app.Activity;
+import android.os.AsyncTask;
+import android.os.Bundle;
+import android.text.InputType;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.AdapterView;
+import android.widget.ArrayAdapter;
+import android.widget.Button;
+import android.widget.CheckBox;
+import android.widget.EditText;
+import android.widget.LinearLayout;
+import android.widget.RadioButton;
+import android.widget.Spinner;
+import android.widget.TableRow;
+import android.widget.TextView;
+import android.widget.Toast;
+
+import com.csl.cs710ademoapp.AccessTask;
+import com.csl.cs710ademoapp.MainActivity;
+import com.csl.cs710ademoapp.R;
+import com.csl.cs710ademoapp.SelectTag;
+import com.csl.cslibrary4a.RfidReaderChipData;
+
+public class AccessAuraSenseFragment extends CommonFragment {
+ final boolean DEBUG = true;
+ Spinner spinnerTagSelect;
+ SelectTag selectTag;
+ RadioButton radioButtonAuraSensAtBoot, radioButtonAuraSensAtSelect;
+ TextView textViewAuraSensorDataOK, textViewAuraSystemConfigurationOK, textViewAuraSensorCalibrationOK, textViewAuraSensorControlOK, textViewAuraSensorDataStoredOK;
+ CheckBox checkBoxAuraSensorDataRCommandW, checkBoxAuraSystemConfiguration, checkBoxAuraCalibration, checkBoxAuraControl, checkBoxAuraDataStored;
+ EditText editTextAuraSensorData, editTextAuraSystemConfiguration, editTextAuraSensorCalibration, editTextAuraSensorDataStored;
+ CheckBox checkBoxAuraSensAtBootCheck, checkBoxAuraSensAtSelectCheck, checkBoxAuraSensWriteCheck;
+ TextView textViewConfigOk, textViewTemperatureOk, textViewEnableOk;
+ CheckBox checkBoxConfig, checkBoxTemperature, checkBoxEnable;
+ TextView textViewTemperature, textViewUnderAlarm, textViewOverAlarm, textViewBatteryAlarm;
+ EditText editTextTempThresUnder, editTextTempThresOver, editTextTempCountUnder, editTextTempCountOver, editTextMonitorDelay, editTextSamplingInterval;
+ Spinner spinnerDelayUnit, spinnerIntervalUnit, spinnerEnable;
+ Spinner spinnerCustomTagType;
+ TextView textViewCustomTagFound;
+ Button buttonCs8304StartLogging, buttonCs8304StopLogging, buttonCs8304CheckAlarm, buttonCs8304GetLogging;
+ TextView textViewCs8304StartLoggingStatus, textViewCs8304StopLoggingStatus, textViewCs8304CheckAlaramStatus, textViewCs8304GetLoggingStatus;
+
+ Button buttonRead, buttonWrite;
+
+ enum ReadWriteTypes {
+ NULL, AURA_SENSORDATARCOMMANDW, AURA_SYSTEMCONFIGURATION, AURA_CALIBRATION, AURA_CONTROL, AURA_DATASTORED,
+ COLDCHAIN_CONFIGURATION, COLDCHAIN_TEMPERATURE, COLDCHAIN_ENABLE,
+ STARTLOGGING, STOPLOGGING, CHECKLOGGING, GETLOGGING
+ }
+
+ enum eMicroTag {
+ emAuraSense, emColdChain, emBap, others
+ }
+ ReadWriteTypes readWriteTypes;
+ boolean operationRead = false;
+ boolean bRequestCheck;
+
+ private AccessTask accessTask;
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ super.onCreateView(inflater, container, savedInstanceState, false);
+ return inflater.inflate(R.layout.fragment_access_aurasense, container, false);
+ }
+
+ @Override
+ public void onActivityCreated(Bundle savedInstanceState) {
+ super.onActivityCreated(savedInstanceState);
+
+ spinnerTagSelect = (Spinner) getActivity().findViewById(R.id.accessEmicroTagSelect);
+ ArrayAdapter targetAdapter1 = ArrayAdapter.createFromResource(getActivity(), R.array.emicro_options, R.layout.custom_spinner_layout);
+ targetAdapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+ spinnerTagSelect.setAdapter(targetAdapter1); spinnerTagSelect.setSelection(0);
+ spinnerTagSelect.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
+ @Override
+ public void onItemSelected(AdapterView> parentView, View selectedItemView, int position, long id) {
+ LinearLayout layout0 = (LinearLayout) getActivity().findViewById(R.id.accessEmicroSelectLayout);
+ LinearLayout layout1 = (LinearLayout) getActivity().findViewById(R.id.accessEmMicroAuroSenseLayout);
+ LinearLayout layout2 = (LinearLayout) getActivity().findViewById(R.id.accessEmMicroColdChainLayout);
+ TableRow tableRow = (TableRow) getActivity().findViewById(R.id.accessEmicroCCTemperature);
+ if (MainActivity.csLibrary4A.get98XX() == 2) tableRow.setVisibility(View.GONE);
+ LinearLayout layout4 = (LinearLayout) getActivity().findViewById(R.id.accessCustomReadWrite);
+ if (position == eMicroTag.emAuraSense.ordinal()) {
+ MainActivity.tagType = TAG_EM_AURASENSE; MainActivity.mDid = "E280B12";
+ layout0.setVisibility(View.VISIBLE);
+ layout1.setVisibility(View.VISIBLE);
+ layout2.setVisibility(View.GONE);
+ layout4.setVisibility(View.VISIBLE);
+ } else if (position == eMicroTag.emColdChain.ordinal()) {
+ MainActivity.tagType = TAG_EM_COLDCHAIN; MainActivity.mDid = "E280B0";
+ layout0.setVisibility(View.VISIBLE);
+ layout1.setVisibility(View.GONE);
+ layout2.setVisibility(View.VISIBLE);
+ layout4.setVisibility(View.VISIBLE);
+ } else if (position == eMicroTag.emBap.ordinal()) {
+ MainActivity.tagType = TAG_EM_BAP; MainActivity.mDid = "E200B0";
+ layout0.setVisibility(View.GONE);
+ layout1.setVisibility(View.GONE);
+ layout2.setVisibility(View.GONE);
+ layout4.setVisibility(View.GONE);
+ } else {
+ MainActivity.tagType = TAG_EM; MainActivity.mDid = "E280B";
+ layout0.setVisibility(View.GONE);
+ layout1.setVisibility(View.GONE);
+ layout2.setVisibility(View.GONE);
+ layout4.setVisibility(View.GONE);
+ }
+ }
+
+ @Override
+ public void onNothingSelected(AdapterView> parentView) {
+ // your code here
+ }
+
+ });
+
+ selectTag = new SelectTag((Activity)getActivity(), 0);
+ selectTag.tableRowSelectMemoryBank.setVisibility(View.GONE);
+
+ radioButtonAuraSensAtBoot = (RadioButton) getActivity().findViewById(R.id.accessAuraSensAtBoot);
+ radioButtonAuraSensAtSelect = (RadioButton) getActivity().findViewById(R.id.accessAuraSensAtSelect);
+
+ textViewAuraSystemConfigurationOK = (TextView) getActivity().findViewById(R.id.accessAuraSystemConfigurationOK);
+ textViewAuraSensorCalibrationOK = (TextView) getActivity().findViewById(R.id.accessAuraSensorCalibrationOK);
+ textViewAuraSensorControlOK = (TextView) getActivity().findViewById(R.id.accessAuraSensorControlOK);
+ textViewAuraSensorDataStoredOK = (TextView) getActivity().findViewById(R.id.accessAuraSensorDataStoredOK);
+
+ checkBoxAuraSystemConfiguration = (CheckBox) getActivity().findViewById(R.id.accessAuraSystemConfigurationCheck);
+ checkBoxAuraCalibration = (CheckBox) getActivity().findViewById(R.id.accessAuraSensorCalibrationCheck);
+ checkBoxAuraControl = (CheckBox) getActivity().findViewById(R.id.accessAuraSensorControlCheck);
+ checkBoxAuraDataStored = (CheckBox) getActivity().findViewById(R.id.accessAuraSensorDataStoredCheck);
+
+ editTextAuraSensorData = (EditText) getActivity().findViewById(R.id.accessAuraSensorData); editTextAuraSensorData.setEnabled(false);
+ editTextAuraSystemConfiguration = (EditText) getActivity().findViewById(R.id.accessAuraSystemConfiguration); editTextAuraSystemConfiguration.setEnabled(false);
+ editTextAuraSensorCalibration = (EditText) getActivity().findViewById(R.id.accessAuraSensorCalibration); editTextAuraSensorCalibration.setInputType(InputType.TYPE_CLASS_NUMBER);
+ editTextAuraSensorDataStored = (EditText) getActivity().findViewById(R.id.accessAuraSensorDataStored); editTextAuraSensorDataStored.setEnabled(false);
+ checkBoxAuraSensAtBootCheck = (CheckBox) getActivity().findViewById(R.id.accessAuraSensAtBootCheck);
+ checkBoxAuraSensAtSelectCheck = (CheckBox) getActivity().findViewById(R.id.accessAuraSensAtSelectCheck);
+ checkBoxAuraSensWriteCheck = (CheckBox) getActivity().findViewById(R.id.accessAuraSensAtWriteCheck);
+
+ textViewConfigOk = (TextView) getActivity().findViewById(R.id.accessCCConfigOK);
+ textViewTemperatureOk = (TextView) getActivity().findViewById(R.id.accessCCTemperatureOK);
+ textViewEnableOk = (TextView) getActivity().findViewById(R.id.accessCCEnableOK);
+
+ checkBoxConfig = (CheckBox) getActivity().findViewById(R.id.accessCCConfigTitle);
+ checkBoxTemperature = (CheckBox) getActivity().findViewById(R.id.accessCCTemperatureTitle);
+ checkBoxEnable = (CheckBox) getActivity().findViewById(R.id.accessCCEnableTitle);
+
+ textViewTemperature = (TextView) getActivity().findViewById(R.id.accessCCTemperature);
+ textViewUnderAlarm = (TextView) getActivity().findViewById(R.id.accessCCUnderTempAlarm);
+ textViewOverAlarm = (TextView) getActivity().findViewById(R.id.accessCCOverTempAlarm);
+ textViewBatteryAlarm = (TextView) getActivity().findViewById(R.id.accessCCBatteryAlarm);
+
+ editTextTempThresUnder = (EditText) getActivity().findViewById(R.id.accessCCTempThresUnder);
+ editTextTempThresOver = (EditText) getActivity().findViewById(R.id.accessCCTempThresOver);
+ editTextTempCountUnder = (EditText) getActivity().findViewById(R.id.accessCCTempCountUnder);
+ editTextTempCountOver = (EditText) getActivity().findViewById(R.id.accessCCTempCountOver);
+ editTextMonitorDelay = (EditText) getActivity().findViewById(R.id.accessCCMonitorDelay);
+ editTextSamplingInterval = (EditText) getActivity().findViewById(R.id.accessCCSamplingInverval);
+
+ ArrayAdapter arrayAdapterUnit = ArrayAdapter.createFromResource(getActivity(), R.array.coldChain_unit_options, R.layout.custom_spinner_layout);
+ arrayAdapterUnit.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+ spinnerDelayUnit = (Spinner) getActivity().findViewById(R.id.accessCCMonitorUnit);
+ spinnerDelayUnit.setAdapter(arrayAdapterUnit);
+
+ ArrayAdapter arrayAdapterUnit1 = ArrayAdapter.createFromResource(getActivity(), R.array.coldChain_IntervalUnit_options, R.layout.custom_spinner_layout);
+ arrayAdapterUnit1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+ spinnerIntervalUnit = (Spinner) getActivity().findViewById(R.id.accessCCSamplingIntervalUnit);
+ spinnerIntervalUnit.setAdapter(arrayAdapterUnit1);
+
+ ArrayAdapter arrayAdapterEnable = ArrayAdapter.createFromResource(getActivity(), R.array.coldChain_enable_options, R.layout.custom_spinner_layout);
+ arrayAdapterEnable.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+ spinnerEnable = (Spinner) getActivity().findViewById(R.id.accessCCEnable);
+ spinnerEnable.setAdapter(arrayAdapterEnable);
+
+ textViewCustomTagFound = (TextView) getActivity().findViewById(R.id.accessCustomTagFound);
+/*
+ ArrayAdapter arrayAdapterTagType = ArrayAdapter.createFromResource(getActivity(), R.array.coldChain_tagtype_options, R.layout.custom_spinner_layout);
+ arrayAdapterTagType.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+ spinnerCustomTagType = (Spinner) getActivity().findViewById(R.id.selectCustomTagType);
+ spinnerCustomTagType.setAdapter(arrayAdapterTagType);
+ spinnerCustomTagType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
+ @Override
+ public void onItemSelected(AdapterView> parentView, View selectedItemView, int position, long id) {
+ switch(position) {
+ case 0:
+ LinearLayout linearLayout = (LinearLayout) getActivity().findViewById(R.id.accessCC8304Layout);
+ linearLayout.setVisibility(View.VISIBLE);
+ linearLayout = (LinearLayout) getActivity().findViewById(R.id.accessCCmaxduraLayout);
+ linearLayout.setVisibility(View.GONE);
+ break;
+ case 1:
+ linearLayout = (LinearLayout) getActivity().findViewById(R.id.accessCC8304Layout);
+ linearLayout.setVisibility(View.GONE);
+ linearLayout = (LinearLayout) getActivity().findViewById(R.id.accessCCmaxduraLayout);
+ linearLayout.setVisibility(View.VISIBLE);
+ break;
+ }
+ }
+
+ @Override
+ public void onNothingSelected(AdapterView> parentView) {
+ // your code here
+ }
+ });
+*/
+ buttonCs8304StartLogging = (Button) getActivity().findViewById(R.id.accessCs8304StartLogging);
+ buttonCs8304StartLogging.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (isOperationRunning()) return;
+ readWriteTypes = ReadWriteTypes.STARTLOGGING;
+ operationRead = true; startAccessTask();
+ }
+ });
+ buttonCs8304StopLogging = (Button) getActivity().findViewById(R.id.accessCs8304StopLogging);
+ buttonCs8304StopLogging.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (isOperationRunning()) return;
+ readWriteTypes = ReadWriteTypes.STOPLOGGING;
+ operationRead = true; startAccessTask();
+ }
+ });
+ buttonCs8304CheckAlarm = (Button) getActivity().findViewById(R.id.accessCs8304CheckAlarm);
+ buttonCs8304CheckAlarm.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (isOperationRunning()) return;
+ readWriteTypes = ReadWriteTypes.CHECKLOGGING;
+ operationRead = true; startAccessTask();
+ }
+ });
+ buttonCs8304GetLogging = (Button) getActivity().findViewById(R.id.accessCs8304GetLogging);
+ buttonCs8304GetLogging.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (isOperationRunning()) return;
+ readWriteTypes = ReadWriteTypes.GETLOGGING;
+ operationRead = true; startAccessTask();
+ }
+ });
+
+ textViewCs8304StartLoggingStatus = (TextView) getActivity().findViewById(R.id.accessCs8304StartLoggingStatus);
+ textViewCs8304StopLoggingStatus = (TextView) getActivity().findViewById(R.id.accessCs8304StopLoggingStatus);
+ textViewCs8304CheckAlaramStatus = (TextView) getActivity().findViewById(R.id.accessCs8304CheckAlarmStatus);
+ textViewCs8304GetLoggingStatus = (TextView) getActivity().findViewById(R.id.accessCs8304GetLoggingStatus);
+
+ buttonRead = (Button) getActivity().findViewById(R.id.accessRWReadButton);
+ buttonRead.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (isOperationRunning()) return;
+ textViewAuraSensorDataOK = (TextView) getActivity().findViewById(R.id.accessAuraSensorDataOK);
+ checkBoxAuraSensorDataRCommandW = (CheckBox) getActivity().findViewById(R.id.accessAuraSensorDataCheck);
+ readWriteTypes = ReadWriteTypes.NULL;
+ operationRead = true; startAccessTask();
+ }
+ });
+
+ buttonWrite = (Button) getActivity().findViewById(R.id.accessRWWriteButton);
+ buttonWrite.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (isOperationRunning()) return;
+ textViewAuraSensorDataOK = (TextView) getActivity().findViewById(R.id.accessAuraWriteSensorDataOK);
+ checkBoxAuraSensorDataRCommandW = (CheckBox) getActivity().findViewById(R.id.accessAuraWriteSensorDataCheck);
+ readWriteTypes = ReadWriteTypes.NULL;
+ operationRead = false; startAccessTask();
+ }
+ });
+
+ MainActivity.csLibrary4A.setSameCheck(false);
+ }
+
+ @Override
+ public void onDestroy() {
+ if (accessTask != null) accessTask.cancel(true);
+ MainActivity.csLibrary4A.setSameCheck(true);
+ super.onDestroy();
+ }
+
+ boolean userVisibleHint = false;
+ @Override
+ public void setUserVisibleHint(boolean isVisibleToUser) {
+ super.setUserVisibleHint(isVisibleToUser);
+ if(getUserVisibleHint()) {
+ if (selectTag != null) selectTag.updateBankSelected();
+ userVisibleHint = true;
+ if (textViewCustomTagFound != null) {
+ if (tagSelected != null) {
+ MainActivity.csLibrary4A.appendToLog("tagSelected = " + tagSelected.getUser());
+ if (tagSelected.getUser() != null && tagSelected.getUser().indexOf("830") == 0) {
+ textViewCustomTagFound.setText("CS" + tagSelected.getUser().substring(0, 4) + "-" + tagSelected.getUser().substring(4, 5));
+ } else textViewCustomTagFound.setText("");
+ }
+ LinearLayout layout = (LinearLayout) getActivity().findViewById(R.id.accessEmicroCS8304Layout);
+ if (textViewCustomTagFound.getText().toString().contains("8304")) {
+ layout.setVisibility(View.VISIBLE);
+ } else layout.setVisibility(View.GONE);
+ }
+ }
+ else {
+ if (spinnerTagSelect != null && spinnerTagSelect.getSelectedItemPosition() == eMicroTag.emAuraSense.ordinal()) {
+ if (radioButtonAuraSensAtBoot != null && radioButtonAuraSensAtSelect != null) {
+ if (radioButtonAuraSensAtBoot.isChecked()) {
+ MainActivity.tagType = TAG_EM_AURASENSE_ATBOOT; MainActivity.mDid = "E280B12A";
+ }
+ if (radioButtonAuraSensAtSelect.isChecked()) {
+ MainActivity.tagType = TAG_EM_AURASENSE_ATSELECT; MainActivity.mDid = "E280B12B";
+ }
+ }
+ }
+ userVisibleHint = false;
+ }
+ }
+
+ public AccessAuraSenseFragment() {
+ super("AccessAuraSenseFragment");
+ }
+
+ boolean isOperationRunning() {
+ if (MainActivity.csLibrary4A.isBleConnected() == false) {
+ Toast.makeText(MainActivity.mContext, R.string.toast_ble_not_connected, Toast.LENGTH_SHORT).show();
+ return true;
+ } else if (MainActivity.csLibrary4A.isRfidFailure()) {
+ Toast.makeText(MainActivity.mContext, "Rfid is disabled", Toast.LENGTH_SHORT).show();
+ return true;
+ } else if (accessTask != null) {
+ if (accessTask.getStatus() == AsyncTask.Status.RUNNING) {
+ Toast.makeText(MainActivity.mContext, "Running acccess task. Please wait", Toast.LENGTH_SHORT).show();
+ return true;
+ }
+ }
+ return false;
+ }
+ void startAccessTask() {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("startAccessTask()");
+ if (updating == false) {
+ updating = true;
+ bankProcessing = 0; checkProcessing = 0;
+ mHandler.removeCallbacks(updateRunnable);
+ mHandler.post(updateRunnable);
+ }
+ }
+ boolean updating = false;
+ int bankProcessing = 0, checkProcessing = 0;
+ private final Runnable updateRunnable = new Runnable() {
+ @Override
+ public void run() {
+ boolean rerunRequest = false; boolean taskRequest = false;
+ if (accessTask == null) {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("AccessAuraSenseFragment().updateRunnable(): NULL accessReadWriteTask");
+ taskRequest = true;
+ } else if (accessTask.getStatus() != AsyncTask.Status.FINISHED) {
+ rerunRequest = true;
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("AccessAuraSenseFragment().updateRunnable(): accessReadWriteTask.getStatus() = " + accessTask.getStatus().toString());
+ } else {
+ taskRequest = true;
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("AccessAuraSenseFragment().updateRunnable(): FINISHED accessReadWriteTask");
+ }
+ if (processResult()) { rerunRequest = true; MainActivity.csLibrary4A.appendToLog("processResult is TRUE");}
+ else if (taskRequest) {
+ boolean invalid = processTickItems();
+ MainActivity.csLibrary4A.appendToLog("processTickItems, invalid = " + invalid);
+ if (bankProcessing++ != 0 && invalid) rerunRequest = false;
+ else {
+ String selectMask = selectTag.editTextTagID.getText().toString();
+ int selectBank = selectTag.spinnerSelectBank.getSelectedItemPosition()+1;
+ int selectOffset = Integer.valueOf(selectTag.editTextSelectOffset.getText().toString());
+ RfidReaderChipData.HostCommands hostCommand;
+ Button buttonAccess;
+ if (readWriteTypes == ReadWriteTypes.COLDCHAIN_TEMPERATURE && operationRead) {
+ hostCommand = RfidReaderChipData.HostCommands.CMD_GETSENSORDATA;
+ buttonAccess = buttonRead;
+ } else if (operationRead) {
+ hostCommand = RfidReaderChipData.HostCommands.CMD_18K6CREAD;
+ buttonAccess = buttonRead;
+ } else {
+ hostCommand = RfidReaderChipData.HostCommands.CMD_18K6CWRITE;
+ buttonAccess = buttonWrite;
+ }
+ MainActivity.csLibrary4A.appendToLog("hostCommand 1 = " + hostCommand.toString());
+ accessTask = new AccessTask(buttonAccess, null, invalid, true,
+ selectMask, selectBank, selectOffset,
+ selectTag.editTextAccessPassword.getText().toString(),
+ Integer.valueOf(selectTag.editTextAccessAntennaPower.getText().toString()),
+ hostCommand,
+ 0, 0, true, false,
+ null, null, null, null, null);
+ accessTask.execute();
+ rerunRequest = true;
+ MainActivity.csLibrary4A.appendToLog("accessTask is created with selectBank = " + selectBank);
+ }
+ }
+ if (rerunRequest) {
+ mHandler.postDelayed(updateRunnable, 500);
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("AccessAuraSenseFragment().updateRunnable(): Restart");
+ } else updating = false;
+ MainActivity.csLibrary4A.appendToLog("AccessAuraSenseFragment().updateRunnable(): Ending with updating = " + updating);
+ }
+ };
+
+ boolean processResult() {
+ String accessResult = null;
+ if (accessTask == null) return false;
+ else if (accessTask.getStatus() != AsyncTask.Status.FINISHED) return false;
+ else {
+ accessResult = accessTask.accessResult;
+ if (DEBUG || true) MainActivity.csLibrary4A.appendToLog("accessResult = " + accessResult);
+ if (readWriteTypes == ReadWriteTypes.STARTLOGGING) textViewCs8304StartLoggingStatus.setText(accessResult);
+ else if (readWriteTypes == ReadWriteTypes.STOPLOGGING) textViewCs8304StopLoggingStatus.setText(accessResult);
+ else if (readWriteTypes == ReadWriteTypes.CHECKLOGGING) textViewCs8304CheckAlaramStatus.setText(accessResult);
+ else if (readWriteTypes == ReadWriteTypes.GETLOGGING) textViewCs8304GetLoggingStatus.setText(accessResult);
+ else if (accessResult == null) {
+ if (readWriteTypes == ReadWriteTypes.AURA_SENSORDATARCOMMANDW) {
+ textViewAuraSensorDataOK.setText("E");
+ //checkBoxUserCode1.setChecked(false);
+ } else if (readWriteTypes == ReadWriteTypes.AURA_SYSTEMCONFIGURATION) {
+ textViewAuraSystemConfigurationOK.setText("E");
+ //checkBoxUserCode2.setChecked(false);
+ } else if (readWriteTypes == ReadWriteTypes.AURA_CALIBRATION) {
+ textViewAuraSensorCalibrationOK.setText("E");
+ //checkBoxUserCode3.setChecked(false);
+ } else if (readWriteTypes == ReadWriteTypes.AURA_CONTROL) {
+ textViewAuraSensorControlOK.setText("E");
+ //checkBoxUserCode4.setChecked(false);
+ } else if (readWriteTypes == ReadWriteTypes.AURA_DATASTORED) {
+ textViewAuraSensorDataStoredOK.setText("E");
+ //checkBoxUserCode5.setChecked(false);
+ } else if (readWriteTypes == ReadWriteTypes.COLDCHAIN_CONFIGURATION) {
+ textViewConfigOk.setText("E"); checkBoxConfig.setChecked(false);
+ } else if (readWriteTypes == ReadWriteTypes.COLDCHAIN_TEMPERATURE && operationRead) {
+ textViewTemperatureOk.setText("E"); checkBoxTemperature.setChecked(false);
+ } else if (readWriteTypes == ReadWriteTypes.COLDCHAIN_ENABLE) {
+ textViewEnableOk.setText("E");
+ checkBoxEnable.setChecked(false);
+ }
+ } else {
+ if (readWriteTypes == ReadWriteTypes.AURA_SENSORDATARCOMMANDW) {
+ textViewAuraSensorDataOK.setText("O");
+ //checkBoxUserCode1.setChecked(false);
+ readWriteTypes = ReadWriteTypes.NULL;
+ if (operationRead) editTextAuraSensorData.setText(showSensorData(accessResult));
+ } else if (readWriteTypes == ReadWriteTypes.AURA_SYSTEMCONFIGURATION) {
+ textViewAuraSystemConfigurationOK.setText("O");
+ //checkBoxUserCode2.setChecked(false);
+ readWriteTypes = ReadWriteTypes.NULL;
+ if (operationRead) editTextAuraSystemConfiguration.setText(accessResult);
+ } else if (readWriteTypes == ReadWriteTypes.AURA_CALIBRATION) {
+ textViewAuraSensorCalibrationOK.setText("O");
+ //checkBoxUserCode3.setChecked(false);
+ readWriteTypes = ReadWriteTypes.NULL;
+ if (operationRead) {
+ int iValue = Integer.parseInt(accessResult, 16);
+ editTextAuraSensorCalibration.setText(String.valueOf(iValue & 0xFF));
+ }
+ } else if (readWriteTypes == ReadWriteTypes.AURA_CONTROL) {
+ textViewAuraSensorControlOK.setText("O");
+ //checkBoxUserCode4.setChecked(false);
+ readWriteTypes = ReadWriteTypes.NULL;
+ if (operationRead) {
+ int iValue = Integer.parseInt(accessResult, 16);
+ if ((iValue & 0x2000) != 0) checkBoxAuraSensAtBootCheck.setChecked(true);
+ if ((iValue & 0x4000) != 0) checkBoxAuraSensAtSelectCheck.setChecked(true);
+ if ((iValue & 0x8000) != 0) checkBoxAuraSensWriteCheck.setChecked(true);
+ }
+ } else if (readWriteTypes == ReadWriteTypes.AURA_DATASTORED) {
+ textViewAuraSensorDataStoredOK.setText("O");
+ //checkBoxUserCode5.setChecked(false);
+ readWriteTypes = ReadWriteTypes.NULL;
+ if (operationRead) editTextAuraSensorDataStored.setText(showSensorData(accessResult));
+ } else if (readWriteTypes == ReadWriteTypes.COLDCHAIN_TEMPERATURE && operationRead == false) {
+ } else if (readWriteTypes == ReadWriteTypes.COLDCHAIN_CONFIGURATION) {
+ textViewConfigOk.setText("O"); checkBoxConfig.setChecked(false); readWriteTypes = ReadWriteTypes.NULL;
+ if (accessResult.length() == 12 && operationRead) { // 43 60 42 FC 04 06
+ byte bValue = Byte.parseByte(accessResult.substring(0, 1), 16);
+ if ((bValue & 8) == 0) {
+ bValue = Byte.parseByte(accessResult.substring(0, 2), 16);
+ bValue &= 0x3F;
+ editTextTempCountUnder.setText(String.valueOf(bValue >> 1));
+ editTextTempThresUnder.setText(getTemperatue(accessResult.substring(1, 4)));
+
+ bValue = Byte.parseByte(accessResult.substring(4, 6), 16);
+ bValue &= 0x3F;
+ editTextTempCountOver.setText(String.valueOf(bValue >> 1));
+ editTextTempThresOver.setText(getTemperatue(accessResult.substring(5, 8)));
+
+ byte bValue2 = Byte.parseByte(accessResult.substring(8, 10), 16);
+ spinnerDelayUnit.setSelection(((bValue2 & 0xFF) >> 6) + 1);
+ editTextMonitorDelay.setText(String.valueOf(bValue2 & 0x3F));
+
+ bValue2 = Byte.parseByte(accessResult.substring(10, 12), 16);
+ spinnerIntervalUnit.setSelection(((bValue2 & 0xFF) >> 6) + 1);
+ editTextSamplingInterval.setText(String.valueOf(bValue2 & 0x3F));
+ }
+ }
+ } else if (readWriteTypes == ReadWriteTypes.COLDCHAIN_TEMPERATURE && operationRead) {
+ textViewTemperatureOk.setText("O"); checkBoxTemperature.setChecked(false); readWriteTypes = ReadWriteTypes.NULL;
+ MainActivity.csLibrary4A.appendToLog("accessResult of Temperature = " + accessResult);
+
+ if (accessResult.length() >= 16) {
+ int indexBegin = accessResult.length() - 16;
+ String stringValue = accessResult.substring(indexBegin, indexBegin + 4);
+ MainActivity.csLibrary4A.appendToLog("temperature part of Temperature accessResult = " + stringValue);
+ accessResult = stringValue;
+ }
+ if (accessResult.length() == 4) {
+ byte bValue = Byte.parseByte(accessResult.substring(0, 1), 16);
+ if ((bValue & 0x8) != 0) textViewBatteryAlarm.setVisibility(View.VISIBLE);
+ else if ((bValue & 0x2) != 0) textViewOverAlarm.setVisibility(View.VISIBLE);
+ else if ((bValue & 01) != 0) textViewUnderAlarm.setVisibility(View.VISIBLE);
+
+ bValue = Byte.parseByte(accessResult.substring(1, 2), 16);
+ Integer iValue2 = Integer.parseInt(accessResult.substring(2, 4), 16);
+ iValue2 &= 0x1FF;
+ if ((bValue & 0x01) != 0 && iValue2 == 0) textViewTemperature.setText("Invalid");
+ else {
+ String stringValue = getTemperatue(accessResult.substring(1, 4));
+ stringValue += (char) 0x00B0 + "C";
+ textViewTemperature.setText(stringValue);
+ }
+ }
+ } else if (readWriteTypes == ReadWriteTypes.COLDCHAIN_ENABLE) {
+ textViewEnableOk.setText("O"); checkBoxEnable.setChecked(false); readWriteTypes = ReadWriteTypes.NULL;
+ if (accessResult.length() == 4 && operationRead) {
+ byte bValue = Byte.parseByte(accessResult.substring(3, 4), 16);
+ if ((bValue & 0x01) != 0) spinnerEnable.setSelection(2);
+ else spinnerEnable.setSelection(1);
+ }
+ }
+ }
+ accessTask = null;
+ return true;
+ }
+ }
+ String showSensorData(String accessResult) {
+ String strValue = "";
+ int iValue = Integer.parseInt(accessResult,16);
+ if ((iValue & 0xFC00) == 0x0C00) {
+ iValue &= 0x3FF;
+ if ((iValue & 0x200) == 0) strValue = String.valueOf(iValue);
+ else {
+ iValue &= 0x1FF;
+ iValue ^= 0x1FF; iValue++; iValue = -iValue;
+ strValue = String.valueOf(iValue);
+ }
+ }
+ return strValue;
+ }
+
+ boolean processTickItems() {
+ boolean invalidRequest1 = false;
+ int accBank = 0, accSize = 0, accOffset = 0;
+ String writeData = "";
+
+ if (selectTag.editTextTagID.getText().toString().length() == 0) invalidRequest1 = true;
+ else if (spinnerTagSelect.getSelectedItemPosition() == eMicroTag.emAuraSense.ordinal()) {
+ if (checkBoxAuraSensorDataRCommandW != null && checkBoxAuraSensorDataRCommandW.isChecked() == true && checkProcessing < 1) {
+ accBank = 1; accSize = 1; accOffset = 0x22; readWriteTypes = ReadWriteTypes.AURA_SENSORDATARCOMMANDW; checkProcessing = 1;
+ if (operationRead) {
+ textViewAuraSensorDataOK.setText("");
+ editTextAuraSensorData.setText("");
+ } else {
+ int iValue = 0;
+ RadioButton radioButtonAuraSens2Null = (RadioButton) getActivity().findViewById(R.id.accessAuraSens2Null);
+ RadioButton radioButtonAuraSens2Store = (RadioButton) getActivity().findViewById(R.id.accessAuraSens2Store);
+ RadioButton radioButtonAuraSens2Calibration = (RadioButton) getActivity().findViewById(R.id.accessAuraSens2Calibration);
+
+ if (radioButtonAuraSens2Null.isChecked()) iValue = 0x8001;
+ else if (radioButtonAuraSens2Store.isChecked()) iValue = 0x1000;
+ else if (radioButtonAuraSens2Calibration.isChecked()) iValue = 0x2000;
+ writeData = String.format("%04X", iValue);
+ MainActivity.csLibrary4A.appendToLog("WriteData = " + writeData);
+ }
+ } else if (checkBoxAuraSystemConfiguration != null && checkBoxAuraSystemConfiguration.isChecked() == true && checkProcessing < 2 && operationRead) {
+ accBank = 3; accSize = 1; accOffset = 0x120; readWriteTypes = ReadWriteTypes.AURA_SYSTEMCONFIGURATION; checkProcessing = 2;
+ if (operationRead) {
+ textViewAuraSystemConfigurationOK.setText("");
+ editTextAuraSystemConfiguration.setText("");
+ }
+ } else if (checkBoxAuraCalibration != null && checkBoxAuraCalibration.isChecked() == true && checkProcessing < 3) {
+ accBank = 3; accSize = 1; accOffset = 0x122; readWriteTypes = ReadWriteTypes.AURA_CALIBRATION; checkProcessing = 3;
+ if (operationRead) {
+ textViewAuraSensorCalibrationOK.setText("");
+ editTextAuraSensorCalibration.setText("");
+ } else {
+ String strValue = editTextAuraSensorCalibration.getText().toString();
+ Integer iValue = Integer.valueOf(strValue);
+ iValue &= 0xFF;
+ writeData = String.format("%04X", iValue);
+ }
+ } else if (checkBoxAuraControl != null && checkBoxAuraControl.isChecked() == true && checkProcessing < 4) {
+ accBank = 3; accSize = 1; accOffset = 0x123; readWriteTypes = ReadWriteTypes.AURA_CONTROL; checkProcessing = 4;
+ if (operationRead) {
+ textViewAuraSensorControlOK.setText("");
+ checkBoxAuraSensAtBootCheck.setChecked(false); checkBoxAuraSensAtSelectCheck.setChecked(false); checkBoxAuraSensWriteCheck.setChecked(false);
+ } else {
+ int iValue = (checkBoxAuraSensAtBootCheck.isChecked() ? 0x2000 : 0) | (checkBoxAuraSensAtSelectCheck.isChecked() ? 0x4000 : 0) | (checkBoxAuraSensWriteCheck.isChecked() ? 0x8000 : 0);
+ writeData = String.format("%04X", iValue);
+ }
+ } else if (checkBoxAuraDataStored != null && checkBoxAuraDataStored.isChecked() == true && checkProcessing < 5 && operationRead) {
+ accBank = 3;
+ accSize = 1;
+ accOffset = 0x124;
+ readWriteTypes = ReadWriteTypes.AURA_DATASTORED;
+ checkProcessing = 5;
+ if (operationRead) {
+ textViewAuraSensorDataStoredOK.setText("");
+ editTextAuraSensorDataStored.setText("");
+ }
+ } else {
+ invalidRequest1 = true;
+ }
+ } else if (spinnerTagSelect.getSelectedItemPosition() == eMicroTag.emColdChain.ordinal()) {
+ accBank = 3;
+ if (bRequestCheck) {
+ readWriteTypes = ReadWriteTypes.COLDCHAIN_TEMPERATURE;
+ if (bankProcessing == 0) {
+ if (operationRead) {
+ textViewTemperature.setText("");
+ accOffset = 0x10D;
+ accSize = 1;
+ writeData = "0000";
+ } else invalidRequest1 = true;
+ } else {
+ operationRead = true;
+ MainActivity.csLibrary4A.macWrite(0x11F, 3);
+ return false;
+ }
+ } else if (checkBoxConfig.isChecked() == true) {
+ accOffset = 0xEC; accSize = 3; readWriteTypes = ReadWriteTypes.COLDCHAIN_CONFIGURATION; textViewConfigOk.setText("");
+ if (operationRead) {
+ editTextTempThresUnder.setText("");
+ editTextTempThresOver.setText("");
+ editTextTempCountUnder.setText("");
+ editTextTempCountOver.setText("");
+ editTextMonitorDelay.setText("");
+ editTextSamplingInterval.setText("");
+ spinnerDelayUnit.setSelection(0);
+ spinnerIntervalUnit.setSelection(0);
+ } else {
+ try {
+ int underTempCount, underTempThreshold, overTempCount, overTempThreshold;
+ byte tempBytes[] = new byte[6];
+
+ tempBytes[0] = 0x40;
+ tempBytes[0] |= (Byte.parseByte(editTextTempCountUnder.getText().toString()) << 1);
+ float fValue = Float.parseFloat(editTextTempThresUnder.getText().toString());
+ short sValue = setTemperature(fValue);
+ if ((sValue & (short)0x100) != 0) tempBytes[0] |= 1;
+ tempBytes[1] = (byte)sValue;
+
+ tempBytes[2] = 0;
+ tempBytes[2] |= (Byte.parseByte(editTextTempCountOver.getText().toString()) << 1);
+ fValue = Float.parseFloat(editTextTempThresOver.getText().toString());
+ sValue = setTemperature(fValue);
+ if ((sValue & (short)0x100) != 0) tempBytes[2] |= 1;
+ tempBytes[3] = (byte)sValue;
+
+ int iTemp = spinnerDelayUnit.getSelectedItemPosition();
+ if (iTemp < 1) iTemp = 1;
+ else if (iTemp > 4) iTemp = 4;
+ iTemp--;
+ tempBytes[4] = (byte)iTemp; tempBytes[4] <<= 6;
+ byte bValue = Byte.parseByte(editTextMonitorDelay.getText().toString());
+ tempBytes[4] |= (bValue & 0x3F);
+
+ iTemp = spinnerIntervalUnit.getSelectedItemPosition();
+ if (iTemp < 1) iTemp = 1;
+ else if (iTemp > 4) iTemp = 4;
+ iTemp--;
+ tempBytes[5] = (byte)iTemp; tempBytes[5] <<= 6;
+ bValue = Byte.parseByte(editTextSamplingInterval.getText().toString());
+ tempBytes[5] |= (bValue & 0x3F);
+
+ writeData = MainActivity.csLibrary4A.byteArrayToString(tempBytes);
+ MainActivity.csLibrary4A.appendToLog("editTextTempCountUnder = " + MainActivity.csLibrary4A.byteArrayToString(tempBytes));
+ } catch (Exception ex) {
+ MainActivity.csLibrary4A.appendToLog("Invalid String.parse !!!");
+ invalidRequest1 = true;
+ }
+ }
+ } else if (checkBoxTemperature.isChecked() == true) {
+ readWriteTypes = ReadWriteTypes.COLDCHAIN_TEMPERATURE;
+ if (bankProcessing == 0) {
+ if (operationRead) {
+ textViewTemperature = (TextView) getActivity().findViewById(R.id.accessCCTemperature);
+ textViewTemperature.setText("");
+ textViewUnderAlarm = (TextView) getActivity().findViewById(R.id.accessCCUnderTempAlarm);
+ textViewUnderAlarm.setVisibility(View.INVISIBLE);
+ textViewOverAlarm = (TextView) getActivity().findViewById(R.id.accessCCOverTempAlarm);
+ textViewOverAlarm.setVisibility(View.INVISIBLE);
+ textViewBatteryAlarm = (TextView) getActivity().findViewById(R.id.accessCCBatteryAlarm);
+ textViewBatteryAlarm.setVisibility(View.INVISIBLE);
+ textViewTemperatureOk.setText("");
+ if (true) {
+ MainActivity.csLibrary4A.macWrite(0x11F, 3);
+ return false;
+ }
+ accOffset = 0x100;
+ accSize = 1;
+ operationRead = false;
+ } else invalidRequest1 = true;
+ } else {
+ accOffset = 0x100;
+ accSize = 1;
+ operationRead = true;
+ }
+ } else if (checkBoxEnable.isChecked() == true) {
+ accOffset = 0x10D;
+ accSize = 1;
+ readWriteTypes = ReadWriteTypes.COLDCHAIN_ENABLE;
+ textViewEnableOk.setText("");
+ if (operationRead) spinnerEnable.setSelection(0);
+ else {
+ int iSelect = spinnerEnable.getSelectedItemPosition();
+ if (iSelect == 0) invalidRequest1 = true;
+ else if (iSelect == 1) writeData = "0000";
+ else writeData = "0001";
+ String stringValue = "0000";
+ }
+ } else if (readWriteTypes == ReadWriteTypes.STARTLOGGING || readWriteTypes == ReadWriteTypes.STOPLOGGING || readWriteTypes == ReadWriteTypes.CHECKLOGGING || readWriteTypes == ReadWriteTypes.GETLOGGING) {
+ MainActivity.csLibrary4A.appendToLog("accessResult 1 bankProcewssing = " + bankProcessing );
+ accOffset = 0xF0; accSize = 1; operationRead = true;
+ if (readWriteTypes == ReadWriteTypes.STARTLOGGING) {
+ switch(bankProcessing) {
+ case 0:
+ textViewCs8304StartLoggingStatus.setText("");
+ break;
+ case 1:
+ long seconds = System.currentTimeMillis() / (long)1000;
+ int interval = 10;
+ float temperatureOffset = 10; //range 20 to 0 represents -20 to 0 degreeC
+ accOffset = 0; accSize = 4; writeData = "";
+
+ writeData += String.format("%08X", seconds);
+ writeData += String.format("%04X", interval);
+ float fTemp = temperatureOffset / (float) 0.25;
+ short sTemp = (short) fTemp;
+ writeData += String.format("%04X", sTemp);
+ operationRead = false;
+ MainActivity.csLibrary4A.appendToLog("accessResult: UTC seconds = " + seconds + ", writedata = " + writeData);
+ break;
+ case 2:
+ float overTemperature = 20;
+ float underTemperature = -10;
+ accOffset = 0x106; accSize = 3; writeData = "";
+
+ fTemp = overTemperature / (float) 0.25;
+ sTemp = (short) fTemp;
+ writeData += String.format("%04X", sTemp);
+ fTemp = underTemperature / (float) 0.25;
+ sTemp = (short) fTemp;
+ writeData += String.format("%04X", sTemp);
+ writeData += "0000"; //clear Alarm status
+ operationRead = false;
+ MainActivity.csLibrary4A.appendToLog("accessResult: temperature alarm: writeData = " + writeData);
+ break;
+ case 3:
+ accOffset = 0x104; accSize = 1; writeData = "0001";
+ operationRead = false;
+ MainActivity.csLibrary4A.appendToLog("accessResult: status: writeData = " + writeData);
+ break;
+ case 4:
+ accOffset = 0xF0; accSize = 1; writeData = "A000";
+ operationRead = false;
+ MainActivity.csLibrary4A.appendToLog("accessResult: control: writeData = " + writeData);
+ break;
+ default:
+ invalidRequest1 = true; readWriteTypes = ReadWriteTypes.NULL;
+ break;
+ }
+ } else if (readWriteTypes == ReadWriteTypes.STOPLOGGING) {
+ switch(bankProcessing) {
+ case 0:
+ textViewCs8304StartLoggingStatus.setText("");
+ break;
+ case 1:
+ accOffset = 0x104; accSize = 1; writeData = "0002";
+ operationRead = false;
+ MainActivity.csLibrary4A.appendToLog("accessResult: status: writeData = " + writeData);
+ break;
+ case 2:
+ case 3:
+ accOffset = 0xF0; accSize = 1; writeData = "A600";
+ operationRead = false;
+ MainActivity.csLibrary4A.appendToLog("accessResult: control: writeData = " + writeData);
+ break;
+ default:
+ invalidRequest1 = true; readWriteTypes = ReadWriteTypes.NULL;
+ break;
+ }
+ } else if (readWriteTypes == ReadWriteTypes.CHECKLOGGING) {
+ switch(bankProcessing) {
+ case 0:
+ textViewCs8304StartLoggingStatus.setText("");
+ break;
+ case 1:
+ accOffset = 0x108; accSize = 1; writeData = "";
+ operationRead = true;
+ break;
+ case 2:
+ int iValue = 0;
+ try {
+ iValue = Integer.parseInt(textViewCs8304CheckAlaramStatus.getText().toString(), 16);
+ } catch (Exception ex) { }
+ if ((iValue & 2) != 0) {
+ accOffset = 0x108; accSize = 1; writeData = "";
+ iValue &= 0x3; iValue |= 1;
+ writeData = String.format("%04X", iValue);
+ operationRead = false;
+ MainActivity.csLibrary4A.appendToLog("accessResult: writeData = " + writeData);
+ break;
+ }
+ default:
+ invalidRequest1 = true; readWriteTypes = ReadWriteTypes.NULL;
+ break;
+ }
+ } else if (readWriteTypes == ReadWriteTypes.GETLOGGING) {
+ switch(bankProcessing) {
+ case 0:
+ textViewCs8304GetLoggingStatus.setText("");
+ break;
+ default:
+ invalidRequest1 = true; readWriteTypes = ReadWriteTypes.NULL;
+ break;
+ }
+ }
+ } else {
+ invalidRequest1 = true;
+ }
+ } else {
+ invalidRequest1 = true;
+ }
+
+ if (invalidRequest1 == false) {
+ if (MainActivity.csLibrary4A.setAccessBank(accBank) == false) {
+ invalidRequest1 = true;
+ }
+ }
+ if (invalidRequest1 == false) {
+ if (MainActivity.csLibrary4A.setAccessOffset(accOffset) == false) {
+ invalidRequest1 = true;
+ }
+ }
+ if (invalidRequest1 == false) {
+ if (accSize == 0) {
+ invalidRequest1 = true;
+ } else if (MainActivity.csLibrary4A.setAccessCount(accSize) == false) {
+ invalidRequest1 = true;
+ }
+ }
+ if (invalidRequest1 == false && operationRead == false) {
+ if (invalidRequest1 == false) {
+ if (MainActivity.csLibrary4A.setAccessWriteData(writeData) == false) {
+ invalidRequest1 = true;
+ }
+ }
+ }
+ MainActivity.csLibrary4A.appendToLog("found invalidRequest1 = " + invalidRequest1);
+ return invalidRequest1;
+ }
+
+ short setTemperature(float fTemperature) {
+ if (fTemperature > 63.75) fTemperature = (float) 63.75;
+ else if (fTemperature < -64) fTemperature = -64;
+ boolean bNegative = false;
+ if (fTemperature < 0) { bNegative = true; fTemperature = 0 - fTemperature; }
+ fTemperature += 0.125; fTemperature /= 0.25;
+ short retValue = (short)fTemperature;
+ if (bNegative) { retValue--; retValue &= 0xFF; retValue ^= 0xFF; retValue |= 0x100; }
+ return retValue;
+ }
+ String getTemperatue(String stringInput) {
+ byte bValue = Byte.parseByte(stringInput.substring(0,1), 16);
+ byte bValue2 = Byte.parseByte(stringInput.substring(1, 2), 16); bValue2 <<= 4;
+ byte bValue3 = Byte.parseByte(stringInput.substring(2, 3), 16); bValue2 |= bValue3;
+ String stringValue = ""; short sValue = (short)(bValue2 & 0xFF);
+ if ((bValue & 0x01) != 0) { stringValue = "-"; bValue2 ^= 0xFF; sValue = (short)(bValue2 & 0xFF); sValue++; }
+ stringValue += String.valueOf((sValue & 0x1FF) >> 2);
+ switch (sValue & 0x03) {
+ case 1:
+ stringValue += ".25";
+ break;
+ case 2:
+ stringValue += ".50";
+ break;
+ case 3:
+ stringValue += ".75";
+ break;
+ }
+ return stringValue;
+ }
+}
+
+
+
+package com.csl.cs710ademoapp.fragments;
+
+import android.os.AsyncTask;
+import android.os.Bundle;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.AdapterView;
+import android.widget.ArrayAdapter;
+import android.widget.Button;
+import android.widget.CheckBox;
+import android.widget.EditText;
+import android.widget.LinearLayout;
+import android.widget.Spinner;
+import android.widget.TextView;
+import android.widget.Toast;
+
+import com.csl.cs710ademoapp.AccessTask;
+import com.csl.cs710ademoapp.GenericTextWatcher;
+import com.csl.cs710ademoapp.MainActivity;
+import com.csl.cs710ademoapp.R;
+import com.csl.cslibrary4a.ReaderDevice;
+import com.csl.cslibrary4a.RfidReaderChipData;
+
+public class AccessColdChainFragment extends CommonFragment {
+ final boolean DEBUG = true;
+ EditText editTextRWTagID, editTextAccessRWAccPassword, editTextaccessRWAntennaPower;
+ TextView textViewConfigOk, textViewTemperatureOk, textViewEnableOk;
+ CheckBox checkBoxConfig, checkBoxTemperature, checkBoxEnable;
+
+ EditText editTextTempThresUnder, editTextTempThresOver, editTextTempCountUnder, editTextTempCountOver, editTextMonitorDelay, editTextSamplingInterval;
+ TextView textViewTemperature, textViewUnderAlarm, textViewOverAlarm, textViewBatteryAlarm;
+ Spinner spinnerDelayUnit, spinnerIntervalUnit, spinnerEnable, spinnerTagType;
+ Button buttonRead, buttonWrite, buttonStartLogging, buttonStopLogging, buttonCheckAlarm, buttonGetLogging;
+ TextView textViewStartLoggingStatus, textViewStopLoggingStatus, textViewCheckAlaramStatus, textViewGetLoggingStatus;
+
+ enum ReadWriteTypes {
+ NULL, TEMPERATURE, CONFIGURATION, ENABLE,
+ STARTLOGGING, STOPLOGGING, CHECKLOGGING, GETLOGGING
+ }
+ boolean operationRead = false;
+ ReadWriteTypes readWriteTypes;
+
+ private AccessTask accessTask;
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ super.onCreateView(inflater, container, savedInstanceState, false);
+ return inflater.inflate(R.layout.fragment_access_coldchain, container, false);
+ }
+
+ @Override
+ public void onActivityCreated(Bundle savedInstanceState) {
+ super.onActivityCreated(savedInstanceState);
+
+ editTextRWTagID = (EditText) getActivity().findViewById(R.id.accessCCTagID);
+ editTextAccessRWAccPassword = (EditText) getActivity().findViewById(R.id.accessCCAccPasswordValue);
+ editTextAccessRWAccPassword.addTextChangedListener(new GenericTextWatcher(editTextAccessRWAccPassword, 8));
+ editTextAccessRWAccPassword.setText("00000000");
+
+ textViewConfigOk = (TextView) getActivity().findViewById(R.id.accessCCConfigOK);
+ textViewTemperatureOk = (TextView) getActivity().findViewById(R.id.accessCCTemperatureOK);
+ textViewEnableOk = (TextView) getActivity().findViewById(R.id.accessCCEnableOK);
+ checkBoxConfig = (CheckBox) getActivity().findViewById(R.id.accessCCConfigTitle);
+ checkBoxTemperature = (CheckBox) getActivity().findViewById(R.id.accessCCTemperatureTitle);
+ checkBoxEnable = (CheckBox) getActivity().findViewById(R.id.accessCCEnableTitle);
+
+ textViewTemperature = (TextView) getActivity().findViewById(R.id.accessCCTemperature);
+ textViewUnderAlarm = (TextView) getActivity().findViewById(R.id.accessCCUnderTempAlarm);
+ textViewOverAlarm = (TextView) getActivity().findViewById(R.id.accessCCOverTempAlarm);
+ textViewBatteryAlarm = (TextView) getActivity().findViewById(R.id.accessCCBatteryAlarm);
+
+ editTextTempThresUnder = (EditText) getActivity().findViewById(R.id.accessCCTempThresUnder);
+ editTextTempThresOver = (EditText) getActivity().findViewById(R.id.accessCCTempThresOver);
+ editTextTempCountUnder = (EditText) getActivity().findViewById(R.id.accessCCTempCountUnder);
+ editTextTempCountOver = (EditText) getActivity().findViewById(R.id.accessCCTempCountOver);
+ editTextMonitorDelay = (EditText) getActivity().findViewById(R.id.accessCCMonitorDelay);
+ editTextSamplingInterval = (EditText) getActivity().findViewById(R.id.accessCCSamplingInverval);
+
+ TextView textViewDegreeC = (TextView) getActivity().findViewById(R.id.accessCCDegreeC);
+ textViewDegreeC.setText(textViewDegreeC.getText().toString() + (char) 0x00B0 + "C)");
+
+ ArrayAdapter arrayAdapterUnit = ArrayAdapter.createFromResource(getActivity(), R.array.coldChain_unit_options, R.layout.custom_spinner_layout);
+ arrayAdapterUnit.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+ spinnerDelayUnit = (Spinner) getActivity().findViewById(R.id.accessCCMonitorUnit);
+ spinnerDelayUnit.setAdapter(arrayAdapterUnit);
+
+ ArrayAdapter arrayAdapterUnit1 = ArrayAdapter.createFromResource(getActivity(), R.array.coldChain_IntervalUnit_options, R.layout.custom_spinner_layout);
+ arrayAdapterUnit1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+ spinnerIntervalUnit = (Spinner) getActivity().findViewById(R.id.accessCCSamplingIntervalUnit);
+ spinnerIntervalUnit.setAdapter(arrayAdapterUnit1);
+
+ ArrayAdapter arrayAdapterEnable = ArrayAdapter.createFromResource(getActivity(), R.array.coldChain_enable_options, R.layout.custom_spinner_layout);
+ arrayAdapterEnable.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+ spinnerEnable = (Spinner) getActivity().findViewById(R.id.accessCCEnable);
+ spinnerEnable.setAdapter(arrayAdapterEnable);
+
+ ArrayAdapter arrayAdapterTagType = ArrayAdapter.createFromResource(getActivity(), R.array.coldChain_tagtype_options, R.layout.custom_spinner_layout);
+ arrayAdapterTagType.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+ spinnerTagType = (Spinner) getActivity().findViewById(R.id.selectCCTagType);
+ spinnerTagType.setAdapter(arrayAdapterTagType);
+ spinnerTagType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
+ @Override
+ public void onItemSelected(AdapterView> parentView, View selectedItemView, int position, long id) {
+ switch(position) {
+ case 0:
+ LinearLayout linearLayout = (LinearLayout) getActivity().findViewById(R.id.accessCC8304Layout);
+ linearLayout.setVisibility(View.VISIBLE);
+ linearLayout = (LinearLayout) getActivity().findViewById(R.id.accessCCmaxduraLayout);
+ linearLayout.setVisibility(View.GONE);
+ break;
+ case 1:
+ linearLayout = (LinearLayout) getActivity().findViewById(R.id.accessCC8304Layout);
+ linearLayout.setVisibility(View.GONE);
+ linearLayout = (LinearLayout) getActivity().findViewById(R.id.accessCCmaxduraLayout);
+ linearLayout.setVisibility(View.VISIBLE);
+ break;
+ }
+ }
+
+ @Override
+ public void onNothingSelected(AdapterView> parentView) {
+ // your code here
+ }
+ });
+
+ editTextaccessRWAntennaPower = (EditText) getActivity().findViewById(R.id.accessCCAntennaPower);
+ editTextaccessRWAntennaPower.setText(String.valueOf(300));
+
+ buttonStartLogging = (Button) getActivity().findViewById(R.id.accessCCStartLogging);
+ buttonStartLogging.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (isOperationRunning()) return;
+ readWriteTypes = ReadWriteTypes.STARTLOGGING;
+ operationRead = true; startAccessTask();
+ }
+ });
+ buttonStopLogging = (Button) getActivity().findViewById(R.id.accessCCStopLogging);
+ buttonStopLogging.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (isOperationRunning()) return;
+ readWriteTypes = ReadWriteTypes.STOPLOGGING;
+ operationRead = true; startAccessTask();
+ }
+ });
+ buttonCheckAlarm = (Button) getActivity().findViewById(R.id.accessCCcheckAlarm);
+ buttonCheckAlarm.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (isOperationRunning()) return;
+ readWriteTypes = ReadWriteTypes.CHECKLOGGING;
+ operationRead = true; startAccessTask();
+ }
+ });
+ buttonGetLogging = (Button) getActivity().findViewById(R.id.accessCCGetLogging);
+ buttonGetLogging.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (isOperationRunning()) return;
+ readWriteTypes = ReadWriteTypes.GETLOGGING;
+ operationRead = true; startAccessTask();
+ }
+ });
+
+ textViewStartLoggingStatus = (TextView) getActivity().findViewById(R.id.accessCCStartLoggingStatus);
+ textViewStopLoggingStatus = (TextView) getActivity().findViewById(R.id.accessCCStopLoggingStatus);
+ textViewCheckAlaramStatus = (TextView) getActivity().findViewById(R.id.accessCCcheckAlarmStatus);
+ textViewGetLoggingStatus = (TextView) getActivity().findViewById(R.id.accessCCGetLoggingStatus);
+
+ buttonRead = (Button) getActivity().findViewById(R.id.accessCCReadButton);
+ buttonRead.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (isOperationRunning()) return;
+ readWriteTypes = ReadWriteTypes.NULL;
+ operationRead = true; startAccessTask();
+ }
+ });
+
+ buttonWrite = (Button) getActivity().findViewById(R.id.accessCCWriteButton);
+ buttonWrite.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (isOperationRunning()) return;
+ readWriteTypes = ReadWriteTypes.NULL;
+ operationRead = false; startAccessTask();
+ }
+ });
+
+ setupTagID();
+ MainActivity.csLibrary4A.setSameCheck(false);
+ }
+
+ @Override
+ public void onDestroy() {
+ if (accessTask != null) accessTask.cancel(true);
+ MainActivity.csLibrary4A.setSameCheck(true);
+ MainActivity.csLibrary4A.restoreAfterTagSelect();
+ super.onDestroy();
+ }
+
+ boolean userVisibleHint = false;
+ @Override
+ public void setUserVisibleHint(boolean isVisibleToUser) {
+ super.setUserVisibleHint(isVisibleToUser);
+ if(getUserVisibleHint()) {
+ userVisibleHint = true;
+ MainActivity.csLibrary4A.appendToLog("AccessColdChainFragment is now VISIBLE");
+ setupTagID();
+ // setNotificationListener();
+ } else {
+ userVisibleHint = false;
+ MainActivity.csLibrary4A.appendToLog("AccessColdChainFragment is now INVISIBLE");
+// MainActivity.mCs108Library4a.setNotificationListener(null);
+ }
+ }
+
+ public AccessColdChainFragment() {
+ super("AccessColdChainFragment");
+ }
+
+ void setupTagID() {
+ ReaderDevice tagSelected = MainActivity.tagSelected;
+ boolean bSelected = false;
+ if (tagSelected != null) {
+ if (tagSelected.getSelected() == true) {
+ bSelected = true;
+ if (editTextRWTagID != null) editTextRWTagID.setText(tagSelected.getAddress());
+
+ String stringDetail = tagSelected.getDetails();
+ int indexUser = stringDetail.indexOf("USER=");
+ if (indexUser != -1) {
+ String stringUser = stringDetail.substring(indexUser + 5);
+ MainActivity.csLibrary4A.appendToLog("stringUser = " + stringUser);
+
+ boolean bEnableBAPMode = false;
+ int number = Integer.valueOf(stringUser.substring(3, 4), 16);
+ if ((number % 2) == 1) bEnableBAPMode = true;
+// CheckBox checkBoxBAP = (CheckBox) getActivity().findViewById(R.id.coldChainEnableBAP);
+// checkBoxBAP.setChecked(bEnableBAPMode);
+ }
+ }
+ }
+ }
+
+ boolean isOperationRunning() {
+ if (MainActivity.csLibrary4A.isBleConnected() == false) {
+ Toast.makeText(MainActivity.mContext, R.string.toast_ble_not_connected, Toast.LENGTH_SHORT).show();
+ return true;
+ } else if (MainActivity.csLibrary4A.isRfidFailure()) {
+ Toast.makeText(MainActivity.mContext, "Rfid is disabled", Toast.LENGTH_SHORT).show();
+ return true;
+ } else if (accessTask != null) {
+ if (accessTask.getStatus() == AsyncTask.Status.RUNNING) {
+ Toast.makeText(MainActivity.mContext, "Running acccess task. Please wait", Toast.LENGTH_SHORT).show();
+ return true;
+ }
+ }
+ return false;
+ }
+
+ void startAccessTask() {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("startAccessTask()");
+ if (updating == false) {
+ updating = true; bankProcessing = 0;
+ mHandler.removeCallbacks(updateRunnable);
+ mHandler.post(updateRunnable);
+ }
+ }
+ boolean updating = false; int bankProcessing = 0;
+ private final Runnable updateRunnable = new Runnable() {
+ @Override
+ public void run() {
+ boolean rerunRequest = false; boolean taskRequest = false;
+ if (accessTask == null) {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("AccessColdChainFragment().updateRunnable(): NULL accessReadWriteTask");
+ taskRequest = true;
+ } else if (accessTask.getStatus() != AsyncTask.Status.FINISHED) {
+ rerunRequest = true;
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("AccessColdChainFragment().updateRunnable(): accessReadWriteTask.getStatus() = " + accessTask.getStatus().toString());
+ } else {
+ taskRequest = true;
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("AccessColdChainFragment().updateRunnable(): FINISHED accessReadWriteTask");
+ }
+ if (processResult()) { rerunRequest = true; MainActivity.csLibrary4A.appendToLog("processResult is TRUE");}
+ else if (taskRequest) {
+ boolean invalid = processTickItems();
+ MainActivity.csLibrary4A.appendToLog("processTickItems, invalid = " + invalid);
+ if (bankProcessing++ != 0 && invalid) rerunRequest = false;
+ else {
+ RfidReaderChipData.HostCommands hostCommand;
+ if (readWriteTypes == ReadWriteTypes.TEMPERATURE) hostCommand = RfidReaderChipData.HostCommands.CMD_GETSENSORDATA;
+ else if (operationRead) hostCommand = RfidReaderChipData.HostCommands.CMD_18K6CREAD;
+ else hostCommand = RfidReaderChipData.HostCommands.CMD_18K6CWRITE;
+ accessTask = new AccessTask((operationRead ? buttonRead : buttonWrite), null, invalid, true,
+ editTextRWTagID.getText().toString(), 1, 32,
+ editTextAccessRWAccPassword.getText().toString(),
+ Integer.valueOf(editTextaccessRWAntennaPower.getText().toString()),
+ hostCommand,
+ 0, 0, true, false,
+ null, null, null, null, null);
+ accessTask.execute();
+ rerunRequest = true;
+ MainActivity.csLibrary4A.appendToLog("accessTask is created");
+ }
+ }
+ if (rerunRequest) {
+ mHandler.postDelayed(updateRunnable, 500);
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("AccessColdChainFragment().updateRunnable(): Restart");
+ }
+ else updating = false;
+ MainActivity.csLibrary4A.appendToLog("AccessColdChainFragment().updateRunnable(): Ending with updating = " + updating);
+ }
+ };
+
+ short setTemperature(float fTemperature) {
+ if (fTemperature > 63.75) fTemperature = (float) 63.75;
+ else if (fTemperature < -64) fTemperature = -64;
+ boolean bNegative = false;
+ if (fTemperature < 0) { bNegative = true; fTemperature = 0 - fTemperature; }
+ fTemperature += 0.125; fTemperature /= 0.25;
+ short retValue = (short)fTemperature;
+ if (bNegative) { retValue--; retValue &= 0xFF; retValue ^= 0xFF; retValue |= 0x100; }
+ return retValue;
+ }
+ String getTemperatue(String stringInput) {
+ byte bValue = Byte.parseByte(stringInput.substring(0,1), 16);
+ byte bValue2 = Byte.parseByte(stringInput.substring(1, 2), 16); bValue2 <<= 4;
+ byte bValue3 = Byte.parseByte(stringInput.substring(2, 3), 16); bValue2 |= bValue3;
+ String stringValue = ""; short sValue = (short)(bValue2 & 0xFF);
+ if ((bValue & 0x01) != 0) { stringValue = "-"; bValue2 ^= 0xFF; sValue = (short)(bValue2 & 0xFF); sValue++; }
+ stringValue += String.valueOf((sValue & 0x1FF) >> 2);
+ switch (sValue & 0x03) {
+ case 1:
+ stringValue += ".25";
+ break;
+ case 2:
+ stringValue += ".50";
+ break;
+ case 3:
+ stringValue += ".75";
+ break;
+ }
+ return stringValue;
+ }
+
+ // int accessBank, accSize, accOffset;
+// int restartCounter = 0; int restartAccessBank = -1;
+ boolean processResult() {
+ String accessResult = null;
+ if (accessTask == null) return false;
+ else if (accessTask.getStatus() != AsyncTask.Status.FINISHED) return false;
+ else {
+ accessResult = accessTask.accessResult;
+ MainActivity.csLibrary4A.appendToLog("accessResult 2 bankProcewssing = " + bankProcessing + ", accessResult = " + accessTask.accessResult );
+ if (readWriteTypes == ReadWriteTypes.STARTLOGGING) textViewStartLoggingStatus.setText(accessResult);
+ else if (readWriteTypes == ReadWriteTypes.STOPLOGGING) textViewStopLoggingStatus.setText(accessResult);
+ else if (readWriteTypes == ReadWriteTypes.CHECKLOGGING) textViewCheckAlaramStatus.setText(accessResult);
+ else if (readWriteTypes == ReadWriteTypes.GETLOGGING) textViewGetLoggingStatus.setText(accessResult);
+ else if (accessResult == null) {
+ if (readWriteTypes == ReadWriteTypes.CONFIGURATION) {
+ textViewConfigOk.setText("E"); checkBoxConfig.setChecked(false);
+ } else if (readWriteTypes == ReadWriteTypes.TEMPERATURE && operationRead) {
+ textViewTemperatureOk.setText("E"); checkBoxTemperature.setChecked(false);
+ } else if (readWriteTypes == ReadWriteTypes.ENABLE) {
+ textViewEnableOk.setText("E"); checkBoxEnable.setChecked(false);
+ }
+ } else {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("accessResult = " + accessResult);
+ if (readWriteTypes == ReadWriteTypes.CONFIGURATION) {
+ textViewConfigOk.setText("O"); checkBoxConfig.setChecked(false); readWriteTypes = ReadWriteTypes.NULL;
+ if (accessResult.length() == 12 && operationRead) { // 43 60 42 FC 04 06
+ byte bValue = Byte.parseByte(accessResult.substring(0, 1), 16);
+ if ((bValue & 8) == 0) {
+ bValue = Byte.parseByte(accessResult.substring(0, 2), 16);
+ bValue &= 0x3F;
+ editTextTempCountUnder.setText(String.valueOf(bValue >> 1));
+ editTextTempThresUnder.setText(getTemperatue(accessResult.substring(1, 4)));
+
+ bValue = Byte.parseByte(accessResult.substring(4, 6), 16);
+ bValue &= 0x3F;
+ editTextTempCountOver.setText(String.valueOf(bValue >> 1));
+ editTextTempThresOver.setText(getTemperatue(accessResult.substring(5, 8)));
+
+ byte bValue2 = Byte.parseByte(accessResult.substring(8, 10), 16);
+ spinnerDelayUnit.setSelection(((bValue2 & 0xFF) >> 6) + 1);
+ editTextMonitorDelay.setText(String.valueOf(bValue2 & 0x3F));
+
+ bValue2 = Byte.parseByte(accessResult.substring(10, 12), 16);
+ spinnerIntervalUnit.setSelection(((bValue2 & 0xFF) >> 6) + 1);
+ editTextSamplingInterval.setText(String.valueOf(bValue2 & 0x3F));
+ }
+ }
+ } else if (readWriteTypes == ReadWriteTypes.TEMPERATURE && operationRead) {
+ textViewTemperatureOk.setText("O"); checkBoxTemperature.setChecked(false); readWriteTypes = ReadWriteTypes.NULL;
+ MainActivity.csLibrary4A.appendToLog("accessResult of Temperature = " + accessResult);
+
+ if (accessResult.length() >= 16) {
+ int indexBegin = accessResult.length() - 16;
+ String stringValue = accessResult.substring(indexBegin, indexBegin + 4);
+ MainActivity.csLibrary4A.appendToLog("temperature part of Temperature accessResult = " + stringValue);
+ accessResult = stringValue;
+ }
+ if (accessResult.length() == 4) {
+ byte bValue = Byte.parseByte(accessResult.substring(0, 1), 16);
+ if ((bValue & 0x8) != 0) textViewBatteryAlarm.setVisibility(View.VISIBLE);
+ else if ((bValue & 0x2) != 0) textViewOverAlarm.setVisibility(View.VISIBLE);
+ else if ((bValue & 01) != 0) textViewUnderAlarm.setVisibility(View.VISIBLE);
+
+ bValue = Byte.parseByte(accessResult.substring(1, 2), 16);
+ Integer iValue2 = Integer.parseInt(accessResult.substring(2, 4), 16);
+ iValue2 &= 0x1FF;
+ if ((bValue & 0x01) != 0 && iValue2 == 0) textViewTemperature.setText("Invalid");
+ else {
+ String stringValue = getTemperatue(accessResult.substring(1, 4));
+ stringValue += (char) 0x00B0 + "C";
+ textViewTemperature.setText(stringValue);
+ }
+ }
+ } else if (readWriteTypes == ReadWriteTypes.ENABLE) {
+ textViewEnableOk.setText("O"); checkBoxEnable.setChecked(false); readWriteTypes = ReadWriteTypes.NULL;
+ if (accessResult.length() == 4 && operationRead) {
+ byte bValue = Byte.parseByte(accessResult.substring(3, 4), 16);
+ if ((bValue & 0x01) != 0) spinnerEnable.setSelection(2);
+ else spinnerEnable.setSelection(1);
+ }
+ }
+ }
+ accessTask = null;
+ return true;
+ }
+ }
+ boolean processTickItems() {
+ boolean invalidRequest1 = false;
+ int accSize = 0, accOffset = 0;
+ String writeData = "";
+
+ if (readWriteTypes == ReadWriteTypes.STARTLOGGING || readWriteTypes == ReadWriteTypes.STOPLOGGING || readWriteTypes == ReadWriteTypes.CHECKLOGGING || readWriteTypes == ReadWriteTypes.GETLOGGING) {
+ MainActivity.csLibrary4A.appendToLog("accessResult 1 bankProcewssing = " + bankProcessing );
+ accOffset = 0xF0; accSize = 1; operationRead = true;
+ if (readWriteTypes == ReadWriteTypes.STARTLOGGING) {
+ switch(bankProcessing) {
+ case 0:
+ textViewStartLoggingStatus.setText("");
+ break;
+ case 1:
+ long seconds = System.currentTimeMillis() / (long)1000;
+ int interval = 10;
+ float temperatureOffset = 10; //range 20 to 0 represents -20 to 0 degreeC
+ accOffset = 0; accSize = 4; writeData = "";
+
+ writeData += String.format("%08X", seconds);
+ writeData += String.format("%04X", interval);
+ float fTemp = temperatureOffset / (float) 0.25;
+ short sTemp = (short) fTemp;
+ writeData += String.format("%04X", sTemp);
+ operationRead = false;
+ MainActivity.csLibrary4A.appendToLog("accessResult: UTC seconds = " + seconds + ", writedata = " + writeData);
+ break;
+ case 2:
+ float overTemperature = 20;
+ float underTemperature = -10;
+ accOffset = 0x106; accSize = 3; writeData = "";
+
+ fTemp = overTemperature / (float) 0.25;
+ sTemp = (short) fTemp;
+ writeData += String.format("%04X", sTemp);
+ fTemp = underTemperature / (float) 0.25;
+ sTemp = (short) fTemp;
+ writeData += String.format("%04X", sTemp);
+ writeData += "0000"; //clear Alarm status
+ operationRead = false;
+ MainActivity.csLibrary4A.appendToLog("accessResult: temperature alarm: writeData = " + writeData);
+ break;
+ case 3:
+ accOffset = 0x104; accSize = 1; writeData = "0001";
+ operationRead = false;
+ MainActivity.csLibrary4A.appendToLog("accessResult: status: writeData = " + writeData);
+ break;
+ case 4:
+ accOffset = 0xF0; accSize = 1; writeData = "A000";
+ operationRead = false;
+ MainActivity.csLibrary4A.appendToLog("accessResult: control: writeData = " + writeData);
+ break;
+ default:
+ invalidRequest1 = true; readWriteTypes = ReadWriteTypes.NULL;
+ break;
+ }
+ } else if (readWriteTypes == ReadWriteTypes.STOPLOGGING) {
+ switch(bankProcessing) {
+ case 0:
+ textViewStartLoggingStatus.setText("");
+ break;
+ case 1:
+ accOffset = 0x104; accSize = 1; writeData = "0002";
+ operationRead = false;
+ MainActivity.csLibrary4A.appendToLog("accessResult: status: writeData = " + writeData);
+ break;
+ case 2:
+ case 3:
+ accOffset = 0xF0; accSize = 1; writeData = "A600";
+ operationRead = false;
+ MainActivity.csLibrary4A.appendToLog("accessResult: control: writeData = " + writeData);
+ break;
+ default:
+ invalidRequest1 = true; readWriteTypes = ReadWriteTypes.NULL;
+ break;
+ }
+ } else if (readWriteTypes == ReadWriteTypes.CHECKLOGGING) {
+ switch(bankProcessing) {
+ case 0:
+ textViewStartLoggingStatus.setText("");
+ break;
+ case 1:
+ accOffset = 0x108; accSize = 1; writeData = "";
+ operationRead = true;
+ break;
+ case 2:
+ int iValue = 0;
+ try {
+ iValue = Integer.parseInt(textViewCheckAlaramStatus.getText().toString(), 16);
+ } catch (Exception ex) { }
+ if ((iValue & 2) != 0) {
+ accOffset = 0x108; accSize = 1; writeData = "";
+ iValue &= 0x3; iValue |= 1;
+ writeData = String.format("%04X", iValue);
+ operationRead = false;
+ MainActivity.csLibrary4A.appendToLog("accessResult: writeData = " + writeData);
+ break;
+ }
+ default:
+ invalidRequest1 = true; readWriteTypes = ReadWriteTypes.NULL;
+ break;
+ }
+ } else if (readWriteTypes == ReadWriteTypes.GETLOGGING) {
+ switch(bankProcessing) {
+ case 0:
+ textViewGetLoggingStatus.setText("");
+ break;
+ default:
+ invalidRequest1 = true; readWriteTypes = ReadWriteTypes.NULL;
+ break;
+ }
+ }
+ } else if (checkBoxConfig.isChecked() == true) {
+ accOffset = 0xEC; accSize = 3; readWriteTypes = ReadWriteTypes.CONFIGURATION; textViewConfigOk.setText("");
+ if (operationRead) {
+ editTextTempThresUnder.setText("");
+ editTextTempThresOver.setText("");
+ editTextTempCountUnder.setText("");
+ editTextTempCountOver.setText("");
+ editTextMonitorDelay.setText("");
+ editTextSamplingInterval.setText("");
+ spinnerDelayUnit.setSelection(0);
+ spinnerIntervalUnit.setSelection(0);
+ } else {
+ try {
+ int underTempCount, underTempThreshold, overTempCount, overTempThreshold;
+ byte tempBytes[] = new byte[6];
+
+ tempBytes[0] = 0x40;
+ tempBytes[0] |= (Byte.parseByte(editTextTempCountUnder.getText().toString()) << 1);
+ float fValue = Float.parseFloat(editTextTempThresUnder.getText().toString());
+ short sValue = setTemperature(fValue);
+ if ((sValue & (short)0x100) != 0) tempBytes[0] |= 1;
+ tempBytes[1] = (byte)sValue;
+
+ tempBytes[2] = 0;
+ tempBytes[2] |= (Byte.parseByte(editTextTempCountOver.getText().toString()) << 1);
+ fValue = Float.parseFloat(editTextTempThresOver.getText().toString());
+ sValue = setTemperature(fValue);
+ if ((sValue & (short)0x100) != 0) tempBytes[2] |= 1;
+ tempBytes[3] = (byte)sValue;
+
+ int iTemp = spinnerDelayUnit.getSelectedItemPosition();
+ if (iTemp < 1) iTemp = 1;
+ else if (iTemp > 4) iTemp = 4;
+ iTemp--;
+ tempBytes[4] = (byte)iTemp; tempBytes[4] <<= 6;
+ byte bValue = Byte.parseByte(editTextMonitorDelay.getText().toString());
+ tempBytes[4] |= (bValue & 0x3F);
+
+ iTemp = spinnerIntervalUnit.getSelectedItemPosition();
+ if (iTemp < 1) iTemp = 1;
+ else if (iTemp > 4) iTemp = 4;
+ iTemp--;
+ tempBytes[5] = (byte)iTemp; tempBytes[5] <<= 6;
+ bValue = Byte.parseByte(editTextSamplingInterval.getText().toString());
+ tempBytes[5] |= (bValue & 0x3F);
+
+ writeData = MainActivity.csLibrary4A.byteArrayToString(tempBytes);
+ MainActivity.csLibrary4A.appendToLog("editTextTempCountUnder = " + MainActivity.csLibrary4A.byteArrayToString(tempBytes));
+ } catch (Exception ex) {
+ MainActivity.csLibrary4A.appendToLog("Invalid String.parse !!!");
+ invalidRequest1 = true;
+ }
+ }
+ } else if (checkBoxTemperature.isChecked() == true) {
+ readWriteTypes = ReadWriteTypes.TEMPERATURE;
+ if (bankProcessing == 0) {
+ if (operationRead) {
+ textViewTemperature = (TextView) getActivity().findViewById(R.id.accessCCTemperature);
+ textViewTemperature.setText("");
+ textViewUnderAlarm = (TextView) getActivity().findViewById(R.id.accessCCUnderTempAlarm);
+ textViewUnderAlarm.setVisibility(View.INVISIBLE);
+ textViewOverAlarm = (TextView) getActivity().findViewById(R.id.accessCCOverTempAlarm);
+ textViewOverAlarm.setVisibility(View.INVISIBLE);
+ textViewBatteryAlarm = (TextView) getActivity().findViewById(R.id.accessCCBatteryAlarm);
+ textViewBatteryAlarm.setVisibility(View.INVISIBLE);
+ textViewTemperatureOk.setText("");
+ if (true) {
+ MainActivity.csLibrary4A.macWrite(0x11F, 3);
+ return false;
+ }
+ accOffset = 0x100; accSize = 1; operationRead = false;
+ } else invalidRequest1 = true;
+ } else {
+ accOffset = 0x100; accSize = 1; operationRead = true;
+ }
+ } else if (checkBoxEnable.isChecked() == true) {
+ accOffset = 0x10D; accSize = 1; readWriteTypes = ReadWriteTypes.ENABLE; textViewEnableOk.setText("");
+ if (operationRead) spinnerEnable.setSelection(0);
+ else {
+ int iSelect = spinnerEnable.getSelectedItemPosition();
+ if (iSelect == 0) invalidRequest1 = true;
+ else if (iSelect == 1) writeData = "0000";
+ else writeData = "0001";
+ String stringValue = "0000";
+ }
+ } else {
+ invalidRequest1 = true;
+ }
+
+ if (invalidRequest1 == false) {
+ if (MainActivity.csLibrary4A.setAccessBank(3) == false) {
+ invalidRequest1 = true;
+ }
+ }
+ if (invalidRequest1 == false) {
+ if (MainActivity.csLibrary4A.setAccessOffset(accOffset) == false) {
+ invalidRequest1 = true;
+ }
+ }
+ if (invalidRequest1 == false) {
+ if (accSize == 0) {
+ invalidRequest1 = true;
+ } else if (MainActivity.csLibrary4A.setAccessCount(accSize) == false) {
+ invalidRequest1 = true;
+ }
+ }
+ if (invalidRequest1 == false && operationRead == false) {
+ if (invalidRequest1 == false) {
+ if (MainActivity.csLibrary4A.setAccessWriteData(writeData) == false) {
+ invalidRequest1 = true;
+ }
+ }
+ }
+ return invalidRequest1;
+ }
+}
+
+
+
+package com.csl.cs710ademoapp.fragments;
+
+import android.os.Bundle;
+import androidx.fragment.app.Fragment;
+import androidx.fragment.app.FragmentManager;
+import androidx.fragment.app.FragmentTransaction;
+import androidx.appcompat.app.ActionBar;
+import androidx.appcompat.app.AppCompatActivity;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.Button;
+import android.widget.EditText;
+import android.widget.TextView;
+
+import com.csl.cs710ademoapp.MainActivity;
+import com.csl.cs710ademoapp.R;
+
+public class AccessConfigFragment extends CommonFragment {
+ boolean bXerxesEnable = false;
+ EditText editTextPassWord, editTextPower, editText0, editText1, editText2;
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ super.onCreateView(inflater, container, savedInstanceState, false);
+ return inflater.inflate(R.layout.fragment_access_config, container, false);
+ }
+
+ @Override
+ public void onActivityCreated(Bundle savedInstanceState) {
+ super.onActivityCreated(savedInstanceState);
+
+ if (((AppCompatActivity) getActivity()).getSupportActionBar() != null) {
+ ActionBar actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
+ actionBar.setTitle(R.string.title_activity_axzonConfig);
+ }
+
+ editTextPassWord = (EditText) getActivity().findViewById(R.id.accessConfigPasswordValue);
+ editTextPassWord.setText("00000000");
+ editTextPower = (EditText) getActivity().findViewById(R.id.accessConfigAntennaPower);
+ editTextPower.setText("300");
+
+ TextView textView0 = (TextView) getActivity().findViewById(R.id.accessConfigData0Label);
+ textView0.setText("select hold(ms)");
+ editText0 = (EditText) getActivity().findViewById(R.id.accessConfigData0);
+
+ if (MainActivity.mDid == null) editText0.setText("0");
+ else if (MainActivity.mDid.indexOf("E282405") == 0) editText0.setText("9");
+ else if (MainActivity.mDid.indexOf("E282403") == 0) editText0.setText("3");
+ else editText0.setText("0");
+
+ TextView textView1 = (TextView) getActivity().findViewById(R.id.accessConfigData1Label);
+ textView1.setText("Upper Limit of On Chip RSSI");
+ editText1 = (EditText) getActivity().findViewById(R.id.accessConfigData1);
+ editText1.setText("21");
+
+ TextView textView2 = (TextView) getActivity().findViewById(R.id.accessConfigData2Label);
+ textView2.setText("Lower Limit On Chip RSSI");
+ editText2 = (EditText) getActivity().findViewById(R.id.accessConfigData2);
+ editText2.setText("13");
+
+ Button button = (Button) getActivity().findViewById(R.id.accessConfigOKButton);
+ button.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ MainActivity.config.configPassword = editTextPassWord.getText().toString();
+ MainActivity.config.configPower = editTextPower.getText().toString();
+ MainActivity.config.config0 = editText0.getText().toString();
+ MainActivity.config.config1 = editText1.getText().toString();
+ MainActivity.config.config2 = editText2.getText().toString();
+
+ if (MainActivity.mDid != null) if (MainActivity.mDid.indexOf("E282405") == 0) bXerxesEnable = true;
+
+ Fragment fragment;
+ if (bXerxesEnable) fragment = new AxzonFragment();
+ else fragment = new MicronFragment();
+
+ FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
+ FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
+ fragmentTransaction.replace(R.id.content_frame, fragment);
+ fragmentTransaction.addToBackStack(null);
+ fragmentTransaction.commit();
+ }
+ });
+ }
+
+ public static AccessConfigFragment newInstance(boolean bXerxesEnable) {
+ AccessConfigFragment myFragment = new AccessConfigFragment();
+ myFragment.bXerxesEnable = bXerxesEnable;
+ return myFragment;
+ }
+ public AccessConfigFragment() {
+ super("AccessConfigFragment");
+ }
+}
+
+
+
+package com.csl.cs710ademoapp.fragments;
+
+import android.os.AsyncTask;
+import android.os.Bundle;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.Button;
+import android.widget.EditText;
+import android.widget.TextView;
+import android.widget.Toast;
+
+import com.csl.cs710ademoapp.AccessTask;
+import com.csl.cs710ademoapp.GenericTextWatcher;
+import com.csl.cs710ademoapp.MainActivity;
+import com.csl.cs710ademoapp.R;
+import com.csl.cslibrary4a.ReaderDevice;
+import com.csl.cslibrary4a.RfidReaderChipData;
+
+public class AccessEm4325PassiveFragment extends CommonFragment {
+ final boolean DEBUG = true;
+ EditText editTextRWTagID, editTextAccessRWAccPassword, editTextaccessRWAntennaPower;
+
+ TextView textViewTemperature;
+ Button buttonRead;
+
+ enum ReadWriteTypes {
+ NULL, TEMPERATURE
+ }
+ boolean operationRead = false;
+ ReadWriteTypes readWriteTypes;
+
+ private AccessTask accessTask;
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ super.onCreateView(inflater, container, savedInstanceState, false);
+ return inflater.inflate(R.layout.fragment_access_em4325passive, container, false);
+ }
+
+ @Override
+ public void onActivityCreated(Bundle savedInstanceState) {
+ super.onActivityCreated(savedInstanceState);
+
+ editTextRWTagID = (EditText) getActivity().findViewById(R.id.accessCCPTagID);
+ editTextAccessRWAccPassword = (EditText) getActivity().findViewById(R.id.accessCCPAccPasswordValue);
+ editTextAccessRWAccPassword.addTextChangedListener(new GenericTextWatcher(editTextAccessRWAccPassword, 8));
+ editTextAccessRWAccPassword.setText("00000000");
+
+ textViewTemperature = (TextView) getActivity().findViewById(R.id.accessCCPTemperature);
+
+ editTextaccessRWAntennaPower = (EditText) getActivity().findViewById(R.id.accessCCPAntennaPower);
+ editTextaccessRWAntennaPower.setText(String.valueOf(300));
+
+ buttonRead = (Button) getActivity().findViewById(R.id.accessCCPReadButton);
+ buttonRead.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (isOperationRunning()) return;
+ readWriteTypes = ReadWriteTypes.NULL;
+ bRequestCheck = true;
+ operationRead = true; startAccessTask();
+ }
+ });
+
+ setupTagID();
+ MainActivity.csLibrary4A.setSameCheck(false);
+ }
+
+ @Override
+ public void onDestroy() {
+ if (accessTask != null) accessTask.cancel(true);
+ MainActivity.csLibrary4A.setSameCheck(true);
+ MainActivity.csLibrary4A.restoreAfterTagSelect();
+ super.onDestroy();
+ }
+
+ boolean userVisibleHint = false;
+ @Override
+ public void setUserVisibleHint(boolean isVisibleToUser) {
+ super.setUserVisibleHint(isVisibleToUser);
+ if(getUserVisibleHint()) {
+ userVisibleHint = true;
+ MainActivity.csLibrary4A.appendToLog("AccessEm4325PassiveFragment is now VISIBLE");
+ setupTagID();
+ // setNotificationListener();
+ } else {
+ userVisibleHint = false;
+ MainActivity.csLibrary4A.appendToLog("AccessEm4325PassiveFragment is now INVISIBLE");
+// MainActivity.mCs108Library4a.setNotificationListener(null);
+ }
+ }
+
+ public AccessEm4325PassiveFragment() {
+ super("AccessEm4325PassiveFragment");
+ }
+
+ void setupTagID() {
+ ReaderDevice tagSelected = MainActivity.tagSelected;
+ if (tagSelected != null) {
+ if (tagSelected.getSelected() == true) {
+ if (editTextRWTagID != null) editTextRWTagID.setText(tagSelected.getAddress());
+ }
+ }
+ }
+
+ boolean isOperationRunning() {
+ if (MainActivity.csLibrary4A.isBleConnected() == false) {
+ Toast.makeText(MainActivity.mContext, R.string.toast_ble_not_connected, Toast.LENGTH_SHORT).show();
+ return true;
+ } else if (MainActivity.csLibrary4A.isRfidFailure()) {
+ Toast.makeText(MainActivity.mContext, "Rfid is disabled", Toast.LENGTH_SHORT).show();
+ return true;
+ } else if (accessTask != null) {
+ if (accessTask.getStatus() == AsyncTask.Status.RUNNING) {
+ Toast.makeText(MainActivity.mContext, "Running acccess task. Please wait", Toast.LENGTH_SHORT).show();
+ return true;
+ }
+ }
+ return false;
+ }
+
+ void startAccessTask() {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("startAccessTask()");
+ if (updating == false) {
+ updating = true; bankProcessing = 0;
+ mHandler.removeCallbacks(updateRunnable);
+ mHandler.post(updateRunnable);
+ }
+ }
+ boolean updating = false; int bankProcessing = 0;
+ private final Runnable updateRunnable = new Runnable() {
+ @Override
+ public void run() {
+ boolean rerunRequest = false; boolean taskRequest = false;
+ if (accessTask == null) {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("AccessEm4325PassiveFragment().updateRunnable(): NULL accessReadWriteTask");
+ taskRequest = true;
+ } else if (accessTask.getStatus() != AsyncTask.Status.FINISHED) {
+ rerunRequest = true;
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("AccessEm4325PassiveFragment().updateRunnable(): accessReadWriteTask.getStatus() = " + accessTask.getStatus().toString());
+ } else {
+ taskRequest = true;
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("AccessEm4325PassiveFragment().updateRunnable(): FINISHED accessReadWriteTask");
+ }
+ if (processResult()) { rerunRequest = true; MainActivity.csLibrary4A.appendToLog("updateRunnable: processResult is TRUE with bankprocessing = " + bankProcessing);}
+ else if (taskRequest) {
+ boolean invalid = processTickItems();
+ MainActivity.csLibrary4A.appendToLog("updateRunnable: processTickItems Result = " + invalid + ", bankprocessing = " + bankProcessing);
+ if (bankProcessing++ != 0 && invalid) rerunRequest = false;
+ else {
+ RfidReaderChipData.HostCommands hostCommand;
+ if (readWriteTypes == ReadWriteTypes.TEMPERATURE && operationRead) hostCommand = RfidReaderChipData.HostCommands.CMD_GETSENSORDATA;
+ else if (operationRead) hostCommand = RfidReaderChipData.HostCommands.CMD_18K6CREAD;
+ else hostCommand = RfidReaderChipData.HostCommands.CMD_18K6CWRITE;
+ MainActivity.csLibrary4A.appendToLog("hostCommand = " + hostCommand.toString());
+ accessTask = new AccessTask(buttonRead, null, invalid, true,
+ editTextRWTagID.getText().toString(), 1, 32,
+ editTextAccessRWAccPassword.getText().toString(),
+ Integer.valueOf(editTextaccessRWAntennaPower.getText().toString()),
+ hostCommand,
+ 0, 0, true, false,
+ null, null, null, null, null);
+ accessTask.execute();
+ rerunRequest = true;
+ MainActivity.csLibrary4A.appendToLog("accessTask is created");
+ }
+ }
+ if (rerunRequest) {
+ mHandler.postDelayed(updateRunnable, 500);
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("AccessEm4325PassiveFragment().updateRunnable(): Restart");
+ }
+ else updating = false;
+ MainActivity.csLibrary4A.appendToLog("AccessEm4325PassiveFragment().updateRunnable(): Ending with updating = " + updating);
+ }
+ };
+
+ short setTemperature(float fTemperature) {
+ if (fTemperature > 63.75) fTemperature = (float) 63.75;
+ else if (fTemperature < -64) fTemperature = -64;
+ boolean bNegative = false;
+ if (fTemperature < 0) { bNegative = true; fTemperature = 0 - fTemperature; }
+ fTemperature += 0.125; fTemperature /= 0.25;
+ short retValue = (short)fTemperature;
+ if (bNegative) { retValue--; retValue &= 0xFF; retValue ^= 0xFF; retValue |= 0x100; }
+ return retValue;
+ }
+ String getTemperatue(String stringInput) {
+ byte bValue = Byte.parseByte(stringInput.substring(0,1), 16);
+ byte bValue2 = Byte.parseByte(stringInput.substring(1, 2), 16); bValue2 <<= 4;
+ byte bValue3 = Byte.parseByte(stringInput.substring(2, 3), 16); bValue2 |= bValue3;
+ String stringValue = ""; short sValue = (short)(bValue2 & 0xFF);
+ if ((bValue & 0x01) != 0) { stringValue = "-"; bValue2 ^= 0xFF; sValue = (short)(bValue2 & 0xFF); sValue++; }
+ stringValue += String.valueOf((sValue & 0x1FF) >> 2);
+ switch (sValue & 0x03) {
+ case 1:
+ stringValue += ".25";
+ break;
+ case 2:
+ stringValue += ".50";
+ break;
+ case 3:
+ stringValue += ".75";
+ break;
+ }
+ return stringValue;
+ }
+
+
+ boolean bRequestCheck;
+ boolean processResult() {
+ String accessResult = null;
+ if (accessTask == null) return false;
+ else if (accessTask.getStatus() != AsyncTask.Status.FINISHED) return false;
+ else {
+ accessResult = accessTask.accessResult;
+ MainActivity.csLibrary4A.appendToLog("accessResult 2 bankProcessing = " + bankProcessing + ", accessResult = " + accessTask.accessResult );
+ if (accessResult == null) {
+ if (readWriteTypes == ReadWriteTypes.TEMPERATURE && operationRead) {
+ bRequestCheck = false;
+ }
+ } else {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("accessResult = " + accessResult);
+ if (readWriteTypes == ReadWriteTypes.TEMPERATURE && operationRead == false) {
+ } else if (readWriteTypes == ReadWriteTypes.TEMPERATURE && operationRead) {
+ bRequestCheck = false; readWriteTypes = ReadWriteTypes.NULL;
+ MainActivity.csLibrary4A.appendToLog("accessResult of Temperature = " + accessResult);
+
+ if (accessResult.length() >= 16) {
+ int indexBegin = accessResult.length() - 16;
+ String stringValue = accessResult.substring(indexBegin, indexBegin + 4);
+ MainActivity.csLibrary4A.appendToLog("temperature part of Temperature accessResult = " + stringValue);
+ accessResult = stringValue; //"00B5"; //stringValue;
+ }
+ if (accessResult.length() == 4) {
+ byte bValue = Byte.parseByte(accessResult.substring(1, 2), 16);
+ Integer iValue2 = Integer.parseInt(accessResult.substring(2, 4), 16);
+ iValue2 &= 0x1FF;
+ if ((bValue & 0x01) != 0 && iValue2 == 0) textViewTemperature.setText("Invalid");
+ else {
+ String stringValue = getTemperatue(accessResult.substring(1, 4));
+ stringValue += (char) 0x00B0 + "C";
+ textViewTemperature.setText(stringValue);
+ }
+ }
+ }
+ }
+ accessTask = null;
+ return true;
+ }
+ }
+ boolean processTickItems() {
+ boolean invalidRequest1 = false;
+ int accSize = 0, accOffset = 0;
+ String writeData = "";
+
+ if (bRequestCheck) {
+ readWriteTypes = ReadWriteTypes.TEMPERATURE;
+ if (bankProcessing == 0) {
+ if (operationRead) {
+ textViewTemperature = (TextView) getActivity().findViewById(R.id.accessCCPTemperature);
+ textViewTemperature.setText("");
+ accOffset = 0x10D; accSize = 1; operationRead = false; writeData = "0000";
+ } else invalidRequest1 = true;
+ } else {
+ operationRead = true;
+ MainActivity.csLibrary4A.macWrite(0x11F, 3);
+ return false;
+ }
+ } else {
+ invalidRequest1 = true;
+ }
+
+ if (invalidRequest1 == false) {
+ if (MainActivity.csLibrary4A.setAccessBank(3) == false) {
+ invalidRequest1 = true;
+ }
+ }
+ if (invalidRequest1 == false) {
+ if (MainActivity.csLibrary4A.setAccessOffset(accOffset) == false) {
+ invalidRequest1 = true;
+ }
+ }
+ if (invalidRequest1 == false) {
+ if (accSize == 0) {
+ invalidRequest1 = true;
+ } else if (MainActivity.csLibrary4A.setAccessCount(accSize) == false) {
+ invalidRequest1 = true;
+ }
+ }
+ if (invalidRequest1 == false && operationRead == false) {
+ if (invalidRequest1 == false) {
+ if (MainActivity.csLibrary4A.setAccessWriteData(writeData) == false) {
+ invalidRequest1 = true;
+ }
+ }
+ }
+ return invalidRequest1;
+ }
+}
+
+
+
+package com.csl.cs710ademoapp.fragments;
+
+import android.app.Activity;
+import android.os.AsyncTask;
+import android.os.Bundle;
+import android.os.Handler;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.AdapterView;
+import android.widget.ArrayAdapter;
+import android.widget.Button;
+import android.widget.CheckBox;
+import android.widget.EditText;
+import android.widget.Spinner;
+import android.widget.TableRow;
+import android.widget.TextView;
+import android.widget.Toast;
+
+import com.csl.cs710ademoapp.AccessTask;
+import com.csl.cs710ademoapp.CustomPopupWindow;
+import com.csl.cs710ademoapp.MainActivity;
+import com.csl.cs710ademoapp.R;
+import com.csl.cs710ademoapp.SaveList2ExternalTask;
+import com.csl.cs710ademoapp.SelectTag;
+import com.csl.cslibrary4a.RfidReaderChipData;
+
+import java.text.SimpleDateFormat;
+import java.util.Date;
+
+import static com.csl.cs710ademoapp.MainActivity.mContext;
+
+public class AccessFdmicroFragment extends CommonFragment {
+ SelectTag selectTag;
+ Spinner spinnerSelectCommand, spinnerSelectAuth, spinnerSelectGetSource;
+ TableRow tableRowOffsetLength, tableRowValue, tableRowAuth, tableRowGetTemperature, tableRowGetTemperature1, tableRowLogging, tableRowReg, tableRowEnable;
+ EditText editTextMemoryValue, editTextDelayStart, editTextCntLimit, editTextStep;
+ TextView textViewTemperatureValue, textViewBatteryValue, textViewLoggingValue, textViewLoggingValue1;
+ Button buttonRead, buttonWrite;
+ SimpleDateFormat formatter;
+
+ boolean operationRunning = false, operationRead = false, operationReadTemperature = false, operationReadBattery = false, operationSetLogging = false, operationCheckLogging = false, operationStopLogging = false, operationGetLogging = false;
+ AccessTask accessTask;
+
+ void clearOperationSelect() {
+ operationReadTemperature = false; operationReadBattery = false; operationSetLogging = false; operationCheckLogging = false; operationStopLogging = false; operationGetLogging = false;
+ }
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ super.onCreateView(inflater, container, savedInstanceState, false);
+ return inflater.inflate(R.layout.fragment_access_fdmicro, container, false);
+ }
+
+ @Override
+ public void onActivityCreated(Bundle savedInstanceState) {
+ super.onActivityCreated(savedInstanceState);
+
+ selectTag = new SelectTag((Activity)getActivity(), 0);
+
+ tableRowOffsetLength = (TableRow) getActivity().findViewById(R.id.accessFDOffsetLengthRow);
+ tableRowValue = (TableRow) getActivity().findViewById(R.id.accessFDValueRow);
+ tableRowAuth = (TableRow) getActivity().findViewById(R.id.accessFDAuthRow);
+ tableRowGetTemperature = (TableRow) getActivity().findViewById(R.id.accessFDGetTemperatureRow);
+ tableRowGetTemperature1 = (TableRow) getActivity().findViewById(R.id.accessFDGetTemperatureRow1);
+ tableRowLogging = (TableRow) getActivity().findViewById(R.id.accessFDLoggingRow);
+ tableRowReg = (TableRow) getActivity().findViewById(R.id.accessFDRegRow);
+ tableRowEnable = (TableRow) getActivity().findViewById(R.id.accessFDEnableRow);
+
+ spinnerSelectCommand = (Spinner) getActivity().findViewById(R.id.selectCommand);
+ ArrayAdapter targetAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.fd_command_options, R.layout.custom_spinner_layout);
+ targetAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+ spinnerSelectCommand.setAdapter(targetAdapter);
+ spinnerSelectCommand.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
+ @Override
+ public void onItemSelected(AdapterView> parent, View view, int position, long id) {
+ commandSelected(position);
+ }
+
+ @Override
+ public void onNothingSelected(AdapterView> parent) {
+
+ }
+ });
+
+ editTextMemoryValue = (EditText) getActivity().findViewById(R.id.accessFDMemoryValue);
+
+ spinnerSelectAuth = (Spinner) getActivity().findViewById(R.id.accessFDselectAuth);
+ ArrayAdapter targetAdapterAuth = ArrayAdapter.createFromResource(getActivity(), R.array.fd_auth_options, R.layout.custom_spinner_layout);
+ targetAdapterAuth.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+ spinnerSelectAuth.setAdapter(targetAdapterAuth);
+
+ spinnerSelectGetSource = (Spinner) getActivity().findViewById(R.id.accessFDSelectGetSource);
+ ArrayAdapter targetAdapterGetSource = ArrayAdapter.createFromResource(getActivity(), R.array.fd_getSource_options, R.layout.custom_spinner_layout);
+ targetAdapterAuth.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+ spinnerSelectGetSource.setAdapter(targetAdapterGetSource);
+
+ Button buttonCheckTemperature = (Button) getActivity().findViewById(R.id.accessFDcheckTemperature);
+ buttonCheckTemperature.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (isOperationRunning()) return;
+ clearOperationSelect(); operationReadTemperature = true;
+ textViewTemperatureValue.setText("");
+ readWriteOperation();
+ }
+ });
+ textViewTemperatureValue = (TextView) getActivity().findViewById(R.id.accessFDtemperatureValue);
+
+ Button buttonCheckBattery = (Button) getActivity().findViewById(R.id.accessFDcheckBattery);
+ buttonCheckBattery.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (isOperationRunning()) return;
+ clearOperationSelect(); operationReadBattery = true;
+ textViewBatteryValue.setText("");
+ readWriteOperation();
+ }
+ });
+ textViewBatteryValue = (TextView) getActivity().findViewById(R.id.accessFDbatteryValue);
+
+ editTextDelayStart = (EditText) getActivity().findViewById(R.id.accessFDvdetDelayStartCfg);
+ editTextCntLimit = (EditText) getActivity().findViewById(R.id.accessFDrtcCntLimit);
+ editTextStep = (EditText) getActivity().findViewById(R.id.accessFDstepCfg);
+ formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
+
+ Button buttonSetLogging = (Button) getActivity().findViewById(R.id.accessFDSetLogging);
+ buttonSetLogging.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (isOperationRunning()) return;
+ clearOperationSelect(); operationSetLogging = true;
+ textViewLoggingValue.setText("");
+ readWriteOperation();
+ }
+ });
+ Button buttonCheckLogging = (Button) getActivity().findViewById(R.id.accessFDCheckLogging);
+ buttonCheckLogging.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (isOperationRunning()) return;
+ clearOperationSelect(); operationCheckLogging = true;
+ textViewLoggingValue.setText("");
+ readWriteOperation();
+ }
+ });
+ Button buttonStopLogging = (Button) getActivity().findViewById(R.id.accessFDStopLogging);
+ buttonStopLogging.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (isOperationRunning()) return;
+ clearOperationSelect(); operationStopLogging = true;
+ textViewLoggingValue.setText("");
+ readWriteOperation();
+ }
+ });
+ Button buttonGetLogging = (Button) getActivity().findViewById(R.id.accessFDGetLogging);
+ buttonGetLogging.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (isOperationRunning()) return;
+ clearOperationSelect(); operationGetLogging = true;
+ textViewLoggingValue1.setText("");
+ readWriteOperation();
+ }
+ });
+ textViewLoggingValue = (TextView) getActivity().findViewById(R.id.accessFDloggingValue);
+ textViewLoggingValue1 = (TextView) getActivity().findViewById(R.id.accessFDloggingValue1);
+
+ Button buttonSaveLogging = (Button) getActivity().findViewById(R.id.accessFDSaveLogging);
+ buttonSaveLogging.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (isOperationRunning()) return;
+ SaveList2ExternalTask saveExternalTask = new SaveList2ExternalTask(MainActivity.sharedObjects.tagsList);
+ String strMessage = "EPC: " + selectTag.editTextTagID.getText().toString() + "\n";
+ strMessage += textViewLoggingValue1.getText().toString();
+ if (logData != null) {
+ Date date = logData.dateLogStart;
+ if (date != null) {
+ long ltime = date.getTime();
+ ltime += (logData.minLogStartDelay * 1000 * 60);
+ if (logData.iSampleSize > 0) {
+ ltime += (logData.iSampleSize -1 ) * logData.secLogSampleInterval * 1000;
+ }
+ date.setTime(ltime);
+ strMessage += ("Stop: " + formatter.format(date) + "\n");
+ }
+ }
+ String resultDisplay = saveExternalTask.save2File(strMessage, false);
+ CustomPopupWindow customPopupWindow = new CustomPopupWindow(mContext);
+ customPopupWindow.popupStart(resultDisplay, false);
+ }
+ });
+
+ buttonRead = (Button) getActivity().findViewById(R.id.accessRWReadButton);
+ buttonRead.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (isOperationRunning()) return;
+ clearOperationSelect(); operationRead = true;
+ readWriteOperation();
+ }
+ });
+
+ buttonWrite = (Button) getActivity().findViewById(R.id.accessRWWriteButton);
+ buttonWrite.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (isOperationRunning()) return;
+ clearOperationSelect(); operationRead = false;
+ readWriteOperation();
+ }
+ });
+
+ MainActivity.csLibrary4A.setSameCheck(true);
+ }
+
+ @Override
+ public void onResume() {
+ super.onResume();
+ MainActivity.csLibrary4A.appendToLog("AccessFdmicro onResume !!!");
+ }
+
+ @Override
+ public void onPause() {
+ super.onPause();
+ }
+
+ @Override
+ public void onDestroy() {
+ MainActivity.csLibrary4A.setSameCheck(true);
+ MainActivity.csLibrary4A.restoreAfterTagSelect();
+ super.onDestroy();
+ }
+
+ boolean userVisibleHint = false;
+ @Override
+ public void setUserVisibleHint(boolean isVisibleToUser) {
+ super.setUserVisibleHint(isVisibleToUser);
+ if (getUserVisibleHint()) {
+ userVisibleHint = true;
+ selectTag.updateBankSelected();
+ MainActivity.csLibrary4A.appendToLog("AccessFdmicroFragment is now VISIBLE");
+ } else {
+ userVisibleHint = false;
+ MainActivity.csLibrary4A.appendToLog("AccessFdmicroFragment is now INVISIBLE");
+ }
+ }
+
+ public AccessFdmicroFragment() {
+ super("AccessFdmicroFragment");
+ }
+
+ class LogData {
+ Date dateLogStart;
+ int minLogStartDelay;
+ int secLogSampleInterval;
+ int iSampleSize;
+ }
+ LogData logData;
+
+ void commandSelected(int position) {
+ if (position < 0 || position > 2) position = spinnerSelectCommand.getSelectedItemPosition();
+ MainActivity.csLibrary4A.appendToLog("commandSelected position = " + position);
+ switch (position) {
+ case 0:
+ tableRowOffsetLength.setVisibility(View.VISIBLE);
+ tableRowValue.setVisibility(View.VISIBLE);
+ tableRowValue.setVisibility(View.VISIBLE);
+ tableRowAuth.setVisibility(View.GONE);
+ tableRowGetTemperature.setVisibility(View.GONE);
+ tableRowGetTemperature1.setVisibility(View.GONE);
+ tableRowLogging.setVisibility(View.GONE);
+ tableRowReg.setVisibility(View.GONE);
+ tableRowEnable.setVisibility(View.GONE);
+ buttonRead.setText(getResources().getString(R.string.read_title));
+ buttonWrite.setText("WRITE");
+ buttonWrite.setVisibility(View.VISIBLE);
+ break;
+ case 1:
+ tableRowOffsetLength.setVisibility(View.GONE);
+ tableRowValue.setVisibility(View.GONE);
+ tableRowAuth.setVisibility(View.VISIBLE);
+ tableRowGetTemperature.setVisibility(View.GONE);
+ tableRowGetTemperature1.setVisibility(View.GONE);
+ tableRowLogging.setVisibility(View.GONE);
+ tableRowReg.setVisibility(View.GONE);
+ tableRowEnable.setVisibility(View.GONE);
+ buttonRead.setText(getResources().getString(R.string.start_title));
+ buttonWrite.setVisibility(View.GONE);
+ break;
+ case 2:
+ tableRowOffsetLength.setVisibility(View.GONE);
+ tableRowValue.setVisibility(View.GONE);
+ tableRowAuth.setVisibility(View.GONE);
+ tableRowGetTemperature.setVisibility(View.VISIBLE);
+ tableRowGetTemperature1.setVisibility(View.VISIBLE);
+ tableRowLogging.setVisibility(View.GONE);
+ tableRowReg.setVisibility(View.GONE);
+ tableRowEnable.setVisibility(View.GONE);
+ buttonRead.setText(getResources().getString(R.string.read_title));
+ buttonWrite.setText("MEASURE");
+ buttonWrite.setVisibility(View.VISIBLE);
+ break;
+ case 3:
+ tableRowOffsetLength.setVisibility(View.GONE);
+ tableRowValue.setVisibility(View.GONE);
+ tableRowAuth.setVisibility(View.GONE);
+ tableRowGetTemperature.setVisibility(View.GONE);
+ tableRowGetTemperature1.setVisibility(View.GONE);
+ tableRowLogging.setVisibility(View.VISIBLE);
+ tableRowReg.setVisibility(View.GONE);
+ tableRowEnable.setVisibility(View.GONE);
+ buttonRead.setText(getResources().getString(R.string.start_title));
+ buttonWrite.setText("STOP");
+ buttonWrite.setVisibility(View.VISIBLE);
+ break;
+ case 4:
+ tableRowOffsetLength.setVisibility(View.GONE);
+ tableRowValue.setVisibility(View.GONE);
+ tableRowValue.setVisibility(View.GONE);
+ tableRowAuth.setVisibility(View.GONE);
+ tableRowGetTemperature.setVisibility(View.GONE);
+ tableRowGetTemperature1.setVisibility(View.GONE);
+ tableRowLogging.setVisibility(View.GONE);
+ tableRowReg.setVisibility(View.VISIBLE);
+ tableRowEnable.setVisibility(View.GONE);
+ buttonRead.setText(getResources().getString(R.string.read_title));
+ buttonWrite.setText("WRITE");
+ buttonWrite.setVisibility(View.VISIBLE);
+ break;
+ case 5:
+ case 6:
+ case 7:
+ case 8:
+ tableRowOffsetLength.setVisibility(View.GONE);
+ tableRowValue.setVisibility(View.GONE);
+ tableRowValue.setVisibility(View.GONE);
+ tableRowAuth.setVisibility(View.GONE);
+ tableRowGetTemperature.setVisibility(View.GONE);
+ tableRowGetTemperature1.setVisibility(View.GONE);
+ tableRowLogging.setVisibility(View.GONE);
+ tableRowReg.setVisibility(View.GONE);
+ CheckBox checkBox = (CheckBox) getActivity().findViewById(R.id.accessFDEnable);
+ if (position == 6) checkBox.setText("refresh temperature measurement");
+ else checkBox.setText("Enable");
+ if (position == 7) tableRowEnable.setVisibility(View.GONE);
+ else tableRowEnable.setVisibility(View.VISIBLE);
+ buttonRead.setText(getResources().getString(R.string.read_title));
+ buttonRead.setText(getResources().getString(R.string.start_title));
+ buttonWrite.setVisibility(View.GONE);
+ break;
+ default:
+ buttonRead.setText(getResources().getString(R.string.read_title));
+ buttonWrite.setText("WRITE");
+ buttonWrite.setVisibility(View.VISIBLE);
+ break;
+ }
+ }
+
+ boolean isOperationRunning() {
+ if (accessTask != null) {
+ if (accessTask.getStatus() == AsyncTask.Status.RUNNING) {
+ Toast.makeText(MainActivity.mContext, "Running acccess task. Please wait", Toast.LENGTH_SHORT).show();
+ return true;
+ }
+ }
+ return false;
+ }
+ void readWriteOperation() {
+ RfidReaderChipData.HostCommands hostCommand = null;
+ if (isOperationRunning()) return;
+ iOtherFlowCount = 0; bLogging = false; iTimeNumber = 0; iTimeTotal = 0;
+ if (operationReadTemperature || operationReadBattery || operationSetLogging || operationCheckLogging || operationGetLogging) {
+ operationRead = true;
+ tableRowEnable.setVisibility(View.GONE);
+ buttonRead.setText(getResources().getString(R.string.start_title));
+ buttonWrite.setVisibility(View.GONE);
+
+ MainActivity.csLibrary4A.set_fdCmdCfg(0x0000);
+ hostCommand = RfidReaderChipData.HostCommands.CMD_FDM_OPMODE_CHECK;
+ } else {
+ MainActivity.csLibrary4A.appendToLog("Item Selected is " + spinnerSelectCommand.getSelectedItemPosition());
+ int position = spinnerSelectCommand.getSelectedItemPosition();
+ if (operationStopLogging) {
+ position = 3; operationRead = false;
+ }
+ switch (position) {
+ case 0:
+ EditText editTextMemoryOffset = (EditText) getActivity().findViewById(R.id.accessFDmemoryOffset);
+ int iMemoryOffset = getEditTextHexValue(editTextMemoryOffset, 4);
+ iMemoryOffset &= 0xFFFC;
+ editTextMemoryOffset.setText(String.format("%X", iMemoryOffset));
+
+ EditText editTextMemoryLength = (EditText) getActivity().findViewById(R.id.accessFDmemoryLength);
+ int iMemoryLength = 0;
+ try {
+ iMemoryLength = Integer.parseInt(editTextMemoryLength.getText().toString());
+ } catch (Exception ex) { }
+ if (iMemoryLength <= 0) iMemoryLength = 1;
+ if (operationRead) {
+ if (iMemoryLength != (iMemoryLength / 4) * 4)
+ iMemoryLength = ((iMemoryLength / 4) + 1) * 4;
+ if (iMemoryLength > 512) iMemoryLength = 512;
+ } else {
+ if (iMemoryLength > 4) iMemoryLength = 4;
+ }
+ editTextMemoryLength.setText(String.valueOf(iMemoryLength));
+
+ if (operationRead) {
+ editTextMemoryValue.setText("");
+ MainActivity.csLibrary4A.set_fdReadMem(iMemoryOffset, iMemoryLength);
+ } else {
+ String strValue = editTextMemoryValue.getText().toString();
+ if (strValue.length() > 8)
+ strValue = strValue.substring(strValue.length() - 8);
+ if (strValue.length() > 2 * iMemoryLength)
+ strValue = strValue.substring(strValue.length() - 2 * iMemoryLength);
+ int iValue = 0;
+ try {
+ iValue = Integer.parseInt(strValue, 16);
+ } catch (Exception ex) {
+ strValue = "00";
+ }
+ strValue = String.format("%X", iValue);
+ editTextMemoryValue.setText(strValue);
+ MainActivity.csLibrary4A.set_fdWriteMem(iMemoryOffset, iMemoryLength, iValue);
+ }
+
+ hostCommand = (operationRead ? RfidReaderChipData.HostCommands.CMD_FDM_RDMEM : RfidReaderChipData.HostCommands.CMD_FDM_WRMEM);
+ break;
+ case 1:
+ int iConfig = spinnerSelectAuth.getSelectedItemPosition();
+ switch (iConfig) {
+ case 1:
+ iConfig = 3;
+ break;
+ case 2:
+ iConfig = 4;
+ break;
+ default:
+ break;
+ }
+ MainActivity.csLibrary4A.set_fdCmdCfg(iConfig); //0 (user area password), 3 (unlock password), 4 (stop logging password)
+
+ EditText editTextAuthPassword = (EditText) getActivity().findViewById(R.id.selectFDAuthPassword);
+ int iValue = getEditTextHexValue(editTextAuthPassword, 8);
+ MainActivity.csLibrary4A.set_fdPwd(iValue);
+
+ hostCommand = RfidReaderChipData.HostCommands.CMD_FDM_AUTH;
+ break;
+ case 2:
+ iConfig = 0;
+ CheckBox checkBoxGetTemperatureStartGet = (CheckBox) getActivity().findViewById(R.id.accessFDGetTemperatureStartGet);
+ if (true) {
+ if (operationRead) checkBoxGetTemperatureStartGet.setChecked(true);
+ else checkBoxGetTemperatureStartGet.setChecked(false);
+ }
+ if (checkBoxGetTemperatureStartGet.isChecked()) iConfig |= 0x80;
+ switch (spinnerSelectGetSource.getSelectedItemPosition()) {
+ case 1:
+ iConfig |= 0x10;
+ break;
+ case 2:
+ iConfig |= 0x20;
+ break;
+ case 3:
+ iConfig |= 0x30;
+ break;
+ }
+ CheckBox checkBoxGetTemperatureResultType = (CheckBox) getActivity().findViewById(R.id.accessFDGetTemperatureResultType);
+ if (checkBoxGetTemperatureResultType.isChecked()) iConfig |= 4;
+ CheckBox checkBoxGetTemperatureCheckField = (CheckBox) getActivity().findViewById(R.id.accessFDGetTemperatureCheckField);
+ if (checkBoxGetTemperatureCheckField.isChecked()) iConfig |= 2;
+ CheckBox checkBoxGetTemperatureStorageEnable = (CheckBox) getActivity().findViewById(R.id.accessFDGetTemperatureStorageEnable);
+ if (checkBoxGetTemperatureStorageEnable.isChecked()) iConfig |= 1;
+ MainActivity.csLibrary4A.set_fdCmdCfg(iConfig);
+
+ EditText editTextStoreOffset = (EditText) getActivity().findViewById(R.id.accessFDStoreOffset);
+ int iStoreOffset = getEditTextHexValue(editTextStoreOffset, 2);
+ MainActivity.csLibrary4A.set_fdBlockAddr4GetTemperature(iStoreOffset);
+
+ hostCommand = RfidReaderChipData.HostCommands.CMD_FDM_GET_TEMPERATURE;
+ break;
+ case 3:
+ MainActivity.csLibrary4A.set_fdCmdCfg(operationRead ? 0 : 80);
+
+ if (operationRead)
+ hostCommand = RfidReaderChipData.HostCommands.CMD_FDM_START_LOGGING;
+ else {
+ EditText editText = (EditText) getActivity().findViewById(R.id.selectFDLoggingPassword);
+ int iPassword = getEditTextHexValue(editText, 8);
+ MainActivity.csLibrary4A.set_fdPwd(iPassword);
+
+ hostCommand = RfidReaderChipData.HostCommands.CMD_FDM_STOP_LOGGING;
+ }
+ break;
+ case 4:
+ EditText editText = (EditText) getActivity().findViewById(R.id.accessFDRegOffset);
+ iValue = getEditTextHexValue(editText, 2);
+ iValue += 0xC000;
+ editText.setText(String.format("%04X", iValue));
+
+ EditText editText1 = (EditText) getActivity().findViewById(R.id.accessFDRegValue);
+ if (operationRead) {
+ editText1.setText("");
+ MainActivity.csLibrary4A.set_fdRegAddr(iValue);
+ hostCommand = RfidReaderChipData.HostCommands.CMD_FDM_RDREG;
+ } else {
+ int iValue1 = getEditTextHexValue(editText1, 4);
+ MainActivity.csLibrary4A.set_fdWrite(iValue, iValue1);
+ hostCommand = RfidReaderChipData.HostCommands.CMD_FDM_WRREG;
+ }
+ break;
+ case 5:
+ case 6:
+ case 7:
+ case 8:
+ CheckBox checkBox1 = (CheckBox) getActivity().findViewById(R.id.accessFDEnable);
+ iValue = 0;
+ if (checkBox1.isChecked()) {
+ if (position == 8) iValue = 2;
+ else if (position != 7) iValue = 1;
+ }
+ MainActivity.csLibrary4A.set_fdCmdCfg(iValue);
+ if (position == 5) hostCommand = RfidReaderChipData.HostCommands.CMD_FDM_DEEP_SLEEP;
+ else if (position == 6)
+ hostCommand = RfidReaderChipData.HostCommands.CMD_FDM_OPMODE_CHECK;
+ else if (position == 7)
+ hostCommand = RfidReaderChipData.HostCommands.CMD_FDM_INIT_REGFILE;
+ else if (position == 8)
+ hostCommand = RfidReaderChipData.HostCommands.CMD_FDM_LED_CTRL;
+ break;
+ default:
+ break;
+ }
+ }
+ doAccessTask(hostCommand);
+ }
+
+ void doAccessTask(RfidReaderChipData.HostCommands hostCommand) {
+ String selectMask = selectTag.editTextTagID.getText().toString();
+ int selectBank = selectTag.spinnerSelectBank.getSelectedItemPosition() + 1;
+ int selectOffset = Integer.valueOf(selectTag.editTextSelectOffset.getText().toString());
+ boolean invalid = false;
+ accessTask = new AccessTask((operationRead ? buttonRead : buttonWrite), null, invalid, true,
+ selectMask, selectBank, selectOffset,
+ selectTag.editTextAccessPassword.getText().toString(),
+ Integer.valueOf(selectTag.editTextAccessAntennaPower.getText().toString()),
+ hostCommand,
+ 0, 0, true, false,
+ null, null, null, null, null);
+ accessTask.setRunnable(updateRunnable);
+ accessTask.execute();
+ }
+
+ Handler handler = new Handler(); boolean bLogging = false; int iOtherFlowCount = 0, iTimeNumber = 0, iTimeTotal = 0, iDelayToStart = 0;
+ private final Runnable updateRunnable = new Runnable() {
+ final boolean DEBUG = true;
+ @Override
+ public void run() {
+ if (accessTask == null) return;
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("AAA: " + "accessTask.status = " + accessTask.getStatus().toString());
+ if (accessTask.getStatus() == AsyncTask.Status.RUNNING) {
+ mHandler.postDelayed(updateRunnable, 100);
+ return;
+ }
+
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("AAA: " + accessTask.accessResult + ": blogging with iOtherFlowCount = " + iOtherFlowCount);
+ if ((operationReadTemperature || operationReadBattery || operationSetLogging || operationCheckLogging || operationGetLogging) && (iOtherFlowCount == 0)) {
+ int iValue = 0;
+ try {
+ iValue = Integer.parseInt(accessTask.accessResult, 16);
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("AAA: " + accessTask.accessResult + ": blogging with iValue = " + iValue);
+ } catch (Exception ex) { }
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("AAA: " + accessTask.accessResult + ": blogging with iValue after catch = " + iValue);
+ if ((iValue & 0x1000) != 0) {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("AAA: " + accessTask.accessResult + ": blogging A is true");
+ bLogging = true;
+ if (operationCheckLogging == false && operationGetLogging == false) {
+ iOtherFlowCount = 99;
+ accessTask.accessResult += ": logging is in processed";
+ }
+ } else bLogging = false;
+ if (operationReadBattery && (iValue & 0x0100) == 0) {
+ iOtherFlowCount = 99;
+ accessTask.accessResult += ": less than 0.9V or no battery.";
+ }
+ }
+ if (operationGetLogging) {
+ switch (iOtherFlowCount) {
+ case 0:
+ MainActivity.csLibrary4A.set_fdReadMem(0, 12);
+ doAccessTask(RfidReaderChipData.HostCommands.CMD_FDM_RDMEM);
+ break;
+ case 1:
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("case 1: bLogging = " + bLogging + ", accessTask.accessResult = " + accessTask.accessResult);
+ if (accessTask.accessResult != null) {
+ Date date = null;
+ long lDateTime = -1;
+ int iDelay = -1, iInterval = -1;
+ if (accessTask.accessResult.length() >= 24) {
+ try {
+ String strDateTime = accessTask.accessResult.substring(6, 8);
+ strDateTime += accessTask.accessResult.substring(4, 6);
+ strDateTime += accessTask.accessResult.substring(2, 4);
+ strDateTime += accessTask.accessResult.substring(0, 2);
+ lDateTime = 1000 * Long.parseLong(strDateTime, 16);
+
+ String strDelay = accessTask.accessResult.substring(18, 20);
+ strDelay += accessTask.accessResult.substring(16, 18);
+ iDelay = Integer.parseInt(strDelay, 16);
+
+ String strInterval = accessTask.accessResult.substring(22, 24);
+ strInterval += accessTask.accessResult.substring(20, 22);
+ iInterval = Integer.parseInt(strInterval, 16);
+ } catch(Exception ex) { }
+ if (iInterval != -1) {
+ date = new Date();
+ date.setTime(lDateTime);
+ textViewLoggingValue1.append("Start: " + formatter.format(date) + "\n");
+ textViewLoggingValue1.append("delay: " + iDelay + " minutes\n");
+ textViewLoggingValue1.append("interval: " + iInterval + " seconds\n");
+ }
+ logData = new LogData();
+ logData.dateLogStart = date;
+ logData.minLogStartDelay = iDelay;
+ logData.secLogSampleInterval = iInterval;
+ }
+ }
+ if (bLogging) {
+ MainActivity.csLibrary4A.set_fdRegAddr(0xc094);
+ doAccessTask(RfidReaderChipData.HostCommands.CMD_FDM_RDREG);
+ } else {
+ MainActivity.csLibrary4A.set_fdReadMem(0xb188, 4);
+ doAccessTask(RfidReaderChipData.HostCommands.CMD_FDM_RDMEM);
+ }
+ break;
+ case 2:
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("bLogging = " + bLogging + ", accessTask.accessResult = " + accessTask.accessResult);
+ if (bLogging) {
+ operationGetLogging = false;
+ int iValue = 0;
+ try {
+ iValue = Integer.parseInt(accessTask.accessResult.substring(2,4), 16) & 0x30;
+ } catch (Exception ex) { }
+ String strMessage = "";
+ if (iValue == 0x10) strMessage = "Initial Delay Start";
+ else if (iValue == 0x20) strMessage = "Logging in Progress";
+ else if (iValue == 00) strMessage = "non-rtc";
+ textViewLoggingValue1.setText(accessTask.accessResult + ": " + strMessage + "\n");
+ break;
+ } else {
+ String strTemp = accessTask.accessResult;
+ iTimeTotal = Integer.parseInt(strTemp.substring(2, 4) + strTemp.substring(0, 2), 16);
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("iTimeTotal is set to " + iTimeTotal + ", with strTemp = " + strTemp);
+ textViewLoggingValue1.append("status: " + accessTask.accessResult + "\n");
+ iTimeTotal++;
+ }
+ logData.iSampleSize = 0;
+ default:
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("iOtherFlowCount = " + iOtherFlowCount + ", accessTask.accessResult = " + accessTask.accessResult);
+ if (iOtherFlowCount != 2) {
+ String strMessage = ""; //accessTask.accessResult + ": ";
+ String strAccessResult = accessTask.accessResult.substring(6, 8) + accessTask.accessResult.substring(4, 6) + accessTask.accessResult.substring(2, 4) + accessTask.accessResult.substring(0, 2);
+ Long lValue = Long.parseLong(strAccessResult, 16);
+ int iOddBit = 0;
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog(String.format("accessResult to lValue = %X", lValue));
+ for (int i = 0; i < 32; i++) {
+ if ((lValue & 1) != 0) {
+ iOddBit++;
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("accessResult, i=" + i + ", iOddbit=" + iOddBit);
+ }
+ lValue = lValue >> 1;
+ }
+ if ((iOddBit & 1) != 0)
+ strMessage += ("invalid checksum, " + strAccessResult);
+ else {
+ iTimeNumber = Integer.parseInt(strAccessResult.substring(0, 4), 16) & 0x7FFF;
+ strMessage += ("item " + iTimeNumber + ": ");
+ int iTemperature = Integer.parseInt(strAccessResult.substring(5, 8), 16) & 0x3FF;
+ strMessage += i2TemperatureString(iTemperature);
+ logData.iSampleSize++;
+ }
+ textViewLoggingValue1.append(strMessage + "\n");
+ }
+
+ if (iTimeTotal <= (iOtherFlowCount - 2) || bLogging) {
+ textViewLoggingValue1.append("end of logging data\n");
+ operationGetLogging = false;
+ commandSelected(spinnerSelectCommand.getSelectedItemPosition());
+ }
+ else {
+ int iValue = 0x1000 + (iOtherFlowCount - 2) * 4;
+ MainActivity.csLibrary4A.set_fdReadMem(iValue, 4);
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog(String.format("set_fdReadMem address = 0x%04x", iValue));
+ doAccessTask(RfidReaderChipData.HostCommands.CMD_FDM_RDMEM);
+ }
+ break;
+ }
+ iOtherFlowCount++;
+ } else if (operationCheckLogging) {
+ switch (iOtherFlowCount) {
+ case 0:
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog(accessTask.accessResult + ": blogging B is " + bLogging);
+ if (bLogging) {
+ MainActivity.csLibrary4A.set_fdRegAddr(0xc096);
+ doAccessTask(RfidReaderChipData.HostCommands.CMD_FDM_RDREG);
+ } else {
+ MainActivity.csLibrary4A.set_fdReadMem(0xb188, 4);
+ doAccessTask(RfidReaderChipData.HostCommands.CMD_FDM_RDMEM);
+ }
+ break;
+ default:
+ operationCheckLogging = false;
+ textViewLoggingValue.setText(accessTask.accessResult);
+ commandSelected(spinnerSelectCommand.getSelectedItemPosition());
+ break;
+ }
+ iOtherFlowCount++;
+ } else if (operationSetLogging) {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("AAA: " + "operationSetLogging: iOtherFlowCount = " + iOtherFlowCount + ", accessResult = " + accessTask.accessResult + ", resultError= " + accessTask.resultError);
+ switch (iOtherFlowCount) {
+ case 0: //0x4cb3,29d6
+ CheckBox checkBox = (CheckBox) getActivity().findViewById(R.id.accessFDenableLEDAutoFlash);
+ long lValue = 0x4db229d6;
+ if (checkBox.isChecked()) {
+ lValue |= 0x2000; lValue &= ~0x20;
+ lValue &= 0xFFFFFFFF;
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("AAA: " + "lValue = " + String.format("%08x", lValue));
+ } else {
+ lValue &= ~0x2000; lValue |= 0x20;
+ lValue &= 0xFFFFFFFF;
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("AAA: " + "lValue1 = " + String.format("%08x", lValue));
+ }
+ MainActivity.csLibrary4A.set_fdWriteMem(0xb040, 4, lValue); //~user_cfg1,user_cfg1,~user_cfg0,user_cfg0: default as 0xd629b34c
+ doAccessTask(RfidReaderChipData.HostCommands.CMD_FDM_WRMEM);
+ logData = new LogData();
+ break;
+ case 1:
+ int iValue0 = 3;
+ try {
+ iValue0 = Integer.parseInt(editTextCntLimit.getText().toString());
+ } catch (Exception ex) {
+ }
+ editTextCntLimit.setText(String.valueOf(iValue0));
+
+ String string1 = String.format("%04X", iValue0);
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("AAA: " + "accessResult: string1 = " + string1);
+ String string2 = string1.substring(2, 4) + string1.substring(0, 2) + "0000";
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("AAA: " + "accessResult: string2 = " + string2);
+ int iValue = Integer.parseInt(string2, 16);
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("AAA: " + String.format("accessResult: iValue = %X, iValue1 = %X", iValue0, iValue));
+
+ MainActivity.csLibrary4A.set_fdWriteMem(0xb094, 4, iValue); //rtc_cnt_limit: default as 0x00000003
+ doAccessTask(RfidReaderChipData.HostCommands.CMD_FDM_WRMEM);
+ break;
+ case 2:
+ MainActivity.csLibrary4A.set_fdWriteMem(0xb0a4, 4, 0x0A000100); //vdet_alarm_step_cfg, vdet_step_cfg: default as 0
+ doAccessTask(RfidReaderChipData.HostCommands.CMD_FDM_WRMEM);
+ break;
+ case 3:
+ iValue = 1;
+ try {
+ iValue = Integer.parseInt(editTextDelayStart.getText().toString());
+ } catch (Exception ex) { }
+ iDelayToStart = iValue;
+ editTextDelayStart.setText(String.valueOf(iValue));
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("AAA: " + String.format("accessResult: iValue = %X", iValue));
+
+ MainActivity.csLibrary4A.set_fdWrite(0xc084, iValue); //vdet_delay_cfg: default as 0xffff in minute
+ doAccessTask(RfidReaderChipData.HostCommands.CMD_FDM_WRREG);
+ logData.minLogStartDelay = iValue;
+ break;
+ case 4:
+ iValue = 1;
+ try {
+ iValue = Integer.parseInt(editTextStep.getText().toString());
+ } catch (Exception ex) { }
+ editTextStep.setText(String.valueOf(iValue));
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("AAA: " + String.format("accessResult: iValue = %X", iValue));
+
+ MainActivity.csLibrary4A.set_fdWrite(0xc085, iValue); //vdet_step_cfg: default as 0xffff in seconds
+ doAccessTask(RfidReaderChipData.HostCommands.CMD_FDM_WRREG);
+ logData.secLogSampleInterval = iValue;
+ break;
+ case 5:
+ MainActivity.csLibrary4A.set_fdWrite(0xc099, 0); //summary_min_temperature: default 0
+ doAccessTask(RfidReaderChipData.HostCommands.CMD_FDM_WRREG);
+ break;
+ case 6:
+ MainActivity.csLibrary4A.set_fdWrite(0xc098, 0x100); //summary_max_temperature: default 0
+ doAccessTask(RfidReaderChipData.HostCommands.CMD_FDM_WRREG);
+ break;
+ case 7:
+ MainActivity.csLibrary4A.set_fdRegAddr(0xc084); //vdet_delay_cfg: default as 0xffff in minute
+ doAccessTask(RfidReaderChipData.HostCommands.CMD_FDM_RDREG);
+ break;
+ case 8:
+ iValue = -1;
+ try {
+ iValue = Integer.parseInt(accessTask.accessResult);
+ } catch (Exception ex) { }
+ if (iValue != iDelayToStart) {
+ iOtherFlowCount = 99;
+ accessTask.accessResult += ": logging failure";
+ textViewLoggingValue.setText(accessTask.accessResult);
+ break;
+ }
+ MainActivity.csLibrary4A.set_fdCmdCfg(0);
+ doAccessTask(RfidReaderChipData.HostCommands.CMD_FDM_START_LOGGING);
+ break;
+ case 9:
+ Date date = new Date();
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("AAA: " + "Current time is " + formatter.format(date));
+
+ long longTemp = date.getTime() / 1000;
+ Long longValue = ((longTemp & 0xFF) << 24);
+ longValue |= ((longTemp & 0xFF00) << 8) ;
+ longValue |= ((longTemp & 0xFF0000) >> 8);
+ longValue |= ((longTemp & 0xFF000000) >> 24) ;
+ MainActivity.csLibrary4A.set_fdWriteMem(0, 4, longValue); //rtc_cnt_limit: default as 0x00000003
+ doAccessTask(RfidReaderChipData.HostCommands.CMD_FDM_WRMEM);
+ break;
+ case 10:
+ longValue = (((long)logData.minLogStartDelay & 0xFF) << 24);
+ longValue |= ((logData.minLogStartDelay & 0xFF00) << 8) ;
+ longValue |= ((logData.secLogSampleInterval & 0XFF) << 8 );
+ longValue |= ((logData.secLogSampleInterval & 0xFF00) >> 8) ;
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("AAA: " + String.format("longValue = %08x, minLogStartDelay = %04x, secLogSampleInterval = %04x", longValue, logData.minLogStartDelay, logData.secLogSampleInterval));
+ MainActivity.csLibrary4A.set_fdWriteMem(8, 4, longValue); //rtc_cnt_limit: default as 0x00000003
+ doAccessTask(RfidReaderChipData.HostCommands.CMD_FDM_WRMEM);
+ break;
+ default:
+ operationSetLogging = false;
+ if (iOtherFlowCount < 88) {
+ String strMessage = accessTask.accessResult;
+ iValue = Integer.parseInt(accessTask.accessResult, 16);
+ if (iValue != 0xFFFF) strMessage += ": Logging Program Started\n";
+ else strMessage += ": invalid logging. Please stop it and try again.\n";
+ textViewLoggingValue.setText(strMessage);
+ } else textViewLoggingValue.setText(accessTask.accessResult);
+ commandSelected(spinnerSelectCommand.getSelectedItemPosition());
+ break;
+ }
+ iOtherFlowCount++;
+ }
+ else if (operationReadBattery) {
+ switch(iOtherFlowCount) {
+ case 0:
+ MainActivity.csLibrary4A.set_fdWrite(0xc012, 0x0008);
+ doAccessTask(RfidReaderChipData.HostCommands.CMD_FDM_WRREG);
+ break;
+ case 1:
+ MainActivity.csLibrary4A.set_fdCmdCfg(0x12);
+ doAccessTask(RfidReaderChipData.HostCommands.CMD_FDM_GET_TEMPERATURE);
+ break;
+ case 2:
+ MainActivity.csLibrary4A.set_fdCmdCfg(0x92);
+ doAccessTask(RfidReaderChipData.HostCommands.CMD_FDM_GET_TEMPERATURE);
+ break;
+ default:
+ operationReadBattery = false;
+ if (iOtherFlowCount < 88) {
+ int iValue = 0;
+ try {
+ iValue = Integer.parseInt(accessTask.accessResult, 16);
+ float fValue = (float) (iValue & 0xFFFF);
+ fValue = fValue / 8192 * (float) 2.5;
+ textViewBatteryValue.setText(String.format("%.2fV", fValue));
+ } catch (Exception ex) {
+ }
+ } else textViewBatteryValue.setText(accessTask.accessResult);
+ commandSelected(spinnerSelectCommand.getSelectedItemPosition());
+ break;
+ }
+ iOtherFlowCount++;
+ }
+ else if (operationReadTemperature) {
+ switch(iOtherFlowCount) {
+ case 0:
+ MainActivity.csLibrary4A.set_fdWrite(0xc012, 0x0000);
+ doAccessTask(RfidReaderChipData.HostCommands.CMD_FDM_WRREG);
+ break;
+ case 1:
+ MainActivity.csLibrary4A.set_fdCmdCfg(0x06);
+ doAccessTask(RfidReaderChipData.HostCommands.CMD_FDM_GET_TEMPERATURE);
+ break;
+ case 2:
+ MainActivity.csLibrary4A.set_fdCmdCfg(0x86);
+ doAccessTask(RfidReaderChipData.HostCommands.CMD_FDM_GET_TEMPERATURE);
+ break;
+ default:
+ operationReadTemperature = false;
+ if (iOtherFlowCount < 88) {
+ int iValue = 0;
+ try {
+ iValue = Integer.parseInt(accessTask.accessResult, 16);
+ if ((iValue & 0x8000) != 0)
+ textViewTemperatureValue.setText("Store addr overflow");
+ else textViewTemperatureValue.setText(i2TemperatureString(iValue));
+ } catch (Exception ex) {
+ }
+ } else textViewTemperatureValue.setText(accessTask.accessResult);
+ commandSelected(spinnerSelectCommand.getSelectedItemPosition());
+ break;
+ }
+ iOtherFlowCount++;
+ } else {
+ int position = spinnerSelectCommand.getSelectedItemPosition();
+ if (operationStopLogging) {
+ operationStopLogging = false;
+ position = 3; operationRead = false;
+ }
+ switch (position) {
+ case 0:
+ if (operationRead) editTextMemoryValue.setText(accessTask.accessResult);
+ break;
+ case 1:
+ int iValue = Integer.parseInt(accessTask.accessResult, 16);
+ String strMessage = accessTask.accessResult + ":";
+ switch (iValue & 0x7) {
+ case 0:
+ strMessage = "User area";
+ break;
+ case 3:
+ strMessage = "Unlock";
+ break;
+ case 4:
+ strMessage = "Stop loggging";
+ break;
+ }
+ strMessage += " password:\nAuth is ";
+ if ((iValue & 0x80) != 0) strMessage += "passed";
+ else strMessage += "failed";
+ strMessage += "\nPassword is ";
+ if ((iValue & 0x40) != 0) strMessage += "zero";
+ else strMessage += "non-zero";
+ CustomPopupWindow customPopupWindow = new CustomPopupWindow(MainActivity.mContext);
+ customPopupWindow.popupStart(strMessage, false);
+ break;
+ case 2:
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("accessResult = " + accessTask.accessResult);
+ strMessage = accessTask.accessResult;
+ CheckBox checkBoxGetTemperatureResultType = (CheckBox) getActivity().findViewById(R.id.accessFDGetTemperatureResultType);
+ if (operationRead) {
+ iValue = Integer.parseInt(strMessage, 16);
+ if ((iValue & 0x8000) != 0) strMessage += ": store addr overflow";
+ else if (checkBoxGetTemperatureResultType.isChecked()) {
+ strMessage += ": temperature = ";
+ strMessage += i2TemperatureString(iValue);
+ } else
+ strMessage += String.format(": raw temperature data = %X", iValue & 0x1FFF);
+ } else {
+ if (strMessage.matches("FFFA")) strMessage += ": enough field energy";
+ else if (strMessage.matches("FFF5"))
+ strMessage += ": insufficient field energy";
+ else if (strMessage.matches("FFF0"))
+ strMessage += ": not yet enable field check";
+ }
+ customPopupWindow = new CustomPopupWindow(MainActivity.mContext);
+ customPopupWindow.popupStart(strMessage, false);
+ break;
+ case 3:
+ textViewLoggingValue.setText(accessTask.accessResult);
+ strMessage = accessTask.accessResult.trim();
+ if (operationRead) {
+ if (strMessage.matches("0000")) strMessage = null;
+ } else {
+ iValue = Integer.parseInt(strMessage, 16);
+ if ((iValue & 2) != 0) strMessage += ": password check is failed";
+ if ((iValue & 1) != 0) strMessage += ": RTC stop password is all zero";
+ }
+ if (strMessage != null) {
+ customPopupWindow = new CustomPopupWindow(MainActivity.mContext);
+ customPopupWindow.popupStart(strMessage, false);
+ }
+ break;
+ case 4:
+ strMessage = null;
+ if (operationRead) {
+ if (false && accessTask.accessResult.matches("FFFF"))
+ strMessage = accessTask.accessResult + ": invalid empty address";
+ else {
+ EditText editText = (EditText) getActivity().findViewById(R.id.accessFDRegValue);
+ editText.setText(accessTask.accessResult);
+ }
+ } else {
+ iValue = 0;
+ try {
+ iValue = Integer.parseInt(accessTask.accessResult, 16);
+ } catch (Exception ex) {
+ }
+ if (iValue != 0) {
+ strMessage = accessTask.accessResult;
+ if (iValue == (byte) 0xFFFF) strMessage += ": invalid/busy address";
+ else {
+ if ((iValue & 0x4) != 0)
+ strMessage += ": the register cannot be written";
+ if ((iValue & 0x02) != 0)
+ strMessage += ": invalid register addresss";
+ }
+ }
+ }
+ if (strMessage != null) {
+ customPopupWindow = new CustomPopupWindow(MainActivity.mContext);
+ customPopupWindow.popupStart(strMessage, false);
+ }
+ break;
+ case 5:
+ case 7:
+ case 8:
+ strMessage = accessTask.accessResult.trim();
+ if (strMessage != null && strMessage.length() != 0 && strMessage.matches("0000") == false) {
+ customPopupWindow = new CustomPopupWindow(MainActivity.mContext);
+ customPopupWindow.popupStart(strMessage, false);
+ }
+ if (position == 8 && iOtherFlowCount == 0) {
+ iOtherFlowCount++;
+ MainActivity.csLibrary4A.set_fdWriteMem(0xb040, 4, 0x4db229d6); //~user_cfg1,user_cfg1,~user_cfg0,user_cfg0: default as 0xd629b34c
+ doAccessTask(RfidReaderChipData.HostCommands.CMD_FDM_WRMEM);
+ }
+ break;
+ case 6:
+ strMessage = accessTask.accessResult;
+ iValue = Integer.parseInt(strMessage, 16);
+ if ((iValue & 0x2000) != 0) strMessage += ": user_access_en";
+ if ((iValue & 0x1000) != 0) strMessage += ": rtc logging";
+ if ((iValue & 0x800) != 0) strMessage += ": vdet_process_flag";
+ if ((iValue & 0x200) != 0) strMessage += ": light_chk_flag";
+ if ((iValue & 0x100) != 0) strMessage += ": vbat_pwr_flag";
+ customPopupWindow = new CustomPopupWindow(MainActivity.mContext);
+ customPopupWindow.popupStart(strMessage, false);
+ break;
+ default:
+ break;
+ }
+ }
+ }
+ };
+
+ String i2TemperatureString(int iValue) {
+ String strMessage = "";
+ if ((iValue & 0x200) != 0) {
+ strMessage += "-";
+ iValue ^= 0x3FF;
+ iValue++;
+ }
+ if (true) { //8 bit data, 2 bit decimal
+ strMessage += String.format("%d.", (iValue >> 2) & 0xFF);
+ strMessage += String.format("%d\u2103", (iValue & 3) * 100 / 4);
+ } else { //7 bit data, 3 bit decimal
+ strMessage += String.format("%d.", (iValue >> 3) & 0x7F);
+ strMessage += String.format("%d\u2103", (iValue & 7) * 1000 / 8);
+ }
+ return strMessage;
+ }
+
+ int getEditTextHexValue(EditText editText, int iStrLen) {
+ String strValue = editText.getText().toString().trim();
+ MainActivity.csLibrary4A.appendToLog("getEditTextHexValue: editText.string=" + strValue + ", iStrLen=" + iStrLen);
+ if (strValue.length() > iStrLen) strValue = strValue.substring(strValue.length() - iStrLen);
+ int iValue = 0;
+ try {
+ iValue = Integer.parseInt(strValue, 16);
+ } catch (Exception ex) { }
+ int iValue2 = 0;
+ for (int i = 0; i < iStrLen; i++) { iValue2 <<= 4; iValue2 |= 0xFF; }
+ strValue = String.format("%0" + String.valueOf(iStrLen) + "X", iValue & iValue2);
+ MainActivity.csLibrary4A.appendToLog("getEditTextHexValue: exit string = " + strValue);
+ editText.setText(strValue);
+ return iValue;
+ }
+}
+
+
+
+package com.csl.cs710ademoapp.fragments;
+
+import static com.csl.cslibrary4a.RfidReader.TagType.TAG_IMPINJ;
+
+import android.app.Activity;
+import android.os.AsyncTask;
+import android.os.Bundle;
+import android.os.SystemClock;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.AdapterView;
+import android.widget.ArrayAdapter;
+import android.widget.Button;
+import android.widget.CheckBox;
+import android.widget.EditText;
+import android.widget.LinearLayout;
+import android.widget.Spinner;
+import android.widget.TextView;
+import android.widget.Toast;
+
+import com.csl.cs710ademoapp.AccessTask;
+import com.csl.cs710ademoapp.AccessTask1;
+import com.csl.cs710ademoapp.CustomPopupWindow;
+import com.csl.cs710ademoapp.MainActivity;
+import com.csl.cs710ademoapp.R;
+import com.csl.cs710ademoapp.SelectTag;
+import com.csl.cslibrary4a.ReaderDevice;
+import com.csl.cslibrary4a.RfidReaderChipData;
+import com.google.android.material.tabs.TabLayout;
+
+public class AccessImpinjFragment extends CommonFragment {
+ CheckBox checkBoxTagFocus, checkBoxFastId, checkBoxProtectSelect, checkBoxAutoTuneDisable, checkBoxProtect, checkBoxShortRange, checkBoxMemorySelect, checkBoxUnkillable;
+ Spinner spinnerTagSelect;
+
+ TextView textViewUserValue;
+ Button buttonReadUserBank, buttonWriteUserBank;
+ TextView textViewRunTime;
+ enum impinjTag {
+ m775, m780, m830, m770, m730, monza_R6A, monza_R6P, monza_x8k, others
+ }
+
+ SelectTag selectTag;
+ TextView textViewAuthenticatedResult, textViewAutotuneValue, textViewProtectValue, textViewProtectNormalValue, textViewEpc128Value, textViewConfiguration;
+ Button button, buttonAutoTuneValueRead, buttonProtectValueRead, buttonProtectResumeRead, buttonEpc128ValueRead, buttonRead, buttonWrite;
+ boolean operationRead = false;
+ AccessTask accessTask;
+ AccessTask1 accessTask1;
+ int iRunType = -1; String stringNewAutoTuneConfig = null;
+ int unprotecting = 0;
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ super.onCreateView(inflater, container, savedInstanceState, false);
+ return inflater.inflate(R.layout.fragment_access_impinj, container, false);
+ }
+
+ @Override
+ public void onActivityCreated(Bundle savedInstanceState) {
+ super.onActivityCreated(savedInstanceState);
+
+ checkBoxTagFocus = (CheckBox) getActivity().findViewById(R.id.accessImpinjTagFocus);
+ if (MainActivity.csLibrary4A.get98XX() == 2) checkBoxTagFocus.setText(checkBoxTagFocus.getText().toString() + " (When enabled, tag select is disabled.)");
+ MainActivity.csLibrary4A.appendToLog("CheckBoxTagFocus is set");
+ checkBoxFastId = (CheckBox) getActivity().findViewById(R.id.accessImpinjFastId);
+
+ checkBoxAutoTuneDisable = (CheckBox) getActivity().findViewById(R.id.accessImpinjAutoTune);
+ checkBoxProtect = (CheckBox) getActivity().findViewById(R.id.accessImpinjProtect);
+ checkBoxShortRange = (CheckBox) getActivity().findViewById(R.id.accessImpinjShortRange);
+ checkBoxMemorySelect = (CheckBox) getActivity().findViewById(R.id.accessImpinjMemorySelect);
+ checkBoxUnkillable = (CheckBox) getActivity().findViewById(R.id.accessImpinjUnkillable);
+
+ spinnerTagSelect = (Spinner) getActivity().findViewById(R.id.accessImpinjTagSelect);
+ ArrayAdapter targetAdapter1 = ArrayAdapter.createFromResource(getActivity(), R.array.impinj_options, R.layout.custom_spinner_layout);
+ targetAdapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+ spinnerTagSelect.setAdapter(targetAdapter1); spinnerTagSelect.setSelection(0);
+ spinnerTagSelect.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
+ @Override
+ public void onItemSelected(AdapterView> parentView, View selectedItemView, int position, long id) {
+ TabLayout tabLayout = (TabLayout) getActivity().findViewById(R.id.OperationsTabLayout);
+ TabLayout.TabView tabView = tabLayout.getTabAt(2).view;
+ //LinearLayout layout = (LinearLayout) getActivity().findViewById(R.id.accessImpinjAuthenticateLayout);
+ if (position == impinjTag.m775.ordinal()) {
+ //layout.setVisibility(View.VISIBLE);
+ textViewAuthenticatedResult.setText("");
+ tabView.setVisibility(View.VISIBLE);
+ } else {
+ //layout.setVisibility(View.GONE);
+ tabView.setVisibility(View.GONE);
+ }
+
+ LinearLayout layoutA = (LinearLayout) getActivity().findViewById(R.id.accessImpinjProtectLayout);
+ LinearLayout layoutA1 = (LinearLayout) getActivity().findViewById(R.id.accessImpinjProtectLayout1);
+ if (position == impinjTag.m775.ordinal() ||
+ position == impinjTag.m780.ordinal() ||
+ position == impinjTag.m830.ordinal() ||
+ position == impinjTag.m770.ordinal() ||
+ position == impinjTag.m730.ordinal()) {
+ layoutA.setVisibility(View.VISIBLE);
+ layoutA1.setVisibility(View.VISIBLE);
+ textViewProtectValue.setText("");
+ } else {
+ layoutA.setVisibility(View.GONE);
+ layoutA1.setVisibility(View.GONE);
+ }
+
+ LinearLayout layout0 = (LinearLayout) getActivity().findViewById(R.id.accessImpinjMemorySelectLayout);
+ if (position == impinjTag.m830.ordinal() || position == impinjTag.monza_R6P.ordinal()) {
+ layout0.setVisibility(View.VISIBLE);
+ textViewEpc128Value.setText("");
+ } else layout0.setVisibility(View.GONE);
+
+ LinearLayout layout1 = (LinearLayout) getActivity().findViewById(R.id.accessImpinjSelectLayout);
+ if (position == impinjTag.others.ordinal()) layout1.setVisibility(View.GONE);
+ else layout1.setVisibility(View.VISIBLE);
+
+ LinearLayout layout2 = (LinearLayout) getActivity().findViewById(R.id.accessImpinjAutotuneLayout);
+ LinearLayout layout3 = (LinearLayout) getActivity().findViewById(R.id.accessImpinjConfigLayout);
+ if (position == impinjTag.monza_x8k.ordinal() || position == impinjTag.others.ordinal()) {
+ layout2.setVisibility(View.GONE);
+ layout3.setVisibility(View.GONE);
+ } else {
+ layout2.setVisibility(View.VISIBLE);
+ layout3.setVisibility(View.VISIBLE);
+
+ textViewAutotuneValue.setText("");
+
+ if (position == impinjTag.monza_R6A.ordinal() || position == impinjTag.monza_R6P.ordinal() || position == impinjTag.others.ordinal()) checkBoxProtect.setVisibility(View.GONE);
+ else checkBoxProtect.setVisibility(View.VISIBLE);
+ if (position == impinjTag.m830.ordinal() || position == impinjTag.monza_R6P.ordinal()) checkBoxMemorySelect.setVisibility(View.VISIBLE);
+ else checkBoxMemorySelect.setVisibility(View.GONE);
+ if (position == impinjTag.m775.ordinal() || position == impinjTag.m780.ordinal() || position == impinjTag.m770.ordinal()) checkBoxUnkillable.setVisibility(View.VISIBLE);
+ else checkBoxUnkillable.setVisibility(View.GONE);
+
+ checkBoxAutoTuneDisable.setChecked(false); checkBoxAutoTuneDisable.setEnabled(false);
+ checkBoxProtect.setChecked(false); checkBoxProtect.setEnabled(false);
+ checkBoxShortRange.setChecked(false); checkBoxShortRange.setEnabled(false);
+ checkBoxMemorySelect.setChecked(false); checkBoxMemorySelect.setEnabled(false);
+ checkBoxUnkillable.setChecked(false); checkBoxUnkillable.setEnabled(false);
+ textViewConfiguration.setText("");
+ }
+
+ LinearLayout layout4 = (LinearLayout) getActivity().findViewById(R.id.accessImpinjReadUserLayout);
+ if (position == impinjTag.monza_x8k.ordinal()) layout4.setVisibility(View.VISIBLE);
+ else layout4.setVisibility(View.GONE);
+ }
+
+ @Override
+ public void onNothingSelected(AdapterView> parentView) {
+ // your code here
+ }
+
+ });
+
+ MainActivity.csLibrary4A.setSameCheck(false);
+ data2Restore.iQuerySession = MainActivity.csLibrary4A.getQuerySession();
+ data2Restore.iQueryTarget = MainActivity.csLibrary4A.getQueryTarget();
+ data2Restore.tagDelay = MainActivity.csLibrary4A.getTagDelay();
+ data2Restore.dwellTime = MainActivity.csLibrary4A.getAntennaDwell();
+ data2Restore.tagFocus = MainActivity.csLibrary4A.getTagFocus();
+
+ selectTag = new SelectTag((Activity)getActivity(), 0);
+
+ if (true) {
+ textViewAuthenticatedResult = (TextView) getActivity().findViewById(R.id.accessImpinjAuthenticatedResult);
+ button = (Button) getActivity().findViewById(R.id.accessImpinjAuthenticateButton);
+ button.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (isRfidConnectionValid() == false) return;
+ if (isRunningAccessTask()) return;
+
+ textViewAuthenticatedResult.setText("");
+ boolean invalidRequest = MainActivity.csLibrary4A.setAuthenticateConfiguration();
+ accessTask = new AccessTask(button, null, false, true,
+ selectTag.editTextTagID.getText().toString(), 1, 32,
+ selectTag.editTextAccessPassword.getText().toString(), Integer.valueOf(selectTag.editTextAccessAntennaPower.getText().toString()), RfidReaderChipData.HostCommands.CMD_18K6CAUTHENTICATE,
+ -1, -1, false, false,
+ null, null, null, null, null);
+ accessTask.execute();
+
+ mHandler.removeCallbacks(updateRunnable);
+ iRunType = 1; mHandler.post(updateRunnable);
+ }
+ });
+ }
+
+ if (true) {
+ textViewAutotuneValue = (TextView) getActivity().findViewById(R.id.accessImpinjAutoTuneValue);
+ buttonAutoTuneValueRead = (Button) getActivity().findViewById(R.id.accessImpinjAutotuneValueButton);
+ buttonAutoTuneValueRead.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (isRfidConnectionValid() == false) return;
+ if (isRunningAccessTask()) return;
+
+ textViewAutotuneValue.setText("");
+ boolean invalidRequest = false;
+ int iAccOffset = 0x1c; int itagSelect = spinnerTagSelect.getSelectedItemPosition();
+ if (itagSelect == impinjTag.m775.ordinal()) iAccOffset = 0x1c;
+ else if (itagSelect == impinjTag.m780.ordinal()) iAccOffset = 0x34;
+ else if (itagSelect == impinjTag.m830.ordinal()) iAccOffset = 0x14;
+ else if (itagSelect == impinjTag.m770.ordinal()) iAccOffset = 0x1c;
+ else if (itagSelect == impinjTag.m730.ordinal()) iAccOffset = 0x14;
+ else if (itagSelect == impinjTag.monza_R6A.ordinal()) iAccOffset = 0x14;
+ else if (itagSelect == impinjTag.monza_R6P.ordinal()) iAccOffset = 0x14;
+ MainActivity.csLibrary4A.appendToLog(String.format("AutoTune offset is 0x%X", iAccOffset));
+ if (set_before_access(0, itagSelect, 1) == false) invalidRequest = true;
+ accessTask = new AccessTask(buttonAutoTuneValueRead, null, invalidRequest, true,
+ selectTag.editTextTagID.getText().toString(), 1, 32,
+ selectTag.editTextAccessPassword.getText().toString(), Integer.valueOf(selectTag.editTextAccessAntennaPower.getText().toString()), RfidReaderChipData.HostCommands.CMD_18K6CREAD,
+ -1, -1, false, checkProtectedBoxBeforeAccess(),
+ null, null, null, null, null);
+ accessTask.execute();
+ mHandler.removeCallbacks(updateRunnable);
+ iRunType = 2; mHandler.post(updateRunnable);
+ }
+ });
+
+ textViewProtectValue = (TextView) getActivity().findViewById(R.id.accessImpinjProtectValue);
+ checkBoxProtectSelect = (CheckBox) getActivity().findViewById(R.id.accessImpinjProtectSelect);
+ textViewProtectNormalValue = (TextView) getActivity().findViewById(R.id.accessImpinjProtectNormalValue);
+ buttonProtectValueRead = (Button) getActivity().findViewById(R.id.accessImpinjProtectValueButton);
+ buttonProtectValueRead.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (isRfidConnectionValid() == false) return;
+ if (isRunningAccessTask()) return;
+
+ textViewProtectValue.setText("");
+ boolean invalidRequest = false;
+ if (set_before_access(1, 2, 6) == false) invalidRequest = true;
+ accessTask = new AccessTask(buttonProtectValueRead, null, invalidRequest, true,
+ selectTag.editTextTagID.getText().toString(), 1, 32,
+ selectTag.editTextAccessPassword.getText().toString(), Integer.valueOf(selectTag.editTextAccessAntennaPower.getText().toString()), RfidReaderChipData.HostCommands.CMD_18K6CREAD,
+ -1, -1, false, checkProtectedBoxBeforeAccess(),
+ null, null, null, null, null);
+ MainActivity.csLibrary4A.appendToLog("setSelectCriteria: before execute");
+ accessTask.execute();
+ MainActivity.csLibrary4A.appendToLog("setSelectCriteria: after execute");
+ mHandler.removeCallbacks(updateRunnable);
+ iRunType = 3; mHandler.post(updateRunnable);
+ }
+ });
+
+ buttonProtectResumeRead = (Button) getActivity().findViewById(R.id.accessImpinjProtectResumeButton);
+ buttonProtectResumeRead.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (isZeroPassword()) return;
+ if (isRfidConnectionValid() == false) return;
+ if (isRunningAccessTask()) {
+ if (accessTask != null) accessTask.taskCancelReason = AccessTask.TaskCancelRReason.DESTORY;
+ }
+
+ if (unprotecting > 0) stopProtectResuming();
+ else {
+ unprotecting = 1;
+ if (spinnerTagSelect.getSelectedItemPosition() == impinjTag.m775.ordinal()) selectTag.editTextTagID.setText("E2C011A2");
+ else if (spinnerTagSelect.getSelectedItemPosition() == impinjTag.m780.ordinal()) selectTag.editTextTagID.setText("E28011C");
+ else if (spinnerTagSelect.getSelectedItemPosition() == impinjTag.m770.ordinal()) selectTag.editTextTagID.setText("E28011A0");
+ else if (spinnerTagSelect.getSelectedItemPosition() == impinjTag.m830.ordinal()) selectTag.editTextTagID.setText("E28011B0");
+ else if (spinnerTagSelect.getSelectedItemPosition() == impinjTag.m730.ordinal()) selectTag.editTextTagID.setText("E280119");
+ selectTag.spinnerSelectBank.setSelection(1);
+ checkBoxProtectSelect.setChecked(true);
+ buttonProtectResumeRead.setText("Stop resuming to normal");
+
+ startConfigRead();
+ }
+ }
+ });
+
+ textViewEpc128Value = (TextView) getActivity().findViewById(R.id.accessImpinjEpc128Value);
+ buttonEpc128ValueRead = (Button) getActivity().findViewById(R.id.accessImpinjEpc128ValueButton);
+ buttonEpc128ValueRead.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (isRfidConnectionValid() == false) return;
+ if (isRunningAccessTask()) return;
+
+ textViewEpc128Value.setText("");
+ boolean invalidRequest = false;
+ if (set_before_access(1, 2, 8) == false) invalidRequest = true;
+ accessTask = new AccessTask(buttonEpc128ValueRead, null, invalidRequest, true,
+ selectTag.editTextTagID.getText().toString(), 1, 32,
+ selectTag.editTextAccessPassword.getText().toString(), Integer.valueOf(selectTag.editTextAccessAntennaPower.getText().toString()), RfidReaderChipData.HostCommands.CMD_18K6CREAD,
+ -1, -1, false, checkProtectedBoxBeforeAccess(),
+ null, null, null, null, null);
+ accessTask.execute();
+ mHandler.removeCallbacks(updateRunnable);
+ iRunType = 4; mHandler.post(updateRunnable);
+ }
+ });
+
+ textViewRunTime = (TextView) getActivity().findViewById(R.id.accessImpinjRunTime);
+ buttonReadUserBank = (Button) getActivity().findViewById(R.id.accessRWReadButton);
+ buttonReadUserBank.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (MainActivity.csLibrary4A.isBleConnected() == false) {
+ Toast.makeText(MainActivity.mContext, R.string.toast_ble_not_connected, Toast.LENGTH_SHORT).show();
+ return;
+ } else if (MainActivity.csLibrary4A.isRfidFailure()) {
+ Toast.makeText(MainActivity.mContext, "Rfid is disabled", Toast.LENGTH_SHORT).show();
+ return;
+ }
+ operationRead = true; startAccessUserTask();
+ }
+ });
+
+ buttonWriteUserBank = (Button) getActivity().findViewById(R.id.accessRWWriteButton);
+ buttonWriteUserBank.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (MainActivity.csLibrary4A.isBleConnected() == false) {
+ Toast.makeText(MainActivity.mContext, R.string.toast_ble_not_connected, Toast.LENGTH_SHORT).show();
+ return;
+ } else if (MainActivity.csLibrary4A.isRfidFailure()) {
+ Toast.makeText(MainActivity.mContext, "Rfid is disabled", Toast.LENGTH_SHORT).show();
+ return;
+ }
+ operationRead = false; startAccessUserTask();
+ }
+ });
+
+ textViewConfiguration = (TextView) getActivity().findViewById(R.id.accessImpinjConfiguration);
+ buttonRead = (Button) getActivity().findViewById(R.id.accessImpinjReadButton);
+ buttonRead.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (isRfidConnectionValid() == false) return;
+ if (isRunningAccessTask()) return;
+
+ startConfigRead();
+ }
+ });
+
+ buttonWrite = (Button) getActivity().findViewById(R.id.accessImpinjWriteButton);
+ buttonWrite.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (isZeroPassword()) return;
+ if (isRfidConnectionValid() == false) return;
+ if (isRunningAccessTask()) return;
+
+ if (textViewConfiguration.getText().toString().length() < 4) {
+ Toast.makeText(MainActivity.mContext, "Please read configuration first", Toast.LENGTH_SHORT).show();
+ return;
+ }
+ startConfigWrite();
+ }
+ });
+ }
+ }
+ boolean isZeroPassword() {
+ boolean bValue = false;
+ int iValue = 0;
+ try {
+ iValue = Integer.parseInt(selectTag.editTextAccessPassword.getText().toString(), 16);
+ } catch (Exception ex) {
+ iValue = -1;
+ }
+ MainActivity.csLibrary4A.appendToLog("Password = " + iValue);
+ if (iValue == 0) {
+ CustomPopupWindow customPopupWindow = new CustomPopupWindow(MainActivity.mContext);
+ customPopupWindow.popupStart("Before operation, please enter non-zero access password !!!", false);
+ bValue = true;
+ }
+ return bValue;
+ }
+ void stopProtectResuming() {
+ unprotecting = 0;
+ checkBoxProtectSelect.setChecked(false);
+ buttonProtectResumeRead.setText("Resume invisible tag to normal");
+ }
+
+ boolean updating = false; long msStartTime; int bankProcessing = 0; int restartAccessBank = -1;
+ void startAccessUserTask() {
+ msStartTime = SystemClock.elapsedRealtime();
+ textViewRunTime.setText("");
+
+ int iSelectBank = selectTag.spinnerSelectBank.getSelectedItemPosition() + 1;
+ int iSelectOffset = 32;
+ if (iSelectBank != 1) iSelectOffset = 0;
+
+ EditText editTextBlockCount = (EditText) getActivity().findViewById(R.id.accessImpinjBlockCount);
+ EditText editTextUserOffset = (EditText) getActivity().findViewById(R.id.accessImpinjUserOffset);
+ EditText editTextUserLength = (EditText) getActivity().findViewById(R.id.accessImpinjUserLength);
+ int accBlockCount = 32, accOffset = 1, accSize = 1;
+ try {
+ accBlockCount = Integer.parseInt(editTextBlockCount.getText().toString());
+ } catch (Exception ex) { }
+ try {
+ accOffset = Integer.valueOf(editTextUserOffset.getText().toString(), 10);
+ } catch (Exception ex) { }
+ try {
+ accSize = Integer.valueOf(editTextUserLength.getText().toString(), 10);
+ } catch (Exception ex) { }
+
+ textViewUserValue = (TextView) getActivity().findViewById(R.id.accessImpinjUserValue);
+ if (operationRead) textViewUserValue.setText("");
+ boolean invalidRequest = false;
+
+ MainActivity.csLibrary4A.appendToLog("Start accessTask1 with accBlockCount + " + accBlockCount + "F" + editTextBlockCount.getText().toString() + ", accOffset = " + accOffset + "F" + editTextUserOffset.getText().toString() + ", accSize = " + accSize + "F" + editTextUserLength.getText().toString());
+ accessTask1 = new AccessTask1(
+ (operationRead ? buttonReadUserBank : buttonWriteUserBank), invalidRequest,
+ 3, accOffset, accSize, accBlockCount, null,
+ selectTag.editTextTagID.getText().toString(), iSelectBank, iSelectOffset,
+ selectTag.editTextAccessPassword.getText().toString(),
+ Integer.valueOf(selectTag.editTextAccessAntennaPower.getText().toString()),
+ (operationRead ? RfidReaderChipData.HostCommands.CMD_18K6CREAD: RfidReaderChipData.HostCommands.CMD_18K6CWRITE), updateRunnable);
+ accessTask1.execute();
+ iRunType = 7;
+ }
+ void startConfigRead() {
+ textViewConfiguration.setText("");
+ boolean invalidRequest = false;
+ if (set_before_access(0, 4, 1) == false) invalidRequest = true;
+ int iSelectBank = selectTag.spinnerSelectBank.getSelectedItemPosition() + 1;
+ int iSelectOffset = 32;
+ if (iSelectBank != 1) iSelectOffset = 0;
+ accessTask = new AccessTask(buttonRead, null, invalidRequest, true,
+ selectTag.editTextTagID.getText().toString(), iSelectBank, iSelectOffset,
+ selectTag.editTextAccessPassword.getText().toString(), Integer.valueOf(selectTag.editTextAccessAntennaPower.getText().toString()), RfidReaderChipData.HostCommands.CMD_18K6CREAD,
+ -1, -1, false, checkProtectedBoxBeforeAccess(),
+ null, null, null, null, null);
+ accessTask.execute();
+ mHandler.removeCallbacks(updateRunnable);
+ iRunType = 5; mHandler.post(updateRunnable);
+ }
+ void startConfigWrite() {
+ boolean invalidRequest = false;
+ if (set_before_access(0, 4, 1) == false) invalidRequest = true;
+ int iSelectBank = selectTag.spinnerSelectBank.getSelectedItemPosition() + 1;
+ int iSelectOffset = 32;
+ if (iSelectBank != 1) iSelectOffset = 0;
+ if (invalidRequest == false) {
+ String string = textViewConfiguration.getText().toString();
+ int iValue = Integer.valueOf(string, 16);
+ MainActivity.csLibrary4A.appendToLog(String.format("iValue = 0x%02X", iValue));
+
+ if (checkBoxAutoTuneDisable.isChecked()) iValue |= 0x01;
+ else iValue &= ~0x01;
+
+ if (spinnerTagSelect.getSelectedItemPosition() == impinjTag.m775.ordinal() ||
+ spinnerTagSelect.getSelectedItemPosition() == impinjTag.m780.ordinal() ||
+ spinnerTagSelect.getSelectedItemPosition() == impinjTag.m830.ordinal() ||
+ spinnerTagSelect.getSelectedItemPosition() == impinjTag.m770.ordinal() ||
+ spinnerTagSelect.getSelectedItemPosition() == impinjTag.m730.ordinal()) {
+ if (checkBoxProtect.isChecked()) iValue |= 0x02;
+ else iValue &= ~0x02;
+ }
+
+ int iValueModified = 0x02;
+ if (spinnerTagSelect.getSelectedItemPosition() == impinjTag.m775.ordinal()) iValueModified = 0x04;
+ else if (spinnerTagSelect.getSelectedItemPosition() == impinjTag.m780.ordinal()) iValueModified = 0x04;
+ else if (spinnerTagSelect.getSelectedItemPosition() == impinjTag.m770.ordinal()) iValueModified = 0x04;
+ else if (spinnerTagSelect.getSelectedItemPosition() == impinjTag.m830.ordinal()) iValueModified = 0x10;
+ else if (spinnerTagSelect.getSelectedItemPosition() == impinjTag.m730.ordinal()) iValueModified = 0x10;
+ if (checkBoxShortRange.isChecked()) iValue |= iValueModified;
+ else iValue &= ~iValueModified;
+
+ iValueModified = 0;
+ if (spinnerTagSelect.getSelectedItemPosition() == impinjTag.m830.ordinal()) iValueModified = 0x08;
+ else if (spinnerTagSelect.getSelectedItemPosition() == impinjTag.monza_R6P.ordinal()) iValueModified = 0x04;
+ if (iValueModified != 0) {
+ if (checkBoxMemorySelect.isChecked()) iValue |= iValueModified;
+ else iValue &= ~iValueModified;
+ }
+
+ if (spinnerTagSelect.getSelectedItemPosition() == impinjTag.m775.ordinal() ||
+ spinnerTagSelect.getSelectedItemPosition() == impinjTag.m780.ordinal() ||
+ spinnerTagSelect.getSelectedItemPosition() == impinjTag.m770.ordinal()) {
+ if (checkBoxUnkillable.isChecked()) iValue |= 0x08;
+ else iValue &= ~0x08;
+ }
+
+ MainActivity.csLibrary4A.appendToLog(String.format("revised iValue = 0x%02X", iValue));
+ string = String.format("%04X", iValue);
+ MainActivity.csLibrary4A.appendToLog("string = " + string);
+ MainActivity.csLibrary4A.appendToLog("new AutotuneConfiguration = " + string);
+ stringNewAutoTuneConfig = string;
+ if (MainActivity.csLibrary4A.setAccessWriteData(string) == false) {
+ invalidRequest = true;
+ }
+ }
+
+ accessTask = new AccessTask(buttonWrite, null, invalidRequest, true,
+ selectTag.editTextTagID.getText().toString(), 1, 32,
+ selectTag.editTextAccessPassword.getText().toString(), Integer.valueOf(selectTag.editTextAccessAntennaPower.getText().toString()), RfidReaderChipData.HostCommands.CMD_18K6CWRITE,
+ -1, -1, false, checkProtectedBoxBeforeAccess(),
+ null, null, null, null, null);
+ accessTask.execute();
+ mHandler.removeCallbacks(updateRunnable);
+ iRunType = 6; mHandler.post(updateRunnable);
+ }
+ boolean bReadySelected = false;
+ boolean checkProtectedBoxBeforeAccess() {
+ bReadySelected = false;
+ if (checkBoxProtectSelect.isChecked()) {
+ MainActivity.csLibrary4A.appendToLog("Going to setSelectCriteria disable");
+ MainActivity.csLibrary4A.setSelectCriteriaDisable(-1);
+ MainActivity.csLibrary4A.appendToLog("Going to setSelectCriteria");
+ MainActivity.csLibrary4A.setSelectCriteria(-1, true, 4, 0, 3, 0, selectTag.editTextAccessPassword.getText().toString(), false);
+ bReadySelected = true;
+ }
+ return checkBoxProtectSelect.isChecked();
+ }
+ boolean isRfidConnectionValid() {
+ boolean bValue = false;
+ if (MainActivity.csLibrary4A.isBleConnected() == false) {
+ Toast.makeText(MainActivity.mContext, R.string.toast_ble_not_connected, Toast.LENGTH_SHORT).show();
+ } else if (MainActivity.csLibrary4A.isRfidFailure()) {
+ Toast.makeText(MainActivity.mContext, "Rfid is disabled", Toast.LENGTH_SHORT).show();
+ } else bValue = true;
+ return bValue;
+ }
+ boolean set_before_access(int accBank, int accOffset, int accSize) {
+ boolean invalidRequest = false;
+ if (invalidRequest == false) {
+ if (MainActivity.csLibrary4A.setAccessBank(accBank) == false) {
+ MainActivity.csLibrary4A.appendToLog("HelloK: accBank, invalidRequest=" + invalidRequest);
+ invalidRequest = true;
+ }
+ }
+ if (invalidRequest == false) {
+ if (MainActivity.csLibrary4A.setAccessOffset(accOffset) == false) {
+ MainActivity.csLibrary4A.appendToLog("HelloK: accOffset, invalidRequest=" + invalidRequest);
+ invalidRequest = true;
+ }
+ }
+ if (invalidRequest == false) {
+ if (MainActivity.csLibrary4A.setAccessCount(accSize) == false) {
+ invalidRequest = true;
+ }
+ }
+ if (invalidRequest) return false;
+ return true;
+ }
+
+ boolean isRunningAccessTask() {
+ boolean retValue = false;
+ if (accessTask != null) {
+ if (accessTask.getStatus() != AsyncTask.Status.FINISHED) retValue = true;
+ }
+ return retValue;
+ }
+ private final Runnable updateRunnable = new Runnable() {
+ @Override
+ public void run() {
+ if (accessTask == null && accessTask1 == null) {
+ MainActivity.csLibrary4A.appendToLog("updateRunnable(): null AccessTask");
+ } else if (accessTask != null && accessTask.getStatus() == AsyncTask.Status.FINISHED) {
+ MainActivity.csLibrary4A.appendToLog("accessResult = " + accessTask.accessResult + " with iRunType = " + iRunType);
+ if (accessTask.accessResult == null) {
+ MainActivity.csLibrary4A.appendToLog("updateRunnable(): accessTask is finished without result but with error = " + accessTask.resultError);
+ if (unprotecting > 0) stopProtectResuming();
+ } else if (iRunType == 1) textViewAuthenticatedResult.setText(accessTask.accessResult);
+ else if (iRunType == 2) textViewAutotuneValue.setText(accessTask.accessResult);
+ else if (iRunType == 3) textViewProtectValue.setText(accessTask.accessResult);
+ else if (iRunType == 4) textViewEpc128Value.setText(accessTask.accessResult);
+ else if (iRunType == 5) {
+ textViewConfiguration.setText(accessTask.accessResult);
+ int iValue = Integer.valueOf(accessTask.accessResult.substring(accessTask.accessResult.length()-2, accessTask.accessResult.length()), 16);
+ MainActivity.csLibrary4A.appendToLog("updateRunnable(): " + String.format("accessResult = %s, iValue = 0x%02X", accessTask.accessResult, iValue));
+
+ if ((iValue & 0x01) != 0) checkBoxAutoTuneDisable.setChecked(true); else checkBoxAutoTuneDisable.setChecked(false);
+ checkBoxAutoTuneDisable.setEnabled(true);
+
+ if (spinnerTagSelect.getSelectedItemPosition() == impinjTag.m775.ordinal() ||
+ spinnerTagSelect.getSelectedItemPosition() == impinjTag.m780.ordinal() ||
+ spinnerTagSelect.getSelectedItemPosition() == impinjTag.m830.ordinal() ||
+ spinnerTagSelect.getSelectedItemPosition() == impinjTag.m770.ordinal() ||
+ spinnerTagSelect.getSelectedItemPosition() == impinjTag.m730.ordinal()) {
+ if ((iValue & 0x02) != 0) checkBoxProtect.setChecked(true); else checkBoxProtect.setChecked(false);
+ checkBoxProtect.setEnabled(true);
+ }
+
+ int iBitCompared = 0x02;
+ if (spinnerTagSelect.getSelectedItemPosition() == impinjTag.m775.ordinal()) iBitCompared = 0x04;
+ else if (spinnerTagSelect.getSelectedItemPosition() == impinjTag.m780.ordinal()) iBitCompared = 0x04;
+ else if (spinnerTagSelect.getSelectedItemPosition() == impinjTag.m770.ordinal()) iBitCompared = 0x04;
+ else if (spinnerTagSelect.getSelectedItemPosition() == impinjTag.m830.ordinal()) iBitCompared = 0x10;
+ else if (spinnerTagSelect.getSelectedItemPosition() == impinjTag.m730.ordinal()) iBitCompared = 0x10;
+ if ((iValue & iBitCompared) != 0) checkBoxShortRange.setChecked(true); else checkBoxShortRange.setChecked(false);
+ checkBoxShortRange.setEnabled(true);
+
+ iBitCompared = 0;
+ if (spinnerTagSelect.getSelectedItemPosition() == impinjTag.m830.ordinal()) iBitCompared = 0x08;
+ else if (spinnerTagSelect.getSelectedItemPosition() == impinjTag.monza_R6P.ordinal()) iBitCompared = 0x04;
+ if (iBitCompared != 0) {
+ if ((iValue & iBitCompared) != 0) checkBoxMemorySelect.setChecked(true); else checkBoxMemorySelect.setChecked(false);
+ checkBoxMemorySelect.setEnabled(true);
+ }
+
+ if (spinnerTagSelect.getSelectedItemPosition() == impinjTag.m775.ordinal() ||
+ spinnerTagSelect.getSelectedItemPosition() == impinjTag.m780.ordinal() ||
+ spinnerTagSelect.getSelectedItemPosition() == impinjTag.m770.ordinal()) {
+ if ((iValue & 0x08) != 0) checkBoxUnkillable.setChecked(true);
+ else checkBoxUnkillable.setChecked(false);
+ checkBoxUnkillable.setEnabled(true);
+ }
+
+ if (unprotecting > 0) {
+ textViewProtectValue.setText(accessTask.accessTagEpc);
+ textViewProtectNormalValue.setText("" + unprotecting);
+ unprotecting++;
+ if (checkBoxProtect.isChecked()) {
+ selectTag.editTextTagID.setText(accessTask.accessTagEpc);
+ selectTag.spinnerSelectBank.setSelection(0);
+ checkBoxProtect.setChecked(false);
+ MainActivity.csLibrary4A.appendToLog("updateRunnable(): startConfigWrite");
+ startConfigWrite();
+ } else {
+ MainActivity.csLibrary4A.appendToLog("updateRunnable(): startConfigRead");
+ startConfigRead();
+ }
+ }
+ }
+ else if (iRunType == 6) {
+ MainActivity.csLibrary4A.appendToLog("updateRunnable(): accessResult = " + accessTask.accessResult + ", accessError = " + accessTask.resultError);
+ if (accessTask.resultError.trim().length() != 0) Toast.makeText(MainActivity.mContext, accessTask.resultError, Toast.LENGTH_SHORT).show();
+ else if (accessTask.accessResult.length() == 0) textViewConfiguration.setText(stringNewAutoTuneConfig);
+
+ if (unprotecting > 0) stopProtectResuming();
+ }
+ else if (iRunType == 7) textViewUserValue.setText(accessTask.accessResult);
+ else MainActivity.csLibrary4A.appendToLog("updateRunnable(): No procedure for iRunType == " + iRunType);
+ } else if (accessTask1 != null && accessTask1.isResultReady()) {
+ long duration = SystemClock.elapsedRealtime() - msStartTime;
+ textViewRunTime.setText(String.format("Run time: %.2f sec", ((float) duration / 1000))); MainActivity.csLibrary4A.appendToLog("StreamOut: End of running time");
+ MainActivity.csLibrary4A.appendToLog("access1Result = " + accessTask1.getResult() + " with iRunType = " + iRunType);
+ if (iRunType == 7) textViewUserValue.setText(accessTask1.getResult());
+ else MainActivity.csLibrary4A.appendToLog("updateRunnable(): No procedure for iRunType == " + iRunType);
+ }else {
+// MainActivity.csLibrary4A.appendToLog("updateRunnable(): rerun after 100ms with accessTask.getStatus() = " + accessTask.getStatus().toString());
+ mHandler.postDelayed(updateRunnable, 100);
+ }
+ }
+ };
+ class Data2Restore {
+ int iQuerySession;
+ int iQueryTarget;
+ byte tagDelay;
+ long dwellTime;
+ int tagFocus;
+ }
+ Data2Restore data2Restore = new Data2Restore();
+
+ @Override
+ public void onDestroy() {
+ MainActivity.csLibrary4A.abortOperation();
+ MainActivity.csLibrary4A.setSameCheck(true);
+ MainActivity.csLibrary4A.setTagGroup(MainActivity.csLibrary4A.getQuerySelect(), data2Restore.iQuerySession, data2Restore.iQueryTarget);
+ MainActivity.csLibrary4A.setTagDelay((byte)data2Restore.tagDelay);
+ MainActivity.csLibrary4A.setAntennaDwell(data2Restore.dwellTime);
+ MainActivity.csLibrary4A.setTagFocus(data2Restore.tagFocus > 0 ? true : false);
+ MainActivity.csLibrary4A.restoreAfterTagSelect();
+ super.onDestroy();
+ }
+
+ boolean userVisibleHint = false;
+ @Override
+ public void setUserVisibleHint(boolean isVisibleToUser) {
+ super.setUserVisibleHint(isVisibleToUser);
+ if(getUserVisibleHint()) {
+ userVisibleHint = true;
+ MainActivity.csLibrary4A.appendToLog("AccessImpinjFragment is now VISIBLE");
+ setupTagID();
+ } else {
+ int iValue = 0;
+ if (checkBoxTagFocus != null && checkBoxFastId != null) {
+ if (checkBoxTagFocus.isChecked()) {
+ MainActivity.csLibrary4A.setTagGroup(MainActivity.csLibrary4A.getQuerySelect(), 1, 0);
+ MainActivity.csLibrary4A.setTagDelay((byte)0);
+ MainActivity.csLibrary4A.setAntennaDwell(2000);
+ iValue |= 0x10;
+ } else MainActivity.csLibrary4A.setTagGroup(MainActivity.csLibrary4A.getQuerySelect(), 0, 2);
+ if (checkBoxFastId.isChecked()) iValue |= 0x20;
+ if (spinnerTagSelect.getSelectedItemPosition() != impinjTag.others.ordinal()) iValue |= (spinnerTagSelect.getSelectedItemPosition() + 1);
+ MainActivity.tagType = TAG_IMPINJ; /* need more tagType */ MainActivity.mDid = "E28011" + String.format("%02X", iValue);
+ MainActivity.csLibrary4A.appendToLog(String.format("HelloK: iValue = 0x%02X, mDid = %s", iValue, MainActivity.mDid));
+ MainActivity.csLibrary4A.setImpinJExtension(checkBoxTagFocus.isChecked(), checkBoxFastId.isChecked());
+ }
+ userVisibleHint = false;
+ MainActivity.csLibrary4A.appendToLog("AccessImpinjFragment is now INVISIBLE" + (checkBoxFastId != null ? (" with Value = " + iValue) : ""));
+ }
+ }
+
+ public AccessImpinjFragment(boolean b775) {
+ super("AccessImpinjFragment");
+ }
+
+ void setupTagID() {
+ ReaderDevice tagSelected = MainActivity.tagSelected;
+ boolean bSelected = false;
+ if (tagSelected != null) {
+ if (tagSelected.getSelected() == true) {
+ bSelected = true;
+ if (selectTag != null) {
+ selectTag.editTextTagID.setText(tagSelected.getAddress());
+ selectTag.spinnerSelectBank.setSelection(0);
+ }
+
+ String stringDetail = tagSelected.getDetails();
+ int indexUser = stringDetail.indexOf("USER=");
+ if (indexUser != -1) {
+ String stringUser = stringDetail.substring(indexUser + 5);
+ MainActivity.csLibrary4A.appendToLog("stringUser = " + stringUser);
+
+ boolean bEnableBAPMode = false;
+ int number = Integer.valueOf(stringUser.substring(3, 4), 16);
+ if ((number % 2) == 1) bEnableBAPMode = true;
+// CheckBox checkBoxBAP = (CheckBox) getActivity().findViewById(R.id.coldChainEnableBAP);
+// checkBoxBAP.setChecked(bEnableBAPMode);
+ }
+ }
+ }
+ }
+}
+
+
+
+package com.csl.cs710ademoapp.fragments;
+
+import androidx.lifecycle.Lifecycle;
+import android.os.AsyncTask;
+import android.os.Bundle;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.Button;
+import android.widget.CheckBox;
+import android.widget.EditText;
+import android.widget.TextView;
+import android.widget.Toast;
+
+import com.csl.cs710ademoapp.AccessTask;
+import com.csl.cs710ademoapp.MainActivity;
+import com.csl.cs710ademoapp.R;
+import com.csl.cslibrary4a.ReaderDevice;
+import com.csl.cslibrary4a.RfidReaderChipData;
+
+public class AccessKilowayFragment extends CommonFragment {
+ final boolean DEBUG = true;
+ EditText editTextRWTagID, editTextaccessRWAntennaPower;
+
+ TextView textViewOk;
+ CheckBox checkBoxRepeat, checkBox;
+ TextView textView;
+
+ private Button buttonRead;
+
+ enum ReadWriteTypes {
+ NULL, READVALUE
+ }
+ ReadWriteTypes readWriteTypes;
+
+ private AccessTask accessTask;
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ super.onCreateView(inflater, container, savedInstanceState, false);
+ return inflater.inflate(R.layout.fragment_access_kiloway, container, false);
+ }
+
+ @Override
+ public void onActivityCreated(Bundle savedInstanceState) {
+ super.onActivityCreated(savedInstanceState);
+
+ editTextRWTagID = (EditText) getActivity().findViewById(R.id.accessKilowayID);
+ editTextaccessRWAntennaPower = (EditText) getActivity().findViewById(R.id.accessLEDAntennaPower);
+
+ checkBoxRepeat = (CheckBox) getActivity().findViewById(R.id.accessKilowayRepeat);
+ textViewOk = (TextView) getActivity().findViewById(R.id.accessKilowayResultOK);
+ checkBox = (CheckBox) getActivity().findViewById(R.id.accessKilowayResultTitle);
+ textView = (TextView) getActivity().findViewById(R.id.accessKilowayResult);
+
+ buttonRead = (Button) getActivity().findViewById(R.id.accessKilowayStartButton);
+ buttonRead.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (MainActivity.csLibrary4A.isBleConnected() == false) {
+ Toast.makeText(MainActivity.mContext, R.string.toast_ble_not_connected, Toast.LENGTH_SHORT).show();
+ return;
+ } else if (MainActivity.csLibrary4A.isRfidFailure()) {
+ Toast.makeText(MainActivity.mContext, "Rfid is disabled", Toast.LENGTH_SHORT).show();
+ return;
+ }
+ startAccessTask();
+ }
+ });
+
+ MainActivity.csLibrary4A.setSameCheck(false);
+ }
+
+ @Override
+ public void onResume() {
+ super.onResume();
+ setupTagID();
+ }
+
+ @Override
+ public void onDestroy() {
+ if (accessTask != null) accessTask.cancel(true);
+ MainActivity.csLibrary4A.setSameCheck(true);
+ super.onDestroy();
+ }
+
+ @Override
+ public void setUserVisibleHint(boolean isVisibleToUser) {
+ super.setUserVisibleHint(isVisibleToUser);
+ if (getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.RESUMED) == false) return;
+ if(getUserVisibleHint()) {
+ setupTagID();
+ } else checkBoxRepeat.setChecked(false);
+ }
+
+ boolean isLongjing = false;
+ public AccessKilowayFragment(boolean isLongjing) {
+ super("AccessLedTagFragment");
+ this.isLongjing = isLongjing;
+ }
+
+ void setupTagID() {
+ ReaderDevice tagSelected = MainActivity.tagSelected;
+ if (tagSelected != null) {
+ if (tagSelected.getSelected() == true) {
+ if (editTextRWTagID != null) editTextRWTagID.setText(tagSelected.getAddress());
+ }
+ }
+ }
+
+ void startAccessTask() {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("startAccessTask()");
+ if (updating == false) {
+ updating = true; bankProcessing = 0; checkProcessing = 0;
+ mHandler.removeCallbacks(updateRunnable);
+ mHandler.post(updateRunnable);
+ }
+ }
+ boolean updating = false; int bankProcessing = 0; int checkProcessing = 0;
+ private final Runnable updateRunnable = new Runnable() {
+ @Override
+ public void run() {
+ MainActivity.csLibrary4A.appendToLog("AccessLedTagFragment(): Beginning"); ///
+ boolean rerunRequest = false; boolean taskRequest = false;
+ if (accessTask == null) {
+ taskRequest = true;
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("AccessLedTagFragment(): NULL accessReadWriteTask"); ///
+ } else if (accessTask.getStatus() != AsyncTask.Status.FINISHED) {
+ rerunRequest = true;
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("AccessLedTagFragment(): accessReadWriteTask.getStatus() = " + accessTask.getStatus().toString());
+ } else {
+ taskRequest = true;
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("AccessLedTagFragment(): FINISHED accessReadWriteTask"); ///
+ }
+ if (processResult()) {
+ rerunRequest = true; MainActivity.csLibrary4A.appendToLog("AccessLedTagFragment(): processResult is TRUE");
+ } else {
+ MainActivity.csLibrary4A.appendToLog("AccessLedTagFragment: processResult is false with taskRequest = " + taskRequest); ///
+ if (taskRequest) {
+ boolean invalid = processTickItems();
+ MainActivity.csLibrary4A.appendToLog("AccessLedTagFragment(): processTickItems with invalid = " + invalid + ", bankProcessing = " + bankProcessing + ", checkProcessing = " + checkProcessing); ///
+ if (bankProcessing++ != 0 && invalid == true) {
+ rerunRequest = true;
+ if (checkBoxRepeat != null && checkBoxRepeat.isChecked()) { bankProcessing = 0; checkProcessing = 0; }
+ else rerunRequest = false;
+ } else {
+ accessTask = new AccessTask(buttonRead, invalid, true,
+ editTextRWTagID.getText().toString(), 1, 32,
+ "00000000", Integer.valueOf(editTextaccessRWAntennaPower.getText().toString()), RfidReaderChipData.HostCommands.CMD_18K6CREAD,
+ false, null);
+ accessTask.execute();
+ rerunRequest = true;
+ MainActivity.csLibrary4A.appendToLog("AccessLedTagFragment(): accessTask is created"); ///
+ }
+ }
+ }
+ if (rerunRequest) {
+ mHandler.postDelayed(updateRunnable, 500);
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("AccessLedTagFragment(): Restart"); ///
+ }
+ else updating = false;
+ MainActivity.csLibrary4A.appendToLog("AccessLedTagFragment(): Ending with updating = " + updating); ///
+ }
+ };
+
+ boolean processResult() {
+ String accessResult = null;
+ if (accessTask == null) return false;
+ else if (accessTask.getStatus() != AsyncTask.Status.FINISHED) return false;
+ else {
+ accessResult = accessTask.accessResult;
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("AccessLedTagFragment(): accessResult = " + accessResult);
+ if (accessResult == null) {
+ if (readWriteTypes == ReadWriteTypes.READVALUE) {
+ textViewOk.setText("E");
+ }
+ } else {
+ if (readWriteTypes == ReadWriteTypes.READVALUE) {
+ textViewOk.setText("O");
+ textView.setText(accessResult);
+ readWriteTypes = ReadWriteTypes.NULL;
+ }
+ }
+ accessTask = null;
+ return true;
+ }
+ }
+
+ boolean processTickItems() {
+ boolean invalidRequest1 = false;
+ int accBank = 0, accSize = 0, accOffset = 0;
+
+ if (editTextRWTagID.getText().toString().length() == 0) invalidRequest1 = true;
+ MainActivity.csLibrary4A.appendToLog("1: invalidRequest1 = " + invalidRequest1);
+
+ if (checkBox.isChecked() == true && checkProcessing < 1) {
+ accBank = 0; accSize = 1; accOffset = 4;
+ if (isLongjing) {
+ accBank = 3; accOffset = 112;
+ }
+
+ readWriteTypes = ReadWriteTypes.READVALUE; checkProcessing = 1;
+ textViewOk.setText(""); textView.setText("");
+ } else {
+ invalidRequest1 = true;
+ }
+ MainActivity.csLibrary4A.appendToLog("2: invalidRequest1 = " + invalidRequest1);
+
+ if (invalidRequest1 == false) {
+ if (MainActivity.csLibrary4A.setAccessBank(accBank) == false) {
+ invalidRequest1 = true;
+ }
+ }
+ MainActivity.csLibrary4A.appendToLog("3: invalidRequest1 = " + invalidRequest1);
+
+ if (invalidRequest1 == false) {
+ if (MainActivity.csLibrary4A.setAccessOffset(accOffset) == false) {
+ invalidRequest1 = true;
+ }
+ }
+ MainActivity.csLibrary4A.appendToLog("4: invalidRequest1 = " + invalidRequest1);
+
+ if (invalidRequest1 == false) {
+ if (accSize == 0) {
+ invalidRequest1 = true;
+ } else if (MainActivity.csLibrary4A.setAccessCount(accSize) == false) {
+ invalidRequest1 = true;
+ }
+ }
+ MainActivity.csLibrary4A.appendToLog("5: invalidRequest1 = " + invalidRequest1);
+
+ return invalidRequest1;
+ }
+}
+
+
+
+package com.csl.cs710ademoapp.fragments;
+
+import static com.csl.cslibrary4a.RfidReader.TagType.TAG_AXZON;
+import static com.csl.cslibrary4a.RfidReader.TagType.TAG_MAGNUS_S2;
+import static com.csl.cslibrary4a.RfidReader.TagType.TAG_MAGNUS_S3;
+import static com.csl.cslibrary4a.RfidReader.TagType.TAG_AXZON_XERXES;
+
+import androidx.lifecycle.Lifecycle;
+import android.graphics.Color;
+import android.os.AsyncTask;
+import android.os.Bundle;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.AdapterView;
+import android.widget.ArrayAdapter;
+import android.widget.Button;
+import android.widget.CheckBox;
+import android.widget.EditText;
+import android.widget.Spinner;
+import android.widget.TableRow;
+import android.widget.TextView;
+import android.widget.Toast;
+
+import com.csl.cs710ademoapp.AccessTask;
+import com.csl.cs710ademoapp.GenericTextWatcher;
+import com.csl.cs710ademoapp.MainActivity;
+import com.csl.cs710ademoapp.R;
+import com.csl.cslibrary4a.ReaderDevice;
+import com.csl.cslibrary4a.RfidReaderChipData;
+
+public class AccessMicronFragment extends CommonFragment {
+ final boolean DEBUG = true;
+ boolean bXerxesEnable = false;
+ EditText editTextaccessRWSelectHoldTime, editTextRWTagID, editTextAccessRWAccPassword, editTextaccessRWAntennaPower;
+ TextView textViewSelectHoldTimeLabel, textViewConfigOk, textViewCalibrationOk, textViewAnalogPort2CodeOk, textViewAnalogPort1CodeOk, textViewSensorCodeOk, textViewRssiCodeOk, textViewTemperatureCodeOk;
+ CheckBox checkBoxConfig, checkBoxCalibration, checkBoxAnalogPort1Code, checkBoxAnalogPort2Code, checkBoxSensorCode, checkBoxRssiCode, checkBoxTemperatureCode;
+ Spinner spinnerTagType, spinnerSensorUnit, spinnerTemperatureUnit;
+ boolean btagTypeSelected = false;
+
+ TextView textViewModelCode, textViewCalibrationVersion, textViewAnalogPort1Code, textViewAnalogPort2Code, textViewSensorCode, textViewRssiCode, textViewTemperatureCode;
+ private Button buttonRead;
+
+ enum ReadWriteTypes {
+ NULL, MODELCODE, CALIBRATION, SENSORCODE, RSSICODE, TEMPERATURECODE
+ }
+ ReadWriteTypes readWriteTypes;
+ boolean operationRead = false;
+
+ private AccessTask accessTask;
+ private int modelCode = 0, selectHold = 15;
+ private int calCode1, calTemp1, calCode2, calTemp2, calVer = -1;
+ private boolean changedSelectIndex = false;
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ super.onCreateView(inflater, container, savedInstanceState, false);
+ return inflater.inflate(R.layout.fragment_access_micron, container, false);
+ }
+
+ @Override
+ public void onActivityCreated(Bundle savedInstanceState) {
+ super.onActivityCreated(savedInstanceState);
+
+ editTextRWTagID = (EditText) getActivity().findViewById(R.id.accessMNTagID);
+ editTextAccessRWAccPassword = (EditText) getActivity().findViewById(R.id.accessMNAccPasswordValue);
+ editTextAccessRWAccPassword.addTextChangedListener(new GenericTextWatcher(editTextAccessRWAccPassword, 8));
+ editTextAccessRWAccPassword.setText(MainActivity.config.configPassword);
+
+ if (MainActivity.config != null) { if (MainActivity.config.config0 != null) selectHold = Integer.parseInt(MainActivity.config.config0); }
+ EditText editText = (EditText) getActivity().findViewById(R.id.accessMNRssiUpperLimit);
+ editText.setText(MainActivity.config.config1);
+ editText = (EditText) getActivity().findViewById(R.id.accessMNRssiLowerLimit);
+ editText.setText(MainActivity.config.config2);
+ editText = (EditText) getActivity().findViewById(R.id.accessMNHumidityThreshold);
+ editText.setText(MainActivity.config.config3);
+ TableRow tableRow = (TableRow) getActivity().findViewById(R.id.accessMNHumidityThresholdRow);
+ if (MainActivity.mDid.matches("E28240")) tableRow.setVisibility(View.GONE);
+
+ textViewConfigOk = (TextView) getActivity().findViewById(R.id.accessMNModelCodeOK);
+ textViewCalibrationOk = (TextView) getActivity().findViewById(R.id.accessMNCalibrationOK);
+ textViewAnalogPort1CodeOk = (TextView) getActivity().findViewById(R.id.accessMNAnalogPort1CodeOK);
+ textViewAnalogPort2CodeOk = (TextView) getActivity().findViewById(R.id.accessMNAnalogPort2CodeOK);
+ textViewSensorCodeOk = (TextView) getActivity().findViewById(R.id.accessMNSensorCodeOK);
+ textViewRssiCodeOk = (TextView) getActivity().findViewById(R.id.accessMNRssiCodeOK);
+ textViewTemperatureCodeOk = (TextView) getActivity().findViewById(R.id.accessMNTemperatureCodeOK);
+
+ checkBoxConfig = (CheckBox) getActivity().findViewById(R.id.accessMNModelCodeTitle);
+ checkBoxCalibration = (CheckBox) getActivity().findViewById(R.id.accessMNCalibrationTitle);
+ checkBoxAnalogPort1Code = (CheckBox) getActivity().findViewById(R.id.accessMNAnalogPort1CodeTitle); checkBoxAnalogPort1Code.setEnabled(false);
+ checkBoxAnalogPort2Code = (CheckBox) getActivity().findViewById(R.id.accessMNAnalogPort2CodeTitle); checkBoxAnalogPort2Code.setEnabled(false);
+ checkBoxSensorCode = (CheckBox) getActivity().findViewById(R.id.accessMNSensorCodeTitle);
+ checkBoxRssiCode = (CheckBox) getActivity().findViewById(R.id.accessMNRssiCodeTitle);
+ checkBoxTemperatureCode = (CheckBox) getActivity().findViewById(R.id.accessMNTemperatureCodeTitle);
+
+ textViewModelCode = (TextView) getActivity().findViewById(R.id.accessMNModelCode);
+
+ textViewAnalogPort1Code = (TextView) getActivity().findViewById(R.id.accessMNAnalogPort1Code);
+ textViewAnalogPort2Code = (TextView) getActivity().findViewById(R.id.accessMNAnalogPort2Code);
+ textViewSensorCode = (TextView) getActivity().findViewById(R.id.accessMNSensorCode);
+ textViewRssiCode = (TextView) getActivity().findViewById(R.id.accessMNRssiCode);
+ textViewCalibrationVersion = (TextView) getActivity().findViewById(R.id.accessMNCalibrationVersion);
+ textViewTemperatureCode = (TextView) getActivity().findViewById(R.id.accessMNTemperatureCode);
+
+ ArrayAdapter arrayAdapterTagType;
+ if (bXerxesEnable) arrayAdapterTagType = ArrayAdapter.createFromResource(getActivity(), R.array.xerxesTag_options, R.layout.custom_spinner_layout);
+ else arrayAdapterTagType = ArrayAdapter.createFromResource(getActivity(), R.array.rfMicronTag_options, R.layout.custom_spinner_layout);
+ arrayAdapterTagType.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+ spinnerTagType = (Spinner) getActivity().findViewById(R.id.accessMNTagType);
+ spinnerTagType.setAdapter(arrayAdapterTagType);
+ spinnerTagType.setEnabled(false);
+ if (MainActivity.mDid != null) {
+ if (MainActivity.mDid.matches("E28240")) spinnerTagType.setSelection(0);
+ else if (MainActivity.mDid.matches("E282402")) spinnerTagType.setSelection(1);
+ else if (MainActivity.mDid.matches("E282403")) spinnerTagType.setSelection(2);
+ else if (MainActivity.mDid.matches("E282405")) spinnerTagType.setSelection(3);
+ }
+ spinnerTagType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
+ @Override
+ public void onItemSelected(AdapterView> adapterView, View view, int i, long l) {
+ TableRow tableRowCalibration = (TableRow) getActivity().findViewById(R.id.accessMNCalibrationRow);
+ TableRow tableRowTemperatureCode = (TableRow) getActivity().findViewById(R.id.accessMNTemperatureCodeRow);
+ TableRow tableRowAnalogPort1 = (TableRow) getActivity().findViewById(R.id.accessMNAnalogPort1CodeRow);
+ TableRow tableRowAnalogPort2 = (TableRow) getActivity().findViewById(R.id.accessMNAnalogPort2CodeRow);
+
+ switch (spinnerTagType.getSelectedItemPosition()) {
+ case 0:
+ MainActivity.tagType = TAG_AXZON; MainActivity.mDid = "E28240";
+ break;
+ case 1:
+ MainActivity.tagType = TAG_MAGNUS_S2; MainActivity.mDid = "E282402";
+ break;
+ case 2:
+ MainActivity.tagType = TAG_MAGNUS_S3; MainActivity.mDid = "E282403";
+ break;
+ case 3:
+ MainActivity.tagType = TAG_AXZON_XERXES; MainActivity.mDid = "E282405";
+ break;
+ }
+ if (btagTypeSelected) {
+ switch (spinnerTagType.getSelectedItemPosition()) {
+ case 0:
+ case 1:
+ editTextaccessRWSelectHoldTime.setText("0");
+ break;
+ case 2:
+ editTextaccessRWSelectHoldTime.setText("3");
+ break;
+ case 3:
+ editTextaccessRWSelectHoldTime.setText("9");
+ break;
+ }
+ } else btagTypeSelected = true;
+ switch (spinnerTagType.getSelectedItemPosition()) {
+ case 0:
+ case 1:
+ case 2:
+ textViewSelectHoldTimeLabel.setVisibility(View.GONE);
+ editTextaccessRWSelectHoldTime.setVisibility(View.GONE);
+ tableRowAnalogPort1.setVisibility(View.GONE);
+ tableRowAnalogPort2.setVisibility(View.GONE);
+ break;
+ case 3:
+ textViewSelectHoldTimeLabel.setVisibility(View.VISIBLE);
+ editTextaccessRWSelectHoldTime.setVisibility(View.VISIBLE);
+ tableRowAnalogPort1.setVisibility(View.VISIBLE);
+ tableRowAnalogPort2.setVisibility(View.VISIBLE);
+ break;
+ }
+ switch (spinnerTagType.getSelectedItemPosition()) {
+ case 0:
+ case 1:
+ tableRowCalibration.setVisibility(View.GONE);
+ tableRowTemperatureCode.setVisibility(View.GONE);
+ break;
+ case 2:
+ case 3:
+ tableRowCalibration.setVisibility(View.VISIBLE);
+ tableRowTemperatureCode.setVisibility(View.VISIBLE);
+ break;
+ }
+ }
+
+ @Override
+ public void onNothingSelected(AdapterView> adapterView) {
+
+ }
+ });
+
+ ArrayAdapter arrayAdapterSensorUnit = ArrayAdapter.createFromResource(getActivity(), R.array.sensor_unit_options, R.layout.custom_spinner_layout);
+ arrayAdapterSensorUnit.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+ spinnerSensorUnit = (Spinner) getActivity().findViewById(R.id.accessMNSensorUnit);
+ spinnerSensorUnit.setAdapter(arrayAdapterSensorUnit);
+ spinnerSensorUnit.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
+ @Override
+ public void onItemSelected(AdapterView> adapterView, View view, int i, long l) {
+ setSensorCode(null);
+ }
+
+ @Override
+ public void onNothingSelected(AdapterView> adapterView) {
+
+ }
+ });
+ if (MainActivity.mDid.matches("E28240")) spinnerSensorUnit.setEnabled(false);
+
+ ArrayAdapter arrayAdapterTemperatureUnit = ArrayAdapter.createFromResource(getActivity(), R.array.temperature_unit_options, R.layout.custom_spinner_layout);
+ arrayAdapterTemperatureUnit.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+ spinnerTemperatureUnit = (Spinner) getActivity().findViewById(R.id.accessMNTemperatureUnit);
+ spinnerTemperatureUnit.setAdapter(arrayAdapterTemperatureUnit);
+ spinnerTemperatureUnit.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
+ @Override
+ public void onItemSelected(AdapterView> adapterView, View view, int i, long l) {
+ setTemperatureCode(null);
+ }
+
+ @Override
+ public void onNothingSelected(AdapterView> adapterView) {
+
+ }
+ });
+
+ textViewSelectHoldTimeLabel = (TextView) getActivity().findViewById(R.id.accessMNSelectHoldTimeLabel);
+ editTextaccessRWSelectHoldTime = (EditText) getActivity().findViewById(R.id.accessMNSelectHoldTime);
+ editTextaccessRWSelectHoldTime.setText(String.valueOf(selectHold));
+
+ editTextaccessRWAntennaPower = (EditText) getActivity().findViewById(R.id.accessMNAntennaPower);
+ editTextaccessRWAntennaPower.setText(String.valueOf(MainActivity.config.configPower));
+
+ buttonRead = (Button) getActivity().findViewById(R.id.accessMNReadButton);
+ buttonRead.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (MainActivity.csLibrary4A.isBleConnected() == false) {
+ Toast.makeText(MainActivity.mContext, R.string.toast_ble_not_connected, Toast.LENGTH_SHORT).show();
+ return;
+ } else if (MainActivity.csLibrary4A.isRfidFailure()) {
+ Toast.makeText(MainActivity.mContext, "Rfid is disabled", Toast.LENGTH_SHORT).show();
+ return;
+ }
+ selectHold = Integer.parseInt(editTextaccessRWSelectHoldTime.getText().toString());
+ operationRead = true; startAccessTask();
+ }
+ });
+
+ MainActivity.csLibrary4A.setSameCheck(false);
+ }
+
+ @Override
+ public void onResume() {
+ super.onResume();
+ setupTagID();
+ }
+
+ @Override
+ public void onDestroy() {
+ if (accessTask != null) accessTask.cancel(true);
+ MainActivity.csLibrary4A.setSameCheck(true);
+ super.onDestroy();
+ }
+
+ boolean userVisibleHint = false;
+ @Override
+ public void setUserVisibleHint(boolean isVisibleToUser) {
+ super.setUserVisibleHint(isVisibleToUser);
+ if (getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.RESUMED) == false) return;
+ if(getUserVisibleHint()) {
+ userVisibleHint = true;
+ setupTagID();
+ } else {
+ userVisibleHint = false;
+
+ if (editTextaccessRWSelectHoldTime == null) return;
+ int iValue = Integer.parseInt(editTextaccessRWSelectHoldTime.getText().toString());
+ if (iValue > 255) editTextaccessRWSelectHoldTime.setText("255");
+ else if (iValue < 0) editTextaccessRWSelectHoldTime.setText("0");
+ iValue = Integer.parseInt(editTextaccessRWSelectHoldTime.getText().toString());
+ MainActivity.selectHold = iValue;
+
+ EditText editText = (EditText) getActivity().findViewById(R.id.accessMNRssiUpperLimit);
+ MainActivity.config.config1 = editText.getText().toString();
+ editText = (EditText) getActivity().findViewById(R.id.accessMNRssiLowerLimit);
+ MainActivity.config.config2 = editText.getText().toString();
+ editText = (EditText) getActivity().findViewById(R.id.accessMNHumidityThreshold);
+ MainActivity.config.config3 = editText.getText().toString();
+ }
+ }
+
+ public static AccessMicronFragment newInstance(boolean bXerxesEnable) {
+ AccessMicronFragment myFragment = new AccessMicronFragment();
+ myFragment.bXerxesEnable = bXerxesEnable;
+ return myFragment;
+ }
+ public AccessMicronFragment() {
+ super("AccessMicronFragment");
+ }
+
+ void setupTagID() {
+ ReaderDevice tagSelected = MainActivity.tagSelected;
+ boolean bSelected = false;
+ if (tagSelected != null) {
+ if (tagSelected.getSelected() == true) {
+ String stringDetail = tagSelected.getDetails();
+ int indexUser = stringDetail.indexOf("TID=");
+ if (indexUser != -1) {
+ //
+ }
+ bSelected = true;
+ if (editTextRWTagID != null) editTextRWTagID.setText(tagSelected.getAddress());
+
+ if (setModelCode(tagSelected.getTid())) {
+ textViewModelCode.setText(tagSelected.getTid().substring(5));
+ } else if (tagSelected.getMdid() == null) {
+ } else if (tagSelected.getMdid().contains("E282402")) {
+ textViewModelCode.setText("02"); modelCode = 2;
+ } else if (tagSelected.getMdid().contains("E282403")) {
+ textViewModelCode.setText("03"); modelCode = 3;
+ } else if (tagSelected.getMdid().contains("E282405")) {
+ textViewModelCode.setText("05"); modelCode = 5;
+ }
+
+ String strRes = tagSelected.getRes();
+ if (strRes != null) {
+ int ibracket = strRes.indexOf("(");
+ if (ibracket > 0) strRes = strRes.substring(0, ibracket);
+
+ if (modelCode == 5) {
+ if (strRes.length() < 4) textViewAnalogPort1Code.setText("");
+ else textViewAnalogPort1Code.setText(str2Decimal(strRes.substring(0,4)));
+ if (strRes.length() < 8) textViewAnalogPort2Code.setText("");
+ else textViewAnalogPort2Code.setText(str2Decimal(strRes.substring(4, 8)));
+ if (strRes.length() < 8) strRes = "";
+ else strRes = strRes.substring(8);
+ }
+
+ if (strRes.length() < 4) textViewSensorCode.setText("");
+ else setSensorCode(strRes.substring(0, 4));
+ if (strRes.length() < 4) strRes = "";
+ else strRes = strRes.substring(4);
+
+ if (modelCode == 2) strRes = tagSelected.getRes2();
+ if (strRes.length() < 4) textViewRssiCode.setText("");
+ else textViewRssiCode.setText(str2Decimal(strRes.substring(0, 4)));
+ if (strRes.length() < 4) strRes = "";
+ else strRes = strRes.substring(4);
+
+ if (modelCode == 3 || modelCode == 5) {
+ if (setCalibrationVersion(tagSelected.getUser()))
+ setTemperatureCode(strRes);
+ }
+ }
+
+ stringDetail = tagSelected.getDetails();
+ indexUser = stringDetail.indexOf("USER=");
+ if (indexUser != -1) {
+ String stringUser = stringDetail.substring(indexUser + 5);
+ MainActivity.csLibrary4A.appendToLog("stringUser = " + stringUser);
+
+ boolean bEnableBAPMode = false;
+ int number = Integer.valueOf(stringUser.substring(3, 4), 16);
+ if ((number % 2) == 1) bEnableBAPMode = true;
+ }
+ }
+ }
+ }
+
+ void startAccessTask() {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("startAccessTask()");
+ if (updating == false) {
+ updating = true; bankProcessing = 0;
+ checkProcessing = 0;
+ mHandler.removeCallbacks(updateRunnable);
+ mHandler.post(updateRunnable);
+ }
+ }
+ boolean updating = false; int bankProcessing = 0;
+ int checkProcessing = 0;
+ private final Runnable updateRunnable = new Runnable() {
+ @Override
+ public void run() {
+ boolean rerunRequest = false; boolean taskRequest = false;
+ if (accessTask == null) {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("AccessMicronFragment().updateRunnable(): NULL accessReadWriteTask");
+ taskRequest = true;
+ } else if (accessTask.getStatus() != AsyncTask.Status.FINISHED) {
+ rerunRequest = true;
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("AccessMicronFragment().updateRunnable(): accessReadWriteTask.getStatus() = " + accessTask.getStatus().toString());
+ } else {
+ taskRequest = true;
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("AccessMicronFragment().updateRunnable(): FINISHED accessReadWriteTask");
+ }
+ if (processResult()) { rerunRequest = true; MainActivity.csLibrary4A.appendToLog("processResult is TRUE");}
+ else if (taskRequest) {
+ boolean invalid = processTickItems();
+ MainActivity.csLibrary4A.appendToLog("processTickItems, invalid = " + invalid);
+ if (bankProcessing++ != 0 && invalid == true) rerunRequest = false;
+ else {
+ int selectBank = 1;
+ int selectOffset = 32;
+ String selectMask = editTextRWTagID.getText().toString();
+ accessTask = new AccessTask(buttonRead, null, invalid, true,
+ selectMask, selectBank, selectOffset,
+ editTextAccessRWAccPassword.getText().toString(),
+ Integer.valueOf(editTextaccessRWAntennaPower.getText().toString()),
+ (operationRead ? RfidReaderChipData.HostCommands.CMD_18K6CREAD: RfidReaderChipData.HostCommands.CMD_18K6CWRITE),
+ 0, 0, true, bSkipClearPrefilter,
+ null, null, null, null, null);
+ accessTask.execute();
+ rerunRequest = true;
+ MainActivity.csLibrary4A.appendToLog("accessTask is created with selectBank = " + selectBank);
+ }
+ }
+ if (rerunRequest) {
+ mHandler.postDelayed(updateRunnable, 500);
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("AccessMicronFragment().updateRunnable(): Restart");
+ }
+ else updating = false;
+ MainActivity.csLibrary4A.appendToLog("AccessMicronFragment().updateRunnable(): Ending with updating = " + updating);
+ }
+ };
+
+ boolean setModelCode(String strTid) {
+ if (strTid == null) return false;
+ if (strTid.length() <= 7) return false;
+ if (strTid.substring(0, 7).matches("E282401")) {
+ modelCode = 1; return true;
+ } else if (strTid.substring(0, 7).matches("E282402")) {
+ modelCode = 2; return true;
+ } else if (strTid.substring(0, 7).matches("E282403")) {
+ modelCode = 3; return true;
+ } else if (strTid.substring(0, 7).matches("E282405")) {
+ modelCode = 5; return true;
+ }
+ return false;
+ }
+ boolean setCalibrationVersion(String strUser) {
+ MainActivity.csLibrary4A.appendToLog("strUser = " + strUser);
+ textViewCalibrationVersion.setText("");
+ if (strUser == null) return false;
+ if (strUser.length() < 16) return false;
+ if (modelCode == 3) {
+ int crc = Integer.parseInt(strUser.substring(0, 4), 16);
+ calCode1 = Integer.parseInt(strUser.substring(4, 7), 16);
+ calTemp1 = Integer.parseInt(strUser.substring(7, 10), 16);
+ calTemp1 >>= 1;
+ calCode2 = Integer.parseInt(strUser.substring(9, 13), 16);
+ calCode2 >>= 1;
+ calCode2 &= 0xFFF;
+ calTemp2 = Integer.parseInt(strUser.substring(12, 16), 16);
+ calTemp2 >>= 2;
+ calTemp2 &= 0x7FF;
+ calVer = Integer.parseInt(strUser.substring(15, 16), 16);
+ calVer &= 0x3;
+ if (DEBUG)
+ MainActivity.csLibrary4A.appendToLog("crc = " + crc + ", code1 = " + calCode1 + ", temp1 = " + calTemp1 + ", code2 = " + calCode2 + ", temp2 = " + calTemp2 + ", ver = " + calVer);
+ strUser += String.format(", v%d", calVer);
+ }
+ textViewCalibrationVersion.setText(strUser);
+ return true;
+ }
+ String str2Decimal(String strData) {
+ int iTemp = -1;
+ if (strData != null) if (strData.length() >= 4) iTemp = Integer.parseInt(strData.substring(0, 4), 16);
+ if (iTemp == -1) return "";
+ return String.format("%d", iTemp);
+ }
+ boolean setRssiCode(String strData) {
+ if (strData == null) return false;
+ if (strData.length() < 4) return false;
+
+ int iTemp = Integer.parseInt(strData.substring(0,4), 16); iTemp &= 0x1F;
+ textViewRssiCode.setText(String.format("%d", iTemp)); //"%02X"
+ EditText editText = (EditText) getActivity().findViewById(R.id.accessMNRssiLowerLimit);
+ int iTempLower = Integer.parseInt(editText.getText().toString());
+ editText = (EditText) getActivity().findViewById(R.id.accessMNRssiUpperLimit);
+ int iTempUpper = Integer.parseInt(editText.getText().toString());
+ if (iTemp >= iTempLower && iTemp <= iTempUpper) textViewRssiCode.setTextColor(Color.BLACK);
+ else textViewRssiCode.setTextColor(Color.RED);
+ return true;
+ }
+
+ String strSensorCode0;
+ boolean setSensorCode(String strData) {
+ if (strData == null) {
+ if (strSensorCode0 != null && textViewSensorCode.getText().toString().length() != 0) strData = strSensorCode0;
+ else return false;
+ }
+ if (strData.length() < 4) return false;
+ strSensorCode0 = strData;
+ strData = str2Decimal(strData);
+ if (spinnerSensorUnit.getSelectedItemPosition() == 1) {
+ float fValue = (float) Integer.parseInt(strData);
+ if (true) {
+ EditText editText = (EditText) getActivity().findViewById(R.id.accessMNHumidityThreshold);
+ int iValue = Integer.parseInt(editText.getText().toString());
+ MainActivity.csLibrary4A.appendToLog("iValue for Dry/Wet comparision = " + iValue);
+ if (fValue >= iValue) strData = "dry";
+ else strData = "wet";
+ } else {
+ if (modelCode == 2) fValue /= (float) 0x1F;
+ else fValue /= (float) 0x1FF;
+ fValue *= 100;
+ strData = String.format("%.1f", fValue);
+ }
+ }
+ textViewSensorCode.setText(strData);
+ return true;
+ }
+
+ String strTemperatureCode0;
+ boolean setTemperatureCode(String strData) {
+ if (strData == null) {
+ if (strTemperatureCode0 != null && textViewTemperatureCode.getText().toString().length() != 0) strData = strTemperatureCode0;
+ else return false;
+ }
+ if (strData.length() < 4) return false;
+ float fTemperature = -500;
+ if (modelCode == 3 && calVer != -1) {
+ fTemperature = Integer.parseInt(strData.substring(0, 4), 16);
+ fTemperature = ((float) calTemp2 - (float) calTemp1) * (fTemperature - (float) calCode1);
+ fTemperature /= ((float) (calCode2) - (float) calCode1);
+ fTemperature += (float) calTemp1;
+ fTemperature -= 800;
+ fTemperature /= 10;
+ } else if (modelCode == 5) {
+ String strCalData = textViewCalibrationVersion.getText().toString();
+ if (strCalData != null) fTemperature = MainActivity.csLibrary4A.decodeMicronTemperature(5, strData, strCalData);
+ }
+ if (fTemperature != -500) {
+ if (spinnerTemperatureUnit.getSelectedItemPosition() == 1) {
+ fTemperature *= 1.8;
+ fTemperature += 32;
+ }
+ strTemperatureCode0 = strData;
+ strData = String.format("%.1f", fTemperature);
+ } else {
+ strTemperatureCode0 = null;
+ strData = "";
+ }
+ textViewTemperatureCode.setText(strData);
+ return true;
+ }
+
+ boolean processResult() {
+ String accessResult = null;
+ if (accessTask == null) return false;
+ else if (accessTask.getStatus() != AsyncTask.Status.FINISHED) return false;
+ else {
+ if (changedSelectIndex) {
+ changedSelectIndex = false; MainActivity.selectFor = 0;
+ MainActivity.csLibrary4A.setSelectCriteriaDisable(-1);
+ }
+ accessResult = accessTask.accessResult;
+ if (accessResult == null) {
+ if (readWriteTypes == ReadWriteTypes.MODELCODE) {
+ textViewConfigOk.setText("E");
+ //checkBoxConfig.setChecked(false);
+ } else if (readWriteTypes == ReadWriteTypes.CALIBRATION) {
+ textViewCalibrationOk.setText("E");
+ //checkBoxCalibration.setChecked(false);
+ } else if (readWriteTypes == ReadWriteTypes.SENSORCODE) {
+ textViewSensorCodeOk.setText("E");
+ //checkBoxSensorCode.setChecked(false);
+ } else if (readWriteTypes == ReadWriteTypes.RSSICODE) {
+ textViewRssiCodeOk.setText("E");
+ //checkBoxRssiCode.setChecked(false);
+ } else if (readWriteTypes == ReadWriteTypes.TEMPERATURECODE) {
+ textViewTemperatureCodeOk.setText("E");
+ //checkBoxTemperatureCode.setChecked(false);
+ }
+ } else {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("accessResult = " + accessResult);
+ if (readWriteTypes == ReadWriteTypes.MODELCODE) {
+ textViewConfigOk.setText("O");
+ //checkBoxConfig.setChecked(false);
+ readWriteTypes = ReadWriteTypes.NULL;
+ boolean valid = setModelCode(accessResult);
+ if (valid) textViewModelCode.setText(accessResult.substring(5));
+ else Toast.makeText(MainActivity.mContext, "This is not Micron 0X tag !!!", Toast.LENGTH_SHORT).show();
+ } else if (readWriteTypes == ReadWriteTypes.CALIBRATION) {
+ textViewCalibrationOk.setText("O");
+ //checkBoxCalibration.setChecked(false);
+ readWriteTypes = ReadWriteTypes.NULL;
+ setCalibrationVersion(accessResult);
+ } else if (readWriteTypes == ReadWriteTypes.SENSORCODE) {
+ textViewSensorCodeOk.setText("O");
+ //checkBoxSensorCode.setChecked(false);
+ readWriteTypes = ReadWriteTypes.NULL;
+ setSensorCode(accessResult);
+ } else if (readWriteTypes == ReadWriteTypes.RSSICODE) {
+ textViewRssiCodeOk.setText("O");
+ //checkBoxRssiCode.setChecked(false);
+ readWriteTypes = ReadWriteTypes.NULL;
+ setRssiCode(accessResult);
+ } else if (readWriteTypes == ReadWriteTypes.TEMPERATURECODE) {
+ textViewTemperatureCodeOk.setText("O");
+ //checkBoxTemperatureCode.setChecked(false);
+ readWriteTypes = ReadWriteTypes.NULL;
+ if (accessResult.length() >= 4) {
+ setTemperatureCode(accessResult.substring(0,4));
+ }
+ }
+ }
+ accessTask = null;
+ return true;
+ }
+ }
+
+ boolean bSkipClearPrefilter = false;
+ boolean processTickItems() {
+ boolean invalidRequest1 = false;
+ int accBank = 0, accSize = 0, accOffset = 0;
+ String writeData = "";
+
+ bSkipClearPrefilter = false;
+ if (editTextRWTagID.getText().toString().length() == 0) invalidRequest1 = true;
+ else if (checkBoxConfig.isChecked() == true && checkProcessing < 1 && operationRead) {
+ accBank = 2; accOffset = 0; accSize = 2; readWriteTypes = ReadWriteTypes.MODELCODE; checkProcessing = 1;
+ textViewConfigOk.setText(""); textViewModelCode.setText(""); modelCode = -1;
+ } else if (checkBoxCalibration.isChecked() == true && checkProcessing < 2 && operationRead && (modelCode == 3 || modelCode == 5)) {
+ accBank = 3; accSize = 4; readWriteTypes = ReadWriteTypes.CALIBRATION; checkProcessing = 2;
+ accOffset = 8; if (modelCode == 5) accOffset = 18;
+ textViewCalibrationOk.setText(""); textViewCalibrationVersion.setText(""); calVer = -1;
+ } else if (checkBoxSensorCode.isChecked() == true && modelCode != -1 && checkProcessing < 3 && operationRead) {
+ accBank = 0; if (modelCode == 1) accBank = 3;
+ accOffset = 11; if (modelCode == 3 || modelCode == 5) accOffset = 12;
+ accSize = 1; readWriteTypes = ReadWriteTypes.SENSORCODE; checkProcessing = 3;
+ textViewSensorCodeOk.setText(""); textViewSensorCode.setText("");
+ } else if (checkBoxRssiCode.isChecked() == true && modelCode != -1 && checkProcessing < 4 && operationRead) {
+ int offset = 0xA0;
+ if (modelCode == 3) offset = 0xD0;
+ else if (modelCode == 5) offset = 0x3D0;
+ bSkipClearPrefilter = true;
+ MainActivity.csLibrary4A.setSelectCriteriaDisable(-1);
+ MainActivity.csLibrary4A.setSelectCriteria(-1, true, 4, 5, selectHold,3, offset, "1F");
+ changedSelectIndex = true;
+ accBank = 0; accOffset = 13; if (modelCode == 1) { accBank = 3; accOffset = 9; }
+ accSize = 1; readWriteTypes = ReadWriteTypes.RSSICODE; checkProcessing = 4;
+ textViewRssiCodeOk.setText(""); textViewRssiCode.setText("");
+ } else if (checkBoxTemperatureCode.isChecked() == true && (modelCode == 3 || modelCode == 5) && checkProcessing < 5 && operationRead) {
+ bSkipClearPrefilter = true;
+ MainActivity.csLibrary4A.setSelectCriteriaDisable(-1);
+ if (modelCode == 3) MainActivity.csLibrary4A.setSelectCriteria(-1, true, 4, 2, 0,3, 0xE0, "");
+ else MainActivity.csLibrary4A.setSelectCriteria(-1, true, 4, 5, selectHold,3, 0x3B0, "00");
+ changedSelectIndex = true;
+ accBank = 0; accOffset = 14; accSize = 1; readWriteTypes = ReadWriteTypes.TEMPERATURECODE; checkProcessing = 5;
+ textViewTemperatureCodeOk.setText(""); textViewTemperatureCode.setText("");
+ } else {
+ invalidRequest1 = true;
+ }
+
+ if (invalidRequest1 == false) {
+ if (MainActivity.csLibrary4A.setAccessBank(accBank) == false) {
+ invalidRequest1 = true;
+ }
+ }
+ if (invalidRequest1 == false) {
+ if (MainActivity.csLibrary4A.setAccessOffset(accOffset) == false) {
+ invalidRequest1 = true;
+ }
+ }
+ if (invalidRequest1 == false) {
+ if (accSize == 0) {
+ invalidRequest1 = true;
+ } else if (MainActivity.csLibrary4A.setAccessCount(accSize) == false) {
+ invalidRequest1 = true;
+ }
+ }
+ if (invalidRequest1 == false && operationRead == false) {
+ if (invalidRequest1 == false) {
+ if (MainActivity.csLibrary4A.setAccessWriteData(writeData) == false) {
+ invalidRequest1 = true;
+ }
+ }
+ }
+ return invalidRequest1;
+ }
+}
+
+
+
+package com.csl.cs710ademoapp.fragments;
+
+import android.app.Activity;
+import android.graphics.Typeface;
+import android.os.Bundle;
+import android.os.Handler;
+import android.os.SystemClock;
+import androidx.appcompat.app.AppCompatActivity;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.AdapterView;
+import android.widget.ArrayAdapter;
+import android.widget.Button;
+import android.widget.CheckBox;
+import android.widget.EditText;
+import android.widget.Spinner;
+import android.widget.TextView;
+import android.widget.Toast;
+
+import com.csl.cs710ademoapp.AccessTask1;
+import com.csl.cs710ademoapp.CustomPopupWindow;
+import com.csl.cs710ademoapp.GenericTextWatcher;
+import com.csl.cs710ademoapp.SelectTag;
+import com.csl.cs710ademoapp.MainActivity;
+import com.csl.cs710ademoapp.R;
+import com.csl.cslibrary4a.ReaderDevice;
+import com.csl.cslibrary4a.RfidReaderChipData;
+
+import static com.csl.cs710ademoapp.MainActivity.mContext;
+import static com.csl.cs710ademoapp.MainActivity.tagSelected;
+
+public class AccessReadWriteFragment extends CommonFragment {
+ SelectTag selectTag;
+ Spinner spinnerSelectBank, spinnerRWSelectEpc1;
+ EditText editTextRWSelectOffset, editTextAccessRWAccPassword, editTextAccessRWKillPwd, editTextAccessRWAccPwd, editTextAccPc, editTextAccessRWEpc, editTExtAccessRWXpc;
+ EditText editTextTidValue, editTextUserValue, editTextEpcValue, editTextaccessRWAntennaPower;
+ TextView textViewEpcLength, textViewRunTime;
+ private Button buttonRead;
+ private Button buttonWrite;
+ Handler mHandler = new Handler();
+ String strPCValueRef = "";
+
+ String accEpcValue = ""; String accXpcValue = ""; String accTidValue = ""; String accUserValue = "";
+ enum ReadWriteTypes {
+ NULL, RESERVE, PC, EPC, XPC, TID, USER, EPC1
+ }
+ boolean operationRead = false;
+ ReadWriteTypes readWriteTypes;
+
+ private AccessTask1 accessTask;
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ super.onCreateView(inflater, container, savedInstanceState, true);
+ return inflater.inflate(R.layout.fragment_access_readwrite, container, false);
+ }
+
+ @Override
+ public void onActivityCreated(Bundle savedInstanceState) {
+ super.onActivityCreated(savedInstanceState);
+
+ androidx.appcompat.app.ActionBar actionBar;
+ actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
+ actionBar.setIcon(R.drawable.dl_access);
+ actionBar.setTitle(R.string.title_activity_readwrite);
+
+ selectTag = new SelectTag((Activity)getActivity(), 0);
+
+ spinnerSelectBank = (Spinner) getActivity().findViewById(R.id.selectMemoryBank);
+ ArrayAdapter targetAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.read_memoryBank_options, R.layout.custom_spinner_layout);
+ targetAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+ spinnerSelectBank.setAdapter(targetAdapter);
+ spinnerSelectBank.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
+ @Override
+ public void onItemSelected(AdapterView> parent, View view, int position, long id) {
+ switch (position) {
+ case 0: //if EPC
+ if (tagSelected != null) selectTag.editTextTagID.setText(tagSelected.getAddress());
+ editTextRWSelectOffset.setText("32");
+ break;
+ case 1:
+ if (tagSelected != null) { if (tagSelected.getTid() != null) selectTag.editTextTagID.setText(tagSelected.getTid()); }
+ editTextRWSelectOffset.setText("0");
+ break;
+ case 2:
+ if (tagSelected != null) { if (tagSelected.getUser() != null) selectTag.editTextTagID.setText(tagSelected.getUser()); }
+ editTextRWSelectOffset.setText("0");
+ break;
+ default:
+ break;
+ }
+ }
+
+ @Override
+ public void onNothingSelected(AdapterView> parent) {
+
+ }
+ });
+
+ editTextRWSelectOffset = (EditText) getActivity().findViewById(R.id.selectMemoryOffset);
+ spinnerRWSelectEpc1 = (Spinner) getActivity().findViewById(R.id.accessRWEpc1Title1);
+ ArrayAdapter targetAdapter1 = ArrayAdapter.createFromResource(getActivity(), R.array.memoryBank_options, R.layout.custom_spinner_layout);
+ targetAdapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+ spinnerRWSelectEpc1.setAdapter(targetAdapter1); spinnerRWSelectEpc1.setSelection(1);
+
+ editTextAccessRWAccPassword = (EditText) getActivity().findViewById(R.id.selectPasswordValue);
+ editTextAccessRWAccPassword.addTextChangedListener(new GenericTextWatcher(editTextAccessRWAccPassword, 8));
+ editTextAccessRWAccPassword.setText("00000000");
+ editTextAccessRWKillPwd = (EditText) getActivity().findViewById(R.id.accessRWKillPwdValue);
+ editTextAccessRWKillPwd.addTextChangedListener(new GenericTextWatcher(editTextAccessRWKillPwd, 8));
+ editTextAccessRWAccPwd = (EditText) getActivity().findViewById(R.id.accessRWAccPwdValue);
+ editTextAccessRWAccPwd.addTextChangedListener(new GenericTextWatcher(editTextAccessRWAccPwd, 8));
+ editTextAccPc = (EditText) getActivity().findViewById(R.id.accessRWAccPcValue);
+ editTextAccPc.setHint("PC value");
+ editTextAccPc.addTextChangedListener(new GenericTextWatcher(editTextAccPc, 4));
+ editTextAccessRWEpc = (EditText) getActivity().findViewById(R.id.accessRWAccEpcValue);
+ editTExtAccessRWXpc = (EditText) getActivity().findViewById(R.id.accessRWAccXpcValue);
+ editTextTidValue = (EditText) getActivity().findViewById(R.id.accessRWTidValue);
+ editTextTidValue.setHint("Data Pattern");
+ editTextUserValue = (EditText) getActivity().findViewById(R.id.accessRWUserValue); editTextUserValue.setTypeface(Typeface.MONOSPACE);
+ editTextUserValue.setHint("Data Pattern");
+ editTextEpcValue = (EditText) getActivity().findViewById(R.id.accessRWEpcValue);
+ editTextEpcValue.setHint("Data Pattern");
+
+ editTextaccessRWAntennaPower = (EditText) getActivity().findViewById(R.id.selectAntennaPower);
+ editTextaccessRWAntennaPower.setText(String.valueOf(300));
+
+ textViewEpcLength = (TextView) getActivity().findViewById(R.id.accessRWAccEpcLength);
+ textViewRunTime = (TextView) getActivity().findViewById(R.id.accessRWRunTime);
+
+ buttonRead = (Button) getActivity().findViewById(R.id.accessRWReadButton);
+ buttonRead.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (MainActivity.csLibrary4A.isBleConnected() == false) {
+ Toast.makeText(MainActivity.mContext, R.string.toast_ble_not_connected, Toast.LENGTH_SHORT).show();
+ return;
+ } else if (MainActivity.csLibrary4A.isRfidFailure()) {
+ Toast.makeText(MainActivity.mContext, "Rfid is disabled", Toast.LENGTH_SHORT).show();
+ return;
+ }
+ operationRead = true; startAccessTask();
+ }
+ });
+
+ buttonWrite = (Button) getActivity().findViewById(R.id.accessRWWriteButton);
+ buttonWrite.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (MainActivity.csLibrary4A.isBleConnected() == false) {
+ Toast.makeText(MainActivity.mContext, R.string.toast_ble_not_connected, Toast.LENGTH_SHORT).show();
+ return;
+ } else if (MainActivity.csLibrary4A.isRfidFailure()) {
+ Toast.makeText(MainActivity.mContext, "Rfid is disabled", Toast.LENGTH_SHORT).show();
+ return;
+ }
+ operationRead = false; startAccessTask();
+ }
+ });
+
+ ReaderDevice tagSelected = MainActivity.tagSelected;
+ if (tagSelected != null) {
+ if (tagSelected.getSelected() == true) {
+ String strEpcValue = tagSelected.getAddress();
+ String detail = tagSelected.getDetails();
+ String header = "PC=";
+ if (detail != null && detail.indexOf(header) >= 0) {
+ int index = detail.indexOf(header) + header.length();
+ strPCValueRef = detail.substring(index, index + 4);
+ updatePCEpc(strPCValueRef, strEpcValue);
+ }
+ }
+ }
+ MainActivity.csLibrary4A.setSameCheck(true);
+ }
+
+ @Override
+ public void onDestroy() {
+ if (accessTask != null) accessTask.cancel(true);
+ MainActivity.csLibrary4A.setSameCheck(true);
+ MainActivity.csLibrary4A.restoreAfterTagSelect();
+ super.onDestroy();
+ }
+
+ public AccessReadWriteFragment() {
+ super("AccessReadWriteFragment");
+ }
+
+ int getPC2EpcWordCount(String detail) {
+ String detail2 = detail.substring(0, 1);
+ int number2 = Integer.valueOf(detail2, 16) * 2;
+ String detail3 = detail.substring(1, 2);
+ int number3 = Integer.valueOf(detail3, 16);
+ if ((number3 / 8) != 0) number2 += 1;
+ return number2;
+ }
+ void updatePCEpc(String strPCValue, String strEpcValue) {
+ boolean needPopup = false;
+ if (strPCValue == null) strPCValue = "";
+ if (strPCValue.length() != 0) editTextAccPc.setText(strPCValue);
+ else strPCValue = strPCValueRef;
+ if (strPCValueRef != null && strPCValue != null) {
+ if (strPCValue.matches(strPCValueRef) == false && strPCValue.length() == 4) {
+ needPopup = true;
+ strPCValueRef = strPCValue;
+ }
+ }
+
+ int iWordCount = getPC2EpcWordCount(strPCValue);
+ textViewEpcLength.setText("EPC has " + (iWordCount * 16) + " bits");
+ if (strEpcValue != null) {
+ tagSelected.setAddress(strEpcValue); if (spinnerSelectBank.getSelectedItemPosition() == 0) selectTag.editTextTagID.setText(strEpcValue);
+ editTextAccessRWEpc.setText(strEpcValue);
+ } else {
+ if (iWordCount * 4 < selectTag.editTextTagID.getText().toString().length()) {
+ // needPopup = true;
+ String strTemp = selectTag.editTextTagID.getText().toString().substring(0, iWordCount * 4);
+ tagSelected.setAddress(strEpcValue); if (spinnerSelectBank.getSelectedItemPosition() == 0) selectTag.editTextTagID.setText(strTemp);
+ }
+ if (iWordCount * 4 < editTextAccessRWEpc.getText().toString().length()) {
+ // needPopup = true;
+ String strTemp = editTextAccessRWEpc.getText().toString().substring(0, iWordCount * 4);
+ editTextAccessRWEpc.setText(strTemp);
+ }
+ if (editTextAccessRWEpc.getText().toString().length() != 0) {
+ String strTemp = editTextAccessRWEpc.getText().toString();
+ if (selectTag.editTextTagID.getText().toString().matches(strTemp) == false) {
+ // needPopup = true;
+ tagSelected.setAddress(strTemp); if (spinnerSelectBank.getSelectedItemPosition() == 0) selectTag.editTextTagID.setText(strTemp);
+ }
+ }
+ }
+ editTextAccessRWEpc.addTextChangedListener(new GenericTextWatcher(editTextAccessRWEpc, iWordCount * 4));
+ String strTemp = editTextAccessRWEpc.getText().toString();
+ editTextAccessRWEpc.setText(strTemp);
+
+ if (needPopup) {
+ CustomPopupWindow customPopupWindow = new CustomPopupWindow(mContext);
+ customPopupWindow.popupStart("Changing EPC Length will automatically modify to " + (iWordCount * 16) + " bits.", false);
+ }
+ }
+
+ long msStartTime;
+ void startAccessTask() {
+ if (selectTag.editTextTagID.getText().toString().length() == 0) {
+ Toast.makeText(MainActivity.mContext, "Please select tag first !!!", Toast.LENGTH_SHORT).show();
+ return;
+ }
+ if (updating == false) {
+ msStartTime = SystemClock.elapsedRealtime();
+ textViewRunTime.setText("");
+ updating = true; bankProcessing = 0; restartAccessBank = -1;
+// MainActivity.mCs108Library4a.
+ mHandler.removeCallbacks(updateRunnable);
+ mHandler.post(updateRunnable);
+ }
+ }
+ boolean updating = false; int bankProcessing = 0;
+ private final Runnable updateRunnable = new Runnable() {
+ @Override
+ public void run() {
+ boolean rerunRequest = true; boolean taskRequest = false;
+ if (processResult()) { rerunRequest = true; }
+ else if (accessTask == null || accessTask.isResultReady()) {
+ bcheckBoxAll = false;
+ boolean invalid = processTickItems();
+ if (bankProcessing == 0 && bcheckBoxAll) rerunRequest = false;
+ else if (bankProcessing++ != 0 && invalid == true) rerunRequest = false;
+ else {
+ if (restartAccessBank != accessBank) {
+ restartAccessBank = accessBank;
+ restartCounter = 3;
+ }
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("AccessReadWriteFragment().InventoryRfidTask(): tagID=" + selectTag.editTextTagID.getText() + ", operationrRead=" + operationRead + ", accessBank=" + accessBank + ", accOffset=" + accOffset + ", accSize=" + accSize);
+ int selectOffset = 0;
+ selectOffset = Integer.parseInt(editTextRWSelectOffset.getText().toString());
+ EditText editTextBlockCount = (EditText) getActivity().findViewById(R.id.accessRWBlockCount);
+ Integer accBlockCount = 32;
+ try {
+ accBlockCount = Integer.parseInt(editTextBlockCount.getText().toString());
+ } catch (Exception ex) { }
+ MainActivity.csLibrary4A.appendToLog("strOut: accWriteData=" + accWriteData);
+ accessTask = new AccessTask1(
+ (operationRead ? buttonRead : buttonWrite), invalid,
+ accessBank, accOffset, accSize, accBlockCount, accWriteData,
+ selectTag.editTextTagID.getText().toString(), spinnerSelectBank.getSelectedItemPosition() + 1, selectOffset,
+ editTextAccessRWAccPassword.getText().toString(),
+ Integer.valueOf(editTextaccessRWAntennaPower.getText().toString()),
+ (operationRead ? RfidReaderChipData.HostCommands.CMD_18K6CREAD: RfidReaderChipData.HostCommands.CMD_18K6CWRITE), updateRunnable);
+ accessTask.execute();
+ rerunRequest = true;
+ }
+ }
+ if (rerunRequest) {
+ mHandler.postDelayed(updateRunnable, 100);
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("AccessReadWriteFragment().updateRunnable(): Restart");
+ }
+ else {
+ if (bankProcessing == 0 && bcheckBoxAll) {
+ Toast.makeText(MainActivity.mContext, "no choice selected yet", Toast.LENGTH_SHORT).show();
+ }
+ updating = false;
+ }
+ }
+ };
+
+ TextView textViewReserveOk, textViewPcOk, textViewEpcOk, textViewTidOk, textViewUserOk, textViewEpc1Ok;
+ CheckBox checkBoxReserve, checkBoxPc, checkBoxEpc, checkBoxTid, checkBoxUser, checkBoxEpc1;
+ int accessBank, accSize, accOffset; String accWriteData;
+ int restartCounter = 0; int restartAccessBank = -1;
+ boolean processResult() {
+ String accessResult = null;
+ if (accessTask == null) return false;
+ if (accessTask.isResultReady() == false) return false;
+ else {
+ long duration = SystemClock.elapsedRealtime() - msStartTime;
+ textViewRunTime.setText(String.format("Run time: %.2f sec", ((float) duration / 1000)));
+ accessResult = accessTask.getResult();
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("processResult(): accessResult = " + accessResult);
+ if (accessResult == null) {
+ if (readWriteTypes == ReadWriteTypes.RESERVE) {
+ textViewReserveOk.setText("E"); checkBoxReserve.setChecked(false);
+ }
+ if (readWriteTypes == ReadWriteTypes.PC) {
+ textViewPcOk.setText("E"); checkBoxPc.setChecked(false);
+ }
+ if (readWriteTypes == ReadWriteTypes.EPC) {
+ textViewEpcOk.setText("E"); checkBoxEpc.setChecked(false);
+ }
+ if (readWriteTypes == ReadWriteTypes.TID) {
+ textViewTidOk.setText("E"); checkBoxTid.setChecked(false);
+ }
+ if (readWriteTypes == ReadWriteTypes.USER) {
+ textViewUserOk.setText("E"); checkBoxUser.setChecked(false);
+ }
+ if (readWriteTypes == ReadWriteTypes.EPC1) {
+ textViewEpc1Ok.setText("E"); checkBoxEpc1.setChecked(false);
+ }
+ } else {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("accessResult = " + accessResult);
+ if (readWriteTypes == ReadWriteTypes.RESERVE) {
+ textViewReserveOk.setText("O"); checkBoxReserve.setChecked(false);
+ readWriteTypes = ReadWriteTypes.NULL;
+ if (accessResult.length() == 0 || operationRead == false) {
+ } else if (accessResult.length() < 8) {
+ editTextAccessRWKillPwd.setText(accessResult);
+ } else {
+ editTextAccessRWKillPwd.setText(accessResult.substring(0, 8));
+ }
+ if (accessResult.length() <= 8) {
+ editTextAccessRWAccPwd.setText("");
+ } else if (accessResult.length() < 16) {
+ editTextAccessRWAccPwd.setText(accessResult.subSequence(8, accessResult.length()));
+ } else {
+ editTextAccessRWAccPwd.setText(accessResult.subSequence(8, 16));
+ }
+ } else if (readWriteTypes == ReadWriteTypes.PC) {
+ textViewPcOk.setText("O"); checkBoxPc.setChecked(false);
+ readWriteTypes = ReadWriteTypes.NULL;
+ if (operationRead) {
+ String newValue = "";
+ if (accessResult.length() <= 4) {
+ newValue = accessResult.subSequence(0, accessResult.length()).toString();
+ } else {
+ newValue = accessResult.subSequence(0, 4).toString();
+ }
+ editTextAccPc.setText(newValue);
+ }
+ updatePCEpc(editTextAccPc.getText().toString(), null);
+ } else if (readWriteTypes == ReadWriteTypes.EPC) {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("AccessReadWrite(). EPC DATA with accessBank = " + accessBank + ", with accessResult.length = " + accessResult.length());
+ textViewEpcOk.setText("O"); checkBoxEpc.setChecked(false);
+ readWriteTypes = ReadWriteTypes.NULL;
+ if (operationRead) {
+ String newValue = "";
+ if (accessResult.length() <= 4) {
+ newValue = accessResult.subSequence(0, accessResult.length()).toString();
+ } else {
+ newValue = accessResult.subSequence(0, 4).toString();
+ }
+ editTextAccPc.setText(newValue);
+ }
+ updatePCEpc(editTextAccPc.getText().toString(), null);
+
+ if (operationRead) {
+ String newValue = "";
+ if (accessResult.length() > 4) {
+ newValue = accessResult.subSequence(4, accessResult.length()).toString();
+ }
+ editTextAccessRWEpc.setText(newValue);
+ }
+ } else if (readWriteTypes == ReadWriteTypes.XPC) {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("AccessReadWrite(). XPC DATA with accessBank = " + accessBank + ", with accessResult.length = " + accessResult.length() + ", with accessResult=" + accessResult);
+ readWriteTypes = ReadWriteTypes.NULL;
+ if (operationRead) {
+ String newValue = accessResult.toString();
+ editTExtAccessRWXpc.setText(newValue);
+ accXpcValue = newValue;
+ } else {
+ accXpcValue = editTExtAccessRWXpc.getText().toString();
+ }
+ } else if (readWriteTypes == ReadWriteTypes.TID) {
+ textViewTidOk.setText("O"); checkBoxTid.setChecked(false);
+ readWriteTypes = ReadWriteTypes.NULL;
+ if (accessResult.length() == 0 || operationRead == false) {
+ } else editTextTidValue.setText(accessResult);
+ } else if (readWriteTypes == ReadWriteTypes.USER) {
+ textViewUserOk.setText("O"); checkBoxUser.setChecked(false);
+ readWriteTypes = ReadWriteTypes.NULL;
+ if (operationRead) {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("AccessReadWrite(). DATA with accessBank = " + accessBank);
+ if (accessTask != null) {
+ int iLength = accessTask.deformatWriteAccessData(accessResult).length();
+ MainActivity.csLibrary4A.appendToLog("endingMessage length=" + iLength);
+ if (iLength < accSize*4) textViewUserOk.setText("H");
+ }
+ editTextUserValue.setText(accessResult);
+ accUserValue = accessResult;
+ } else {
+ accUserValue = editTextUserValue.getText().toString();
+ }
+ } else if (readWriteTypes == ReadWriteTypes.EPC1) {
+ textViewEpc1Ok.setText("O"); checkBoxEpc1.setChecked(false);
+ readWriteTypes = ReadWriteTypes.NULL;
+ if (accessResult.length() == 0 || operationRead == false) {
+ } else {
+ editTextEpcValue.setText(accessResult);
+ accEpcValue = accessResult;
+ }
+ if (operationRead == false) accEpcValue = editTextEpcValue.getText().toString();
+ }
+ accessResult = null;
+ }
+ accessTask = null;
+ return true;
+ }
+ }
+ boolean bcheckBoxAll = false;
+ boolean processTickItems() {
+ String writeData = "";
+ boolean invalidRequest1 = false;
+
+ textViewReserveOk = (TextView) getActivity().findViewById(R.id.accessRWReserveOK);
+ textViewPcOk = (TextView) getActivity().findViewById(R.id.accessRWPcOK);
+ textViewEpcOk = (TextView) getActivity().findViewById(R.id.accessRWEpcOK);
+ textViewTidOk = (TextView) getActivity().findViewById(R.id.accessRWTidOK);
+ textViewUserOk = (TextView) getActivity().findViewById(R.id.accessRWUserOK);
+ textViewEpc1Ok = (TextView) getActivity().findViewById(R.id.accessRWEpc1OK);
+
+ checkBoxReserve = (CheckBox) getActivity().findViewById(R.id.accessRWReserveTitle);
+ checkBoxPc = (CheckBox) getActivity().findViewById(R.id.accessRWPcTitle);
+ checkBoxEpc = (CheckBox) getActivity().findViewById(R.id.accessRWEpcTitle);
+ checkBoxTid = (CheckBox) getActivity().findViewById(R.id.accessRWTidTitle);
+ checkBoxUser = (CheckBox) getActivity().findViewById(R.id.accessRWUserTitle);
+ checkBoxEpc1 = (CheckBox) getActivity().findViewById(R.id.accessRWEpc1);
+
+ if (checkBoxReserve.isChecked() == true) {
+ textViewReserveOk.setText("");
+ accessBank = 0; accOffset = 0; accSize = 4; readWriteTypes = ReadWriteTypes.RESERVE;
+ if (operationRead) {
+ editTextAccessRWKillPwd.setText("");
+ editTextAccessRWAccPwd.setText("");
+ } else {
+ String strValue = editTextAccessRWKillPwd.getText().toString();
+ String strValue1 = editTextAccessRWAccPwd.getText().toString();
+ if (strValue.length() != 8 || strValue1.length() != 8) {
+ invalidRequest1 = true;
+ } else {
+ writeData = strValue + strValue1;
+ }
+ }
+ } else if (checkBoxPc.isChecked() == true || ((checkBoxEpc.isChecked() == true) && (strPCValueRef.length() != 4) )) {
+ textViewPcOk.setText("");
+ accessBank = 1; accOffset = 1; accSize = 1; readWriteTypes = ReadWriteTypes.PC;
+ if (operationRead) {
+ editTextAccPc.setText("");
+ } else {
+ String strValue = editTextAccPc.getText().toString();
+ if (strValue.length() != 4) invalidRequest1 = true;
+ else writeData = strValue;
+ }
+ } else if (checkBoxEpc.isChecked() == true) {
+ textViewEpcOk.setText("");
+ accessBank = 1; accOffset = 1; accSize = 0; readWriteTypes = ReadWriteTypes.EPC;
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("processTickItems(): start EPC operation");
+ if (operationRead) {
+ if (strPCValueRef.length() != 4) accSize = 1;
+ else {
+ accSize = getPC2EpcWordCount(strPCValueRef) + 1;
+ editTextAccessRWEpc.setText("");
+ }
+ } else {
+ String strValue = editTextAccPc.getText().toString();
+ String strValue1 = editTextAccessRWEpc.getText().toString();
+ if (strValue1.length() == 0) {
+ if (strValue.length() != 4) invalidRequest1 = true;
+ else {
+ accSize = 1;
+ writeData = strValue;
+ }
+ } else {
+ accSize += strValue1.length() / 4;
+ if (strValue1.length() % 4 != 0) accSize++;
+ if (strValue.length() == 4) {
+ int iPCWordCount = getPC2EpcWordCount(strValue);
+ if (iPCWordCount < accSize) accSize = iPCWordCount;
+ accSize++;
+ writeData = strValue + strValue1;
+ } else {
+ accOffset = 2;
+ writeData = strValue1;
+ }
+ }
+ }
+ } else if (checkBoxTid.isChecked() == true) {
+ textViewTidOk.setText("");
+ accessBank = 2; accOffset = 0; accSize = 0; readWriteTypes = ReadWriteTypes.TID;
+ EditText editTextTidValue = (EditText) getActivity().findViewById(R.id.accessRWTidValue);
+ if (operationRead) {
+ int iValue = 0;
+ try {
+ EditText editTextTidOffset = (EditText) getActivity().findViewById(R.id.accessRWTidOffset);
+ iValue = Integer.parseInt(editTextTidOffset.getText().toString());
+ } catch (Exception ex) {
+ }
+ accOffset = iValue;
+ iValue = 0;
+ try {
+ EditText editTextTidLength = (EditText) getActivity().findViewById(R.id.accessRWTidLength);
+ iValue = Integer.parseInt(editTextTidLength.getText().toString());
+ } catch (Exception ex) {
+ }
+ accSize = iValue;
+ editTextTidValue.setText("");
+ } else {
+ invalidRequest1 = true;
+ editTextTidValue.setText("");
+
+ }
+ } else if (checkBoxUser.isChecked() == true) {
+ textViewUserOk.setText("");
+ accessBank = 3; accOffset = 0; accSize = 0; readWriteTypes = ReadWriteTypes.USER;
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("processTickItems(): start USER operation");
+ int iValue = 0;
+ try {
+ EditText editTextTidOffset = (EditText) getActivity().findViewById(R.id.accessRWUserOffset);
+ iValue = Integer.parseInt(editTextTidOffset.getText().toString());
+ } catch (Exception ex) {
+ }
+ accOffset = iValue;
+ iValue = 0;
+ try {
+ EditText editTextUserLength = (EditText) getActivity().findViewById(R.id.accessRWUserLength);
+ iValue = Integer.parseInt(editTextUserLength.getText().toString());
+ } catch (Exception ex) {
+ }
+ accSize = iValue;
+ if (operationRead) {
+ editTextUserValue.setText("");
+ } else {
+ String strValue = editTextUserValue.getText().toString();
+ MainActivity.csLibrary4A.appendToLog("strOut: strValue=" + strValue + ", strValue.length=" + strValue.length() + ", accUserValue=" + accUserValue + ", accUserValue.lengt=" + accUserValue.length());
+ if (strValue.length() >= 4 && accUserValue.matches(strValue) == false) {
+ writeData = strValue;
+ }
+ }
+ } else if (checkBoxEpc1.isChecked() == true) {
+ textViewEpc1Ok.setText("");
+ accessBank = spinnerRWSelectEpc1.getSelectedItemPosition(); accOffset = 0; accSize = 0; readWriteTypes = ReadWriteTypes.EPC1;
+ int iValue = 0;
+ try {
+ EditText editTextEpcOffset = (EditText) getActivity().findViewById(R.id.accessRWEpcOffset);
+ iValue = Integer.parseInt(editTextEpcOffset.getText().toString());
+ } catch (Exception ex) {
+ }
+ accOffset = iValue;
+ iValue = 0;
+ try {
+ EditText editTextEpcLength = (EditText) getActivity().findViewById(R.id.accessRWEpcLength);
+ iValue = Integer.parseInt(editTextEpcLength.getText().toString());
+ } catch (Exception ex) {
+ }
+ accSize = iValue;
+ if (operationRead) {
+ editTextEpcValue.setText("");
+ } else {
+ String strValue = editTextEpcValue.getText().toString();
+ if (strValue.length() >= 4 && strValue.matches(accEpcValue) == false) {
+ accSize = strValue.length() / 4;
+ if (strValue.length() %4 != 0) accSize++;
+ writeData = strValue;
+ }
+ }
+ } else {
+ invalidRequest1 = true;
+ bcheckBoxAll = true;
+ }
+
+ if (restartAccessBank == accessBank) {
+ if (restartCounter == 0) invalidRequest1 = true;
+ else restartCounter--;
+ }
+ accWriteData = writeData;
+ return invalidRequest1;
+ }
+}
+
+
+
+package com.csl.cs710ademoapp.fragments;
+
+import android.app.Activity;
+import android.graphics.Typeface;
+import android.os.Bundle;
+import android.os.Handler;
+import android.os.SystemClock;
+import androidx.appcompat.app.AppCompatActivity;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.AdapterView;
+import android.widget.ArrayAdapter;
+import android.widget.Button;
+import android.widget.CheckBox;
+import android.widget.EditText;
+import android.widget.Spinner;
+import android.widget.TableRow;
+import android.widget.TextView;
+import android.widget.Toast;
+
+import com.csl.cs710ademoapp.AccessTask1;
+import com.csl.cs710ademoapp.CustomPopupWindow;
+import com.csl.cs710ademoapp.GenericTextWatcher;
+import com.csl.cs710ademoapp.SelectTag;
+import com.csl.cs710ademoapp.MainActivity;
+import com.csl.cs710ademoapp.R;
+import com.csl.cslibrary4a.ReaderDevice;
+import com.csl.cslibrary4a.RfidReaderChipData;
+
+import static com.csl.cs710ademoapp.MainActivity.mContext;
+import static com.csl.cs710ademoapp.MainActivity.tagSelected;
+
+public class AccessReadWriteUserFragment extends CommonFragment {
+ SelectTag selectTag;
+ Spinner spinnerSelectBank, spinnerRWSelectBank;
+ EditText editTextRWSelectOffset, editTextAccessRWAccPassword, editTextAccessRWKillPwd, editTextAccessRWAccPwd, editTextAccPc, editTextAccessRWEpc;
+ EditText editTextUserValue, editTextEpcValue, editTextaccessRWAntennaPower;
+ TextView textViewEpcLength, textViewRunTime;
+ private Button buttonRead;
+ private Button buttonWrite;
+ Handler mHandler = new Handler();
+ String strPCValueRef = "";
+
+ String accEpcValue = ""; String accUserValue = "";
+ enum ReadWriteTypes {
+ NULL, USER, SBANK
+ }
+ boolean operationRead = false;
+ ReadWriteTypes readWriteTypes;
+
+ private AccessTask1 accessTask;
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ super.onCreateView(inflater, container, savedInstanceState, true);
+ return inflater.inflate(R.layout.fragment_access_readwrite, container, false);
+ }
+
+ @Override
+ public void onActivityCreated(Bundle savedInstanceState) {
+ super.onActivityCreated(savedInstanceState);
+
+ androidx.appcompat.app.ActionBar actionBar;
+ actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
+ actionBar.setIcon(R.drawable.dl_access);
+ actionBar.setTitle(R.string.title_activity_readWriteUser);
+
+ selectTag = new SelectTag((Activity)getActivity(), 0);
+ spinnerSelectBank = (Spinner) getActivity().findViewById(R.id.selectMemoryBank);
+ ArrayAdapter targetAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.read_memoryBank_options, R.layout.custom_spinner_layout);
+ targetAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+ spinnerSelectBank.setAdapter(targetAdapter);
+ spinnerSelectBank.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
+ @Override
+ public void onItemSelected(AdapterView> parent, View view, int position, long id) {
+ switch (position) {
+ case 0: //if EPC
+ if (tagSelected != null) selectTag.editTextTagID.setText(tagSelected.getAddress());
+ editTextRWSelectOffset.setText("32");
+ break;
+ case 1:
+ if (tagSelected != null) { if (tagSelected.getTid() != null) selectTag.editTextTagID.setText(tagSelected.getTid()); }
+ editTextRWSelectOffset.setText("0");
+ break;
+ case 2:
+ if (tagSelected != null) { if (tagSelected.getUser() != null) selectTag.editTextTagID.setText(tagSelected.getUser()); }
+ editTextRWSelectOffset.setText("0");
+ break;
+ default:
+ break;
+ }
+ }
+
+ @Override
+ public void onNothingSelected(AdapterView> parent) {
+
+ }
+ });
+
+ TableRow tableRow = (TableRow) getActivity().findViewById(R.id.accessRWReserveTitleRow);
+ tableRow.setVisibility(View.GONE);
+ tableRow = (TableRow) getActivity().findViewById(R.id.accessRWReserveValueRow);
+ tableRow.setVisibility(View.GONE);
+ tableRow = (TableRow) getActivity().findViewById(R.id.accessRWPcTitleRow);
+ tableRow.setVisibility(View.GONE);
+ tableRow = (TableRow) getActivity().findViewById(R.id.accessRWEpcTitleRow);
+ tableRow.setVisibility(View.GONE);
+ tableRow = (TableRow) getActivity().findViewById(R.id.accessRWTidTitleRow);
+ tableRow.setVisibility(View.GONE);
+ tableRow = (TableRow) getActivity().findViewById(R.id.accessRWTidValueRow);
+ tableRow.setVisibility(View.GONE);
+ tableRow = (TableRow) getActivity().findViewById(R.id.accessRWAnyTitleRow);
+ tableRow.setVisibility(View.GONE);
+ tableRow = (TableRow) getActivity().findViewById(R.id.accessRWAnyValueRow);
+ tableRow.setVisibility(View.GONE);
+
+ editTextRWSelectOffset = (EditText) getActivity().findViewById(R.id.selectMemoryOffset);
+ spinnerRWSelectBank = (Spinner) getActivity().findViewById(R.id.accessRWEpc1Title1);
+ ArrayAdapter targetAdapter1 = ArrayAdapter.createFromResource(getActivity(), R.array.memoryBank_options, R.layout.custom_spinner_layout);
+ targetAdapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+ spinnerRWSelectBank.setAdapter(targetAdapter1); spinnerRWSelectBank.setSelection(1);
+
+ editTextAccessRWAccPassword = (EditText) getActivity().findViewById(R.id.selectPasswordValue);
+ editTextAccessRWAccPassword.addTextChangedListener(new GenericTextWatcher(editTextAccessRWAccPassword, 8));
+ editTextAccessRWAccPassword.setText("00000000");
+ editTextAccessRWKillPwd = (EditText) getActivity().findViewById(R.id.accessRWKillPwdValue);
+ editTextAccessRWKillPwd.addTextChangedListener(new GenericTextWatcher(editTextAccessRWKillPwd, 8));
+ editTextAccessRWAccPwd = (EditText) getActivity().findViewById(R.id.accessRWAccPwdValue);
+ editTextAccessRWAccPwd.addTextChangedListener(new GenericTextWatcher(editTextAccessRWAccPwd, 8));
+ editTextAccPc = (EditText) getActivity().findViewById(R.id.accessRWAccPcValue);
+ editTextAccPc.setHint("PC value");
+ editTextAccPc.addTextChangedListener(new GenericTextWatcher(editTextAccPc, 4));
+ editTextAccessRWEpc = (EditText) getActivity().findViewById(R.id.accessRWAccEpcValue);
+ EditText editTextBlockCount = (EditText) getActivity().findViewById(R.id.accessRWBlockCount);
+ editTextBlockCount.setText("48");
+ EditText editTextUserLength = (EditText) getActivity().findViewById(R.id.accessRWUserLength);
+ editTextUserLength.setText("512");
+ editTextUserValue = (EditText) getActivity().findViewById(R.id.accessRWUserValue); editTextUserValue.setTypeface(Typeface.MONOSPACE);
+ editTextUserValue.setHint("Data Pattern");
+ editTextEpcValue = (EditText) getActivity().findViewById(R.id.accessRWEpcValue);
+ editTextEpcValue.setHint("Data Pattern");
+
+ editTextaccessRWAntennaPower = (EditText) getActivity().findViewById(R.id.selectAntennaPower);
+ editTextaccessRWAntennaPower.setText(String.valueOf(300));
+
+ textViewEpcLength = (TextView) getActivity().findViewById(R.id.accessRWAccEpcLength);
+ textViewRunTime = (TextView) getActivity().findViewById(R.id.accessRWRunTime);
+
+ buttonRead = (Button) getActivity().findViewById(R.id.accessRWReadButton);
+ buttonRead.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (MainActivity.csLibrary4A.isBleConnected() == false) {
+ Toast.makeText(MainActivity.mContext, R.string.toast_ble_not_connected, Toast.LENGTH_SHORT).show();
+ return;
+ } else if (MainActivity.csLibrary4A.isRfidFailure()) {
+ Toast.makeText(MainActivity.mContext, "Rfid is disabled", Toast.LENGTH_SHORT).show();
+ return;
+ }
+ operationRead = true; startAccessTask();
+ }
+ });
+
+ buttonWrite = (Button) getActivity().findViewById(R.id.accessRWWriteButton);
+ buttonWrite.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (MainActivity.csLibrary4A.isBleConnected() == false) {
+ Toast.makeText(MainActivity.mContext, R.string.toast_ble_not_connected, Toast.LENGTH_SHORT).show();
+ return;
+ } else if (MainActivity.csLibrary4A.isRfidFailure()) {
+ Toast.makeText(MainActivity.mContext, "Rfid is disabled", Toast.LENGTH_SHORT).show();
+ return;
+ }
+ operationRead = false; startAccessTask();
+ }
+ });
+
+ ReaderDevice tagSelected = MainActivity.tagSelected;
+ if (tagSelected != null) {
+ if (tagSelected.getSelected() == true) {
+ String strEpcValue = tagSelected.getAddress();
+ String detail = tagSelected.getDetails();
+ String header = "PC=";
+ int index = detail.indexOf(header) + header.length();
+ strPCValueRef = detail.substring(index, index + 4);
+ updatePCEpc(strPCValueRef, strEpcValue);
+ }
+ }
+ MainActivity.csLibrary4A.setSameCheck(true);
+ }
+
+ @Override
+ public void onDestroy() {
+ if (accessTask != null) accessTask.cancel(true);
+ MainActivity.csLibrary4A.setSameCheck(true);
+ MainActivity.csLibrary4A.restoreAfterTagSelect();
+ super.onDestroy();
+ }
+
+ public AccessReadWriteUserFragment() {
+ super("AccessReadWriteUserFragment");
+ }
+
+ int getPC2EpcWordCount(String detail) {
+ String detail2 = detail.substring(0, 1);
+ int number2 = Integer.valueOf(detail2, 16) * 2;
+ String detail3 = detail.substring(1, 2);
+ int number3 = Integer.valueOf(detail3, 16);
+ if ((number3 / 8) != 0) number2 += 1;
+ return number2;
+ }
+ void updatePCEpc(String strPCValue, String strEpcValue) {
+ boolean needPopup = false;
+ if (strPCValue == null) strPCValue = "";
+ if (strPCValue.length() != 0) editTextAccPc.setText(strPCValue);
+ else strPCValue = strPCValueRef;
+ if (strPCValueRef != null && strPCValue != null) {
+ if (strPCValue.matches(strPCValueRef) == false && strPCValue.length() == 4) {
+ needPopup = true;
+ strPCValueRef = strPCValue;
+ }
+ }
+
+ int iWordCount = getPC2EpcWordCount(strPCValue);
+ textViewEpcLength.setText("EPC has " + (iWordCount * 16) + " bits");
+ if (strEpcValue != null) {
+ tagSelected.setAddress(strEpcValue); if (spinnerSelectBank.getSelectedItemPosition() == 0) selectTag.editTextTagID.setText(strEpcValue);
+ editTextAccessRWEpc.setText(strEpcValue);
+ } else {
+ if (iWordCount * 4 < selectTag.editTextTagID.getText().toString().length()) {
+ // needPopup = true;
+ String strTemp = selectTag.editTextTagID.getText().toString().substring(0, iWordCount * 4);
+ tagSelected.setAddress(strEpcValue); if (spinnerSelectBank.getSelectedItemPosition() == 0) selectTag.editTextTagID.setText(strTemp);
+ }
+ if (iWordCount * 4 < editTextAccessRWEpc.getText().toString().length()) {
+ // needPopup = true;
+ String strTemp = editTextAccessRWEpc.getText().toString().substring(0, iWordCount * 4);
+ editTextAccessRWEpc.setText(strTemp);
+ }
+ if (editTextAccessRWEpc.getText().toString().length() != 0) {
+ String strTemp = editTextAccessRWEpc.getText().toString();
+ if (selectTag.editTextTagID.getText().toString().matches(strTemp) == false) {
+ // needPopup = true;
+ tagSelected.setAddress(strEpcValue); if (spinnerSelectBank.getSelectedItemPosition() == 0) selectTag.editTextTagID.setText(strTemp);
+ }
+ }
+ }
+ editTextAccessRWEpc.addTextChangedListener(new GenericTextWatcher(editTextAccessRWEpc, iWordCount * 4));
+ String strTemp = editTextAccessRWEpc.getText().toString();
+ editTextAccessRWEpc.setText(strTemp);
+
+ if (needPopup) {
+ CustomPopupWindow customPopupWindow = new CustomPopupWindow(mContext);
+ customPopupWindow.popupStart("Changing EPC Length will automatically modify to " + (iWordCount * 16) + " bits.", false);
+ }
+ }
+
+ long msStartTime;
+ void startAccessTask() {
+ if (selectTag.editTextTagID.getText().toString().length() == 0) {
+ Toast.makeText(MainActivity.mContext, "Please select tag first !!!", Toast.LENGTH_SHORT).show();
+ return;
+ }
+ CheckBox checkBox = (CheckBox) getActivity().findViewById(R.id.accessRWUserTitle);
+ checkBox.setChecked(true);
+ if (updating == false) {
+ msStartTime = SystemClock.elapsedRealtime();
+ textViewRunTime.setText(""); MainActivity.csLibrary4A.appendToLog("StreamOut: Start of running time");
+ updating = true; bankProcessing = 0; restartAccessBank = -1;
+ mHandler.removeCallbacks(updateRunnable);
+ mHandler.post(updateRunnable);
+ }
+ }
+ boolean updating = false; int bankProcessing = 0;
+ private final Runnable updateRunnable = new Runnable() {
+ @Override
+ public void run() {
+ boolean rerunRequest = true; boolean taskRequest = false;
+ if (processResult()) { rerunRequest = true; }
+ else if (accessTask == null || accessTask.isResultReady()) {
+ bcheckBoxAll = false;
+ boolean invalid = processTickItems();
+ if (bankProcessing == 0 && bcheckBoxAll) rerunRequest = false;
+ else if (bankProcessing++ != 0 && invalid == true) rerunRequest = false;
+ else {
+ if (restartAccessBank != accessBank) {
+ restartAccessBank = accessBank;
+ restartCounter = 3;
+ }
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("AccessReadWriteUserFragment().InventoryRfidTask(): tagID=" + selectTag.editTextTagID.getText() + ", operationrRead=" + operationRead + ", accessBank=" + accessBank + ", accOffset=" + accOffset + ", accSize=" + accSize);
+ int selectOffset = 0;
+ selectOffset = Integer.parseInt(editTextRWSelectOffset.getText().toString());
+ EditText editTextBlockCount = (EditText) getActivity().findViewById(R.id.accessRWBlockCount);
+ Integer accBlockCount = 32;
+ try {
+ accBlockCount = Integer.parseInt(editTextBlockCount.getText().toString());
+ } catch (Exception ex) { }
+ MainActivity.csLibrary4A.appendToLog("strOut: accWriteData=" + accWriteData);
+ accessTask = new AccessTask1(
+ (operationRead ? buttonRead : buttonWrite), invalid,
+ accessBank, accOffset, accSize, accBlockCount, accWriteData,
+ selectTag.editTextTagID.getText().toString(), spinnerSelectBank.getSelectedItemPosition() + 1, selectOffset,
+ editTextAccessRWAccPassword.getText().toString(),
+ Integer.valueOf(editTextaccessRWAntennaPower.getText().toString()),
+ (operationRead ? RfidReaderChipData.HostCommands.CMD_18K6CREAD: RfidReaderChipData.HostCommands.CMD_18K6CWRITE), updateRunnable);
+ accessTask.execute();
+ rerunRequest = true;
+ }
+ }
+ if (rerunRequest) {
+ mHandler.postDelayed(updateRunnable, 100);
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("AccessReadWriteUserFragment().updateRunnable(): Restart");
+ }
+ else {
+ if (bankProcessing == 0 && bcheckBoxAll) {
+ Toast.makeText(MainActivity.mContext, "no choice selected yet", Toast.LENGTH_SHORT).show();
+ }
+ updating = false;
+ }
+ }
+ };
+
+ TextView textViewUserOk, textViewBankOk;
+ CheckBox checkBoxUser, checkBoxBank;
+ int accessBank, accSize, accOffset; String accWriteData;
+ int restartCounter = 0; int restartAccessBank = -1;
+ boolean processResult() {
+ String accessResult = null;
+ if (accessTask == null) return false;
+ if (accessTask.isResultReady() == false) return false;
+ else {
+ long duration = SystemClock.elapsedRealtime() - msStartTime;
+ textViewRunTime.setText(String.format("Run time: %.2f sec", ((float) duration / 1000))); MainActivity.csLibrary4A.appendToLog("StreamOut: End of running time");
+ accessResult = accessTask.getResult();
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("processResult(): accessResult = " + accessResult);
+ if (accessResult == null) {
+ if (readWriteTypes == ReadWriteTypes.USER) {
+ textViewUserOk.setText("E"); checkBoxUser.setChecked(false);
+ }
+ if (readWriteTypes == ReadWriteTypes.SBANK) {
+ textViewBankOk.setText("E"); checkBoxBank.setChecked(false);
+ }
+ } else {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("accessResult = " + accessResult);
+ if (readWriteTypes == ReadWriteTypes.USER) {
+ textViewUserOk.setText("O"); checkBoxUser.setChecked(false);
+ readWriteTypes = ReadWriteTypes.NULL;
+ if (operationRead) {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("AccessReadWrite(). DATA with accessBank = " + accessBank);
+ if (accessTask != null) {
+ int iLength = accessTask.deformatWriteAccessData(accessResult).length();
+ MainActivity.csLibrary4A.appendToLog("endingMessage length=" + iLength);
+ if (iLength < accSize*4) textViewUserOk.setText("H");
+ }
+ editTextUserValue.setText(accessResult);
+ accUserValue = accessResult;
+ } else {
+ accUserValue = editTextUserValue.getText().toString();
+ }
+ } else if (readWriteTypes == ReadWriteTypes.SBANK) {
+ textViewBankOk.setText("O"); checkBoxBank.setChecked(false);
+ readWriteTypes = ReadWriteTypes.NULL;
+ if (accessResult.length() == 0 || operationRead == false) {
+ } else {
+ editTextEpcValue.setText(accessResult);
+ accEpcValue = accessResult;
+ }
+ if (operationRead == false) accEpcValue = editTextEpcValue.getText().toString();
+ }
+ accessResult = null;
+ }
+ accessTask = null;
+ return true;
+ }
+ }
+ boolean bcheckBoxAll = false;
+ boolean processTickItems() {
+ String writeData = "";
+ boolean invalidRequest1 = false;
+
+ textViewUserOk = (TextView) getActivity().findViewById(R.id.accessRWUserOK);
+ textViewBankOk = (TextView) getActivity().findViewById(R.id.accessRWEpc1OK);
+
+ checkBoxUser = (CheckBox) getActivity().findViewById(R.id.accessRWUserTitle);
+ checkBoxBank = (CheckBox) getActivity().findViewById(R.id.accessRWEpc1);
+
+ if (checkBoxUser.isChecked() == true) {
+ textViewUserOk.setText("");
+ accessBank = 3; accOffset = 0; accSize = 0; readWriteTypes = ReadWriteTypes.USER;
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("processTickItems(): start USER operation");
+ int iValue = 0;
+ try {
+ EditText editTextTidOffset = (EditText) getActivity().findViewById(R.id.accessRWUserOffset);
+ iValue = Integer.parseInt(editTextTidOffset.getText().toString());
+ } catch (Exception ex) {
+ }
+ accOffset = iValue;
+ iValue = 0;
+ try {
+ EditText editTextUserLength = (EditText) getActivity().findViewById(R.id.accessRWUserLength);
+ iValue = Integer.parseInt(editTextUserLength.getText().toString());
+ } catch (Exception ex) {
+ }
+ accSize = iValue;
+ if (operationRead) {
+ editTextUserValue.setText("");
+ } else {
+ String strValue = editTextUserValue.getText().toString();
+ MainActivity.csLibrary4A.appendToLog("strOut: strValue=" + strValue + ", strValue.length=" + strValue.length() + ", accUserValue=" + accUserValue + ", accUserValue.lengt=" + accUserValue.length());
+ if (strValue.length() >= 4 && accUserValue.matches(strValue) == false) {
+ writeData = strValue;
+ }
+ }
+ } else if (checkBoxBank.isChecked() == true) {
+ textViewBankOk.setText("");
+ accessBank = spinnerRWSelectBank.getSelectedItemPosition(); accOffset = 0; accSize = 0; readWriteTypes = ReadWriteTypes.SBANK;
+ int iValue = 0;
+ try {
+ EditText editTextEpcOffset = (EditText) getActivity().findViewById(R.id.accessRWEpcOffset);
+ iValue = Integer.parseInt(editTextEpcOffset.getText().toString());
+ } catch (Exception ex) {
+ }
+ accOffset = iValue;
+ iValue = 0;
+ try {
+ EditText editTextEpcLength = (EditText) getActivity().findViewById(R.id.accessRWEpcLength);
+ iValue = Integer.parseInt(editTextEpcLength.getText().toString());
+ } catch (Exception ex) {
+ }
+ accSize = iValue;
+ if (operationRead) {
+ editTextEpcValue.setText("");
+ } else {
+ String strValue = editTextEpcValue.getText().toString();
+ if (strValue.length() >= 4 && strValue.matches(accEpcValue) == false) {
+ accSize = strValue.length() / 4;
+ if (strValue.length() %4 != 0) accSize++;
+ writeData = strValue;
+ }
+ }
+ } else {
+ invalidRequest1 = true;
+ bcheckBoxAll = true;
+ }
+
+ if (restartAccessBank == accessBank) {
+ if (restartCounter == 0) invalidRequest1 = true;
+ else restartCounter--;
+ }
+ accWriteData = writeData;
+ return invalidRequest1;
+ }
+}
+
+
+
+package com.csl.cs710ademoapp.fragments;
+
+import static com.csl.cs710ademoapp.MainActivity.mContext;
+
+import android.graphics.Color;
+import android.os.AsyncTask;
+import android.os.Bundle;
+import androidx.appcompat.app.ActionBar;
+import androidx.appcompat.app.AppCompatActivity;
+import android.text.Editable;
+import android.text.TextWatcher;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.AdapterView;
+import android.widget.ArrayAdapter;
+import android.widget.Button;
+import android.widget.CheckBox;
+import android.widget.CompoundButton;
+import android.widget.EditText;
+import android.widget.Spinner;
+import android.widget.TableRow;
+import android.widget.TextView;
+import android.widget.Toast;
+
+import com.csl.cs710ademoapp.AccessTask;
+import com.csl.cs710ademoapp.CustomPopupWindow;
+import com.csl.cs710ademoapp.InventoryBarcodeTask;
+import com.csl.cs710ademoapp.InventoryRfidTask;
+import com.csl.cs710ademoapp.MainActivity;
+import com.csl.cs710ademoapp.R;
+import com.csl.cslibrary4a.NotificationConnector;
+import com.csl.cslibrary4a.ReaderDevice;
+import com.csl.cslibrary4a.RfidReaderChipData;
+import com.csl.cslibrary4a.Utility;
+
+import java.util.ArrayList;
+
+public class AccessRegisterFragment extends CommonFragment {
+ CustomPopupWindow customPopupWindow;
+
+ TableRow tableRowSelectMask, tableRowSelectBank;
+ Spinner spinnerSelectBank, spinnerAccessBank, spinnerWriteEpcClass, spinnerWriteDataType;
+ EditText editTextSelectMask, editTextSelectPopulation, editTextPassword, editTextAntennaPower, editTextWriteData, editTextWriteLength;
+ CheckBox checkBoxWriteLengthEnable;
+ TextView textViewSelectedTags, textViewWriteCount, textViewRunTime, textViewTagGot, textViewVoltageLevel;
+ TextView textViewYield, textViewTotal;
+ Button buttonSelect, buttonClearSelect, buttonReadBar, buttonWrite;
+
+ InventoryRfidTask inventoryRfidTask;
+ InventoryBarcodeTask inventoryBarcodeTask;
+ AccessTask accessTask;
+
+ ReaderDevice tagSelected = MainActivity.tagSelected;
+ boolean newWriteData;
+ String writeValueOld = "";
+ int iAutoRun = 0;
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ super.onCreateView(inflater, container, savedInstanceState, true);
+ return inflater.inflate(R.layout.fragment_access_register, container, false);
+ }
+
+ @Override
+ public void onActivityCreated(Bundle savedInstanceState) {
+ super.onActivityCreated(savedInstanceState);
+
+ ActionBar actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
+ actionBar.setIcon(R.drawable.dl_access);
+ actionBar.setTitle(R.string.title_activity_registertag);
+
+ customPopupWindow = new CustomPopupWindow(mContext);
+
+ tableRowSelectMask = (TableRow) getActivity().findViewById(R.id.registerSelectMaskRow);
+ tableRowSelectBank = (TableRow) getActivity().findViewById(R.id.registerSelectBankRow);
+
+ spinnerSelectBank = (Spinner) getActivity().findViewById(R.id.registerSelectBank);
+ ArrayAdapter targetAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.read_memoryBank_options, R.layout.custom_spinner_layout);
+ targetAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+ spinnerSelectBank.setAdapter(targetAdapter);
+ spinnerSelectBank.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
+ @Override
+ public void onItemSelected(AdapterView> parent, View view, int position, long id) {
+ switch (position) {
+ case 0: //if EPC
+ if (tagSelected != null) editTextSelectMask.setText(tagSelected.getAddress());
+ break;
+ case 1:
+ if (tagSelected != null) { if (tagSelected.getTid() != null) editTextSelectMask.setText(tagSelected.getTid()); }
+ break;
+ case 2:
+ if (tagSelected != null) { if (tagSelected.getUser() != null) editTextSelectMask.setText(tagSelected.getUser()); }
+ break;
+ default:
+ break;
+ }
+ }
+
+ @Override
+ public void onNothingSelected(AdapterView> parent) {
+
+ }
+ });
+
+ spinnerAccessBank = (Spinner) getActivity().findViewById(R.id.registerAccessBank);
+ targetAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.write_memoryBank_options, R.layout.custom_spinner_layout);
+ targetAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+ spinnerAccessBank.setAdapter(targetAdapter);
+
+ spinnerWriteEpcClass = (Spinner) getActivity().findViewById(R.id.registerWriteEpcClass);
+ targetAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.write_Epc_options, R.layout.custom_spinner_layout);
+ targetAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+ spinnerWriteEpcClass.setAdapter(targetAdapter);
+ spinnerWriteEpcClass.setEnabled(false);
+
+ spinnerWriteDataType = (Spinner) getActivity().findViewById(R.id.registerWriteDataType);
+ targetAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.write_data_options, R.layout.custom_spinner_layout);
+ targetAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+ spinnerWriteDataType.setAdapter(targetAdapter);
+
+ Button buttonConfirm = (Button) getActivity().findViewById(R.id.registerConfirm2Button);
+ buttonConfirm.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View view) {
+ Toast.makeText(MainActivity.mContext, "Step 2 data is confirmed.", Toast.LENGTH_SHORT).show();
+ }
+ });
+
+ editTextSelectMask = (EditText) getActivity().findViewById(R.id.registerSelectMask);
+ editTextSelectPopulation = (EditText) getActivity().findViewById(R.id.registerSelectPopulation);
+ editTextPassword = (EditText) getActivity().findViewById(R.id.registerPassword);
+ editTextPassword.setText("00000000");
+ editTextAntennaPower = (EditText) getActivity().findViewById(R.id.registerAntennaPower);
+ editTextWriteData = (EditText) getActivity().findViewById(R.id.registerWriteData);
+ editTextWriteData.setEnabled(true);
+// editTextBarValue.setText("19dec163");
+ newWriteData = false; editTextWriteData.setTextColor(Color.RED);
+ editTextWriteData.addTextChangedListener(new TextWatcher() {
+ @Override
+ public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { }
+
+ @Override
+ public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { }
+
+ @Override
+ public void afterTextChanged(Editable editable) {
+ String writeValue = editTextWriteData.getText().toString().trim();
+ if (true) newWriteData = true;
+ if (writeValue.matches(writeValueOld) == false) {
+ writeValueOld = writeValue;
+ editTextWriteData.setTextColor(Color.BLACK);
+ //checkBoxNewValue.setEnabled(true);
+ //checkBoxNewValue.setText("Reset to old value");
+ newWriteData = true;
+ }
+
+ if (inventoryBarcodeTask != null) {
+ if (inventoryBarcodeTask.getStatus() == AsyncTask.Status.RUNNING) {
+ barcodeReadDone = true; MainActivity.csLibrary4A.appendToLog("barcodeReadDone = true in textChanged");
+ MainActivity.csLibrary4A.appendToLog("going to startStopBarcodeHandler 1"); startStopBarcodeHandler(false);
+ }
+ }
+ if (checkBoxWriteLengthEnable.isChecked() == false) {
+ int length1 = writeValue.length() * 4;
+ int length = length1 / 16;
+ if (length * 16 != length1) length++;
+ editTextWriteLength.setText(String.valueOf(length));
+ }
+ }
+ });
+ editTextWriteLength = (EditText) getActivity().findViewById(R.id.registerWriteLength);
+
+ checkBoxWriteLengthEnable = (CheckBox) getActivity().findViewById(R.id.registerWriteLengthEnable);
+ checkBoxWriteLengthEnable.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
+ @Override
+ public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
+ if (isChecked) editTextWriteLength.setEnabled(true);
+ else editTextWriteLength.setEnabled(false);
+ }
+ });
+
+ buttonClearSelect = (Button) getActivity().findViewById(R.id.registerClearSelectButton);
+ buttonClearSelect.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View view) {
+ tagSelected = null;
+ editTextSelectMask.setText("");
+ }
+ });
+
+ buttonSelect = (Button) getActivity().findViewById(R.id.registerSelectButton);
+ buttonSelect.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View view) {
+ if (buttonSelect.getText().toString().contains("Clear")) {
+ buttonClearSelect.setVisibility(View.VISIBLE);
+ tableRowSelectMask.setVisibility(View.VISIBLE);
+ tableRowSelectBank.setVisibility(View.VISIBLE);
+ textViewSelectedTags.setText("");
+ buttonSelect.setText("Read");
+ } else if (buttonSelect.getText().toString().contains("Stop")) {
+ inventoryRfidTask.taskCancelReason = InventoryRfidTask.TaskCancelRReason.BUTTON_RELEASE;
+ mHandler.removeCallbacks(runnableSelect);
+ textViewSelectedTags.setText("");
+ for (int i = 0; i < epcArrayList.size(); i++) {
+ MainActivity.csLibrary4A.appendToLog("epcArrayList.get[" + i + "] = " + epcArrayList.get(i));
+ textViewSelectedTags.append(epcArrayList.get(i) + "\n");
+ }
+ if (textViewSelectedTags.getText().toString().trim().length() == 0) {
+ buttonSelect.setText("Read");
+ } else {
+ buttonClearSelect.setVisibility(View.GONE);
+ tableRowSelectMask.setVisibility(View.GONE);
+ tableRowSelectBank.setVisibility(View.GONE);
+ buttonSelect.setText("Clear");
+ }
+ }
+ else {
+ textViewSelectedTags.setText("");
+ String strTagId = editTextSelectMask.getText().toString();
+ int selectBank = spinnerSelectBank.getSelectedItemPosition() + 1;
+ long pwrlevel = Integer.parseInt(editTextAntennaPower.getText().toString());
+ MainActivity.csLibrary4A.setTagRead(0);
+ MainActivity.csLibrary4A.setSelectedTag(strTagId, selectBank, pwrlevel);
+ MainActivity.csLibrary4A.appendToLog("Debug_Compact: AccessRegisterFragment.onActivityCreated.onClick");
+ MainActivity.csLibrary4A.startOperation(RfidReaderChipData.OperationTypes.TAG_INVENTORY);
+ inventoryRfidTask = new InventoryRfidTask();
+ inventoryRfidTask.execute();
+ MainActivity.sharedObjects.serviceArrayList.clear(); epcArrayList.clear();
+ mHandler.post(runnableSelect); buttonSelect.setText("Stop");
+ }
+ }
+ });
+
+ Button buttonConvert = (Button) getActivity().findViewById(R.id.registerWriteConvert);
+ buttonConvert.setOnClickListener(new View.OnClickListener() {
+ EditText editTextWriteEpcFilter = (EditText) getActivity().findViewById(R.id.registerWriteEpcFilter);
+ EditText editTextWriteEpcCompanyPrefix = (EditText) getActivity().findViewById(R.id.registerWriteEpcCompanyPrefix);
+ EditText editTextWriteEpcItemReference = (EditText) getActivity().findViewById(R.id.registerWriteEpcItemReference);
+ EditText editTextWriteEpcSerial = (EditText) getActivity().findViewById(R.id.registerWriteEpcSerial);
+ @Override
+ public void onClick(View view) {
+ String strValue = MainActivity.csLibrary4A.getEpc4upcSerial(
+ Utility.EpcClass.values()[spinnerWriteEpcClass.getSelectedItemPosition()],
+ editTextWriteEpcFilter.getText().toString(),
+ editTextWriteEpcCompanyPrefix.getText().toString(),
+ editTextWriteEpcItemReference.getText().toString(),
+ editTextWriteEpcSerial.getText().toString()
+ );
+ if (strValue != null) editTextWriteData.setText(strValue);
+ }
+ });
+
+ buttonReadBar = (Button) getActivity().findViewById(R.id.registerReadBarButton);
+ buttonReadBar.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View view) {
+ MainActivity.csLibrary4A.appendToLog("going to startStopBarcodeHandler 2"); startStopBarcodeHandler(false);
+ }
+ });
+
+ textViewSelectedTags = (TextView) getActivity().findViewById(R.id.registerSelectedTags);
+ //textViewWriteCount = (TextView) getActivity().findViewById(R.id.registerWrittenCount);
+ textViewRunTime = (TextView) getActivity().findViewById(R.id.registerRunTime);
+ textViewTagGot = (TextView) getActivity().findViewById(R.id.registetTagGotView);
+ textViewVoltageLevel = (TextView) getActivity().findViewById(R.id.registerVoltageLevel);
+
+ buttonWrite = (Button) getActivity().findViewById(R.id.registerWriteButton);
+ buttonWrite.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View view) {
+ if (buttonWrite.getText().toString().trim().length() == 0) return;
+ runningAuto123 = 0; startStopAccessHandler(false);
+ }
+ });
+
+ Button buttonWrite3 = (Button) getActivity().findViewById(R.id.registerWrite3Button);
+ buttonWrite3.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View view) {
+ if (accessTask != null) if (accessTask.getStatus() == AsyncTask.Status.RUNNING) return;
+ runningAuto123 = 0; startStopAccessHandler(false);
+ }
+ });
+
+ Button buttonAuto = (Button) getActivity().findViewById(R.id.registerAutoButton);
+ buttonAuto.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View view) {
+ if (accessTask != null) if (accessTask.getStatus() == AsyncTask.Status.RUNNING) return;
+ runningAuto123 = 1; startStopAccessHandler(false);
+ }
+ });
+
+ Button buttonAuto123 = (Button) getActivity().findViewById(R.id.registerAutoButtonWBarcodeRead);
+ buttonAuto123.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View view) {
+ if (accessTask != null) if (accessTask.getStatus() == AsyncTask.Status.RUNNING) return;
+ runningAuto123 = 2; mHandler.post(runnableAuto123);
+ }
+ });
+
+ textViewYield = (TextView) getActivity().findViewById(R.id.registerYieldView);
+ textViewTotal = (TextView) getActivity().findViewById(R.id.registerTotalView);
+
+ Button buttonResetCount = (Button) getActivity().findViewById(R.id.registerResetCountButton);
+ buttonResetCount.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View view) {
+ resetCount = true;
+ textViewRunTime.setText(""); textViewTagGot.setText(""); textViewVoltageLevel.setText("");
+ textViewYield.setText(""); textViewTotal.setText("");
+ }
+ });
+
+ MainActivity.csLibrary4A.setSameCheck(false);
+ }
+
+ @Override
+ public void onResume() {
+ super.onResume();
+ setNotificationListener();
+ }
+
+ @Override
+ public void onPause() {
+ MainActivity.csLibrary4A.setNotificationListener(null);
+ super.onPause();
+ }
+
+ @Override
+ public void onDestroy() {
+ MainActivity.csLibrary4A.setNotificationListener(null);
+ mHandler.removeCallbacks(runnableSelect);
+ mHandler.removeCallbacks(runnableAuto123);
+ if (inventoryBarcodeTask != null) inventoryBarcodeTask.taskCancelReason = InventoryBarcodeTask.TaskCancelRReason.DESTORY;
+ if (accessTask != null) accessTask.taskCancelReason = AccessTask.TaskCancelRReason.DESTORY;
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("AcccessRegisterFragment().onDestory(): onDestory()");
+ MainActivity.csLibrary4A.setSameCheck(true);
+ MainActivity.csLibrary4A.restoreAfterTagSelect();
+ super.onDestroy();
+ }
+
+ public AccessRegisterFragment() {
+ super("AccessRegisterFragment");
+ }
+
+ void setNotificationListener() {
+ MainActivity.csLibrary4A.setNotificationListener(new NotificationConnector.NotificationListener() {
+ @Override
+ public void onChange() {
+ MainActivity.csLibrary4A.appendToLog("TRIGGER key is pressed.");
+ if (barcodeReadRequesting) {
+ if (customPopupWindow.popupWindow.isShowing()) {
+ customPopupWindow.popupWindow.dismiss();
+ barcodeReadRequesting = false; MainActivity.csLibrary4A.appendToLog("barcodeReadRequesting = false");
+ ready2nextRun = true; MainActivity.csLibrary4A.appendToLog("ready2nextRun 1 = true after popup");
+ }
+ }
+ }
+ });
+ }
+
+ ArrayList epcArrayList = new ArrayList();
+ Runnable runnableSelect = new Runnable() {
+ @Override
+ public void run() {
+ while (MainActivity.sharedObjects.serviceArrayList.size() != 0) {
+ String strEpc = MainActivity.sharedObjects.serviceArrayList.get(0); MainActivity.sharedObjects.serviceArrayList.remove(0);
+ MainActivity.csLibrary4A.appendToLog("epcArrayList.add[" + epcArrayList.size() + "] = " + strEpc);
+ boolean matched = false;
+ for (int i = 0; i < epcArrayList.size(); i++) {
+ if (epcArrayList.get(i).matches(strEpc)) {
+ matched = true;
+ break;
+ }
+ }
+ if (matched == false && strEpc != null) {
+ epcArrayList.add(strEpc);
+ }
+ }
+ textViewSelectedTags.setText("unique tag number = " + epcArrayList.size());
+ mHandler.postDelayed(runnableSelect, 1000);
+ }
+ };
+
+ boolean ready2nextRun = true, barcodeReadRequesting = false, barcodeReadDone = false;
+ boolean runningAccessTask = false; int runningAuto123 = 0, totalTag = 0;
+ Runnable runnableAuto123 = new Runnable() {
+ @Override
+ public void run() {
+ boolean running = false;
+ MainActivity.csLibrary4A.appendToLog("found barcodeReadRequesting as " + barcodeReadRequesting );
+ if (barcodeReadRequesting) {
+ if (customPopupWindow.popupWindow.isShowing()) running = true;
+ else {
+ barcodeReadRequesting = false; MainActivity.csLibrary4A.appendToLog("barcodeReadRequesting = false");
+ ready2nextRun = true; MainActivity.csLibrary4A.appendToLog("ready2nextRun 1 = true after popup");
+ }
+ }
+ MainActivity.csLibrary4A.appendToLog("runnableAuto123: runningAuto123 = " + runningAuto123 + ", inventoryBarcodeTask = " + (inventoryBarcodeTask != null ? "valid" : "null"));
+ if (runningAuto123 == 2 && inventoryBarcodeTask != null) { if (inventoryBarcodeTask.getStatus() == AsyncTask.Status.RUNNING) running = true; }
+ MainActivity.csLibrary4A.appendToLog("runnableAuto123: accessTask = " + (accessTask != null ? "valid" : "null"));
+ if (accessTask != null) { if (accessTask.getStatus() == AsyncTask.Status.RUNNING) running = true; }
+ MainActivity.csLibrary4A.appendToLog("runnableAuto123: running = " + running);
+ if (running == false) {
+ int totalTagNew = getTotalTag();
+ if (runningAccessTask) {
+ if (totalTagNew > totalTag) {
+ if (spinnerWriteDataType.getSelectedItemPosition() == 2) editTextWriteData.setText(incrementString(editTextWriteData.getText().toString()));
+ } else runningAuto123 = 0;
+ }
+ MainActivity.csLibrary4A.appendToLog("runnableAuto123: totalTagNew = " + totalTagNew + ", totalTag = " + totalTag + ", runningAuto123 = " + runningAuto123 + ", runningAccessTask = " + runningAccessTask);
+ runningAccessTask = false;
+
+ boolean bcontinue = true;
+ if (spinnerWriteDataType.getSelectedItemPosition() == 1 && ready2nextRun == false) {
+ if (buttonSelect.getText().toString().contains("Clear")) {
+ if (textViewSelectedTags.getText().toString().trim().length() == 0) bcontinue = false;
+ }
+ if (bcontinue) {
+ customPopupWindow.popupStart("Next barcode.", false);
+ barcodeReadRequesting = true; MainActivity.csLibrary4A.appendToLog("barcodeReadRequesting = true");
+ barcodeReadDone = false; MainActivity.csLibrary4A.appendToLog("barcodeReadDone = false as popup");
+ bcontinue = false;
+ running = true;
+ }
+ }
+ if (bcontinue) {
+ if (ready2nextRun == false) {
+ if (buttonSelect.getText().toString().contains("Clear")) {
+ if (textViewSelectedTags.getText().toString().trim().length() != 0) {
+ ready2nextRun = true; MainActivity.csLibrary4A.appendToLog("ready2nextRun = true as valid selected tag in textview");
+ }
+ } else {
+ ready2nextRun = true; MainActivity.csLibrary4A.appendToLog("ready2nextRun = true as not clear");
+ }
+ }
+ if (ready2nextRun) {
+ if (startStopAccessHandler(false)) running = true;
+ }
+ }
+ }
+ if (running && runningAuto123 == 2) mHandler.postDelayed(runnableAuto123, 250);
+ else {
+ ready2nextRun = true; MainActivity.csLibrary4A.appendToLog("ready2nextRun = true at the runnable end");
+ barcodeReadRequesting = false; barcodeReadDone = false; MainActivity.csLibrary4A.appendToLog("barcodeReadDone = false at the runnable end");
+ }
+ }
+ };
+
+ String incrementString(String string1) {
+ for (int i = 0; i < string1.length(); i++) {
+ String string2 = string1.substring(string1.length() - 1 - i, string1.length() - i);
+ Integer iValue = Integer.valueOf(string2, 16);
+ if (++iValue >= 16) iValue = 0;
+ String stringA = string1.substring(0, string1.length() - 1 - i);
+ String stringB = String.format("%X", iValue);
+ String stringC = null;
+ if (i > 0) stringC = string1.substring(string1.length() - i, string1.length());
+ MainActivity.csLibrary4A.appendToLog("stringABC = " + stringA + "," + stringB + "," + stringC);
+ String stringABC = (stringA != null ? stringA : "") + stringB + (stringC != null ? stringC : "");
+ string1 = stringABC;
+ if (iValue != 0) break;
+ }
+ return string1;
+ }
+
+ int getTotalTag() {
+ int iValue = 0;
+ String stringTotal = textViewTotal.getText().toString();
+ String stringTotalTag = stringTotal.replaceAll("[^0-9.]", "");
+ try {
+ iValue = Integer.parseInt(stringTotalTag);
+ } catch (Exception ex) {
+ }
+ MainActivity.csLibrary4A.appendToLog("totalTag = " + iValue);
+ return iValue;
+ }
+
+ void startStopBarcodeHandler(boolean buttonTrigger) {
+ if (MainActivity.sharedObjects.runningInventoryRfidTask) {
+ Toast.makeText(MainActivity.mContext, "Running RFID access", Toast.LENGTH_SHORT).show();
+ return;
+ }
+
+ boolean started = false;
+ if (inventoryBarcodeTask != null) if (inventoryBarcodeTask.getStatus() == AsyncTask.Status.RUNNING) started = true;
+ if (buttonTrigger && ((started && MainActivity.csLibrary4A.getTriggerButtonStatus()) || (started == false && MainActivity.csLibrary4A.getTriggerButtonStatus() == false))) return;
+ if (started == false) {
+ if (MainActivity.csLibrary4A.isBleConnected() == false) {
+ Toast.makeText(MainActivity.mContext, R.string.toast_ble_not_connected, Toast.LENGTH_SHORT).show();
+ return;
+ }
+ if (MainActivity.csLibrary4A.isBarcodeFailure()) {
+ MainActivity.csLibrary4A.appendToLog("Toasted 'Barcode is disable'");
+ Toast.makeText(MainActivity.mContext, "Barcode is disabled", Toast.LENGTH_SHORT).show();
+ return;
+ }
+ boolean noToast = true; //runningAuto123;
+ inventoryBarcodeTask = new InventoryBarcodeTask(null, null, editTextWriteData, null, null, null, buttonReadBar, buttonWrite, null, noToast);
+ inventoryBarcodeTask.execute();
+ } else inventoryBarcodeTask.taskCancelReason = InventoryBarcodeTask.TaskCancelRReason.STOP;
+ }
+
+ boolean startStopAccessHandler(boolean buttonTrigger) {
+ boolean runningBarcode = false;
+ if (inventoryBarcodeTask != null) {
+ if (inventoryBarcodeTask.getStatus() == AsyncTask.Status.RUNNING) {
+ MainActivity.csLibrary4A.appendToLog("going to startStopBarcodeHandler 1"); startStopBarcodeHandler(buttonTrigger);
+ runningBarcode = true;
+ }
+ }
+
+ boolean runningAccessTask = false;
+ if (accessTask != null) { if (accessTask.getStatus() == AsyncTask.Status.RUNNING) runningAccessTask = true; }
+ if (buttonTrigger && ((runningAccessTask && MainActivity.csLibrary4A.getTriggerButtonStatus()) || (runningAccessTask == false && MainActivity.csLibrary4A.getTriggerButtonStatus() == false))) {
+ return true;
+ }
+
+ boolean validResult = true;
+ if (runningBarcode) { }
+ else if (runningAccessTask) {
+ if (buttonTrigger) accessTask.taskCancelReason = AccessTask.TaskCancelRReason.BUTTON_RELEASE;
+ else accessTask.taskCancelReason = AccessTask.TaskCancelRReason.STOP;
+ } else {
+ if (MainActivity.csLibrary4A.isBleConnected() == false) {
+ Toast.makeText(MainActivity.mContext, R.string.toast_ble_not_connected, Toast.LENGTH_SHORT).show();
+ validResult = false;
+ } else if (MainActivity.csLibrary4A.isRfidFailure()) {
+ Toast.makeText(MainActivity.mContext, "Rfid is disabled", Toast.LENGTH_SHORT).show();
+ validResult = false;
+ } else if (MainActivity.csLibrary4A.mrfidToWriteSize() != 0) {
+ Toast.makeText(MainActivity.mContext, R.string.toast_not_ready, Toast.LENGTH_SHORT).show();
+ validResult = false;
+ }
+
+ if (validResult) {
+ if (barcodeReadDone == false && spinnerWriteDataType.getSelectedItemPosition() == 1) {
+ MainActivity.csLibrary4A.appendToLog("going to startStopBarcodeHandler 2");
+ startStopBarcodeHandler(buttonTrigger);
+ } else {
+ totalTag = getTotalTag();
+ if (startAccessTask()) validResult = false;
+ else if (runningAuto123 == 2) this.runningAccessTask = true;
+ MainActivity.csLibrary4A.appendToLog("runningAccessTask = " + this.runningAccessTask);
+ resetOldValue();
+ ready2nextRun = false;
+ MainActivity.csLibrary4A.appendToLog("ready2nextRun = false after startStopAccessHandler");
+ }
+ }
+ }
+ return validResult;
+ }
+
+ void resetOldValue() {
+ editTextWriteData.setTextColor(Color.RED);
+ /*checkBoxNewValue.setEnabled(false);
+ checkBoxNewValue.setText("Old value");
+ checkBoxNewValue.setChecked(false);*/
+ newWriteData = false;
+ }
+
+ boolean resetCount = true;
+ boolean startAccessTask() {
+ boolean invalidRequest1 = false;
+
+ int selectQValue = -1, selectPopulation = -1;
+ try {
+ selectPopulation = Integer.parseInt(editTextSelectPopulation.getText().toString());
+ } catch (Exception ex) { }
+ if (selectPopulation < 0) invalidRequest1 = true;
+ else if (selectPopulation <= getTotalTag()) invalidRequest1 = true;
+ else {
+ selectQValue = MainActivity.csLibrary4A.getPopulation2Q(selectPopulation);
+ if (selectQValue < 0) invalidRequest1 = true;
+ }
+ MainActivity.csLibrary4A.appendToLog("selectQValue = " + selectQValue + ", selectPopulation = " + selectPopulation);
+
+ String selectMask = "";
+ int selectBank1 = -1;
+ int selectOffset1 = -1;
+ if (buttonSelect.getText().toString().contains("Clear")) {
+ String[] stringSplited = textViewSelectedTags.getText().toString().split("\n", 2);
+ if (stringSplited != null && stringSplited.length > 0 && stringSplited[0] != null && stringSplited[0].trim().length() != 0) {
+ selectMask = stringSplited[0].trim();
+ selectBank1 = 1;
+ selectOffset1 = 32;
+ if (stringSplited.length > 1 && stringSplited[1] != null && stringSplited[1].trim().length() != 0) textViewSelectedTags.setText(stringSplited[1].trim());
+ else textViewSelectedTags.setText("");
+ }
+ } else {
+ selectMask = editTextSelectMask.getText().toString().trim();
+ int selectBankPosition = spinnerSelectBank.getSelectedItemPosition();
+ selectBank1 = selectBankPosition + 1;
+ int selectOffset = 0;
+ try {
+ EditText editTextSelectOffset = (EditText) getActivity().findViewById(R.id.registerSelectOffset);
+ selectOffset = Integer.parseInt(editTextSelectOffset.getText().toString());
+ } catch (Exception ex) { }
+ selectOffset1 = selectBankPosition == 0 ? selectOffset + 32 : selectOffset;
+ }
+ if (selectMask.trim().length() == 0 || selectBank1 < 0 || selectOffset1 < 0) {
+ invalidRequest1 = true;
+ }
+
+ String password = editTextPassword.getText().toString();
+ if (password.length() != 8) invalidRequest1 = true;
+
+ int antennaPower = -1;
+ try {
+ editTextAntennaPower = (EditText) getActivity().findViewById(R.id.registerAntennaPower);
+ antennaPower = Integer.parseInt(editTextAntennaPower.getText().toString());
+ } catch (Exception ex) { }
+ if (antennaPower < 0) invalidRequest1 = true;
+
+ int accessBank = spinnerAccessBank.getSelectedItemPosition() == 0 ? 1 : 3;
+ MainActivity.csLibrary4A.appendToLog("accessBank = " + accessBank);
+ if (invalidRequest1 == false) {
+ if (MainActivity.csLibrary4A.setAccessBank(accessBank) == false) invalidRequest1 = true;
+ }
+
+ int writeOffset = -1;
+ try {
+ EditText editTextWriteOffset = (EditText) getActivity().findViewById(R.id.registerWriteOffset);
+ writeOffset = Integer.parseInt(editTextWriteOffset.getText().toString());
+ if (spinnerAccessBank.getSelectedItemPosition() == 0) writeOffset += 2;
+ } catch (Exception ex) { }
+ if (writeOffset < 0) invalidRequest1 = true;
+ MainActivity.csLibrary4A.appendToLog("writeOffset = " + writeOffset);
+ if (invalidRequest1 == false) {
+ if (MainActivity.csLibrary4A.setAccessOffset(writeOffset) == false) invalidRequest1 = true;
+ }
+
+ int writeLength = -1;
+ try {
+ writeLength = Integer.parseInt(editTextWriteLength.getText().toString());
+ } catch (Exception ex) { }
+ if (writeLength < 0) invalidRequest1 = true;
+ MainActivity.csLibrary4A.appendToLog("writeLength = " + writeLength);
+ if (invalidRequest1 == false) {
+ if (writeLength == 0) invalidRequest1 = true;
+ else if (MainActivity.csLibrary4A.setAccessCount(writeLength) == false) {
+ invalidRequest1 = true;
+ }
+ }
+
+ String writeData = editTextWriteData.getText().toString().trim();
+ if (writeData.length() == 0) invalidRequest1 = true;
+ MainActivity.csLibrary4A.appendToLog("writeData = " + writeData);
+ if (invalidRequest1 == false) {
+ if (MainActivity.csLibrary4A.setAccessWriteData(writeData) == false) {
+ invalidRequest1 = true;
+ }
+ }
+
+ int repeatCount = 0;
+ if (runningAuto123 == 1) repeatCount = selectPopulation;
+
+ MainActivity.csLibrary4A.appendToLog("invalidRequest1 = " + invalidRequest1
+ + ", selectMask = " + selectMask + ", selectBank1 = " + selectBank1 + ", selectOffset1 = " + selectOffset1
+ + ", password = " + password + ", power = " + antennaPower + ", repeatCount = " + repeatCount + ", resetCount = " + resetCount);
+ accessTask = new AccessTask(buttonWrite, textViewWriteCount, invalidRequest1, true,
+ selectMask, selectBank1, selectOffset1,
+ password, antennaPower, RfidReaderChipData.HostCommands.CMD_18K6CWRITE,
+ selectQValue, repeatCount, resetCount, false,
+ textViewRunTime, textViewTagGot, textViewVoltageLevel, textViewYield, textViewTotal);
+ accessTask.execute();
+ resetCount = false;
+ return invalidRequest1;
+ }
+}
+
+
+
+package com.csl.cs710ademoapp.fragments;
+
+import android.os.Bundle;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+
+import androidx.appcompat.app.ActionBar;
+import androidx.appcompat.app.AppCompatActivity;
+import androidx.viewpager.widget.ViewPager;
+
+import com.csl.cs710ademoapp.MainActivity;
+import com.csl.cs710ademoapp.R;
+import com.csl.cslibrary4a.AdapterTab;
+import com.google.android.material.tabs.TabLayout;
+
+public class AccessSecurityFragment extends CommonFragment {
+ private ActionBar actionBar;
+ private ViewPager viewPager;
+ AdapterTab adapter;
+
+ private String[] tabs = {"Lock", "Kill"};
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ super.onCreateView(inflater, container, savedInstanceState, true);
+ return inflater.inflate(R.layout.custom_tabbed_layout, container, false);
+ }
+
+ @Override
+ public void onActivityCreated(Bundle savedInstanceState) {
+ super.onActivityCreated(savedInstanceState);
+
+ actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
+ actionBar.setIcon(R.drawable.dl_access);
+ actionBar.setTitle(R.string.title_activity_security);
+
+ TabLayout tabLayout = (TabLayout) getActivity().findViewById(R.id.OperationsTabLayout);
+
+ adapter = new AdapterTab(getActivity().getSupportFragmentManager(), tabs.length);
+ adapter.setFragment(0, new AccessSecurityLockFragment());
+ adapter.setFragment(1, new AccessSecurityKillFragment());
+
+ viewPager = (ViewPager) getActivity().findViewById(R.id.OperationsPager);
+ viewPager.setAdapter(adapter);
+ viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
+
+ for (String tab_name : tabs) {
+ tabLayout.addTab(tabLayout.newTab().setText(tab_name));
+ }
+
+ tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
+ @Override
+ public void onTabSelected(TabLayout.Tab tab) {
+ viewPager.setCurrentItem(tab.getPosition());
+ }
+
+ @Override
+ public void onTabUnselected(TabLayout.Tab tab) {
+ }
+
+ @Override
+ public void onTabReselected(TabLayout.Tab tab) {
+ }
+ });
+ }
+
+ @Override
+ public void onPause() {
+ adapter.fragment0.onPause();
+ adapter.fragment1.onPause();
+ super.onPause();
+ }
+
+ @Override
+ public void onStop() {
+ adapter.fragment0.onStop();
+ adapter.fragment1.onStop();
+ super.onStop();
+ }
+
+ @Override
+ public void onDestroyView() {
+ adapter.fragment0.onDestroyView();
+ adapter.fragment1.onDestroyView();
+ super.onDestroyView();
+ }
+
+ @Override
+ public void onDestroy() {
+ adapter.fragment0.onDestroy();
+ adapter.fragment1.onDestroy();
+ MainActivity.csLibrary4A.setSameCheck(true);
+ MainActivity.csLibrary4A.restoreAfterTagSelect();
+ super.onDestroy();
+ }
+
+ @Override
+ public void onDetach() {
+ adapter.fragment0.onDetach();
+ adapter.fragment1.onDetach();
+ super.onDetach();
+ }
+
+ public AccessSecurityFragment() {
+ super("AccessSecurityFragment");
+ }
+}
+
+
+
+package com.csl.cs710ademoapp.fragments;
+
+import android.os.AsyncTask;
+import android.os.Bundle;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.Button;
+import android.widget.EditText;
+import android.widget.Toast;
+
+import com.csl.cs710ademoapp.AccessTask;
+import com.csl.cs710ademoapp.GenericTextWatcher;
+import com.csl.cs710ademoapp.MainActivity;
+import com.csl.cs710ademoapp.R;
+import com.csl.cslibrary4a.NotificationConnector;
+import com.csl.cslibrary4a.ReaderDevice;
+import com.csl.cslibrary4a.RfidReaderChipData;
+
+public class AccessSecurityKillFragment extends CommonFragment {
+ private EditText editTextTagID, editTextPassword, editTextAntennaPower;
+ private Button button;
+
+ private AccessTask accessTask;
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ super.onCreateView(inflater, container, savedInstanceState, false);
+ return inflater.inflate(R.layout.fragment_access_kill, container, false);
+ }
+
+ @Override
+ public void onActivityCreated(Bundle savedInstanceState) {
+ super.onActivityCreated(savedInstanceState);
+
+ editTextTagID = (EditText) getActivity().findViewById(R.id.accessKillTagID);
+ editTextPassword = (EditText) getActivity().findViewById(R.id.accessKillPasswordValue);
+ editTextPassword.addTextChangedListener(new GenericTextWatcher(editTextPassword, 8));
+ editTextPassword.setText("00000000");
+
+ editTextAntennaPower = (EditText) getActivity().findViewById(R.id.accessKillAntennaPower);
+ editTextAntennaPower.setText(String.valueOf(300));
+
+ button = (Button) getActivity().findViewById(R.id.accessKillButton);
+ button.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (MainActivity.csLibrary4A.isBleConnected() == false) {
+ Toast.makeText(MainActivity.mContext, R.string.toast_ble_not_connected, Toast.LENGTH_SHORT).show();
+ return;
+ } else if (MainActivity.csLibrary4A.isRfidFailure()) {
+ Toast.makeText(MainActivity.mContext, "Rfid is disabled", Toast.LENGTH_SHORT).show();
+ return;
+ }
+ startAccessTask();
+ }
+ });
+
+ ReaderDevice tagSelected = MainActivity.tagSelected;
+ if (tagSelected != null) {
+ if (tagSelected.getSelected() == true) {
+ editTextTagID.setText(tagSelected.getAddress());
+ }
+ }
+ MainActivity.csLibrary4A.setSameCheck(false);
+ }
+
+ @Override
+ public void onResume() {
+ super.onResume();
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("AccessSecurityKillFragment().onResume(): userVisibleHint = " + userVisibleHint);
+ if (userVisibleHint) {
+ setNotificationListener();
+ }
+ }
+
+ @Override
+ public void onPause() {
+ MainActivity.csLibrary4A.setNotificationListener(null);
+ super.onPause();
+ }
+
+ @Override
+ public void onDestroy() {
+ MainActivity.csLibrary4A.setNotificationListener(null);
+ if (accessTask != null) accessTask.cancel(true);
+ super.onDestroy();
+ }
+
+ boolean userVisibleHint = false;
+ @Override
+ public void setUserVisibleHint(boolean isVisibleToUser) {
+ super.setUserVisibleHint(isVisibleToUser);
+ if(getUserVisibleHint()) {
+ userVisibleHint = true;
+ MainActivity.csLibrary4A.appendToLog("AccessSecurityKillFragment is now VISIBLE");
+ setNotificationListener();
+ } else {
+ userVisibleHint = false;
+ MainActivity.csLibrary4A.appendToLog("AccessSecurityKillFragment is now INVISIBLE");
+ MainActivity.csLibrary4A.setNotificationListener(null);
+ }
+ }
+
+ public AccessSecurityKillFragment() {
+ super("AccessSecurityKillFragment");
+ }
+
+ void setNotificationListener() {
+ MainActivity.csLibrary4A.setNotificationListener(new NotificationConnector.NotificationListener() {
+ @Override
+ public void onChange() {
+ MainActivity.csLibrary4A.appendToLog("TRIGGER key is pressed.");
+ if (MainActivity.csLibrary4A.getTriggerButtonStatus()) startAccessTask();
+ }
+ });
+ }
+
+ void startAccessTask() {
+ if (accessTask != null) if (accessTask.getStatus() == AsyncTask.Status.RUNNING) return;
+ boolean invalidRequest = false;
+ String strTagID = editTextTagID.getText().toString();
+ String strPassword = editTextPassword.getText().toString();
+ int powerLevel = Integer.valueOf(editTextAntennaPower.getText().toString());
+ accessTask = new AccessTask(button, null, invalidRequest, true,
+ strTagID, 1, 32,
+ strPassword, powerLevel, RfidReaderChipData.HostCommands.CMD_18K6CKILL,
+ 0, 0, true, false,
+ null, null, null, null, null);
+ accessTask.execute();
+ }
+}
+
+
+
+package com.csl.cs710ademoapp.fragments;
+
+import android.os.AsyncTask;
+import android.os.Bundle;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.ArrayAdapter;
+import android.widget.Button;
+import android.widget.CheckBox;
+import android.widget.EditText;
+import android.widget.Spinner;
+import android.widget.Toast;
+
+import com.csl.cs710ademoapp.AccessTask;
+import com.csl.cs710ademoapp.GenericTextWatcher;
+import com.csl.cs710ademoapp.MainActivity;
+import com.csl.cs710ademoapp.R;
+import com.csl.cslibrary4a.NotificationConnector;
+import com.csl.cslibrary4a.ReaderDevice;
+import com.csl.cslibrary4a.RfidReaderChipData;
+
+public class AccessSecurityLockFragment extends CommonFragment {
+ private EditText editTextTagID, editTextPassword, editTextAntennaPower;
+ private CheckBox checkBox;
+ private Spinner spinner4KillPwd, spinner4AccessPwd, spinner4EpcMemory, spinner4TidMemory, spinner4UserMemory;
+ private Button button;
+
+ private AccessTask accessTask;
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ super.onCreateView(inflater, container, savedInstanceState, false);
+ return inflater.inflate(R.layout.fragment_access_lock, container, false);
+ }
+
+ @Override
+ public void onActivityCreated(Bundle savedInstanceState) {
+ super.onActivityCreated(savedInstanceState);
+
+ editTextTagID = (EditText) getActivity().findViewById(R.id.accessLockTagID);
+ editTextPassword = (EditText) getActivity().findViewById(R.id.accessLockPasswordValue);
+ editTextPassword.addTextChangedListener(new GenericTextWatcher(editTextPassword, 8));
+ editTextPassword.setText("00000000");
+
+ checkBox = (CheckBox) getActivity().findViewById(R.id.accessLockAllPermLock);
+
+ ArrayAdapter arrayAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.access_lock_privilege_array, R.layout.custom_spinner_layout);
+ arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+
+ spinner4KillPwd = (Spinner) getActivity().findViewById(R.id.accessLockPrivilege4KillPwd);
+ spinner4KillPwd.setAdapter(arrayAdapter);
+
+ spinner4AccessPwd = (Spinner) getActivity().findViewById(R.id.accessLockPrivilege4AccessPwd);
+ spinner4AccessPwd.setAdapter(arrayAdapter);
+
+ spinner4EpcMemory = (Spinner) getActivity().findViewById(R.id.accessLockPrivilege4EpcMemory);
+ spinner4EpcMemory.setAdapter(arrayAdapter);
+
+ spinner4TidMemory = (Spinner) getActivity().findViewById(R.id.accessLockPrivilege4TidMemory);
+ spinner4TidMemory.setAdapter(arrayAdapter);
+
+ spinner4UserMemory = (Spinner) getActivity().findViewById(R.id.accessLockPrivilege4UserMemory);
+ spinner4UserMemory.setAdapter(arrayAdapter);
+
+ editTextAntennaPower = (EditText) getActivity().findViewById(R.id.accessLockAntennaPower);
+ editTextAntennaPower.setText(String.valueOf(300));
+
+ button = (Button) getActivity().findViewById(R.id.accessLockButton);
+ button.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (MainActivity.csLibrary4A.isBleConnected() == false) {
+ Toast.makeText(MainActivity.mContext, R.string.toast_ble_not_connected, Toast.LENGTH_SHORT).show();
+ return;
+ } else if (MainActivity.csLibrary4A.isRfidFailure()) {
+ Toast.makeText(MainActivity.mContext, "Rfid is disabled", Toast.LENGTH_SHORT).show();
+ return;
+ }
+ startAccessTask();
+ }
+ });
+
+ ReaderDevice tagSelected = MainActivity.tagSelected;
+ if (tagSelected != null) {
+ if (tagSelected.getSelected() == true) {
+ editTextTagID.setText(tagSelected.getAddress());
+ }
+ }
+ MainActivity.csLibrary4A.setSameCheck(false);
+ }
+
+ @Override
+ public void onResume() {
+ super.onResume();
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("AccessSecurityLockFragment().onResume(): userVisibleHint = " + userVisibleHint);
+ if (userVisibleHint) {
+ setNotificationListener();
+ }
+ }
+
+ @Override
+ public void onPause() {
+ MainActivity.csLibrary4A.setNotificationListener(null);
+ super.onPause();
+ }
+
+ @Override
+ public void onDestroy() {
+ MainActivity.csLibrary4A.setNotificationListener(null);
+ if (accessTask != null) accessTask.cancel(true);
+ super.onDestroy();
+ }
+
+ boolean userVisibleHint = false;
+ @Override
+ public void setUserVisibleHint(boolean isVisibleToUser) {
+ super.setUserVisibleHint(isVisibleToUser);
+ if(getUserVisibleHint()) {
+ userVisibleHint = true;
+ MainActivity.csLibrary4A.appendToLog("AccessSecurityLockFragment is now VISIBLE");
+ setNotificationListener();
+ } else {
+ userVisibleHint = false;
+ MainActivity.csLibrary4A.appendToLog("AccessSecurityLockFragment is now INVISIBLE");
+ MainActivity.csLibrary4A.setNotificationListener(null);
+ }
+ }
+
+ public AccessSecurityLockFragment() {
+ super("AccessSecurityLockFragment");
+ }
+
+ void setNotificationListener() {
+ MainActivity.csLibrary4A.setNotificationListener(new NotificationConnector.NotificationListener() {
+ @Override
+ public void onChange() {
+ MainActivity.csLibrary4A.appendToLog("TRIGGER key is pressed.");
+ if (MainActivity.csLibrary4A.getTriggerButtonStatus()) startAccessTask();
+ }
+ });
+ }
+
+ void startAccessTask() {
+ int accessLockAction = 0;
+ int accessLockMask = 0;
+ int lockAction;
+
+ if (accessTask != null) if (accessTask.getStatus() == AsyncTask.Status.RUNNING) return;
+ if (checkBox.isChecked()) {
+ accessLockAction = 0x3FF;
+ accessLockMask = 0x3FF;
+ } else {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("accessLockAction = " + String.format("%x", accessLockAction) + ", accessLockMask = " + String.format("%x", accessLockMask));
+ lockAction = spinner4KillPwd.getSelectedItemPosition();
+ accessLockAction |= ((lockAction == 0 ? 0 : lockAction - 1) << 8);
+ accessLockMask |= ((lockAction == 0 ? 0 : 3) << 8);
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("Kill: accessLockAction = " + String.format("%x", accessLockAction) + ", accessLockMask = " + String.format("%x", accessLockMask));
+
+ lockAction = spinner4AccessPwd.getSelectedItemPosition();
+ accessLockAction |= ((lockAction == 0 ? 0 : lockAction - 1) << 6);
+ accessLockMask |= ((lockAction == 0 ? 0 : 3) << 6);
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("Access: accessLockAction = " + String.format("%x", accessLockAction) + ", accessLockMask = " + String.format("%x", accessLockMask));
+
+ lockAction = spinner4EpcMemory.getSelectedItemPosition();
+ accessLockAction |= ((lockAction == 0 ? 0 : lockAction - 1) << 4);
+ accessLockMask |= ((lockAction == 0 ? 0 : 3) << 4);
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("Epc: accessLockAction = " + String.format("%x", accessLockAction) + ", accessLockMask = " + String.format("%x", accessLockMask));
+
+ lockAction = spinner4TidMemory.getSelectedItemPosition();
+ accessLockAction |= ((lockAction == 0 ? 0 : lockAction - 1) << 2);
+ accessLockMask |= ((lockAction == 0 ? 0 : 3) << 2);
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("Tid: accessLockAction = " + String.format("%x", accessLockAction) + ", accessLockMask = " + String.format("%x", accessLockMask));
+
+ lockAction = spinner4UserMemory.getSelectedItemPosition();
+ accessLockAction |= (lockAction == 0 ? 0 : lockAction - 1);
+ accessLockMask |= (lockAction == 0 ? 0 : 3);
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("Uesr: accessLockAction = " + String.format("%x", accessLockAction) + ", accessLockMask = " + String.format("%x", accessLockMask));
+ }
+
+ boolean invalidRequest = false;
+ String strTagID = editTextTagID.getText().toString();
+ String strPassword = editTextPassword.getText().toString();
+ int powerLevel = Integer.valueOf(editTextAntennaPower.getText().toString());
+ if (invalidRequest == false) {
+ if (MainActivity.csLibrary4A.setAccessLockAction(accessLockAction, accessLockMask) == false) {
+ invalidRequest = true;
+ }
+ }
+ accessTask = new AccessTask(button, null, invalidRequest, true,
+ strTagID, 1, 32,
+ strPassword, powerLevel, RfidReaderChipData.HostCommands.CMD_18K6CLOCK,
+ 0, 0, true, false,
+ null, null, null, null, null);
+ accessTask.execute();
+ }
+}
+
+
+
+package com.csl.cs710ademoapp.fragments;
+
+import static com.csl.cslibrary4a.RfidReader.TagType.TAG_NXP;
+import static com.csl.cslibrary4a.RfidReader.TagType.TAG_NXP_UCODE8_EPC;
+import static com.csl.cslibrary4a.RfidReader.TagType.TAG_NXP_UCODE8_EPCBRAND;
+import static com.csl.cslibrary4a.RfidReader.TagType.TAG_NXP_UCODE8_EPCBRANDTID;
+import static com.csl.cslibrary4a.RfidReader.TagType.TAG_NXP_UCODE8_EPCTID;
+import static com.csl.cslibrary4a.RfidReader.TagType.TAG_NXP_UCODEDNA;
+
+import android.os.Bundle;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.AdapterView;
+import android.widget.ArrayAdapter;
+import android.widget.LinearLayout;
+import android.widget.RadioButton;
+import android.widget.Spinner;
+
+import com.csl.cs710ademoapp.MainActivity;
+import com.csl.cs710ademoapp.R;
+import com.google.android.material.tabs.TabLayout;
+
+public class AccessUcode8Fragment extends CommonFragment {
+ final boolean DEBUG = true;
+ Spinner spinnerTagSelect;
+ RadioButton radioButtonSelectEpc, radioButtonSelectEpcTid, radioButtonSelectEpcBrand, radioButtonSelectEpcBrandTidCheck;
+ enum nxpTag {
+ ucode8, ucodeDNA, others
+ }
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ super.onCreateView(inflater, container, savedInstanceState, false);
+ return inflater.inflate(R.layout.fragment_access_ucode8, container, false);
+ }
+
+ @Override
+ public void onActivityCreated(Bundle savedInstanceState) {
+ super.onActivityCreated(savedInstanceState);
+
+ spinnerTagSelect = (Spinner) getActivity().findViewById(R.id.accessNxpTagSelect);
+ ArrayAdapter targetAdapter1 = ArrayAdapter.createFromResource(getActivity(), R.array.nxp_options, R.layout.custom_spinner_layout);
+ targetAdapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+ spinnerTagSelect.setAdapter(targetAdapter1); spinnerTagSelect.setSelection(0);
+ spinnerTagSelect.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
+ @Override
+ public void onItemSelected(AdapterView> parentView, View selectedItemView, int position, long id) {
+ TabLayout tabLayout = (TabLayout) getActivity().findViewById(R.id.OperationsTabLayout);
+ TabLayout.TabView tabView = tabLayout.getTabAt(2).view; tabView.setVisibility(View.GONE);
+ TabLayout.TabView tabViewUntrace = tabLayout.getTabAt(3).view; tabViewUntrace.setVisibility(View.GONE);
+ LinearLayout layout = (LinearLayout) getActivity().findViewById(R.id.accessNxpUcode8Select); layout.setVisibility(View.GONE);
+ if (position == nxpTag.ucode8.ordinal()) {
+ updateUcode8Type();
+ MainActivity.csLibrary4A.appendToLog("AccessUcode8Fragment.onItemSelected[spinnerTagSelect] set MainActivity.mDid as " + MainActivity.mDid);
+ if (MainActivity.csLibrary4A.get98XX() == 0) tabViewUntrace.setVisibility(View.VISIBLE);
+ layout.setVisibility(View.VISIBLE);
+ } else if (position == nxpTag.ucodeDNA.ordinal()) {
+ MainActivity.tagType = TAG_NXP_UCODEDNA; MainActivity.mDid = "E2C06";
+ MainActivity.csLibrary4A.appendToLog("AccessUcode8Fragment.onItemSelected set MainActivity.mDid as E2C06");
+ tabView.setVisibility(View.VISIBLE);
+ if (MainActivity.csLibrary4A.get98XX() == 0) tabViewUntrace.setVisibility(View.VISIBLE);
+ } else {
+ MainActivity.tagType = TAG_NXP; MainActivity.mDid = "E2806";
+ MainActivity.csLibrary4A.appendToLog("AccessUcode8Fragment.onItemSelected set MainActivity.mDid as E2806");
+ }
+ MainActivity.csLibrary4A.appendToLog("new mDid = " + MainActivity.mDid);
+ }
+
+ @Override
+ public void onNothingSelected(AdapterView> parentView) {
+ // your code here
+ }
+
+ });
+
+ radioButtonSelectEpc = (RadioButton) getActivity().findViewById(R.id.accessUC8SelectEpc);
+ radioButtonSelectEpcTid = (RadioButton) getActivity().findViewById(R.id.accessUC8SelectEpcTid);
+ radioButtonSelectEpcBrand = (RadioButton) getActivity().findViewById(R.id.accessUC8SelectEpcBrand);
+ radioButtonSelectEpcBrandTidCheck = (RadioButton) getActivity().findViewById(R.id.accessUC8SelectEpcBrandTidCheck);
+ if (MainActivity.csLibrary4A.get98XX() == 2) {
+ radioButtonSelectEpc.setChecked(true);
+ radioButtonSelectEpcBrand.setVisibility(View.GONE);
+ radioButtonSelectEpcBrandTidCheck.setVisibility(View.GONE);
+ } else radioButtonSelectEpcBrand.setChecked(true);
+
+ MainActivity.csLibrary4A.setSameCheck(false);
+ }
+
+ @Override
+ public void onDestroy() {
+ MainActivity.csLibrary4A.setSameCheck(true);
+ super.onDestroy();
+ }
+
+ boolean userVisibleHint = false;
+ @Override
+ public void setUserVisibleHint(boolean isVisibleToUser) {
+ super.setUserVisibleHint(isVisibleToUser);
+ if(getUserVisibleHint()) {
+ userVisibleHint = true;
+ MainActivity.csLibrary4A.appendToLog("AccessUcode8Fragment is now VISIBLE");
+ // setNotificationListener();
+ } else {
+ updateUcode8Type();
+ MainActivity.csLibrary4A.appendToLog("AccessUcode8Fragment.setUserVisibleHint set MainActivity.mDid as " + MainActivity.mDid);
+ userVisibleHint = false;
+ MainActivity.csLibrary4A.appendToLog("AccessUcode8Fragment is now INVISIBLE");
+ }
+ }
+
+ void updateUcode8Type() {
+ if (spinnerTagSelect != null && spinnerTagSelect.getSelectedItemPosition() == nxpTag.ucode8.ordinal()) {
+ if (radioButtonSelectEpc != null && radioButtonSelectEpcTid != null && radioButtonSelectEpcBrand != null && radioButtonSelectEpcBrandTidCheck != null) {
+ if (radioButtonSelectEpc.isChecked()) {
+ MainActivity.csLibrary4A.appendToLog("Selected EPC");
+ MainActivity.tagType = TAG_NXP_UCODE8_EPC; MainActivity.mDid = "E2806894A";
+ MainActivity.csLibrary4A.appendToLog("AccessUcode8Fragment.setUserVisibleHint set MainActivity.mDid as E2806894A");
+ }
+ if (radioButtonSelectEpcTid.isChecked()) {
+ MainActivity.csLibrary4A.appendToLog("Selected EPC+TID");
+ MainActivity.tagType = TAG_NXP_UCODE8_EPCTID; MainActivity.mDid = "E2806894B";
+ MainActivity.csLibrary4A.appendToLog("AccessUcode8Fragment.setUserVisibleHint set MainActivity.mDid as E2806894b");
+ }
+ if (radioButtonSelectEpcBrand.isChecked()) {
+ MainActivity.csLibrary4A.appendToLog("Selected EPC+BRAND");
+ MainActivity.tagType = TAG_NXP_UCODE8_EPCBRAND; MainActivity.mDid = "E2806894C";
+ MainActivity.csLibrary4A.appendToLog("AccessUcode8Fragment.setUserVisibleHint set MainActivity.mDid as E2806894C");
+ }
+ if (radioButtonSelectEpcBrandTidCheck.isChecked()) {
+ MainActivity.csLibrary4A.appendToLog("Selected EPC+BRAND");
+ MainActivity.tagType = TAG_NXP_UCODE8_EPCBRANDTID; MainActivity.mDid = "E2806894d";
+ MainActivity.csLibrary4A.appendToLog("AccessUcode8Fragment.setUserVisibleHint set MainActivity.mDid as E2806894d");
+ }
+ MainActivity.csLibrary4A.appendToLog("newDid 1 = " + MainActivity.mDid);
+ }
+ }
+ }
+
+ public AccessUcode8Fragment() {
+ super("AccessUcode8Fragment");
+ }
+}
+
+
+
+package com.csl.cs710ademoapp.fragments;
+
+import static com.csl.cs710ademoapp.MainActivity.csLibrary4A;
+
+import android.app.Activity;
+import android.os.AsyncTask;
+import android.os.Bundle;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.ArrayAdapter;
+import android.widget.Button;
+import android.widget.CheckBox;
+import android.widget.EditText;
+import android.widget.LinearLayout;
+import android.widget.Spinner;
+import android.widget.TableRow;
+import android.widget.TextView;
+import android.widget.Toast;
+
+import com.csl.cs710ademoapp.AccessTask;
+import com.csl.cs710ademoapp.GenericTextWatcher;
+import com.csl.cs710ademoapp.MainActivity;
+import com.csl.cs710ademoapp.R;
+import com.csl.cs710ademoapp.SaveList2ExternalTask;
+import com.csl.cs710ademoapp.SelectTag;
+import com.csl.cslibrary4a.AesCmac;
+import com.csl.cslibrary4a.ReaderDevice;
+import com.csl.cslibrary4a.RfidReaderChipData;
+
+import org.json.JSONArray;
+import org.json.JSONException;
+import org.json.JSONObject;
+
+import javax.crypto.Cipher;
+import javax.crypto.Mac;
+import javax.crypto.spec.IvParameterSpec;
+import javax.crypto.spec.SecretKeySpec;
+
+public class AccessUcodeFragment extends CommonFragment {
+ final boolean DEBUG = true; int iTagType = -1;
+ SelectTag selectTag;
+ TextView textViewAesKey0ActivateOk, textViewAesKey1ActivateOk, textViewAesKey0Ok, textViewAesKey1Ok;
+ Spinner spinnerHideTid;
+ CheckBox checkBoxAuthEncryptMode, checkBoxAuthValidMode;
+ CheckBox checkBoxHideEpc, checkBoxHideTid, checkBoxHideUser, checkBoxHideRange;
+ CheckBox checkBoxAesKey0Activate, checkBoxAesKey1Activate, checkBoxAesKey0, checkBoxAesKey1;
+
+ EditText editTextAuthKeyId, editTextAuthMsg, editTextAuthProfile, editTextAuthOffset, editTextAuthBlockId, editTextAuthProtMode, editTextEpcSize, editTextAesKey0, editTextAesKey1, editTextAuthResponse;
+ TextView textViewAuthResponseDecoded, textViewAuthResponseDecodedCustom, editTextAuthResponseEncodedMac, textViewImpinjResponse;
+ EditText editTextAccessUCTid, editTextAccessUCserverImpinj, editTextAccessUCemail, editTextAccessUCpassword;
+ private Button buttonRead, buttonWrite;
+ private Button buttonReadBuffer, buttonTam1, buttonTam2, buttonUntrace, buttonShowEpc; String strShowEpcButtonBackup;
+
+ enum ReadWriteTypes {
+ NULL, TEMPERATURE, AESKEY0, AESKEY1, AESKEY0ACTIVATE, AESKEY1ACTIVATE, ENABLE
+ }
+ boolean operationRead = false;
+ boolean readBufferChecked = false;
+ boolean authenChecked = false; boolean authenTam1; int keyId, profile, offset, blockId, protMode; String strChallenge;
+ boolean untraceChecked = false;
+ boolean showEpcChecked = false;
+ ReadWriteTypes readWriteTypes;
+ boolean bImpinJTag = false;
+
+ private AccessTask accessTask;
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ super.onCreateView(inflater, container, savedInstanceState, false);
+ return inflater.inflate(R.layout.fragment_access_ucode, container, false);
+ }
+
+ @Override
+ public void onActivityCreated(Bundle savedInstanceState) {
+ super.onActivityCreated(savedInstanceState);
+ if (MainActivity.mDid != null) if (MainActivity.mDid.contains("E28240")) iTagType = 5;
+
+ selectTag = new SelectTag((Activity)getActivity(), 1);
+ if (MainActivity.mDid != null && MainActivity.mDid.indexOf("E2801") == 0) bImpinJTag = true;
+
+ spinnerHideTid = (Spinner) getActivity().findViewById(R.id.accessUCHideTid);
+ ArrayAdapter targetAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.hideTid_options, R.layout.custom_spinner_layout);
+ targetAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+ spinnerHideTid.setAdapter(targetAdapter);
+
+ checkBoxHideEpc = (CheckBox) getActivity().findViewById(R.id.accessUCHideEpc);
+ checkBoxHideTid = (CheckBox) getActivity().findViewById(R.id.accessUCHideTid1);
+ checkBoxHideUser = (CheckBox) getActivity().findViewById(R.id.accessUCHideUser);
+ checkBoxHideRange = (CheckBox) getActivity().findViewById(R.id.accessUCHideRange);
+ textViewAesKey0ActivateOk = (TextView) getActivity().findViewById(R.id.accessUCAesKey0ActivateOK);
+ textViewAesKey1ActivateOk = (TextView) getActivity().findViewById(R.id.accessUCAesKey1ActivateOK);
+ checkBoxAesKey0Activate = (CheckBox) getActivity().findViewById(R.id.accessUCAesKey0Activate);
+ checkBoxAesKey1Activate = (CheckBox) getActivity().findViewById(R.id.accessUCAesKey1Activate);
+
+ TableRow tableRow = (TableRow) getActivity().findViewById(R.id.accessUCAesKeysRow);
+ if (iTagType == 5) tableRow.setVisibility(View.GONE);
+ textViewAesKey0Ok = (TextView) getActivity().findViewById(R.id.accessUCAesKey0OK);
+ textViewAesKey1Ok = (TextView) getActivity().findViewById(R.id.accessUCAesKey1OK);
+ checkBoxAesKey0 = (CheckBox) getActivity().findViewById(R.id.accessUCAesKey0Title);
+ checkBoxAesKey1 = (CheckBox) getActivity().findViewById(R.id.accessUCAesKey1Title);
+
+ editTextAuthKeyId = (EditText) getActivity().findViewById(R.id.accessUCAuthKeyId);
+ editTextAuthKeyId.setText(String.valueOf(0));
+ editTextAuthMsg = (EditText) getActivity().findViewById(R.id.accessUCAuthMsg);
+ editTextAuthMsg.addTextChangedListener(new GenericTextWatcher(editTextAuthMsg, bImpinJTag ? 12 : 20));
+ editTextAuthProfile = (EditText) getActivity().findViewById(R.id.accessUCAuthProfile);
+ editTextAuthProfile.setText(String.valueOf(0));
+ editTextAuthOffset = (EditText) getActivity().findViewById(R.id.accessUCAuthOffset);
+ editTextAuthOffset.setText(String.valueOf(0));
+ editTextAuthBlockId = (EditText) getActivity().findViewById(R.id.accessUCAuthBlockId);
+ editTextAuthBlockId.setText(String.valueOf(1));
+
+ TextView textViewAuthProtModeLabel = (TextView) getActivity().findViewById(R.id.accessUCAuthProtModeLabel);
+ editTextAuthProtMode = (EditText) getActivity().findViewById(R.id.accessUCAuthProtMode);
+ TableRow tableRowAuthProtMode = (TableRow) getActivity().findViewById(R.id.accessUCAuthtModeRow);
+ checkBoxAuthEncryptMode = (CheckBox) getActivity().findViewById(R.id.accessUCAuthEncryptMode);
+ checkBoxAuthValidMode = (CheckBox) getActivity().findViewById(R.id.accessUCAuthValidMode);
+ if (iTagType == 5) {
+ textViewAuthProtModeLabel.setVisibility(View.GONE);
+ editTextAuthProtMode.setVisibility(View.GONE);
+ } else {
+ tableRowAuthProtMode.setVisibility(View.GONE);
+ editTextAuthProtMode.setText(String.valueOf(1));
+ }
+
+ editTextAuthResponse = (EditText) getActivity().findViewById(R.id.accessUCAuthResponse);
+ textViewAuthResponseDecoded = (TextView) getActivity().findViewById(R.id.accessUCAuthResponseDecoded);
+ textViewAuthResponseDecodedCustom = (TextView) getActivity().findViewById(R.id.accessUCAuthResponseDecodedCustom);
+ editTextAuthResponseEncodedMac = (TextView) getActivity().findViewById(R.id.accessUCAuthResponseEecodedMac);
+ textViewImpinjResponse = (TextView) getActivity().findViewById(R.id.accessUCImpinjResponse);
+ editTextEpcSize = (EditText) getActivity().findViewById(R.id.accessUCEpcSize);
+ editTextAesKey0 = (EditText) getActivity().findViewById(R.id.accessUCAesKey0);
+ editTextAesKey0.addTextChangedListener(new GenericTextWatcher(editTextAesKey0, 32));
+ editTextAesKey1 = (EditText) getActivity().findViewById(R.id.accessUCAesKey1);
+ editTextAesKey1.addTextChangedListener(new GenericTextWatcher(editTextAesKey1, 32));
+
+ buttonRead = (Button) getActivity().findViewById(R.id.accessUCReadButton);
+ if (iTagType == 5) buttonRead.setVisibility(View.GONE);
+ buttonRead.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (MainActivity.csLibrary4A.isBleConnected() == false) {
+ Toast.makeText(MainActivity.mContext, R.string.toast_ble_not_connected, Toast.LENGTH_SHORT).show();
+ return;
+ } else if (MainActivity.csLibrary4A.isRfidFailure()) {
+ Toast.makeText(MainActivity.mContext, "Rfid is disabled", Toast.LENGTH_SHORT).show();
+ return;
+ }
+ operationRead = true; startAccessTask();
+ }
+ });
+
+ buttonWrite = (Button) getActivity().findViewById(R.id.accessUCWriteButton);
+ buttonWrite.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (MainActivity.csLibrary4A.isBleConnected() == false) {
+ Toast.makeText(MainActivity.mContext, R.string.toast_ble_not_connected, Toast.LENGTH_SHORT).show();
+ return;
+ } else if (MainActivity.csLibrary4A.isRfidFailure()) {
+ Toast.makeText(MainActivity.mContext, "Rfid is disabled", Toast.LENGTH_SHORT).show();
+ return;
+ }
+ operationRead = false; startAccessTask();
+ }
+ });
+
+ buttonReadBuffer = (Button) getActivity().findViewById(R.id.accessUCReadBufferButton);
+ buttonReadBuffer.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (MainActivity.csLibrary4A.isBleConnected() == false) {
+ Toast.makeText(MainActivity.mContext, R.string.toast_ble_not_connected, Toast.LENGTH_SHORT).show();
+ return;
+ } else if (MainActivity.csLibrary4A.isRfidFailure()) {
+ Toast.makeText(MainActivity.mContext, "Rfid is disabled", Toast.LENGTH_SHORT).show();
+ return;
+ }
+ readBufferChecked = true; startAccessTask();
+ }
+ });
+
+ buttonTam1 = (Button) getActivity().findViewById(R.id.accessUCTam1AuthButton);
+ buttonTam1.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (MainActivity.csLibrary4A.isBleConnected() == false) {
+ Toast.makeText(MainActivity.mContext, R.string.toast_ble_not_connected, Toast.LENGTH_SHORT).show();
+ return;
+ } else if (MainActivity.csLibrary4A.isRfidFailure()) {
+ Toast.makeText(MainActivity.mContext, "Rfid is disabled", Toast.LENGTH_SHORT).show();
+ return;
+ }
+ MainActivity.csLibrary4A.appendToLog("buttonTam1 is pressed");
+ authenTam1 = true; authenChecked = true; keyId = Integer.parseInt(editTextAuthKeyId.getText().toString()); strChallenge = editTextAuthMsg.getText().toString();
+ startAccessTask();
+ }
+ });
+
+ buttonTam2 = (Button) getActivity().findViewById(R.id.accessUCTam2AuthButton);
+ buttonTam2.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (MainActivity.csLibrary4A.isBleConnected() == false) {
+ Toast.makeText(MainActivity.mContext, R.string.toast_ble_not_connected, Toast.LENGTH_SHORT).show();
+ return;
+ } else if (MainActivity.csLibrary4A.isRfidFailure()) {
+ Toast.makeText(MainActivity.mContext, "Rfid is disabled", Toast.LENGTH_SHORT).show();
+ return;
+ }
+ MainActivity.csLibrary4A.appendToLog("buttonTam2 is pressed");
+ authenTam1 = false; authenChecked = true; keyId = Integer.parseInt(editTextAuthKeyId.getText().toString()); strChallenge = editTextAuthMsg.getText().toString();
+ profile = Integer.parseInt(editTextAuthProfile.getText().toString());
+ offset = Integer.parseInt(editTextAuthOffset.getText().toString());
+ blockId = Integer.parseInt(editTextAuthBlockId.getText().toString());
+ if (iTagType != 5) protMode = Integer.parseInt(editTextAuthProtMode.getText().toString());
+ else {
+ protMode = 0;
+ if (checkBoxAuthEncryptMode.isChecked()) protMode += 1;
+ if (checkBoxAuthValidMode.isChecked()) protMode += 2;
+ }
+ startAccessTask();
+ }
+ });
+
+ buttonUntrace = (Button) getActivity().findViewById(R.id.accessUCUntraceButton);
+ buttonUntrace.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (MainActivity.csLibrary4A.isBleConnected() == false) {
+ Toast.makeText(MainActivity.mContext, R.string.toast_ble_not_connected, Toast.LENGTH_SHORT).show();
+ return;
+ } else if (MainActivity.csLibrary4A.isRfidFailure()) {
+ Toast.makeText(MainActivity.mContext, "Rfid is disabled", Toast.LENGTH_SHORT).show();
+ return;
+ }
+ untraceChecked = true; startAccessTask();
+ }
+ });
+
+ tableRow = (TableRow) getActivity().findViewById(R.id.accessUCShowEpcRow);
+ if (iTagType == 5) tableRow.setVisibility(View.GONE);
+ buttonShowEpc = (Button) getActivity().findViewById(R.id.accessUCShowEpcButton);
+ buttonShowEpc.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (MainActivity.csLibrary4A.isBleConnected() == false) {
+ Toast.makeText(MainActivity.mContext, R.string.toast_ble_not_connected, Toast.LENGTH_SHORT).show();
+ return;
+ } else if (MainActivity.csLibrary4A.isRfidFailure()) {
+ Toast.makeText(MainActivity.mContext, "Rfid is disabled", Toast.LENGTH_SHORT).show();
+ return;
+ }
+ showEpcChecked = true; startAccessTask();
+ }
+ });
+
+ TextView textViewWarning = (TextView) getActivity().findViewById(R.id.accessUCWarning);
+ if (iTagType == 5) textViewWarning.setText("Notice: Xerxes assumes Key0 for Tam1 and Tam 2");
+ else textViewWarning.setText("Notice: Ucode assumes Key1 for Tam2");
+
+ MainActivity.csLibrary4A.getAuthenticateReplyLength();
+ MainActivity.csLibrary4A.getUntraceableEpcLength();
+ MainActivity.csLibrary4A.setSameCheck(false);
+
+ MainActivity.csLibrary4A.appendToLog("mDid in AccessUcodeFragment = " + MainActivity.mDid);
+ TextView textView = (TextView) getActivity().findViewById(R.id.accessUCAuthKeyIdLabel);
+ EditText editText = (EditText) getActivity().findViewById(R.id.accessUCAuthKeyId);
+ TableRow tableRow1 = (TableRow) getActivity().findViewById(R.id.accessUCAuthProfileRow);
+ LinearLayout layout1 = (LinearLayout) getActivity().findViewById(R.id.accessUCKeyLayout);
+ LinearLayout layout = (LinearLayout) getActivity().findViewById(R.id.accessUCButtons);
+ if (bImpinJTag) {
+ textView.setVisibility(View.GONE);
+ editText.setVisibility(View.GONE);
+ editTextAuthMsg.setText("049CA53E55EA");
+ tableRow1.setVisibility(View.GONE);
+ layout1.setVisibility(View.GONE);
+ layout.setVisibility(View.GONE);
+ }
+
+ Button buttonImpinjCheck = (Button) getActivity().findViewById(R.id.accessUCImpinjCheck);
+ buttonImpinjCheck.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View view) {
+ if (!bRunning) {
+ textViewImpinjResponse.setText("");
+ mHandler.post(runnable);
+ }
+ }
+ });
+
+ editTextAccessUCserverImpinj = (EditText) getActivity().findViewById(R.id.accessUCserverImpinj);
+ editTextAccessUCemail = (EditText) getActivity().findViewById(R.id.accessUCemail);
+ editTextAccessUCpassword = (EditText) getActivity().findViewById(R.id.accessUCpassword);
+ if (true) {
+ editTextAccessUCserverImpinj.setText(csLibrary4A.getServerImpinjLocation());
+ editTextAccessUCemail.setText(csLibrary4A.getServerImpinjName());
+ editTextAccessUCpassword.setText(csLibrary4A.getServerImpinjPassword());
+ } else if (false) {
+ editTextAccessUCserverImpinj.setText("https://h9tqczg9-7275.asse.devtunnels.ms");
+ editTextAccessUCemail.setText("wallace.sit@cne.com.hk");
+ editTextAccessUCpassword.setText("Cne12345678?");
+ } else {
+ editTextAccessUCserverImpinj.setText("https://democloud.convergence.com.hk/ias");
+ editTextAccessUCemail.setText("wallace.sit@cne.com.hk");
+ editTextAccessUCpassword.setText("Cne12345678?");
+ }
+ }
+
+ SaveList2ExternalTask saveExternalTask; boolean bRunning = false; int bStep = 0; String strBearer = null;
+ Runnable runnable = new Runnable() {
+ @Override
+ public void run() {
+ csLibrary4A.appendToLog("0 bRunning = " + bRunning + ", bStep = " + bStep);
+ if (saveExternalTask != null && saveExternalTask.getStatus() == AsyncTask.Status.FINISHED) {
+ bStep++;
+ if (saveExternalTask.responseCode != 200) bStep++;
+ else {
+ if (bStep == 1) strBearer = saveExternalTask.response;
+ else {
+ String strTid = null, strResult = null;
+ JSONObject obj = null;
+ try {
+ obj = new JSONObject(saveExternalTask.response);
+ JSONArray jsonArray = obj.getJSONArray("tagValidity");
+ MainActivity.csLibrary4A.appendToLog("Json tagValidity is " + (jsonArray == null ? "null" : "valid"));
+ strTid = jsonArray.getJSONObject(0).getString("tid");
+ strResult = jsonArray.getJSONObject(0).getString("tagValid");
+ } catch (JSONException e) {
+ csLibrary4A.appendToLog("Json exception = " + e.toString());
+ }
+ if (strTid != null && strResult != null) {
+ //textViewImpinjResponse.setText(strResult + " " + strTid);
+ textViewImpinjResponse.setText((strResult.matches("true") ? "Valid" : "Invalid"));
+ }
+ }
+ }
+ MainActivity.csLibrary4A.appendToLog("responseCode = " + saveExternalTask.responseCode + ", response = " + saveExternalTask.response);
+ saveExternalTask = null;
+ }
+ csLibrary4A.appendToLog("bRunning = " + bRunning + ", bStep = " + bStep);
+ if (bStep < 2) {
+ if (saveExternalTask == null || saveExternalTask.getStatus() != AsyncTask.Status.RUNNING) {
+ csLibrary4A.appendToLog("1 bRunning = " + bRunning + ", bStep = " + bStep);
+ bRunning = true;
+ if (bStep == 0) {
+ bStep = 0;
+ saveExternalTask = new SaveList2ExternalTask(true);
+
+ JSONObject object = new JSONObject();
+ try {
+ //object.put("Username", "CslAuth2047#$");
+ //object.put("Password", "Sheungwan123#$");
+ object.put("email", editTextAccessUCemail.getText().toString()); //"wallace.sit@cne.com.hk");
+ object.put("password", editTextAccessUCpassword.getText().toString()); //"Cne12345678?");
+ } catch (Exception ex) {
+ MainActivity.csLibrary4A.appendToLog("Error in creating Json");
+ }
+ saveExternalTask.messageStr = object.toString();
+ //saveExternalTask.url = "https://ias.authenticate.impinj.io/external/jwt/authenticate";
+ saveExternalTask.url = editTextAccessUCserverImpinj.getText().toString() + "/api/Auth/login"; // "https://h9tqczg9-7275.asse.devtunnels.ms/api/Auth/login";
+ MainActivity.csLibrary4A.appendToLog("Adddress: " + saveExternalTask.url + ", json message:" + saveExternalTask.messageStr);
+ saveExternalTask.execute();
+ MainActivity.csLibrary4A.appendToLog("responseCode = " + saveExternalTask.responseCode + ", response = " + saveExternalTask.response);
+ } else {
+ saveExternalTask = new SaveList2ExternalTask(true);
+
+ JSONObject object = new JSONObject();
+ try {
+ JSONArray jsonArray = new JSONArray();
+ JSONObject object1 = new JSONObject();
+ object1.put("tid", editTextAccessUCTid.getText().toString()); //tagSelected.getTid()); //"E2C011A21234123412341234"); //
+ object1.put("challenge", editTextAuthMsg.getText().toString());
+ object1.put("tagResponse", editTextAuthResponse.getText().toString());
+ jsonArray.put(object1);
+ object.put("tagVerify", jsonArray);
+ object.put("sendSignature", true);
+ object.put("sendSalt", true);
+ object.put("sendTime", true);
+ } catch (Exception ex) {
+ MainActivity.csLibrary4A.appendToLog("Error in creating Json");
+ }
+ saveExternalTask.messageStr = object.toString();
+ saveExternalTask.url = editTextAccessUCserverImpinj.getText().toString() + "/api/ImpinjAuthentication/authenticate"; //"https://h9tqczg9-7275.asse.devtunnels.ms/api/ImpinjAuthentication/authenticate";
+ saveExternalTask.strBearer = "Bearer " + strBearer;
+ MainActivity.csLibrary4A.appendToLog("Adddress: " + saveExternalTask.url + ", json message:" + saveExternalTask.messageStr);
+ saveExternalTask.execute();
+ MainActivity.csLibrary4A.appendToLog("responseCode = " + saveExternalTask.responseCode + ", response = " + saveExternalTask.response);
+ }
+ }
+ mHandler.postDelayed(runnable, 100);
+ } else {
+ bRunning = false; bStep = 0;
+ }
+ }
+ };
+
+ @Override
+ public void onResume() {
+ super.onResume();
+ setupTagID();
+ }
+
+ @Override
+ public void onDestroy() {
+ if (accessTask != null) accessTask.cancel(true);
+ MainActivity.csLibrary4A.setSameCheck(true);
+ //MainActivity.mCs108Library4a.appendToLog("onDestroy");
+ super.onDestroy();
+ }
+
+ boolean userVisibleHint = false;
+ @Override
+ public void setUserVisibleHint(boolean isVisibleToUser) {
+ super.setUserVisibleHint(isVisibleToUser);
+ if(getUserVisibleHint()) {
+ userVisibleHint = true;
+ MainActivity.csLibrary4A.appendToLog("AccessUcodeFragment is now VISIBLE");
+ setupTagID();
+ // setNotificationListener();
+ } else {
+ userVisibleHint = false;
+ MainActivity.csLibrary4A.appendToLog("AccessUcodeFragment is now INVISIBLE");
+// MainActivity.mCs108Library4a.setNotificationListener(null);
+ }
+ }
+
+ public AccessUcodeFragment() {
+ super("AccessUcodeFragment");
+ }
+
+ void setupTagID() {
+ if (selectTag == null) return;
+ ReaderDevice tagSelected = MainActivity.tagSelected;
+ MainActivity.csLibrary4A.appendToLog("Start with tagSelected = " + (tagSelected == null ? "NULL" : (tagSelected.getSelected() + ", " + tagSelected.getAddress())));
+ boolean bSelected = false;
+ if (tagSelected != null) {
+ if (tagSelected.getSelected() == true) {
+ bSelected = true;
+ MainActivity.csLibrary4A.appendToLog("selectTag is " + (selectTag == null ? "NULL" : "valid"));
+ if (selectTag != null) MainActivity.csLibrary4A.appendToLog("selectTag.editTextTag is " + (selectTag.editTextTagID == null ? "NULL" : "valid"));
+ if (selectTag.editTextTagID != null) {
+ MainActivity.csLibrary4A.appendToLog("editTextRWTagID.setTTEXT " + tagSelected.getAddress());
+ selectTag.editTextTagID.setText(tagSelected.getAddress());
+ }
+
+ String stringDetail = tagSelected.getDetails();
+ int indexUser = stringDetail.indexOf("USER=");
+ if (indexUser != -1) {
+ String stringUser = stringDetail.substring(indexUser + 5);
+ MainActivity.csLibrary4A.appendToLog("stringUser = " + stringUser);
+
+ boolean bEnableBAPMode = false;
+ int number = Integer.valueOf(stringUser.substring(3, 4), 16);
+ if ((number % 2) == 1) bEnableBAPMode = true;
+// CheckBox checkBoxBAP = (CheckBox) getActivity().findViewById(R.id.coldChainEnableBAP);
+// checkBoxBAP.setChecked(bEnableBAPMode);
+ }
+
+ editTextAccessUCTid = (EditText) getActivity().findViewById(R.id.accessUCTid);
+ editTextAccessUCTid.setText(tagSelected.getTid());
+ }
+ }
+ }
+
+ private byte[] doubleSubKey(byte[] k) {
+ byte[] ret = new byte[k.length];
+
+ boolean firstBitSet = ((k[0]&0x80) != 0);
+ for (int i=0; i= 2) {
+ if (true) {
+ AesCmac mac = null;
+ mac = new AesCmac();
+ secretKey = new SecretKeySpec(key1, "AES");
+ mac.init(secretKey); //set master key
+ mac.updateBlock(dataIn); //given input
+ decValue = mac.doFinal();
+ } else if (true) {
+ cipher = Cipher.getInstance(strAlgo);
+ secretKey = new SecretKeySpec(key1, "AES");
+ cipher.init(Cipher.ENCRYPT_MODE, secretKey, new IvParameterSpec(iv));
+
+ // First calculate k0 from zero bytes
+ byte[] k0 = new byte[16];
+ cipher.update(k0, 0, k0.length, k0, 0);
+
+ // Calculate values for k1 and k2
+ byte[] k1 = doubleSubKey(k0);
+ byte[] k2 = doubleSubKey(k1);
+ cipher.init(Cipher.ENCRYPT_MODE, secretKey, new IvParameterSpec(iv));
+ int bufferCount;
+ } else if (false) {
+ secretKey = new SecretKeySpec(key1, "AES");
+ Mac hmac = Mac.getInstance("HmacSHA256"); //HmacMD5, HmacSHA1, HmacSHA256
+ hmac.init(secretKey);
+ hmac.update(iv);
+ decValue = hmac.doFinal(dataIn);
+ MainActivity.csLibrary4A.appendToLog("decValue1.length = " + decValue.length);
+ } else {
+ secretKey = new SecretKeySpec(key1, "AES");
+ cipher = Cipher.getInstance(strAlgo);
+ cipher.init(Cipher.ENCRYPT_MODE, secretKey, new IvParameterSpec(iv));
+ decValue = cipher.doFinal(dataIn);
+ }
+ String strMac = MainActivity.csLibrary4A.byteArrayToString(decValue).substring(0, 24);
+ editTextAuthResponseEncodedMac.setText(strMac);
+
+ strMatchResult += ", MAC";
+ strMatching = editTextAuthResponse.getText().toString();
+ while (strMatching.length() > 32)
+ strMatching = strMatching.substring(32).trim();
+ bMatch = false;
+ if (strMatching.matches(strMac)) bMatch = true;
+ if (bMatch) strMatchResult += " Matched";
+ else strMatchResult += " Not Matched";
+ }
+ }
+ Toast.makeText(MainActivity.mContext, strMatchResult, Toast.LENGTH_SHORT).show();
+ retValue = true;
+ }
+
+ if (false) {
+ secretKey = new SecretKeySpec(key, "HmacSHA256");
+ try {
+ Mac hmac = Mac.getInstance("HmacSHA256");
+
+ byte[] data2dec = dataIn;
+ byte[] iv = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
+
+ hmac.init(secretKey);
+ hmac.update(iv);
+ byte[] decValue = hmac.doFinal(data2dec);
+ MainActivity.csLibrary4A.appendToLog("decValue.length = " + decValue.length);
+ editTextAuthResponseEncodedMac.setText(MainActivity.csLibrary4A.byteArrayToString(decValue));
+ if (false) {
+ byte[] decValue16 = new byte[16];
+ System.arraycopy(decValue, 0, decValue16, 0, 16);
+ textViewAuthResponseDecoded.setText(MainActivity.csLibrary4A.byteArrayToString(decValue16));
+ if (protMode == 0 || protMode == 2) {
+ decValue16 = new byte[16];
+ System.arraycopy(data2dec, 16, decValue16, 0, 16);
+ } else {
+ decValue16 = new byte[16];
+ System.arraycopy(decValue, 16, decValue16, 0, 16);
+ }
+ textViewAuthResponseDecodedCustom.setText(MainActivity.csLibrary4A.byteArrayToString(decValue16));
+ retValue = true;
+ }
+ } catch (Exception ex) {
+ MainActivity.csLibrary4A.appendToLog("Error while encrypting: " + ex.toString());
+ }
+ }
+ } catch (Exception ex) {
+ MainActivity.csLibrary4A.appendToLog("Error while encrypting: " + ex.toString());
+ }
+ return retValue;
+ }
+ void startAccessTask() {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("startAccessTask()");
+ MainActivity.csLibrary4A.setInvAlgo(false);
+ if (MainActivity.csLibrary4A.getRetryCount() < 2) MainActivity.csLibrary4A.setRetryCount(2);
+ if (updating == false) {
+ updating = true; bankProcessing = 0;
+ mHandler.removeCallbacks(updateRunnable);
+ mHandler.post(updateRunnable);
+ }
+ }
+ boolean updating = false; int bankProcessing = 0;
+ private final Runnable updateRunnable = new Runnable() {
+ @Override
+ public void run() {
+ boolean rerunRequest = false; boolean taskRequest = false;
+ if (accessTask == null) {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("updateRunnable(): NULL accessReadWriteTask");
+ taskRequest = true;
+ } else if (accessTask.getStatus() != AsyncTask.Status.FINISHED) {
+ rerunRequest = true;
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("updateRunnable(): accessReadWriteTask.getStatus() = " + accessTask.getStatus().toString());
+ } else {
+ taskRequest = true;
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("updateRunnable(): FINISHED accessReadWriteTask");
+ }
+ if (processResult()) { rerunRequest = true; MainActivity.csLibrary4A.appendToLog("processResult is TRUE"); }
+ else if (taskRequest) {
+ boolean invalid = processTickItems();
+ MainActivity.csLibrary4A.appendToLog("processTickItems, invalid = " + invalid);
+ if (bankProcessing++ != 0 && invalid == true) rerunRequest = false;
+ else {
+ Button button;
+ if (readBufferChecked) button = buttonReadBuffer;
+ else if (authenChecked && authenTam1) button = buttonTam1;
+ else if (authenChecked) button = buttonTam2;
+ else if (untraceChecked) button = buttonUntrace;
+ else if (showEpcChecked) { if (strShowEpcButtonBackup == null) strShowEpcButtonBackup = buttonShowEpc.getText().toString(); buttonShowEpc.setText("Show"); button = buttonShowEpc; }
+ else if (operationRead) button = buttonRead;
+ else button = buttonWrite;
+
+ RfidReaderChipData.HostCommands hostCommand;
+ if (readBufferChecked) hostCommand = RfidReaderChipData.HostCommands.CMD_READBUFFER;
+ else if (authenChecked) hostCommand = RfidReaderChipData.HostCommands.CMD_18K6CAUTHENTICATE;
+ else if (untraceChecked || showEpcChecked) hostCommand = RfidReaderChipData.HostCommands.CMD_UNTRACEABLE;
+ else if (operationRead) hostCommand = RfidReaderChipData.HostCommands.CMD_18K6CREAD;
+ else hostCommand = RfidReaderChipData.HostCommands.CMD_18K6CWRITE;
+
+ accessTask = new AccessTask(button, null, invalid, true,
+ selectTag.editTextTagID.getText().toString(), 1, 32,
+ selectTag.editTextAccessPassword.getText().toString(), Integer.valueOf(selectTag.editTextAccessAntennaPower.getText().toString()), hostCommand,
+ 0, 0, true, false,
+ null, null, null, null, null);
+ accessTask.execute();
+ rerunRequest = true;
+ MainActivity.csLibrary4A.appendToLog("accessTask is created");
+ }
+ }
+ if (rerunRequest) {
+ mHandler.postDelayed(updateRunnable, 500);
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("updateRunnable(): Restart");
+ }
+ else updating = false;
+ MainActivity.csLibrary4A.appendToLog("updateRunnable(): Ending with updating = " + updating);
+ }
+ };
+
+ short setTemperature(float fTemperature) {
+ if (fTemperature > 63.75) fTemperature = (float) 63.75;
+ else if (fTemperature < -64) fTemperature = -64;
+ boolean bNegative = false;
+ if (fTemperature < 0) { bNegative = true; fTemperature = 0 - fTemperature; }
+ fTemperature += 0.125; fTemperature /= 0.25;
+ short retValue = (short)fTemperature;
+ if (bNegative) { retValue--; retValue &= 0xFF; retValue ^= 0xFF; retValue |= 0x100; }
+ return retValue;
+ }
+ String getTemperatue(String stringInput) {
+ byte bValue = Byte.parseByte(stringInput.substring(0,1), 16);
+ byte bValue2 = Byte.parseByte(stringInput.substring(1, 2), 16); bValue2 <<= 4;
+ byte bValue3 = Byte.parseByte(stringInput.substring(2, 3), 16); bValue2 |= bValue3;
+ String stringValue = ""; short sValue = (short)(bValue2 & 0xFF);
+ if ((bValue & 0x01) != 0) { stringValue = "-"; bValue2 ^= 0xFF; sValue = (short)(bValue2 & 0xFF); sValue++; }
+ stringValue += String.valueOf((sValue & 0x1FF) >> 2);
+ switch (sValue & 0x03) {
+ case 1:
+ stringValue += ".25";
+ break;
+ case 2:
+ stringValue += ".50";
+ break;
+ case 3:
+ stringValue += ".75";
+ break;
+ }
+ return stringValue;
+ }
+
+ boolean processResult() {
+ String accessResult = null;
+ if (accessTask == null) return false;
+ else if (accessTask.getStatus() != AsyncTask.Status.FINISHED) return false;
+ else {
+ accessResult = accessTask.accessResult;
+ if (readBufferChecked) readBufferChecked = false;
+ else if (authenChecked) {
+ authenChecked = false; if (accessResult != null) {
+ String strValue = "";
+ for (int i = 0; i < accessResult.length(); i += 32) {
+ int i_end = i + 32; if (i_end >= accessResult.length()) i_end = accessResult.length();
+ if (i != 0) strValue += "\n";
+ strValue += accessResult.substring(i, i_end);
+ }
+ editTextAuthResponse.setText(strValue);
+ if (bImpinJTag) {
+ LinearLayout layout = (LinearLayout) getActivity().findViewById(R.id.accessUCImpinjLayout);
+ if (authenTam1) layout.setVisibility(View.VISIBLE);
+ else layout.setVisibility(View.GONE);
+ } else processAESdata(accessResult);
+ }
+ }
+ else if (untraceChecked) untraceChecked = false;
+ else if (showEpcChecked) { showEpcChecked = false; if (strShowEpcButtonBackup != null) buttonShowEpc.setText(strShowEpcButtonBackup); strShowEpcButtonBackup = null; }
+ else if (accessResult == null) {
+ if (readWriteTypes == ReadWriteTypes.AESKEY0ACTIVATE) {
+ textViewAesKey0ActivateOk.setText("E"); checkBoxAesKey0Activate.setChecked(false);
+ } else if (readWriteTypes == ReadWriteTypes.AESKEY1ACTIVATE) {
+ textViewAesKey1ActivateOk.setText("E"); checkBoxAesKey1Activate.setChecked(false);
+ } else if (readWriteTypes == ReadWriteTypes.AESKEY0) {
+ textViewAesKey0Ok.setText("E"); checkBoxAesKey0.setChecked(false);
+ } else if (readWriteTypes == ReadWriteTypes.AESKEY1) {
+ textViewAesKey1Ok.setText("E"); checkBoxAesKey1.setChecked(false);
+ }
+ } else {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("accessResult = " + accessResult);
+ if (readWriteTypes == ReadWriteTypes.AESKEY0ACTIVATE) {
+ textViewAesKey0ActivateOk.setText("O"); checkBoxAesKey0Activate.setChecked(false); readWriteTypes = ReadWriteTypes.NULL;
+ } else if (readWriteTypes == ReadWriteTypes.AESKEY1ACTIVATE) {
+ textViewAesKey1ActivateOk.setText("O"); checkBoxAesKey1Activate.setChecked(false); readWriteTypes = ReadWriteTypes.NULL;
+ } else if (readWriteTypes == ReadWriteTypes.AESKEY0) {
+ textViewAesKey0Ok.setText("O"); checkBoxAesKey0.setChecked(false); readWriteTypes = ReadWriteTypes.NULL;
+ if (operationRead) editTextAesKey0.setText(accessResult);
+ } else if (readWriteTypes == ReadWriteTypes.AESKEY1) {
+ textViewAesKey1Ok.setText("O"); checkBoxAesKey1.setChecked(false); readWriteTypes = ReadWriteTypes.NULL;
+ if (operationRead) editTextAesKey1.setText(accessResult);
+ }
+ }
+ accessTask = null;
+ return true;
+ }
+ }
+ boolean processTickItems() {
+ boolean invalidRequest1 = false;
+ int accSize = 0, accOffset = 0, accBank = 3;
+ String writeData = "";
+
+ if (readBufferChecked) {
+ accOffset = 0; accSize = 1;
+ } else if (authenChecked) {
+ if (authenTam1) {
+ if (bImpinJTag) {
+ if (MainActivity.csLibrary4A.setTamConfiguration(false, strChallenge) == false)
+ invalidRequest1 = true;
+ } else if (MainActivity.csLibrary4A.setTam1Configuration(keyId, strChallenge) == false)
+ invalidRequest1 = true;
+ } else if (bImpinJTag) {
+ if (MainActivity.csLibrary4A.setTamConfiguration(true, strChallenge) == false)
+ invalidRequest1 = true;
+ } else if (MainActivity.csLibrary4A.setTam2Configuration(keyId, strChallenge, profile, offset, blockId, protMode) == false)
+ invalidRequest1 = true;
+ if (invalidRequest1 == false) { editTextAuthResponse.setText(""); textViewAuthResponseDecoded.setText(""); textViewAuthResponseDecodedCustom.setText(""); editTextAuthResponseEncodedMac.setText(""); }
+ return invalidRequest1;
+ } else if (untraceChecked) {
+ if (MainActivity.csLibrary4A.setUntraceable(checkBoxHideEpc.isChecked(), checkBoxHideEpc.isChecked() ? 2 : 6, checkBoxHideTid.isChecked() ? 1: 0, checkBoxHideUser.isChecked(), checkBoxHideRange.isChecked()) == false) invalidRequest1 = true;
+ return invalidRequest1;
+ } else if (showEpcChecked) {
+ try {
+ if (MainActivity.csLibrary4A.setUntraceable(false, Integer.parseInt(editTextEpcSize.getText().toString()), 0, false, false) == false) invalidRequest1 = true;
+ } catch (Exception ex) {
+ invalidRequest1 = true;
+ }
+ return invalidRequest1;
+ } else if (checkBoxAesKey0Activate.isChecked() == true) {
+ accOffset = 0xC8; accSize = 1; readWriteTypes = ReadWriteTypes.AESKEY0ACTIVATE; textViewAesKey0ActivateOk.setText("");
+ if (operationRead == false) writeData = "E200";
+ } else if (checkBoxAesKey1Activate.isChecked() == true) {
+ accOffset = 0xD8; accSize = 1; readWriteTypes = ReadWriteTypes.AESKEY1ACTIVATE; textViewAesKey0ActivateOk.setText("");
+ if (operationRead == false) writeData = "E200";
+ } else if (checkBoxAesKey0.isChecked() == true) {
+ accOffset = 0xC0; if (iTagType == 5) { accOffset = 0x10; accBank = 0; }
+ accSize = 8; readWriteTypes = ReadWriteTypes.AESKEY0; textViewAesKey0Ok.setText("");
+ if (operationRead) editTextAesKey0.setText("");
+ else writeData = editTextAesKey0.getText().toString();
+ } else if (checkBoxAesKey1.isChecked() == true) {
+ accOffset = 0xD0; if (iTagType == 5) { accOffset = 0x18; accBank = 0; }
+ accSize = 8; readWriteTypes = ReadWriteTypes.AESKEY1; textViewAesKey1Ok.setText("");
+ if (operationRead) editTextAesKey1.setText("");
+ else writeData = editTextAesKey1.getText().toString();
+ } else {
+ invalidRequest1 = true;
+ }
+
+ if (invalidRequest1 == false) {
+ if (MainActivity.csLibrary4A.setAccessBank(accBank) == false) {
+ invalidRequest1 = true;
+ }
+ }
+ if (invalidRequest1 == false) {
+ if (MainActivity.csLibrary4A.setAccessOffset(accOffset) == false) {
+ invalidRequest1 = true;
+ }
+ }
+ if (invalidRequest1 == false) {
+ if (accSize == 0) {
+ invalidRequest1 = true;
+ } else if (MainActivity.csLibrary4A.setAccessCount(accSize) == false) {
+ invalidRequest1 = true;
+ }
+ }
+ if (invalidRequest1 == false && operationRead == false) {
+ if (invalidRequest1 == false) {
+ if (MainActivity.csLibrary4A.setAccessWriteData(writeData) == false) {
+ invalidRequest1 = true;
+ }
+ }
+ }
+ return invalidRequest1;
+ }
+}
+
+
+
+package com.csl.cs710ademoapp.fragments;
+
+import androidx.lifecycle.Lifecycle;
+import android.os.AsyncTask;
+import android.os.Bundle;
+import android.text.InputType;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.AdapterView;
+import android.widget.ArrayAdapter;
+import android.widget.Button;
+import android.widget.CheckBox;
+import android.widget.EditText;
+import android.widget.Spinner;
+import android.widget.TextView;
+import android.widget.Toast;
+
+import com.csl.cs710ademoapp.AccessTask;
+import com.csl.cs710ademoapp.GenericTextWatcher;
+import com.csl.cs710ademoapp.MainActivity;
+import com.csl.cs710ademoapp.R;
+import com.csl.cslibrary4a.ReaderDevice;
+import com.csl.cslibrary4a.RfidReaderChipData;
+
+public class AccessXerxesLoggerFragment extends CommonFragment {
+ final boolean DEBUG = true;
+ boolean bXerxesEnable = false;
+ EditText editTextRWTagID, editTextAccessRWAccPassword, editTextaccessRWAntennaPower;
+ TextView textViewUserCode1OK, textViewUserCode2OK, textViewUserCode3OK, textViewUserCode4OK, textViewUserCode5OK;
+ CheckBox checkBoxUserCode1, checkBoxUserCode2, checkBoxUserCode3, checkBoxUserCode4, checkBoxUserCode5;
+ EditText editTextUserCode1, editTextUserCode2, editTextUserCode3, editTextUserCode4, editTextUserCode5;
+ Spinner spinnerUserCode2Unit, spinnerUserCode3Unit; int iUserCode2UnitPosition, iUserCode3UnitPosition;
+ String strReadUserCode1, strReadUserCode2, strReadUserCode3, strReadUserCode4, strReadUserCode5;
+ private Button buttonRead, buttonWrite;
+
+ enum ReadWriteTypes {
+ NULL, USERCODE1, USERCODE2, USERCODE3, USERCODE4, USERCODE5
+ }
+ ReadWriteTypes readWriteTypes;
+ boolean operationRead = false;
+
+ private AccessTask accessTask;
+ private int modelCode = 0;
+ private int calCode1, calTemp1, calCode2, calTemp2, calVer = -1;
+ private boolean changedSelectIndex = false;
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ super.onCreateView(inflater, container, savedInstanceState, false);
+ return inflater.inflate(R.layout.fragment_access_xerxes, container, false);
+ }
+
+ @Override
+ public void onActivityCreated(Bundle savedInstanceState) {
+ super.onActivityCreated(savedInstanceState);
+
+ editTextRWTagID = (EditText) getActivity().findViewById(R.id.accessXXTagID);
+ editTextAccessRWAccPassword = (EditText) getActivity().findViewById(R.id.accessXXAccPasswordValue);
+ editTextAccessRWAccPassword.addTextChangedListener(new GenericTextWatcher(editTextAccessRWAccPassword, 8));
+ editTextAccessRWAccPassword.setText("00000000");
+
+ textViewUserCode1OK = (TextView) getActivity().findViewById(R.id.accessXXXerxes1OK);
+ textViewUserCode2OK = (TextView) getActivity().findViewById(R.id.accessXXXerxes2OK);
+ textViewUserCode3OK = (TextView) getActivity().findViewById(R.id.accessXXXerxes3OK);
+ textViewUserCode4OK = (TextView) getActivity().findViewById(R.id.accessXXXerxes4OK);
+ textViewUserCode5OK = (TextView) getActivity().findViewById(R.id.accessXXXerxes5OK);
+
+ checkBoxUserCode1 = (CheckBox) getActivity().findViewById(R.id.accessXXXerxees1Title); checkBoxUserCode1.setText("Log number:");
+ checkBoxUserCode2 = (CheckBox) getActivity().findViewById(R.id.accessXXXerxees2Title); checkBoxUserCode2.setText("Temperature:");
+ checkBoxUserCode3 = (CheckBox) getActivity().findViewById(R.id.accessXXXerxees3Title); checkBoxUserCode3.setText("Maximum temperature:");
+ checkBoxUserCode4 = (CheckBox) getActivity().findViewById(R.id.accessXXXerxees4Title); checkBoxUserCode4.setText("Alarm high trigger count:");
+ checkBoxUserCode5 = (CheckBox) getActivity().findViewById(R.id.accessXXXerxees5Title); checkBoxUserCode5.setText("Alarm low trigger count:");
+
+ editTextUserCode1 = (EditText) getActivity().findViewById(R.id.accessXXXerxes1Code); editTextUserCode1.setInputType(InputType.TYPE_CLASS_NUMBER);
+ editTextUserCode2 = (EditText) getActivity().findViewById(R.id.accessXXXerxes2Code); editTextUserCode2.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL | InputType.TYPE_NUMBER_FLAG_SIGNED);
+ editTextUserCode3 = (EditText) getActivity().findViewById(R.id.accessXXXerxes3Code); editTextUserCode3.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL | InputType.TYPE_NUMBER_FLAG_SIGNED);
+ editTextUserCode4 = (EditText) getActivity().findViewById(R.id.accessXXXerxes4Code); editTextUserCode4.setInputType(InputType.TYPE_CLASS_NUMBER);
+ editTextUserCode5 = (EditText) getActivity().findViewById(R.id.accessXXXerxes5Code); editTextUserCode5.setInputType(InputType.TYPE_CLASS_NUMBER);
+
+ ArrayAdapter arrayAdapterUserCode2Unit = ArrayAdapter.createFromResource(getActivity(), R.array.temperature_unit_options, R.layout.custom_spinner_layout);
+ arrayAdapterUserCode2Unit.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+ spinnerUserCode2Unit = (Spinner) getActivity().findViewById(R.id.accessXXXerxes2Unit);
+ spinnerUserCode2Unit.setAdapter(arrayAdapterUserCode2Unit);
+ spinnerUserCode2Unit.setSelection(0); iUserCode2UnitPosition = 0;
+ spinnerUserCode2Unit.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
+ @Override
+ public void onItemSelected(AdapterView> adapterView, View view, int i, long l) {
+ if (i != iUserCode2UnitPosition) {
+ String strValue = editTextUserCode2.getText().toString();
+ if (iUserCode2UnitPosition == 0 && i == 1) strValue = MainActivity.csLibrary4A.temperatureC2F(strValue);
+ else if (iUserCode2UnitPosition == 1 && i == 0) strValue = MainActivity.csLibrary4A.temperatureF2C(strValue);
+ editTextUserCode2.setText(strValue);
+ }
+ iUserCode2UnitPosition = i;
+ }
+
+ @Override
+ public void onNothingSelected(AdapterView> adapterView) {
+ }
+ });
+
+ spinnerUserCode3Unit = (Spinner) getActivity().findViewById(R.id.accessXXXerxes3Unit);
+ spinnerUserCode3Unit.setAdapter(arrayAdapterUserCode2Unit);
+ spinnerUserCode3Unit.setSelection(0); iUserCode3UnitPosition = 0;
+ spinnerUserCode3Unit.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
+ @Override
+ public void onItemSelected(AdapterView> adapterView, View view, int i, long l) {
+ if (i != iUserCode3UnitPosition) {
+ String strValue = editTextUserCode3.getText().toString();
+ if (iUserCode3UnitPosition == 0 && i == 1) strValue = MainActivity.csLibrary4A.temperatureC2F(strValue);
+ else if (iUserCode3UnitPosition == 1 && i == 0) strValue = MainActivity.csLibrary4A.temperatureF2C(strValue);
+ editTextUserCode3.setText(strValue);
+ }
+ iUserCode3UnitPosition = i;
+ }
+
+ @Override
+ public void onNothingSelected(AdapterView> adapterView) {
+ }
+ });
+
+ editTextaccessRWAntennaPower = (EditText) getActivity().findViewById(R.id.accessXXAntennaPower);
+ editTextaccessRWAntennaPower.setText(String.valueOf(300));
+
+ buttonRead = (Button) getActivity().findViewById(R.id.accessRWReadButton);
+ buttonRead.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (MainActivity.csLibrary4A.isBleConnected() == false) {
+ Toast.makeText(MainActivity.mContext, R.string.toast_ble_not_connected, Toast.LENGTH_SHORT).show();
+ return;
+ } else if (MainActivity.csLibrary4A.isRfidFailure()) {
+ Toast.makeText(MainActivity.mContext, "Rfid is disabled", Toast.LENGTH_SHORT).show();
+ return;
+ }
+ operationRead = true; startAccessTask();
+ }
+ });
+
+ buttonWrite = (Button) getActivity().findViewById(R.id.accessRWWriteButton);
+ buttonWrite.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (MainActivity.csLibrary4A.isBleConnected() == false) {
+ Toast.makeText(MainActivity.mContext, R.string.toast_ble_not_connected, Toast.LENGTH_SHORT).show();
+ return;
+ } else if (MainActivity.csLibrary4A.isRfidFailure()) {
+ Toast.makeText(MainActivity.mContext, "Rfid is disabled", Toast.LENGTH_SHORT).show();
+ return;
+ }
+ operationRead = false; startAccessTask();
+ }
+ });
+
+ MainActivity.csLibrary4A.setSameCheck(false);
+ }
+
+ @Override
+ public void onResume() {
+ super.onResume();
+ setupTagID();
+ }
+
+ @Override
+ public void onDestroy() {
+ if (accessTask != null) accessTask.cancel(true);
+ MainActivity.csLibrary4A.setSameCheck(true);
+ super.onDestroy();
+ }
+
+ boolean userVisibleHint = false;
+ @Override
+ public void setUserVisibleHint(boolean isVisibleToUser) {
+ super.setUserVisibleHint(isVisibleToUser);
+ if (getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.RESUMED) == false) return;
+ if(getUserVisibleHint()) {
+ userVisibleHint = true;
+ setupTagID();
+ } else {
+ userVisibleHint = false;
+ }
+ }
+
+ public AccessXerxesLoggerFragment() {
+ super("AccessXerxesLoggerFragment");
+ }
+
+ void setupTagID() {
+ ReaderDevice tagSelected = MainActivity.tagSelected;
+ boolean bSelected = false;
+ if (tagSelected != null) {
+ if (tagSelected.getSelected() == true) {
+ String stringDetail = tagSelected.getDetails();
+ int indexUser = stringDetail.indexOf("TID=");
+ if (indexUser != -1) {
+ //
+ }
+ bSelected = true;
+ if (editTextRWTagID != null) editTextRWTagID.setText(tagSelected.getAddress());
+
+ if (tagSelected.getMdid() == null) {
+ } else if (tagSelected.getMdid().contains("E282402")) {
+ modelCode = 2;
+ } else if (tagSelected.getMdid().contains("E282403")) {
+ modelCode = 3;
+ } else if (tagSelected.getMdid().contains("E282405")) {
+ modelCode = 5;
+ }
+
+ String strRes = tagSelected.getRes();
+ if (strRes != null) {
+ int ibracket = strRes.indexOf("(");
+ if (ibracket > 0) strRes = strRes.substring(0, ibracket);
+ }
+
+ stringDetail = tagSelected.getDetails();
+ indexUser = stringDetail.indexOf("USER=");
+ if (indexUser != -1) {
+ String stringUser = stringDetail.substring(indexUser + 5);
+ MainActivity.csLibrary4A.appendToLog("stringUser = " + stringUser);
+
+ boolean bEnableBAPMode = false;
+ int number = Integer.valueOf(stringUser.substring(3, 4), 16);
+ if ((number % 2) == 1) bEnableBAPMode = true;
+ }
+ }
+ }
+ }
+
+ void startAccessTask() {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("startAccessTask()");
+ if (updating == false) {
+ updating = true; bankProcessing = 0;
+ checkProcessing = 0;
+ mHandler.removeCallbacks(updateRunnable);
+ mHandler.post(updateRunnable);
+ }
+ }
+ boolean updating = false; int bankProcessing = 0;
+ int checkProcessing = 0;
+ private final Runnable updateRunnable = new Runnable() {
+ @Override
+ public void run() {
+ boolean rerunRequest = false; boolean taskRequest = false;
+ if (accessTask == null) {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("AccessXerxesLoggerFragment().updateRunnable(): NULL accessReadWriteTask");
+ taskRequest = true;
+ } else if (accessTask.getStatus() != AsyncTask.Status.FINISHED) {
+ rerunRequest = true;
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("AccessXerxesLoggerFragment().updateRunnable(): accessReadWriteTask.getStatus() = " + accessTask.getStatus().toString());
+ } else {
+ taskRequest = true;
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("AccessXerxesLoggerFragment().updateRunnable(): FINISHED accessReadWriteTask");
+ }
+ if (processResult()) { rerunRequest = true; MainActivity.csLibrary4A.appendToLog("processResult is TRUE");}
+ else if (taskRequest) {
+ boolean invalid = processTickItems();
+ MainActivity.csLibrary4A.appendToLog("processTickItems, invalid = " + invalid);
+ if (bankProcessing++ != 0 && invalid == true) rerunRequest = false;
+ else {
+ int selectBank = 1;
+ int selectOffset = 32;
+ String selectMask = editTextRWTagID.getText().toString();
+ accessTask = new AccessTask((operationRead ? buttonRead : buttonWrite), null, invalid, true,
+ selectMask, selectBank, selectOffset,
+ editTextAccessRWAccPassword.getText().toString(), Integer.valueOf(editTextaccessRWAntennaPower.getText().toString()), (operationRead ? RfidReaderChipData.HostCommands.CMD_18K6CREAD: RfidReaderChipData.HostCommands.CMD_18K6CWRITE),
+ 0, 0, true, false,
+ null, null, null, null, null);
+ accessTask.execute();
+ rerunRequest = true;
+ MainActivity.csLibrary4A.appendToLog("accessTask is created with selectBank = " + selectBank);
+ }
+ }
+ if (rerunRequest) {
+ mHandler.postDelayed(updateRunnable, 500);
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("AccessXerxesLoggerFragment().updateRunnable(): Restart");
+ }
+ else updating = false;
+ MainActivity.csLibrary4A.appendToLog("AccessXerxesLoggerFragment().updateRunnable(): Ending with updating = " + updating);
+ }
+ };
+
+ boolean setTemperatureCode(String strData, int iTempIndex) {
+ if (strData == null) return false;
+ if (strData.length() < 4) return false;
+
+ String strValue = MainActivity.csLibrary4A.strFloat16toFloat32(strData);
+ if (strValue == null) return false;
+ else {
+ if ( (iTempIndex == 0 && spinnerUserCode2Unit.getSelectedItemPosition() == 1)
+ || (iTempIndex == 1 && spinnerUserCode3Unit.getSelectedItemPosition() == 1) )
+ strValue = MainActivity.csLibrary4A.temperatureC2F(strValue);
+ if (iTempIndex == 0) editTextUserCode2.setText(strValue);
+ else editTextUserCode3.setText(strValue);
+ }
+ return true;
+ }
+
+ boolean processResult() {
+ String accessResult = null;
+ if (accessTask == null) return false;
+ else if (accessTask.getStatus() != AsyncTask.Status.FINISHED) return false;
+ else {
+ if (changedSelectIndex) {
+ changedSelectIndex = false; MainActivity.selectFor = 0;
+ MainActivity.csLibrary4A.setSelectCriteriaDisable(-1);
+ }
+ accessResult = accessTask.accessResult;
+ if (accessResult == null) {
+ if (readWriteTypes == ReadWriteTypes.USERCODE1) {
+ textViewUserCode1OK.setText("E");
+ //checkBoxUserCode1.setChecked(false);
+ } else if (readWriteTypes == ReadWriteTypes.USERCODE2) {
+ textViewUserCode2OK.setText("E");
+ //checkBoxUserCode2.setChecked(false);
+ } else if (readWriteTypes == ReadWriteTypes.USERCODE3) {
+ textViewUserCode3OK.setText("E");
+ //checkBoxUserCode3.setChecked(false);
+ } else if (readWriteTypes == ReadWriteTypes.USERCODE4) {
+ textViewUserCode4OK.setText("E");
+ //checkBoxUserCode4.setChecked(false);
+ } else if (readWriteTypes == ReadWriteTypes.USERCODE5) {
+ textViewUserCode5OK.setText("E");
+ //checkBoxUserCode5.setChecked(false);
+ }
+ } else {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("accessResult = " + accessResult);
+ if (readWriteTypes == ReadWriteTypes.USERCODE1) {
+ textViewUserCode1OK.setText("O");
+ //checkBoxUserCode1.setChecked(false);
+ readWriteTypes = ReadWriteTypes.NULL;
+ if (operationRead) {
+ int iValue = Integer.parseInt(accessResult, 16);
+ strReadUserCode1 = String.valueOf(iValue);
+ editTextUserCode1.setText(strReadUserCode1);
+ }
+ } else if (readWriteTypes == ReadWriteTypes.USERCODE2) {
+ textViewUserCode2OK.setText("O");
+ //checkBoxUserCode2.setChecked(false);
+ readWriteTypes = ReadWriteTypes.NULL;
+ if (operationRead) setTemperatureCode(accessResult, 0);
+ } else if (readWriteTypes == ReadWriteTypes.USERCODE3) {
+ textViewUserCode3OK.setText("O");
+ //checkBoxUserCode3.setChecked(false);
+ readWriteTypes = ReadWriteTypes.NULL;
+ if (operationRead) setTemperatureCode(accessResult, 1);
+ } else if (readWriteTypes == ReadWriteTypes.USERCODE4) {
+ textViewUserCode4OK.setText("O");
+ //checkBoxUserCode4.setChecked(false);
+ readWriteTypes = ReadWriteTypes.NULL;
+ if (operationRead) {
+ int iValue = Integer.parseInt(accessResult, 16);
+ strReadUserCode4 = String.valueOf(iValue);
+ editTextUserCode4.setText(strReadUserCode4);
+ }
+ } else if (readWriteTypes == ReadWriteTypes.USERCODE5) {
+ textViewUserCode5OK.setText("O");
+ //checkBoxUserCode5.setChecked(false);
+ readWriteTypes = ReadWriteTypes.NULL;
+ if (operationRead) {
+ int iValue = Integer.parseInt(accessResult, 16);
+ strReadUserCode5 = String.valueOf(iValue);
+ editTextUserCode5.setText(strReadUserCode5);
+ }
+ }
+ }
+ accessTask = null;
+ return true;
+ }
+ }
+
+ boolean processTickItems() {
+ boolean invalidRequest1 = false;
+ int accBank = 0, accSize = 0, accOffset = 0;
+ String writeData = "";
+
+ if (editTextRWTagID.getText().toString().length() == 0) invalidRequest1 = true;
+ else if (checkBoxUserCode1.isChecked() == true && checkProcessing < 1 && modelCode == 5) {
+ accBank = 3; accSize = 1; accOffset = 2; readWriteTypes = ReadWriteTypes.USERCODE1; checkProcessing = 1;
+ if (operationRead) {
+ textViewUserCode1OK.setText("");
+ editTextUserCode1.setText("");
+ } else {
+ String strValue = editTextUserCode1.getText().toString();
+ if (strValue.length() == 0) invalidRequest1 = true;
+ else {
+ int iValue = Integer.parseInt(strValue);
+ if (iValue > 0xFFFF) invalidRequest1 = true;
+ else writeData = String.format("%04X", iValue);
+ }
+ }
+ } else if (checkBoxUserCode2.isChecked() == true && checkProcessing < 2 && modelCode == 5) {
+ accBank = 3; accSize = 1; accOffset = 3; readWriteTypes = ReadWriteTypes.USERCODE2; checkProcessing = 2;
+ if (operationRead) {
+ textViewUserCode2OK.setText("");
+ editTextUserCode2.setText("");
+ } else {
+ String strValue = editTextUserCode2.getText().toString();
+ if (strValue.length() == 0) invalidRequest1 = true;
+ else {
+ if (spinnerUserCode2Unit.getSelectedItemPosition() == 1) strValue = MainActivity.csLibrary4A.temperatureF2C(strValue);
+ strValue = MainActivity.csLibrary4A.str2float16(strValue);
+ if (strValue.length() != 4) invalidRequest1 = true;
+ else writeData = strValue;
+ }
+ }
+ } else if (checkBoxUserCode3.isChecked() == true && checkProcessing < 3 && modelCode == 5) {
+ accBank = 3; accSize = 1; accOffset = 4; readWriteTypes = ReadWriteTypes.USERCODE3; checkProcessing = 3;
+ if (operationRead) {
+ textViewUserCode3OK.setText("");
+ editTextUserCode3.setText("");
+ } else {
+ String strValue = editTextUserCode3.getText().toString();
+ if (strValue.length() == 0) invalidRequest1 = true;
+ else {
+ if (spinnerUserCode3Unit.getSelectedItemPosition() == 1) strValue = MainActivity.csLibrary4A.temperatureF2C(strValue);
+ strValue = MainActivity.csLibrary4A.str2float16(strValue);
+ if (strValue.length() != 4) invalidRequest1 = true;
+ else writeData = strValue;
+ }
+ }
+ } else if (checkBoxUserCode4.isChecked() == true && checkProcessing < 4 && modelCode == 5) {
+ accBank = 3; accSize = 1; accOffset = 5; readWriteTypes = ReadWriteTypes.USERCODE4; checkProcessing = 4;
+ if (operationRead) {
+ textViewUserCode4OK.setText("");
+ editTextUserCode4.setText("");
+ } else {
+ String strValue = editTextUserCode4.getText().toString();
+ if (strValue.length() == 0) invalidRequest1 = true;
+ else {
+ int iValue = Integer.parseInt(strValue);
+ if (iValue > 0xFFFF) invalidRequest1 = true;
+ else writeData = String.format("%04X", iValue);
+ }
+ }
+ } else if (checkBoxUserCode5.isChecked() == true && checkProcessing < 5 && modelCode == 5) {
+ accBank = 3; accSize = 1; accOffset = 6; readWriteTypes = ReadWriteTypes.USERCODE5; checkProcessing = 5;
+ if (operationRead) {
+ textViewUserCode5OK.setText("");
+ editTextUserCode5.setText("");
+ } else {
+ String strValue = editTextUserCode5.getText().toString();
+ if (strValue.length() == 0) invalidRequest1 = true;
+ else {
+ int iValue = Integer.parseInt(strValue);
+ if (iValue > 0xFFFF) invalidRequest1 = true;
+ else writeData = String.format("%04X", iValue);
+ }
+ }
+ } else {
+ invalidRequest1 = true;
+ }
+
+ if (invalidRequest1 == false) {
+ if (MainActivity.csLibrary4A.setAccessBank(accBank) == false) {
+ invalidRequest1 = true;
+ }
+ }
+ if (invalidRequest1 == false) {
+ if (MainActivity.csLibrary4A.setAccessOffset(accOffset) == false) {
+ invalidRequest1 = true;
+ }
+ }
+ if (invalidRequest1 == false) {
+ if (accSize == 0) {
+ invalidRequest1 = true;
+ } else if (MainActivity.csLibrary4A.setAccessCount(accSize) == false) {
+ invalidRequest1 = true;
+ }
+ }
+ if (invalidRequest1 == false && operationRead == false) {
+ if (invalidRequest1 == false) {
+ if (MainActivity.csLibrary4A.setAccessWriteData(writeData) == false) {
+ invalidRequest1 = true;
+ }
+ }
+ }
+ return invalidRequest1;
+ }
+}
+
+
+
+package com.csl.cs710ademoapp.fragments;
+
+import static com.csl.cslibrary4a.RfidReader.TagType.TAG_EM_AURASENSE;
+
+import android.os.Bundle;
+
+import com.google.android.material.tabs.TabLayout;
+import androidx.fragment.app.Fragment;
+import androidx.fragment.app.FragmentManager;
+import androidx.fragment.app.FragmentStatePagerAdapter;
+import androidx.viewpager.widget.PagerAdapter;
+import androidx.viewpager.widget.ViewPager;
+import androidx.appcompat.app.ActionBar;
+import androidx.appcompat.app.AppCompatActivity;
+import android.view.LayoutInflater;
+import android.view.MenuItem;
+import android.view.View;
+import android.view.ViewGroup;
+
+import com.csl.cs710ademoapp.MainActivity;
+import com.csl.cs710ademoapp.R;
+
+public class AuraSenseFragment extends CommonFragment {
+ private ActionBar actionBar;
+ private ViewPager viewPager;
+ AuraSenseAdapter mAdapter;
+
+ private String[] tabs = {"Configuration", "Scan" };
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ super.onCreateView(inflater, container, savedInstanceState, true);
+ return inflater.inflate(R.layout.custom_tabbed_layout, container, false);
+ }
+
+ @Override
+ public boolean onOptionsItemSelected(MenuItem item) {
+ InventoryRfidiMultiFragment fragment1 = (InventoryRfidiMultiFragment) mAdapter.fragment1;
+ if (item.getItemId() == R.id.menuAction_clear) {
+ fragment1.clearTagsList();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_sortRssi) {
+ fragment1.sortTagsListByRssi();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_sort) {
+ fragment1.sortTagsList();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_save) {
+ fragment1.saveTagsList();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_share) {
+ fragment1.shareTagsList();
+ return true;
+ } else return super.onOptionsItemSelected(item);
+ }
+
+ @Override
+ public void onActivityCreated(Bundle savedInstanceState) {
+ super.onActivityCreated(savedInstanceState);
+
+ actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
+ actionBar.setIcon(R.drawable.dl_inv);
+ actionBar.setTitle(R.string.title_activity_auraSense);
+
+ TabLayout tabLayout = (TabLayout) getActivity().findViewById(R.id.OperationsTabLayout);
+
+ mAdapter = new AuraSenseAdapter(getActivity().getSupportFragmentManager());
+ viewPager = (ViewPager) getActivity().findViewById(R.id.OperationsPager);
+ viewPager.setAdapter(mAdapter);
+ viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
+
+ for (String tab_name : tabs) {
+ tabLayout.addTab(tabLayout.newTab().setText(tab_name));
+ }
+
+ tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
+ @Override
+ public void onTabSelected(TabLayout.Tab tab) {
+ viewPager.setCurrentItem(tab.getPosition());
+ }
+
+ @Override
+ public void onTabUnselected(TabLayout.Tab tab) {
+ }
+
+ @Override
+ public void onTabReselected(TabLayout.Tab tab) {
+ }
+ });
+ }
+
+ @Override
+ public void onPause() {
+ mAdapter.fragment0.onPause();
+ mAdapter.fragment1.onPause();
+ super.onPause();
+ }
+
+ @Override
+ public void onStop() {
+ mAdapter.fragment0.onStop();
+ mAdapter.fragment1.onStop();
+ super.onStop();
+ }
+
+ @Override
+ public void onDestroyView() {
+ mAdapter.fragment0.onDestroyView();
+ mAdapter.fragment1.onDestroyView();
+ super.onDestroyView();
+ }
+
+ @Override
+ public void onDestroy() {
+ mAdapter.fragment0.onDestroy();
+ mAdapter.fragment1.onDestroy();
+ MainActivity.csLibrary4A.setSelectCriteriaDisable(-1);
+ MainActivity.csLibrary4A.setSameCheck(true);
+ MainActivity.csLibrary4A.restoreAfterTagSelect();
+ super.onDestroy();
+ }
+
+ @Override
+ public void onDetach() {
+ mAdapter.fragment0.onDetach();
+ mAdapter.fragment1.onDetach();
+ super.onDetach();
+ }
+
+ public AuraSenseFragment() {
+ super("AuraSenseFragment");
+ }
+
+ class AuraSenseAdapter extends FragmentStatePagerAdapter {
+ private final int NO_OF_TABS = 2;
+ public Fragment fragment0, fragment1, fragment2;
+
+ @Override
+ public Fragment getItem(int index) {
+ Fragment fragment = null;
+ switch (index) {
+ case 0:
+ fragment = new AccessAuraSenseFragment();
+ fragment0 = fragment;
+ break;
+ default:
+ fragment = InventoryRfidiMultiFragment.newInstance(true, TAG_EM_AURASENSE, "E280B12");
+ fragment1 = fragment;
+ break;
+ }
+ return fragment;
+ }
+
+ @Override
+ public int getCount() {
+ return NO_OF_TABS;
+ }
+
+ @Override
+ public int getItemPosition(Object object) {
+ return PagerAdapter.POSITION_NONE;
+ }
+
+ public AuraSenseAdapter(FragmentManager fm) {
+ super(fm);
+ }
+ }
+}
+
+
+
+package com.csl.cs710ademoapp.fragments;
+
+import androidx.lifecycle.Lifecycle;
+import android.os.Bundle;
+
+import com.csl.cslibrary4a.AdapterTab;
+import com.google.android.material.tabs.TabLayout;
+import androidx.viewpager.widget.ViewPager;
+import androidx.appcompat.app.ActionBar;
+import androidx.appcompat.app.AppCompatActivity;
+import android.view.LayoutInflater;
+import android.view.MenuItem;
+import android.view.View;
+import android.view.ViewGroup;
+
+import com.csl.cs710ademoapp.MainActivity;
+import com.csl.cs710ademoapp.R;
+
+public class AxzonFragment extends CommonFragment {
+ private ActionBar actionBar;
+ private ViewPager viewPager;
+ AdapterTab adapter;
+
+ private String[] tabs = { "Scan/Select", "Read" };
+ private String[] tabsXerxes0 = { "Logger" };
+ private String[] tabsXerxes = { "Logger", "Security" };
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ super.onCreateView(inflater, container, savedInstanceState, true);
+ return inflater.inflate(R.layout.custom_tabbed_layout, container, false);
+ }
+
+ @Override
+ public boolean onOptionsItemSelected(MenuItem item) {
+ InventoryRfidiMultiFragment fragment = (InventoryRfidiMultiFragment) adapter.fragment0;
+ if (item.getItemId() == R.id.menuAction_clear) {
+ fragment.clearTagsList();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_sortRssi) {
+ fragment.sortTagsListByRssi();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_sort) {
+ fragment.sortTagsList();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_save) {
+ fragment.saveTagsList();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_share) {
+ fragment.shareTagsList();
+ return true;
+ } else return super.onOptionsItemSelected(item);
+ }
+
+ @Override
+ public void onActivityCreated(Bundle savedInstanceState) {
+ super.onActivityCreated(savedInstanceState);
+
+ actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
+ actionBar.setIcon(R.drawable.dl_inv);
+ MainActivity.csLibrary4A.appendToLog("MainActivity.mDid = " + MainActivity.mDid);
+ if (false) actionBar.setTitle(R.string.title_activity_axzon);
+ else {
+ String stringTitle = getResources().getString(R.string.title_activity_axzon);
+ if (MainActivity.mDid.matches("E282402")) stringTitle = "S2";
+ else if (MainActivity.mDid.matches("E282403")) stringTitle = "S3";
+ if (MainActivity.mDid.matches("E282405")) stringTitle = "Xerxes";
+ actionBar.setTitle(stringTitle);
+ }
+
+ boolean bXervesTag = false;
+ if (MainActivity.mDid != null) if (MainActivity.mDid.matches("E282405")) bXervesTag = true;
+
+ TabLayout tabLayout = (TabLayout) getActivity().findViewById(R.id.OperationsTabLayout);
+
+ adapter = new AdapterTab(getActivity().getSupportFragmentManager(), (bXervesTag ? 4 : 2));
+ adapter.setFragment(0, InventoryRfidiMultiFragment.newInstance(true, null, ""));
+ adapter.setFragment(1, AccessMicronFragment.newInstance(true));
+ adapter.setFragment(2, new AccessXerxesLoggerFragment());
+ adapter.setFragment(3, new AccessUcodeFragment());
+
+ viewPager = (ViewPager) getActivity().findViewById(R.id.OperationsPager);
+ viewPager.setAdapter(adapter);
+ viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
+
+ for (String tab_name : tabs) {
+ tabLayout.addTab(tabLayout.newTab().setText(tab_name));
+ }
+ if (bXervesTag) {
+ if (MainActivity.csLibrary4A.get98XX() == 2 && MainActivity.csLibrary4A.getMacVer().indexOf("1.2") != 0) {
+ for (String tab_name : tabsXerxes0) {
+ tabLayout.addTab(tabLayout.newTab().setText(tab_name));
+ }
+ } else {
+ for (String tab_name : tabsXerxes) {
+ tabLayout.addTab(tabLayout.newTab().setText(tab_name));
+ }
+ }
+ }
+
+ tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
+ @Override
+ public void onTabSelected(TabLayout.Tab tab) {
+ viewPager.setCurrentItem(tab.getPosition());
+ }
+
+ @Override
+ public void onTabUnselected(TabLayout.Tab tab) {
+ }
+
+ @Override
+ public void onTabReselected(TabLayout.Tab tab) {
+ }
+ });
+
+ MainActivity.csLibrary4A.setBasicCurrentLinkProfile();
+ }
+
+ @Override
+ public void onPause() {
+ if (adapter.fragment0 != null) if (adapter.fragment0.getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.RESUMED)) adapter.fragment0.onPause();
+ if (adapter.fragment1 != null) if (adapter.fragment1.getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.RESUMED)) adapter.fragment1.onPause();
+ if (adapter.fragment2 != null) if (adapter.fragment2.getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.RESUMED)) adapter.fragment2.onPause();
+ if (adapter.fragment3 != null) if (adapter.fragment3.getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.RESUMED)) adapter.fragment3.onPause();
+ super.onPause();
+ }
+
+ @Override
+ public void onStop() {
+ if (adapter.fragment0 != null) if (adapter.fragment0.getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.RESUMED)) adapter.fragment0.onStop();
+ if (adapter.fragment1 != null) if (adapter.fragment1.getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.RESUMED)) adapter.fragment1.onStop();
+ if (adapter.fragment2 != null) if (adapter.fragment2.getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.RESUMED)) adapter.fragment2.onStop();
+ if (adapter.fragment3 != null) if (adapter.fragment3.getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.RESUMED)) adapter.fragment3.onStop();
+ super.onStop();
+ }
+
+ @Override
+ public void onDestroyView() {
+ if (adapter.fragment0 != null) if (adapter.fragment0.getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.RESUMED)) adapter.fragment0.onDestroyView();
+ if (adapter.fragment1 != null) if (adapter.fragment1.getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.RESUMED)) adapter.fragment1.onDestroyView();
+ if (adapter.fragment2 != null) if (adapter.fragment2.getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.RESUMED)) adapter.fragment2.onDestroyView();
+ if (adapter.fragment3 != null) if (adapter.fragment3.getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.RESUMED)) adapter.fragment3.onDestroyView();
+ super.onDestroyView();
+ }
+
+ @Override
+ public void onDestroy() {
+ if (adapter.fragment0 != null) if (adapter.fragment0.getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.RESUMED)) adapter.fragment0.onDestroy();
+ if (adapter.fragment1 != null) if (adapter.fragment1.getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.RESUMED)) adapter.fragment1.onDestroy();
+ if (adapter.fragment2 != null) if (adapter.fragment2.getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.RESUMED)) adapter.fragment2.onDestroy();
+ if (adapter.fragment3 != null) if (adapter.fragment3.getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.RESUMED)) adapter.fragment3.onDestroy();
+ if (MainActivity.selectFor != -1) {
+ MainActivity.csLibrary4A.setSelectCriteriaDisable(-1);
+ MainActivity.selectFor = -1;
+ }
+ MainActivity.csLibrary4A.restoreAfterTagSelect();
+ super.onDestroy();
+ }
+
+ @Override
+ public void onDetach() {
+ if (adapter.fragment0 != null) if (adapter.fragment0.getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.RESUMED)) adapter.fragment0.onDetach();
+ if (adapter.fragment1 != null) if (adapter.fragment1.getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.RESUMED)) adapter.fragment1.onDetach();
+ if (adapter.fragment2 != null) if (adapter.fragment2.getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.RESUMED)) adapter.fragment2.onDetach();
+ if (adapter.fragment3 != null) if (adapter.fragment3.getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.RESUMED)) adapter.fragment3.onDetach();
+ super.onDetach();
+ }
+
+ public AxzonFragment() { super("AxzonFragment"); }
+}
+
+
+
+package com.csl.cs710ademoapp.fragments;
+
+import static com.csl.cslibrary4a.RfidReader.TagType.TAG_AXZON;
+import static com.csl.cslibrary4a.RfidReader.TagType.TAG_MAGNUS_S2;
+import static com.csl.cslibrary4a.RfidReader.TagType.TAG_MAGNUS_S3;
+import static com.csl.cslibrary4a.RfidReader.TagType.TAG_AXZON_XERXES;
+
+import android.os.Bundle;
+import androidx.fragment.app.Fragment;
+import androidx.fragment.app.FragmentManager;
+import androidx.fragment.app.FragmentTransaction;
+import androidx.appcompat.app.ActionBar;
+import androidx.appcompat.app.AppCompatActivity;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.Button;
+
+import com.csl.cs710ademoapp.MainActivity;
+import com.csl.cs710ademoapp.R;
+
+public class AxzonSelectorFragment extends CommonFragment {
+ boolean bXerxesEnable = false;
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ super.onCreateView(inflater, container, savedInstanceState, true);
+ return inflater.inflate(R.layout.fragment_select_axzon, container, false);
+ }
+
+ @Override
+ public void onActivityCreated(Bundle savedInstanceState) {
+ super.onActivityCreated(savedInstanceState);
+
+ if (((AppCompatActivity) getActivity()).getSupportActionBar() != null) {
+ ActionBar actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
+ actionBar.setTitle(R.string.title_activity_axzonSelector);
+ }
+
+ Button button_s2 = (Button) getActivity().findViewById(R.id.select_axzon_s2);
+ button_s2.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ gotoAxzonFragment(2);
+ }
+ });
+ Button button_s3 = (Button) getActivity().findViewById(R.id.select_axzon_s3);
+ button_s3.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ gotoAxzonFragment(3);
+ }
+ });
+ Button button_xx = (Button) getActivity().findViewById(R.id.select_axzon_xx);
+ button_xx.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ gotoAxzonFragment(5);
+ }
+ });
+ Button button_all = (Button) getActivity().findViewById(R.id.select_axzon_all);
+ button_all.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ gotoAxzonFragment(0);
+ }
+ });
+ if (bXerxesEnable == false) {
+ button_xx.setVisibility(View.GONE);
+ button_all.setText("All Magnus");
+ }
+ }
+
+ public static AxzonSelectorFragment newInstance(boolean bXerxesEnable) {
+ AxzonSelectorFragment myFragment = new AxzonSelectorFragment();
+ myFragment.bXerxesEnable = bXerxesEnable;
+ return myFragment;
+ }
+ public AxzonSelectorFragment() {
+ super("AxzonSelectorFragment");
+ }
+
+ void gotoAxzonFragment(int tagType) {
+ switch(tagType) {
+ case 2:
+ MainActivity.tagType = TAG_MAGNUS_S2; MainActivity.mDid = "E282402";
+ break;
+ case 3:
+ MainActivity.tagType = TAG_MAGNUS_S3; MainActivity.mDid = "E282403";
+ break;
+ case 5:
+ MainActivity.tagType = TAG_AXZON_XERXES; MainActivity.mDid = "E282405";
+ break;
+ default:
+ MainActivity.tagType = TAG_AXZON; MainActivity.mDid = "E2824";
+ break;
+ }
+ MainActivity.csLibrary4A.appendToLog("HelloABC: gotoAxzonFragment with tagType = " + tagType + ", MainActivity.mDid = " + MainActivity.mDid);
+
+ MainActivity.csLibrary4A.appendToLog("HelloABC: config is " + (MainActivity.config == null ? "null" : "Valid"));
+ MainActivity.config.configPassword = "00000000";
+ MainActivity.config.configPower = Integer.toString(300);
+ MainActivity.config.config0 = Integer.toString(9);
+ MainActivity.config.config1 = Integer.toString(21);
+ MainActivity.config.config2 = Integer.toString(13);
+ if (tagType == 2) MainActivity.config.config3 = Integer.toString(13);
+ else MainActivity.config.config3 = Integer.toString(160);
+
+ if (true) {
+ Fragment fragment;
+ if (bXerxesEnable) fragment = new AxzonFragment();
+ else fragment = new MicronFragment();
+
+ FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
+ FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
+ fragmentTransaction.replace(R.id.content_frame, fragment);
+ fragmentTransaction.addToBackStack(null);
+ fragmentTransaction.commit();
+ } else {
+ Fragment fragment = AccessConfigFragment.newInstance(bXerxesEnable);
+ FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
+ FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
+ fragmentTransaction.replace(R.id.content_frame, fragment);
+ fragmentTransaction.addToBackStack(null);
+ fragmentTransaction.commit();
+ }
+ }
+}
+
+
+
+package com.csl.cs710ademoapp.fragments;
+
+import static com.csl.cslibrary4a.RfidReader.TagType.TAG_EM_COLDCHAIN;
+
+import android.os.Bundle;
+import android.view.LayoutInflater;
+import android.view.MenuItem;
+import android.view.View;
+import android.view.ViewGroup;
+
+import androidx.appcompat.app.ActionBar;
+import androidx.appcompat.app.AppCompatActivity;
+import androidx.viewpager.widget.ViewPager;
+
+import com.csl.cs710ademoapp.MainActivity;
+import com.csl.cs710ademoapp.R;
+import com.csl.cslibrary4a.AdapterTab;
+import com.google.android.material.tabs.TabLayout;
+
+public class ColdChainFragment extends CommonFragment {
+ private ActionBar actionBar;
+ private ViewPager viewPager;
+ AdapterTab adapter;
+
+ private String[] tabs = {"Select Tag", "Logging", "One-shot"};
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ super.onCreateView(inflater, container, savedInstanceState, true);
+ return inflater.inflate(R.layout.custom_tabbed_layout, container, false);
+ }
+
+ @Override
+ public boolean onOptionsItemSelected(MenuItem item) {
+ InventoryRfidiMultiFragment fragment1 = (InventoryRfidiMultiFragment) adapter.fragment0;
+ if (item.getItemId() == R.id.menuAction_clear) {
+ fragment1.clearTagsList();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_sortRssi) {
+ fragment1.sortTagsListByRssi();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_sort) {
+ fragment1.sortTagsList();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_save) {
+ fragment1.saveTagsList();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_share) {
+ fragment1.shareTagsList();
+ return true;
+ } else return super.onOptionsItemSelected(item);
+ }
+
+ @Override
+ public void onActivityCreated(Bundle savedInstanceState) {
+ super.onActivityCreated(savedInstanceState);
+
+ actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
+ actionBar.setIcon(R.drawable.dl_inv);
+ actionBar.setTitle(R.string.title_activity_coldChain);
+
+ TabLayout tabLayout = (TabLayout) getActivity().findViewById(R.id.OperationsTabLayout);
+
+ adapter = new AdapterTab(getActivity().getSupportFragmentManager(), tabs.length);
+ adapter.setFragment(0, InventoryRfidiMultiFragment.newInstance(true, TAG_EM_COLDCHAIN, "E280B0"));
+ adapter.setFragment(1, new AccessColdChainFragment());
+ adapter.setFragment(2, new AccessEm4325PassiveFragment());
+
+ viewPager = (ViewPager) getActivity().findViewById(R.id.OperationsPager);
+ viewPager.setAdapter(adapter);
+ viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
+
+ for (int i = 0; i < tabs.length; i++) {
+ if (MainActivity.csLibrary4A.get98XX() == 2 && i == tabs.length -1) break;;
+ String tab_name = tabs[i];
+ tabLayout.addTab(tabLayout.newTab().setText(tab_name));
+ }
+
+ tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
+ @Override
+ public void onTabSelected(TabLayout.Tab tab) {
+ viewPager.setCurrentItem(tab.getPosition());
+ }
+
+ @Override
+ public void onTabUnselected(TabLayout.Tab tab) {
+ }
+
+ @Override
+ public void onTabReselected(TabLayout.Tab tab) {
+ }
+ });
+ }
+
+ @Override
+ public void onPause() {
+ if (adapter.fragment0 != null) adapter.fragment0.onPause();
+ if (adapter.fragment1 != null) adapter.fragment1.onPause();
+ if (adapter.fragment2 != null) adapter.fragment2.onPause();
+ super.onPause();
+ }
+
+ @Override
+ public void onStop() {
+ if (adapter.fragment0 != null) adapter.fragment0.onStop();
+ if (adapter.fragment1 != null) adapter.fragment1.onStop();
+ if (adapter.fragment2 != null) adapter.fragment2.onStop();
+ super.onStop();
+ }
+
+ @Override
+ public void onDestroyView() {
+ if (adapter.fragment0 != null) adapter.fragment0.onDestroyView();
+ if (adapter.fragment1 != null) adapter.fragment1.onDestroyView();
+ if (adapter.fragment2 != null) adapter.fragment2.onDestroyView();
+ super.onDestroyView();
+ }
+
+ @Override
+ public void onDestroy() {
+ if (adapter.fragment0 != null) adapter.fragment0.onDestroy();
+ if (adapter.fragment1 != null) adapter.fragment1.onDestroy();
+ if (adapter.fragment2 != null) adapter.fragment2.onDestroy();
+ super.onDestroy();
+ }
+
+ @Override
+ public void onDetach() {
+ if (adapter.fragment0 != null) adapter.fragment0.onDetach();
+ if (adapter.fragment1 != null) adapter.fragment1.onDetach();
+ if (adapter.fragment2 != null) adapter.fragment2.onDetach();
+ super.onDetach();
+ }
+
+ public ColdChainFragment() {
+ super("ColdChainFragment");
+ }
+}
+
+
+
+package com.csl.cs710ademoapp.fragments;
+
+import android.app.Activity;
+import android.content.Context;
+import android.graphics.Color;
+import android.os.Bundle;
+import android.os.Handler;
+import android.text.SpannableString;
+import android.text.style.ForegroundColorSpan;
+import android.util.Log;
+import android.view.LayoutInflater;
+import android.view.Menu;
+import android.view.MenuInflater;
+import android.view.MenuItem;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.Toast;
+
+import androidx.appcompat.app.ActionBar;
+import androidx.appcompat.app.AppCompatActivity;
+import androidx.fragment.app.Fragment;
+
+import com.csl.cs710ademoapp.CustomAlertDialog;
+import com.csl.cs710ademoapp.CustomPopupWindow;
+import com.csl.cs710ademoapp.MainActivity;
+import com.csl.cs710ademoapp.R;
+
+public abstract class CommonFragment extends Fragment {
+ final boolean DEBUG = false; final String TAG = "Hello";
+ private String fragmentName;
+ MenuItem menuTriggerItem, menuBatteryVoltageItem;
+ Handler mHandler = new Handler();
+ boolean fragmentActive = false;
+
+ @Override
+ public void onAttach(Context context) {
+ if (DEBUG) {
+ if (fragmentName == null) Log.i(TAG, "CommonFragment.onAttach: NULL fragmentName");
+ else Log.i(TAG, "CommonFragment.onAttach: fragmentName = " + fragmentName);
+ if (MainActivity.csLibrary4A == null) Log.i(TAG, "CommonFragment.onAttach: NULL MainActivity.csLibrary4a");
+ if (fragmentName == null) MainActivity.csLibrary4A.appendToLog("NULL fragmentName");
+ MainActivity.csLibrary4A.appendToLog(fragmentName);
+ }
+ super.onAttach(context);
+ }
+
+ @Override
+ public void onCreate(Bundle savedInstanceState) {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog(fragmentName);
+ super.onCreate(savedInstanceState);
+ }
+
+ boolean menuFragment = false;
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState, boolean menuFragment) {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog(fragmentName);
+ this.menuFragment = menuFragment;
+
+ bleConnected = false; if (MainActivity.csLibrary4A.isBleConnected()) bleConnected = true;
+ rfidFailure = false; if (MainActivity.csLibrary4A.isRfidFailure()) rfidFailure = true;
+ ActionBar actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
+ boolean bHomeAsUpEnabled = true;
+ if (fragmentName.matches("HomeFragment")) bHomeAsUpEnabled = false;
+ if (fragmentName.matches("HomeWFragment")) bHomeAsUpEnabled = false;
+ actionBar.setDisplayHomeAsUpEnabled(bHomeAsUpEnabled);
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("CommonFragment: onCreateView with fragmentName = " + fragmentName + " , onOptionsItemSelected = " + menuFragment + ", DisplayHomeAsUpEnabled = " + bHomeAsUpEnabled);
+
+ if (menuFragment) setHasOptionsMenu(true);
+ return super.onCreateView(inflater, container, savedInstanceState);
+ }
+
+ int triggerCount_old;
+ private final Runnable updateTriggerRunnable = new Runnable() {
+ @Override
+ public void run() {
+ short reportCount = 5;
+ if (MainActivity.csLibrary4A.isBleConnected()) {
+ byte[] notificationData = MainActivity.csLibrary4A.onNotificationEvent();
+ if (false && notificationData != null) {
+ MainActivity.csLibrary4A.appendToLog("2 matched Error: " + MainActivity.csLibrary4A.byteArrayToString(notificationData));
+ CustomPopupWindow customPopupWindow = new CustomPopupWindow(MainActivity.mContext);
+ customPopupWindow.popupStart("Common Notification Error Code A101: " + MainActivity.csLibrary4A.byteArrayToString(notificationData), false);
+ }
+ reportCount = MainActivity.csLibrary4A.getTriggerReportingCount();
+ }
+
+ mHandler.postDelayed(updateTriggerRunnable, reportCount * 1100);
+ if (menuTriggerItem == null) return;
+ if (MainActivity.csLibrary4A.isBleConnected() == false) { menuTriggerItem.setTitle(""); return; }
+
+ int triggerCount = MainActivity.csLibrary4A.getTriggerCount();
+ if (triggerCount != triggerCount_old) {
+ triggerCount_old = triggerCount;
+ if (MainActivity.csLibrary4A.getTriggerButtonStatus()) menuTriggerItem.setTitle("Ton");
+ else menuTriggerItem.setTitle("Toff");
+ } else menuTriggerItem.setTitle("");
+ }
+ };
+
+ boolean bleDisConnecting = false;
+ boolean bleConnected = false, rfidFailure = false;
+ int batteryCount_old; boolean batteryUpdate = false; CustomPopupWindow batteryWarningPopupWindow; String strBatteryLow;
+ private final Runnable updateBatteryRunnable = new Runnable() {
+ @Override
+ public void run() {
+ mHandler.postDelayed(updateBatteryRunnable, 5000); //normal battery level updates every 4 seconds
+
+ if (menuBatteryVoltageItem == null) return;
+ if (MainActivity.csLibrary4A.isBleConnected() == false) {
+ if (bleDisConnecting) bleConnected = false; bleDisConnecting = true;
+ if (bleConnected) {
+ bleConnected = false; if (DEBUG) MainActivity.csLibrary4A.appendToLog("bleConnected is FALSE in " + fragmentName);
+ if (false) Toast.makeText(MainActivity.mContext, "Bluetooth is disconnected", Toast.LENGTH_SHORT).show();
+ else {
+ CustomAlertDialog appdialog = new CustomAlertDialog();
+ appdialog.Confirm((Activity) MainActivity.mContext, "Bluetooth is DISCONNECTED",
+ "Do you want to reconnect the Bluetooth ?",
+ "No thanks", "Reconnect",
+ new Runnable() {
+ @Override
+ public void run() {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("Confirm is pressed");
+ MainActivity.csLibrary4A.connect(null);
+ }
+ },
+ new Runnable() {
+ @Override
+ public void run() {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("Cancel is pressed.");
+ }
+ });
+ }
+ } else if (DEBUG) MainActivity.csLibrary4A.appendToLog("bleConnected is Kept as FALSE in " + fragmentName);
+ MainActivity.sharedObjects.batteryWarningShown = 0; menuBatteryVoltageItem.setTitle("");
+ return;
+ } else {
+ bleConnected = true;
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("bleConnected is TRUE in " + fragmentName);
+ }
+
+ if (MainActivity.csLibrary4A.isRfidFailure()) {
+ if (rfidFailure == false) {
+ rfidFailure = true;
+ if (false) {
+ CustomAlertDialog appdialog = new CustomAlertDialog();
+ appdialog.Confirm((Activity) MainActivity.mContext, "Rfid Transmission failure",
+ "Do you want to disconnect the Bluetooth ?",
+ "No thanks", "Disconnect",
+ new Runnable() {
+ @Override
+ public void run() {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("Confirm is pressed");
+ MainActivity.csLibrary4A.forceBTdisconnect();
+ }
+ },
+ new Runnable() {
+ @Override
+ public void run() {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("Cancel is pressed.");
+ }
+ });
+ }
+ }
+ } else {
+ rfidFailure = false;
+ }
+
+ int batteryCount = MainActivity.csLibrary4A.getBatteryCount();
+ String strText = MainActivity.csLibrary4A.getBatteryDisplay(false);
+ if (batteryCount_old != batteryCount) strBatteryLow = MainActivity.csLibrary4A.isBatteryLow();
+
+ if (strBatteryLow == null) MainActivity.sharedObjects.batteryWarningShown = 0;
+ else if (++MainActivity.sharedObjects.batteryWarningShown == 1) {
+ if (batteryWarningPopupWindow != null)
+ batteryWarningPopupWindow.popupWindow.dismiss();
+ batteryWarningPopupWindow = new CustomPopupWindow(MainActivity.mContext);
+ batteryWarningPopupWindow.popupStart(strBatteryLow + "% Battery Life Left, Please Recharge CSL Reader or Replace with Freshly Charged CSL Reader battery", false);
+ } else if (false && MainActivity.sharedObjects.batteryWarningShown > 10) MainActivity.sharedObjects.batteryWarningShown = 0;
+
+ if (batteryCount_old == batteryCount && strText.length() != 0) {
+ if (batteryUpdate) strText = "B" + strText;
+ else strText = "A" + strText;
+ batteryUpdate = !batteryUpdate;
+ menuBatteryVoltageItem.setTitle(strText);
+ MainActivity.csLibrary4A.batteryLevelRequest();
+ } else {
+ batteryCount_old = batteryCount;
+ SpannableString spanString = new SpannableString(strText);
+ spanString.setSpan(new ForegroundColorSpan(Color.RED), 0, spanString.length(), 0); //fix the color to white
+ if (false || strBatteryLow != null) menuBatteryVoltageItem.setTitle(spanString);
+ else menuBatteryVoltageItem.setTitle(strText);
+ }
+ }
+ };
+
+ @Override
+ public void onActivityCreated(Bundle savedInstanceState) {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog(fragmentName);
+ super.onActivityCreated(savedInstanceState);
+ }
+
+ @Override
+ public void onViewStateRestored(Bundle savedInstanceState) {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog(fragmentName);
+ super.onViewStateRestored(savedInstanceState);
+ }
+
+ @Override
+ public void onStart() {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog(fragmentName);
+ super.onStart();
+ }
+
+ @Override
+ public void onResume() {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog(fragmentName);
+ if (menuFragment) {
+ batteryCount_old = -1;
+ mHandler.post(updateTriggerRunnable);
+ mHandler.post(updateBatteryRunnable);
+ }
+ super.onResume();
+ fragmentActive = true;
+ }
+
+ @Override
+ public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog(fragmentName + " with fragmentActive = " + fragmentActive);
+ if (fragmentActive == false) return;
+ if (fragmentName.matches("ConnectionFragment")) {
+ inflater.inflate(R.menu.menu_connection, menu);
+ if (MainActivity.csLibrary4A.isBleScanning()) {
+ menu.findItem(R.id.action_refresh).setActionView(R.layout.actionbar_indeterminate_progress);
+ } else {
+ menu.findItem(R.id.action_refresh).setActionView(null);
+ }
+ } else {
+ inflater.inflate(R.menu.menu_home, menu);
+ menuBatteryVoltageItem = menu.findItem(R.id.home_voltage);;
+ menuTriggerItem = menu.findItem(R.id.home_trigger);
+ menu.removeItem(R.id.home_menu);
+ if (fragmentName.matches("InventoryFragment")
+ || fragmentName.contains("InventoryRfidiMultiFragment")
+ || fragmentName.contains("InventoryRfidSimpleFragment")
+
+ || fragmentName.contains("ImpinjFragment")
+ || fragmentName.contains("Ucode8Fragment")
+ || fragmentName.contains("UcodeFragment")
+ || fragmentName.contains("ColdChainFragment")
+ || fragmentName.contains("AuraSenseFragment")
+ || fragmentName.contains("AxzonFragment")
+ || fragmentName.contains("MicronFragment")
+ || fragmentName.contains("FdmicroFragment")
+ || fragmentName.contains("LedTagFragment")
+
+ || fragmentName.contains("InventoryRfidSimpleFragment")
+ ) {
+ menu.findItem(R.id.menuAction_clear).setTitle("Clear");
+ menu.findItem(R.id.menuAction_save).setTitle("Save");
+ menu.findItem(R.id.menuAction_share).setTitle("Share");
+ menu.findItem(R.id.menuAction_share).setIcon(android.R.drawable.ic_menu_share);
+ if (fragmentName.contains("InventoryBarcodeFragment")) {
+ menu.removeItem(R.id.menuAction_sort);
+ menu.removeItem(R.id.menuAction_sortRssi);
+ } else {
+ menu.findItem(R.id.menuAction_sort).setTitle("Sort by EPC");
+ menu.findItem(R.id.menuAction_sortRssi).setTitle("Sort by Rssi");
+ }
+ } else {
+ menu.removeItem(R.id.menuAction_clear);
+ menu.removeItem(R.id.menuAction_save);
+ menu.removeItem(R.id.menuAction_share);
+ menu.removeItem(R.id.menuAction_sort);
+ menu.removeItem(R.id.menuAction_sortRssi);
+ }
+ }
+ }
+
+ @Override
+ public boolean onOptionsItemSelected(MenuItem item) {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("CommonFragment: onOptionsItemSelected");
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog(fragmentName + " with fragmentActive = " + fragmentActive);
+ if (fragmentActive == false) return false;
+ switch (item.getItemId()) {
+ case android.R.id.home:
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("CommonFragment: onOptionsItemSelected: getActivity().onBackPressed");
+ getActivity().onBackPressed();
+ return true;
+ default:
+ return super.onOptionsItemSelected(item);
+ }
+ }
+
+ @Override
+ public void onPause() {
+ fragmentActive = false;
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog(fragmentName);
+ super.onPause();
+ }
+
+ @Override
+ public void onStop() {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog(fragmentName);
+ mHandler.removeCallbacks(updateTriggerRunnable);
+ mHandler.removeCallbacks(updateBatteryRunnable);
+ super.onStop();
+ }
+
+ @Override
+ public void onDestroyView() {
+ if (false) MainActivity.csLibrary4A.appendToLog(fragmentName);
+ super.onDestroyView();
+ }
+
+ @Override
+ public void onDestroy() {
+ if (DEBUG && MainActivity.csLibrary4A != null) MainActivity.csLibrary4A.appendToLog(fragmentName);
+ super.onDestroy();
+ }
+
+ @Override
+ public void onDetach() {
+ if (DEBUG && MainActivity.csLibrary4A != null) MainActivity.csLibrary4A.appendToLog(fragmentName);
+ super.onDetach();
+ }
+
+ CommonFragment(String text) {
+ fragmentName = text;
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog(",,," + fragmentName);
+ }
+}
+
+
+
+package com.csl.cs710ademoapp.fragments;
+
+import android.Manifest;
+import android.bluetooth.BluetoothAdapter;
+import android.bluetooth.BluetoothDevice;
+import android.bluetooth.le.ScanCallback;
+import android.content.pm.PackageManager;
+import android.os.AsyncTask;
+import android.os.Build;
+import android.os.Bundle;
+import android.os.Handler;
+
+import androidx.appcompat.app.ActionBar;
+import androidx.appcompat.app.AppCompatActivity;
+import androidx.core.app.ActivityCompat;
+
+import android.os.ParcelUuid;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.AdapterView;
+import android.widget.ListView;
+import android.widget.TextView;
+import android.widget.Toast;
+
+import com.csl.cs710ademoapp.CustomProgressDialog;
+import com.csl.cs710ademoapp.MainActivity;
+import com.csl.cs710ademoapp.R;
+import com.csl.cslibrary4a.BluetoothGatt;
+import com.csl.cslibrary4a.ReaderDevice;
+import com.csl.cs710ademoapp.adapters.ReaderListAdapter;
+
+import java.util.ArrayList;
+
+public class ConnectionFragment extends CommonFragment {
+ private DeviceScanTask deviceScanTask;
+ private ReaderListAdapter readerListAdapter;
+ private BluetoothAdapter.LeScanCallback mLeScanCallback;
+ private ScanCallback mScanCallback;
+ private ArrayList readersList = MainActivity.sharedObjects.readersList;
+
+ private ArrayList mScanResultList = new ArrayList<>();
+ private Handler mHandler = new Handler();
+ private DeviceConnectTask deviceConnectTask;
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ super.onCreateView(inflater, container, savedInstanceState, true);
+ return inflater.inflate(R.layout.fragment_connection, container, false);
+ }
+
+ @Override
+ public void onActivityCreated(Bundle savedInstanceState) {
+ super.onActivityCreated(savedInstanceState);
+
+ ActionBar actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
+ actionBar.setIcon(R.drawable.dl_rdl);
+ actionBar.setTitle(R.string.title_activity_connection);
+
+ TextView textview = (TextView) getActivity().findViewById(R.id.connection_warning);
+ MainActivity.csLibrary4A.appendToLog("getActivity().getPackageName() = " + getActivity().getPackageName());
+ if (getActivity().getPackageName().contains("com.csl.cs710ademoapp")) textview.setVisibility(View.VISIBLE);
+
+ if (MainActivity.csLibrary4A.isBleConnected() == false) readersList.clear();
+ final ListView readerListView = (ListView) getActivity().findViewById(R.id.readersList);
+ TextView readerEmptyView = (TextView) getActivity().findViewById(R.id.empty);
+ readerListView.setEmptyView(readerEmptyView);
+ readerListAdapter = new ReaderListAdapter(getActivity(), R.layout.readers_list_item, readersList, true, true);
+ readerListView.setAdapter(readerListAdapter);
+ readerListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
+ readerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
+ boolean DEBUG = false;
+ @Override
+ public void onItemClick(AdapterView> parent, View view, int position, long id) {
+ if (bConnecting) return;
+
+ ReaderDevice readerDevice = readerListAdapter.getItem(position);
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("ConnectionFragment.OnItemClickListener: bConnecting = " + bConnecting + ", postion = " + position);
+ boolean bSelectOld = readerDevice.getSelected();
+
+ if (MainActivity.csLibrary4A.isBleConnected() && readerDevice.isConnected() && (readerDevice.getSelected() || false)) {
+ MainActivity.csLibrary4A.appendToLog("ConnectionFragment.onItemClick, Fragment: ");
+ MainActivity.csLibrary4A.disconnect(false); bleDisConnecting = true;
+ readersList.clear();
+ } else if (MainActivity.csLibrary4A.isBleConnected() == false && readerDevice.getSelected() == false) {
+ boolean validStart = false;
+ if (deviceConnectTask == null) {
+ validStart = true;
+ } else if (deviceConnectTask.getStatus() == AsyncTask.Status.FINISHED) {
+ validStart = true;
+ }
+ if (validStart) {
+ bConnecting = true;
+ if (deviceScanTask != null) deviceScanTask.cancel(true);
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("ConnectionFragment.OnItemClickListener: Connecting");
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
+ deviceConnectTask = new DeviceConnectTask(position, readerDevice, "Connecting with " + readerDevice.getName());
+ deviceConnectTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
+ } else {
+ deviceConnectTask = new DeviceConnectTask(position, readerDevice, "Connecting with " + readerDevice.getName());
+ deviceConnectTask.execute();
+ }
+ }
+ }
+
+ if (readersList.size() > position) {
+ if (readerDevice.getSelected()) readerDevice.setSelected(false);
+ else readerDevice.setSelected(true);
+ readersList.set(position, readerDevice);
+ for (int i = 0; i < readersList.size(); i++) {
+ if (i != position) {
+ ReaderDevice readerDevice1 = readersList.get(i);
+ if (readerDevice1.getSelected()) {
+ readerDevice1.setSelected(false);
+ readersList.set(i, readerDevice1);
+ }
+ }
+ }
+ }
+ readerListAdapter.notifyDataSetChanged();
+ }
+ });
+ if (MainActivity.csLibrary4A.isBleConnected() == false) {
+ for (int i = 0; i < readersList.size(); i++) {
+ ReaderDevice readerDevice1 = readersList.get(i);
+ if (readerDevice1.isConnected()) {
+ readerDevice1.setConnected(false);
+ readersList.set(i, readerDevice1);
+ }
+ }
+ }
+ readerListAdapter.notifyDataSetChanged();
+ }
+
+ @Override
+ public void onResume() {
+ mHandler.post(checkRunnable);
+ super.onResume();
+ }
+
+ @Override
+ public void onStop() {
+ mHandler.removeCallbacks(checkRunnable);
+ if (deviceScanTask != null) {
+ deviceScanTask.cancel(true);
+ }
+ if (deviceConnectTask != null) {
+ deviceConnectTask.cancel(true);
+ }
+ super.onStop();
+ }
+
+ public ConnectionFragment() {
+ super("ConnectionFragment");
+ }
+
+ private final Runnable checkRunnable = new Runnable() {
+ @Override
+ public void run() {
+ boolean operating = false;
+ if (MainActivity.csLibrary4A.isBleConnected()) operating = true;
+ if (operating == false && deviceScanTask != null) {
+ if (deviceScanTask.isCancelled() == false) operating = true;
+ }
+ if (operating == false && deviceConnectTask != null) {
+ if (deviceConnectTask.isCancelled() == false) operating = true;
+ }
+ if (operating == false) {
+ deviceScanTask = new DeviceScanTask();
+ deviceScanTask.execute();
+ }
+ mHandler.postDelayed(checkRunnable, 5000);
+ }
+ };
+
+ private class DeviceScanTask extends AsyncTask {
+ private long timeMillisUpdate = System.currentTimeMillis();
+ ArrayList readersListOld = new ArrayList();
+ boolean wait4process = false; boolean scanning = false, DEBUG = false;
+
+ @Override
+ protected String doInBackground(Void... a) {
+ while (isCancelled() == false) {
+ if (wait4process == false) {
+ BluetoothGatt.CsScanData csScanData = MainActivity.csLibrary4A.getNewDeviceScanned();
+ if (csScanData != null) mScanResultList.add(csScanData);
+ if (scanning == false || mScanResultList.size() != 0 || System.currentTimeMillis() - timeMillisUpdate > 10000) {
+ wait4process = true; publishProgress("");
+ }
+ }
+ }
+ return "End of Asynctask()";
+ }
+
+ @Override
+ protected void onProgressUpdate(String... output) {
+ if (scanning == false) {
+ scanning = true;
+ if (MainActivity.csLibrary4A.scanLeDevice(true) == false) cancel(true);
+ else getActivity().invalidateOptionsMenu();
+ }
+ boolean listUpdated = false;
+ while (mScanResultList.size() != 0) {
+ BluetoothGatt.CsScanData scanResultA = mScanResultList.get(0);
+ mScanResultList.remove(0);
+ if (getActivity() == null) continue;
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
+ if (ActivityCompat.checkSelfPermission(getActivity().getApplicationContext(), Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) continue;
+ } else if (ActivityCompat.checkSelfPermission(getActivity().getApplicationContext(), Manifest.permission.BLUETOOTH) != PackageManager.PERMISSION_GRANTED) continue;
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("scanResultA.device.getType() = " + scanResultA.device.getType() + ". scanResultA.rssi = " + scanResultA.rssi);
+ if (/*scanResultA.device.getType() == BluetoothDevice.DEVICE_TYPE_LE &&*/(true || scanResultA.rssi < 0)) {
+ boolean match = false;
+ for (int i = 0; i < readersList.size(); i++) {
+ String stringReaderAddress = readersList.get(i).getAddress();
+ String stringDeviceAddress = (scanResultA.device == null ? scanResultA.getAddress() : scanResultA.device.getAddress());
+ if (stringReaderAddress.matches(stringDeviceAddress)) {
+ ReaderDevice readerDevice1 = readersList.get(i);
+ int count = readerDevice1.getCount();
+ count++;
+ readerDevice1.setCount(count);
+ readerDevice1.setRssi(scanResultA.rssi);
+ readerDevice1.setServiceUUID2p1(scanResultA.serviceUUID2p2);
+ readersList.set(i, readerDevice1); listUpdated = true;
+ match = true;
+ break;
+ }
+ }
+ if (match == false) {
+ String name = scanResultA.getName(); //(scanResultA.device == null ? scanResultA.getName() : scanResultA.device.getName());
+ if (false) {
+ if (scanResultA.device != null && scanResultA.rssi == 0) {
+ BluetoothDevice bluetoothDevice = scanResultA.device;
+ ParcelUuid[] parcelUuids = bluetoothDevice.getUuids();
+ for (int k = 0; parcelUuids != null && k < parcelUuids.length; k++) {
+ name += (", " + parcelUuids[k].toString());
+ }
+ }
+ }
+ String address = (scanResultA.device == null ? scanResultA.getAddress() : scanResultA.device.getAddress());
+ ReaderDevice readerDevice = new ReaderDevice(name, address, false, "", 1, scanResultA.rssi, scanResultA.serviceUUID2p2);
+ String strInfo = "";
+ if (scanResultA.device != null && scanResultA.device.getBondState() == 12) {
+ strInfo += "BOND_BONDED\n";
+ }
+ readerDevice.setDetails(strInfo + "scanRecord=" + MainActivity.csLibrary4A.byteArrayToString(scanResultA.scanRecord));
+ readersList.add(readerDevice); listUpdated = true;
+ }
+ } else {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("deviceScanTask: rssi=" + scanResultA.rssi + ", error type=" + scanResultA.device.getType());
+ }
+ }
+ if (System.currentTimeMillis() - timeMillisUpdate > 10000) {
+ timeMillisUpdate = System.currentTimeMillis();
+ for (int i = 0; i < readersList.size(); i++) {
+ ReaderDevice readerDeviceNew = readersList.get(i);
+ boolean matched = false;
+ for (int k = 0; k < readersListOld.size(); k++) {
+ ReaderDevice readerDeviceOld = readersListOld.get(k);
+ if (readerDeviceOld.getAddress().matches(readerDeviceNew.getAddress())) {
+ matched = true;
+ if (readerDeviceOld.getCount() >= readerDeviceNew.getCount()) {
+ readersList.remove(i); listUpdated = true;
+ readersListOld.remove(k);
+ } else readerDeviceOld.setCount(readerDeviceNew.getCount());
+ break;
+ }
+ }
+ if (matched == false) {
+ ReaderDevice readerDevice1 = new ReaderDevice(null, readerDeviceNew.getAddress(), false, null, readerDeviceNew.getCount(), 0);
+ readersListOld.add(readerDevice1);
+ }
+ }
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("Matched. Updated readerListOld with size = " + readersListOld.size());
+ MainActivity.csLibrary4A.scanLeDevice(false);
+ getActivity().invalidateOptionsMenu();
+ scanning = false;
+ }
+ if (listUpdated) readerListAdapter.notifyDataSetChanged();
+ wait4process = false;
+ }
+
+ @Override
+ protected void onCancelled() {
+ super.onCancelled();
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("Stop Scanning 1A");
+ deviceScanEnding();
+ }
+
+ @Override
+ protected void onPostExecute(String result) {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("Stop Scanning 1B");
+ deviceScanEnding();
+ }
+
+ void deviceScanEnding() {
+ MainActivity.csLibrary4A.scanLeDevice(false);
+ }
+ }
+
+ long connectTimeMillis; boolean bConnecting = false;
+ private class DeviceConnectTask extends AsyncTask {
+ boolean DEBUG = false;
+ private int position;
+ private final ReaderDevice connectingDevice;
+ private String prgressMsg;
+ int waitTime;
+ private CustomProgressDialog progressDialog;
+ private int setting;
+
+ DeviceConnectTask(int position, ReaderDevice connectingDevice, String prgressMsg) {
+ this.position = position;
+ this.connectingDevice = connectingDevice;
+ this.prgressMsg = prgressMsg;
+ }
+
+ @Override
+ protected void onPreExecute() {
+ super.onPreExecute();
+
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("start of Connection with mrfidToWriteSize = " + MainActivity.csLibrary4A.mrfidToWriteSize());
+ MainActivity.csLibrary4A.connect(connectingDevice);
+ waitTime = 30;
+ setting = -1;
+ progressDialog = new CustomProgressDialog(getActivity(), prgressMsg);
+ progressDialog.show();
+ }
+
+ @Override
+ protected Integer doInBackground(Void... a) {
+ do {
+ try {
+ Thread.sleep(500);
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ publishProgress("kkk ");
+ if (MainActivity.csLibrary4A.isBleConnected()) {
+ setting = 0; break;
+ }
+ } while (--waitTime > 0);
+ if (progressDialog.isShowing())
+ progressDialog.dismiss();
+ if (setting != 0 || waitTime <= 0) {
+ cancel(true);
+ }
+ publishProgress("mmm ");
+ return waitTime;
+ }
+
+ @Override
+ protected void onProgressUpdate(String... output) {
+ }
+
+ @Override
+ protected void onCancelled(Integer result) {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("ConnectionFragment.deviceConnectTask: onCancelled(): setting = " + setting + ", waitTime = " + waitTime);
+ if (setting >= 0) {
+ Toast.makeText(getActivity().getApplicationContext(), getResources().getString(R.string.toast_ble_setup_problem), Toast.LENGTH_SHORT).show();
+ } else {
+ MainActivity.csLibrary4A.isBleConnected();
+ Toast.makeText(getActivity().getApplicationContext(), getResources().getString(R.string.error_bluetooth_connection_failed), Toast.LENGTH_SHORT).show();
+ }
+ super.onCancelled();
+ MainActivity.csLibrary4A.disconnect(false); bleDisConnecting = true;
+
+ bConnecting = false;
+ }
+
+ protected void onPostExecute(Integer result) {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("ConnectionFragment.deviceConnectTask: onPostExecute(): setting = " + setting + ", waitTime = " + waitTime);
+ ReaderDevice readerDevice = readersList.get(position);
+ readerDevice.setConnected(true);
+ readersList.set(position, readerDevice);
+ readerListAdapter.notifyDataSetChanged();
+
+ String connectedBleAddress = connectingDevice.getAddress();
+ if (connectedBleAddress.matches(MainActivity.sharedObjects.connectedBleAddressOld) == false) MainActivity.sharedObjects.versionWarningShown = false;
+ MainActivity.sharedObjects.connectedBleAddressOld = connectedBleAddress;
+ MainActivity.sharedObjects.barsList.clear();
+ MainActivity.sharedObjects.tagsList.clear();
+ MainActivity.sharedObjects.tagsIndexList.clear();
+
+ Toast.makeText(getActivity().getApplicationContext(), getResources().getString(R.string.toast_ble_connected), Toast.LENGTH_SHORT).show();
+
+ connectTimeMillis = System.currentTimeMillis();
+ super.onPostExecute(result);
+
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("ConnectionFragment: onPostExecute: getActivity().onBackPressed");
+ getActivity().onBackPressed();
+ bConnecting = false;
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("end of Connection with mrfidToWriteSize = " + MainActivity.csLibrary4A.mrfidToWriteSize());
+ }
+ }
+}
+
+
+
+package com.csl.cs710ademoapp.fragments;
+
+import static android.Manifest.permission.ACCESS_COARSE_LOCATION;
+import static android.Manifest.permission.ACCESS_FINE_LOCATION;
+import static android.Manifest.permission.BLUETOOTH;
+import static android.Manifest.permission.BLUETOOTH_CONNECT;
+import static android.Manifest.permission.BLUETOOTH_SCAN;
+import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
+import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
+import static android.content.Context.LOCATION_SERVICE;
+
+import static com.csl.cs710ademoapp.MainActivity.mContext;
+
+import android.content.Intent;
+import android.content.pm.PackageManager;
+import android.graphics.drawable.ColorDrawable;
+import android.location.LocationManager;
+import android.os.Build;
+import android.os.Bundle;
+import android.os.Handler;
+import android.os.IBinder;
+import android.provider.Settings;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.view.inputmethod.InputMethodInfo;
+import android.view.inputmethod.InputMethodManager;
+import android.view.inputmethod.InputMethodSubtype;
+import android.widget.AdapterView;
+import android.widget.Button;
+import android.widget.ListView;
+import android.widget.TableRow;
+import android.widget.TextView;
+import android.widget.Toast;
+
+import androidx.appcompat.app.ActionBar;
+import androidx.appcompat.app.AppCompatActivity;
+import androidx.core.app.ActivityCompat;
+
+import com.csl.cs710ademoapp.CustomPopupWindow;
+import com.csl.cs710ademoapp.DrawerListContent;
+import com.csl.cs710ademoapp.adapters.ReaderListAdapter;
+import com.csl.cs710ademoapp.MainActivity;
+import com.csl.cs710ademoapp.R;
+import com.csl.cs710ademoapp.CustomAlertDialog;
+import com.csl.cslibrary4a.BluetoothGatt;
+import com.csl.cslibrary4a.ReaderDevice;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public class DirectWedgeFragment extends CommonFragment {
+ Button buttonConnect;
+ private ArrayList readersList = MainActivity.sharedObjects.readersList;
+ Handler handler = new Handler();
+ private ReaderListAdapter readerListAdapter;
+ boolean bWedgeConnecting = false, bWedgeConnected = false;
+ boolean bCurrentIMEmatched = false;
+ String stringImeExpected, stringLabelExpected;
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ super.onCreateView(inflater, container, savedInstanceState, true);
+ return inflater.inflate(R.layout.fragment_directwedge, container, false);
+ }
+
+ @Override
+ public void onActivityCreated(Bundle savedInstanceState) {
+ super.onActivityCreated(savedInstanceState);
+
+ TableRow tableRow1 = getActivity().findViewById(R.id.directWedgeRow1);
+ TableRow tableRow2 = getActivity().findViewById(R.id.directWedgeRow2);
+ TableRow tableRow3 = getActivity().findViewById(R.id.directWedgeRow3);
+ TableRow tableRow4 = getActivity().findViewById(R.id.directWedgeRow4);
+ TableRow tableRow5 = getActivity().findViewById(R.id.directWedgeRow5);
+ TableRow tableRowStart = getActivity().findViewById(R.id.directWedgeRowStart);
+ MainActivity.csLibrary4A.appendToLog("getPackageName = " + getActivity().getPackageName());
+ if (getActivity().getPackageName().contains("cs710awedgeapp")) {
+ androidx.appcompat.app.ActionBar actionBar;
+ actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
+ actionBar.setIcon(R.drawable.dl_access);
+ ColorDrawable colorDrawable = new ColorDrawable(getResources().getColor(R.color.colorPrimary));
+ actionBar.setBackgroundDrawable(colorDrawable);
+ actionBar.setTitle(R.string.app_ime_simplewedge1);
+ actionBar.setDisplayHomeAsUpEnabled(false);
+ //String strTitle = actionBar.getTitle().toString() + " v" + BuildConfig.VERSION_NAME;
+ //actionBar.setTitle(strTitle);
+ } else { //if (getActivity().getPackageName().contains("cs710ademoapp")) {
+ ActionBar actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
+ actionBar.setIcon(R.drawable.dl_inv);
+ actionBar.setTitle("Wedge");
+
+ tableRow1.setVisibility(View.GONE);
+ tableRow2.setVisibility(View.GONE);
+ tableRow3.setVisibility(View.GONE);
+ tableRow4.setVisibility(View.GONE);
+ tableRow5.setVisibility(View.GONE);
+ tableRowStart.setVisibility(View.VISIBLE);
+ }
+
+ if (false) {
+ ReaderDevice readerDevice1 = new ReaderDevice(null, "123456", false, null, 0, 0);
+ ReaderDevice readerDevice2 = new ReaderDevice(null, "1234567890", false, null, 0, 0);
+ readersList.add(readerDevice1);
+ readersList.add(readerDevice2);
+ }
+
+ ListView readerListView = (ListView) getActivity().findViewById(R.id.directWedgeListView);
+ TextView readerEmptyView = (TextView) getActivity().findViewById(R.id.directWedgeTextViewEmpty);
+ readerListView.setEmptyView(readerEmptyView);
+ readerListAdapter = new ReaderListAdapter(getActivity(), R.layout.readers_list_item, readersList, true, true);
+ readerListView.setAdapter(readerListAdapter);
+ readerListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
+ readerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
+ boolean DEBUG = true;
+ @Override
+ public void onItemClick(AdapterView> parent, View view, int position, long id) {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("OnItemClickListener: bConnecting = " + bWedgeConnecting + ", position = " + position);
+ if (bWedgeConnecting) return;
+
+ ReaderDevice readerDevice = readerListAdapter.getItem(position);
+ if (readersList.size() > position) {
+ if (readerDevice.getSelected()) readerDevice.setSelected(false);
+ else readerDevice.setSelected(true);
+ readersList.set(position, readerDevice);
+ for (int i = 0; i < readersList.size(); i++) {
+ if (i != position) {
+ ReaderDevice readerDevice1 = readersList.get(i);
+ if (readerDevice1.getSelected()) {
+ readerDevice1.setSelected(false);
+ readersList.set(i, readerDevice1);
+ }
+ }
+ }
+ }
+ readerListAdapter.notifyDataSetChanged();
+
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("OnItemClickListener: readerDevice.getSelected = " + readerDevice.getSelected());
+ if (MainActivity.csLibrary4A.isBleConnected() && readerDevice.getSelected() == false && readerDevice.isConnected()) {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("OnItemClickListener: going to disconnect");
+ disconnectWedge();
+ } else if (MainActivity.csLibrary4A.isBleConnected() == false && readerDevice.getSelected()) {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("OnItemClickListener: going to CONNECT");
+ if (true) connectWedge(readerDevice);
+ }
+ }
+ });
+
+ Button buttonSetup = (Button) getActivity().findViewById(R.id.directWedgeButtonSetup);
+ buttonSetup.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (MainActivity.csLibrary4A.isBleConnected() || true) new SettingWedgeFragment().show(getChildFragmentManager(), "TAG");
+ else if (MainActivity.csLibrary4A.mrfidToWriteSize() != 0) Toast.makeText(getActivity().getApplicationContext(), getResources().getString(R.string.toast_not_ready), Toast.LENGTH_SHORT).show();
+ else Toast.makeText(getActivity().getApplicationContext(), getResources().getString(R.string.toast_ble_not_connected), Toast.LENGTH_SHORT).show();
+ }
+ });
+
+ buttonConnect = (Button) getActivity().findViewById(R.id.directWedgeButtonConnect);
+ buttonConnect.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (bWedgeConnecting) return;
+ if (MainActivity.csLibrary4A.isBleConnected()) {
+ disconnectWedge();
+ readerListAdapter.notifyDataSetChanged();
+ } else {
+ boolean bFound = false;
+ for (int i = 0; i < readersList.size(); i++) {
+ ReaderDevice readerDevice = readersList.get(i);
+ if (readerDevice.getSelected() && readerDevice.isConnected() == false) {
+ connectWedge(readerDevice);
+ bFound = true;
+ break;
+ }
+ }
+ if (bFound == false) Toast.makeText(getActivity().getApplicationContext(), getResources().getString(R.string.toast_select_reader_first), Toast.LENGTH_SHORT).show();
+ }
+ }
+ });
+
+ Button buttonStart = (Button) getActivity().findViewById(R.id.directWedgeButtonStart);
+ if (!getActivity().getPackageName().matches("com.csl.cs710awedgeapp")) buttonStart.setVisibility(View.VISIBLE);
+ buttonStart.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (MainActivity.csLibrary4A.isBleConnected()) {
+ if (MainActivity.csLibrary4A.mrfidToWriteSize() == 0) {
+ MainActivity.wedged = true;
+ Intent i = new Intent(Intent.ACTION_MAIN);
+ i.addCategory(Intent.CATEGORY_HOME);
+ startActivity(i);
+ }
+ } else Toast.makeText(getActivity().getApplicationContext(), getResources().getString(R.string.toast_ble_not_connected), Toast.LENGTH_SHORT).show();
+ }
+ });
+
+ Button buttonInfo = (Button) getActivity().findViewById(R.id.directWedgeButtonInfo);
+ buttonInfo.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ CustomPopupWindow customPopupWindow = new CustomPopupWindow(mContext);
+ String stringInfo =
+ "1. For the first time launching the application, please grant device permission for location, connectivity and enabling . \n\n" +
+ "2. Readers will be discovered by the app and please check the box on the right hand side to select the reader to be connected. \n\n" +
+ "3. Once connected, put the application in background.\n\n" +
+ "4. Open the target application where you would like data to be printed.\n\n" +
+ "5. On the target applicatoin , put the cursor to the text field where data will be printed. Switch your keyboard to .\n\n" +
+ "6. Press and hold the trigger key of the reader to start reading tags. EPC values will be printed to the cursor on your target application.\n\n" +
+ "7. Switch back to the CSL Data Wedge application. Now you can press the \"Disconnect\" button to disconnect from the reader.\n\n" +
+ "8. Configuration button: Press the button to modify parameters such as power, prefix, suffix and delimiter.\n\n";
+ MainActivity.csLibrary4A.appendToLog(stringInfo);
+ customPopupWindow.popupStart(stringInfo, false);
+ }
+ });
+
+ handler.post(runnableStartService);
+ handler.postDelayed(runnableStart, 1000);
+ }
+
+ @Override
+ public void onResume() {
+ super.onResume();
+ readerListAdapter.notifyDataSetChanged();
+ updateCurrentIMEMatched();
+ }
+
+ @Override
+ public void onDestroy() {
+ MainActivity.csLibrary4A.setSameCheck(true);
+ MainActivity.csLibrary4A.restoreAfterTagSelect();
+ super.onDestroy();
+ }
+
+ public DirectWedgeFragment() {
+ super("DirectWedgeFragment");
+ }
+
+ public static boolean bUserRequestedDisconnect = false;
+ void disconnectWedge() {
+ MainActivity.csLibrary4A.appendToLog("foregroundReader108: updated 2A");
+ MainActivity.csLibrary4A.setForegroundServiceEnable(false);
+ MainActivity.csLibrary4A.appendToLog("getForegroundReader = " + MainActivity.csLibrary4A.getForegroundReader());
+
+ MainActivity.csLibrary4A.disconnect(false); bleDisConnecting = true; bWedgeConnecting = false; bUserRequestedDisconnect = true;
+ readersList.clear();
+ buttonConnect.setText("Connect");
+ handler.removeCallbacks(runnableStart); handler.postDelayed(runnableStart, 2000);
+
+ MainActivity.csLibrary4A.setWedgeDeviceName(null); MainActivity.csLibrary4A.setWedgeDeviceAddress(null);
+ }
+ void connectWedge(ReaderDevice readerDevice) {
+ MainActivity.csLibrary4A.scanLeDevice(false);
+ MainActivity.csLibrary4A.connect(readerDevice); bWedgeConnecting = true; bWedgeConnected = false; bUserRequestedDisconnect = false;
+ buttonConnect.setText("Connecting");
+ MainActivity.csLibrary4A.setWedgeDeviceName(readerDevice.getName()); MainActivity.csLibrary4A.setWedgeDeviceAddress(readerDevice.getAddress());
+ MainActivity.csLibrary4A.setWedgeDeviceUUID2p1(readerDevice.getServiceUUID2p1());
+ }
+
+ Runnable runnableStartService = new Runnable() {
+ boolean DEBUG = false;
+
+ @Override
+ public void run() {
+ MainActivity.csLibrary4A.appendToLog("runnableStartService: ActivityCompat.checkSelfPermission(activity, WRITE_EXTERNAL_STORAGE) = " + ActivityCompat.checkSelfPermission(mContext, WRITE_EXTERNAL_STORAGE));
+ MainActivity.csLibrary4A.appendToLog("runnableStartService: ActivityCompat.checkSelfPermission(activity, READ_EXTERNAL_STORAGE) = " + ActivityCompat.checkSelfPermission(mContext, READ_EXTERNAL_STORAGE));
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
+ if (mContext.checkSelfPermission(WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
+ MainActivity.csLibrary4A.appendToLog("runnableStartService: requestPermissions WRITE_EXTERNAL_STORAGE"); //
+ requestPermissions(new String[] { WRITE_EXTERNAL_STORAGE, READ_EXTERNAL_STORAGE }, 1);
+ //Toast.makeText(mContext, com.csl.cslibrary4a.R.string.toast_permission_not_granted, Toast.LENGTH_SHORT).show();
+ } else MainActivity.csLibrary4A.appendToLog("runnableStartService: WRITE_EXTERNAL_STORAGE is permitted"); ///
+ } else MainActivity.csLibrary4A.appendToLog("runnableStartService: no need to handle WRITE_EXTERNAL_STORAGE");
+
+ LocationManager locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
+ MainActivity.csLibrary4A.appendToLog("runnableStartService: locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) = " + locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER));
+ MainActivity.csLibrary4A.appendToLog("runnableStartService: locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER) = " + locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER));
+ MainActivity.csLibrary4A.appendToLog("runnableStartService: ActivityCompat.checkSelfPermission(activity, ACCESS_FINE_LOCATION) = " + ActivityCompat.checkSelfPermission(mContext, ACCESS_FINE_LOCATION));
+ MainActivity.csLibrary4A.appendToLog("runnableStartService: ActivityCompat.checkSelfPermission(activity, ACCESS_COARSE_LOCATION) = " + ActivityCompat.checkSelfPermission(mContext, ACCESS_COARSE_LOCATION));
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
+ if ((ActivityCompat.checkSelfPermission(mContext, ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
+ || ActivityCompat.checkSelfPermission(mContext, ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)) {
+ CustomAlertDialog appdialog = new CustomAlertDialog();
+ appdialog.Confirm(getActivity(), "Use your location",
+ "This app collects location data in the background. In terms of the features using this location data in the background, this App collects location data when it is reading RFID tag in all inventory pages. The purpose of this is to correlate the RFID tag with the actual GNSS(GPS) location of the tag. In other words, this is to track the physical location of the logistics item tagged with the RFID tag.",
+ "No thanks", "Turn on",
+ new Runnable() {
+ @Override
+ public void run() {
+ MainActivity.csLibrary4A.appendToLog("runnableStartService: allow permission in ACCESS_FINE_LOCATION handler");
+ MainActivity.csLibrary4A.appendToLog("runnableStartService: requestPermissions ACCESS_FINE_LOCATION");
+ requestPermissions(new String[] { ACCESS_FINE_LOCATION }, 123); //ACCESS_FINE_LOCATION, ACCESS_COARSE_LOCATION
+ //if (false) Toast.makeText(mContext, com.csl.cslibrary4a.R.string.toast_permission_not_granted, Toast.LENGTH_SHORT).show();
+ /*{
+ LocationManager locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
+ if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) == false && locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER) == false) {
+ MainActivity.csLibrary4A.appendToLog("popupAlert: StreamOut: start activity ACTION_LOCATION_SOURCE_SETTINGS");
+ Intent intent1 = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
+ mContext.startActivity(intent1);
+ }
+ }*/
+ //bleEnableRequestShown0 = true; mHandler.postDelayed(mRquestAllowRunnable, 60000);
+ //bAlerting = false;
+ }
+ },
+ new Runnable() {
+ @Override
+ public void run() {
+ MainActivity.csLibrary4A.appendToLog("runnableStartService: reject permission in ACCESS_FINE_LOCATION handler");
+ //bAlerting = false;
+ //bleEnableRequestShown0 = true; mHandler.postDelayed(mRquestAllowRunnable, 60000);
+ }
+ });
+ MainActivity.csLibrary4A.appendToLog("runnableStartService: started ACCESS_FINE_LOCATION handler");
+ } else MainActivity.csLibrary4A.appendToLog("runnableStartService: handled ACCESS_FINE_LOCATION");
+ } else MainActivity.csLibrary4A.appendToLog("runnableStartService: no need to handle ACCESS_FINE_LOCATION");
+
+ MainActivity.csLibrary4A.appendToLog("runnableStartService: ActivityCompat.checkSelfPermission(activity, BLUETOOTH_CONNECT) = " + ActivityCompat.checkSelfPermission(mContext, BLUETOOTH_CONNECT));
+ MainActivity.csLibrary4A.appendToLog("runnableStartService: ActivityCompat.checkSelfPermission(activity, BLUETOOTH_SCAN) = " + ActivityCompat.checkSelfPermission(mContext, BLUETOOTH_SCAN));
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
+ if (ActivityCompat.checkSelfPermission(mContext, BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED || ActivityCompat.checkSelfPermission(mContext, BLUETOOTH_SCAN) != PackageManager.PERMISSION_GRANTED) {
+ MainActivity.csLibrary4A.appendToLog("runnableStartService: requestPermissions BLUETOOTH_SCAN and BLUETOOTH_CONNECT");
+ requestPermissions(new String[] { BLUETOOTH_SCAN, BLUETOOTH_CONNECT }, 123);
+ } else MainActivity.csLibrary4A.appendToLog("runnableStartService: handled BLUETOOTH_CONNECT and BLUETOOTH_SCAN");
+ } else MainActivity.csLibrary4A.appendToLog("runnableStartService: no need to handle BLUETOOTH_SCAN and BLUETOOTH_CONNECT");
+ }
+ };
+
+ int runningMode = -1, connectWait = 0, scanWait = 0;
+ Runnable runnableStart = new Runnable() {
+ @Override
+ public void run() {
+ boolean bValue = true;
+ if (MainActivity.csLibrary4A.isBleConnected()) {
+ if (MainActivity.csLibrary4A.mrfidToWriteSize() == 0) {
+ bWedgeConnecting = false;
+ if (bWedgeConnected == false) {
+ bWedgeConnected = true;
+ MainActivity.csLibrary4A.setPowerLevel(MainActivity.csLibrary4A.getWedgePower());
+ MainActivity.csLibrary4A.appendToLog("runnableStart: isBleConnected is true with mrfidToWriteSize = " + MainActivity.csLibrary4A.mrfidToWriteSize());
+ for (int i = 0; i < readersList.size(); i++) {
+ ReaderDevice readerDevice = readersList.get(i);
+ if (readerDevice.getSelected() && readerDevice.isConnected() == false) {
+ readerDevice.setConnected(true);
+ readersList.set(i, readerDevice);
+ readerListAdapter.notifyDataSetChanged();
+ }
+ }
+ if (getActivity().getPackageName().contains("cs710awedgeapp")) {
+ MainActivity.csLibrary4A.appendToLog("foregroundReader108: updated 2b");
+ MainActivity.csLibrary4A.setForegroundServiceEnable(true);
+ MainActivity.csLibrary4A.saveSetting2File();
+ }
+ }
+ buttonConnect.setText("Disconnect");
+ } //else Toast.makeText(getActivity().getApplicationContext(), getResources().getString(R.string.toast_not_ready), Toast.LENGTH_SHORT).show();
+ } else if (bWedgeConnecting) {
+ MainActivity.csLibrary4A.appendToLog("runnableStart: bConnecting is true");
+ } else if (MainActivity.csLibrary4A.isBleScanning()) {
+ MainActivity.csLibrary4A.appendToLog("runnableStart: isBleScanning is true");
+ boolean listUpdated = false;
+ if (++scanWait > 10) {
+ boolean bValue1 = MainActivity.csLibrary4A.scanLeDevice(false);
+ MainActivity.csLibrary4A.appendToLog("runnableStart: STOP scanning with result = " + bValue1);
+ scanWait = 0;
+ readersList.clear();
+ listUpdated = true;
+ } else {
+ while (true) {
+ BluetoothGatt.CsScanData csScanData = MainActivity.csLibrary4A.getNewDeviceScanned();
+ if (csScanData != null) {
+ BluetoothGatt.CsScanData scanResultA = csScanData;
+ if (getActivity() == null) continue;
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
+ if (ActivityCompat.checkSelfPermission(getActivity().getApplicationContext(), BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
+ continue;
+ }
+ } else if (ActivityCompat.checkSelfPermission(getActivity().getApplicationContext(), BLUETOOTH) != PackageManager.PERMISSION_GRANTED) {
+ continue;
+ }
+ if (DEBUG)
+ MainActivity.csLibrary4A.appendToLog("runnableStart: scanResultA.device.getType() = " + scanResultA.device.getType() + ". scanResultA.rssi = " + scanResultA.rssi);
+ if (/*scanResultA.device.getType() == BluetoothDevice.DEVICE_TYPE_LE &&*/ (true || scanResultA.rssi < 0)) {
+ boolean match = false;
+ for (int i = 0; i < readersList.size(); i++) {
+ if (readersList.get(i).getAddress().matches(scanResultA.device.getAddress())) {
+ ReaderDevice readerDevice1 = readersList.get(i);
+ int count = readerDevice1.getCount();
+ count++;
+ readerDevice1.setCount(count);
+ readerDevice1.setRssi(scanResultA.rssi);
+ readersList.set(i, readerDevice1);
+ listUpdated = true;
+ match = true;
+ break;
+ }
+ }
+ if (match == false) {
+ ReaderDevice readerDevice = new ReaderDevice(scanResultA.device.getName(), scanResultA.device.getAddress(), false, "", 1, scanResultA.rssi, scanResultA.serviceUUID2p2);
+ String strInfo = "";
+ if (scanResultA.device.getBondState() == 12) {
+ strInfo += "BOND_BONDED\n";
+ }
+ //readerDevice.setDetails(strInfo + "scanRecord=" + mCsLibrary4A.byteArrayToString(scanResultA.scanRecord));
+ readersList.add(readerDevice);
+ listUpdated = true;
+ }
+ } else {
+ if (DEBUG)
+ MainActivity.csLibrary4A.appendToLog("runnableStart: deviceScanTask: rssi=" + scanResultA.rssi + ", error type=" + scanResultA.device.getType());
+ }
+ //scanWait = 0;
+ } else {
+ MainActivity.csLibrary4A.appendToLog("runnableStart: NO reader is found with scanWait = " + scanWait);
+ break;
+ }
+ }
+ if (listUpdated) readerListAdapter.notifyDataSetChanged();
+ }
+ } else {
+ MainActivity.csLibrary4A.appendToLog("bbb 4");
+ if (bWedgeConnected) {
+ bWedgeConnected = false;
+ MainActivity.csLibrary4A.appendToLog("bbb 4A");
+ readersList.clear(); readerListAdapter.notifyDataSetChanged();
+ buttonConnect.setText("Connect");
+ }
+ MainActivity.csLibrary4A.appendToLog("runnableStart: isBleScanning is FALSE");
+ boolean bScanPermitted = true;
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { //that is android 12 or above
+ if (ActivityCompat.checkSelfPermission(mContext, BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED
+ || ActivityCompat.checkSelfPermission(mContext, BLUETOOTH_SCAN) != PackageManager.PERMISSION_GRANTED) {
+ bScanPermitted = false;
+ //MainActivity.csLibrary4A.appendToLog("runnableStartService: requestPermissions BLUETOOTH_SCAN and BLUETOOTH_CONNECT");
+ //requestPermissions(new String[] { BLUETOOTH_SCAN, BLUETOOTH_CONNECT }, 123);
+ MainActivity.csLibrary4A.appendToLog("runnableStart: CANNOT start scanLeDevice as BLUETOOTH_CONNECT && BLUETOOTH_SCAN is NOT yet permitted");
+ } else {
+ MainActivity.csLibrary4A.appendToLog("runnableStartService: BLUETOOTH_CONNECT and BLUETOOTH_SCAN and (ACCESS_FINE_LOCATION or ACCESS_COARSE_LOCATION) is permitted");
+ }
+ } else {
+ MainActivity.csLibrary4A.appendToLog("runnableStartService: no need to handle BLUETOOTH_SCAN and BLUETOOTH_CONNECT");
+ if (ActivityCompat.checkSelfPermission(mContext, BLUETOOTH) != PackageManager.PERMISSION_GRANTED) {
+ bScanPermitted = false;
+ MainActivity.csLibrary4A.appendToLog("runnableStart: CANNOT start scanLeDevice as BLUETOOTH is NOT yet permitted");
+ } else {
+ MainActivity.csLibrary4A.appendToLog("runnableStartService: BLUETOOTH_CONNECT and BLUETOOTH_SCAN and (ACCESS_FINE_LOCATION or ACCESS_COARSE_LOCATION) is permitted");
+ }
+ }
+ if ((ActivityCompat.checkSelfPermission(mContext, ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
+ || ActivityCompat.checkSelfPermission(mContext, ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)) {
+ bScanPermitted = false;
+ MainActivity.csLibrary4A.appendToLog("runnableStart: CANNOT start scanLeDevice as ACCESS_FINE_LOCATION or ACCESS_COARSE_LOCATION is NOT yet permitted");
+ }
+ bWedgeConnecting = false; connectWait = 0; scanWait = 0;
+ boolean bValue1 = false;
+ if (bScanPermitted) bValue1 = MainActivity.csLibrary4A.scanLeDevice(true);
+ MainActivity.csLibrary4A.appendToLog("runnableStart: starting scanLeDevice is " + bValue1 + " with isScanning = " + MainActivity.csLibrary4A.isBleScanning());
+ }
+ handler.postDelayed(runnableStart, 1000);
+ }
+ };
+ CustomAlertDialog appdialog;
+ void popupAlert() {
+ MainActivity.csLibrary4A.appendToLog("DirectWedgeFragment: entering popupAlert");
+ if (appdialog != null && appdialog.isShowing()) {
+ MainActivity.csLibrary4A.appendToLog("DirectWedgeFragment: skip popupAlert");
+ return;
+ }
+ appdialog = new CustomAlertDialog();
+ appdialog.Confirm(getActivity(), "Enable <" + stringLabelExpected + ">",
+ "<" + stringLabelExpected + "> is not enabled. Click OK to open Languages & Input Settings. You will need to select <" + stringLabelExpected + "> in your current keyboard to use it",
+ "No thanks", "OK",
+ new Runnable() {
+ @Override
+ public void run() {
+ MainActivity.csLibrary4A.appendToLog("Ok Procedure");
+ Intent enableIntent = new Intent(Settings.ACTION_INPUT_METHOD_SETTINGS);
+ enableIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+ getActivity().startActivity(enableIntent);
+ }
+ },
+ new Runnable() {
+ @Override
+ public void run() {
+ MainActivity.csLibrary4A.appendToLog("Cancel procedure");
+ getActivity().finish();
+ //System.exit(0);
+ }
+ });
+ MainActivity.csLibrary4A.appendToLog("DirectWedgeFragment: EXIT popupAlert");
+ }
+
+ void updateCurrentIMEMatched() {
+ if (true) {
+ boolean bFound = false;
+ List list = null;
+ stringImeExpected = getActivity().getPackageName() + ".CustomIME";
+ if (MainActivity.drawerPositionsDefault != DrawerListContent.DrawerPositions.MAIN) stringLabelExpected = getResources().getString(R.string.app_ime_simplewedge1);
+ else if (getActivity().getPackageName().contains("cs710ademoapp")) stringLabelExpected = getResources().getString(R.string.app_ime_cs710);
+ else stringLabelExpected = getResources().getString(R.string.app_ime_cs108);
+ InputMethodManager inputMethodManager = inputMethodManager = (InputMethodManager) getActivity().getSystemService(getActivity().INPUT_METHOD_SERVICE);
+
+ MainActivity.csLibrary4A.appendToLog("FEATURE_INPUT_METHODS is " + getActivity().getPackageManager().hasSystemFeature(PackageManager.FEATURE_INPUT_METHODS));
+ list = inputMethodManager.getEnabledInputMethodList(); bFound = false;
+ MainActivity.csLibrary4A.appendToLog("getCurrentInputMethodSubtype = " + inputMethodManager.getCurrentInputMethodSubtype().getLanguageTag());
+ for (int i = 0; i < list.size(); i++) {
+ MainActivity.csLibrary4A.appendToLog("enabled " + i + ": " + list.get(i).getServiceName()
+ + ", " + list.get(i).getPackageName()
+ + ", " + list.get(i).loadLabel(getActivity().getPackageManager()).toString()
+ + ", " + list.get(i).getIsDefaultResourceId());
+ if (list.get(i).getServiceName().contains(stringImeExpected) && list.get(i).loadLabel(getActivity().getPackageManager()).toString().contains(stringLabelExpected)) {
+ bFound = true;
+ MainActivity.csLibrary4A.appendToLog("Found expected IME");
+ }
+ }
+
+ if (bFound == false) {
+ MainActivity.csLibrary4A.appendToLog("DirectWedgeFragment: No " + stringImeExpected + " is found");
+ if (false) inputMethodManager.showInputMethodPicker();
+ else popupAlert();
+ } else if (true) {
+ list = inputMethodManager.getInputMethodList(); bFound = false;
+ for (int i = 0; i < list.size(); i++) {
+ MainActivity.csLibrary4A.appendToLog(i + ": " + list.get(i).getServiceName()
+ + ", " + list.get(i).getPackageName()
+ + ", " + list.get(i).loadLabel(getActivity().getPackageManager()).toString()
+ + ", " + list.get(i).getIsDefaultResourceId());
+
+ List submethods = inputMethodManager.getEnabledInputMethodSubtypeList(list.get(i), true);
+ for (InputMethodSubtype submethod : submethods) {
+ if (submethod.getMode().equals("keyboard")) {
+ String currentLocale = submethod.getLocale();
+ MainActivity.csLibrary4A.appendToLog("Available input method locale: " + currentLocale);
+ }
+ }
+
+ if (list.get(i).getServiceName().contains(stringImeExpected) && list.get(i).loadLabel(getActivity().getPackageManager()).toString().contains(stringLabelExpected)) {
+ bFound = true;
+ MainActivity.csLibrary4A.appendToLog("Found expected IME with id = " + list.get(i).getId());
+ String idCurrent = Settings.Secure.getString(mContext.getContentResolver(), Settings.Secure.DEFAULT_INPUT_METHOD);
+ MainActivity.csLibrary4A.appendToLog("Found current IME with id = " + idCurrent);
+ if (list.get(i).getId().matches(idCurrent)) {
+ MainActivity.csLibrary4A.appendToLog("expected IME matches current IME");
+ bCurrentIMEmatched = true;
+ } else {
+ MainActivity.csLibrary4A.appendToLog("expected IME does NOT match current IME");
+ bCurrentIMEmatched = false;
+ }
+/*
+ CustomIME customIME = new CustomIME();
+ InputMethodService inputMethodService = getActivity().get
+ customIME.switchInputMethod(list.get(i).getId());
+*/
+ //String oldDefaultKeyboard = Settings.Secure.getString(resolver, Setting.Secure.DEFAULT_INPUT_METHOD);
+ //MainActivity.csLibrary4A.appendToLog("oldDefaultKeyboard = " + oldDefaultKeyboard);
+ /*inputMethodManager.toggleSoftInputFromWindow(
+ linearLayout.getApplicationWindowToken(),
+ InputMethodManager.SHOW_FORCED, 0);*/
+
+ IBinder iBinder = getView().getWindowToken();
+ MainActivity.csLibrary4A.appendToLog("iBinder is " + (iBinder == null ? "null" : "valid"));
+ if (iBinder != null) inputMethodManager.setInputMethod(iBinder, list.get(i).getId());
+ }
+ }
+ }
+ }
+ }
+}
+
+
+
+package com.csl.cs710ademoapp.fragments;
+
+import static com.csl.cslibrary4a.RfidReader.TagType.TAG_FDMICRO;
+
+import android.os.Bundle;
+
+import com.csl.cslibrary4a.AdapterTab;
+import com.google.android.material.tabs.TabLayout;
+
+import androidx.viewpager.widget.ViewPager;
+import androidx.appcompat.app.ActionBar;
+import androidx.appcompat.app.AppCompatActivity;
+import android.view.LayoutInflater;
+import android.view.MenuItem;
+import android.view.View;
+import android.view.ViewGroup;
+
+import com.csl.cs710ademoapp.R;
+
+public class FdmicroFragment extends CommonFragment {
+ private ActionBar actionBar;
+ private ViewPager viewPager;
+ AdapterTab adapter;
+
+ private String[] tabs = {"Scan", "Configuration"};
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ super.onCreateView(inflater, container, savedInstanceState, true);
+ return inflater.inflate(R.layout.custom_tabbed_layout, container, false);
+ }
+
+ @Override
+ public boolean onOptionsItemSelected(MenuItem item) {
+ InventoryRfidiMultiFragment fragment = (InventoryRfidiMultiFragment) adapter.fragment0;
+ if (item.getItemId() == R.id.menuAction_clear) {
+ fragment.clearTagsList();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_sortRssi) {
+ fragment.sortTagsListByRssi();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_sort) {
+ fragment.sortTagsList();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_save) {
+ fragment.saveTagsList();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_share) {
+ fragment.shareTagsList();
+ return true;
+ } else return super.onOptionsItemSelected(item);
+ }
+
+ @Override
+ public void onActivityCreated(Bundle savedInstanceState) {
+ super.onActivityCreated(savedInstanceState);
+
+ actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
+ actionBar.setIcon(R.drawable.dl_inv);
+ actionBar.setTitle(R.string.title_activity_fdMicro);
+
+ TabLayout tabLayout = (TabLayout) getActivity().findViewById(R.id.OperationsTabLayout);
+ for (String tab_name : tabs) {
+ tabLayout.addTab(tabLayout.newTab().setText(tab_name));
+ }
+ tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
+ @Override
+ public void onTabSelected(TabLayout.Tab tab) {
+ viewPager.setCurrentItem(tab.getPosition());
+ }
+
+ @Override
+ public void onTabUnselected(TabLayout.Tab tab) {
+ }
+
+ @Override
+ public void onTabReselected(TabLayout.Tab tab) {
+ }
+ });
+
+ adapter = new AdapterTab(getActivity().getSupportFragmentManager(), tabs.length);
+ adapter.setFragment(0, InventoryRfidiMultiFragment.newInstance(true, TAG_FDMICRO, "E2827001"));
+ adapter.setFragment(1, new AccessFdmicroFragment());
+
+ viewPager = (ViewPager) getActivity().findViewById(R.id.OperationsPager);
+ viewPager.setAdapter(adapter);
+ viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
+ }
+
+ @Override
+ public void onPause() {
+ adapter.fragment0.onPause();
+ adapter.fragment1.onPause();
+ super.onPause();
+ }
+
+ @Override
+ public void onStop() {
+ adapter.fragment0.onStop();
+ adapter.fragment1.onStop();
+ super.onStop();
+ }
+
+ @Override
+ public void onDestroyView() {
+ adapter.fragment0.onDestroyView();
+ adapter.fragment1.onDestroyView();
+ super.onDestroyView();
+ }
+
+ @Override
+ public void onDestroy() {
+ adapter.fragment0.onDestroy();
+ adapter.fragment1.onDestroy();
+ super.onDestroy();
+ }
+
+ @Override
+ public void onDetach() {
+ adapter.fragment0.onDetach();
+ adapter.fragment1.onDetach();
+ super.onDetach();
+ }
+
+ public FdmicroFragment() {
+ super("FdmicroFragment");
+ }
+}
+
+
+
+package com.csl.cs710ademoapp.fragments;
+
+import android.os.Bundle;
+import android.os.Handler;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.TextView;
+
+import androidx.appcompat.app.ActionBar;
+import androidx.appcompat.app.AppCompatActivity;
+
+import com.csl.cs710ademoapp.BuildConfig;
+import com.csl.cs710ademoapp.MainActivity;
+import com.csl.cs710ademoapp.R;
+
+public class ForegroundFragment extends CommonFragment {
+ Handler mHandler = new Handler();
+ long timeMillis = 0;
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ super.onCreateView(inflater, container, savedInstanceState, true);
+ return inflater.inflate(R.layout.fragment_about, container, false);
+ }
+
+ @Override
+ public void onActivityCreated(Bundle savedInstanceState) {
+ super.onActivityCreated(savedInstanceState);
+
+ ActionBar actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
+ actionBar.setIcon(R.drawable.dl_about);
+ actionBar.setTitle(R.string.title_activity_about);
+
+ TextView appVersionView = (TextView) getActivity().findViewById(R.id.appVersion);
+ appVersionView.setText(BuildConfig.VERSION_NAME);
+ TextView libVersionView = (TextView) getActivity().findViewById(R.id.libVersion);
+ libVersionView.setText(MainActivity.csLibrary4A.getlibraryVersion());
+
+ MainActivity.mSensorConnector.mLocationDevice.turnOn(true);
+ MainActivity.mSensorConnector.mSensorDevice.turnOn(true);
+ mHandler.post(updateRunnable);
+ }
+
+ @Override
+ public void onDestroy() {
+ MainActivity.mSensorConnector.mLocationDevice.turnOn(false);
+ MainActivity.mSensorConnector.mSensorDevice.turnOn(false);
+ mHandler.removeCallbacks(updateRunnable);
+ super.onDestroy();
+ }
+
+ public ForegroundFragment() {
+ super("AboutFragment");
+ }
+
+ private final Runnable updateRunnable = new Runnable() {
+ @Override
+ public void run() {
+ TextView timeStampView = (TextView) getActivity().findViewById(R.id.timeStamp);
+ TextView locationView = (TextView) getActivity().findViewById(R.id.GeoLocation);
+ TextView eCompassView = (TextView) getActivity().findViewById(R.id.eCompass);
+
+ TextView radioVersion = (TextView) getActivity().findViewById(R.id.radioVersion);
+ TextView modelVersion = (TextView) getActivity().findViewById(R.id.modelVersion);
+ TextView moduleRfidOnStatus = (TextView) getActivity().findViewById(R.id.moduleRfid_onStatus);
+ TextView moduleBarOnStatus = (TextView) getActivity().findViewById(R.id.moduleBar_onStatus);
+ TextView triggerOnStatus = (TextView) getActivity().findViewById(R.id.trigger_onStatus);
+ TextView moduleBattery = (TextView) getActivity().findViewById(R.id.module_battery);
+ TextView moduleVersionLabel = (TextView) getActivity().findViewById(R.id.module_versionLabel);
+ if (MainActivity.csLibrary4A.get98XX() == 2) moduleVersionLabel.setText("Atmel firmware version");
+ else if (MainActivity.csLibrary4A.get98XX() == 0) moduleVersionLabel.setText("SiliconLab firmware version");
+ TextView moduleVersion = (TextView) getActivity().findViewById(R.id.module_version);
+ TextView radioSerial = (TextView) getActivity().findViewById(R.id.radio_serialnumber);
+ TextView radioBoardVersion = (TextView) getActivity().findViewById(R.id.radio_boardVersion);
+ TextView productSerial = (TextView) getActivity().findViewById(R.id.module_productserialnumber);
+ TextView boardVersion = (TextView) getActivity().findViewById(R.id.module_boardversion);
+ TextView barcodeSerial = (TextView) getActivity().findViewById(R.id.moduleBar_serialNumber);
+ TextView barcodeDate = (TextView) getActivity().findViewById(R.id.moduleBar_date);
+ TextView barcodeVersion = (TextView) getActivity().findViewById(R.id.moduleBar_version);
+
+ TextView bluetoothVersion = (TextView) getActivity().findViewById(R.id.bluetooth_version);
+ TextView bluetoothAddress = (TextView) getActivity().findViewById(R.id.bluetooth_address);
+ TextView bluetoothRssi = (TextView) getActivity().findViewById(R.id.bluetooth_rssi);
+
+ timeStampView.setText(MainActivity.mSensorConnector.getTimeStamp());
+ locationView.setText(MainActivity.mSensorConnector.mLocationDevice.getLocation());
+ eCompassView.setText(MainActivity.mSensorConnector.mSensorDevice.getEcompass());
+ if (MainActivity.csLibrary4A.isBleConnected()) {
+ if (System.currentTimeMillis() - timeMillis > 5000) {
+ timeMillis = System.currentTimeMillis();
+ radioVersion.setText(MainActivity.csLibrary4A.getMacVer());
+ modelVersion.setText(MainActivity.csLibrary4A.getModelNumber());
+ moduleVersion.setText(MainActivity.csLibrary4A.hostProcessorICGetFirmwareVersion());
+ bluetoothVersion.setText(MainActivity.csLibrary4A.getBluetoothICFirmwareVersion());
+ MainActivity.csLibrary4A.batteryLevelRequest();
+ }
+ moduleRfidOnStatus.setText(MainActivity.csLibrary4A.getRfidOnStatus() ? "on" : "off");
+ triggerOnStatus.setText(MainActivity.csLibrary4A.getTriggerButtonStatus() ? "pressed" : "released");
+ moduleBarOnStatus.setText(MainActivity.csLibrary4A.getBarcodeOnStatus() ? "on" : "off");
+ moduleBattery.setText(MainActivity.csLibrary4A.getBatteryDisplay(true));
+ if (MainActivity.csLibrary4A.isRfidFailure()) radioSerial.setText("Not available");
+ else radioSerial.setText(MainActivity.csLibrary4A.getRadioSerial());
+ radioBoardVersion.setText(MainActivity.csLibrary4A.getRadioBoardVersion());
+ productSerial.setText(MainActivity.csLibrary4A.getHostProcessorICSerialNumber());
+ boardVersion.setText(MainActivity.csLibrary4A.getHostProcessorICBoardVersion());
+ if (MainActivity.csLibrary4A.isBarcodeFailure()) barcodeSerial.setText("Not available");
+ else {
+ barcodeSerial.setText(MainActivity.csLibrary4A.getBarcodeSerial());
+ barcodeDate.setText(MainActivity.csLibrary4A.getBarcodeDate());
+ barcodeVersion.setText(MainActivity.csLibrary4A.getBarcodeVersion());
+ }
+ bluetoothAddress.setText(MainActivity.csLibrary4A.getBluetoothDeviceAddress());
+ bluetoothRssi.setText(String.valueOf(MainActivity.csLibrary4A.getRssi()));
+ } else {
+ radioVersion.setText("");
+ moduleRfidOnStatus.setText("");
+ moduleBarOnStatus.setText("");
+ triggerOnStatus.setText("");
+ moduleBattery.setText("");
+ moduleVersion.setText("");
+ bluetoothVersion.setText("");
+ radioSerial.setText("");
+ radioBoardVersion.setText("");
+ productSerial.setText("");
+ boardVersion.setText("");
+ barcodeSerial.setText("");
+ bluetoothAddress.setText("");
+ bluetoothRssi.setText("");
+ }
+ mHandler.postDelayed(updateRunnable, 1000);
+ }
+ };
+}
+
+
+
+package com.csl.cs710ademoapp.fragments;
+
+import static android.Manifest.permission.ACCESS_COARSE_LOCATION;
+import static android.Manifest.permission.ACCESS_FINE_LOCATION;
+import static android.Manifest.permission.BLUETOOTH_CONNECT;
+import static android.Manifest.permission.BLUETOOTH_SCAN;
+import static android.Manifest.permission.POST_NOTIFICATIONS;
+import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
+import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
+import static android.content.Context.LOCATION_SERVICE;
+import static androidx.core.app.ServiceCompat.STOP_FOREGROUND_REMOVE;
+import static androidx.core.app.ServiceCompat.stopForeground;
+import static androidx.core.content.ContextCompat.getSystemService;
+import static com.csl.cs710ademoapp.MainActivity.isHomeFragment;
+import static com.csl.cs710ademoapp.MainActivity.mContext;
+
+import android.app.ActivityManager;
+import android.app.Service;
+import android.content.Context;
+import android.content.Intent;
+import android.content.pm.PackageManager;
+import android.location.LocationManager;
+import android.os.Build;
+import android.os.Bundle;
+import android.util.Log;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.Button;
+import android.widget.FrameLayout;
+import android.widget.LinearLayout;
+
+import androidx.appcompat.app.ActionBar;
+import androidx.appcompat.app.AppCompatActivity;
+import androidx.core.app.ActivityCompat;
+import androidx.core.app.NotificationManagerCompat;
+import androidx.core.content.ContextCompat;
+
+import com.csl.cs710ademoapp.CustomAlertDialog;
+import com.csl.cs710ademoapp.CustomPopupWindow;
+import com.csl.cs710ademoapp.CustomProgressDialog;
+import com.csl.cs710ademoapp.MainActivity;
+import com.csl.cs710ademoapp.MyForegroundService;
+import com.csl.cs710ademoapp.R;
+
+public class HomeFragment extends CommonFragment {
+ final boolean DEBUG = false;
+
+ @Override
+ public void onAttach(Context context) {
+ Log.i("Hello", "HomeFragment.onAttach");
+ super.onAttach(context);
+ }
+ @Override
+ public void onStart() {
+ Log.i("Hello", "HomeFragment.onStart");
+ isHomeFragment = true;
+ MainActivity.csLibrary4A.appendToLog("isHomeFragment1 = " + isHomeFragment);
+ super.onStart();
+ }
+
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ super.onCreateView(inflater, container, savedInstanceState, true);
+ if (getActivity().getPackageName().contains("com.csl.cs710ademoapp")) return inflater.inflate(R.layout.home_layout710, container, false);
+ else return inflater.inflate(R.layout.home_layout108, container, false);
+ }
+
+ @Override
+ public void onActivityCreated(Bundle savedInstanceState) {
+ super.onActivityCreated(savedInstanceState);
+
+ if (true) {
+ String strForegroundReader = MainActivity.csLibrary4A.getForegroundReader();
+ MainActivity.csLibrary4A.appendToLog("strForegroundReader = " + strForegroundReader + ", getForegroundServiceEnable = " + MainActivity.csLibrary4A.getForegroundServiceEnable());
+ if (!getActivity().getPackageName().contains("com.csl.cs710awedgeapp") && strForegroundReader != null && strForegroundReader.length() != 0) {
+ MainActivity.csLibrary4A.appendToLog("strForegroundReader = " + strForegroundReader + ", getForegroundServiceEnable = " + MainActivity.csLibrary4A.getForegroundServiceEnable());
+ LinearLayout linearLayout1, linearLayout2, linearLayout3, linearLayout4, linearLayout5;
+ linearLayout1 = (LinearLayout) getActivity().findViewById(R.id.mainRow1);
+ linearLayout2 = (LinearLayout) getActivity().findViewById(R.id.mainRow2);
+ linearLayout3 = (LinearLayout) getActivity().findViewById(R.id.mainRow3);
+ linearLayout4 = (LinearLayout) getActivity().findViewById(R.id.mainRow4);
+ linearLayout5 = (LinearLayout) getActivity().findViewById(R.id.mainRow5);
+ if (getActivity().getPackageName().contains("com.csl.cs710ademoapp")) {
+ FrameLayout frameLayout = (FrameLayout) getActivity().findViewById(R.id.mainButton1);
+ frameLayout.setVisibility(View.INVISIBLE);
+ } else {
+ Button button = (Button) getActivity().findViewById(R.id.mainButton1);
+ button.setVisibility(View.INVISIBLE);
+ }
+ linearLayout1.setVisibility(View.INVISIBLE);
+ linearLayout2.setVisibility(View.GONE);
+ linearLayout3.setVisibility(View.VISIBLE);
+ linearLayout4.setVisibility(View.INVISIBLE);
+ //linearLayout5.setVisibility(View.INVISIBLE);
+
+ }
+ }
+ MainActivity.tagType = null; MainActivity.mDid = null;
+ if (true || MainActivity.sharedObjects.versionWarningShown == false)
+ mHandler.post(runnableConfiguring);
+ mHandler.postDelayed(runnableStartService, 1000);
+ }
+
+ @Override
+ public void onStop() {
+ stopProgressDialog();
+ mHandler.removeCallbacks(runnableConfiguring);
+ super.onStop();
+ }
+
+ @Override
+ public void onDestroyView() {
+ isHomeFragment = false;
+ //MainActivity.csLibrary4A.appendToLog("isHomeFragment1 = " + isHomeFragment);
+ super.onDestroyView();
+ }
+
+ public HomeFragment() {
+ super("HomeFragment");
+ }
+
+ CustomProgressDialog progressDialog;
+ void stopProgressDialog() {
+ if (progressDialog != null) { if (progressDialog.isShowing()) progressDialog.dismiss(); }
+ }
+ Runnable runnableConfiguring = new Runnable() {
+ boolean DEBUG = false;
+ @Override
+ public void run() {
+ if (true) {
+ MainActivity.csLibrary4A.appendToLog("runnableConfiguring(): isBleConnected = " + MainActivity.csLibrary4A.isBleConnected() + ", isRfidFailure = " + MainActivity.csLibrary4A.isRfidFailure());
+ MainActivity.csLibrary4A.appendToLog("runnableConfiguring(): mrfidToWriteSize = " + MainActivity.csLibrary4A.mrfidToWriteSize());
+ }
+ boolean progressShown = false;
+ if (progressDialog != null) { if (progressDialog.isShowing()) progressShown = true; }
+ if (MainActivity.csLibrary4A.isBleConnected() == false || MainActivity.csLibrary4A.isRfidFailure()) {
+ if (progressShown) {
+ stopProgressDialog();
+ /*String stringPopup = "Connection failed, please rescan.";
+ CustomPopupWindow customPopupWindow = new CustomPopupWindow((Context) getActivity());
+ customPopupWindow.popupStart(stringPopup, false); */
+ }
+ } else if (MainActivity.csLibrary4A.mrfidToWriteSize() != 0) {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("mrfidToWriteSize = " + MainActivity.csLibrary4A.mrfidToWriteSize());
+ mHandler.postDelayed(runnableConfiguring, 250);
+ if (progressShown == false) {
+ progressDialog = new CustomProgressDialog(getActivity(), "Initializing reader. Please wait.");
+ progressDialog.show();
+ }
+ } else {
+ stopProgressDialog();
+ if (MainActivity.sharedObjects.versionWarningShown == false) {
+ String stringPopup = MainActivity.csLibrary4A.checkVersion();
+ if (stringPopup != null && stringPopup.length() != 0) {
+ if (stringPopup.indexOf("Unknown") != 0) stringPopup = "Firmware too old\nPlease upgrade firmware to at least:" + stringPopup;
+ CustomPopupWindow customPopupWindow = new CustomPopupWindow((Context)getActivity());
+ customPopupWindow.popupStart(stringPopup, false);
+ }
+ MainActivity.sharedObjects.versionWarningShown = true;
+ }
+ }
+ MainActivity.csLibrary4A.setPwrManagementMode(true);
+ }
+ };
+
+ Runnable runnableStartService = new Runnable() {
+ boolean DEBUG = false;
+
+ @Override
+ public void run() {
+ MainActivity.csLibrary4A.appendToLog("runnableStartService: ActivityCompat.checkSelfPermission(activity, WRITE_EXTERNAL_STORAGE) = " + ActivityCompat.checkSelfPermission(mContext, WRITE_EXTERNAL_STORAGE));
+ MainActivity.csLibrary4A.appendToLog("runnableStartService: ActivityCompat.checkSelfPermission(activity, READ_EXTERNAL_STORAGE) = " + ActivityCompat.checkSelfPermission(mContext, READ_EXTERNAL_STORAGE));
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
+ if (mContext.checkSelfPermission(WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
+ MainActivity.csLibrary4A.appendToLog("runnableStartService: requestPermissions WRITE_EXTERNAL_STORAGE"); //
+ requestPermissions(new String[] { WRITE_EXTERNAL_STORAGE, READ_EXTERNAL_STORAGE }, 1);
+ //Toast.makeText(mContext, com.csl.cslibrary4a.R.string.toast_permission_not_granted, Toast.LENGTH_SHORT).show();
+ } else MainActivity.csLibrary4A.appendToLog("runnableStartService: WRITE_EXTERNAL_STORAGE is permitted"); ///
+ } else MainActivity.csLibrary4A.appendToLog("runnableStartService: no need to handle WRITE_EXTERNAL_STORAGE");
+
+ LocationManager locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
+ MainActivity.csLibrary4A.appendToLog("runnableStartService: locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) = " + locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER));
+ MainActivity.csLibrary4A.appendToLog("runnableStartService: locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER) = " + locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER));
+ MainActivity.csLibrary4A.appendToLog("runnableStartService: ActivityCompat.checkSelfPermission(activity, ACCESS_FINE_LOCATION) = " + ActivityCompat.checkSelfPermission(mContext, ACCESS_FINE_LOCATION));
+ MainActivity.csLibrary4A.appendToLog("runnableStartService: ActivityCompat.checkSelfPermission(activity, ACCESS_COARSE_LOCATION) = " + ActivityCompat.checkSelfPermission(mContext, ACCESS_COARSE_LOCATION));
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
+ if ((ActivityCompat.checkSelfPermission(mContext, ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED || ActivityCompat.checkSelfPermission(mContext, ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)) {
+ CustomAlertDialog appdialog = new CustomAlertDialog();
+ appdialog.Confirm(getActivity(), "Use your location",
+ "This app collects location data in the background. In terms of the features using this location data in the background, this App collects location data when it is reading RFID tag in all inventory pages. The purpose of this is to correlate the RFID tag with the actual GNSS(GPS) location of the tag. In other words, this is to track the physical location of the logistics item tagged with the RFID tag.",
+ "No thanks", "Turn on",
+ new Runnable() {
+ @Override
+ public void run() {
+ MainActivity.csLibrary4A.appendToLog("runnableStartService: allow permission in ACCESS_FINE_LOCATION handler");
+ MainActivity.csLibrary4A.appendToLog("runnableStartService: requestPermissions ACCESS_FINE_LOCATION");
+ requestPermissions(new String[] { ACCESS_FINE_LOCATION }, 123); //ACCESS_FINE_LOCATION, ACCESS_COARSE_LOCATION
+ //if (false) Toast.makeText(mContext, com.csl.cslibrary4a.R.string.toast_permission_not_granted, Toast.LENGTH_SHORT).show();
+ /*{
+ LocationManager locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
+ if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) == false && locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER) == false) {
+ MainActivity.csLibrary4A.appendToLog("popupAlert: StreamOut: start activity ACTION_LOCATION_SOURCE_SETTINGS");
+ Intent intent1 = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
+ mContext.startActivity(intent1);
+ }
+ }*/
+ //bleEnableRequestShown0 = true; mHandler.postDelayed(mRquestAllowRunnable, 60000);
+ //bAlerting = false;
+ }
+ },
+ new Runnable() {
+ @Override
+ public void run() {
+ MainActivity.csLibrary4A.appendToLog("runnableStartService: reject permission in ACCESS_FINE_LOCATION handler");
+ //bAlerting = false;
+ //bleEnableRequestShown0 = true; mHandler.postDelayed(mRquestAllowRunnable, 60000);
+ }
+ });
+ MainActivity.csLibrary4A.appendToLog("runnableStartService: started ACCESS_FINE_LOCATION handler");
+ } else MainActivity.csLibrary4A.appendToLog("runnableStartService: handled ACCESS_FINE_LOCATION");
+ } else MainActivity.csLibrary4A.appendToLog("runnableStartService: no need to handle ACCESS_FINE_LOCATION");
+
+ MainActivity.csLibrary4A.appendToLog("runnableStartService: ActivityCompat.checkSelfPermission(activity, BLUETOOTH_CONNECT) = " + ActivityCompat.checkSelfPermission(mContext, BLUETOOTH_CONNECT));
+ MainActivity.csLibrary4A.appendToLog("runnableStartService: ActivityCompat.checkSelfPermission(activity, BLUETOOTH_SCAN) = " + ActivityCompat.checkSelfPermission(mContext, BLUETOOTH_SCAN));
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
+ if (ActivityCompat.checkSelfPermission(mContext, BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED || ActivityCompat.checkSelfPermission(mContext, BLUETOOTH_SCAN) != PackageManager.PERMISSION_GRANTED) {
+ MainActivity.csLibrary4A.appendToLog("runnableStartService: requestPermissions BLUETOOTH_SCAN and BLUETOOTH_CONNECT");
+ requestPermissions(new String[] { BLUETOOTH_SCAN, BLUETOOTH_CONNECT }, 123);
+ } else MainActivity.csLibrary4A.appendToLog("runnableStartService: handled BLUETOOTH_CONNECT and BLUETOOTH_SCAN");
+ } else MainActivity.csLibrary4A.appendToLog("runnableStartService: no need to handle BLUETOOTH_SCAN and BLUETOOTH_CONNECT");
+
+ MainActivity.csLibrary4A.appendToLog("runnableStartService: ActivityCompat.checkSelfPermission(activity, POST_NOTIFICATIONS) = " + ActivityCompat.checkSelfPermission(mContext, POST_NOTIFICATIONS));
+ if (NotificationManagerCompat.from(getActivity()).areNotificationsEnabled()) MainActivity.csLibrary4A.appendToLog("Notification is enabled");
+ else MainActivity.csLibrary4A.appendToLog("Notification is disabled");
+ if (!MainActivity.foregroundServiceEnable) { }
+ else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
+ if (ActivityCompat.checkSelfPermission(mContext, POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
+ MainActivity.csLibrary4A.appendToLog("runnableStartService: requestPermissions POST_NOTIFICATIONS");
+ requestPermissions(new String[] { POST_NOTIFICATIONS }, 10); //POST_NOTIFICATIONS, FOREGROUND_SERVICE_LOCATION
+ } else {
+ MainActivity.csLibrary4A.appendToLog("runnableStartService: handled POST_NOTIFICATIONS");
+ startService();
+ }
+ } else {
+ MainActivity.csLibrary4A.appendToLog("runnableStartService: no need to handle POST_NOTIFICATIONS");
+ startService();
+ }
+ }
+ };
+ Intent serviceIntent;
+ Service serviceStarted;
+ public void startService() {
+ ActivityManager activityManager = (ActivityManager) getSystemService(getContext(), ActivityManager.class);
+ for (ActivityManager.RunningServiceInfo service: activityManager.getRunningServices(Integer.MAX_VALUE)) {
+ MainActivity.csLibrary4A.appendToLog("MyForegroundService.class.getName = " + MyForegroundService.class.getName() + ", service.service.getClassName = " + service.service.getClassName());
+ if (MyForegroundService.class.getName().equals(service.service.getClassName())) {
+ return;
+ }
+ }
+ serviceIntent = new Intent(getActivity(), MyForegroundService.class);
+ Log.i("Hello", "getActivity is " + (getActivity() == null ? "NULL" : "Valid"));
+ serviceIntent.putExtra("inputExtra", "Foreground Service Example in Android");
+ Log.i("Hello", "getContext is " + (getContext() == null ? "NULL" : "Valid"));
+ ContextCompat.startForegroundService(getContext(), serviceIntent);
+ }
+ public void stopService1() {
+ //Intent serviceIntent = new Intent(getActivity(), CustomForegroundService.class);
+ stopForeground(serviceStarted, STOP_FOREGROUND_REMOVE);
+ }
+
+ void popupAlert() {
+
+ }
+}
+
+
+
+package com.csl.cs710ademoapp.fragments;
+
+import android.os.Bundle;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.Button;
+
+import androidx.appcompat.app.ActionBar;
+import androidx.appcompat.app.AppCompatActivity;
+
+import com.csl.cs710ademoapp.MainActivity;
+import com.csl.cs710ademoapp.R;
+
+public class HomeSpecialFragment extends CommonFragment {
+ final boolean DEBUG = false;
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ super.onCreateView(inflater, container, savedInstanceState, true);
+ return inflater.inflate(R.layout.home_special_layout, container, false);
+ }
+
+ @Override
+ public void onActivityCreated(Bundle savedInstanceState) {
+ super.onActivityCreated(savedInstanceState);
+
+ if (((AppCompatActivity) getActivity()).getSupportActionBar() != null) {
+ ActionBar actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
+ actionBar.setTitle(R.string.title_activity_special);
+ }
+
+ Button buttonAuraSense = (Button) getActivity().findViewById(R.id.SpecialButtonAurasense);
+ Button buttonFdmicro = (Button) getActivity().findViewById(R.id.SpecialButtonFdmicro);
+ Button buttonLanda = (Button) getActivity().findViewById(R.id.SpecialButtonLanda);
+ if (MainActivity.csLibrary4A.get98XX() == 2) {
+ buttonAuraSense.setVisibility(View.GONE);
+ buttonFdmicro.setVisibility(View.GONE); buttonLanda.setVisibility(View.GONE);
+ }
+ MainActivity.tagType = null; MainActivity.mDid = null;
+ if (MainActivity.csLibrary4A.isBleConnected()) MainActivity.csLibrary4A.restoreAfterTagSelect();
+ }
+
+ public HomeSpecialFragment() {
+ super("HomeSpecialFragment");
+ }
+}
+
+
+
+package com.csl.cs710ademoapp.fragments;
+
+import android.os.Bundle;
+import android.view.LayoutInflater;
+import android.view.MenuItem;
+import android.view.View;
+import android.view.ViewGroup;
+
+import androidx.appcompat.app.ActionBar;
+import androidx.appcompat.app.AppCompatActivity;
+import androidx.viewpager.widget.ViewPager;
+
+import com.csl.cs710ademoapp.MainActivity;
+import com.csl.cs710ademoapp.R;
+import com.csl.cslibrary4a.AdapterTab;
+import com.google.android.material.tabs.TabLayout;
+
+public class HomeWFragment extends CommonFragment {
+ private ActionBar actionBar;
+ private ViewPager viewPager;
+ AdapterTab adapter;
+
+ private String[] tabs = {"Normal", "Simple"};
+ int iTargetOld, iSessionOld;
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ super.onCreateView(inflater, container, savedInstanceState, true);
+ return inflater.inflate(R.layout.custom_tabbed_layout, container, false);
+ }
+
+ @Override
+ public boolean onOptionsItemSelected(MenuItem item) {
+ InventoryRfidiMultiFragment fragment1 = (InventoryRfidiMultiFragment) adapter.fragment1;
+ if (item.getItemId() == R.id.menuAction_clear) {
+ fragment1.clearTagsList();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_sortRssi) {
+ fragment1.sortTagsListByRssi();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_sort) {
+ fragment1.sortTagsList();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_save) {
+ fragment1.saveTagsList();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_share) {
+ fragment1.shareTagsList();
+ return true;
+ } else return super.onOptionsItemSelected(item);
+ }
+
+ @Override
+ public void onActivityCreated(Bundle savedInstanceState) {
+ super.onActivityCreated(savedInstanceState);
+
+ actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
+ actionBar.setIcon(R.drawable.dl_inv);
+ actionBar.setTitle(R.string.title_activity_home_cs108);
+
+ TabLayout tabLayout = (TabLayout) getActivity().findViewById(R.id.OperationsTabLayout);
+
+ MainActivity.csLibrary4A.appendToLog("adaptoer is " + (adapter == null ? "null" : "valid"));
+ if (adapter != null) {
+ adapter.fragment0.onDestroy();
+ adapter.fragment1.onDestroy();
+ }
+
+ adapter = new AdapterTab(getActivity().getSupportFragmentManager(), tabs.length);
+ adapter.setFragment(0, new HomeFragment());
+ adapter.setFragment(1, new DirectWedgeFragment());
+
+ MainActivity.csLibrary4A.appendToLog("viewPager is " + (viewPager == null ? "null" : "valid"));
+ viewPager = (ViewPager) getActivity().findViewById(R.id.OperationsPager);
+ viewPager.setAdapter(null); viewPager.setAdapter(adapter);
+ viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
+
+ for (String tab_name : tabs) {
+ MainActivity.csLibrary4A.appendToLog("adding tab_name = " + tab_name);
+ tabLayout.addTab(tabLayout.newTab().setText(tab_name));
+ }
+
+ tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
+ @Override
+ public void onTabSelected(TabLayout.Tab tab) {
+ viewPager.setCurrentItem(tab.getPosition());
+ }
+
+ @Override
+ public void onTabUnselected(TabLayout.Tab tab) {
+ }
+
+ @Override
+ public void onTabReselected(TabLayout.Tab tab) {
+ }
+ });
+ }
+
+ @Override
+ public void onPause() {
+ adapter.fragment0.onPause();
+ adapter.fragment1.onPause();
+ super.onPause();
+ }
+
+ @Override
+ public void onStop() {
+ adapter.fragment0.onStop();
+ adapter.fragment1.onStop();
+ super.onStop();
+ }
+
+ @Override
+ public void onDestroyView() {
+ adapter.fragment0.onDestroyView();
+ adapter.fragment1.onDestroyView();
+ super.onDestroyView();
+ }
+
+ @Override
+ public void onDestroy() {
+ adapter.fragment0.onDestroy();
+ adapter.fragment1.onDestroy();
+ super.onDestroy();
+ }
+
+ @Override
+ public void onDetach() {
+ adapter.fragment0.onDetach();
+ adapter.fragment1.onDetach();
+ super.onDetach();
+ }
+
+ public HomeWFragment() {
+ super("HomeWFragment");
+ }
+}
+
+
+
+package com.csl.cs710ademoapp.fragments;
+
+import android.os.Bundle;
+import android.view.LayoutInflater;
+import android.view.MenuItem;
+import android.view.View;
+import android.view.ViewGroup;
+
+import androidx.appcompat.app.ActionBar;
+import androidx.appcompat.app.AppCompatActivity;
+import androidx.viewpager.widget.ViewPager;
+
+import com.csl.cs710ademoapp.MainActivity;
+import com.csl.cs710ademoapp.R;
+import com.csl.cslibrary4a.AdapterTab;
+import com.google.android.material.tabs.TabLayout;
+
+public class ImpinjFragment extends CommonFragment {
+ private ActionBar actionBar;
+ private ViewPager viewPager;
+ AdapterTab adapter;
+
+ private String[] tabs = {"Configure", "Scan", "Authenticate"};
+ int iTargetOld, iSessionOld;
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ super.onCreateView(inflater, container, savedInstanceState, true);
+ return inflater.inflate(R.layout.custom_tabbed_layout, container, false);
+ }
+
+ @Override
+ public boolean onOptionsItemSelected(MenuItem item) {
+ InventoryRfidiMultiFragment fragment = (InventoryRfidiMultiFragment) adapter.getItem(1);
+ if (item.getItemId() == R.id.menuAction_clear) {
+ fragment.clearTagsList();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_sortRssi) {
+ fragment.sortTagsListByRssi();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_sort) {
+ fragment.sortTagsList();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_save) {
+ fragment.saveTagsList();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_share) {
+ fragment.shareTagsList();
+ return true;
+ } else return super.onOptionsItemSelected(item);
+ }
+
+ @Override
+ public void onActivityCreated(Bundle savedInstanceState) {
+ super.onActivityCreated(savedInstanceState);
+
+ actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
+ actionBar.setIcon(R.drawable.dl_inv);
+ actionBar.setTitle(R.string.title_activity_impinj);
+
+ TabLayout tabLayout = (TabLayout) getActivity().findViewById(R.id.OperationsTabLayout);
+
+ adapter = new AdapterTab(getActivity().getSupportFragmentManager(), tabs.length);
+ adapter.setFragment(0, new AccessImpinjFragment(false));
+ adapter.setFragment(1, InventoryRfidiMultiFragment.newInstance(true, null, ""));
+ adapter.setFragment(2, new AccessUcodeFragment());
+
+ viewPager = (ViewPager) getActivity().findViewById(R.id.OperationsPager);
+ viewPager.setAdapter(adapter);
+ viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
+
+ for (String tab_name : tabs) {
+ tabLayout.addTab(tabLayout.newTab().setText(tab_name));
+ }
+
+ tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
+ @Override
+ public void onTabSelected(TabLayout.Tab tab) {
+ viewPager.setCurrentItem(tab.getPosition());
+ }
+
+ @Override
+ public void onTabUnselected(TabLayout.Tab tab) {
+ }
+
+ @Override
+ public void onTabReselected(TabLayout.Tab tab) {
+ }
+ });
+
+ iTargetOld = MainActivity.csLibrary4A.getQueryTarget();
+ iSessionOld = MainActivity.csLibrary4A.getQuerySession();
+ }
+
+ @Override
+ public void onPause() {
+ adapter.fragment0.onPause();
+ adapter.fragment1.onPause();
+ super.onPause();
+ }
+
+ @Override
+ public void onStop() {
+ adapter.fragment0.onStop();
+ adapter.fragment1.onStop();
+ super.onStop();
+ }
+
+ @Override
+ public void onDestroyView() {
+ adapter.fragment0.onDestroyView();
+ adapter.fragment1.onDestroyView();
+ super.onDestroyView();
+ }
+
+ @Override
+ public void onDestroy() {
+ adapter.fragment0.onDestroy();
+ adapter.fragment1.onDestroy();
+ MainActivity.csLibrary4A.setTagGroup(MainActivity.csLibrary4A.getQuerySelect(), iSessionOld, iTargetOld);
+ //MainActivity.mCs108Library4a.macWrite(0x203, 0);
+ super.onDestroy();
+ }
+
+ @Override
+ public void onDetach() {
+ adapter.fragment0.onDetach();
+ adapter.fragment1.onDetach();
+ super.onDetach();
+ }
+
+ public ImpinjFragment() {
+ super("ImpinjFragment");
+ }
+}
+
+
+
+package com.csl.cs710ademoapp.fragments;
+
+import static com.csl.cslibrary4a.RfidReader.TagType.TAG_IMPINJ_M755;
+
+import androidx.appcompat.app.ActionBar;
+import androidx.appcompat.app.AppCompatActivity;
+import androidx.viewpager.widget.ViewPager;
+
+import android.os.Bundle;
+import android.view.LayoutInflater;
+import android.view.MenuItem;
+import android.view.View;
+import android.view.ViewGroup;
+
+import com.csl.cs710ademoapp.MainActivity;
+import com.csl.cs710ademoapp.R;
+import com.csl.cslibrary4a.AdapterTab;
+import com.google.android.material.tabs.TabLayout;
+
+public class ImpinjM775Fragment extends CommonFragment {
+ private ActionBar actionBar;
+ private ViewPager viewPager;
+ AdapterTab adapter;
+
+ private String[] tabs = {"Configuration", "Scan"};
+ int iTargetOld, iSessionOld;
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ super.onCreateView(inflater, container, savedInstanceState, true);
+ return inflater.inflate(R.layout.custom_tabbed_layout, container, false);
+ }
+
+ @Override
+ public boolean onOptionsItemSelected(MenuItem item) {
+ InventoryRfidiMultiFragment fragment = (InventoryRfidiMultiFragment) adapter.getItem(1);
+ return fragment.onOptionsItemSelected(item);
+ }
+
+ @Override
+ public void onActivityCreated(Bundle savedInstanceState) {
+ super.onActivityCreated(savedInstanceState);
+
+ actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
+ actionBar.setIcon(R.drawable.dl_inv);
+ actionBar.setTitle(R.string.title_activity_m775);
+
+ TabLayout tabLayout = (TabLayout) getActivity().findViewById(R.id.OperationsTabLayout);
+
+ adapter = new AdapterTab(getActivity().getSupportFragmentManager(), tabs.length);
+ adapter.setFragment(0, new AccessImpinjFragment(true));
+ adapter.setFragment(1, InventoryRfidiMultiFragment.newInstance(true, TAG_IMPINJ_M755, "E2C011"));
+
+ viewPager = (ViewPager) getActivity().findViewById(R.id.OperationsPager);
+ viewPager.setAdapter(adapter);
+ viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
+
+ for (String tab_name : tabs) {
+ tabLayout.addTab(tabLayout.newTab().setText(tab_name));
+ }
+
+ tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
+ @Override
+ public void onTabSelected(TabLayout.Tab tab) {
+ viewPager.setCurrentItem(tab.getPosition());
+ }
+
+ @Override
+ public void onTabUnselected(TabLayout.Tab tab) {
+ }
+
+ @Override
+ public void onTabReselected(TabLayout.Tab tab) {
+ }
+ });
+
+ iTargetOld = MainActivity.csLibrary4A.getQueryTarget();
+ iSessionOld = MainActivity.csLibrary4A.getQuerySession();
+ }
+
+ @Override
+ public void onPause() {
+ adapter.fragment0.onPause();
+ adapter.fragment1.onPause();
+ super.onPause();
+ }
+
+ @Override
+ public void onStop() {
+ adapter.fragment0.onStop();
+ adapter.fragment1.onStop();
+ super.onStop();
+ }
+
+ @Override
+ public void onDestroyView() {
+ adapter.fragment0.onDestroyView();
+ adapter.fragment1.onDestroyView();
+ super.onDestroyView();
+ }
+
+ @Override
+ public void onDestroy() {
+ adapter.fragment0.onDestroy();
+ adapter.fragment1.onDestroy();
+ MainActivity.csLibrary4A.setTagGroup(MainActivity.csLibrary4A.getQuerySelect(), iSessionOld, iTargetOld);
+ //MainActivity.library4a.macWrite(0x203, 0);
+ super.onDestroy();
+ }
+
+ @Override
+ public void onDetach() {
+ adapter.fragment0.onDetach();
+ adapter.fragment1.onDetach();
+ super.onDetach();
+ }
+
+ public ImpinjM775Fragment() {
+ super("ImpinjM775Fragment");
+ }
+}
+
+
+
+package com.csl.cs710ademoapp.fragments;
+
+import android.content.Intent;
+import android.media.MediaPlayer;
+import android.os.AsyncTask;
+import android.os.Bundle;
+import android.view.LayoutInflater;
+import android.view.MenuItem;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.AdapterView;
+import android.widget.Button;
+import android.widget.ListView;
+import android.widget.TextView;
+import android.widget.Toast;
+
+import com.csl.cs710ademoapp.InventoryBarcodeTask;
+import com.csl.cs710ademoapp.MainActivity;
+import com.csl.cs710ademoapp.R;
+import com.csl.cs710ademoapp.SaveList2ExternalTask;
+import com.csl.cs710ademoapp.adapters.ReaderListAdapter;
+import com.csl.cslibrary4a.NotificationConnector;
+import com.csl.cslibrary4a.ReaderDevice;
+
+import java.util.Collections;
+
+public class InventoryBarcodeFragment extends CommonFragment {
+ private ListView barcodeListView;
+ private TextView barcodeEmptyView;
+ private TextView barcodeRunTime, barcodeVoltageLevel;
+ private TextView barcodeYieldView, barcodeTotal;
+ private Button button;
+
+ MediaPlayer playerO, playerN;
+
+ private ReaderListAdapter readerListAdapter;
+
+ InventoryBarcodeTask inventoryBarcodeTask;
+
+ void clearTagsList() {
+ barcodeYieldView.setText(""); barcodeTotal.setText("");
+ MainActivity.sharedObjects.barsList.clear();
+ readerListAdapter.notifyDataSetChanged();
+ }
+ void sortTagsList() {
+ Collections.sort(MainActivity.sharedObjects.barsList);
+ readerListAdapter.notifyDataSetChanged();
+ }
+ void saveTagsList() {
+ SaveList2ExternalTask saveExternalTask = new SaveList2ExternalTask(MainActivity.sharedObjects.barsList);
+ saveExternalTask.execute();
+ }
+ void shareTagsList() {
+ SaveList2ExternalTask saveExternalTask = new SaveList2ExternalTask(MainActivity.sharedObjects.barsList);
+ String stringOutput = saveExternalTask.createStrEpcList();
+
+ Intent sendIntent = new Intent();
+ sendIntent.setAction(Intent.ACTION_SEND);
+ sendIntent.putExtra(Intent.EXTRA_TEXT, stringOutput);
+ sendIntent.setType("text/plain");
+ startActivity(Intent.createChooser(sendIntent, "Sharing to"));
+ }
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ super.onCreateView(inflater, container, savedInstanceState, false);
+ return inflater.inflate(R.layout.fragment_inventory_barcode, container, false);
+ }
+
+ @Override
+ public boolean onOptionsItemSelected(MenuItem item) {
+ if (item.getItemId() == R.id.menuAction_clear) {
+ clearTagsList();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_sortRssi) {
+ //sortTagsListByRssi();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_sort) {
+ sortTagsList();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_save) {
+ saveTagsList();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_share) {
+ shareTagsList();
+ return true;
+ } else return super.onOptionsItemSelected(item);
+ }
+
+ @Override
+ public void onActivityCreated(Bundle savedInstanceState) {
+ super.onActivityCreated(savedInstanceState);
+
+ barcodeListView = (ListView) getActivity().findViewById(R.id.inventoryBarcodeList);
+ barcodeEmptyView = (TextView) getActivity().findViewById(R.id.inventoryBarcodeEmpty);
+ barcodeListView.setEmptyView(barcodeEmptyView);
+ readerListAdapter = new ReaderListAdapter(getActivity(), R.layout.readers_list_item, MainActivity.sharedObjects.barsList, true, false);
+ barcodeListView.setAdapter(readerListAdapter);
+ barcodeListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
+ barcodeListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
+ @Override
+ public void onItemClick(AdapterView> parent, View view, int position, long id) {
+ ReaderDevice readerDevice = readerListAdapter.getItem(position);
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("Position = " + position);
+ if (readerDevice.getSelected()) {
+ readerDevice.setSelected(false);
+ } else {
+ readerDevice.setSelected(true);
+ }
+ MainActivity.sharedObjects.barsList.set(position, readerDevice);
+ if (readerDevice.getSelected()) MainActivity.tagSelected = readerDevice;
+ else MainActivity.tagSelected = null;
+ for (int i = 0; i < MainActivity.sharedObjects.barsList.size(); i++) {
+ if (i != position) {
+ ReaderDevice readerDevice1 = MainActivity.sharedObjects.barsList.get(i);
+ if (readerDevice1.getSelected()) {
+ readerDevice1.setSelected(false);
+ MainActivity.sharedObjects.barsList.set(i, readerDevice1);
+ }
+ }
+ }
+ readerListAdapter.notifyDataSetChanged();
+ }
+ });
+
+ barcodeRunTime = (TextView) getActivity().findViewById(R.id.inventoryBarcodeRunTime);
+ barcodeVoltageLevel = (TextView) getActivity().findViewById(R.id.inventoryBarcodeVoltageLevel);
+
+ barcodeYieldView = (TextView) getActivity().findViewById(R.id.inventoryBarcodeYield);
+ button = (Button) getActivity().findViewById(R.id.inventoryBarcodeButton);
+ button.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ startStopHandler(false);
+ }
+ });
+
+ barcodeTotal = (TextView) getActivity().findViewById(R.id.inventoryBarcodeTotal);
+
+ MainActivity.csLibrary4A.getBarcodePreSuffix();
+ }
+
+ @Override
+ public void onResume() {
+ super.onResume();
+ if (true) MainActivity.csLibrary4A.appendToLog("InventoryBarcodeFragment().onResume(): userVisibleHint = " + userVisibleHint);
+ if (userVisibleHint) {
+ MainActivity.csLibrary4A.setAutoBarStartSTop(true); setNotificationListener();
+ }
+ }
+
+ @Override
+ public void onPause() {
+ if (MainActivity.csLibrary4A != null) MainActivity.csLibrary4A.setNotificationListener(null);
+ if (inventoryBarcodeTask != null) {
+ if (DEBUG && MainActivity.csLibrary4A != null) MainActivity.csLibrary4A.appendToLog("InventoryBarcodeFragment().onDestory(): VALID inventoryBarcodeTask");
+ inventoryBarcodeTask.taskCancelReason = InventoryBarcodeTask.TaskCancelRReason.DESTORY;
+ }
+ super.onPause();
+ }
+
+ @Override
+ public void onDestroy() {
+ if (MainActivity.csLibrary4A != null) {
+ MainActivity.csLibrary4A.setAutoBarStartSTop(false);
+ MainActivity.csLibrary4A.setNotificationListener(null);
+ }
+ super.onDestroy();
+ }
+
+ boolean userVisibleHint = false;
+ @Override
+ public void setUserVisibleHint(boolean isVisibleToUser) {
+ super.setUserVisibleHint(isVisibleToUser);
+ if(getUserVisibleHint()) {
+ MainActivity.csLibrary4A.appendToLog("InventoryBarcodeFragment is now VISIBLE");
+ userVisibleHint = true;
+ MainActivity.csLibrary4A.setAutoBarStartSTop(true); setNotificationListener();
+ } else {
+ MainActivity.csLibrary4A.appendToLog("InventoryBarcodeFragment is now INVISIBLE");
+ userVisibleHint = false;
+ MainActivity.csLibrary4A.setAutoBarStartSTop(false); MainActivity.csLibrary4A.setNotificationListener(null);
+ }
+ }
+
+ public InventoryBarcodeFragment() {
+ super("InventoryBarcodeFragment");
+ }
+
+ void setNotificationListener() {
+ MainActivity.csLibrary4A.setNotificationListener(new NotificationConnector.NotificationListener() {
+ @Override
+ public void onChange() {
+ startStopHandler(true);
+ }
+ });
+ }
+
+ void startStopHandler(boolean buttonTrigger) {
+ if (buttonTrigger) MainActivity.csLibrary4A.appendToLog("BARTRIGGER: getTriggerButtonStatus = " + MainActivity.csLibrary4A.getTriggerButtonStatus());
+ if (MainActivity.sharedObjects.runningInventoryRfidTask) {
+ Toast.makeText(MainActivity.mContext, "Running RFID inventory", Toast.LENGTH_SHORT).show();
+ return;
+ }
+ boolean started = false;
+ if (inventoryBarcodeTask != null) if (inventoryBarcodeTask.getStatus() == AsyncTask.Status.RUNNING) started = true;
+ if (buttonTrigger && ((started && MainActivity.csLibrary4A.getTriggerButtonStatus()) || (started == false && MainActivity.csLibrary4A.getTriggerButtonStatus() == false))) {
+ MainActivity.csLibrary4A.appendToLog("BARTRIGGER: trigger ignore");
+ return;
+ }
+ if (started == false) {
+ if (MainActivity.csLibrary4A.isBleConnected() == false) {
+ Toast.makeText(MainActivity.mContext, R.string.toast_ble_not_connected, Toast.LENGTH_SHORT).show();
+ return;
+ }
+ if (MainActivity.csLibrary4A.isBarcodeFailure()) {
+ Toast.makeText(MainActivity.mContext, "Barcode is disabled", Toast.LENGTH_SHORT).show();
+ return;
+ }
+ MainActivity.csLibrary4A.appendToLog("BARTRIGGER: Start Barcode inventory");
+ started = true;
+ inventoryBarcodeTask = new InventoryBarcodeTask(MainActivity.sharedObjects.barsList, readerListAdapter, null, barcodeRunTime, barcodeVoltageLevel, barcodeYieldView, button, null, barcodeTotal, false);
+ inventoryBarcodeTask.execute();
+ } else {
+ MainActivity.csLibrary4A.appendToLog("BARTRIGGER: Stop Barcode inventory");
+ if (buttonTrigger) inventoryBarcodeTask.taskCancelReason = InventoryBarcodeTask.TaskCancelRReason.BUTTON_RELEASE;
+ else inventoryBarcodeTask.taskCancelReason = InventoryBarcodeTask.TaskCancelRReason.STOP;
+ }
+ }
+}
+
+
+
+package com.csl.cs710ademoapp.fragments;
+
+import android.os.Bundle;
+import android.util.Log;
+import android.view.LayoutInflater;
+import android.view.MenuItem;
+import android.view.View;
+import android.view.ViewGroup;
+
+import androidx.appcompat.app.ActionBar;
+import androidx.appcompat.app.AppCompatActivity;
+import androidx.viewpager.widget.ViewPager;
+
+import com.csl.cs710ademoapp.MainActivity;
+import com.csl.cs710ademoapp.R;
+import com.csl.cslibrary4a.AdapterTab;
+import com.google.android.material.tabs.TabLayout;
+
+public class InventoryFragment extends CommonFragment {
+ private ActionBar actionBar;
+ private ViewPager viewPager;
+ AdapterTab adapter;
+
+ private String[] tabs = {"RFID", "Barcode"};
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ savedInstanceState = null;
+ super.onCreateView(inflater, container, savedInstanceState, true);
+ return inflater.inflate(R.layout.custom_tabbed_layout, container, false);
+ }
+
+ @Override
+ public boolean onOptionsItemSelected(MenuItem item) {
+ MainActivity.csLibrary4A.appendToLog("InventoryFragment: onOptionsItemSelected with viewPager as " + viewPager.getCurrentItem());
+ InventoryRfidiMultiFragment fragment0 = (InventoryRfidiMultiFragment) adapter.getItem(0);
+ InventoryBarcodeFragment fragment1 = (InventoryBarcodeFragment) adapter.getItem(1);
+ switch (viewPager.getCurrentItem()) {
+ case 0:
+ return fragment0.onOptionsItemSelected(item);
+ case 1:
+ return fragment1.onOptionsItemSelected(item);
+ default:
+ return super.onOptionsItemSelected(item);
+ }
+ }
+
+ @Override
+ public void onActivityCreated(Bundle savedInstanceState) {
+ super.onActivityCreated(savedInstanceState);
+
+ actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
+ actionBar.setIcon(R.drawable.dl_inv);
+ actionBar.setTitle(R.string.title_activity_inventory);
+
+ TabLayout tabLayout = (TabLayout) getActivity().findViewById(R.id.OperationsTabLayout);
+
+ adapter = new AdapterTab(getActivity().getSupportFragmentManager(), tabs.length);
+ adapter.setFragment(0, InventoryRfidiMultiFragment.newInstance(false, null, null));
+ adapter.setFragment(1, new InventoryBarcodeFragment());
+
+ viewPager = (ViewPager) getActivity().findViewById(R.id.OperationsPager);
+ Log.i("Hello", "InventoryFragment.onActivity");
+ viewPager.setAdapter(adapter);
+ viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
+
+ for (String tab_name : tabs) {
+ tabLayout.addTab(tabLayout.newTab().setText(tab_name));
+ }
+
+ tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
+ @Override
+ public void onTabSelected(TabLayout.Tab tab) {
+ viewPager.setCurrentItem(tab.getPosition());
+ }
+
+ @Override
+ public void onTabUnselected(TabLayout.Tab tab) {
+ }
+
+ @Override
+ public void onTabReselected(TabLayout.Tab tab) {
+ }
+ });
+ }
+
+ @Override
+ public void onPause() {
+ adapter.fragment0.onPause();
+ adapter.fragment1.onPause();
+ super.onPause();
+ }
+
+ @Override
+ public void onStop() {
+ adapter.fragment0.onStop();
+ adapter.fragment1.onStop();
+ super.onStop();
+ }
+
+ @Override
+ public void onDestroyView() {
+ adapter.fragment0.onDestroyView();
+ adapter.fragment1.onDestroyView();
+ super.onDestroyView();
+ }
+
+ @Override
+ public void onDestroy() {
+ adapter.fragment0.onDestroy();
+ adapter.fragment1.onDestroy();
+ super.onDestroy();
+ }
+
+ @Override
+ public void onDetach() {
+ adapter.fragment0.onDetach();
+ adapter.fragment1.onDetach();
+ super.onDetach();
+ }
+
+ public InventoryFragment() {
+ super("InventoryFragment");
+ }
+}
+
+
+
+package com.csl.cs710ademoapp.fragments;
+
+import static com.csl.cslibrary4a.RfidReader.TagType.TAG_ASYGN;
+import static com.csl.cslibrary4a.RfidReader.TagType.TAG_CTESIUS;
+
+import android.content.Intent;
+import android.os.AsyncTask;
+import android.os.Bundle;
+import android.util.Log;
+import android.view.LayoutInflater;
+import android.view.MenuItem;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.AbsListView;
+import android.widget.AdapterView;
+import android.widget.ArrayAdapter;
+import android.widget.Button;
+import android.widget.CheckBox;
+import android.widget.EditText;
+import android.widget.LinearLayout;
+import android.widget.ListView;
+import android.widget.Spinner;
+import android.widget.TextView;
+import android.widget.Toast;
+
+import androidx.appcompat.app.ActionBar;
+import androidx.appcompat.app.AppCompatActivity;
+
+import com.csl.cs710ademoapp.CustomPopupWindow;
+import com.csl.cs710ademoapp.GenericTextWatcher;
+import com.csl.cs710ademoapp.InventoryRfidTask;
+import com.csl.cs710ademoapp.MainActivity;
+import com.csl.cs710ademoapp.R;
+import com.csl.cs710ademoapp.SaveList2ExternalTask;
+import com.csl.cs710ademoapp.adapters.ReaderListAdapter;
+import com.csl.cslibrary4a.NotificationConnector;
+import com.csl.cslibrary4a.ReaderDevice;
+import com.csl.cslibrary4a.RfidReader;
+import com.csl.cslibrary4a.RfidReaderChipData;
+
+import java.util.Collections;
+import java.util.Comparator;
+
+public class InventoryRfidiMultiFragment extends CommonFragment {
+ final private boolean bAdd2End = false;
+ private boolean bMultiBank = false, bMultiBankInventory = false, bctesiusInventory = false;
+ private RfidReader.TagType tagType;
+ private String mDid = null;
+ int vibrateTimeBackup = 0;
+
+ private CheckBox checkBoxDupElim, checkBoxFilterByTid, checkBoxFilterByEpc, checkBoxFilterByProtect;
+ private EditText editTextProtectPassword;
+ private Spinner spinnerBank1, spinnerBank2;
+ private ListView rfidListView;
+ private TextView rfidEmptyView;
+ private TextView rfidRunTime, rfidVoltageLevel;
+ private TextView rfidYieldView;
+ private TextView rfidRateView;
+ private Button button;
+
+ private ReaderListAdapter readerListAdapter;
+ private InventoryRfidTask inventoryRfidTask;
+
+ void clearTagsList() {
+ MainActivity.csLibrary4A.appendToLog("InventoryRfidMultiFragment: NOT onOptionsItemSelected: clearTagsList");
+ MainActivity.csLibrary4A.appendToLog("runningInventoryRfidTask = " + MainActivity.sharedObjects.runningInventoryRfidTask + ", readerListAdapter" + (readerListAdapter != null ? " tagCount = " + String.valueOf(readerListAdapter.getCount()) : " = NULL"));
+ if (MainActivity.sharedObjects.runningInventoryRfidTask) return;
+ rfidYieldView.setText("");
+ rfidRateView.setText("");
+ MainActivity.tagSelected = null;
+ MainActivity.sharedObjects.tagsList.clear();
+ MainActivity.sharedObjects.tagsIndexList.clear();
+ readerListAdapter.notifyDataSetChanged();
+ MainActivity.mLogView.setText("");
+ }
+ void sortTagsList() {
+ if (MainActivity.sharedObjects.runningInventoryRfidTask) return;
+ Collections.sort(MainActivity.sharedObjects.tagsList);
+ readerListAdapter.notifyDataSetChanged();
+ }
+ void sortTagsListByRssi() {
+ if (MainActivity.sharedObjects.runningInventoryRfidTask) return;
+ Collections.sort(MainActivity.sharedObjects.tagsList, new Comparator() {
+ @Override
+ public int compare(ReaderDevice deviceTag, ReaderDevice t1) {
+ if (deviceTag.getRssi() == t1.getRssi()) return 0;
+ else if (deviceTag.getRssi() < t1.getRssi()) return 1;
+ else return -1;
+ }
+ });
+ readerListAdapter.notifyDataSetChanged();
+ }
+ void saveTagsList() {
+ if (MainActivity.sharedObjects.runningInventoryRfidTask) return;
+ SaveList2ExternalTask saveExternalTask = new SaveList2ExternalTask(MainActivity.sharedObjects.tagsList);
+ saveExternalTask.execute();
+ }
+ void shareTagsList() {
+ SaveList2ExternalTask saveExternalTask = new SaveList2ExternalTask(MainActivity.sharedObjects.tagsList);
+ String stringOutput = saveExternalTask.createStrEpcList();
+
+ Intent sendIntent = new Intent();
+ sendIntent.setAction(Intent.ACTION_SEND);
+ sendIntent.putExtra(Intent.EXTRA_TEXT, stringOutput);
+ sendIntent.setType("text/plain");
+ startActivity(Intent.createChooser(sendIntent, "Sharing to"));
+ }
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ super.onCreateView(inflater, container, savedInstanceState, bMultiBankInventory | bctesiusInventory);
+ return inflater.inflate(R.layout.fragment_inventory_rfid_multi, container, false);
+ }
+
+ @Override
+ public boolean onOptionsItemSelected(MenuItem item) {
+ MainActivity.csLibrary4A.appendToLog("InventoryRfidMultiFragment: onOptionsItemSelected");
+ if (item.getItemId() == R.id.menuAction_clear) {
+ clearTagsList();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_sortRssi) {
+ sortTagsListByRssi();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_sort) {
+ sortTagsList();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_save) {
+ saveTagsList();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_share) {
+ shareTagsList();
+ return true;
+ } else return super.onOptionsItemSelected(item);
+ }
+
+ @Override
+ public void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ if (getArguments() != null) {
+ bMultiBank = getArguments().getBoolean("bMultiBank");
+ mDid = getArguments().getString("mDid");
+ try {
+ int iValue = getArguments().getInt("enumTagType");
+ MainActivity.csLibrary4A.appendToLog("onCreate: enumTagType iValue = " + iValue);
+ tagType = RfidReader.TagType.values()[iValue];
+ MainActivity.csLibrary4A.appendToLog("onCreate: enumTagType = " + tagType.toString());
+ } catch (Exception e) { }
+ if (bMultiBank && mDid == null) {
+ bMultiBankInventory = true;
+ } else if (bMultiBank && mDid != null) {
+ if (mDid.matches("E2003")
+ || mDid.matches("E200B0")
+ || (tagType == TAG_CTESIUS /*mDid.matches("E203510"*/)
+ || (tagType == TAG_ASYGN /*mDid.matches("E283A")*/)) {
+ bctesiusInventory = true;
+ }
+ }
+ }
+ }
+
+ @Override
+ public void onActivityCreated(Bundle savedInstanceState) {
+ super.onActivityCreated(savedInstanceState);
+
+ MainActivity.selectFor = -1;
+ if (bMultiBankInventory | bctesiusInventory) {
+ ActionBar actionBar;
+ actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
+ actionBar.setIcon(R.drawable.dl_inv);
+ if (bMultiBankInventory) actionBar.setTitle(R.string.title_activity_inventoryRfidMulti);
+ else if (bctesiusInventory) {
+ if (mDid.matches("E2003")) actionBar.setTitle("Alien");
+ else if (mDid.matches("E200B0")) actionBar.setTitle(R.string.title_activity_bap);
+ else if (tagType == TAG_CTESIUS /*mDid.matches("E203510")*/) actionBar.setTitle(R.string.title_activity_ctesisu);
+ else if (tagType == TAG_ASYGN /*mDid.matches("E283A")*/) actionBar.setTitle("AS321x");
+ }
+ }
+ if (bMultiBankInventory) {
+ LinearLayout linearLayout = (LinearLayout) getActivity().findViewById(R.id.inventoryMultibankSetting);
+ linearLayout.setVisibility(View.VISIBLE);
+ checkBoxDupElim = (CheckBox) getActivity().findViewById(R.id.accessInventoryDupElim);
+ checkBoxDupElim.setVisibility(View.VISIBLE);
+ checkBoxDupElim.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View view) {
+ if (checkBoxDupElim.isChecked()) readerListAdapter.setSelectDupElim(true);
+ else readerListAdapter.setSelectDupElim(false);
+ }
+ });
+ }
+
+ checkBoxFilterByTid = (CheckBox) getActivity().findViewById(R.id.accessInventoryFilterByTid);
+ MainActivity.csLibrary4A.appendToLog("InventoryRfidMultiFragment.onActivityCreated: mDid = " + mDid + ", MainActivity.mDid = " + MainActivity.mDid);
+ if (mDid != null) {
+ if (mDid.indexOf("E2827001") == 0) {
+ checkBoxFilterByTid.setVisibility(View.VISIBLE);
+ //checkBoxFilterByTid.setText("filter FM13DT160 only");
+ }
+ } else if (bMultiBankInventory == false) {
+ checkBoxFilterByEpc = (CheckBox) getActivity().findViewById(R.id.accessInventoryFilterByEpc);
+ checkBoxFilterByEpc.setVisibility(View.VISIBLE);
+ }
+
+ checkBoxFilterByProtect = (CheckBox) getActivity().findViewById(R.id.accessInventoryFilterByProtect);
+ editTextProtectPassword = (EditText) getActivity().findViewById(R.id.accessInventoryProtectPassword);
+ editTextProtectPassword.addTextChangedListener(new GenericTextWatcher(editTextProtectPassword, 8));
+ editTextProtectPassword.setText("00000000");
+
+ ArrayAdapter lockAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.memoryBank_options, R.layout.custom_spinner_layout);
+ lockAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+
+ spinnerBank1 = (Spinner) getActivity().findViewById(R.id.accessInventoryBank1);
+ spinnerBank1.setAdapter(lockAdapter); spinnerBank1.setSelection(2);
+ spinnerBank2 = (Spinner) getActivity().findViewById(R.id.accessInventoryBank2);
+ spinnerBank2.setAdapter(lockAdapter); spinnerBank2.setSelection(3);
+
+ rfidListView = (ListView) getActivity().findViewById(R.id.inventoryRfidList1);
+ rfidEmptyView = (TextView) getActivity().findViewById(R.id.inventoryRfidEmpty1);
+ rfidListView.setEmptyView(rfidEmptyView);
+ boolean bSelect4detail = true;
+ if (bMultiBankInventory) bSelect4detail = false;
+ boolean needDupElim = true;
+
+ boolean need4Extra1 = MainActivity.csLibrary4A.getPortNumber() > 1 ? true : false;
+ boolean need4Extra2 = (mDid != null ? true : false);
+
+ readerListAdapter = new ReaderListAdapter(getActivity(), R.layout.readers_list_item, MainActivity.sharedObjects.tagsList, bSelect4detail, true, needDupElim, need4Extra1, need4Extra2);
+ rfidListView.setAdapter(readerListAdapter);
+ rfidListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
+ rfidListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
+ @Override
+ public void onItemClick(AdapterView> parent, View view, int position, long id) {
+ ReaderDevice readerDevice = readerListAdapter.getItem(position);
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("Position = " + position);
+ if (readerDevice.getSelected()) {
+ readerDevice.setSelected(false);
+ } else {
+ readerDevice.setSelected(true);
+ String strPopup = readerDevice.getUpcSerial();
+ MainActivity.csLibrary4A.appendToLog("strPopup = " + (strPopup == null ? "null" : strPopup));
+ if (strPopup != null && strPopup.trim().length() != 0) {
+ strPopup = MainActivity.csLibrary4A.getUpcSerialDetail(strPopup);
+ CustomPopupWindow epcSerialPopupWindow = new CustomPopupWindow(MainActivity.mContext);
+ epcSerialPopupWindow.popupStart(strPopup, false);
+ }
+ }
+ MainActivity.sharedObjects.tagsList.set(position, readerDevice);
+ if (readerDevice.getSelected()) MainActivity.tagSelected = readerDevice;
+ else MainActivity.tagSelected = null;
+ for (int i = 0; i < MainActivity.sharedObjects.tagsList.size(); i++) {
+ if (i != position) {
+ ReaderDevice readerDevice1 = MainActivity.sharedObjects.tagsList.get(i);
+ if (readerDevice1.getSelected()) {
+ readerDevice1.setSelected(false);
+ MainActivity.sharedObjects.tagsList.set(i, readerDevice1);
+ }
+ }
+ }
+ readerListAdapter.notifyDataSetChanged();
+ }
+ });
+
+ rfidRunTime = (TextView) getActivity().findViewById(R.id.inventoryRfidRunTime1);
+ rfidVoltageLevel = (TextView) getActivity().findViewById(R.id.inventoryRfidVoltageLevel1);
+ TextView rfidFilterOn = (TextView) getActivity().findViewById(R.id.inventoryRfidFilterOn1);
+ if (mDid != null || (MainActivity.csLibrary4A.getSelectEnable() == false && MainActivity.csLibrary4A.getInvMatchEnable() == false && MainActivity.csLibrary4A.getRssiFilterEnable() == false))
+ rfidFilterOn.setVisibility(View.INVISIBLE);
+
+ rfidYieldView = (TextView) getActivity().findViewById(R.id.inventoryRfidYield1);
+ rfidRateView = (TextView) getActivity().findViewById(R.id.inventoryRfidRate1);
+ button = (Button) getActivity().findViewById(R.id.inventoryRfidButton1);
+ button.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ startStopHandler(false);
+ }
+ });
+
+ vibrateTimeBackup = MainActivity.csLibrary4A.getVibrateTime();
+ final Button buttonT1 = (Button) getActivity().findViewById(R.id.inventoryRfidButtonT1);
+ buttonT1.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ String buttonText = buttonT1.getText().toString().trim();
+ if (buttonText.toUpperCase().matches("BUZ")) {
+ MainActivity.csLibrary4A.appendToLog("setVibrateOn G 1");
+ MainActivity.csLibrary4A.setVibrateTime(0); MainActivity.csLibrary4A.setVibrateOn(1);
+ buttonT1.setText("STOP");
+ }
+ else {
+ MainActivity.csLibrary4A.appendToLog("setVibrateOn H 0");
+ MainActivity.csLibrary4A.setVibrateOn(0);
+ buttonT1.setText("BUZ");
+ }
+ }
+ });
+ }
+
+ @Override
+ public void onResume() {
+ super.onResume();
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("InventoryRfidiMultiFragment().onResume(): userVisibleHint = " + userVisibleHint);
+ if (userVisibleHint) setNotificationListener();
+ }
+
+ @Override
+ public void onPause() {
+ MainActivity.csLibrary4A.setNotificationListener(null);
+ super.onPause();
+ }
+
+ @Override
+ public void onDestroy() {
+ mHandler.removeCallbacks(runnableCheckReady);
+ if (MainActivity.csLibrary4A != null) MainActivity.csLibrary4A.setNotificationListener(null);
+ if (inventoryRfidTask != null) {
+ inventoryRfidTask.taskCancelReason = InventoryRfidTask.TaskCancelRReason.DESTORY;
+ if (MainActivity.csLibrary4A != null) {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("InventoryRfidiMultiFragment().onDestory(): VALID inventoryRfidTask");
+ MainActivity.csLibrary4A.abortOperation(); //added in case inventoryRiidTask is removed
+ }
+ }
+ if (MainActivity.csLibrary4A != null) {
+ MainActivity.csLibrary4A.setSameCheck(true);
+ MainActivity.csLibrary4A.setInvBrandId(false);
+ resetSelectData();
+ MainActivity.csLibrary4A.setVibrateTime(vibrateTimeBackup);
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("InventoryRfidiMultiFragment().onDestory(): onDestory()");
+ }
+ super.onDestroy();
+ }
+
+ boolean userVisibleHint = true;
+ @Override
+ public void setUserVisibleHint(boolean isVisibleToUser) {
+ super.setUserVisibleHint(isVisibleToUser);
+ if(getUserVisibleHint()) {
+ userVisibleHint = true;
+ MainActivity.csLibrary4A.appendToLog("InventoryRfidiMultiFragment is now VISIBLE");
+ MainActivity.csLibrary4A.appendToLog("11 mDid = " + mDid + ", MainActivity.mDid = " + MainActivity.mDid);
+ if (MainActivity.mDid != null && MainActivity.mDid.indexOf("E28011") == 0) {
+ int iValue = Integer.valueOf(MainActivity.mDid.substring(6, 8), 16);
+ iValue &= 0x0F;
+ MainActivity.csLibrary4A.appendToLog(String.format("iValue = 0x%X", iValue));
+ if (iValue > 0 && iValue < 6) {
+ checkBoxFilterByProtect.setVisibility(View.VISIBLE);
+ editTextProtectPassword.setVisibility(View.VISIBLE);
+ } else {
+ checkBoxFilterByProtect.setVisibility(View.GONE); checkBoxFilterByProtect.setChecked(false);
+ editTextProtectPassword.setVisibility(View.GONE);
+ }
+ }
+ MainActivity.csLibrary4A.appendToLog("setNotificationListener in multibank inventory");
+ setNotificationListener();
+ } else {
+ userVisibleHint = false;
+ MainActivity.csLibrary4A.appendToLog("InventoryRfidiMultiFragment is now INVISIBLE");
+ MainActivity.csLibrary4A.appendToLog("setNotificationListener null in multibank inventory");
+ MainActivity.csLibrary4A.setNotificationListener(null);
+ if (inventoryRfidTask != null) {
+ inventoryRfidTask.taskCancelReason = InventoryRfidTask.TaskCancelRReason.STOP;
+ }
+ }
+ }
+
+ public static InventoryRfidiMultiFragment newInstance(boolean bMultiBank, RfidReader.TagType tagType, String mDid) {
+ InventoryRfidiMultiFragment myFragment = new InventoryRfidiMultiFragment();
+
+ Bundle args = new Bundle();
+ MainActivity.csLibrary4A.appendToLog("newInstance: enumTagType = " + (tagType == null ? "null" : tagType.toString()));
+ if (tagType != null) args.putInt("enumTagType", tagType.ordinal());
+ args.putBoolean("bMultiBank", bMultiBank);
+ args.putString("mDid", mDid);
+ myFragment.setArguments(args);
+
+ return myFragment;
+ }
+ public InventoryRfidiMultiFragment() {
+ super("InventoryRfidiMultiFragment");
+ }
+
+ void setNotificationListener() {
+ MainActivity.csLibrary4A.appendToLog("setNotificationListener A in multibank inventory");
+ MainActivity.csLibrary4A.setNotificationListener(new NotificationConnector.NotificationListener() {
+ @Override
+ public void onChange() {
+ MainActivity.csLibrary4A.appendToLog("setNotificationListener TRIGGER key is pressed in multibank inventory.");
+ startStopHandler(true);
+ }
+ });
+ }
+
+ boolean needResetData = false;
+ void resetSelectData() {
+ MainActivity.csLibrary4A.appendToLog("InventoryRfidMultiFragment.resetSelectData: mDid = " + mDid + ", MainActivity.mDid = " + MainActivity.mDid);
+ if (MainActivity.mDid != null && MainActivity.mDid.indexOf("E282405") == 0) { }
+ else MainActivity.csLibrary4A.restoreAfterTagSelect();
+ if (needResetData) {
+ MainActivity.csLibrary4A.setTagRead(0);
+ MainActivity.csLibrary4A.setAccessBank(1);
+ MainActivity.csLibrary4A.setAccessOffset(0);
+ MainActivity.csLibrary4A.setAccessCount(0);
+ needResetData = false;
+ }
+ if (mDid != null && tagType == TAG_CTESIUS /*mDid.matches("E203510")*/) MainActivity.csLibrary4A.setSelectCriteriaDisable(1);
+ }
+ void startStopHandler(boolean buttonTrigger) {
+ MainActivity.csLibrary4A.appendToLog("0 buttonTrigger is " + buttonTrigger);
+ if (buttonTrigger) MainActivity.csLibrary4A.appendToLog("BARTRIGGER: getTriggerButtonStatus = " + MainActivity.csLibrary4A.getTriggerButtonStatus());
+ if (MainActivity.sharedObjects.runningInventoryBarcodeTask) {
+ Toast.makeText(MainActivity.mContext, "Running barcode inventory", Toast.LENGTH_SHORT).show();
+ return;
+ }
+ boolean started = false;
+ if (inventoryRfidTask != null) if (inventoryRfidTask.getStatus() == AsyncTask.Status.RUNNING) started = true;
+ if (buttonTrigger && ((started && MainActivity.csLibrary4A.getTriggerButtonStatus()) || (started == false && MainActivity.csLibrary4A.getTriggerButtonStatus() == false))) {
+ MainActivity.csLibrary4A.appendToLog("BARTRIGGER: trigger ignore");
+ return;
+ }
+ if (started == false) {
+ if (MainActivity.csLibrary4A.isBleConnected() == false) {
+ Toast.makeText(MainActivity.mContext, R.string.toast_ble_not_connected, Toast.LENGTH_SHORT).show();
+ return;
+ } else if (MainActivity.csLibrary4A.isRfidFailure()) {
+ Toast.makeText(MainActivity.mContext, "Rfid is disabled", Toast.LENGTH_SHORT).show();
+ return;
+ } else if (MainActivity.csLibrary4A.mrfidToWriteSize() != 0) {
+ //Toast.makeText(MainActivity.mContext, R.string.toast_not_ready, Toast.LENGTH_SHORT).show();
+ mHandler.post(runnableCheckReady);
+ return;
+ }
+ if (bAdd2End) rfidListView.setTranscriptMode(AbsListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
+ else rfidListView.setSelection(0);
+ startInventoryTask();
+ } else if (MainActivity.csLibrary4A.mrfidToWriteSize() == 0) {
+ if (bAdd2End) rfidListView.setTranscriptMode(AbsListView.TRANSCRIPT_MODE_NORMAL);
+ if (buttonTrigger) inventoryRfidTask.taskCancelReason = InventoryRfidTask.TaskCancelRReason.BUTTON_RELEASE;
+ else inventoryRfidTask.taskCancelReason = InventoryRfidTask.TaskCancelRReason.STOP;
+ MainActivity.csLibrary4A.appendToLogView("CANCELLING: StartStopHandler generates taskCancelReason = " + inventoryRfidTask.taskCancelReason.toString());
+ } else MainActivity.csLibrary4A.appendToLog("BtData. Stop when still writing !!!");
+ }
+ void startInventoryTask() {
+ MainActivity.csLibrary4A.appendToLog("startInventoryTask");
+ //RfidReader.ExtraBankData extraBankData = new RfidReader.ExtraBankData();
+ String mDid = this.mDid;
+
+ MainActivity.csLibrary4A.appendToLog("Rin: mDid = " + (mDid == null ? "null" : mDid) + ", MainActivity.mDid = " + MainActivity.mDid + ", bMultiBankInventory = " + bMultiBankInventory);
+ if (mDid != null && MainActivity.mDid != null) {
+ if (MainActivity.mDid.indexOf("E280B12") != 0) mDid = MainActivity.mDid;
+ }
+
+ RfidReader.ExtraBankData extraBankData = new RfidReader.ExtraBankData();
+ if (mDid != null) extraBankData.setExtraBankData(MainActivity.tagType, mDid);
+ else if (bMultiBank) {
+ CheckBox checkBox = (CheckBox) getActivity().findViewById(R.id.accessInventoryBankTitle1);
+ int extra1Bank = 0, extra2Bank = 0;
+ int extra1Count, extra2Count;
+ int extra1Offset = 0, extra2Offset = 0;
+ if (checkBox.isChecked()) {
+ extra1Bank = spinnerBank1.getSelectedItemPosition();
+ EditText editText = (EditText) getActivity().findViewById(R.id.accessInventoryOffset1);
+ extra1Offset = Integer.valueOf(editText.getText().toString());
+ editText = (EditText) getActivity().findViewById(R.id.accessInventoryLength1);
+ extra1Count = Integer.valueOf(editText.getText().toString());
+ } else extra1Count = 0;
+ checkBox = (CheckBox) getActivity().findViewById(R.id.accessInventoryBankTitle2);
+ if (checkBox.isChecked()) {
+ extra2Bank = spinnerBank2.getSelectedItemPosition();
+ EditText editText = (EditText) getActivity().findViewById(R.id.accessInventoryOffset2);
+ extra2Offset = Integer.valueOf(editText.getText().toString());
+ editText = (EditText) getActivity().findViewById(R.id.accessInventoryLength2);
+ extra2Count = Integer.valueOf(editText.getText().toString());
+ } else extra2Count = 0;
+ extraBankData.setExtraBankData(extra1Bank, extra1Count, extra1Offset, extra2Bank, extra2Count, extra2Offset);
+ }
+
+ if (mDid != null) {
+ MainActivity.csLibrary4A.appendToLog("mDid is valid as " + mDid);
+ if (MainActivity.mDid != null && mDid.length() == 0) mDid = MainActivity.mDid;
+ MainActivity.csLibrary4A.appendToLog("new mDid is " + mDid);
+
+ MainActivity.csLibrary4A.appendToLog("mDid = " + mDid);
+ if (tagType == TAG_CTESIUS /*mDid.matches("E203510")*/) {
+ if (MainActivity.csLibrary4A.get98XX() == 2) MainActivity.csLibrary4A.setCurrentLinkProfile(1); //set profile 302
+ } else if (tagType == TAG_ASYGN /*mDid.matches("E283A")*/) {
+ if (MainActivity.csLibrary4A.get98XX() == 2) MainActivity.csLibrary4A.setCurrentLinkProfile(9); //set profile 244
+ } else if (mDid.matches("E282405")) {
+ if (MainActivity.csLibrary4A.getRetryCount() < 2) MainActivity.csLibrary4A.setRetryCount(2);
+ }
+ boolean bNeedSelectedTagByTID = true;
+ if (mDid.indexOf("E2806894") == 0) {
+ Log.i(TAG, "HelloK: Find E2806894 with MainActivity.mDid = " + MainActivity.mDid + ", mDid = " + mDid);
+ if (mDid.matches("E2806894A")) {
+ Log.i(TAG, "HelloK: Find E2806894A");
+ MainActivity.csLibrary4A.setInvBrandId(false);
+ } else if (mDid.matches("E2806894B")) {
+ Log.i(TAG, "HelloK: Find E2806894B");
+ MainActivity.csLibrary4A.setInvBrandId(false);
+ if (true) bNeedSelectedTagByTID = false;
+ } else if (mDid.matches("E2806894C") || mDid.matches("E2806894d")) {
+ Log.i(TAG, "HelloK: Find " + MainActivity.mDid);
+ MainActivity.csLibrary4A.setInvBrandId(true);
+ if (true) bNeedSelectedTagByTID = false;
+ }
+ }
+ MainActivity.csLibrary4A.setOtherInventoryData(tagType, mDid);
+ int iValue123 = MainActivity.csLibrary4A.setSelectData(tagType, mDid,
+ bNeedSelectedTagByTID && checkBoxFilterByTid.isChecked(),
+ (checkBoxFilterByProtect.isChecked() ? editTextProtectPassword.getText().toString(): null),
+ MainActivity.selectFor, MainActivity.selectHold);
+ if (mDid.indexOf("E2806894") == 0) {
+ mDid = "E2806894";
+ }
+ if (iValue123 > 0) MainActivity.selectFor = iValue123;
+ }
+
+ MainActivity.csLibrary4A.appendToLog("bSgtinOnly: bMultiBank is " + bMultiBank + ", checkBoxFilterByEpc is " + (checkBoxFilterByEpc == null ? "null" : checkBoxFilterByEpc.isChecked()));
+ if (bMultiBank == false) {
+ if (checkBoxFilterByEpc.isChecked()) {
+ MainActivity.csLibrary4A.appendToLog("bSgtinOnly: clearTagList");
+ clearTagsList();
+ }
+ MainActivity.csLibrary4A.restoreAfterTagSelect();
+ inventoryRfidTask = new InventoryRfidTask(getContext(), -1, -1, 0, 0, 0, 0,
+ false, MainActivity.csLibrary4A.getInventoryBeep(),
+ MainActivity.sharedObjects.tagsList, readerListAdapter, null, RfidReader.TagType.TAG_NULL, null,
+ rfidRunTime, null, rfidVoltageLevel, rfidYieldView, button, rfidRateView);
+ inventoryRfidTask.bSgtinOnly = checkBoxFilterByEpc.isChecked();
+ MainActivity.csLibrary4A.appendToLog("Debug_Compact 1: InventoryRfidMultiFragment.startInventoryTask");
+ MainActivity.csLibrary4A.startOperation(RfidReaderChipData.OperationTypes.TAG_INVENTORY_COMPACT);
+ } else {
+ boolean inventoryUcode8_bc = mDid != null && mDid.matches("E2806894") && MainActivity.mDid != null && (MainActivity.mDid.matches("E2806894B") || MainActivity.mDid.matches("E2806894C"));
+ if ((extraBankData.extra1Bank != -1 && extraBankData.extra1Count != 0) || (extraBankData.extra2Bank != -1 && extraBankData.extra2Count != 0)) {
+ extraBankData.adjustExtraBank1();
+ MainActivity.csLibrary4A.appendToLog("HelloK: mDid = " + mDid + ", MainActivity.mDid = " + MainActivity.mDid + " with extra1Bank = " + extraBankData.extra1Bank + "," + extraBankData.extra1Offset + "," + extraBankData.extra1Count + ", extra2Bank = " + extraBankData.extra2Bank + "," + extraBankData.extra2Offset + "," + extraBankData.extra2Count);
+ if (mDid != null) MainActivity.csLibrary4A.setResReadNoReply(mDid.matches("E281D"));
+ if (inventoryUcode8_bc == false) {
+ MainActivity.csLibrary4A.appendToLog("BleStreamOut: Set Multibank");
+ MainActivity.csLibrary4A.setTagRead(extraBankData.extra2Count != 0 && extraBankData.extra2Count != 0 ? 2 : 1);
+ MainActivity.csLibrary4A.setAccessBank(extraBankData.extra1Bank, extraBankData.extra2Bank);
+ MainActivity.csLibrary4A.setAccessOffset(extraBankData.extra1Offset, extraBankData.extra2Offset);
+ MainActivity.csLibrary4A.setAccessCount(extraBankData.extra1Count, extraBankData.extra2Count);
+ needResetData = true;
+ } else if (needResetData) {
+ MainActivity.csLibrary4A.setTagRead(0);
+ MainActivity.csLibrary4A.setAccessBank(1);
+ MainActivity.csLibrary4A.setAccessOffset(0);
+ MainActivity.csLibrary4A.setAccessCount(0);
+ needResetData = false;
+ }
+ } else resetSelectData();
+ MainActivity.csLibrary4A.appendToLog("startInventoryTask: going to startOperation with extra1Bank = " + extraBankData.extra1Bank + "," + extraBankData.extra1Offset + "," + extraBankData.extra1Count + ", extra2Bank = " + extraBankData.extra2Bank + "," + extraBankData.extra2Offset + "," + extraBankData.extra2Count);
+ inventoryRfidTask = new InventoryRfidTask(getContext(), extraBankData.extra1Bank, extraBankData.extra2Bank, extraBankData.extra1Count, extraBankData.extra2Count, extraBankData.extra1Offset, extraBankData.extra2Offset,
+ false, MainActivity.csLibrary4A.getInventoryBeep(),
+ MainActivity.sharedObjects.tagsList, readerListAdapter, null, tagType, mDid,
+ rfidRunTime, null, rfidVoltageLevel, rfidYieldView, button, rfidRateView);
+ inventoryRfidTask.bProtectOnly = checkBoxFilterByProtect.isChecked();
+ if (inventoryUcode8_bc) {
+ MainActivity.csLibrary4A.appendToLog("Debug_Compact 2: InventoryRfidMultiFragment.startInventoryTask");
+ MainActivity.csLibrary4A.startOperation(RfidReaderChipData.OperationTypes.TAG_INVENTORY_COMPACT);
+ } else {
+ MainActivity.csLibrary4A.appendToLog("Debug_Compact 3: InventoryRfidMultiFragment.startInventoryTask");
+ MainActivity.csLibrary4A.startOperation(RfidReaderChipData.OperationTypes.TAG_INVENTORY);
+ }
+ }
+ inventoryRfidTask.execute();
+ }
+
+ private final Runnable runnableCheckReady = new Runnable() {
+ @Override
+ public void run() {
+ if (MainActivity.csLibrary4A.mrfidToWriteSize() != 0) {
+ button.setEnabled(false);
+ button.setText("Please wait");
+ MainActivity.csLibrary4A.setNotificationListener(null);
+ mHandler.postDelayed(runnableCheckReady, 500);
+ } else {
+ button.setText("Start");
+ button.setEnabled(true);
+ if (userVisibleHint) setNotificationListener();
+ }
+ }
+ };
+}
+
+
+
+package com.csl.cs710ademoapp.fragments;
+
+import static com.csl.cs710ademoapp.MainActivity.tagSelected;
+
+import android.app.Activity;
+import android.os.AsyncTask;
+import android.os.Bundle;
+import androidx.appcompat.app.AppCompatActivity;
+import android.text.Editable;
+import android.text.TextWatcher;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.AdapterView;
+import android.widget.ArrayAdapter;
+import android.widget.Button;
+import android.widget.CheckBox;
+import android.widget.EditText;
+import android.widget.ProgressBar;
+import android.widget.SeekBar;
+import android.widget.Spinner;
+import android.widget.TableRow;
+import android.widget.TextView;
+import android.widget.Toast;
+
+import com.csl.cs710ademoapp.CustomMediaPlayer;
+import com.csl.cs710ademoapp.InventoryRfidTask;
+import com.csl.cs710ademoapp.SelectTag;
+import com.csl.cs710ademoapp.MainActivity;
+import com.csl.cs710ademoapp.R;
+import com.csl.cslibrary4a.NotificationConnector;
+import com.csl.cslibrary4a.ReaderDevice;
+import com.csl.cslibrary4a.RfidReader;
+import com.csl.cslibrary4a.RfidReaderChipData;
+
+public class InventoryRfidSearchFragment extends CommonFragment {
+ double dBuV_dBm_constant = MainActivity.csLibrary4A.dBuV_dBm_constant;
+ final int labelMin = -90;
+ final int labelMax = -10;
+
+ SelectTag selectTag;
+ private ProgressBar geigerProgress;
+ private CheckBox checkBoxGeigerTone;
+ private SeekBar seekGeiger;
+ private Spinner memoryBankSpinner;
+ private EditText editTextRWSelectOffset, editTextGeigerAntennaPower;
+ private TextView geigerThresholdView;
+ private TextView geigerTagRssiView;
+ private TextView geigerTagGotView;
+ private TextView geigerRunTime, geigerVoltageLevelView;
+ private TextView rfidYieldView;
+ private TextView rfidRateView;
+ private Button button;
+
+ private boolean started = false;
+ int thresholdValue = 0;
+
+ private InventoryRfidTask geigerSearchTask;
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ super.onCreateView(inflater, container, savedInstanceState, true);
+ return inflater.inflate(R.layout.fragment_geiger_search, container, false);
+ }
+
+ @Override
+ public void onActivityCreated(Bundle savedInstanceState) {
+ super.onActivityCreated(savedInstanceState);
+
+ if (!isTabbed) {
+ androidx.appcompat.app.ActionBar actionBar;
+ actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
+ actionBar.setIcon(R.drawable.dl_loc);
+ actionBar.setTitle(R.string.title_activity_geiger);
+ }
+
+ selectTag = new SelectTag((Activity)getActivity(), 0);
+ TableRow tableRowProgressLabel;
+ TextView textViewProgressLabelMin = (TextView) getActivity().findViewById(R.id.geigerProgressLabelMin);
+ TextView textViewProgressLabelMid = (TextView) getActivity().findViewById(R.id.geigerProgressLabelMid);
+ TextView textViewProgressLabelMax = (TextView) getActivity().findViewById(R.id.geigerProgressLabelMax);
+ textViewProgressLabelMin.setText(String.format("%.0f", MainActivity.csLibrary4A.getRssiDisplaySetting() != 0 ? labelMin : labelMin + dBuV_dBm_constant));
+ textViewProgressLabelMid.setText(String.format("%.0f", MainActivity.csLibrary4A.getRssiDisplaySetting() != 0 ? labelMin + (labelMax - labelMin) / 2 : labelMin + (labelMax - labelMin) / 2 + dBuV_dBm_constant));
+ textViewProgressLabelMax.setText(String.format("%.0f", MainActivity.csLibrary4A.getRssiDisplaySetting() != 0 ? labelMax : labelMax + dBuV_dBm_constant));
+
+ geigerProgress = (ProgressBar) getActivity().findViewById(R.id.geigerProgress);
+ checkBoxGeigerTone = (CheckBox) getActivity().findViewById(R.id.geigerToneCheck);
+
+ seekGeiger = (SeekBar) getActivity().findViewById(R.id.geigerSeek);
+ seekGeiger.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
+ @Override
+ public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
+ if (seekBar == seekGeiger && fromUser == true) {
+ thresholdValue = progress;
+ geigerThresholdView.setText(String.format("%.2f", MainActivity.csLibrary4A.getRssiDisplaySetting() == 0 ? thresholdValue : thresholdValue - dBuV_dBm_constant));
+ }
+ }
+
+ @Override
+ public void onStartTrackingTouch(SeekBar seekBar) { }
+ @Override
+ public void onStopTrackingTouch(SeekBar seekBar) { }
+ });
+
+ memoryBankSpinner = (Spinner) getActivity().findViewById(R.id.selectMemoryBank);
+ ArrayAdapter memoryBankAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.read_memoryBank_options, R.layout.custom_spinner_layout);
+ memoryBankAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+ memoryBankSpinner.setAdapter(memoryBankAdapter);
+ memoryBankSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
+ @Override
+ public void onItemSelected(AdapterView> parent, View view, int position, long id) {
+ switch (position) {
+ case 0: //if EPC
+ if (tagSelected != null) selectTag.editTextTagID.setText(tagSelected.getAddress());
+ editTextRWSelectOffset.setText("32");
+ break;
+ case 1:
+ if (tagSelected != null) selectTag.editTextTagID.setText(tagSelected.getTid());
+ editTextRWSelectOffset.setText("0");
+ break;
+ case 2:
+ if (tagSelected != null) selectTag.editTextTagID.setText(tagSelected.getUser());
+ editTextRWSelectOffset.setText("0");
+ break;
+ default:
+ break;
+ }
+ }
+
+ @Override
+ public void onNothingSelected(AdapterView> parent) {
+
+ }
+ });
+
+ editTextRWSelectOffset = (EditText) getActivity().findViewById(R.id.selectMemoryOffset);
+
+ TableRow tableRowSelectPassword = (TableRow) getActivity().findViewById(R.id.selectPasswordRow);
+ tableRowSelectPassword.setVisibility(View.GONE);
+
+ editTextGeigerAntennaPower = (EditText) getActivity().findViewById(R.id.selectAntennaPower);
+ editTextGeigerAntennaPower.setText(String.valueOf(300));
+
+ geigerThresholdView = (TextView) getActivity().findViewById(R.id.geigerThreshold);
+ geigerTagRssiView = (TextView) getActivity().findViewById(R.id.geigerTagRssi);
+ geigerTagRssiView.addTextChangedListener(new TextWatcher() {
+ @Override
+ public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { }
+
+ @Override
+ public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { }
+
+ @Override
+ public void afterTextChanged(Editable editable) {
+ if (alertRssiUpdateTime < 0) return;
+ double rssi = Double.parseDouble(geigerTagRssiView.getText().toString());
+ if (MainActivity.csLibrary4A.getRssiDisplaySetting() != 0) rssi += dBuV_dBm_constant;
+
+ double progressPos = geigerProgress.getMax() * ( rssi - labelMin - dBuV_dBm_constant) / (labelMax - labelMin);
+ if (progressPos < 0) progressPos = 0;
+ if (progressPos > geigerProgress.getMax()) progressPos = geigerProgress.getMax();
+ geigerProgress.setProgress((int) (progressPos));
+
+ alertRssiUpdateTime = System.currentTimeMillis(); alertRssi = rssi;
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("afterTextChanged(): alerting = " + alerting + ", alertRssi = " + alertRssi);
+ if (rssi > thresholdValue && checkBoxGeigerTone.isChecked()) {
+ if (alerting == false) {
+ alerting = true;
+ mHandler.removeCallbacks(mAlertRunnable);
+ mHandler.post(mAlertRunnable);
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("afterTextChanged(): mAlertRunnable starts");
+ }
+ }
+ }
+ });
+ geigerRunTime = (TextView) getActivity().findViewById(R.id.geigerRunTime);
+ geigerTagGotView = (TextView) getActivity().findViewById(R.id.geigerTagGot);
+ geigerVoltageLevelView = (TextView) getActivity().findViewById(R.id.geigerVoltageLevel);
+ rfidYieldView = (TextView) getActivity().findViewById(R.id.geigerYield);
+ rfidRateView = (TextView) getActivity().findViewById(R.id.geigerRate);
+ button = (Button) getActivity().findViewById(R.id.geigerStart);
+ button.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ startStopHandler(false);
+ }
+ });
+
+ playerN = MainActivity.sharedObjects.playerL;
+ setupTagID();
+ }
+
+ @Override
+ public void onResume() {
+ super.onResume();
+ if (userVisibleHint) setNotificationListener();
+ }
+
+ @Override
+ public void onPause() {
+ MainActivity.csLibrary4A.setNotificationListener(null);
+ super.onPause();
+ }
+
+ @Override
+ public void onDestroy() {
+ MainActivity.csLibrary4A.setNotificationListener(null);
+ if (geigerSearchTask != null) {
+ geigerSearchTask.taskCancelReason = InventoryRfidTask.TaskCancelRReason.DESTORY;
+ }
+ MainActivity.csLibrary4A.restoreAfterTagSelect();
+ super.onDestroy();
+ }
+
+ boolean userVisibleHint = true;
+ @Override
+ public void setUserVisibleHint(boolean isVisibleToUser) {
+ super.setUserVisibleHint(isVisibleToUser);
+ if(getUserVisibleHint()) {
+ userVisibleHint = true;
+ MainActivity.csLibrary4A.appendToLog("InventoryRfidSearchFragment is now VISIBLE");
+ setupTagID();
+ MainActivity.csLibrary4A.appendToLog("setNotificationListener in search inventory");
+ setNotificationListener();
+ } else {
+ userVisibleHint = false;
+ MainActivity.csLibrary4A.appendToLog("InventoryRfidSearchFragment is now INVISIBLE");
+ MainActivity.csLibrary4A.appendToLog("setNotificationListener NULL in search inventory");
+ MainActivity.csLibrary4A.setNotificationListener(null);
+ }
+ }
+
+ boolean isTabbed = false;
+ public InventoryRfidSearchFragment(boolean isTabbed) {
+ super("InventoryRfidSearchFragment");
+ this.isTabbed = isTabbed;
+ }
+ void setupTagID() {
+ final ReaderDevice tagSelected = MainActivity.tagSelected;
+ if (tagSelected != null) {
+ if (tagSelected.getSelected() == true) {
+ if (tagSelected.getTid() != null) {
+ if (tagSelected.getTid().indexOf("E281D") == 0 || tagSelected.getTid().indexOf("E201E") == 0) {
+ memoryBankSpinner.setSelection(1);
+ }
+ }
+ switch (memoryBankSpinner.getSelectedItemPosition()) {
+ case 0:
+ selectTag.editTextTagID.setText(tagSelected.getAddress());
+ break;
+ case 1:
+ selectTag.editTextTagID.setText(tagSelected.getTid());
+ break;
+ case 2:
+ selectTag.editTextTagID.setText(tagSelected.getUser());
+ break;
+ }
+ }
+ }
+ }
+
+ double alertRssi; boolean alerting = false; long alertRssiUpdateTime;
+ CustomMediaPlayer playerN;
+ private final Runnable mAlertRunnable = new Runnable() {
+ @Override
+ public void run() {
+ boolean alerting1 = true;
+ final int toneLength = 50;
+
+ mHandler.removeCallbacks(mAlertRunnable);
+
+ if (alertRssi < 20 || alertRssi < thresholdValue || checkBoxGeigerTone.isChecked() == false || alertRssiUpdateTime < 0 || System.currentTimeMillis() - alertRssiUpdateTime > 200) alerting1 = false;
+ if (alerting1 == false) {
+ playerN.pause(); alerting = false;
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("mAlertRunnable(): ENDS with new alerting1 = " + alerting1 + ", alertRssi = " + alertRssi);
+ } else if (playerN.isPlaying() == false) {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("mAlertRunnable(): TONE starts");
+ mHandler.postDelayed(mAlertRunnable, toneLength);
+ playerN.start();
+ } else {
+ int tonePause = 0;
+ if (alertRssi >= 60) tonePause = toneLength;
+ else if (alertRssi >= 50) tonePause = 250 - toneLength;
+ else if (alertRssi >= 40) tonePause = 500 - toneLength;
+ else if (alertRssi >= 30) tonePause = 1000 - toneLength;
+ else if (alertRssi >= 20) tonePause = 2000 - toneLength;
+ if (tonePause > 0) mHandler.postDelayed(mAlertRunnable, tonePause);
+ if (tonePause <= 0 || alertRssi < 60) { playerN.pause(); if (DEBUG) MainActivity.csLibrary4A.appendToLog("Pause"); }
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("mAlertRunnable(): START with new alerting1 = " + alerting1 + ", alertRssi = " + alertRssi);
+ alerting = tonePause > 0 ? true : false;
+ }
+ }
+ };
+
+ void setNotificationListener() {
+ MainActivity.csLibrary4A.appendToLog("setNotificationListener A in search inventory");
+ MainActivity.csLibrary4A.setNotificationListener(new NotificationConnector.NotificationListener() {
+ @Override
+ public void onChange() {
+ MainActivity.csLibrary4A.appendToLog("setNotificationListener TRIGGER key is pressed in search inventory.");
+ startStopHandler(true);
+ }
+ });
+ }
+
+ void startStopHandler(boolean buttonTrigger) {
+ boolean started = false;
+ if (geigerSearchTask != null) {
+ if (geigerSearchTask.getStatus() == AsyncTask.Status.RUNNING) started = true;
+ }
+ if (buttonTrigger == true &&
+ ((started && MainActivity.csLibrary4A.getTriggerButtonStatus())
+ || (started == false && MainActivity.csLibrary4A.getTriggerButtonStatus() == false))) return;
+ if (started == false) {
+ if (MainActivity.csLibrary4A.isBleConnected() == false) {
+ Toast.makeText(MainActivity.mContext, R.string.toast_ble_not_connected, Toast.LENGTH_SHORT).show();
+ return;
+ } else if (MainActivity.csLibrary4A.isRfidFailure()) {
+ Toast.makeText(MainActivity.mContext, "Rfid is disabled", Toast.LENGTH_SHORT).show();
+ return;
+ } else if (MainActivity.csLibrary4A.mrfidToWriteSize() != 0) {
+ Toast.makeText(MainActivity.mContext, R.string.toast_not_ready, Toast.LENGTH_SHORT).show();
+ return;
+ }
+ startInventoryTask();
+ alertRssiUpdateTime = 0;
+ } else {
+ if (buttonTrigger) geigerSearchTask.taskCancelReason = InventoryRfidTask.TaskCancelRReason.BUTTON_RELEASE;
+ else geigerSearchTask.taskCancelReason = InventoryRfidTask.TaskCancelRReason.STOP;
+ alertRssiUpdateTime = -1;
+ }
+ }
+
+ void startInventoryTask() {
+ started = true; boolean invalidRequest = false;
+ if (tagSelected != null) {
+ if (tagSelected.getTid() != null) {
+ if (tagSelected.getTid().indexOf("E201E") == 0) {
+ MainActivity.csLibrary4A.setTagRead(1);
+ MainActivity.csLibrary4A.setAccessBank(3);
+ MainActivity.csLibrary4A.setAccessOffset(112);
+ MainActivity.csLibrary4A.setAccessCount(1);
+ }
+ }
+ }
+ int memorybank = memoryBankSpinner.getSelectedItemPosition();
+ int powerLevel = Integer.valueOf(editTextGeigerAntennaPower.getText().toString());
+ if (powerLevel < 0 || powerLevel > MainActivity.powerLevelMax) {
+ MainActivity.csLibrary4A.appendToLog("invalidRequest = " + invalidRequest + ", with powerLevel = " + powerLevel);
+ invalidRequest = true;
+ } else if (MainActivity.csLibrary4A.setSelectedTag(selectTag.editTextTagID.getText().toString(), memorybank+1, powerLevel) == false) {
+ invalidRequest = true;
+ MainActivity.csLibrary4A.appendToLog("invalidRequest = " + invalidRequest + ", with setSelectedTag as false, string = " + selectTag.editTextTagID.getText().toString() + ", bank = " + memorybank+1 + ", power = " + powerLevel);
+ } else {
+ MainActivity.csLibrary4A.startOperation(RfidReaderChipData.OperationTypes.TAG_SEARCHING);
+ }
+ MainActivity.csLibrary4A.appendToLog("invalidRequest = " + invalidRequest);
+ geigerSearchTask = new InventoryRfidTask(getContext(), -1,-1, 0, 0, 0, 0, invalidRequest, true,
+ null, null, geigerTagRssiView, RfidReader.TagType.TAG_NULL, null,
+ geigerRunTime, geigerTagGotView, geigerVoltageLevelView, null, button, rfidRateView);
+ geigerSearchTask.execute();
+ }
+}
+
+
+
+package com.csl.cs710ademoapp.fragments;
+
+import android.content.Intent;
+import android.os.Bundle;
+import androidx.appcompat.app.AppCompatActivity;
+
+import android.os.Handler;
+import android.os.Looper;
+import android.view.LayoutInflater;
+import android.view.MenuItem;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.AbsListView;
+import android.widget.AdapterView;
+import android.widget.Button;
+import android.widget.EditText;
+import android.widget.ListView;
+import android.widget.TextView;
+import android.widget.Toast;
+import com.csl.cs710ademoapp.MainActivity;
+import com.csl.cs710ademoapp.R;
+import com.csl.cs710ademoapp.SaveList2ExternalTask;
+import com.csl.cs710ademoapp.SharedObjects;
+import com.csl.cs710ademoapp.adapters.ReaderListAdapter;
+import com.csl.cslibrary4a.NotificationConnector;
+import com.csl.cslibrary4a.ReaderDevice;
+import com.csl.cslibrary4a.RfidReaderChipData;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Comparator;
+
+public class InventoryRfidSimpleFragment extends CommonFragment {
+ final private boolean bAdd2End = false;
+ int vibrateTimeBackup = 0;
+
+ private ListView rfidListView;
+ private TextView rfidEmptyView;
+ private TextView rfidRunTime;
+ private TextView rfidYieldView;
+ private TextView rfidRateView;
+ private Button button, buttonShow;
+
+ private ReaderListAdapter readerListAdapter;
+
+ void clearTagsList() {
+ if (bRunningInventory) return;
+ rfidYieldView.setText("");
+ rfidRateView.setText("");
+ MainActivity.tagSelected = null;
+ MainActivity.sharedObjects.tagsList.clear(); MainActivity.sharedObjects.tagsIndexList.clear();
+ readerListAdapter.notifyDataSetChanged();
+ MainActivity.mLogView.setText("");
+ }
+ void sortTagsList() {
+ if (bRunningInventory) return;
+ Collections.sort(MainActivity.sharedObjects.tagsList);
+ readerListAdapter.notifyDataSetChanged();
+ }
+ void sortTagsListByRssi() {
+ if (bRunningInventory) return;
+ Collections.sort(MainActivity.sharedObjects.tagsList, new Comparator() {
+ @Override
+ public int compare(ReaderDevice deviceTag, ReaderDevice t1) {
+ if (deviceTag.getRssi() == t1.getRssi()) return 0;
+ else if (deviceTag.getRssi() < t1.getRssi()) return 1;
+ else return -1;
+ }
+ });
+ readerListAdapter.notifyDataSetChanged();
+ }
+ void saveTagsList() {
+ if (bRunningInventory) return;
+ SaveList2ExternalTask saveExternalTask = new SaveList2ExternalTask(MainActivity.sharedObjects.tagsList);
+ saveExternalTask.execute();
+ }
+ void shareTagsList() {
+ SaveList2ExternalTask saveExternalTask = new SaveList2ExternalTask(MainActivity.sharedObjects.tagsList);
+ String stringOutput = saveExternalTask.createStrEpcList();
+
+ Intent sendIntent = new Intent();
+ sendIntent.setAction(Intent.ACTION_SEND);
+ sendIntent.putExtra(Intent.EXTRA_TEXT, stringOutput);
+ sendIntent.setType("text/plain");
+ startActivity(Intent.createChooser(sendIntent, "Sharing to"));
+ }
+
+ @Override
+ public boolean onOptionsItemSelected(MenuItem item) {
+ if (item.getItemId() == R.id.menuAction_clear) {
+ clearTagsList();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_sortRssi) {
+ sortTagsListByRssi();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_sort) {
+ sortTagsList();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_save) {
+ saveTagsList();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_share) {
+ shareTagsList();
+ return true;
+ } else return super.onOptionsItemSelected(item);
+ }
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ super.onCreateView(inflater, container, savedInstanceState, true);
+ return inflater.inflate(R.layout.fragment_inventory_rfid_simple, container, false);
+ }
+
+ @Override
+ public void onActivityCreated(Bundle savedInstanceState) {
+ super.onActivityCreated(savedInstanceState);
+
+ MainActivity.selectFor = -1;
+ if (true) {
+ androidx.appcompat.app.ActionBar actionBar;
+ actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
+ actionBar.setIcon(R.drawable.dl_inv);
+ actionBar.setTitle(R.string.title_activity_simpleInventory);
+ }
+
+ rfidListView = (ListView) getActivity().findViewById(R.id.simpleInventoryinventoryRfidList1);
+ rfidEmptyView = (TextView) getActivity().findViewById(R.id.simpleInventoryRfidEmpty1);
+ rfidListView.setEmptyView(rfidEmptyView);
+ boolean bSelect4detail = true;
+
+ boolean needDupElim = true;
+ boolean need4Extra1 = MainActivity.csLibrary4A.getPortNumber() > 1 ? true : false;
+ boolean need4Extra2 = false;
+ readerListAdapter = new ReaderListAdapter(getActivity(), R.layout.readers_list_item, MainActivity.sharedObjects.tagsList, bSelect4detail, true, needDupElim, need4Extra1, need4Extra2);
+
+ rfidListView.setAdapter(readerListAdapter);
+ rfidListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
+ rfidListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
+ @Override
+ public void onItemClick(AdapterView> parent, View view, int position, long id) {
+ ReaderDevice readerDevice = readerListAdapter.getItem(position);
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("Position = " + position);
+ if (readerDevice.getSelected()) {
+ readerDevice.setSelected(false);
+ } else {
+ readerDevice.setSelected(true);
+ }
+ MainActivity.sharedObjects.tagsList.set(position, readerDevice);
+ if (readerDevice.getSelected()) MainActivity.tagSelected = readerDevice;
+ else MainActivity.tagSelected = null;
+ for (int i = 0; i < MainActivity.sharedObjects.tagsList.size(); i++) {
+ if (i != position) {
+ ReaderDevice readerDevice1 = MainActivity.sharedObjects.tagsList.get(i);
+ if (readerDevice1.getSelected()) {
+ readerDevice1.setSelected(false);
+ MainActivity.sharedObjects.tagsList.set(i, readerDevice1);
+ }
+ }
+ }
+ readerListAdapter.notifyDataSetChanged();
+ }
+ });
+
+ rfidRunTime = (TextView) getActivity().findViewById(R.id.simpleInventoryRfidRunTime1);
+ TextView rfidFilterOn = (TextView) getActivity().findViewById(R.id.SimpleInventoryRfidFilterOn1);
+ if (MainActivity.csLibrary4A.getSelectEnable() == false && MainActivity.csLibrary4A.getInvMatchEnable() == false && MainActivity.csLibrary4A.getRssiFilterEnable() == false )
+ rfidFilterOn.setVisibility(View.INVISIBLE);
+
+ rfidYieldView = (TextView) getActivity().findViewById(R.id.simpleInventoryRfidYield1);
+ rfidRateView = (TextView) getActivity().findViewById(R.id.simpleInventoryRfidRate1);
+
+ button = (Button) getActivity().findViewById(R.id.simpleInventoryRfidButton1);
+ button.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ startStopHandler(false);
+ }
+ });
+
+ buttonShow = (Button) getActivity().findViewById(R.id.simpleInventoryRfidButtonShow);
+ buttonShow.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ buttonShow.setVisibility(View.GONE);
+ inventoryHandler_tag();
+ }
+ });
+
+ vibrateTimeBackup = MainActivity.csLibrary4A.getVibrateTime();
+ }
+
+ @Override
+ public void onResume() {
+ super.onResume();
+ setNotificationListener();
+ }
+
+ @Override
+ public void onPause() {
+ MainActivity.csLibrary4A.setNotificationListener(null);
+ super.onPause();
+ }
+
+ @Override
+ public void onDestroy() {
+ mHandler.removeCallbacks(runnableCheckReady);
+ MainActivity.csLibrary4A.setNotificationListener(null);
+ MainActivity.csLibrary4A.setSameCheck(true);
+ MainActivity.csLibrary4A.setInvBrandId(false);
+ MainActivity.csLibrary4A.setVibrateTime(vibrateTimeBackup);
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("InventoryRfidSimpleFragment().onDestory(): onDestory()");
+ super.onDestroy();
+ }
+
+ public static InventoryRfidSimpleFragment newInstance(boolean bMultiBank, String mDid) {
+ InventoryRfidSimpleFragment myFragment = new InventoryRfidSimpleFragment();
+
+ Bundle args = new Bundle();
+ args.putBoolean("bMultiBank", bMultiBank);
+ args.putString("mDid", mDid);
+ myFragment.setArguments(args);
+
+ return myFragment;
+ }
+ public InventoryRfidSimpleFragment() {
+ super("InventoryRfidSimpleFragment");
+ }
+
+ void setNotificationListener() {
+ MainActivity.csLibrary4A.setNotificationListener(new NotificationConnector.NotificationListener() {
+ @Override
+ public void onChange() {
+ MainActivity.csLibrary4A.appendToLog("TRIGGER key is pressed.");
+ startStopHandler(true);
+ }
+ });
+ }
+ void startStopHandler(boolean buttonTrigger) {
+ if (buttonTrigger) MainActivity.csLibrary4A.appendToLog("getTriggerButtonStatus = " + MainActivity.csLibrary4A.getTriggerButtonStatus());
+ else MainActivity.csLibrary4A.appendToLog("TriggerButton is pressed");
+
+ boolean started = false;
+ if (bRunningInventory) started = true;
+ if (buttonTrigger && ((started && MainActivity.csLibrary4A.getTriggerButtonStatus()) || (started == false && MainActivity.csLibrary4A.getTriggerButtonStatus() == false))) {
+ MainActivity.csLibrary4A.appendToLog("BARTRIGGER: trigger ignore");
+ return;
+ }
+ MainActivity.csLibrary4A.appendToLog("started = " + started);
+ if (started == false) {
+ if (MainActivity.csLibrary4A.isBleConnected() == false) {
+ Toast.makeText(MainActivity.mContext, R.string.toast_ble_not_connected, Toast.LENGTH_SHORT).show();
+ return;
+ } else if (MainActivity.csLibrary4A.isRfidFailure()) {
+ Toast.makeText(MainActivity.mContext, "Rfid is disabled", Toast.LENGTH_SHORT).show();
+ return;
+ } else if (MainActivity.csLibrary4A.mrfidToWriteSize() != 0) {
+ //Toast.makeText(MainActivity.mContext, R.string.toast_not_ready, Toast.LENGTH_SHORT).show();
+ mHandler.post(runnableCheckReady);
+ return;
+ }
+
+ if (true) {
+ EditText editText = (EditText) getActivity().findViewById(R.id.simpleInventoryTagPopulation);
+ int iValue = Integer.valueOf(editText.getText().toString(), 16);
+ MainActivity.csLibrary4A.setPopulation(iValue);
+
+ editText = (EditText) getActivity().findViewById(R.id.simpleInventoryTagTargetNumber);
+ iTagTarget = Integer.valueOf(editText.getText().toString());
+ iTagGot = 0;
+
+ uplinkPacketList.clear();
+
+ timeMillis = System.currentTimeMillis(); startTimeMillis = timeMillis; runTimeMillis = timeMillis;
+ total = 0;
+ }
+
+ MainActivity.sharedObjects.tagsList.clear(); MainActivity.sharedObjects.tagsIndexList.clear();
+ rfidYieldView.setText("");
+ rfidRateView.setText("");
+ button.setText("Stop");
+ if (bAdd2End) rfidListView.setTranscriptMode(AbsListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
+ else rfidListView.setSelection(0);
+
+ MainActivity.csLibrary4A.appendToLog("setVibrateOn i 2 with getInventoryVibrate as " + MainActivity.csLibrary4A.getInventoryVibrate() + ", getVibrateModeSetting as " + MainActivity.csLibrary4A.getVibrateModeSetting());
+ if (MainActivity.csLibrary4A.getInventoryVibrate() && MainActivity.csLibrary4A.getVibrateModeSetting() == 1) {
+ MainActivity.csLibrary4A.setVibrateOn(2);
+ }
+ //else MainActivity.csLibrary4A.setVibrateOn(0);
+
+ startInventoryTask();
+ bRunningInventory = true;
+ myHandler.post(runnableSimpleInentory);
+ } else {
+ MainActivity.csLibrary4A.abortOperation();
+ if (bAdd2End) rfidListView.setTranscriptMode(AbsListView.TRANSCRIPT_MODE_NORMAL);
+ if (true) { bRunningInventory = false; }
+ }
+ }
+
+ boolean bRunningInventory = false;
+ int total;
+ long timeMillis, startTimeMillis, runTimeMillis, rateTimeMillis;
+ int iTagTarget, iTagGot;
+ Handler myHandler = new Handler(Looper.getMainLooper());
+ ArrayList uplinkPacketList = new ArrayList<>();
+ Runnable runnableSimpleInentory = new Runnable() {
+ @Override
+ public void run() {
+ RfidReaderChipData.Rx000pkgData uplinkPacket;
+ if (MainActivity.csLibrary4A.isBleConnected() && bRunningInventory) {
+ while (MainActivity.csLibrary4A.mrfidToWriteSize() == 0 && (iTagTarget == 0 || iTagGot < iTagTarget)) {
+ if (System.currentTimeMillis() > runTimeMillis + 1000) {
+ runTimeMillis = System.currentTimeMillis();
+ long timePeriod = (System.currentTimeMillis() - startTimeMillis) / 1000;
+ if (timePeriod > 0) {
+ if (rfidRunTime != null) rfidRunTime.setText(String.format("Run time: %d sec", timePeriod));
+ }
+ }
+ uplinkPacket = MainActivity.csLibrary4A.onRFIDEvent();
+ if (uplinkPacket == null) break;
+ else {
+ uplinkPacketList.add(uplinkPacket);
+ iTagGot++;
+ mHandler.postDelayed(runnableStartBeep, 250);
+ }
+ }
+ if (iTagTarget != 0 && iTagGot >= iTagTarget) {
+ MainActivity.csLibrary4A.abortOperation();
+ bRunningInventory = false;
+ }
+
+ if (iTagGot != 0) {
+ rfidYieldView.setText("Total:" + iTagGot);
+
+ long tagRate = MainActivity.csLibrary4A.getTagRate();
+ String strRate = ""; boolean bUpdateRate = false;
+ if (tagRate >= 0) {
+ strRate = String.valueOf(tagRate);
+ bUpdateRate = true;
+ } else {
+ if (System.currentTimeMillis() - rateTimeMillis > 1500) {
+ strRate = "___";
+ bUpdateRate = true;
+ }
+ }
+ if (bUpdateRate) {
+ rfidRateView.setText("Rate:" + strRate);
+ rateTimeMillis = System.currentTimeMillis();
+ }
+ }
+ myHandler.postDelayed(runnableSimpleInentory, 200);
+ } else {
+ bRunningInventory = false;
+ button.setText("Start"); buttonShow.setVisibility(View.VISIBLE);
+ }
+ }
+ };
+
+ void inventoryHandler_tag() {
+ double rssi = 0;
+ int phase = -1, chidx = -1, port = -1;
+ int total = 0;
+
+ while (uplinkPacketList.size() != 0) {
+ RfidReaderChipData.Rx000pkgData uplinkPacket = uplinkPacketList.get(0);
+ uplinkPacketList.remove(0);
+ RfidReaderChipData.Rx000pkgData tagData = uplinkPacket;
+
+ boolean match = false;
+ total++;
+ rssi = uplinkPacket.decodedRssi;
+ phase = uplinkPacket.decodedPhase;
+ chidx = uplinkPacket.decodedChidx;
+ port = uplinkPacket.decodedPort;
+
+ ReaderDevice deviceTag = null;
+ int iMatchItem = -1;
+ if (true) {
+ int index = Collections.binarySearch(MainActivity.sharedObjects.tagsIndexList, new SharedObjects.TagsIndex(MainActivity.csLibrary4A.byteArrayToString(tagData.decodedEpc), 0));
+ if (index >= 0) {
+ iMatchItem = MainActivity.sharedObjects.tagsIndexList.size() - 1 - MainActivity.sharedObjects.tagsIndexList.get(index).getPosition();
+ }
+ }
+ if (iMatchItem >= 0) {
+ deviceTag = MainActivity.sharedObjects.tagsList.get(iMatchItem);
+ int count = deviceTag.getCount();
+ count++;
+ deviceTag.setCount(count);
+ deviceTag.setRssi(rssi);
+ deviceTag.setPhase(phase);
+ deviceTag.setChannel(chidx);
+ deviceTag.setPort(port);
+ MainActivity.sharedObjects.tagsList.set(iMatchItem, deviceTag);
+ match = true;
+ }
+ if (match == false) {
+ deviceTag = new ReaderDevice("", MainActivity.csLibrary4A.byteArrayToString(uplinkPacket.decodedEpc), false, null,
+ MainActivity.csLibrary4A.byteArrayToString(uplinkPacket.decodedPc),
+ null,
+ (uplinkPacket.decodedCrc != null ? MainActivity.csLibrary4A.byteArrayToString(uplinkPacket.decodedCrc) : null),
+ null, null, 0, 0, null, 0, 0,null, null, null, null, 1,
+ rssi, phase, chidx, port,
+ 0, 0, 0, 0, 0, 0, null, 0);
+ if (bAdd2End) MainActivity.sharedObjects.tagsList.add(deviceTag);
+ else MainActivity.sharedObjects.tagsList.add(0, deviceTag);
+ SharedObjects.TagsIndex tagsIndex = new SharedObjects.TagsIndex(MainActivity.csLibrary4A.byteArrayToString(uplinkPacket.decodedEpc), MainActivity.sharedObjects.tagsList.size() - 1);
+ MainActivity.sharedObjects.tagsIndexList.add(tagsIndex);
+ Collections.sort(MainActivity.sharedObjects.tagsIndexList);
+ }
+ }
+ MainActivity.csLibrary4A.appendToLog("readerListAdapter is " + (readerListAdapter != null ? "valid" : "null"));
+ if (readerListAdapter != null) readerListAdapter.notifyDataSetChanged();
+ rfidYieldView.setText("Unique:" + MainActivity.sharedObjects.tagsList.size() + "\nTotal:" + total);
+ }
+
+ Runnable runnableStartBeep = new Runnable() {
+ @Override
+ public void run() {
+ //if (MainActivity.isInventoryRfidRequestNewSound()) MainActivity.sharedObjects.playerN.start(); //playerN.setVolume(300, 300);
+ //else
+ MainActivity.sharedObjects.playerO.start();
+ }
+ };
+
+ void startInventoryTask() {
+ MainActivity.csLibrary4A.appendToLog("startInventoryTask");
+ MainActivity.csLibrary4A.restoreAfterTagSelect();
+ MainActivity.csLibrary4A.startOperation(RfidReaderChipData.OperationTypes.TAG_INVENTORY_COMPACT);
+ }
+
+ private final Runnable runnableCheckReady = new Runnable() {
+ @Override
+ public void run() {
+ if (MainActivity.csLibrary4A.mrfidToWriteSize() != 0) {
+ button.setEnabled(false);
+ button.setText("Please wait");
+ MainActivity.csLibrary4A.setNotificationListener(null);
+ mHandler.postDelayed(runnableCheckReady, 500);
+ } else {
+ button.setText("Start");
+ button.setEnabled(true);
+ setNotificationListener();
+ }
+ }
+ };
+}
+
+
+
+package com.csl.cs710ademoapp.fragments;
+
+import static com.csl.cslibrary4a.RfidReader.TagType.TAG_KILOWAY;
+
+import android.os.Bundle;
+import android.view.LayoutInflater;
+import android.view.MenuItem;
+import android.view.View;
+import android.view.ViewGroup;
+
+import androidx.appcompat.app.ActionBar;
+import androidx.appcompat.app.AppCompatActivity;
+import androidx.viewpager.widget.ViewPager;
+
+import com.csl.cs710ademoapp.MainActivity;
+import com.csl.cs710ademoapp.R;
+import com.csl.cslibrary4a.AdapterTab;
+import com.google.android.material.tabs.TabLayout;
+
+public class KilowayFragment extends CommonFragment {
+ private ActionBar actionBar;
+ private ViewPager viewPager;
+ AdapterTab adapter;
+
+ private String[] tabs = {"Scan", "Geiger"}; //, "Access"};
+ int iTargetOld, iSessionOld;
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ super.onCreateView(inflater, container, savedInstanceState, true);
+ return inflater.inflate(R.layout.custom_tabbed_layout, container, false);
+ }
+
+ @Override
+ public boolean onOptionsItemSelected(MenuItem item) {
+ InventoryRfidiMultiFragment fragment = (InventoryRfidiMultiFragment) adapter.getItem(0);
+ if (item.getItemId() == R.id.menuAction_clear) {
+ fragment.clearTagsList();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_sortRssi) {
+ fragment.sortTagsListByRssi();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_sort) {
+ fragment.sortTagsList();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_save) {
+ fragment.saveTagsList();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_share) {
+ fragment.shareTagsList();
+ return true;
+ } else return super.onOptionsItemSelected(item);
+ }
+
+ @Override
+ public void onActivityCreated(Bundle savedInstanceState) {
+ super.onActivityCreated(savedInstanceState);
+
+ actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
+ actionBar.setIcon(R.drawable.dl_inv);
+ actionBar.setTitle(R.string.title_activity_kiloway);
+
+ TabLayout tabLayout = (TabLayout) getActivity().findViewById(R.id.OperationsTabLayout);
+
+ adapter = new AdapterTab(getActivity().getSupportFragmentManager(), tabs.length);
+ adapter.setFragment(0, InventoryRfidiMultiFragment.newInstance(true, TAG_KILOWAY, "E281D"));
+ adapter.setFragment(1, new InventoryRfidSearchFragment(true));
+ adapter.setFragment(2, new AccessKilowayFragment(false));
+
+ viewPager = (ViewPager) getActivity().findViewById(R.id.OperationsPager);
+ viewPager.setAdapter(adapter);
+ viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
+
+ for (String tab_name : tabs) {
+ tabLayout.addTab(tabLayout.newTab().setText(tab_name));
+ }
+
+ tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
+ @Override
+ public void onTabSelected(TabLayout.Tab tab) {
+ viewPager.setCurrentItem(tab.getPosition());
+ }
+
+ @Override
+ public void onTabUnselected(TabLayout.Tab tab) {
+ }
+
+ @Override
+ public void onTabReselected(TabLayout.Tab tab) {
+ }
+ });
+
+ iTargetOld = MainActivity.csLibrary4A.getQueryTarget();
+ iSessionOld = MainActivity.csLibrary4A.getQuerySession();
+ MainActivity.csLibrary4A.setBasicCurrentLinkProfile();
+ }
+
+ @Override
+ public void onPause() {
+ adapter.fragment0.onPause();
+ adapter.fragment1.onPause();
+ super.onPause();
+ }
+
+ @Override
+ public void onStop() {
+ adapter.fragment0.onStop();
+ adapter.fragment1.onStop();
+ super.onStop();
+ }
+
+ @Override
+ public void onDestroyView() {
+ adapter.fragment0.onDestroyView();
+ adapter.fragment1.onDestroyView();
+ super.onDestroyView();
+ }
+
+ @Override
+ public void onDestroy() {
+ adapter.fragment0.onDestroy();
+ adapter.fragment1.onDestroy();
+ MainActivity.csLibrary4A.setTagGroup(MainActivity.csLibrary4A.getQuerySelect(), iSessionOld, iTargetOld);
+ //MainActivity.mCs108Library4a.macWrite(0x203, 0);
+ super.onDestroy();
+ }
+
+ @Override
+ public void onDetach() {
+ adapter.fragment0.onDetach();
+ adapter.fragment1.onDetach();
+ super.onDetach();
+ }
+
+ public KilowayFragment() {
+ super("LedTagFragment");
+ }
+}
+
+
+
+package com.csl.cs710ademoapp.fragments;
+
+import static com.csl.cslibrary4a.RfidReader.TagType.TAG_LONGJING;
+
+import android.os.Bundle;
+import android.view.LayoutInflater;
+import android.view.MenuItem;
+import android.view.View;
+import android.view.ViewGroup;
+
+import androidx.appcompat.app.ActionBar;
+import androidx.appcompat.app.AppCompatActivity;
+import androidx.viewpager.widget.ViewPager;
+
+import com.csl.cs710ademoapp.MainActivity;
+import com.csl.cs710ademoapp.R;
+import com.csl.cslibrary4a.AdapterTab;
+import com.google.android.material.tabs.TabLayout;
+
+public class LongjingFragment extends CommonFragment {
+ private ActionBar actionBar;
+ private ViewPager viewPager;
+ AdapterTab adapter;
+
+ private String[] tabs = {"Scan", "Geiger"}; //"Access",
+ int iTargetOld, iSessionOld;
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ super.onCreateView(inflater, container, savedInstanceState, true);
+ return inflater.inflate(R.layout.custom_tabbed_layout, container, false);
+ }
+
+ @Override
+ public boolean onOptionsItemSelected(MenuItem item) {
+ InventoryRfidiMultiFragment fragment1 = (InventoryRfidiMultiFragment) adapter.getItem(0);
+ if (item.getItemId() == R.id.menuAction_clear) {
+ fragment1.clearTagsList();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_sortRssi) {
+ fragment1.sortTagsListByRssi();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_sort) {
+ fragment1.sortTagsList();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_save) {
+ fragment1.saveTagsList();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_share) {
+ fragment1.shareTagsList();
+ return true;
+ } else return super.onOptionsItemSelected(item);
+ }
+
+ @Override
+ public void onActivityCreated(Bundle savedInstanceState) {
+ super.onActivityCreated(savedInstanceState);
+
+ actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
+ actionBar.setIcon(R.drawable.dl_inv);
+ actionBar.setTitle(R.string.title_activity_longjing);
+
+ TabLayout tabLayout = (TabLayout) getActivity().findViewById(R.id.OperationsTabLayout);
+
+ adapter = new AdapterTab(getActivity().getSupportFragmentManager(), tabs.length);
+ adapter.setFragment(0, InventoryRfidiMultiFragment.newInstance(true, TAG_LONGJING, "E201E"));
+ adapter.setFragment(1, new InventoryRfidSearchFragment(true));
+ adapter.setFragment(2, new AccessKilowayFragment(true));
+
+ viewPager = (ViewPager) getActivity().findViewById(R.id.OperationsPager);
+ viewPager.setAdapter(adapter);
+ viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
+
+ for (String tab_name : tabs) {
+ tabLayout.addTab(tabLayout.newTab().setText(tab_name));
+ }
+
+ tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
+ @Override
+ public void onTabSelected(TabLayout.Tab tab) {
+ viewPager.setCurrentItem(tab.getPosition());
+ }
+
+ @Override
+ public void onTabUnselected(TabLayout.Tab tab) {
+ }
+
+ @Override
+ public void onTabReselected(TabLayout.Tab tab) {
+ }
+ });
+
+ iTargetOld = MainActivity.csLibrary4A.getQueryTarget();
+ iSessionOld = MainActivity.csLibrary4A.getQuerySession();
+ MainActivity.csLibrary4A.setBasicCurrentLinkProfile();
+ }
+
+ @Override
+ public void onPause() {
+ adapter.fragment0.onPause();
+ adapter.fragment1.onPause();
+ super.onPause();
+ }
+
+ @Override
+ public void onStop() {
+ adapter.fragment0.onStop();
+ adapter.fragment1.onStop();
+ super.onStop();
+ }
+
+ @Override
+ public void onDestroyView() {
+ adapter.fragment0.onDestroyView();
+ adapter.fragment1.onDestroyView();
+ super.onDestroyView();
+ }
+
+ @Override
+ public void onDestroy() {
+ adapter.fragment0.onDestroy();
+ adapter.fragment1.onDestroy();
+ MainActivity.csLibrary4A.setTagGroup(MainActivity.csLibrary4A.getQuerySelect(), iSessionOld, iTargetOld);
+ //MainActivity.mCs108Library4a.macWrite(0x203, 0);
+ super.onDestroy();
+ }
+
+ @Override
+ public void onDetach() {
+ adapter.fragment0.onDetach();
+ adapter.fragment1.onDetach();
+ super.onDetach();
+ }
+
+ public LongjingFragment() {
+ super("LedTagFragment");
+ }
+}
+
+
+
+package com.csl.cs710ademoapp.fragments;
+
+import android.os.Bundle;
+
+import com.csl.cslibrary4a.AdapterTab;
+import com.google.android.material.tabs.TabLayout;
+import androidx.viewpager.widget.ViewPager;
+import androidx.appcompat.app.ActionBar;
+import androidx.appcompat.app.AppCompatActivity;
+import android.view.LayoutInflater;
+import android.view.MenuItem;
+import android.view.View;
+import android.view.ViewGroup;
+
+import com.csl.cs710ademoapp.MainActivity;
+import com.csl.cs710ademoapp.R;
+
+public class MicronFragment extends CommonFragment {
+ private ActionBar actionBar;
+ private ViewPager viewPager;
+ AdapterTab adapter;
+
+ private String[] tabs = { "Scan/Select", "Read" };
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ super.onCreateView(inflater, container, savedInstanceState, true);
+ return inflater.inflate(R.layout.custom_tabbed_layout, container, false);
+ }
+
+ @Override
+ public boolean onOptionsItemSelected(MenuItem item) {
+ InventoryRfidiMultiFragment fragment = (InventoryRfidiMultiFragment) adapter.fragment0;
+ if (item.getItemId() == R.id.menuAction_clear) {
+ fragment.clearTagsList();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_sortRssi) {
+ fragment.sortTagsListByRssi();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_sort) {
+ fragment.sortTagsList();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_save) {
+ fragment.saveTagsList();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_share) {
+ fragment.shareTagsList();
+ return true;
+ } else return super.onOptionsItemSelected(item);
+ }
+
+ @Override
+ public void onActivityCreated(Bundle savedInstanceState) {
+ super.onActivityCreated(savedInstanceState);
+
+ actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
+ actionBar.setIcon(R.drawable.dl_inv);
+ actionBar.setTitle(R.string.title_activity_emMicro);
+
+ TabLayout tabLayout = (TabLayout) getActivity().findViewById(R.id.OperationsTabLayout);
+
+ adapter = new AdapterTab(getActivity().getSupportFragmentManager(), tabs.length);
+ adapter.setFragment(0, InventoryRfidiMultiFragment.newInstance(true, null, ""));
+ adapter.setFragment(1, AccessMicronFragment.newInstance(false));
+
+ viewPager = (ViewPager) getActivity().findViewById(R.id.OperationsPager);
+ viewPager.setAdapter(adapter);
+ viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
+
+ for (String tab_name : tabs) {
+ tabLayout.addTab(tabLayout.newTab().setText(tab_name));
+ }
+
+ tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
+ @Override
+ public void onTabSelected(TabLayout.Tab tab) {
+ viewPager.setCurrentItem(tab.getPosition());
+ }
+
+ @Override
+ public void onTabUnselected(TabLayout.Tab tab) {
+ }
+
+ @Override
+ public void onTabReselected(TabLayout.Tab tab) {
+ }
+ });
+
+ MainActivity.csLibrary4A.setBasicCurrentLinkProfile();
+ }
+
+ @Override
+ public void onPause() {
+ if (adapter.fragment0 != null) adapter.fragment0.onPause();
+ if (adapter.fragment1 != null) adapter.fragment1.onPause();
+ super.onPause();
+ }
+
+ @Override
+ public void onStop() {
+ if (adapter.fragment0 != null) adapter.fragment0.onStop();
+ if (adapter.fragment1 != null) adapter.fragment1.onStop();
+ super.onStop();
+ }
+
+ @Override
+ public void onDestroyView() {
+ if (adapter.fragment0 != null) adapter.fragment0.onDestroyView();
+ if (adapter.fragment1 != null) adapter.fragment1.onDestroyView();
+ super.onDestroyView();
+ }
+
+ @Override
+ public void onDestroy() {
+ if (adapter.fragment0 != null) adapter.fragment0.onDestroy();
+ if (adapter.fragment1 != null) adapter.fragment1.onDestroy();
+ if (MainActivity.selectFor != -1) {
+ MainActivity.csLibrary4A.setSelectCriteriaDisable(-1);
+ MainActivity.selectFor = -1;
+ }
+ MainActivity.csLibrary4A.restoreAfterTagSelect();
+ super.onDestroy();
+ }
+
+ @Override
+ public void onDetach() {
+ if (adapter.fragment0 != null) adapter.fragment0.onDetach();
+ if (adapter.fragment1 != null) adapter.fragment1.onDetach();
+ super.onDetach();
+ }
+
+ public MicronFragment() {
+ super("MicronFragment");
+ }
+}
+
+
+
+package com.csl.cs710ademoapp.fragments;
+
+import android.os.Bundle;
+import android.os.Handler;
+import android.text.InputFilter;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.AdapterView;
+import android.widget.ArrayAdapter;
+import android.widget.Button;
+import android.widget.CheckBox;
+import android.widget.EditText;
+import android.widget.LinearLayout;
+import android.widget.RadioButton;
+import android.widget.Spinner;
+import android.widget.TableRow;
+import android.widget.TextView;
+import android.widget.Toast;
+
+import com.csl.cs710ademoapp.CustomPopupWindow;
+import com.csl.cs710ademoapp.MainActivity;
+import com.csl.cs710ademoapp.R;
+import com.csl.cs710ademoapp.SettingTask;
+import com.csl.cslibrary4a.RfidReaderChipData;
+
+public class SettingAdminFragment extends CommonFragment {
+ private CheckBox checkBoxTriggerReporting, checkBoxInventoryBeep, checkBoxInventoryVibrate, checkBoxSaveFileEnable, checkBoxSaveCloudEnable, checkBoxSaveNewCloudEnable, checkBoxSaveAllCloudEnable, checkBoxDebugEnable, checkBoxForegroundService;
+ private CheckBox checkBoxCsvColumnResBank, checkBoxCsvColumnEpcBank, checkBoxCsvColumnTidBank, checkBoxCsvColumnUserBank, checkBoxCsvColumnPhase, checkBoxCsvColumnChannel, checkBoxCsvColumnTime, checkBoxCsvColumnTimeZone, checkBoxCsvColumnLocation, checkBoxCsvColumnDirection, checkBoxCsvColumnOthers;
+ private EditText editTextDeviceName, editTextCycleDelay, editTextTriggerReportingCount, editTextBeepCount, editTextVibrateTime, editTextVibrateWindow, editTextServer, editTextServerTimeout, editTextServerMqtt, editTextTopicMqtt, editTextForegroundDupElim, editTextServerImpinj, editTextServerImpinjName, editTextServerImpinjPasword;
+ private RadioButton radioButtonCloudSaveNone, radioButtonCloudSaveHttp, radioButtonCloudSaveMqtt;
+ private TextView textViewReaderModel;
+ private Spinner spinnerQueryBattery, spinnerQueryRssi, spinnerQueryVibrateMode, spinnerSavingFormat;
+ private Button buttonCSLServer, button;
+
+ final boolean sameCheck = true;
+ Handler mHandler = new Handler();
+
+ int batteryDisplaySelect = -1;
+ int rssiDisplaySelect = -1;
+ int vibrateModeSelect = -1;
+ int savingFormatSelect = -1;
+ int csvColumnSelect = -1;
+ String deviceName = "";
+ long cycleDelay = -1; long cycleDelayMin = 0; long cycleDelayMax = 2000;
+ int iBeepCount = -1; int iBeepCountMin = 1; int iBeepCountMax = 100;
+ short sTriggerCount = -1, sTriggerCountMin = 1, sTriggerCountMax = 100;
+ int iVibrateTime = -1; int iVibrateTimeMin = 1; int iVibrateTimeMax = 999;
+ int iVibrateWindow = -1; int iVibrateWindowMin = 1; int iVibrateWindowMax = 4;
+ boolean triggerReporting, inventoryBeep, inventoryVibrate, saveFileEnable, saveCloudEnable, saveNewCloudEnable, saveAllCloudEnable, debugEnable, foregroundServiceEnable;
+ String serverName, serverMqtt, topicMqtt, serverImpinj, serverImpinjName, serverImpinjPasword;
+ int buttonCloudSave = -1, iForegroundDupElimNew = -1;
+ int iServerTimeout = -1; int iServerTimeoutMin = 3; int iServerTimeoutMax = 9;
+
+ private SettingTask settingTask;
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ super.onCreateView(inflater, container, savedInstanceState, false);
+ return inflater.inflate(R.layout.fragment_settings_admin, container, false);
+ }
+
+ @Override
+ public void onActivityCreated(Bundle savedInstanceState) {
+ super.onActivityCreated(savedInstanceState);
+
+ textViewReaderModel = (TextView) getActivity().findViewById(R.id.settingAdminReaderModel);
+ editTextDeviceName = (EditText) getActivity().findViewById(R.id.settingAdminDeviceName);
+ editTextDeviceName.setBackgroundResource(R.drawable.my_edittext_background);
+ editTextDeviceName.setHint("Name Pattern");
+ InputFilter[] FilterArray = new InputFilter[1];
+ FilterArray[0] = new InputFilter.LengthFilter(20);
+ editTextDeviceName.setFilters(FilterArray);
+
+ spinnerQueryBattery = (Spinner) getActivity().findViewById(R.id.settingAdminBattery);
+ {
+ ArrayAdapter targetAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.admin_battery_options, R.layout.custom_spinner_layout);
+ targetAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+ spinnerQueryBattery.setAdapter(targetAdapter);
+ }
+
+ spinnerQueryRssi = (Spinner) getActivity().findViewById(R.id.settingAdminRssi);
+ {
+ ArrayAdapter targetAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.admin_rssi_options, R.layout.custom_spinner_layout);
+ targetAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+ spinnerQueryRssi.setAdapter(targetAdapter);
+ }
+
+ spinnerQueryVibrateMode = (Spinner) getActivity().findViewById(R.id.settingAdminVibrateMode);
+ {
+ ArrayAdapter targetAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.admin_vibratemode_options, R.layout.custom_spinner_layout);
+ targetAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+ spinnerQueryVibrateMode.setAdapter(targetAdapter);
+ }
+
+ if (MainActivity.csLibrary4A.get98XX() == 2) {
+ LinearLayout linearLayout = (LinearLayout) getActivity().findViewById(R.id.settingAdminCycleDelayRow);
+ linearLayout.setVisibility(View.GONE);
+ spinnerQueryVibrateMode.setEnabled(false);
+ }
+
+ spinnerSavingFormat = (Spinner) getActivity().findViewById(R.id.settingAdminSavingFormat);
+ {
+ ArrayAdapter targetAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.admin_savingformat_options, R.layout.custom_spinner_layout);
+ targetAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+ spinnerSavingFormat.setAdapter(targetAdapter);
+ spinnerSavingFormat.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
+ @Override
+ public void onItemSelected(AdapterView> adapterView, View view, int i, long l) {
+ LinearLayout linearLayout = (LinearLayout) getActivity().findViewById(R.id.settingAdminCSVColumnSelectLayout);
+ switch (i) {
+ case 1:
+ linearLayout.setVisibility(View.VISIBLE);
+ break;
+ default:
+ linearLayout.setVisibility(View.GONE);
+ break;
+ }
+ }
+
+ @Override
+ public void onNothingSelected(AdapterView> adapterView) {
+
+ }
+ });
+ }
+
+ checkBoxCsvColumnResBank = (CheckBox) getActivity().findViewById(R.id.settingAdminCSVColumnResBank);
+ checkBoxCsvColumnEpcBank = (CheckBox) getActivity().findViewById(R.id.settingAdminCSVColumnEpcBank);
+ checkBoxCsvColumnTidBank = (CheckBox) getActivity().findViewById(R.id.settingAdminCSVColumnTidBank);
+ checkBoxCsvColumnUserBank = (CheckBox) getActivity().findViewById(R.id.settingAdminCSVColumnUserBank);
+ checkBoxCsvColumnPhase = (CheckBox) getActivity().findViewById(R.id.settingAdminCSVColumnPhase);
+ checkBoxCsvColumnChannel = (CheckBox) getActivity().findViewById(R.id.settingAdminCSVColumnChannel);
+ checkBoxCsvColumnTime = (CheckBox) getActivity().findViewById(R.id.settingAdminCSVColumnTime);
+ checkBoxCsvColumnTimeZone = (CheckBox) getActivity().findViewById(R.id.settingAdminCSVColumnTimeZone);
+ checkBoxCsvColumnLocation = (CheckBox) getActivity().findViewById(R.id.settingAdminCSVColumnLocation);
+ checkBoxCsvColumnDirection = (CheckBox) getActivity().findViewById(R.id.settingAdminCSVColumnDirection);
+ checkBoxCsvColumnOthers = (CheckBox) getActivity().findViewById(R.id.settingAdminCSVColumnOthers);
+
+ TextView textViewAdminCycleDelayLabel = (TextView) getActivity().findViewById(R.id.settingAdminCycleDelayLabel);
+ String stringAdminCycleDelayLabel = textViewAdminCycleDelayLabel.getText().toString();
+ stringAdminCycleDelayLabel += "(" + String.valueOf(cycleDelayMin) + "-" + String.valueOf(cycleDelayMax) + "ms)";
+ textViewAdminCycleDelayLabel.setText(stringAdminCycleDelayLabel);
+ editTextCycleDelay = (EditText) getActivity().findViewById(R.id.settingAdminCycleDelay);
+
+ TextView textViewAdminTriggerReportingCountLabel = (TextView) getActivity().findViewById(R.id.settingAdminTriggerReportingCountLabel);
+ String stringAdminTriggeringReportingCountLabel = textViewAdminTriggerReportingCountLabel.getText().toString();
+ stringAdminTriggeringReportingCountLabel += "(" + String.valueOf(sTriggerCountMin) + "-" + String.valueOf(sTriggerCountMax) + ") sec";
+ textViewAdminTriggerReportingCountLabel.setText(stringAdminTriggeringReportingCountLabel);
+ editTextTriggerReportingCount = (EditText) getActivity().findViewById(R.id.settingAdminTriggerReportingCount);
+
+ TextView textViewAdminBeepCountLabel = (TextView) getActivity().findViewById(R.id.settingAdminBeepCountLabel);
+ String stringAdminBeepCountLabel = textViewAdminBeepCountLabel.getText().toString();
+ stringAdminBeepCountLabel += "(" + String.valueOf(iBeepCountMin) + "-" + String.valueOf(iBeepCountMax) + ")";
+ textViewAdminBeepCountLabel.setText(stringAdminBeepCountLabel);
+ editTextBeepCount = (EditText) getActivity().findViewById(R.id.settingAdminBeepCount);
+
+ TextView textViewAdminVibrateTimeLabel = (TextView) getActivity().findViewById(R.id.settingAdminVibrateTimeLabel);
+ String stringAdminVibrateTimeLabel = textViewAdminVibrateTimeLabel.getText().toString();
+ stringAdminVibrateTimeLabel += "(" + String.valueOf(iVibrateTimeMin) + "-" + String.valueOf(iVibrateTimeMax) + "ms)";
+ textViewAdminVibrateTimeLabel.setText(stringAdminVibrateTimeLabel);
+ editTextVibrateTime = (EditText) getActivity().findViewById(R.id.settingAdminVibrateTime);
+
+ TextView textViewAdminVibrateWindowLabel = (TextView) getActivity().findViewById(R.id.settingAdminVibrateWindowLabel);
+ String stringAdminVibrateWindowLabel = textViewAdminVibrateWindowLabel.getText().toString();
+ stringAdminVibrateWindowLabel += "(" + String.valueOf(iVibrateWindowMin) + "-" + String.valueOf(iVibrateWindowMax) + "sec)";
+ textViewAdminVibrateWindowLabel.setText(stringAdminVibrateWindowLabel);
+ editTextVibrateWindow = (EditText) getActivity().findViewById(R.id.settingAdminVibrateWindow);
+
+ checkBoxTriggerReporting = (CheckBox) getActivity().findViewById(R.id.settingAdminTriggerReporting);
+ checkBoxInventoryBeep = (CheckBox) getActivity().findViewById(R.id.settingAdminInventoryBeep);
+ checkBoxInventoryVibrate = (CheckBox) getActivity().findViewById(R.id.settingAdminInventoryVibrate);
+ checkBoxSaveFileEnable = (CheckBox) getActivity().findViewById(R.id.settingAdminToFileEnable);
+ checkBoxSaveCloudEnable = (CheckBox) getActivity().findViewById(R.id.settingAdminToCloudEnable);
+ checkBoxSaveNewCloudEnable = (CheckBox) getActivity().findViewById(R.id.settingAdminNewToCloudEnable);
+ checkBoxSaveAllCloudEnable = (CheckBox) getActivity().findViewById(R.id.settingAdminAllToCloudEnable);
+ editTextServer = (EditText) getActivity().findViewById(R.id.settingAdminServer);
+ editTextServer.setHint("Cloud Address Pattern");
+ editTextServerMqtt = (EditText) getActivity().findViewById(R.id.settingAdminMqttServer);
+ editTextServerMqtt.setHint("IP Address Pattern");
+ editTextTopicMqtt = (EditText) getActivity().findViewById(R.id.settingAdminTopicMqtt);
+ editTextForegroundDupElim = (EditText) getActivity().findViewById(R.id.settingAdminDupElimDelay);
+ radioButtonCloudSaveNone = (RadioButton) getActivity().findViewById(R.id.settingAdminCloudSaveNone);
+ radioButtonCloudSaveHttp = (RadioButton) getActivity().findViewById(R.id.settingAdminCloudSaveHttp);
+ radioButtonCloudSaveMqtt = (RadioButton) getActivity().findViewById(R.id.settingAdminCloudSaveMqtt);
+ editTextServerImpinj = (EditText) getActivity().findViewById(R.id.settingAdminServerImpinj);
+ editTextServerImpinjName = (EditText) getActivity().findViewById(R.id.settingAdminServerImpinjName);
+ editTextServerImpinjPasword = (EditText) getActivity().findViewById(R.id.settingAdminServerImpinjPassword);
+
+ TextView textViewAdminServerConnectTimeoutLabel = (TextView) getActivity().findViewById(R.id.settingAdminServerConnectTimeoutLabel);
+ String stringAdminServerConnectTimeoutLabel = textViewAdminServerConnectTimeoutLabel.getText().toString();
+ stringAdminServerConnectTimeoutLabel += "(" + String.valueOf(iServerTimeoutMin) + "-" + String.valueOf(iServerTimeoutMax) + "sec)";
+ textViewAdminServerConnectTimeoutLabel.setText(stringAdminServerConnectTimeoutLabel);
+ editTextServerTimeout = (EditText) getActivity().findViewById(R.id.settingAdminServerConnectTimeout);
+
+ buttonCSLServer = (Button) getActivity().findViewById(R.id.settingAdminCSLServer);
+ buttonCSLServer.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View view) {
+ String serverLocation = "https://" + "democloud.convergence.com.hk:" + "29090/WebServiceRESTs/1.0/req/" + "create-update-delete/update-entity/" + "tagdata";
+ //String serverLocation = "https://" + "www.convergence.com.hk:" + "29090/WebServiceRESTs/1.0/req/" + "create-update-delete/update-entity/" + "tagdata";
+ //String serverLocation = "http://ptsv2.com/t/10i1t-1519143332/post";
+ editTextServer.setText(serverLocation);
+ //String serverMqttLocation = "192.168.25.182";
+ //editTextServerMqtt.setText(serverMqttLocation);
+ //editTextTopicMqtt.setText("test/topic");
+ }
+ });
+
+ Button buttonReset = (Button) getActivity().findViewById(R.id.settingAdminBarcodeResetButton);
+ buttonReset.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (MainActivity.csLibrary4A.isBleConnected() == false) {
+ Toast.makeText(MainActivity.mContext, R.string.toast_ble_not_connected, Toast.LENGTH_SHORT).show();
+ return;
+ } else if (MainActivity.csLibrary4A.isBarcodeFailure()) {
+ Toast.makeText(MainActivity.mContext, "Barcode is disabled", Toast.LENGTH_SHORT).show();
+ return;
+ } else {
+ MainActivity.csLibrary4A.setBarcodeOn(true);
+ MainActivity.csLibrary4A.barcodeSendCommandConinuous();
+ MainActivity.csLibrary4A.setBarcodeOn(false);
+ MainActivity.csLibrary4A.saveSetting2File();
+ Toast.makeText(MainActivity.mContext, R.string.toast_saved, Toast.LENGTH_SHORT).show();
+ }
+ }
+ });
+
+ Button buttonReset2 = (Button) getActivity().findViewById(R.id.settingAdminBarcodeResetButtonT);
+ buttonReset2.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (MainActivity.csLibrary4A.isBleConnected() == false) {
+ Toast.makeText(MainActivity.mContext, R.string.toast_ble_not_connected, Toast.LENGTH_SHORT).show();
+ return;
+ } else if (MainActivity.csLibrary4A.isBarcodeFailure()) {
+ Toast.makeText(MainActivity.mContext, "Barcode is disabled", Toast.LENGTH_SHORT).show();
+ return;
+ } else {
+ MainActivity.csLibrary4A.setBarcodeOn(true);
+ MainActivity.csLibrary4A.barcodeSendCommandTrigger();
+ MainActivity.csLibrary4A.saveSetting2File();
+ Toast.makeText(MainActivity.mContext, R.string.toast_saved, Toast.LENGTH_SHORT).show();
+ }
+ }
+ });
+
+ Button buttonReset3 = (Button) getActivity().findViewById(R.id.settingAdminBarcodeResetButtonF);
+ buttonReset3.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (MainActivity.csLibrary4A.isBleConnected() == false) {
+ Toast.makeText(MainActivity.mContext, R.string.toast_ble_not_connected, Toast.LENGTH_SHORT).show();
+ return;
+ } else if (MainActivity.csLibrary4A.isBarcodeFailure()) {
+ Toast.makeText(MainActivity.mContext, "Barcode is disabled", Toast.LENGTH_SHORT).show();
+ return;
+ } else {
+ MainActivity.csLibrary4A.setBarcodeOn(true);
+ MainActivity.csLibrary4A.barcodeSendCommandSetPreSuffix();
+ Toast.makeText(MainActivity.mContext, R.string.toast_saved, Toast.LENGTH_SHORT).show();
+ }
+ }
+ });
+
+ Button buttonReset4 = (Button) getActivity().findViewById(R.id.settingAdminBarcodeResetButtonR);
+ buttonReset4.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (MainActivity.csLibrary4A.isBleConnected() == false) {
+ Toast.makeText(MainActivity.mContext, R.string.toast_ble_not_connected, Toast.LENGTH_SHORT).show();
+ return;
+ } else if (MainActivity.csLibrary4A.isBarcodeFailure()) {
+ Toast.makeText(MainActivity.mContext, "Barcode is disabled", Toast.LENGTH_SHORT).show();
+ return;
+ } else {
+ MainActivity.csLibrary4A.setBarcodeOn(true);
+ MainActivity.csLibrary4A.barcodeSendCommandResetPreSuffix();
+ Toast.makeText(MainActivity.mContext, R.string.toast_saved, Toast.LENGTH_SHORT).show();
+ }
+ }
+ });
+
+ Button buttonReset1 = (Button) getActivity().findViewById(R.id.settingAdminReaderResetButton);
+ buttonReset1.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (MainActivity.csLibrary4A.isBleConnected() == false) {
+ Toast.makeText(MainActivity.mContext, R.string.toast_ble_not_connected, Toast.LENGTH_SHORT).show();
+ return;
+ } else if (false && MainActivity.csLibrary4A.isRfidFailure()) {
+ Toast.makeText(MainActivity.mContext, "Rfid is disabled", Toast.LENGTH_SHORT).show();
+ return;
+ } else {
+ MainActivity.csLibrary4A.setReaderDefault();
+ MainActivity.csLibrary4A.saveSetting2File();
+ Toast.makeText(MainActivity.mContext, R.string.toast_saved, Toast.LENGTH_SHORT).show();
+
+ mHandler.post(updateRunnable);
+ CustomPopupWindow customPopupWindow = new CustomPopupWindow(MainActivity.mContext);
+ String stringInfo = "Please power cycle reader and also this application";
+ customPopupWindow.popupStart(stringInfo, false);
+ }
+ }
+ });
+
+ button = (Button) getActivity().findViewById(R.id.settingSaveButtonAdmin);
+ button.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ boolean validValue = false;
+ if (MainActivity.csLibrary4A.isBleConnected() == false) {
+ Toast.makeText(MainActivity.mContext, R.string.toast_ble_not_connected, Toast.LENGTH_SHORT).show();
+ return;
+ } else if (false && MainActivity.csLibrary4A.isRfidFailure()) {
+ Toast.makeText(MainActivity.mContext, "Rfid is disabled", Toast.LENGTH_SHORT).show();
+ return;
+ } else if (updateRunning) {
+ Toast.makeText(MainActivity.mContext, R.string.toast_not_ready, Toast.LENGTH_SHORT).show();
+ return;
+ } else {
+ try {
+ deviceName = editTextDeviceName.getText().toString();
+ batteryDisplaySelect = spinnerQueryBattery.getSelectedItemPosition();
+ rssiDisplaySelect = spinnerQueryRssi.getSelectedItemPosition();
+ vibrateModeSelect = spinnerQueryVibrateMode.getSelectedItemPosition();
+ savingFormatSelect = spinnerSavingFormat.getSelectedItemPosition();
+ {
+ csvColumnSelect = 0;
+ if (checkBoxCsvColumnResBank.isChecked()) csvColumnSelect |= (0x01 << RfidReaderChipData.CsvColumn.RESERVE_BANK.ordinal());
+ if (checkBoxCsvColumnEpcBank.isChecked()) csvColumnSelect |= (0x01 << RfidReaderChipData.CsvColumn.EPC_BANK.ordinal());
+ if (checkBoxCsvColumnTidBank.isChecked()) csvColumnSelect |= (0x01 << RfidReaderChipData.CsvColumn.TID_BANK.ordinal());
+ if (checkBoxCsvColumnUserBank.isChecked()) csvColumnSelect |= (0x01 << RfidReaderChipData.CsvColumn.USER_BANK.ordinal());
+ if (checkBoxCsvColumnPhase.isChecked()) csvColumnSelect |= (0x01 << RfidReaderChipData.CsvColumn.PHASE.ordinal());
+ if (checkBoxCsvColumnChannel.isChecked()) csvColumnSelect |= (0x01 << RfidReaderChipData.CsvColumn.CHANNEL.ordinal());
+ if (checkBoxCsvColumnTime.isChecked()) csvColumnSelect |= (0x01 << RfidReaderChipData.CsvColumn.TIME.ordinal());
+ if (checkBoxCsvColumnTimeZone.isChecked()) csvColumnSelect |= (0x01 << RfidReaderChipData.CsvColumn.TIMEZONE.ordinal());
+ if (checkBoxCsvColumnLocation.isChecked()) csvColumnSelect |= (0x01 << RfidReaderChipData.CsvColumn.LOCATION.ordinal());
+ if (checkBoxCsvColumnDirection.isChecked()) csvColumnSelect |= (0x01 << RfidReaderChipData.CsvColumn.DIRECTION.ordinal());
+ if (checkBoxCsvColumnOthers.isChecked()) csvColumnSelect |= (0x01 << RfidReaderChipData.CsvColumn.OTHERS.ordinal());
+ }
+ if (editTextCycleDelay != null) cycleDelay = Long.parseLong(editTextCycleDelay.getText().toString());
+ if (editTextTriggerReportingCount != null) sTriggerCount = Short.parseShort(editTextTriggerReportingCount.getText().toString());
+ if (editTextBeepCount != null) iBeepCount = Integer.parseInt(editTextBeepCount.getText().toString());
+ if (editTextVibrateTime != null) iVibrateTime = Integer.parseInt(editTextVibrateTime.getText().toString());
+ if (editTextVibrateWindow != null) iVibrateWindow = Integer.parseInt(editTextVibrateWindow.getText().toString());
+ triggerReporting = checkBoxTriggerReporting.isChecked();
+ inventoryBeep = checkBoxInventoryBeep.isChecked();
+ inventoryVibrate = checkBoxInventoryVibrate.isChecked();
+ saveFileEnable = checkBoxSaveFileEnable.isChecked();
+ saveCloudEnable = checkBoxSaveCloudEnable.isChecked();
+ saveNewCloudEnable = checkBoxSaveNewCloudEnable.isChecked();
+ saveAllCloudEnable = checkBoxSaveAllCloudEnable.isChecked();
+ serverName = editTextServer.getText().toString();
+ iServerTimeout = Integer.parseInt(editTextServerTimeout.getText().toString());
+ serverMqtt = editTextServerMqtt.getText().toString();
+ topicMqtt = editTextTopicMqtt.getText().toString();
+ iForegroundDupElimNew = Integer.parseInt(editTextForegroundDupElim.getText().toString());
+ buttonCloudSave = 0;
+ if (radioButtonCloudSaveNone.isChecked()) buttonCloudSave = 0;
+ else if (radioButtonCloudSaveHttp.isChecked()) buttonCloudSave = 1;
+ else if (radioButtonCloudSaveMqtt.isChecked()) buttonCloudSave = 2;
+ serverImpinj = editTextServerImpinj.getText().toString();
+ serverImpinjName = editTextServerImpinjName.getText().toString();
+ serverImpinjPasword = editTextServerImpinjPasword.getText().toString();
+ debugEnable = checkBoxDebugEnable.isChecked();
+ foregroundServiceEnable = checkBoxForegroundService.isChecked();
+ settingUpdate();
+ } catch (Exception ex) {
+ Toast.makeText(MainActivity.mContext, R.string.toast_invalid_range, Toast.LENGTH_SHORT).show();
+ }
+ }
+ }
+ });
+
+ checkBoxDebugEnable = (CheckBox) getActivity().findViewById(R.id.settingAdminDebugEnable);
+ checkBoxForegroundService = (CheckBox) getActivity().findViewById(R.id.settingAdminForegroundEnable);
+
+ if (!MainActivity.foregroundServiceEnable) {
+ LinearLayout linearLayout = (LinearLayout) getActivity().findViewById(R.id.settingAdminForegroundLayout);
+ linearLayout.setVisibility(View.GONE);
+ }
+ if (sameCheck == false) MainActivity.csLibrary4A.setSameCheck(false);
+ mHandler.post(updateRunnable);
+ }
+
+ @Override
+ public void onDestroy() {
+ if (settingTask != null) settingTask.cancel(true);
+ MainActivity.csLibrary4A.setSameCheck(true);
+ mHandler.removeCallbacks(updateRunnable);
+ super.onDestroy();
+ }
+
+ @Override
+ public void setUserVisibleHint(boolean isVisibleToUser) {
+ super.setUserVisibleHint(isVisibleToUser);
+ if(isVisibleToUser) {
+ checkBoxTriggerReporting.setChecked(MainActivity.csLibrary4A.getTriggerReporting());
+ checkBoxInventoryBeep.setChecked(MainActivity.csLibrary4A.getInventoryBeep());
+ checkBoxInventoryVibrate.setChecked(MainActivity.csLibrary4A.getInventoryVibrate());
+ checkBoxSaveFileEnable.setChecked(MainActivity.csLibrary4A.getSaveFileEnable());
+ checkBoxSaveCloudEnable.setChecked(MainActivity.csLibrary4A.getSaveCloudEnable());
+ checkBoxSaveNewCloudEnable.setChecked(MainActivity.csLibrary4A.getSaveNewCloudEnable());
+ checkBoxSaveAllCloudEnable.setChecked(MainActivity.csLibrary4A.getSaveAllCloudEnable());
+ checkBoxDebugEnable.setChecked(MainActivity.csLibrary4A.getUserDebugEnable());
+ checkBoxForegroundService.setChecked(MainActivity.csLibrary4A.getForegroundServiceEnable());
+ }
+ }
+
+ public SettingAdminFragment() {
+ super("SettingAdminFragment");
+ }
+
+ boolean updateRunning = false;
+ private final Runnable updateRunnable = new Runnable() {
+ @Override
+ public void run() {
+ int iValue;
+ long lValue;
+ boolean updating = false;
+
+ updateRunning = true;
+ spinnerQueryBattery.setSelection(MainActivity.csLibrary4A.getBatteryDisplaySetting());
+ spinnerQueryRssi.setSelection(MainActivity.csLibrary4A.getRssiDisplaySetting());
+ spinnerQueryVibrateMode.setSelection(MainActivity.csLibrary4A.getVibrateModeSetting());
+ spinnerSavingFormat.setSelection(MainActivity.csLibrary4A.getSavingFormatSetting());
+ {
+ int csvColumnSelect = MainActivity.csLibrary4A.getCsvColumnSelectSetting();
+ if ((csvColumnSelect & (0x01 << RfidReaderChipData.CsvColumn.RESERVE_BANK.ordinal())) != 0) checkBoxCsvColumnResBank.setChecked(true); else checkBoxCsvColumnResBank.setChecked(false);
+ if ((csvColumnSelect & (0x01 << RfidReaderChipData.CsvColumn.EPC_BANK.ordinal())) != 0) checkBoxCsvColumnEpcBank.setChecked(true); else checkBoxCsvColumnEpcBank.setChecked(false);
+ if ((csvColumnSelect & (0x01 << RfidReaderChipData.CsvColumn.TID_BANK.ordinal())) != 0) checkBoxCsvColumnTidBank.setChecked(true); else checkBoxCsvColumnTidBank.setChecked(false);
+ if ((csvColumnSelect & (0x01 << RfidReaderChipData.CsvColumn.USER_BANK.ordinal())) != 0) checkBoxCsvColumnUserBank.setChecked(true); else checkBoxCsvColumnUserBank.setChecked(false);
+ if ((csvColumnSelect & (0x01 << RfidReaderChipData.CsvColumn.PHASE.ordinal())) != 0) checkBoxCsvColumnPhase.setChecked(true); else checkBoxCsvColumnPhase.setChecked(false);
+ if ((csvColumnSelect & (0x01 << RfidReaderChipData.CsvColumn.CHANNEL.ordinal())) != 0) checkBoxCsvColumnChannel.setChecked(true); else checkBoxCsvColumnChannel.setChecked(false);
+ if ((csvColumnSelect & (0x01 << RfidReaderChipData.CsvColumn.TIME.ordinal())) != 0) checkBoxCsvColumnTime.setChecked(true); else checkBoxCsvColumnTime.setChecked(false);
+ if ((csvColumnSelect & (0x01 << RfidReaderChipData.CsvColumn.TIMEZONE.ordinal())) != 0) checkBoxCsvColumnTimeZone.setChecked(true); else checkBoxCsvColumnTimeZone.setChecked(false);
+ if ((csvColumnSelect & (0x01 << RfidReaderChipData.CsvColumn.LOCATION.ordinal())) != 0) checkBoxCsvColumnLocation.setChecked(true); else checkBoxCsvColumnLocation.setChecked(false);
+ if ((csvColumnSelect & (0x01 << RfidReaderChipData.CsvColumn.DIRECTION.ordinal())) != 0) checkBoxCsvColumnDirection.setChecked(true); else checkBoxCsvColumnDirection.setChecked(false);
+ if ((csvColumnSelect & (0x01 << RfidReaderChipData.CsvColumn.OTHERS.ordinal())) != 0) checkBoxCsvColumnOthers.setChecked(true); else checkBoxCsvColumnOthers.setChecked(false);
+ }
+ if (editTextCycleDelay != null) editTextCycleDelay.setText(String.valueOf(MainActivity.csLibrary4A.getCycleDelay()));
+ if (editTextTriggerReportingCount != null) {
+ int triggerReportingCount = MainActivity.csLibrary4A.getTriggerReportingCount();
+ if (triggerReportingCount != MainActivity.csLibrary4A.iNO_SUCH_SETTING) {
+ TableRow tableRow = (TableRow) getActivity().findViewById(R.id.settingAdminTriggerReportingRow);
+ tableRow.setVisibility(View.VISIBLE);
+ }
+ editTextTriggerReportingCount.setText(String.valueOf(triggerReportingCount));
+ }
+ if (editTextBeepCount != null) editTextBeepCount.setText(String.valueOf(MainActivity.csLibrary4A.getBeepCount()));
+ if (editTextVibrateTime != null) editTextVibrateTime.setText(String.valueOf(MainActivity.csLibrary4A.getVibrateTime()));
+ if (editTextVibrateWindow != null) editTextVibrateWindow.setText(String.valueOf(MainActivity.csLibrary4A.getVibrateWindow()));
+ editTextServer.setText(MainActivity.csLibrary4A.getServerLocation());
+ editTextServerTimeout.setText(String.valueOf(MainActivity.csLibrary4A.getServerTimeout()));
+ editTextServerMqtt.setText(MainActivity.csLibrary4A.getServerMqttLocation());
+ editTextTopicMqtt.setText(MainActivity.csLibrary4A.getTopicMqtt());
+ editTextForegroundDupElim.setText(String.valueOf(MainActivity.csLibrary4A.getForegroundDupElim()));
+ int inventoryCloudSave = MainActivity.csLibrary4A.getInventoryCloudSave();
+ if (inventoryCloudSave == 0) radioButtonCloudSaveNone.setChecked(true);
+ else if (inventoryCloudSave == 1) radioButtonCloudSaveHttp.setChecked(true);
+ else if (inventoryCloudSave == 2) radioButtonCloudSaveMqtt.setChecked(true);
+ editTextServerImpinj.setText(MainActivity.csLibrary4A.getServerImpinjLocation());
+ editTextServerImpinjName.setText(MainActivity.csLibrary4A.getServerImpinjName());
+ editTextServerImpinjPasword.setText(MainActivity.csLibrary4A.getServerImpinjPassword());
+ if (updating == false) {
+ String name = MainActivity.csLibrary4A.getBluetoothICFirmwareName();
+ if (name == null) {
+ MainActivity.csLibrary4A.appendToLog("updating 1");
+ updating = true;
+ }
+ else if (name.length() == 0) {
+ MainActivity.csLibrary4A.appendToLog("updating 2");
+ updating = true;
+ }
+ else editTextDeviceName.setText(name);
+ }
+ if (updating == false) {
+ String name = MainActivity.csLibrary4A.getModelNumber();
+ if (name == null) {
+ MainActivity.csLibrary4A.appendToLog("updating 3");
+ updating = true;
+ }
+ else if (name.length() == 0) {
+ MainActivity.csLibrary4A.appendToLog("updating 4");
+ updating = true;
+ }
+ else textViewReaderModel.setText(name);
+ }
+ if (updating) {
+ mHandler.postDelayed(updateRunnable, 1000);
+ } else updateRunning = false;
+ }
+ };
+
+ void settingUpdate() {
+ boolean sameSetting = true;
+ boolean invalidRequest = false;
+
+ if (invalidRequest == false && (MainActivity.csLibrary4A.getBluetoothICFirmwareName().matches(deviceName) == false || sameCheck == false)) {
+ sameSetting = false;
+ if (MainActivity.csLibrary4A.setBluetoothICFirmwareName(deviceName) == false)
+ invalidRequest = true;
+ }
+ if (invalidRequest == false && (MainActivity.csLibrary4A.getBatteryDisplaySetting() != batteryDisplaySelect || sameCheck == false)) {
+ sameSetting = false;
+ if (MainActivity.csLibrary4A.setBatteryDisplaySetting(batteryDisplaySelect) == false)
+ invalidRequest = true;
+ }
+ if (invalidRequest == false && (MainActivity.csLibrary4A.getRssiDisplaySetting() != rssiDisplaySelect || sameCheck == false)) {
+ sameSetting = false;
+ if (MainActivity.csLibrary4A.setRssiDisplaySetting(rssiDisplaySelect) == false)
+ invalidRequest = true;
+ }
+ if (invalidRequest == false && (MainActivity.csLibrary4A.getVibrateModeSetting() != vibrateModeSelect || sameCheck == false)) {
+ sameSetting = false;
+ if (MainActivity.csLibrary4A.setVibrateModeSetting(vibrateModeSelect) == false)
+ invalidRequest = true;
+ }
+ if (invalidRequest == false && (MainActivity.csLibrary4A.getSavingFormatSetting() != savingFormatSelect || sameCheck == false)) {
+ sameSetting = false;
+ if (MainActivity.csLibrary4A.setSavingFormatSetting(savingFormatSelect) == false)
+ invalidRequest = true;
+ }
+ if (invalidRequest == false && (MainActivity.csLibrary4A.getCsvColumnSelectSetting() != csvColumnSelect || sameCheck == false)) {
+ sameSetting = false;
+ if (MainActivity.csLibrary4A.setCsvColumnSelectSetting(csvColumnSelect) == false)
+ invalidRequest = true;
+ }
+ if (invalidRequest == false && editTextCycleDelay != null) {
+ if (MainActivity.csLibrary4A.getCycleDelay() != cycleDelay || sameCheck == false) {
+ sameSetting = false;
+ if (cycleDelay < cycleDelayMin || cycleDelay > cycleDelayMax) invalidRequest = true;
+ else if (MainActivity.csLibrary4A.setCycleDelay(cycleDelay) == false)
+ invalidRequest = true;
+ }
+ }
+ if (invalidRequest == false && editTextTriggerReportingCount != null) {
+ if (MainActivity.csLibrary4A.getTriggerReportingCount() != sTriggerCount || sameCheck == false) {
+ sameSetting = false;
+ if (sTriggerCount < sTriggerCountMin || sTriggerCount > sTriggerCountMax) invalidRequest = true;
+ else if (MainActivity.csLibrary4A.setTriggerReportingCount(sTriggerCount) == false)
+ invalidRequest = true;
+ }
+ }
+ if (invalidRequest == false && editTextBeepCount != null) {
+ if (MainActivity.csLibrary4A.getBeepCount() != iBeepCount || sameCheck == false) {
+ sameSetting = false;
+ if (iBeepCount < iBeepCountMin || iBeepCount > iBeepCountMax) invalidRequest = true;
+ else if (MainActivity.csLibrary4A.setBeepCount(iBeepCount) == false)
+ invalidRequest = true;
+ }
+ }
+ if (invalidRequest == false && editTextVibrateTime != null) {
+ if (MainActivity.csLibrary4A.getVibrateTime() != iVibrateTime || sameCheck == false) {
+ sameSetting = false;
+ if (iVibrateTime < iVibrateTimeMin || iVibrateTime > iVibrateTimeMax) invalidRequest = true;
+ else if (MainActivity.csLibrary4A.setVibrateTime(iVibrateTime) == false)
+ invalidRequest = true;
+ }
+ }
+ if (invalidRequest == false && editTextVibrateWindow != null) {
+ if (MainActivity.csLibrary4A.getVibrateWindow() != iVibrateWindow || sameCheck == false) {
+ sameSetting = false;
+ if (iVibrateWindow < iVibrateWindowMin || iVibrateWindow > iVibrateWindowMax) invalidRequest = true;
+ else if (MainActivity.csLibrary4A.setVibrateWindow(iVibrateWindow) == false)
+ invalidRequest = true;
+ }
+ }
+ if (invalidRequest == false && checkBoxInventoryVibrate != null) {
+ MainActivity.csLibrary4A.appendToLog("getInventoryVibrate = " + MainActivity.csLibrary4A.getInventoryVibrate() + ", inventoryVibrate = " + inventoryVibrate);
+ if (MainActivity.csLibrary4A.getInventoryVibrate() != inventoryVibrate || sameCheck == false) {
+ sameSetting = false;
+ if (MainActivity.csLibrary4A.setInventoryVibrate(inventoryVibrate) == false)
+ invalidRequest = true;
+ }
+ }
+ if (invalidRequest == false && checkBoxTriggerReporting != null) {
+ if (MainActivity.csLibrary4A.getTriggerReporting() != triggerReporting || sameCheck == false) {
+ sameSetting = false;
+ if (MainActivity.csLibrary4A.setTriggerReporting(triggerReporting) == false)
+ invalidRequest = true;
+ }
+ }
+ if (invalidRequest == false && checkBoxInventoryBeep != null) {
+ MainActivity.csLibrary4A.appendToLog("getInventoryBeep = " + MainActivity.csLibrary4A.getInventoryBeep() + ", inventoryBeep = " + inventoryBeep);
+ if (MainActivity.csLibrary4A.getInventoryBeep() != inventoryBeep || sameCheck == false) {
+ sameSetting = false;
+ if (MainActivity.csLibrary4A.setInventoryBeep(inventoryBeep) == false)
+ invalidRequest = true;
+ }
+ }
+ if (invalidRequest == false && checkBoxSaveFileEnable != null) {
+ MainActivity.csLibrary4A.appendToLog("getSaveFileEnable = " + MainActivity.csLibrary4A.getSaveFileEnable() + ", saveFileEnable = " + saveFileEnable);
+ if (MainActivity.csLibrary4A.getSaveFileEnable() != saveFileEnable || sameCheck == false) {
+ sameSetting = false;
+ if (MainActivity.csLibrary4A.setSaveFileEnable(saveFileEnable) == false)
+ invalidRequest = true;
+ }
+ }
+ if (invalidRequest == false && checkBoxSaveCloudEnable != null) {
+ MainActivity.csLibrary4A.appendToLog("getSaveCloudEnable = " + MainActivity.csLibrary4A.getSaveCloudEnable() + ", saveCloudEnable = " + saveCloudEnable);
+ if (MainActivity.csLibrary4A.getSaveCloudEnable() != saveCloudEnable || sameCheck == false) {
+ sameSetting = false;
+ if (MainActivity.csLibrary4A.setSaveCloudEnable(saveCloudEnable) == false)
+ invalidRequest = true;
+ }
+ }
+ if (invalidRequest == false && checkBoxSaveNewCloudEnable != null) {
+ MainActivity.csLibrary4A.appendToLog("getSaveNewCloudEnable = " + MainActivity.csLibrary4A.getSaveNewCloudEnable() + ", saveNewCloudEnable = " + saveNewCloudEnable);
+ if (MainActivity.csLibrary4A.getSaveNewCloudEnable() != saveNewCloudEnable || sameCheck == false) {
+ sameSetting = false;
+ if (MainActivity.csLibrary4A.setSaveNewCloudEnable(saveNewCloudEnable) == false)
+ invalidRequest = true;
+ }
+ }
+ if (invalidRequest == false && checkBoxSaveAllCloudEnable != null) {
+ MainActivity.csLibrary4A.appendToLog("getSaveAllCloudEnable = " + MainActivity.csLibrary4A.getSaveAllCloudEnable() + ", saveAllCloudEnable = " + saveAllCloudEnable);
+ if (MainActivity.csLibrary4A.getSaveAllCloudEnable() != saveAllCloudEnable || sameCheck == false) {
+ sameSetting = false;
+ if (MainActivity.csLibrary4A.setSaveAllCloudEnable(saveAllCloudEnable) == false)
+ invalidRequest = true;
+ }
+ }
+ if (invalidRequest == false && editTextServer != null) {
+ String serverLocation = MainActivity.csLibrary4A.getServerLocation(); if (serverLocation == null) serverLocation = "";
+ if (serverLocation.matches(serverName) == false || sameCheck == false) {
+ sameSetting = false;
+ if (MainActivity.csLibrary4A.setServerLocation(serverName) == false)
+ invalidRequest = true;
+ }
+ }
+ if (invalidRequest == false && editTextServerTimeout != null) {
+ if (MainActivity.csLibrary4A.getServerTimeout() != iServerTimeout || sameCheck == false) {
+ sameSetting = false;
+ if (iServerTimeout < iServerTimeoutMin || iServerTimeout > iServerTimeoutMax) invalidRequest = true;
+ else if (MainActivity.csLibrary4A.setServerTimeout(iServerTimeout) == false)
+ invalidRequest = true;
+ }
+ }
+ if (invalidRequest == false && editTextServerMqtt != null) {
+ String serverLocation = MainActivity.csLibrary4A.getServerMqttLocation(); if (serverLocation == null) serverLocation = "";
+ if (serverLocation.matches(serverMqtt) == false || sameCheck == false) {
+ sameSetting = false;
+ if (MainActivity.csLibrary4A.setServerMqttLocation(serverMqtt) == false)
+ invalidRequest = true;
+ }
+ }
+ if (invalidRequest == false && editTextTopicMqtt != null) {
+ String topic = MainActivity.csLibrary4A.getTopicMqtt(); if (topic == null) topic = "";
+ if (topic.matches(topicMqtt) == false || sameCheck == false) {
+ sameSetting = false;
+ if (MainActivity.csLibrary4A.setTopicMqtt(topicMqtt) == false)
+ invalidRequest = true;
+ }
+ }
+ if (invalidRequest == false && editTextForegroundDupElim != null) {
+ int iForegroundDupElim = MainActivity.csLibrary4A.getForegroundDupElim(); if (iForegroundDupElim < 0) iForegroundDupElim = 0;
+ if (iForegroundDupElim != iForegroundDupElimNew || sameCheck == false) {
+ sameSetting = false;
+ if (MainActivity.csLibrary4A.setForegroundDupElim(iForegroundDupElimNew) == false)
+ invalidRequest = true;
+ }
+ }
+ if (invalidRequest == false && radioButtonCloudSaveNone != null && radioButtonCloudSaveHttp != null && radioButtonCloudSaveMqtt != null) {
+ int inventoryCloudSave = MainActivity.csLibrary4A.getInventoryCloudSave();
+ if (inventoryCloudSave != buttonCloudSave || sameCheck == false) {
+ sameSetting = false;
+ if (MainActivity.csLibrary4A.setInventoryCloudSave(buttonCloudSave) == false)
+ invalidRequest = true;
+ }
+ }
+ if (invalidRequest == false && editTextServerImpinj != null) {
+ String string = MainActivity.csLibrary4A.getServerImpinjLocation(); if (string == null) string = "";
+ MainActivity.csLibrary4A.appendToLog("old serverImpinj = " + string + ", new = " + serverImpinj);
+ if (string.matches(serverImpinj) == false || sameCheck == false) {
+ sameSetting = false;
+ if (MainActivity.csLibrary4A.setServerImpinjLocation(serverImpinj) == false)
+ invalidRequest = true;
+ }
+ }
+ if (invalidRequest == false && editTextServerImpinjName != null) {
+ String string = MainActivity.csLibrary4A.getServerImpinjName(); if (string == null) string = "";
+ MainActivity.csLibrary4A.appendToLog("old serverImpinjName = " + string + ", new = " + serverImpinjName);
+ if (string.matches(serverImpinjName) == false || sameCheck == false) {
+ sameSetting = false;
+ if (MainActivity.csLibrary4A.setServerImpinjName(serverImpinjName) == false)
+ invalidRequest = true;
+ }
+ }
+ if (invalidRequest == false && editTextServerImpinjPasword != null) {
+ String string = MainActivity.csLibrary4A.getServerImpinjPassword(); if (string == null) string = "";
+ MainActivity.csLibrary4A.appendToLog("old serverImpinjPassword = " + string + ", new = " + serverImpinjPasword + ", matched = " + string.matches(serverImpinjPasword));
+ if (string.length() != serverImpinjPasword.length() || string.matches(serverImpinjPasword) == false || sameCheck == false) {
+ sameSetting = false;
+ if (MainActivity.csLibrary4A.setServerImpinjPassword(serverImpinjPasword) == false)
+ invalidRequest = true;
+ }
+ }
+ if (invalidRequest == false && checkBoxDebugEnable != null) {
+ MainActivity.csLibrary4A.appendToLog("getDebugEnable = " + MainActivity.csLibrary4A.getUserDebugEnable() + ", debugEnable = " + debugEnable);
+ if (MainActivity.csLibrary4A.getUserDebugEnable() != debugEnable || sameCheck == false) {
+ sameSetting = false;
+ if (MainActivity.csLibrary4A.setUserDebugEnable(debugEnable) == false)
+ invalidRequest = true;
+ }
+ }
+ if (invalidRequest == false && checkBoxForegroundService != null && MainActivity.foregroundServiceEnable) {
+ MainActivity.csLibrary4A.appendToLog("getForegroundServiceEnable = " + MainActivity.csLibrary4A.getForegroundServiceEnable() + ", foregroundServiceEnable = " + foregroundServiceEnable);
+ if (MainActivity.csLibrary4A.getForegroundServiceEnable() != foregroundServiceEnable || sameCheck == false) {
+ sameSetting = false;
+ MainActivity.csLibrary4A.appendToLog("foregroundReader108: updated 2C");
+ if (MainActivity.csLibrary4A.setForegroundServiceEnable(foregroundServiceEnable) == false)
+ invalidRequest = true;
+ }
+ }
+ settingTask = new SettingTask(button, sameSetting, invalidRequest);
+ settingTask.execute();
+ MainActivity.csLibrary4A.saveSetting2File();
+ }
+}
+
+
+
+package com.csl.cs710ademoapp.fragments;
+
+import android.os.Bundle;
+import android.util.Log;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+
+import androidx.appcompat.app.ActionBar;
+import androidx.appcompat.app.AppCompatActivity;
+import androidx.viewpager.widget.ViewPager;
+
+import com.csl.cs710ademoapp.R;
+import com.csl.cslibrary4a.AdapterTab;
+import com.google.android.material.tabs.TabLayout;
+
+public class SettingFilterFragment extends CommonFragment {
+ private ActionBar actionBar;
+ private ViewPager viewPager;
+ AdapterTab adapter;
+
+ private String[] tabs = {"Pre-filter", "Post-filter", "Rssi-filter"};
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ super.onCreateView(inflater, container, savedInstanceState, true);
+ return inflater.inflate(R.layout.custom_tabbed_layout, container, false);
+ }
+
+ @Override
+ public void onActivityCreated(Bundle savedInstanceState) {
+ super.onActivityCreated(savedInstanceState);
+
+ actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
+ actionBar.setIcon(R.drawable.dl_filters);
+ actionBar.setTitle(R.string.title_activity_filters);
+
+ TabLayout tabLayout = (TabLayout) getActivity().findViewById(R.id.OperationsTabLayout);
+
+ adapter = new AdapterTab(getActivity().getSupportFragmentManager(), tabs.length);
+ adapter.setFragment(0, new SettingFilterPreFragment());
+ adapter.setFragment(1, new SettingFilterPostFragment());
+ adapter.setFragment(2, new SettingFilterRssiFragment());
+
+ viewPager = (ViewPager) getActivity().findViewById(R.id.OperationsPager);
+ viewPager.setAdapter(adapter);
+ viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
+
+ for (String tab_name : tabs) {
+ tabLayout.addTab(tabLayout.newTab().setText(tab_name));
+ }
+
+ tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
+ @Override
+ public void onTabSelected(TabLayout.Tab tab) {
+ Log.i(TAG, "tab.position is " + tab.getPosition());
+ viewPager.setCurrentItem(tab.getPosition());
+ }
+
+ @Override
+ public void onTabUnselected(TabLayout.Tab tab) {
+ }
+
+ @Override
+ public void onTabReselected(TabLayout.Tab tab) {
+ }
+ });
+ }
+
+ @Override
+ public void onPause() {
+ adapter.fragment0.onPause();
+ adapter.fragment1.onPause();
+ super.onPause();
+ }
+
+ @Override
+ public void onStop() {
+ adapter.fragment0.onStop();
+ adapter.fragment1.onStop();
+ super.onStop();
+ }
+
+ @Override
+ public void onDestroyView() {
+ adapter.fragment0.onDestroyView();
+ adapter.fragment1.onDestroyView();
+ super.onDestroyView();
+ }
+
+ @Override
+ public void onDestroy() {
+ adapter.fragment0.onDestroy();
+ adapter.fragment1.onDestroy();
+ super.onDestroy();
+ }
+
+ @Override
+ public void onDetach() {
+ adapter.fragment0.onDetach();
+ adapter.fragment1.onDetach();
+ super.onDetach();
+ }
+
+ public SettingFilterFragment() {
+ super("SettingFilterFragment");
+ }
+}
+
+
+
+package com.csl.cs710ademoapp.fragments;
+
+import android.os.Bundle;
+import android.os.Handler;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.Button;
+import android.widget.CheckBox;
+import android.widget.EditText;
+import android.widget.Toast;
+
+import com.csl.cs710ademoapp.MainActivity;
+import com.csl.cs710ademoapp.R;
+import com.csl.cs710ademoapp.SettingTask;
+
+public class SettingFilterPostFragment extends CommonFragment {
+ private CheckBox checkBoxEnable;
+ private CheckBox checkBoxType;
+ private EditText postFilterOffset;
+ private EditText filterPostMaskData;
+ private Button button;
+
+ final boolean sameCheck = false;
+ Handler mHandler = new Handler();
+
+ boolean invMatchEnable;
+ boolean invMatchType;
+ int invMatchOffset = -1;
+ String invMatchData = null;
+
+ private SettingTask settingTask;
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ super.onCreateView(inflater, container, savedInstanceState, false);
+ return inflater.inflate(R.layout.fragment_filterpost_content, container, false);
+ }
+
+ @Override
+ public void onActivityCreated(Bundle savedInstanceState) {
+ super.onActivityCreated(savedInstanceState);
+
+ checkBoxEnable = (CheckBox) getActivity().findViewById(R.id.filterPostCheckEnable);
+ checkBoxType = (CheckBox) getActivity().findViewById(R.id.filterPostCheckType);
+ postFilterOffset = (EditText) getActivity().findViewById(R.id.filterPostOffset);
+ filterPostMaskData = (EditText) getActivity().findViewById(R.id.filterPostMaskData);
+
+ button = (Button) getActivity().findViewById(R.id.filterPostSaveButton);
+ button.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ boolean validValue = false;
+ if (MainActivity.csLibrary4A.isBleConnected() == false) {
+ Toast.makeText(MainActivity.mContext, R.string.toast_ble_not_connected, Toast.LENGTH_SHORT).show();
+ return;
+ } else if (MainActivity.csLibrary4A.isRfidFailure()) {
+ Toast.makeText(MainActivity.mContext, "Rfid is disabled", Toast.LENGTH_SHORT).show();
+ return;
+ } else {
+ try {
+ invMatchEnable = checkBoxEnable.isChecked();
+ invMatchType = checkBoxType.isChecked();
+ invMatchOffset = Integer.parseInt(postFilterOffset.getText().toString());
+
+ settingUpdate();
+ } catch (Exception ex) {
+ Toast.makeText(MainActivity.mContext, R.string.toast_invalid_range, Toast.LENGTH_SHORT).show();
+ }
+ }
+ }
+ });
+
+ if (sameCheck == false) MainActivity.csLibrary4A.setSameCheck(false);
+ mHandler.post(updateRunnable);
+ }
+
+ @Override
+ public void onDestroy() {
+ if (settingTask != null) settingTask.cancel(true);
+ MainActivity.csLibrary4A.setSameCheck(true);
+ mHandler.removeCallbacks(updateRunnable);
+ super.onDestroy();
+ }
+
+ public SettingFilterPostFragment() {
+ super("SettingFilterPostFragment");
+ }
+
+ private final Runnable updateRunnable = new Runnable() {
+ @Override
+ public void run() {
+ int iValue;
+ long lValue;
+ boolean updating = false;
+
+ if (MainActivity.csLibrary4A.mrfidToWriteSize() != 0) updating = true;
+ else {
+ if (updating == false) {
+ checkBoxEnable.setChecked(MainActivity.csLibrary4A.getInvMatchEnable());
+ checkBoxType.setChecked(MainActivity.csLibrary4A.getInvMatchType());
+ }
+ if (updating == false) {
+ int iValue1 = MainActivity.csLibrary4A.getInvMatchOffset();
+ if (iValue1 < 0) {
+ updating = true;
+ } else {
+ postFilterOffset.setText(String.valueOf(iValue1));
+ }
+ }
+ if (updating == false && filterPostMaskData.getText().length() == 0) {
+ String strValue = MainActivity.csLibrary4A.getInvMatchData();
+ if (strValue == null) {
+ updating = true;
+ } else {
+ filterPostMaskData.setText(strValue);
+ }
+ }
+ }
+ if (updating) {
+ mHandler.postDelayed(updateRunnable, 1000);
+ }
+ }
+ };
+
+ void settingUpdate() {
+ boolean dataMatched = false;
+ invMatchData = filterPostMaskData.getText().toString();
+ String strValue = MainActivity.csLibrary4A.getInvMatchData();
+ boolean sameSetting = true;
+ boolean invalidRequest = false;
+
+ if (invMatchData.length() != strValue.length()) {
+ dataMatched = false;
+ } else if (invMatchData.length() == 0 && strValue.length() == 0) {
+ dataMatched = true;
+ } else dataMatched = invMatchData.matches(strValue);
+ if (MainActivity.csLibrary4A.getInvMatchEnable() != invMatchEnable
+ || MainActivity.csLibrary4A.getInvMatchType() != invMatchType
+ || MainActivity.csLibrary4A.getInvMatchOffset() != invMatchOffset
+ || dataMatched == false || sameCheck == false) {
+ sameSetting = false;
+ if (MainActivity.csLibrary4A.setPostMatchCriteria(invMatchEnable, invMatchType, invMatchOffset, invMatchData) == false)
+ invalidRequest = true;
+ }
+ settingTask = new SettingTask(button, sameSetting, invalidRequest);
+ settingTask.execute();
+ }
+}
+
+
+
+package com.csl.cs710ademoapp.fragments;
+
+import android.os.Bundle;
+import android.os.Handler;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.AdapterView;
+import android.widget.ArrayAdapter;
+import android.widget.Button;
+import android.widget.CheckBox;
+import android.widget.EditText;
+import android.widget.Spinner;
+import android.widget.Toast;
+
+import com.csl.cs710ademoapp.MainActivity;
+import com.csl.cs710ademoapp.R;
+import com.csl.cs710ademoapp.SettingTask;
+
+public class SettingFilterPreFragment extends CommonFragment {
+ private EditText editTextFilterPreSelectIndex;
+ private CheckBox checkBoxEnable;
+ private Spinner targetSpinner;
+ private Spinner actionSpinner;
+ private Spinner memoryBankSpinner;
+ private Spinner spinnerMaskDataType;
+ private EditText preFilterOffset;
+ private EditText filterPreMaskDataHex, filterPreMaskDataBit;
+ private Button button;
+
+ final boolean sameCheck = false;
+ Handler mHandler = new Handler();
+
+ int invSelectIndex = -1;
+ boolean invSelectEnable;
+ int invSelectTarget = -1;
+ int invSelectAction = -1;
+ int invSelectMaskBank = -1;
+ int invSelectMaskOffset = -1;
+ String invSelectMaskData = null;
+
+ private SettingTask settingTask;
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ super.onCreateView(inflater, container, savedInstanceState, false);
+ return inflater.inflate(R.layout.fragment_filterpre_content, container, false);
+ }
+
+ @Override
+ public void onActivityCreated(Bundle savedInstanceState) {
+ super.onActivityCreated(savedInstanceState);
+
+ editTextFilterPreSelectIndex = (EditText) getActivity().findViewById(R.id.filterPreSelectxIndex);
+ checkBoxEnable = (CheckBox) getActivity().findViewById(R.id.filterPreCheck);
+
+ targetSpinner = (Spinner) getActivity().findViewById(R.id.preFilterTarget);
+ ArrayAdapter targetAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.filterPre_target_options, R.layout.custom_spinner_layout);
+ targetAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+ targetSpinner.setAdapter(targetAdapter);
+ if (false) targetSpinner.setEnabled(false);
+
+ actionSpinner = (Spinner) getActivity().findViewById(R.id.preFilterAction);
+ ArrayAdapter actionAdapter;
+ if (true) { //MainActivity.csLibrary4A.getQuerySelect() >= 2) {
+ actionAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.filterPre_SLaction_options, R.layout.custom_spinner_layout);
+ } else {
+ actionAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.filterPre_SessionAction_options, R.layout.custom_spinner_layout);
+ }
+ actionAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+ actionSpinner.setAdapter(actionAdapter);
+ if (false) actionSpinner.setEnabled(false);
+
+ memoryBankSpinner = (Spinner) getActivity().findViewById(R.id.preFilterMemoryBank);
+ ArrayAdapter memoryBankAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.read_memoryBank_options, R.layout.custom_spinner_layout);
+ memoryBankAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+ memoryBankSpinner.setAdapter(memoryBankAdapter);
+ memoryBankSpinner.setEnabled(true);
+
+ spinnerMaskDataType = (Spinner) getActivity().findViewById(R.id.filterPreMaskDataType);
+ ArrayAdapter maskDataTypeAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.dataType_options, R.layout.custom_spinner_layout);
+ maskDataTypeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+ spinnerMaskDataType.setAdapter(maskDataTypeAdapter);
+ spinnerMaskDataType.setEnabled(true);
+ spinnerMaskDataType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
+ @Override
+ public void onItemSelected(AdapterView> adapterView, View view, int i, long l) {
+ if (spinnerMaskDataType.getSelectedItemPosition() == 0) {
+ filterPreMaskDataHex.setVisibility(View.VISIBLE);
+ filterPreMaskDataBit.setVisibility(View.GONE);
+ } else {
+ filterPreMaskDataHex.setVisibility(View.GONE);
+ filterPreMaskDataBit.setVisibility(View.VISIBLE);
+ }
+ }
+ @Override
+ public void onNothingSelected(AdapterView> adapterView) {
+ }
+ });
+
+ preFilterOffset = (EditText) getActivity().findViewById(R.id.filterPreOffset);
+ filterPreMaskDataHex = (EditText) getActivity().findViewById(R.id.filterPreMaskDataHex);
+ filterPreMaskDataBit = (EditText) getActivity().findViewById(R.id.filterPreMaskDataBit);
+
+ button = (Button) getActivity().findViewById(R.id.filterPreSaveButton);
+ button.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ boolean validValue = false;
+ if (MainActivity.csLibrary4A.isBleConnected() == false) {
+ Toast.makeText(MainActivity.mContext, R.string.toast_ble_not_connected, Toast.LENGTH_SHORT).show();
+ return;
+ } else if (MainActivity.csLibrary4A.isRfidFailure()) {
+ Toast.makeText(MainActivity.mContext, "Rfid is disabled", Toast.LENGTH_SHORT).show();
+ return;
+ } else {
+ try {
+ invSelectIndex = Integer.parseInt(editTextFilterPreSelectIndex.getText().toString());
+ invSelectEnable = checkBoxEnable.isChecked();
+ invSelectTarget = targetSpinner.getSelectedItemPosition();
+ invSelectAction = actionSpinner.getSelectedItemPosition();
+ invSelectMaskBank = memoryBankSpinner.getSelectedItemPosition() + 1;
+ invSelectMaskOffset = Integer.parseInt(preFilterOffset.getText().toString()); if (invSelectMaskBank == 1) invSelectMaskOffset += 32;
+
+ settingUpdate();
+ } catch (Exception ex) {
+ Toast.makeText(MainActivity.mContext, R.string.toast_invalid_range, Toast.LENGTH_SHORT).show();
+ }
+ }
+ }
+ });
+
+ if (sameCheck == false) MainActivity.csLibrary4A.setSameCheck(false);
+ mHandler.post(updateRunnable);
+ }
+
+ @Override
+ public void onDestroy() {
+ if (settingTask != null) settingTask.cancel(true);
+ MainActivity.csLibrary4A.setSameCheck(true);
+ mHandler.removeCallbacks(updateRunnable);
+ super.onDestroy();
+ }
+
+ public SettingFilterPreFragment() {
+ super("SettingFilterPreFragment");
+ }
+
+ private final Runnable updateRunnable = new Runnable() {
+ @Override
+ public void run() {
+ int iValue;
+ long lValue;
+ boolean updating = false;
+
+ if (MainActivity.csLibrary4A.mrfidToWriteSize() != 0) updating = true;
+ else {
+ if (updating == false && editTextFilterPreSelectIndex.getText().length() == 0) {
+ lValue = MainActivity.csLibrary4A.getInvSelectIndex();
+ MainActivity.csLibrary4A.appendToLog("updateRunnable getInvSelectIndex = " + lValue);
+ if (lValue < 0) {
+ updating = true;
+ } else {
+ editTextFilterPreSelectIndex.setText(String.valueOf(lValue));
+ }
+ }
+ if (updating == false) {
+ boolean bValue = MainActivity.csLibrary4A.getSelectEnable();
+ MainActivity.csLibrary4A.appendToLog("updateRunnable getSelectEnable = " + bValue);
+ checkBoxEnable.setChecked(bValue);
+ }
+ if (updating == false) {
+ int iValue1 = MainActivity.csLibrary4A.getSelectTarget();
+ MainActivity.csLibrary4A.appendToLog("updateRunnable getSelectTarget = " + iValue1);
+ if (iValue1 < 0) {
+ updating = true;
+ } else {
+ if (iValue1 > 4) iValue1 = 4;
+ iValue1 = 4; //fixed as SL
+ targetSpinner.setSelection(iValue1);
+ }
+ }
+ if (updating == false) {
+ int iValue1 = MainActivity.csLibrary4A.getSelectAction();
+ MainActivity.csLibrary4A.appendToLog("updateRunnable getSelectAction = " + iValue1);
+ if (iValue1 < 0) {
+ updating = true;
+ } else {
+ actionSpinner.setSelection(iValue1);
+ }
+ }
+ if (updating == false) {
+ int iValue1 = MainActivity.csLibrary4A.getSelectMaskBank();
+ MainActivity.csLibrary4A.appendToLog("updateRunnable getSelectMaskBank = " + iValue1);
+ if (iValue1 < 0) {
+ updating = true;
+ } else {
+ if (iValue1 < 1) iValue1 = 1;
+ iValue1--;
+ memoryBankSpinner.setSelection(iValue1);
+ }
+ }
+ if (updating == false) {
+ int iValue1 = MainActivity.csLibrary4A.getSelectMaskOffset();
+ MainActivity.csLibrary4A.appendToLog("updateRunnable getSelectMaskOffset = " + iValue1);
+ if (iValue1 < 0) {
+ updating = true;
+ } else {
+ if (iValue1 < 32) iValue1 = 32;
+ iValue1 -= 32;
+ preFilterOffset.setText(String.valueOf(iValue1));
+ }
+ }
+ if (updating == false) {
+ String strValue = MainActivity.csLibrary4A.getSelectMaskData();
+ MainActivity.csLibrary4A.appendToLog("updateRunnable getSelectMaskData = " + strValue);
+ if (strValue == null) {
+ updating = true;
+ } else {
+ spinnerMaskDataType.setSelection(0);
+ filterPreMaskDataHex.setText(strValue);
+ }
+ }
+ }
+ if (updating) {
+ mHandler.postDelayed(updateRunnable, 1000);
+ }
+ }
+ };
+
+ void settingUpdate() {
+ boolean sameSetting = true;
+ boolean invalidRequest = false;
+
+ if (MainActivity.csLibrary4A.getInvSelectIndex() != invSelectIndex) {
+ sameSetting = false;
+ if (MainActivity.csLibrary4A.setInvSelectIndex(invSelectIndex) == false)
+ invalidRequest = true;
+ else {
+ mHandler.removeCallbacks(updateRunnable);
+ mHandler.post(updateRunnable);
+ }
+ }
+ if (sameSetting == true && invalidRequest == false) {
+ if (true)
+ {
+ boolean dataMatched = false;
+ boolean maskbit = (spinnerMaskDataType.getSelectedItemPosition() == 0 ? false : true);
+ if (maskbit) invSelectMaskData = filterPreMaskDataBit.getText().toString();
+ else invSelectMaskData = filterPreMaskDataHex.getText().toString();
+ String strValue = MainActivity.csLibrary4A.getSelectMaskData();
+ if (invSelectMaskData.length() != strValue.length()) { }
+ else if (invSelectMaskData.length() == 0 && strValue.length() == 0) { dataMatched = true; }
+ else dataMatched = invSelectMaskData.matches(strValue);
+ if (MainActivity.csLibrary4A.getSelectEnable() != invSelectEnable
+ || MainActivity.csLibrary4A.getSelectTarget() != invSelectTarget
+ || MainActivity.csLibrary4A.getSelectAction() != invSelectAction
+ || MainActivity.csLibrary4A.getSelectMaskBank() != invSelectMaskBank
+ || MainActivity.csLibrary4A.getSelectMaskOffset() != invSelectMaskOffset
+ || dataMatched == false || sameCheck == false) {
+ sameSetting = false;
+ if (MainActivity.csLibrary4A.setSelectCriteria(0, invSelectEnable, invSelectTarget, invSelectAction, invSelectMaskBank, invSelectMaskOffset, invSelectMaskData, maskbit) == false)
+ invalidRequest = true;
+ }
+ }
+ }
+
+ settingTask = new SettingTask(button, sameSetting, invalidRequest);
+ settingTask.execute();
+ MainActivity.csLibrary4A.saveSetting2File();
+ }
+}
+
+
+
+package com.csl.cs710ademoapp.fragments;
+
+import android.os.Bundle;
+import android.os.Handler;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.ArrayAdapter;
+import android.widget.Button;
+import android.widget.CheckBox;
+import android.widget.EditText;
+import android.widget.Spinner;
+import android.widget.TextView;
+import android.widget.Toast;
+
+import com.csl.cs710ademoapp.MainActivity;
+import com.csl.cs710ademoapp.R;
+import com.csl.cs710ademoapp.SettingTask;
+
+public class SettingFilterRssiFragment extends CommonFragment {
+ private CheckBox checkBoxEnable;
+ private Spinner spinnerFilterType, spinnerFilterOption;
+ private EditText editTextFilterThreshold1, editTextFilterThreshold2, editTextFilterCount;
+ private Button button;
+
+ final boolean sameCheck = false;
+ Handler mHandler = new Handler();
+
+ boolean invSelectEnable;
+ int invSelectFilterType = -1, invSelectFilterOption = -1;
+ double invSelectFilterThreshold1 = -1, invSelectFilterThreshold2 = -1;
+ long invSelectFilterCount = -1;
+
+ private SettingTask settingTask;
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ super.onCreateView(inflater, container, savedInstanceState, false);
+ return inflater.inflate(R.layout.fragment_filterrssi_content, container, false);
+ }
+
+ @Override
+ public void onActivityCreated(Bundle savedInstanceState) {
+ super.onActivityCreated(savedInstanceState);
+
+ checkBoxEnable = (CheckBox) getActivity().findViewById(R.id.filterRssiCheck);
+
+ spinnerFilterType = (Spinner) getActivity().findViewById(R.id.filterRssiFilterType);
+ ArrayAdapter filterTypeAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.filterType_options, R.layout.custom_spinner_layout);
+ filterTypeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+ spinnerFilterType.setAdapter(filterTypeAdapter);
+ spinnerFilterType.setEnabled(false);
+
+ spinnerFilterOption = (Spinner) getActivity().findViewById(R.id.filterRssiFilterOption);
+ ArrayAdapter filterOptionAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.filter_options1, R.layout.custom_spinner_layout);
+ filterOptionAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+ spinnerFilterOption.setAdapter(filterOptionAdapter);
+
+ String strUnit = MainActivity.csLibrary4A.getRssiDisplaySetting() > 0 ? "(dBm)" : "(dBuV)";
+ TextView textViewThreshold1 = (TextView) getActivity().findViewById(R.id.filterRssiThreshold1Label);
+ textViewThreshold1.setText(textViewThreshold1.getText().toString() + strUnit);
+ TextView textViewThreshold2 = (TextView) getActivity().findViewById(R.id.filterRssiThreshold2Label);
+ textViewThreshold2.setText(textViewThreshold2.getText().toString() + strUnit);
+
+ editTextFilterThreshold1 = (EditText) getActivity().findViewById(R.id.filterRssiThreshold1);
+ editTextFilterThreshold2 = (EditText) getActivity().findViewById(R.id.filterRssiThreshold2);
+ editTextFilterCount = (EditText) getActivity().findViewById(R.id.filterRssiCount);
+
+ button = (Button) getActivity().findViewById(R.id.filterRssiSaveButton);
+ button.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ boolean validValue = false;
+ if (MainActivity.csLibrary4A.isBleConnected() == false) {
+ Toast.makeText(MainActivity.mContext, R.string.toast_ble_not_connected, Toast.LENGTH_SHORT).show();
+ return;
+ } else if (MainActivity.csLibrary4A.isRfidFailure()) {
+ Toast.makeText(MainActivity.mContext, "Rfid is disabled", Toast.LENGTH_SHORT).show();
+ return;
+ } else {
+ boolean bValid = false;
+ try {
+ invSelectEnable = checkBoxEnable.isChecked();
+ invSelectFilterType = spinnerFilterType.getSelectedItemPosition();
+ invSelectFilterOption = spinnerFilterOption.getSelectedItemPosition();
+ invSelectFilterThreshold1 = Float.parseFloat(editTextFilterThreshold1.getText().toString());
+ if (MainActivity.csLibrary4A.getRssiDisplaySetting() > 0) invSelectFilterThreshold1 += MainActivity.csLibrary4A.dBuV_dBm_constant;
+ invSelectFilterThreshold2 = Float.parseFloat(editTextFilterThreshold2.getText().toString());
+ if (MainActivity.csLibrary4A.getRssiDisplaySetting() > 0) invSelectFilterThreshold2 += MainActivity.csLibrary4A.dBuV_dBm_constant;
+ invSelectFilterCount = Integer.parseInt(editTextFilterCount.getText().toString());
+ bValid = true;
+ } catch (Exception ex) {
+ Toast.makeText(MainActivity.mContext, R.string.toast_invalid_range, Toast.LENGTH_SHORT).show();
+ }
+ if (bValid) settingUpdate();
+ }
+ }
+ });
+
+ if (sameCheck == false) MainActivity.csLibrary4A.setSameCheck(false);
+ mHandler.post(updateRunnable);
+ }
+
+ @Override
+ public void onDestroy() {
+ if (settingTask != null) settingTask.cancel(true);
+ MainActivity.csLibrary4A.setSameCheck(true);
+ mHandler.removeCallbacks(updateRunnable);
+ super.onDestroy();
+ }
+
+ public SettingFilterRssiFragment() {
+ super("SettingFilterRssiFragment");
+ }
+
+ private final Runnable updateRunnable = new Runnable() {
+ @Override
+ public void run() {
+ int iValue;
+ long lValue;
+ String updating = null;
+
+ if (MainActivity.csLibrary4A.mrfidToWriteSize() != 0) updating = "waiting empty buffer";
+ else {
+ if (updating == null) {
+ boolean bValue = MainActivity.csLibrary4A.getRssiFilterEnable();
+ MainActivity.csLibrary4A.appendToLog("0 updateRunnable getSelectEnable = " + bValue);
+ checkBoxEnable.setChecked(bValue);
+ }
+ if (updating == null) {
+ int iValue1 = MainActivity.csLibrary4A.getRssiFilterType();
+ MainActivity.csLibrary4A.appendToLog("1 updateRunnable getSelectAction = " + iValue1);
+ if (iValue1 < 0) updating = "getting filter type";
+ else spinnerFilterType.setSelection(iValue1);
+ }
+ if (updating == null) {
+ int iValue1 = MainActivity.csLibrary4A.getRssiFilterOption();
+ MainActivity.csLibrary4A.appendToLog("2 updateRunnable getSelectAction = " + iValue1);
+ if (iValue1 < 0) updating = "getting filter option";
+ else spinnerFilterOption.setSelection(iValue1);
+ }
+ if (updating == null) {
+ double dValue = MainActivity.csLibrary4A.getRssiFilterThreshold1();
+ MainActivity.csLibrary4A.appendToLog(String.format("3 updateRunnable getRssiFilterThreshold1 = %f", dValue));
+ if (dValue < 0 && false) updating = "updating threshold 1";
+ else editTextFilterThreshold1.setText(String.format("%.1f", (MainActivity.csLibrary4A.getRssiDisplaySetting() > 0 ? dValue -= MainActivity.csLibrary4A.dBuV_dBm_constant : dValue)));
+ }
+ if (updating == null) {
+ double dValue = MainActivity.csLibrary4A.getRssiFilterThreshold2();
+ MainActivity.csLibrary4A.appendToLog(String.format("4 updateRunnable getRssiFilterThreshold2 = %f", dValue));
+ if (dValue < 0 && false) updating = "updating threshold 2";
+ else editTextFilterThreshold2.setText(String.format("%.1f", (MainActivity.csLibrary4A.getRssiDisplaySetting() > 0 ? dValue -= MainActivity.csLibrary4A.dBuV_dBm_constant : dValue)));
+ }
+ if (updating == null) {
+ long lValue1 = MainActivity.csLibrary4A.getRssiFilterCount();
+ MainActivity.csLibrary4A.appendToLog(String.format("5 updateRunnable getRssiFilterCount = %d", lValue1));
+ if (lValue1 < 0) updating = "updating count";
+ else editTextFilterCount.setText(String.valueOf(lValue1));
+ }
+ }
+ if (updating != null) {
+ mHandler.postDelayed(updateRunnable, 1000);
+ MainActivity.csLibrary4A.appendToLogView("Updating in " + updating);
+ }
+ }
+ };
+
+ void settingUpdate() {
+ boolean sameSetting = true;
+ String invalidRequest = null;
+
+ if (sameSetting == true && invalidRequest == null) {
+ if (MainActivity.csLibrary4A.getRssiFilterEnable() != invSelectEnable
+ || MainActivity.csLibrary4A.getRssiFilterType() != invSelectFilterType
+ || MainActivity.csLibrary4A.getRssiFilterOption() != invSelectFilterOption) {
+ sameSetting = false;
+ if (MainActivity.csLibrary4A.setRssiFilterConfig(invSelectEnable, invSelectFilterType, invSelectFilterOption) == false) invalidRequest = "setting filter type";
+ }
+ if (MainActivity.csLibrary4A.getRssiFilterThreshold1() != invSelectFilterThreshold1 || MainActivity.csLibrary4A.getRssiFilterThreshold2() != invSelectFilterThreshold2) {
+ sameSetting = false;
+ MainActivity.csLibrary4A.appendToLog(String.format("updateRunnable: getRssiFilterThreshold2 = %f, invSelectFilterThreshold2 = %f", MainActivity.csLibrary4A.getRssiFilterThreshold2(), invSelectFilterThreshold2));
+ invSelectFilterThreshold2 = 0;
+ if (MainActivity.csLibrary4A.setRssiFilterThreshold(invSelectFilterThreshold1, invSelectFilterThreshold2) == false) invalidRequest = "setting filter threshold";
+ }
+ if (MainActivity.csLibrary4A.getRssiFilterCount() != invSelectFilterCount) {
+ sameSetting = false;
+ MainActivity.csLibrary4A.appendToLog("rssiFilterCount = " + invSelectFilterCount);
+ if (MainActivity.csLibrary4A.setRssiFilterCount(invSelectFilterCount) == false) invalidRequest = "setting filter count";
+ }
+ }
+
+ if (invalidRequest != null) {
+ String strValue = "Invalid " + invalidRequest + ". Operation is cancelled.";
+ Toast.makeText(MainActivity.mContext, strValue, Toast.LENGTH_SHORT).show();
+
+ } else {
+ settingTask = new SettingTask(button, sameSetting, false);
+ settingTask.execute();
+ MainActivity.csLibrary4A.saveSetting2File();
+ }
+ }
+}
+
+
+
+package com.csl.cs710ademoapp.fragments;
+
+import android.os.Bundle;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+
+import androidx.appcompat.app.ActionBar;
+import androidx.appcompat.app.AppCompatActivity;
+import androidx.fragment.app.Fragment;
+import androidx.fragment.app.FragmentManager;
+import androidx.fragment.app.FragmentStatePagerAdapter;
+import androidx.viewpager.widget.PagerAdapter;
+import androidx.viewpager.widget.ViewPager;
+
+import com.csl.cs710ademoapp.MainActivity;
+import com.csl.cslibrary4a.AdapterTab;
+import com.csl.cs710ademoapp.R;
+import com.google.android.material.tabs.TabLayout;
+
+public class SettingFragment extends CommonFragment {
+ private ActionBar actionBar;
+ private ViewPager viewPager;
+ FragmentStatePagerAdapter pagerAdapter;
+ AdapterTab adapter;
+ Fragment fragment0, fragment1;
+
+ private String[] tabs = { "Operation", "Administration" };
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ super.onCreateView(inflater, container, savedInstanceState, true);
+ return inflater.inflate(R.layout.custom_tabbed_layout, container, false);
+ }
+
+ @Override
+ public void onActivityCreated(Bundle savedInstanceState) {
+ super.onActivityCreated(savedInstanceState);
+
+ actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
+ actionBar.setTitle(R.string.title_activity_settings);
+
+ TabLayout tabLayout = (TabLayout) getActivity().findViewById(R.id.OperationsTabLayout);
+ FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
+ pagerAdapter = new FragmentStatePagerAdapter(getActivity().getSupportFragmentManager()) {
+ @Override
+ public int getCount() {
+ return tabs.length;
+ }
+ @Override
+ public int getItemPosition(Object object) {
+ return PagerAdapter.POSITION_NONE;
+ }
+ @Override
+ public Fragment getItem(int position) {
+ Fragment fragment = null;
+ switch (position) {
+ case 0:
+ fragment = new SettingOperateFragment(); //AccessSecurityLockFragment(); //InventoryRfidiMultiFragment();
+ fragment0 = fragment;
+ break;
+ case 1:
+ fragment1 = new SettingAdminFragment();
+ break;
+ default:
+ fragment = null;
+ break;
+ }
+ return fragment;
+ }
+ };
+ adapter = new AdapterTab(getActivity().getSupportFragmentManager(), tabs.length);
+ adapter.setFragment(0, new SettingOperateFragment());
+ adapter.setFragment(1, new SettingAdminFragment());
+
+ viewPager = (ViewPager) getActivity().findViewById(R.id.OperationsPager);
+ viewPager.setAdapter(adapter); //pagerAdapter); //mAdapter);
+ viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
+
+ for (String tab_name : tabs) {
+ tabLayout.addTab(tabLayout.newTab().setText(tab_name));
+ }
+
+ tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
+ @Override
+ public void onTabSelected(TabLayout.Tab tab) {
+ viewPager.setCurrentItem(tab.getPosition());
+ }
+
+ @Override
+ public void onTabUnselected(TabLayout.Tab tab) {
+ }
+
+ @Override
+ public void onTabReselected(TabLayout.Tab tab) {
+ }
+ });
+ }
+
+ @Override
+ public void onPause() {
+ adapter.fragment0.onPause();
+ adapter.fragment1.onPause();
+ super.onPause();
+ }
+
+ @Override
+ public void onStop() {
+ adapter.fragment0.onStop();
+ adapter.fragment1.onStop();
+ MainActivity.csLibrary4A.setAntennaSelect(0);
+ super.onStop();
+ }
+
+ @Override
+ public void onDestroyView() {
+ adapter.fragment0.onDestroyView();
+ adapter.fragment1.onDestroyView();
+ super.onDestroyView();
+ }
+
+ @Override
+ public void onDestroy() {
+ adapter.fragment0.onDestroy();
+ adapter.fragment1.onDestroy();
+ super.onDestroy();
+ }
+
+ @Override
+ public void onDetach() {
+ adapter.fragment0.onDetach();
+ adapter.fragment1.onDetach();
+ super.onDetach();
+ }
+
+ public SettingFragment() {
+ super("SettingFragment");
+ }
+}
+
+
+
+package com.csl.cs710ademoapp.fragments;
+
+import android.os.Bundle;
+import android.os.Handler;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.ArrayAdapter;
+import android.widget.Button;
+import android.widget.CheckBox;
+import android.widget.CompoundButton;
+import android.widget.EditText;
+import android.widget.LinearLayout;
+import android.widget.Spinner;
+import android.widget.TableRow;
+import android.widget.TextView;
+import android.widget.Toast;
+
+import com.csl.cs710ademoapp.CustomPopupWindow;
+import com.csl.cs710ademoapp.MainActivity;
+import com.csl.cs710ademoapp.R;
+import com.csl.cs710ademoapp.SettingTask;
+
+public class SettingOperateFragment extends CommonFragment {
+ final String strOVERRIDE = "Override"; final String strRESET = "Reset";
+ private CheckBox checkBoxPortEnable, checkBoxTagFocus, checkBoxFastId, checkBoxHighCompression;
+ private Spinner spinnerRegulatoryRegion, spinnerFrequencyOrder, spinnerChannel, spinnerQueryTarget, spinnerQuerySession, spinnerInvAlgo, spinnerProfile, spinnerRflnaGain, spinnerIflnaGain, spinnerAgcGain;
+ private EditText editTextPopulation, editTextStartQValue, editTextOperatePower, editTextPortDwell, editTextTagDelay, editTextIntraPkDelay, editTextDupDelay, editTextRetry;
+ private TextView textViewPortChannel;
+ private Button buttonPortSelect, buttonOverride, button, button1;
+ private TextView textViewEnvironmentalRSSI;
+
+ boolean sameCheck = true;
+ Handler mHandler = new Handler();
+ class SettingBeforeTagFocus {
+ int querySession;
+ int queryTarget;
+ String dwell;
+ String tagDelay;//, intraPkDelay, dupDelay;
+ void store() {
+ querySession = spinnerQuerySession.getSelectedItemPosition(); spinnerQuerySession.setSelection(1); spinnerQuerySession.setEnabled(false);
+ queryTarget = spinnerQueryTarget.getSelectedItemPosition(); spinnerQueryTarget.setSelection(0); spinnerQueryTarget.setEnabled(false);
+ dwell = editTextPortDwell.getText().toString(); editTextPortDwell.setText("2000"); editTextPortDwell.setEnabled(false);
+ tagDelay = editTextTagDelay.getText().toString(); editTextTagDelay.setText("0"); editTextTagDelay.setEnabled(false);
+ //intraPkDelay = editTextIntraPkDelay.getText().toString(); editTextIntraPkDelay.setText("0"); editTextIntraPkDelay.setEnabled(false);
+ //dupDelay = editTextDupDelay.getText().toString(); editTextDupDelay.setText("0"); editTextDupDelay.setEnabled(false);
+ }
+ void restore() {
+ spinnerQuerySession.setSelection(querySession); spinnerQuerySession.setEnabled(true);
+ spinnerQueryTarget.setSelection(queryTarget); spinnerQueryTarget.setEnabled(true);
+ editTextPortDwell.setText(dwell); editTextPortDwell.setEnabled(true);
+ editTextTagDelay.setText(tagDelay); editTextTagDelay.setEnabled(true);
+ //editTextIntraPkDelay.setText(intraPkDelay); editTextIntraPkDelay.setEnabled(true);
+ //editTextDupDelay.setText(dupDelay); editTextDupDelay.setEnabled(true);
+ }
+ };
+ SettingBeforeTagFocus settingBeforeTagFocus = new SettingBeforeTagFocus();
+
+ boolean overriding = false;
+ int countrySelect = -1;
+ int channelOrder = -1; int channelSelect = -1;
+ int channel = -1; final int channelMin = 1; int channelMax = 1; int iPortNumber = 1;
+ boolean portEnable = false;
+ long powerLevel = -1; final long powerLevelMin = 0; final long powerLevelMax = 300;
+ long dwellTime = -1; final long dwellTimeMin = 0; final long dwellTimeMax = 10000;
+ byte byteTagDelay = -1; byte byteTagDelayMin = 0; byte byteTagDelayMax = 63;
+ byte byteIntraPkDelay = -1; byte byteIntraPkDelayMin = 0; byte byteIntraPkDelayMax = 63;
+ byte byteDupDelay = -1; byte byteDupDelayMin = 0; byte byteDupDelayMax = 63;
+ int iPopulation = -1; int iPopulationMin = 1; int iPopulationMax = 9999;
+ byte byteFixedQValue = -1; byte byteFixedQValueMin = 0; byte byteFixedQValueMax = 15;
+ int queryTarget;
+ int querySession = -1;
+ int tagFocus = -1, fastId = -1;
+ boolean invAlgoDynamic = false;
+ int retry = -1;
+ int profile = -1;
+ int highCompression = -1, rflnagain = -1, iflnagain = -1, agcgain = -1;
+
+ private SettingTask settingTask;
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ super.onCreateView(inflater, container, savedInstanceState, false);
+ return inflater.inflate(R.layout.fragment_settings_operate, container, false);
+ }
+
+ @Override
+ public void onActivityCreated(Bundle savedInstanceState) {
+ super.onActivityCreated(savedInstanceState);
+
+ if (MainActivity.csLibrary4A.get98XX() == 2) {
+ TableRow tableRow = (TableRow) getActivity().findViewById(R.id.settingOperateCompactDelayRow);
+ tableRow.setVisibility(View.GONE);
+ LinearLayout linearLayout = (LinearLayout) getActivity().findViewById(R.id.settingOperateGainControl);
+ linearLayout.setVisibility(View.GONE);
+ } else {
+ TableRow tableRow = (TableRow) getActivity().findViewById(R.id.settingOperateDupDelayRow);
+ tableRow.setVisibility(View.GONE);
+ TableRow tableRow1 = (TableRow) getActivity().findViewById(R.id.settingOperateIntraPkDelayRow);
+ tableRow1.setVisibility(View.GONE);
+ //TableRow tableRow2 = (TableRow) getActivity().findViewById(R.id.settingOperatePortWarningRow);
+ //tableRow2.setVisibility(View.GONE);
+ }
+
+ spinnerRegulatoryRegion = (Spinner) getActivity().findViewById(R.id.settingOperateRegulatoryRegion);
+ spinnerFrequencyOrder = (Spinner) getActivity().findViewById(R.id.settingOperateFrequencyOrder); spinnerFrequencyOrder.setEnabled(false);
+ spinnerChannel = (Spinner) getActivity().findViewById(R.id.settingOperateChannel);
+
+ iPortNumber = MainActivity.csLibrary4A.getPortNumber();
+ if (iPortNumber == 1 && false) {
+ TableRow tableRow = (TableRow) getActivity().findViewById(R.id.settingOperatePortChannelRow);
+ tableRow.setVisibility(View.GONE);
+ tableRow = (TableRow) getActivity().findViewById(R.id.settingOperatePortEnableRow);
+ tableRow.setVisibility(View.GONE);
+ tableRow = (TableRow) getActivity().findViewById(R.id.settingOperatePortDwellRow);
+ tableRow.setVisibility(View.GONE);
+ } else {
+ int iTemp = iPortNumber;
+ if (iTemp > 1) channelMax = iTemp;
+ else channelMax = 16;
+ if (channelMax != 1) {
+ TextView textViewPortChannelLabel = (TextView) getActivity().findViewById(R.id.settingOperatePortChannelLabel);
+ if (iPortNumber != 1) textViewPortChannelLabel.setText("Ant port #");
+ else textViewPortChannelLabel.setText("Power level");
+ String stringPortChannelLabel = textViewPortChannelLabel.getText().toString();
+ stringPortChannelLabel += "(" + String.valueOf(channelMin) + "-" + String.valueOf(channelMax) + ")";
+ textViewPortChannelLabel.setText(stringPortChannelLabel);
+ }
+ textViewPortChannel = (TextView) getActivity().findViewById(R.id.settingOperatePortChannel); textViewPortChannel.setText("1");
+ buttonPortSelect = (Button) getActivity().findViewById(R.id.settingOperatePortChannelSelect);
+ if (false && MainActivity.csLibrary4A.get98XX() == 2) buttonPortSelect.setEnabled(false);
+ buttonPortSelect.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ int channel = Integer.parseInt(textViewPortChannel.getText().toString());
+ if (channel < 1) channel = channelMin;
+ if (++channel > channelMax) channel = channelMin;
+ textViewPortChannel.setText(""); if (MainActivity.csLibrary4A.setAntennaSelect(channel-1)) textViewPortChannel.setText(String.valueOf(channel));
+ editTextOperatePower.setText("");
+ editTextPortDwell.setText("");
+ mHandler.post(updateRunnable);
+ }
+ });
+
+ checkBoxPortEnable = (CheckBox) getActivity().findViewById(R.id.settingOperatePortEnable);
+
+ TextView textViewPortDwellLabel = (TextView) getActivity().findViewById(R.id.settingOperatePortDwellLabel);
+ String stringPortDwellLabel = textViewPortDwellLabel.getText().toString();
+ stringPortDwellLabel += "(" + String.valueOf(dwellTimeMin) + "-" + String.valueOf(dwellTimeMax) + ")";
+ textViewPortDwellLabel.setText(stringPortDwellLabel);
+ editTextPortDwell = (EditText) getActivity().findViewById(R.id.settingOperatePortDwell);
+ }
+
+ TextView textViewAdminTagDelayLabel = (TextView) getActivity().findViewById(R.id.settingAdminTagDelayLabel);
+ String stringAdminTagDelayLabel = textViewAdminTagDelayLabel.getText().toString();
+ stringAdminTagDelayLabel += "(" + String.valueOf(byteTagDelayMin) + "-" + String.valueOf(byteTagDelayMax) + "ms)";
+ textViewAdminTagDelayLabel.setText(stringAdminTagDelayLabel);
+ editTextTagDelay = (EditText) getActivity().findViewById(R.id.settingOperateTagDelay);
+ editTextIntraPkDelay = (EditText) getActivity().findViewById(R.id.settingOperateIntraPkDelay);
+ editTextDupDelay = (EditText) getActivity().findViewById(R.id.settingOperateDupDelay);
+
+ TextView textViewOperatePowerLabel = (TextView) getActivity().findViewById(R.id.settingOperatePowerLabel);
+ String stringOperationPowerLabel = textViewOperatePowerLabel.getText().toString();
+ stringOperationPowerLabel += "(" + String.valueOf(powerLevelMin) + "-" + String.valueOf(powerLevelMax) + ")";
+ textViewOperatePowerLabel.setText(stringOperationPowerLabel);
+ editTextOperatePower = (EditText) getActivity().findViewById(R.id.settingOperatePower);
+
+ TextView textViewOperatePopulationLabel = (TextView) getActivity().findViewById(R.id.settingOperatePopulationLabel);
+ String stringOperationPopulationLabel = textViewOperatePopulationLabel.getText().toString();
+ stringOperationPopulationLabel += "(" + String.valueOf(iPopulationMin) + "-" + String.valueOf(iPopulationMax) + ")";
+ textViewOperatePopulationLabel.setText(stringOperationPopulationLabel);
+ editTextPopulation = (EditText) getActivity().findViewById(R.id.settingOperatePopulation);
+
+ editTextStartQValue = (EditText) getActivity().findViewById(R.id.settingOperateQValue);
+
+ spinnerQueryTarget = (Spinner) getActivity().findViewById(R.id.settingOperateTarget);
+ ArrayAdapter targetAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.query_target_options, R.layout.custom_spinner_layout);
+ targetAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+ spinnerQueryTarget.setAdapter(targetAdapter);
+
+ spinnerQuerySession = (Spinner) getActivity().findViewById(R.id.settingOperateSession);
+ targetAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.query_session_options, R.layout.custom_spinner_layout);
+ targetAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+ spinnerQuerySession.setAdapter(targetAdapter);
+
+ checkBoxTagFocus = (CheckBox) getActivity().findViewById(R.id.settingOperateTagFocus);
+ String string = checkBoxTagFocus.getText().toString();
+ if (MainActivity.csLibrary4A.get98XX() == 2) checkBoxTagFocus.setText(string.substring(0, string.length()-1) + ". When enabled, tag select is disabled.)");
+ checkBoxTagFocus.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
+ @Override
+ public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
+ if (isChecked) settingBeforeTagFocus.store();
+ else settingBeforeTagFocus.restore();
+ }
+ });
+
+ checkBoxFastId = (CheckBox) getActivity().findViewById(R.id.settingOperateFastId);
+
+ spinnerInvAlgo = (Spinner) getActivity().findViewById(R.id.settingOperateAlgorithmToUse);
+ targetAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.inventory_algorithm_options, R.layout.custom_spinner_layout);
+ targetAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+ spinnerInvAlgo.setAdapter(targetAdapter);
+
+ TextView textViewRetry = (TextView) getActivity().findViewById(R.id.settingOperateRetryLabel);
+ if (MainActivity.csLibrary4A.get98XX() == 2) textViewRetry.setText("Minimum minQ cycles");
+ editTextRetry = (EditText) getActivity().findViewById(R.id.settingOperateRetry);
+
+ spinnerProfile = (Spinner) getActivity().findViewById(R.id.settingOperateProfile);
+ if (true) {
+ ArrayAdapter targetAdapter1 = new ArrayAdapter(getContext(), android.R.layout.simple_spinner_dropdown_item, MainActivity.csLibrary4A.getProfileList());
+ targetAdapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+ spinnerProfile.setAdapter(targetAdapter1);
+ }
+
+ MainActivity.csLibrary4A.resetEnvironmentalRSSI();
+ textViewEnvironmentalRSSI = (TextView) getActivity().findViewById(R.id.settingOperateEnvironmentalRSSI);
+ checkBoxHighCompression = (CheckBox) getActivity().findViewById(R.id.settingOperateHighCompression);
+
+ spinnerRflnaGain = (Spinner) getActivity().findViewById(R.id.settingOperateRflnaGain);
+ targetAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.rflnagain_options, R.layout.custom_spinner_layout);
+ targetAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+ spinnerRflnaGain.setAdapter(targetAdapter);
+
+ spinnerIflnaGain = (Spinner) getActivity().findViewById(R.id.settingOperateIflnaGain);
+ targetAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.iflnagain_options, R.layout.custom_spinner_layout);
+ targetAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+ spinnerIflnaGain.setAdapter(targetAdapter);
+
+ spinnerAgcGain = (Spinner) getActivity().findViewById(R.id.settingOperateAgcGAin);
+ targetAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.agcgain_options, R.layout.custom_spinner_layout);
+ targetAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+ spinnerAgcGain.setAdapter(targetAdapter);
+
+ buttonOverride = (Button) getActivity().findViewById(R.id.settingOperateOverrideButton);
+ String strText = buttonOverride.getText().toString();
+ if (strText.contains(strOVERRIDE)) {
+ editTextPopulation.setEnabled(true);
+ editTextStartQValue.setEnabled(false);
+ } else {
+ editTextPopulation.setEnabled(false);
+ editTextStartQValue.setEnabled(true);
+ }
+ buttonOverride.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ String strText = buttonOverride.getText().toString();
+ if (strText.contains(strOVERRIDE)) {
+ editTextPopulation.setEnabled(false);
+ editTextStartQValue.setEnabled(true);
+ buttonOverride.setText(strRESET); overriding = true;
+ } else {
+ editTextPopulation.setEnabled(true);
+ editTextStartQValue.setEnabled(false);;
+ buttonOverride.setText(strOVERRIDE); overriding = false;
+
+ iPopulation = Integer.parseInt(editTextPopulation.getText().toString());
+ editTextStartQValue.setText(String.valueOf(MainActivity.csLibrary4A.getPopulation2Q(iPopulation)));
+ }
+ }
+ });
+
+ button = (Button) getActivity().findViewById(R.id.settingSaveButtonOperate);
+ button.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ sameCheck = true; settingUpdate1();
+ }
+ });
+
+ button1 = (Button) getActivity().findViewById(R.id.settingSaveButtonOperate1);
+ button1.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ sameCheck = false; settingUpdate1();
+ }
+ });
+
+ mHandler.post(updateRunnable);
+ }
+
+ void settingUpdate1() {
+ if (MainActivity.csLibrary4A.isBleConnected() == false) {
+ Toast.makeText(MainActivity.mContext, R.string.toast_ble_not_connected, Toast.LENGTH_SHORT).show();
+ return;
+ } else if (MainActivity.csLibrary4A.isRfidFailure()) {
+ Toast.makeText(MainActivity.mContext, "Rfid is disabled", Toast.LENGTH_SHORT).show();
+ return;
+ } else if (updateRunning) {
+ Toast.makeText(MainActivity.mContext, R.string.toast_not_ready, Toast.LENGTH_SHORT).show();
+ return;
+ } else {
+ MainActivity.csLibrary4A.setSameCheck(sameCheck);
+ try {
+ countrySelect = spinnerRegulatoryRegion.getSelectedItemPosition();
+ channelOrder = spinnerFrequencyOrder.getSelectedItemPosition();
+ channelSelect = spinnerChannel.getSelectedItemPosition();
+ if (textViewPortChannel != null)
+ channel = Integer.parseInt(textViewPortChannel.getText().toString());
+ if (checkBoxPortEnable != null) portEnable = checkBoxPortEnable.isChecked();
+ powerLevel = Long.parseLong(editTextOperatePower.getText().toString());
+ if (editTextPortDwell != null)
+ dwellTime = Long.parseLong(editTextPortDwell.getText().toString());
+ if (editTextTagDelay != null)
+ byteTagDelay = Byte.parseByte(editTextTagDelay.getText().toString());
+ if (editTextIntraPkDelay != null)
+ byteIntraPkDelay = Byte.parseByte(editTextIntraPkDelay.getText().toString());
+ if (editTextDupDelay != null)
+ byteDupDelay = Byte.parseByte(editTextDupDelay.getText().toString());
+ iPopulation = Integer.parseInt(editTextPopulation.getText().toString());
+ byteFixedQValue = Byte.parseByte(editTextStartQValue.getText().toString());
+ queryTarget = spinnerQueryTarget.getSelectedItemPosition();
+ querySession = spinnerQuerySession.getSelectedItemPosition();
+ tagFocus = (checkBoxTagFocus.isChecked() ? 1 : 0);
+ fastId = (checkBoxFastId.isChecked() ? 1 : 0);
+ invAlgoDynamic = (spinnerInvAlgo.getSelectedItemPosition() == 0 ? true : false);
+ retry = Integer.parseInt(editTextRetry.getText().toString());
+ profile = spinnerProfile.getSelectedItemPosition();
+ highCompression = (checkBoxHighCompression.isChecked() ? 1 : 0);
+ rflnagain = spinnerRflnaGain.getSelectedItemPosition();
+ iflnagain = spinnerIflnaGain.getSelectedItemPosition();
+ agcgain = spinnerAgcGain.getSelectedItemPosition();
+ settingUpdate();
+ } catch (Exception ex) {
+ Toast.makeText(MainActivity.mContext, R.string.toast_invalid_range, Toast.LENGTH_SHORT).show();
+ }
+ }
+ }
+
+ @Override
+ public void onDestroy() {
+ if (settingTask != null) settingTask.cancel(true);
+ if (MainActivity.csLibrary4A != null) MainActivity.csLibrary4A.setSameCheck(true);
+ mHandler.removeCallbacks(updateRunnable);
+ super.onDestroy();
+ }
+
+ boolean userVisibleHint = true;
+ @Override
+ public void setUserVisibleHint(boolean isVisibleToUser) {
+ MainActivity.csLibrary4A.appendToLog("isVisibleToUser = " + isVisibleToUser);
+ super.setUserVisibleHint(isVisibleToUser);
+ if(getUserVisibleHint()) {
+ if (userVisibleHint == false) {
+ userVisibleHint = true;
+ mHandler.post(updateRunnable);
+ }
+ } else {
+ userVisibleHint = false;
+ }
+ }
+
+ public SettingOperateFragment() {
+ super("SettingOperateFragment");
+ }
+
+ boolean updateRunning = false;
+ private final Runnable updateRunnable = new Runnable() {
+ @Override
+ public void run() {
+ int iValue;
+ long lValue;
+ boolean updating = false;
+
+ updateRunning = true;
+ if (MainActivity.csLibrary4A.mrfidToWriteSize() != 0) {
+ updating = true; MainActivity.csLibrary4A.appendToLog("updating 1");
+ }
+ else {
+ iPopulation = MainActivity.csLibrary4A.getPopulation();
+ if (iPopulation < 0) {
+ updating = true; MainActivity.csLibrary4A.appendToLog("updating 2");
+ }
+ else {
+ editTextPopulation.setText(String.valueOf(iPopulation));
+
+ byteFixedQValue = MainActivity.csLibrary4A.getQValue();
+ editTextStartQValue.setText(String.valueOf(byteFixedQValue));
+ if (MainActivity.csLibrary4A.getPopulation2Q(iPopulation) != byteFixedQValue) {
+ buttonOverride.setText(strRESET); overriding = true;
+ } else {
+ buttonOverride.setText(strOVERRIDE); overriding = false;
+ }
+ }
+ if (updating == false && textViewPortChannel != null) {
+ lValue = MainActivity.csLibrary4A.getAntennaSelect();
+ if (lValue < 0) {
+ updating = true; MainActivity.csLibrary4A.appendToLog("updating 4");
+ } else {
+ textViewPortChannel.setText(String.valueOf(lValue+1));
+ }
+ }
+ if (checkBoxPortEnable != null) checkBoxPortEnable.setChecked(MainActivity.csLibrary4A.getAntennaEnable());
+ if (updating == false) {
+ lValue = MainActivity.csLibrary4A.getPwrlevel();
+ if (lValue < 0) {
+ updating = true; MainActivity.csLibrary4A.appendToLog("updating 5");
+ } else {
+ editTextOperatePower.setText(String.valueOf(lValue));
+ }
+ }
+ if (updating == false && editTextPortDwell != null) {
+ lValue = MainActivity.csLibrary4A.getAntennaDwell();
+ if (lValue < 0) {
+ updating = true; MainActivity.csLibrary4A.appendToLog("updating 6");
+ } else {
+ editTextPortDwell.setText(String.valueOf(lValue));
+ }
+ }
+ if (editTextTagDelay != null) editTextTagDelay.setText(String.valueOf(MainActivity.csLibrary4A.getTagDelay()));
+ if (editTextIntraPkDelay != null) editTextIntraPkDelay.setText(String.valueOf(MainActivity.csLibrary4A.getIntraPkDelay()));
+ if (editTextDupDelay != null) editTextDupDelay.setText(String.valueOf(MainActivity.csLibrary4A.getDupDelay()));
+ if (updating == false) {
+ spinnerQueryTarget.setSelection(MainActivity.csLibrary4A.getQueryTarget());
+ }
+ if (updating == false) {
+ iValue = MainActivity.csLibrary4A.getQuerySession();
+ if (iValue < 0) {
+ updating = true; MainActivity.csLibrary4A.appendToLog("updating 7");
+ } else {
+ spinnerQuerySession.setSelection(iValue);
+ }
+ }
+ if (updating == false) {
+ iValue = MainActivity.csLibrary4A.getTagFocus();
+ if (iValue < 0) {
+ updating = true; MainActivity.csLibrary4A.appendToLog("updating 8");
+ }
+ else {
+ checkBoxTagFocus.setChecked(iValue > 0 ? true : false);
+ if (checkBoxTagFocus.isChecked()) settingBeforeTagFocus.store();
+ }
+ }
+ if (updating == false) {
+ iValue = MainActivity.csLibrary4A.getFastId();
+ if (iValue < 0) {
+ updating = true; MainActivity.csLibrary4A.appendToLog("updating 8");
+ }
+ else checkBoxFastId.setChecked(iValue > 0 ? true : false);
+ }
+ if (updating == false) {
+ spinnerInvAlgo.setSelection(MainActivity.csLibrary4A.getInvAlgo() ? 0 : 1);
+ }
+ if (updating == false) {
+ int iRetry = MainActivity.csLibrary4A.getRetryCount();
+ if (iRetry < 0) {
+ updating = true; MainActivity.csLibrary4A.appendToLog("updating 9");
+ }
+ else editTextRetry.setText(String.valueOf(iRetry));
+ }
+ if (updating == false) {
+ String[] strCountryList = MainActivity.csLibrary4A.getCountryList();
+ for (int i = 0; i < strCountryList.length; i++) MainActivity.csLibrary4A.appendToLog("updating: String " + i + " = " + strCountryList[i]);
+ String[] strChannelFrequencyList = MainActivity.csLibrary4A.getChannelFrequencyList();
+ //for (int i = 0; i < strChannelFrequencyList.length; i++) MainActivity.csLibrary4A.appendToLog("updating: String " + i + " = " + strChannelFrequencyList[i]);
+ if (strCountryList == null) {
+ updating = true; MainActivity.csLibrary4A.appendToLog("updating 10");
+ } else {
+ ArrayAdapter targetAdapter1 = new ArrayAdapter(getActivity(), R.layout.custom_spinner_layout, strCountryList);
+ targetAdapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+ spinnerRegulatoryRegion.setAdapter(targetAdapter1);
+ int countryNumber = MainActivity.csLibrary4A.getCountryNumberInList();
+ MainActivity.csLibrary4A.appendToLog("updating countryNumber = " + countryNumber);
+ if (countryNumber < 0 || countryNumber > strCountryList.length) spinnerRegulatoryRegion.setSelection(0);
+ else spinnerRegulatoryRegion.setSelection(countryNumber);
+ if (strCountryList.length == 1) spinnerRegulatoryRegion.setEnabled(false);
+ else spinnerRegulatoryRegion.setEnabled(true);
+
+ ArrayAdapter targetAdapter;
+ //if (MainActivity.csLibrary4A.getChannelHoppingDefault())
+ targetAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.frequencyOrder_options, R.layout.custom_spinner_layout);
+ //else targetAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.frequencyAgile_options, R.layout.custom_spinner_layout);
+ targetAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+ spinnerFrequencyOrder.setAdapter(targetAdapter);
+ spinnerFrequencyOrder.setSelection(MainActivity.csLibrary4A.getChannelHoppingStatus() ? 0 : 1);
+ if (MainActivity.csLibrary4A.getChannelHoppingStatus()) spinnerChannel.setEnabled(false);
+ else spinnerChannel.setEnabled(true);
+
+ ArrayAdapter targetAdapter2 = new ArrayAdapter(getActivity(), R.layout.custom_spinner_layout, strChannelFrequencyList);
+ targetAdapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+ spinnerChannel.setAdapter(targetAdapter2);
+ int channel = MainActivity.csLibrary4A.getChannel();
+ MainActivity.csLibrary4A.appendToLog("channel = " + channel);
+ if (channel < 0 || channel > strChannelFrequencyList.length) spinnerChannel.setSelection(0);
+ else spinnerChannel.setSelection(channel);
+ }
+ }
+ }
+ if (updating == false) {
+ iValue = MainActivity.csLibrary4A.getCurrentProfile();
+ if (iValue < 0) {
+ updating = true; MainActivity.csLibrary4A.appendToLog("updating 11");
+ } else {
+ spinnerProfile.setSelection(iValue);
+ }
+ }
+ if (updating == false) {
+ String strRssi = MainActivity.csLibrary4A.getEnvironmentalRSSI();
+ if (strRssi == null) {
+ updating = true; MainActivity.csLibrary4A.appendToLog("updating 12");
+ }
+ else textViewEnvironmentalRSSI.setText(strRssi);
+ }
+ if (updating == false) {
+ iValue = MainActivity.csLibrary4A.getHighCompression();
+ if (iValue < 0) {
+ updating = true; MainActivity.csLibrary4A.appendToLog("updating 13");
+ } else checkBoxHighCompression.setChecked(iValue == 0 ? false : true);
+ }
+ if (updating == false) {
+ iValue = MainActivity.csLibrary4A.getRflnaGain();
+ if (iValue < 0) {
+ updating = true; MainActivity.csLibrary4A.appendToLog("updating 14");
+ } else {
+ switch (iValue) {
+ case 2:
+ iValue = 1;
+ break;
+ case 3:
+ iValue = 2;
+ break;
+ case 0:
+ default:
+ iValue = 0;
+ break;
+ }
+ spinnerRflnaGain.setSelection(iValue);
+ }
+ }
+ if (updating == false) {
+ iValue = MainActivity.csLibrary4A.getIflnaGain();
+ if (iValue < 0) {
+ updating = true; MainActivity.csLibrary4A.appendToLog("updating 15");
+ } else {
+ switch (iValue) {
+ case 1:
+ iValue = 1;
+ break;
+ case 3:
+ iValue = 2;
+ break;
+ case 7:
+ iValue = 3;
+ break;
+ case 0:
+ default:
+ iValue = 0;
+ break;
+ }
+ spinnerIflnaGain.setSelection(iValue);
+ }
+ }
+ if (updating == false) {
+ iValue = MainActivity.csLibrary4A.getAgcGain();
+ if (iValue < 0) {
+ updating = true; MainActivity.csLibrary4A.appendToLog("updating 16");
+ } else {
+ switch (iValue) {
+ case 4:
+ iValue = 1;
+ break;
+ case 6:
+ iValue = 2;
+ break;
+ case 7:
+ iValue = 3;
+ break;
+ case 0:
+ default:
+ iValue = 0;
+ break;
+
+ }
+ spinnerAgcGain.setSelection(iValue);
+ }
+ }
+ if (updating) {
+ mHandler.postDelayed(updateRunnable, 500);
+ } else updateRunning = false;
+ }
+ };
+
+ void settingUpdate() {
+ boolean sameSetting = true;
+ boolean invalidRequest = false;
+ boolean changedChannel = false;
+
+ if (invalidRequest == false && (MainActivity.csLibrary4A.getCountryNumberInList() != countrySelect || sameCheck == false)) {
+ sameSetting = false; MainActivity.csLibrary4A.appendToLog("point 1");
+ if (MainActivity.csLibrary4A.setCountryInList(countrySelect) == false) invalidRequest = true;
+ }
+ if (invalidRequest == false && (MainActivity.csLibrary4A.getChannelHoppingStatus() != (channelOrder == 0 ? true : false) || sameCheck == false)) {
+ sameSetting = false; MainActivity.csLibrary4A.appendToLog("point 2");
+ if (MainActivity.csLibrary4A.setChannelHoppingStatus(channelOrder == 0 ? true : false) == false) invalidRequest = true;
+ else if (channelOrder > 0) spinnerChannel.setEnabled(true);
+ else spinnerChannel.setEnabled(false);
+ spinnerChannel.setSelection(MainActivity.csLibrary4A.getChannel()); MainActivity.csLibrary4A.appendToLog("1 channel = ");
+ }
+ if (invalidRequest == false && (MainActivity.csLibrary4A.getChannel() != channelSelect || sameCheck == false)) {
+ sameSetting = false; MainActivity.csLibrary4A.appendToLog("point 3");
+ if (channelSelect < MainActivity.csLibrary4A.FreqChnCnt()) {
+ if (MainActivity.csLibrary4A.setChannel(channelSelect) == false) invalidRequest = true;
+ } else {
+ invalidRequest = true;
+ }
+ }
+ if (false && invalidRequest == false && (MainActivity.csLibrary4A.getAntennaSelect() + 1 != channel || sameCheck == false)) {
+ sameSetting = false; MainActivity.csLibrary4A.appendToLog("point 4");
+ if (channel < channelMin || channel > channelMax) invalidRequest = true;
+ else if (MainActivity.csLibrary4A.setAntennaSelect(channel - 1) == false) invalidRequest = true;
+ else changedChannel = true;
+ }
+ if (invalidRequest == false && (MainActivity.csLibrary4A.getAntennaEnable() != portEnable || sameCheck == false || changedChannel)) {
+ sameSetting = false; MainActivity.csLibrary4A.appendToLog("point 5");
+ if (MainActivity.csLibrary4A.setAntennaEnable(portEnable) == false)
+ invalidRequest = true;
+ }
+ if (invalidRequest == false && (MainActivity.csLibrary4A.getPwrlevel() != powerLevel || sameCheck == false)) {
+ sameSetting = false; MainActivity.csLibrary4A.appendToLog("point 6");
+ if (powerLevel < powerLevelMin) invalidRequest = true;
+ else if (powerLevel > MainActivity.powerLevelMax) {
+ CustomPopupWindow customPopupWindow = new CustomPopupWindow(MainActivity.mContext);
+ customPopupWindow.popupStart("Power can only be set to 320 or below", false);
+ invalidRequest = true;
+ }
+ else if (MainActivity.csLibrary4A.setPowerLevel(powerLevel) == false) invalidRequest = true;
+ }
+ if ((invalidRequest == false && (MainActivity.csLibrary4A.getAntennaDwell() != dwellTime || sameCheck == false || changedChannel))) {
+ sameSetting = false; MainActivity.csLibrary4A.appendToLog("point 7");
+ if (dwellTime < dwellTimeMin || dwellTime > dwellTimeMax) invalidRequest = true;
+ else if (MainActivity.csLibrary4A.setAntennaDwell(dwellTime) == false) invalidRequest = true;
+ }
+ if ((invalidRequest == false && editTextTagDelay != null)) {
+ if (MainActivity.csLibrary4A.getTagDelay() != byteTagDelay || sameCheck == false) {
+ sameSetting = false; MainActivity.csLibrary4A.appendToLog("point 8");
+ if (byteTagDelay < byteTagDelayMin || byteTagDelay > byteTagDelayMax) invalidRequest = true;
+ else if (MainActivity.csLibrary4A.setTagDelay(byteTagDelay) == false)
+ invalidRequest = true;
+ }
+ }
+ if ((invalidRequest == false && editTextIntraPkDelay != null)) {
+ if (MainActivity.csLibrary4A.getIntraPkDelay() != byteIntraPkDelay || sameCheck == false) {
+ sameSetting = false; MainActivity.csLibrary4A.appendToLog("point 9A");
+ if (byteDupDelay < byteIntraPkDelayMin || byteIntraPkDelay > byteIntraPkDelayMax) invalidRequest = true;
+ else if (MainActivity.csLibrary4A.setIntraPkDelay(byteIntraPkDelay) == false)
+ invalidRequest = true;
+ }
+ }
+ if ((invalidRequest == false && editTextDupDelay != null)) {
+ if (MainActivity.csLibrary4A.getDupDelay() != byteDupDelay || sameCheck == false) {
+ sameSetting = false; MainActivity.csLibrary4A.appendToLog("point 9");
+ if (byteDupDelay < byteDupDelayMin || byteDupDelay > byteDupDelayMax) invalidRequest = true;
+ else if (MainActivity.csLibrary4A.setDupDelay(byteDupDelay) == false)
+ invalidRequest = true;
+ }
+ }
+
+ if (overriding) {
+ if (MainActivity.csLibrary4A.getQValue() != byteFixedQValue || sameCheck == false) {
+ sameSetting = false; MainActivity.csLibrary4A.appendToLog("point 9");
+ if (byteFixedQValue < byteFixedQValueMin || byteFixedQValue > byteFixedQValueMax) invalidRequest = true;
+ if (MainActivity.csLibrary4A.setQValue(byteFixedQValue) == false)
+ invalidRequest = true;
+ }
+ } else {
+ if (invalidRequest == false && (MainActivity.csLibrary4A.getPopulation() != iPopulation || MainActivity.csLibrary4A.getQValue() != byteFixedQValue || sameCheck == false)) {
+ sameSetting = false; MainActivity.csLibrary4A.appendToLog("point 10");
+ if (iPopulation < iPopulationMin || iPopulation > iPopulationMax) invalidRequest = true;
+ else if (MainActivity.csLibrary4A.setPopulation(iPopulation) == false) {
+ invalidRequest = true;
+ } else {
+ editTextStartQValue.setText(String.valueOf(MainActivity.csLibrary4A.getPopulation2Q(iPopulation)));
+ }
+ }
+ }
+ if ((MainActivity.csLibrary4A.getQueryTarget() != queryTarget
+ || MainActivity.csLibrary4A.getQuerySession() != querySession || sameCheck == false)) {
+ sameSetting = false; MainActivity.csLibrary4A.appendToLog("point 11");
+ if (MainActivity.csLibrary4A.setTagGroup(MainActivity.csLibrary4A.getQuerySelect(), querySession, queryTarget) == false)
+ invalidRequest = true;
+ }
+ if (MainActivity.csLibrary4A.getTagFocus() != tagFocus || sameCheck == false) {
+ sameSetting = false; MainActivity.csLibrary4A.appendToLog("point 12");
+ if (MainActivity.csLibrary4A.setTagFocus(tagFocus > 0 ? true : false) == false)
+ invalidRequest = true;
+ }
+ if (MainActivity.csLibrary4A.getFastId() != fastId || sameCheck == false) {
+ sameSetting = false; MainActivity.csLibrary4A.appendToLog("point 12");
+ if (MainActivity.csLibrary4A.setFastId(fastId > 0 ? true : false) == false)
+ invalidRequest = true;
+ }
+ if (invalidRequest == false) {
+ if (MainActivity.csLibrary4A.getInvAlgo() != invAlgoDynamic || sameCheck == false) {
+ sameSetting = false; MainActivity.csLibrary4A.appendToLog("point 13");
+ if (MainActivity.csLibrary4A.setInvAlgo(invAlgoDynamic) == false)
+ invalidRequest = true;
+ spinnerQueryTarget.setSelection(MainActivity.csLibrary4A.getQueryTarget());
+ }
+ }
+ if (invalidRequest == false) {
+ if (MainActivity.csLibrary4A.getRetryCount() != retry || sameCheck == false) {
+ sameSetting = false; MainActivity.csLibrary4A.appendToLog("point 14");
+ if (MainActivity.csLibrary4A.setRetryCount(retry) == false)
+ invalidRequest = true;
+ }
+ }
+ if (invalidRequest == false) {
+ if (MainActivity.csLibrary4A.getCurrentProfile() != profile || sameCheck == false) {
+ sameSetting = false; MainActivity.csLibrary4A.appendToLog("point 15 with profile = " + profile);
+ if (MainActivity.csLibrary4A.setCurrentLinkProfile(profile) == false)
+ invalidRequest = true;
+ }
+ }
+ if (invalidRequest == false) {
+ switch(rflnagain) {
+ case 1:
+ rflnagain = 2;
+ break;
+ case 2:
+ rflnagain = 3;
+ break;
+ case 0:
+ default:
+ rflnagain = 0;
+ break;
+ }
+ switch(iflnagain) {
+ case 1:
+ iflnagain = 1;
+ break;
+ case 2:
+ iflnagain = 3;
+ break;
+ case 3:
+ iflnagain = 7;
+ break;
+ case 0:
+ default:
+ iflnagain = 0;
+ break;
+ }
+ switch(agcgain) {
+ case 1:
+ agcgain = 4;
+ break;
+ case 2:
+ agcgain = 6;
+ break;
+ case 3:
+ agcgain = 7;
+ break;
+ case 0:
+ default:
+ agcgain = 0;
+ break;
+ }
+ if ((MainActivity.csLibrary4A.getHighCompression() != highCompression)
+ || (MainActivity.csLibrary4A.getRflnaGain() != rflnagain)
+ || (MainActivity.csLibrary4A.getIflnaGain() != iflnagain)
+ || (MainActivity.csLibrary4A.getAgcGain() != agcgain)
+ || sameCheck == false) {
+ sameSetting = false;
+ if (MainActivity.csLibrary4A.setRxGain(highCompression, rflnagain, iflnagain, agcgain) == false)
+ invalidRequest = true;
+ }
+ }
+ settingTask = new SettingTask((sameCheck ? button: button1), sameSetting, invalidRequest);
+ settingTask.execute();
+ MainActivity.csLibrary4A.saveSetting2File();
+ mHandler.post(updateRunnable);
+ }
+}
+
+
+
+package com.csl.cs710ademoapp.fragments;
+
+import android.app.AlertDialog;
+import android.app.Dialog;
+import android.content.DialogInterface;
+import android.os.Bundle;
+import android.view.View;
+import android.widget.ArrayAdapter;
+import android.widget.EditText;
+import android.widget.Spinner;
+
+import androidx.fragment.app.DialogFragment;
+
+import com.csl.cs710ademoapp.MainActivity;
+import com.csl.cs710ademoapp.R;
+
+public class SettingWedgeFragment extends DialogFragment {
+ EditText editTextPower, editTextPrefix, editTextSuffix;
+ Spinner spinnerDelimiter, spinnerOutput;
+
+ @Override
+ public Dialog onCreateDialog(Bundle savedInstanceState) {
+ View view = getActivity().getLayoutInflater().inflate(R.layout.fragment_directwedge_settings, null);
+
+ AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
+ builder.setTitle("Wedge Settings");
+ //builder.setMessage("simple wedge setttings");
+ builder.setView(view);
+ builder.setPositiveButton("Save", new DialogInterface.OnClickListener() {
+ public void onClick(DialogInterface dialog, int whichButton) {
+ String wedgePower = editTextPower.getText().toString();
+ try {
+ int iWedgePower = Integer.parseInt(wedgePower);
+ if (iWedgePower < 0) iWedgePower = 0;
+ else if (iWedgePower > 300) iWedgePower = 300;
+ editTextPower.setText(String.valueOf(iWedgePower));
+ MainActivity.csLibrary4A.setWedgePower(iWedgePower);
+ } catch (Exception ex) { }
+ MainActivity.csLibrary4A.setWedgePrefix(editTextPrefix.getText().toString());
+ MainActivity.csLibrary4A.setWedgeSuffix(editTextSuffix.getText().toString());
+ int wedgeDelimiter = 0x0A;
+ switch (spinnerDelimiter.getSelectedItemPosition()) {
+ default:
+ break;
+ case 1:
+ wedgeDelimiter = 0x09;
+ break;
+ case 2:
+ wedgeDelimiter = 0x2c;
+ break;
+ case 3:
+ wedgeDelimiter = 0x20;
+ break;
+ case 4:
+ wedgeDelimiter = -1;
+ break;
+ }
+ MainActivity.csLibrary4A.setWedgeDelimiter(wedgeDelimiter);
+ MainActivity.csLibrary4A.appendToLog("SettingWedgeFragment, onCreateDialog: wedgeDelimiter = " + MainActivity.csLibrary4A.getWedgeOutput());
+ MainActivity.csLibrary4A.setWedgeOutput(spinnerOutput.getSelectedItemPosition());
+ MainActivity.csLibrary4A.saveWedgeSetting2File();
+ getDialog().dismiss();
+ }
+ });
+ builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
+ public void onClick(DialogInterface dialog, int whichButton) {
+ getDialog().dismiss();
+ }
+ });
+
+ editTextPower = (EditText) view.findViewById(R.id.directWedgeSettingEditTextPower);
+ MainActivity.csLibrary4A.appendToLog("editTextPower is " + (editTextPower == null ? "null" : "valid"));
+ if (editTextPower != null) editTextPower.setText(String.valueOf(MainActivity.csLibrary4A.getWedgePower()));
+
+ editTextPrefix = (EditText) view.findViewById(R.id.directWedgeSettingEditTextPrefix);
+ MainActivity.csLibrary4A.appendToLog("editTextPrefix is " + (editTextPrefix == null ? "null" : "valid"));
+ if (editTextPrefix != null) editTextPrefix.setText(MainActivity.csLibrary4A.getWedgePrefix());
+
+ editTextSuffix = (EditText) view.findViewById(R.id.directWedgeSettingEditTextSuffix);
+ MainActivity.csLibrary4A.appendToLog("editTextSuffix is " + (editTextSuffix == null ? "null" : "valid"));
+ if (editTextSuffix != null) editTextSuffix.setText(MainActivity.csLibrary4A.getWedgeSuffix());
+
+ spinnerDelimiter = (Spinner) view.findViewById(R.id.directWedgeSettingSpinnerDelimiter);
+ MainActivity.csLibrary4A.appendToLog("spinnerDelimiter is " + (spinnerDelimiter == null ? "null" : "valid"));
+ ArrayAdapter targetAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.delimiter_options, R.layout.custom_spinner_layout);
+ MainActivity.csLibrary4A.appendToLog("targetAdapter is " + (targetAdapter == null ? "null" : "valid"));
+ targetAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+ int position = 0;
+ MainActivity.csLibrary4A.appendToLog("SettingWedgeFragment, onCreatDialog: wedgeDelimiter = " + MainActivity.csLibrary4A.getWedgeDelimiter());
+ switch (MainActivity.csLibrary4A.getWedgeDelimiter()) {
+ default:
+ position = 0;
+ break;
+ case 0x09:
+ position = 1;
+ break;
+ case 0x2C:
+ position = 2;
+ break;
+ case 0x20:
+ position = 3;
+ break;
+ case -1:
+ position = 4;
+ break;
+ }
+ MainActivity.csLibrary4A.appendToLog("position is " + position);
+ spinnerDelimiter.setAdapter(targetAdapter);
+ spinnerDelimiter.setSelection(position);
+
+ spinnerOutput = (Spinner) view.findViewById(R.id.directWedgeSettingSpinnerOutput);
+ MainActivity.csLibrary4A.appendToLog("spinnerOutput is " + (spinnerOutput == null ? "null" : "valid"));
+ ArrayAdapter targetAdapter1 = ArrayAdapter.createFromResource(getActivity(), R.array.wedgeOutput_options, R.layout.custom_spinner_layout);
+ MainActivity.csLibrary4A.appendToLog("targetAdapter1 is " + (targetAdapter1 == null ? "null" : "valid"));
+ targetAdapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+ int position1 = MainActivity.csLibrary4A.getWedgeOutput();
+ MainActivity.csLibrary4A.appendToLog("position1 is " + position1);
+ spinnerOutput.setAdapter(targetAdapter1);
+ spinnerOutput.setSelection(position1);
+
+ return builder.create();
+ }
+}
+
+
+
+package com.csl.cs710ademoapp.fragments;
+
+import static android.Manifest.permission.RECORD_AUDIO;
+import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
+
+import android.content.pm.PackageManager;
+import android.media.MediaPlayer;
+import android.media.MediaRecorder;
+import android.os.Bundle;
+import android.os.Environment;
+import android.os.Handler;
+import android.util.Log;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.Button;
+import android.widget.SeekBar;
+import android.widget.TextView;
+import android.widget.Toast;
+
+import androidx.appcompat.app.AppCompatActivity;
+import androidx.core.app.ActivityCompat;
+import androidx.core.content.ContextCompat;
+
+import com.csl.cs710ademoapp.MainActivity;
+import com.csl.cs710ademoapp.R;
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.text.SimpleDateFormat;
+
+public class Test1Fragment extends CommonFragment {
+ Button startbtn, stopbtn, playbtn, stopplay;
+ MediaRecorder mRecorder;
+ MediaPlayer mediaPlayer;
+ static final String LOG_TAG = "AudioRecording";
+ static String mFileName = null;
+ public static final int REQUEST_AUDIO_PERMISSION_CODE = 1;
+ Handler handler = new Handler();
+
+ TextView seekBarHint;
+ SeekBar seekBar;
+ boolean wasPlaying = false;
+
+ File file;
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ super.onCreateView(inflater, container, savedInstanceState, true);
+ return inflater.inflate(R.layout.fragment_test1, container, false);
+ }
+
+ @Override
+ public void onActivityCreated(Bundle savedInstanceState) {
+ super.onActivityCreated(savedInstanceState);
+
+ androidx.appcompat.app.ActionBar actionBar;
+ actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
+ actionBar.setIcon(R.drawable.dl_access);
+ actionBar.setTitle("Test");
+
+ startbtn = (Button) getActivity().findViewById(R.id.btnRecord);
+ stopbtn = (Button) getActivity().findViewById(R.id.btnStop);
+ playbtn = (Button) getActivity().findViewById(R.id.btnPlay);
+ stopplay = (Button) getActivity().findViewById(R.id.btnStopPlay);
+ stopbtn.setEnabled(false);
+ playbtn.setEnabled(false);
+ stopplay.setEnabled(false);
+ mFileName = Environment.getExternalStorageDirectory().getAbsolutePath();
+ mFileName += "/Download/cs710Java/";
+
+ seekBarHint = (TextView) getActivity().findViewById(R.id.textView);
+ seekBar = (SeekBar) getActivity().findViewById(R.id.seekbar);
+
+ startbtn.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if(CheckPermissions() == false) RequestPermissions();
+ else {
+ startbtn.setEnabled(false);
+ stopbtn.setEnabled(true);
+ playbtn.setEnabled(false);
+ stopplay.setEnabled(false);
+
+ mRecorder = new MediaRecorder();
+ mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
+ mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
+ mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
+ mFileName += "audio";
+ mFileName += new SimpleDateFormat("_yyMMdd_HHmmss").format(new java.util.Date());
+ Log.i("Hello2", "mFileName is " + mFileName );
+ mRecorder.setOutputFile(mFileName + ".3gp");
+ try {
+ mRecorder.prepare();
+ } catch (IOException e) {
+ Log.e(LOG_TAG, "prepare() failed");
+ }
+ mRecorder.start();
+ Toast.makeText(getActivity().getApplicationContext(), "Recording Started", Toast.LENGTH_LONG).show();
+
+ file = new File(getActivity().getFilesDir(), mFileName + ".txt");
+ try {
+ FileOutputStream stream = new FileOutputStream(file);
+ stream.write("Start of data\n".getBytes());
+ String outData = "preFilterData.maskbit";
+ stream.write(outData.getBytes());
+ stream.write("End of data\n".getBytes());
+ stream.close();
+ } catch (Exception ex) {
+ Log.i("Hello2", "Exception is " + ex.toString());
+ }
+
+ MainActivity.mSensorConnector.mLocationDevice.turnOn(true);
+ MainActivity.mSensorConnector.mSensorDevice.turnOn(true);
+ handler.post(runnableRecord);
+ }
+ }
+ });
+
+ stopbtn.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ startbtn.setEnabled(true);
+ stopbtn.setEnabled(false);
+ playbtn.setEnabled(true);
+ stopplay.setEnabled(true);
+ mRecorder.stop();
+ mRecorder.release();
+ mRecorder = null;
+ Toast.makeText(getActivity().getApplicationContext(), "Recording Stopped", Toast.LENGTH_LONG).show();
+
+ MainActivity.mSensorConnector.mLocationDevice.turnOn(false);
+ MainActivity.mSensorConnector.mSensorDevice.turnOn(false);
+ handler.removeCallbacks(runnableRecord);
+ }
+ });
+
+ playbtn.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ startbtn.setEnabled(true);
+ stopbtn.setEnabled(false);
+ playbtn.setEnabled(false);
+ stopplay.setEnabled(true);
+
+ if (mediaPlayer != null) {
+ try {
+ if (mediaPlayer.isPlaying()) {
+ clearMediaPlayer();
+ wasPlaying = true;
+ }
+ } catch (Exception ex) {
+ Log.i("Hello2", "Exception is " + ex.toString());
+ }
+ }
+ if (!wasPlaying) {
+ if (mediaPlayer == null) mediaPlayer = new MediaPlayer();
+ try {
+ mediaPlayer.setDataSource(mFileName);
+ mediaPlayer.prepare();
+ mediaPlayer.setLooping(false);
+ seekBar.setMax(mediaPlayer.getDuration());
+
+ mediaPlayer.start();
+ Toast.makeText(getActivity().getApplicationContext(), "Recording Started Playing", Toast.LENGTH_LONG).show();
+ handler.removeCallbacks(runnablePlay);
+ handler.post(runnablePlay);
+ } catch (IOException e) {
+ Log.e(LOG_TAG, "prepare() failed");
+ }
+ }
+ }
+ });
+
+ stopplay.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ clearMediaPlayer();
+ Toast.makeText(getActivity().getApplicationContext(),"Playing Audio Stopped", Toast.LENGTH_SHORT).show();
+ }
+ });
+
+ seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
+ @Override
+ public void onStartTrackingTouch(SeekBar seekBar) {
+ seekBarHint.setVisibility(View.VISIBLE);
+ }
+
+ @Override
+ public void onProgressChanged(SeekBar seekBar, int progress, boolean fromTouch) {
+ seekBarHint.setVisibility(View.VISIBLE);
+ int x = (int) Math.ceil(progress / 1000f);
+ if (x != 0 && mediaPlayer != null && !mediaPlayer.isPlaying()) {
+ clearMediaPlayer();
+ }
+ }
+
+ @Override
+ public void onStopTrackingTouch(SeekBar seekBar) {
+ if (mediaPlayer != null && mediaPlayer.isPlaying()) {
+ mediaPlayer.seekTo(seekBar.getProgress());
+ }
+ }
+ });
+ }
+
+ void clearMediaPlayer() {
+ if (mediaPlayer != null) {
+ mediaPlayer.stop();
+ mediaPlayer.release();
+ }
+ seekBar.setProgress(0);
+ startbtn.setEnabled(true);
+ stopbtn.setEnabled(false);
+ playbtn.setEnabled(true);
+ stopplay.setEnabled(false);
+ mediaPlayer = null;
+ }
+
+ @Override
+ public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
+ switch (requestCode) {
+ case REQUEST_AUDIO_PERMISSION_CODE:
+ if (grantResults.length> 0) {
+ boolean permissionToRecord = grantResults[0] == PackageManager.PERMISSION_GRANTED;
+ boolean permissionToStore = grantResults[1] == PackageManager.PERMISSION_GRANTED;
+ if (permissionToRecord && permissionToStore) {
+ Toast.makeText(getActivity().getApplicationContext(), "Permission Granted", Toast.LENGTH_LONG).show();
+ } else {
+ Toast.makeText(getActivity().getApplicationContext(),"Permission Denied",Toast.LENGTH_LONG).show();
+ }
+ }
+ break;
+ }
+ }
+
+ boolean CheckPermissions() {
+ int result = ContextCompat.checkSelfPermission(getActivity().getApplicationContext(), WRITE_EXTERNAL_STORAGE);
+ int result1 = ContextCompat.checkSelfPermission(getActivity().getApplicationContext(), RECORD_AUDIO);
+ Log.i("Hello2", "result = " + result + ", result1 = " + result1);
+ return result == PackageManager.PERMISSION_GRANTED && result1 == PackageManager.PERMISSION_GRANTED;
+ }
+
+ void RequestPermissions() {
+ ActivityCompat.requestPermissions(getActivity(), new String[]{RECORD_AUDIO, WRITE_EXTERNAL_STORAGE}, REQUEST_AUDIO_PERMISSION_CODE);
+ }
+
+
+ final Runnable runnableRecord = new Runnable() {
+ boolean DEBUG = false;
+ @Override
+ public void run() {
+ String stringLocation = MainActivity.mSensorConnector.mLocationDevice.getLocation();
+ String stringCompass = MainActivity.mSensorConnector.mSensorDevice.getEcompass();
+ Log.i("Hello2", "stringLocation = " + stringLocation + ", stringCompass = " + stringCompass);
+ handler.postDelayed(runnableRecord, 1000);
+ }
+ };
+
+ final Runnable runnablePlay = new Runnable() {
+ boolean DEBUG = false;
+ @Override
+ public void run() {
+ boolean bPlaying = false;
+ try {
+ if (mediaPlayer != null && mediaPlayer.isPlaying()) {
+ int currentPosition = mediaPlayer.getCurrentPosition();
+ int total = mediaPlayer.getDuration();
+ if (currentPosition < total) {
+ seekBar.setProgress(currentPosition);
+ bPlaying = true;
+ }
+ } else clearMediaPlayer();
+ } catch (Exception ex) {
+ Log.i("Hello2", "Runnable Exception: " + ex.toString());
+ }
+ if (bPlaying) handler.postDelayed(runnablePlay, 1000);
+ else clearMediaPlayer();
+ }
+ };
+
+ @Override
+ public void onDestroy() {
+ super.onDestroy();
+ }
+
+ public Test1Fragment() {
+ super("Test1Fragment");
+ }
+
+}
+
+
+
+package com.csl.cs710ademoapp.fragments;
+
+import android.os.Bundle;
+
+import androidx.appcompat.app.AppCompatActivity;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.Button;
+
+import com.csl.cs710ademoapp.MainActivity;
+import com.csl.cs710ademoapp.R;
+
+public class TestFragment extends CommonFragment {
+ private Button buttonRead;
+ private Button buttonWrite;
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ super.onCreateView(inflater, container, savedInstanceState, true);
+ return inflater.inflate(R.layout.fragment_test, container, false);
+ }
+
+ @Override
+ public void onActivityCreated(Bundle savedInstanceState) {
+ super.onActivityCreated(savedInstanceState);
+
+ androidx.appcompat.app.ActionBar actionBar;
+ actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
+ actionBar.setIcon(R.drawable.dl_access);
+ actionBar.setTitle("Test");
+
+ buttonRead = (Button) getActivity().findViewById(R.id.accessRWReadButton);
+ buttonWrite = (Button) getActivity().findViewById(R.id.accessRWWriteButton);
+ }
+
+ @Override
+ public void onDestroy() {
+ MainActivity.csLibrary4A.setSameCheck(true);
+ MainActivity.csLibrary4A.restoreAfterTagSelect();
+ super.onDestroy();
+ }
+
+ public TestFragment() {
+ super("TestFragment");
+ }
+}
+
+
+
+package com.csl.cs710ademoapp.fragments;
+
+import android.os.Bundle;
+import android.view.LayoutInflater;
+import android.view.MenuItem;
+import android.view.View;
+import android.view.ViewGroup;
+
+import androidx.appcompat.app.ActionBar;
+import androidx.appcompat.app.AppCompatActivity;
+import androidx.viewpager.widget.ViewPager;
+
+import com.csl.cs710ademoapp.MainActivity;
+import com.csl.cs710ademoapp.R;
+import com.csl.cslibrary4a.AdapterTab;
+import com.google.android.material.tabs.TabLayout;
+
+public class Ucode8Fragment extends CommonFragment {
+ private ActionBar actionBar;
+ private ViewPager viewPager;
+ AdapterTab adapter;
+
+ private String[] tabs = {"Configure", "Scan", "Security", "Untrace"};
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ super.onCreateView(inflater, container, savedInstanceState, true);
+ return inflater.inflate(R.layout.custom_tabbed_layout, container, false);
+ }
+
+ @Override
+ public boolean onOptionsItemSelected(MenuItem item) {
+ InventoryRfidiMultiFragment fragment = (InventoryRfidiMultiFragment) adapter.getItem(1);
+ if (item.getItemId() == R.id.menuAction_clear) {
+ fragment.clearTagsList();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_sortRssi) {
+ fragment.sortTagsListByRssi();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_sort) {
+ fragment.sortTagsList();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_save) {
+ fragment.saveTagsList();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_share) {
+ fragment.shareTagsList();
+ return true;
+ } else return super.onOptionsItemSelected(item);
+ }
+
+ @Override
+ public void onActivityCreated(Bundle savedInstanceState) {
+ super.onActivityCreated(savedInstanceState);
+
+ actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
+ actionBar.setIcon(R.drawable.dl_inv);
+ actionBar.setTitle(R.string.title_activity_ucode8);
+
+ TabLayout tabLayout = (TabLayout) getActivity().findViewById(R.id.OperationsTabLayout);
+
+ adapter = new AdapterTab(getActivity().getSupportFragmentManager(), tabs.length);
+ adapter.setFragment(0, new AccessUcode8Fragment());
+ adapter.setFragment(1, InventoryRfidiMultiFragment.newInstance(true, null, ""));
+ adapter.setFragment(2, new AccessUcodeFragment());
+ adapter.setFragment(3, new UtraceFragment());
+
+ viewPager = (ViewPager) getActivity().findViewById(R.id.OperationsPager);
+ viewPager.setAdapter(adapter);
+ viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
+
+ for (String tab_name : tabs) {
+ tabLayout.addTab(tabLayout.newTab().setText(tab_name));
+ }
+
+ tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
+ @Override
+ public void onTabSelected(TabLayout.Tab tab) {
+ viewPager.setCurrentItem(tab.getPosition());
+ }
+
+ @Override
+ public void onTabUnselected(TabLayout.Tab tab) {
+ }
+
+ @Override
+ public void onTabReselected(TabLayout.Tab tab) {
+ }
+ });
+ }
+
+ @Override
+ public void onPause() {
+ adapter.fragment0.onPause();
+ adapter.fragment1.onPause();
+ super.onPause();
+ }
+
+ @Override
+ public void onStop() {
+ adapter.fragment0.onStop();
+ adapter.fragment1.onStop();
+ super.onStop();
+ }
+
+ @Override
+ public void onDestroyView() {
+ adapter.fragment0.onDestroyView();
+ adapter.fragment1.onDestroyView();
+ super.onDestroyView();
+ }
+
+ @Override
+ public void onDestroy() {
+ adapter.fragment0.onDestroy();
+ adapter.fragment1.onDestroy();
+ MainActivity.csLibrary4A.setSelectCriteriaDisable(1);
+ MainActivity.csLibrary4A.restoreAfterTagSelect();
+ super.onDestroy();
+ }
+
+ @Override
+ public void onDetach() {
+ adapter.fragment0.onDetach();
+ adapter.fragment1.onDetach();
+ super.onDetach();
+ }
+
+ public Ucode8Fragment() {
+ super("Ucode8Fragment");
+ }
+}
+
+
+
+package com.csl.cs710ademoapp.fragments;
+
+import static com.csl.cslibrary4a.RfidReader.TagType.TAG_NXP_UCODEDNA;
+
+import android.os.Bundle;
+import android.view.LayoutInflater;
+import android.view.MenuItem;
+import android.view.View;
+import android.view.ViewGroup;
+
+import androidx.appcompat.app.ActionBar;
+import androidx.appcompat.app.AppCompatActivity;
+import androidx.viewpager.widget.ViewPager;
+
+import com.csl.cs710ademoapp.R;
+import com.csl.cslibrary4a.AdapterTab;
+import com.google.android.material.tabs.TabLayout;
+
+public class UcodeFragment extends CommonFragment {
+ private ActionBar actionBar;
+ private ViewPager viewPager;
+ AdapterTab adapter;
+
+ private String[] tabs = {"Scan", "Authenticate"};
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ super.onCreateView(inflater, container, savedInstanceState, true);
+ return inflater.inflate(R.layout.custom_tabbed_layout, container, false);
+ }
+
+ @Override
+ public boolean onOptionsItemSelected(MenuItem item) {
+ InventoryRfidiMultiFragment fragment = (InventoryRfidiMultiFragment) adapter.getItem(0);
+ if (item.getItemId() == R.id.menuAction_clear) {
+ fragment.clearTagsList();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_sortRssi) {
+ fragment.sortTagsListByRssi();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_sort) {
+ fragment.sortTagsList();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_save) {
+ fragment.saveTagsList();
+ return true;
+ } else if (item.getItemId() == R.id.menuAction_share) {
+ fragment.shareTagsList();
+ return true;
+ } else return super.onOptionsItemSelected(item);
+ }
+
+ @Override
+ public void onActivityCreated(Bundle savedInstanceState) {
+ super.onActivityCreated(savedInstanceState);
+
+ actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
+ actionBar.setIcon(R.drawable.dl_inv);
+ actionBar.setTitle(R.string.title_activity_ucodeDNA);
+
+ TabLayout tabLayout = (TabLayout) getActivity().findViewById(R.id.OperationsTabLayout);
+
+ adapter = new AdapterTab(getActivity().getSupportFragmentManager(), tabs.length);
+ adapter.setFragment(0, InventoryRfidiMultiFragment.newInstance(true, TAG_NXP_UCODEDNA, "E2C06"));
+ adapter.setFragment(1, new AccessUcodeFragment());
+
+
+ viewPager = (ViewPager) getActivity().findViewById(R.id.OperationsPager);
+ viewPager.setAdapter(adapter);
+ viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
+
+ for (String tab_name : tabs) {
+ tabLayout.addTab(tabLayout.newTab().setText(tab_name));
+ }
+
+ tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
+ @Override
+ public void onTabSelected(TabLayout.Tab tab) {
+ viewPager.setCurrentItem(tab.getPosition());
+ }
+
+ @Override
+ public void onTabUnselected(TabLayout.Tab tab) {
+ }
+
+ @Override
+ public void onTabReselected(TabLayout.Tab tab) {
+ }
+ });
+ }
+
+ @Override
+ public void onPause() {
+ adapter.fragment0.onPause();
+ adapter.fragment1.onPause();
+ super.onPause();
+ }
+
+ @Override
+ public void onStop() {
+ adapter.fragment0.onStop();
+ adapter.fragment1.onStop();
+ super.onStop();
+ }
+
+ @Override
+ public void onDestroyView() {
+ adapter.fragment0.onDestroyView();
+ adapter.fragment1.onDestroyView();
+ super.onDestroyView();
+ }
+
+ @Override
+ public void onDestroy() {
+ adapter.fragment0.onDestroy();
+ adapter.fragment1.onDestroy();
+ super.onDestroy();
+ }
+
+ @Override
+ public void onDetach() {
+ adapter.fragment0.onDetach();
+ adapter.fragment1.onDetach();
+ super.onDetach();
+ }
+
+ public UcodeFragment() {
+ super("UcodeFragment");
+ }
+}
+
+
+
+package com.csl.cs710ademoapp.fragments;
+
+import android.app.Activity;
+import android.os.AsyncTask;
+import android.os.Bundle;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.Button;
+import android.widget.CheckBox;
+import android.widget.CompoundButton;
+import android.widget.EditText;
+import android.widget.RadioButton;
+import android.widget.Spinner;
+import android.widget.TextView;
+import android.widget.Toast;
+
+import com.csl.cs710ademoapp.AccessTask;
+import com.csl.cs710ademoapp.MainActivity;
+import com.csl.cs710ademoapp.R;
+import com.csl.cs710ademoapp.SelectTag;
+import com.csl.cslibrary4a.ReaderDevice;
+import com.csl.cslibrary4a.RfidReaderChipData;
+
+public class UtraceFragment extends CommonFragment {
+ final boolean DEBUG = true;
+ SelectTag selectTag;
+ Spinner memoryBankSpinner;
+ EditText editTextRWTagID, editTextAccessRWAccPassword;
+ CheckBox checkBoxHideXpc, checkBoxHideEpc, checkBoxHideTid, checkBoxHideUser, checkBoxHideRange;
+ RadioButton radioButtonRangeToggle, radioButtonRangeReduced, radioButtonHideSomeTid, radioButtonHideAllTid;
+
+ EditText editTextEpcSize;
+ private Button buttonUntrace; String strUntraceButtonBackup;
+ private AccessTask accessTask;
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ super.onCreateView(inflater, container, savedInstanceState, false);
+ return inflater.inflate(R.layout.fragment_utrace, container, false);
+ }
+
+ @Override
+ public void onActivityCreated(Bundle savedInstanceState) {
+ super.onActivityCreated(savedInstanceState);
+
+ selectTag = new SelectTag((Activity)getActivity(), 2);
+
+ checkBoxHideXpc = (CheckBox) getActivity().findViewById(R.id.utraceAssertUXPC);
+ checkBoxHideEpc = (CheckBox) getActivity().findViewById(R.id.utraceHideEpc);
+ checkBoxHideEpc.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
+ @Override
+ public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
+ TextView textView = (TextView) getActivity().findViewById(R.id.utraceEpcLengthTitle);
+ if (isChecked) {
+ textView.setVisibility(View.VISIBLE);
+ editTextEpcSize.setVisibility(View.VISIBLE);
+ } else {
+ textView.setVisibility(View.INVISIBLE);
+ editTextEpcSize.setVisibility(View.INVISIBLE);
+ }
+ }
+ });
+ checkBoxHideTid = (CheckBox) getActivity().findViewById(R.id.utraceHideTid);
+ radioButtonHideSomeTid = (RadioButton) getActivity().findViewById(R.id.utraceHideSomeTid);
+ radioButtonHideAllTid = (RadioButton) getActivity().findViewById(R.id.utraceHideAllTid);
+ checkBoxHideTid.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
+ @Override
+ public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
+ RadioButton radioButton1 = (RadioButton) getActivity().findViewById(R.id.utraceHideSomeTid);
+ RadioButton radioButton2 = (RadioButton) getActivity().findViewById(R.id.utraceHideAllTid);
+ if (isChecked) {
+ radioButton1.setVisibility(View.VISIBLE);
+ radioButton2.setVisibility(View.VISIBLE);
+ } else {
+ radioButton1.setVisibility(View.INVISIBLE);
+ radioButton2.setVisibility(View.INVISIBLE);
+ }
+ }
+ });
+ checkBoxHideUser = (CheckBox) getActivity().findViewById(R.id.utraceHideUser);
+
+ checkBoxHideRange = (CheckBox) getActivity().findViewById(R.id.utraceHideRange);
+ radioButtonRangeToggle = (RadioButton) getActivity().findViewById(R.id.utraceRangeToggle);
+ radioButtonRangeReduced = (RadioButton) getActivity().findViewById(R.id.utraceRangeReduced);
+ checkBoxHideRange.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
+ @Override
+ public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
+ RadioButton radioButton1 = (RadioButton) getActivity().findViewById(R.id.utraceRangeToggle);
+ RadioButton radioButton2 = (RadioButton) getActivity().findViewById(R.id.utraceRangeReduced);
+ if (isChecked) {
+ radioButton1.setVisibility(View.VISIBLE);
+ radioButton2.setVisibility(View.VISIBLE);
+ } else {
+ radioButton1.setVisibility(View.INVISIBLE);
+ radioButton2.setVisibility(View.INVISIBLE);
+ }
+ }
+ });
+
+ editTextEpcSize = (EditText) getActivity().findViewById(R.id.utraceEpcLength);
+
+ selectTag.editTextAccessAntennaPower.setText(String.valueOf(300));
+
+ buttonUntrace = (Button) getActivity().findViewById(R.id.utraceUntraceButton);
+ buttonUntrace.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (MainActivity.csLibrary4A.isBleConnected() == false) {
+ Toast.makeText(MainActivity.mContext, R.string.toast_ble_not_connected, Toast.LENGTH_SHORT).show();
+ return;
+ } else if (MainActivity.csLibrary4A.isRfidFailure()) {
+ Toast.makeText(MainActivity.mContext, "Rfid is disabled", Toast.LENGTH_SHORT).show();
+ return;
+ }
+ startAccessTask();
+ }
+ });
+
+ MainActivity.csLibrary4A.appendToLog("going to setupTagID"); setupTagID();
+ MainActivity.csLibrary4A.setSameCheck(false);
+ }
+
+ @Override
+ public void onResume() {
+ super.onResume();
+ MainActivity.csLibrary4A.appendToLog("going to setupTagID"); setupTagID();
+ }
+
+ @Override
+ public void onDestroy() {
+ if (accessTask != null) accessTask.cancel(true);
+ super.onDestroy();
+ }
+
+ boolean userVisibleHint = false;
+ @Override
+ public void setUserVisibleHint(boolean isVisibleToUser) {
+ super.setUserVisibleHint(isVisibleToUser);
+ if(getUserVisibleHint()) {
+ MainActivity.csLibrary4A.appendToLog("going to setupTagID"); setupTagID();
+ userVisibleHint = true;
+ MainActivity.csLibrary4A.appendToLog("UtraceFragment is now VISIBLE");
+ } else {
+ userVisibleHint = false;
+ MainActivity.csLibrary4A.appendToLog("UtraceFragment is now INVISIBLE");
+ }
+ }
+
+ public UtraceFragment() {
+ super("UtraceFragment");
+ }
+
+ void setupTagID() {
+ MainActivity.csLibrary4A.appendToLog("selectTag 1 = " + (selectTag != null ? "Valid" : "Null"));
+ if (selectTag == null) return;
+ ReaderDevice tagSelected = MainActivity.tagSelected;
+ MainActivity.csLibrary4A.appendToLog("Start with tagSelected = " + (tagSelected == null ? "NULL" : (tagSelected.getSelected() + ", " + tagSelected.getAddress())));
+ boolean bSelected = false;
+ if (tagSelected != null) {
+ if (tagSelected.getSelected() == true) {
+ bSelected = true;
+ MainActivity.csLibrary4A.appendToLog("selectTag is " + (selectTag == null ? "NULL" : "valid"));
+ if (selectTag != null) MainActivity.csLibrary4A.appendToLog("selectTag.editTextTag is " + (selectTag.editTextTagID == null ? "NULL" : "valid"));
+ if (selectTag.editTextTagID != null) {
+ MainActivity.csLibrary4A.appendToLog("editTextRWTagID.setText " + tagSelected.getAddress());
+ selectTag.editTextTagID.setText(tagSelected.getAddress());
+ }
+
+ String stringDetail = tagSelected.getDetails();
+ int indexUser = stringDetail.indexOf("USER=");
+ if (indexUser != -1) {
+ String stringUser = stringDetail.substring(indexUser + 5);
+ MainActivity.csLibrary4A.appendToLog("stringUser = " + stringUser);
+
+ boolean bEnableBAPMode = false;
+ int number = Integer.valueOf(stringUser.substring(3, 4), 16);
+ if ((number % 2) == 1) bEnableBAPMode = true;
+// CheckBox checkBoxBAP = (CheckBox) getActivity().findViewById(R.id.coldChainEnableBAP);
+// checkBoxBAP.setChecked(bEnableBAPMode);
+ }
+ }
+ }
+ }
+
+ void startAccessTask() {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("startAccessTask()");
+ if (updating == false) {
+ updating = true;
+ mHandler.removeCallbacks(updateRunnable);
+ mHandler.post(updateRunnable);
+ }
+ }
+ boolean updating = false;
+ private final Runnable updateRunnable = new Runnable() {
+ @Override
+ public void run() {
+ boolean rerunRequest = false; boolean taskRequest = false;
+ if (accessTask == null) {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("updateRunnable(): NULL accessReadWriteTask");
+ taskRequest = true;
+ } else if (accessTask.getStatus() != AsyncTask.Status.FINISHED) {
+ rerunRequest = true;
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("updateRunnable(): accessReadWriteTask.getStatus() = " + accessTask.getStatus().toString());
+ } else {
+ taskRequest = true;
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("updateRunnable(): FINISHED accessReadWriteTask");
+ }
+ if (processResult()) { MainActivity.csLibrary4A.appendToLog("processResult is TRUE"); }
+ else if (taskRequest) {
+ int rangeValue = 0;
+ if (checkBoxHideRange.isChecked()) {
+ if (radioButtonRangeToggle.isChecked()) rangeValue = 1;
+ else if (radioButtonRangeReduced.isChecked()) rangeValue = 2;
+ }
+ int tidValue = 0;
+ if (checkBoxHideTid.isChecked()) {
+ if (radioButtonHideSomeTid.isChecked()) tidValue = 1;
+ else if (radioButtonHideAllTid.isChecked()) tidValue = 2;
+ }
+ int epcValue = 0;
+ epcValue = Integer.parseInt(editTextEpcSize.getText().toString());
+ if (epcValue < 0 || epcValue > 31) {
+ epcValue = 6; editTextEpcSize.setText("6");
+ }
+ boolean invalid = (MainActivity.csLibrary4A.setUntraceable(rangeValue, checkBoxHideUser.isChecked(), tidValue, epcValue, checkBoxHideEpc.isChecked(), checkBoxHideXpc.isChecked()) == false);
+ MainActivity.csLibrary4A.appendToLog("processTickItems, invalid = " + invalid);
+
+ Button button = buttonUntrace; int selectBank = selectTag.spinnerSelectBank.getSelectedItemPosition() + 1; MainActivity.csLibrary4A.appendToLog("selectBank = " + selectBank);
+ //if (strUntraceButtonBackup == null) strUntraceButtonBackup = buttonUntrace.getText().toString(); buttonUntrace.setText("Show"); button = buttonUntrace;
+ accessTask = new AccessTask(button, null, invalid, true,
+ selectTag.editTextTagID.getText().toString(), selectBank, (selectBank == 1 ? 32 : 0),
+ selectTag.editTextAccessPassword.getText().toString(), Integer.valueOf(selectTag.editTextAccessAntennaPower.getText().toString()), RfidReaderChipData.HostCommands.CMD_UNTRACEABLE,
+ 0, 0, true, false,
+ null, null, null, null, null);
+ accessTask.execute();
+ rerunRequest = true;
+ }
+ if (rerunRequest) {
+ mHandler.postDelayed(updateRunnable, 500);
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("updateRunnable(): Restart");
+ }
+ else updating = false;
+ MainActivity.csLibrary4A.appendToLog("updateRunnable(): Ending with updating = " + updating);
+ }
+ };
+
+ boolean processResult() {
+ String accessResult = null;
+ if (accessTask == null) return false;
+ else if (accessTask.getStatus() != AsyncTask.Status.FINISHED) return false;
+ else {
+ accessResult = accessTask.accessResult;
+ //if (strUntraceButtonBackup != null) buttonUntrace.setText(strUntraceButtonBackup); strUntraceButtonBackup = null;
+ accessTask = null;
+ return true;
+ }
+ }
+}
+
+
+
+package com.csl.cs710ademoapp;
+
+import android.graphics.Color;
+import android.text.Editable;
+import android.text.InputFilter;
+import android.text.TextWatcher;
+import android.widget.EditText;
+
+public class GenericTextWatcher implements TextWatcher {
+ EditText editText;
+ int maxLength;
+ InputFilter mInputFilter;
+
+ public GenericTextWatcher(EditText editText, int maxLength) {
+ this.editText = editText;
+ this.maxLength = maxLength;
+ mInputFilter = new InputFilter.LengthFilter(maxLength);
+ editText.setFilters(new InputFilter[] { mInputFilter });
+ }
+
+ public void afterTextChanged(Editable s) {
+ if (s.length() != 0 && s.length() < maxLength) {
+ editText.setTextColor(Color.RED);
+ } else
+ editText.setTextColor(Color.BLACK);
+ }
+ public void beforeTextChanged(CharSequence s, int start, int count, int after){}
+ public void onTextChanged(CharSequence s, int start, int before, int count){}
+}
+
+
+
+package com.csl.cs710ademoapp;
+
+import android.os.AsyncTask;
+import android.os.Handler;
+import android.widget.Button;
+import android.widget.EditText;
+import android.widget.TextView;
+import android.widget.Toast;
+
+import com.csl.cs710ademoapp.adapters.ReaderListAdapter;
+import com.csl.cslibrary4a.ReaderDevice;
+
+import java.util.ArrayList;
+
+public class InventoryBarcodeTask extends AsyncTask {
+ final boolean DEBUG = false, ALLOW_WEDGE = true;
+ public enum TaskCancelRReason {
+ NULL, INVALD_REQUEST, DESTORY, STOP, BUTTON_RELEASE, TIMEOUT
+ }
+ final private boolean bAdd2End = false;
+ final boolean endingRequest = false;
+
+ public TaskCancelRReason taskCancelReason;
+ int batteryCountInventory_old; long startTimeMillis, runTimeMillis;
+
+ private int total, allTotal;
+ private int yield = 0;
+ private long timeMillis;
+
+ boolean requestSound = false; boolean requestNewSound = false; boolean requestNewVibrate = false; long timeMillisNewVibrate;
+ long timeMillisSound = 0;
+ Handler handler = new Handler(); boolean bUseVibrateMode0 = false;
+
+ protected void onPreExecute() {
+ MainActivity.sharedObjects.runningInventoryBarcodeTask = true;
+ if (button != null) button.setText("Stop"); if (button1 != null) button1.setText("Stop");
+ total = 0; allTotal = 0; yield = 0;
+ if (tagsList != null) {
+ yield = tagsList.size();
+ for (int i = 0; i < yield; i++) {
+ allTotal += tagsList.get(i).getCount();
+ }
+ }
+// tagsList.clear();
+// readerListAdapter.notifyDataSetChanged();
+ timeMillis = 0; startTimeMillis = System.currentTimeMillis(); runTimeMillis = startTimeMillis;
+ taskCancelReason = TaskCancelRReason.NULL;
+ if (barcodeYieldView != null) barcodeYieldView.setText("");
+
+ MainActivity.csLibrary4A.barcodeInventory(true);
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("InventoryBarcodeFragment.InventoryRfidTask.onPreExecute()");
+ MainActivity.csLibrary4A.appendToLog("setVibrateOn A 3 with getInventoryVibrate as " + MainActivity.csLibrary4A.getInventoryVibrate() + ", bUseVibrateMode0 as " + bUseVibrateMode0);
+ if (MainActivity.csLibrary4A.getInventoryVibrate() && bUseVibrateMode0 == false) MainActivity.csLibrary4A.setVibrateOn(3);
+ }
+
+ @Override
+ protected String doInBackground(Void... a) {
+ while (MainActivity.csLibrary4A.isBleConnected() && isCancelled() == false) {
+ int batteryCount = MainActivity.csLibrary4A.getBatteryCount();
+ if (batteryCountInventory_old != batteryCount) {
+ batteryCountInventory_old = batteryCount;
+ publishProgress("VV");
+ }
+ if (System.currentTimeMillis() > runTimeMillis + 1000) {
+ runTimeMillis = System.currentTimeMillis();
+ publishProgress("WW");
+ }
+ if (System.currentTimeMillis() - timeMillisSound > 1000) {
+ timeMillisSound = System.currentTimeMillis();
+ requestSound = true;
+ }
+ byte[] onBarcodeEvent = MainActivity.csLibrary4A.onBarcodeEvent();
+ if (onBarcodeEvent != null) {
+ MainActivity.csLibrary4A.appendToLog("BarStream: onBarcodeEvent= " + MainActivity.csLibrary4A.byteArrayToString(onBarcodeEvent));
+ String stringBar = null;
+ if (true) stringBar = new String(onBarcodeEvent);
+ else if (onBarcodeEvent.length != 0) {
+ for (int i = 0; i < onBarcodeEvent.length; i++) {
+ String stringLetter = "";
+ if (false && onBarcodeEvent[i] == 0x0D) { if (false) stringLetter = ""; }
+ else if (false && onBarcodeEvent[i] == 0x0A) { if (false) stringLetter = ""; }
+ else {
+ byte[] arrayLetter = new byte[1];
+ arrayLetter[0] = onBarcodeEvent[i];
+ stringLetter = new String(arrayLetter);
+ if (stringLetter.length() == 0) MainActivity.csLibrary4A.appendToLog("Non-printable character = " + MainActivity.csLibrary4A.byteArrayToString(arrayLetter));
+ }
+ if (stringBar == null) stringBar = stringLetter;
+ else stringBar += stringLetter;
+ }
+ }
+ MainActivity.csLibrary4A.appendToLog("BarStream: onBarcodeEvent, stringBar= " + stringBar);
+ if (stringBar != null) { if (stringBar.length() != 0) { publishProgress(null, stringBar.trim()); } }
+ timeMillis = System.currentTimeMillis();
+ } else if (System.currentTimeMillis() - timeMillis > 300) { if (taskCancelReason != TaskCancelRReason.NULL) cancel(true); }
+ if (MainActivity.csLibrary4A.isBleConnected() == false) taskCancelReason = TaskCancelRReason.DESTORY;
+ }
+ return "End of Asynctask()";
+ }
+
+ @Override
+ protected void onProgressUpdate(String... output) {
+ if (output != null) {
+ if (output[0] != null) {
+ if (output[0].length() == 2) {
+ if (output[0].contains("WW")) {
+ long timePeriod = (System.currentTimeMillis() - startTimeMillis) / 1000;
+ if (timePeriod > 0)
+ if (barcodeRunTime != null) barcodeRunTime.setText(String.format("Run time: %d sec", timePeriod));
+ } else if (taskCancelReason == TaskCancelRReason.NULL) {
+ if (barcodeVoltageLevel != null) barcodeVoltageLevel.setText(MainActivity.csLibrary4A.getBatteryDisplay(true));
+ }
+ }
+ return;
+ }
+ if (registerBarValue != null) registerBarValue.setText(output[1]);
+ boolean match = false;
+ if (false || tagsList != null) {
+ MainActivity.csLibrary4A.appendToLog("BarMatch: Matching bdata = " + output[1]);
+ for (int i = 0; i < tagsList.size(); i++) {
+ String strInList = tagsList.get(i).getAddress();
+ if (output[1].length() == strInList.length() && output[1].indexOf(strInList) == 0) {
+ MainActivity.csLibrary4A.appendToLog("BarMatch: Matched stored bdata" + i + "= " + tagsList.get(i).getAddress());
+ ReaderDevice readerDevice = tagsList.get(i);
+ int count = readerDevice.getCount();
+ count++;
+ readerDevice.setCount(count);
+ tagsList.set(i, readerDevice);
+ match = true;
+ break;
+ } else MainActivity.csLibrary4A.appendToLog("BarMatch: NOT Matched stored bdata" + i + "= " + tagsList.get(i).getAddress());
+ }
+ }
+ if (match == false) {
+ if (ALLOW_WEDGE) MainActivity.sharedObjects.serviceArrayList.add(output[1]);
+ MainActivity.csLibrary4A.appendToLog(output[1] + " is added to MainActivity.shareObjects.serviceArrayList with size = " + MainActivity.sharedObjects.serviceArrayList.size());
+
+ ReaderDevice readerDevice = new ReaderDevice("", output[1], false, "", 1, 0);
+ if (tagsList != null) {
+ if (bAdd2End) tagsList.add(readerDevice);
+ else tagsList.add(0, readerDevice);
+ }
+ yield++;
+ if (barcodeYieldView != null) barcodeYieldView.setText("Unique:" + String.valueOf(yield));
+ requestNewSound = true; requestNewVibrate = true;
+ }
+ total++; allTotal++;
+ if (barcodeRateView != null) barcodeRateView.setText("Total:" + String.valueOf(allTotal));
+ if (readerListAdapter != null) readerListAdapter.notifyDataSetChanged();
+
+ if (playerN != null && playerO != null) {
+ if (requestSound && playerO.isPlaying() == false && playerN.isPlaying() == false) {
+ if (true) {
+ if (bStartBeepWaiting == false) {
+ bStartBeepWaiting = true;
+ handler.postDelayed(runnableStartBeep, 250);
+ }
+ if (MainActivity.csLibrary4A.getInventoryVibrate()) {
+ boolean validVibrate0 = false, validVibrate = false;
+ if (MainActivity.csLibrary4A.getVibrateModeSetting() == 0) {
+ if (requestNewVibrate) validVibrate0 = true;
+ } else validVibrate0 = true;
+ requestNewVibrate = false;
+
+ if (bUseVibrateMode0 && validVibrate0 && bStartVibrateWaiting == false) {
+ if (System.currentTimeMillis() - timeMillisNewVibrate > MainActivity.csLibrary4A.getVibrateWindow() * 1000 ) {
+ timeMillisNewVibrate = System.currentTimeMillis();
+ validVibrate = true;
+ }
+ }
+ if (validVibrate) {
+ MainActivity.csLibrary4A.appendToLog("setVibrateOn b 1");
+ MainActivity.csLibrary4A.setVibrateOn(1);
+ bStartVibrateWaiting = true;
+ handler.postDelayed(runnableStartVibrate, MainActivity.csLibrary4A.getVibrateTime());
+ }
+ }
+ } else {
+ requestSound = false;
+ if (requestNewSound) {
+ requestNewSound = false;
+ if (playerN != null) playerN.start();
+ } else {
+ if (playerO != null) playerO.start();
+ }
+ }
+ }
+ }
+ } else {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("InventoryBarcodeFragment with NULL data");
+ }
+ }
+
+ boolean bStartBeepWaiting = false;
+ Runnable runnableStartBeep = new Runnable() {
+ @Override
+ public void run() {
+ bStartBeepWaiting = false;
+ requestSound = false;
+ if (requestNewSound) {
+ requestNewSound = false;
+ playerN.start(); //playerN.setVolume(300, 300);
+ } else {
+ playerO.start(); //playerO.setVolume(30, 30);
+ }
+ }
+ };
+
+ boolean bStartVibrateWaiting = false;
+ Runnable runnableStartVibrate = new Runnable() {
+ @Override
+ public void run() {
+ bStartVibrateWaiting = false;
+ }
+ };
+
+ @Override
+ protected void onCancelled() {
+ super.onCancelled();
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("InventoryBarcodeFragment() onCancelled()");
+
+ DeviceConnectTask4InventoryEnding(taskCancelReason);
+ }
+
+ @Override
+ protected void onPostExecute(String result) {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("InventoryBarcodeFragment() onPostExecute(): " + result);
+
+ DeviceConnectTask4InventoryEnding(taskCancelReason);
+ }
+
+ private EditText registerBarValue;
+ private ArrayList tagsList;
+ private ReaderListAdapter readerListAdapter;
+ private TextView barcodeRunTime, barcodeVoltageLevel;
+ private TextView barcodeYieldView;
+ private Button button, button1; String textButton, btextButton1;
+ private TextView barcodeRateView;
+ private boolean noToast;
+ CustomMediaPlayer playerO, playerN;
+ public InventoryBarcodeTask() { }
+ public InventoryBarcodeTask(ArrayList tagsList, ReaderListAdapter readerListAdapter, EditText registerBarValue,
+ TextView barcodeRunTime, TextView barcodeVoltageLevel,
+ TextView barcodeYieldView, Button button, Button button1, TextView barcodeRateView, boolean noToast) {
+ this.registerBarValue = registerBarValue;
+ this.tagsList = tagsList;
+ this.readerListAdapter = readerListAdapter;
+ this.barcodeRunTime = barcodeRunTime;
+ this.barcodeVoltageLevel = barcodeVoltageLevel;
+ this.barcodeYieldView = barcodeYieldView;
+ this.button = button; textButton = button.getText().toString();
+ this.button1 = button1; if (button1 != null) btextButton1 = button1.getText().toString();
+ this.barcodeRateView = barcodeRateView;
+ this.noToast = noToast;
+
+ playerO = MainActivity.sharedObjects.playerO;
+ playerN = MainActivity.sharedObjects.playerN;
+ }
+
+ void DeviceConnectTask4InventoryEnding(TaskCancelRReason taskCancelRReason) {
+ if (readerListAdapter != null) readerListAdapter.notifyDataSetChanged();
+ MainActivity.csLibrary4A.barcodeInventory(false);
+ if (true) MainActivity.csLibrary4A.appendToLog("DeviceConnectTask4InventoryEnding(): sent setBarcodeOn(false)");
+ if (taskCancelReason == null) {
+ new Handler().postDelayed(new Runnable() {
+ @Override
+ public void run() {
+ if (noToast == false) Toast.makeText(MainActivity.mContext, R.string.toast_abort_by_END, Toast.LENGTH_SHORT).show();
+ button.setText(textButton);
+ if (button1 != null) button1.setText(btextButton1);
+ }
+ }, 5000);
+ } else {
+ if (endingRequest) {
+ switch (taskCancelReason) {
+ case STOP:
+ if (noToast == false)
+ Toast.makeText(MainActivity.mContext, R.string.toast_abort_by_STOP, Toast.LENGTH_SHORT).show();
+ break;
+ case BUTTON_RELEASE:
+ if (noToast == false)
+ Toast.makeText(MainActivity.mContext, R.string.toast_abort_by_BUTTON, Toast.LENGTH_SHORT).show();
+ break;
+ }
+ }
+ if (button != null) button.setText(textButton);
+ if (button1 != null) button1.setText(btextButton1);
+ }
+ MainActivity.sharedObjects.runningInventoryBarcodeTask = false;
+ MainActivity.csLibrary4A.appendToLog("setVibrateOn C 0");
+ MainActivity.csLibrary4A.setVibrateOn(0);
+ }
+}
+
+
+
+package com.csl.cs710ademoapp;
+
+import android.content.Context;
+import android.os.AsyncTask;
+import android.os.Handler;
+import android.widget.Button;
+import android.widget.TextView;
+import android.widget.Toast;
+
+import com.csl.cs710ademoapp.adapters.ReaderListAdapter;
+import com.csl.cslibrary4a.ReaderDevice;
+import com.csl.cslibrary4a.RfidReader;
+import com.csl.cslibrary4a.RfidReaderChipData;
+
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Date;
+
+public class InventoryRfidTask extends AsyncTask {
+ final boolean DEBUG = false; final boolean ALLOW_WEDGE = true; boolean ALLOW_RTSAVE = false;
+ public enum TaskCancelRReason {
+ NULL, INVALD_REQUEST, DESTORY, STOP, BUTTON_RELEASE, TIMEOUT, RFID_RESET, ERROR
+ }
+ final private boolean bAdd2End = false;
+ final boolean endingRequest = true;
+
+ Context context;
+ public TaskCancelRReason taskCancelReason;
+ public boolean bSgtinOnly = false, bProtectOnly;
+ private boolean invalidRequest;
+ boolean beepEnable;
+
+ private ArrayList tagsList;
+ private ReaderListAdapter readerListAdapter;
+ private TextView geigerTagRssiView;
+ private TextView rfidRunTime, geigerTagGotView, rfidVoltageLevel;
+ private TextView rfidYieldView, rfidRateView;
+ private Button button;
+
+ CustomMediaPlayer playerO, playerN; int requestSoundCount;
+
+ int extra1Bank = -1, extra2Bank = -1;
+ RfidReader.TagType tagType; String strMdid;
+
+ final boolean invalidDisplay = false;
+ private int total, allTotal;
+ private int yield, yield4RateCount, yieldRate;
+ double rssi = 0; int phase, chidx, data1_count, data2_count, data1_offset, data2_offset;
+ int port = -1; int portstatus; int backport1, backport2, codeSensor, codeRssi; float codeTempC; final int INVALID_CODEVALUE = -500; String brand;
+ long timeMillis, startTimeMillis, runTimeMillis;
+ long firstTime;
+ long lastTime;
+ boolean continousRequest = false;
+ int batteryCountInventory_old;
+
+ boolean requestSound = false; boolean requestNewSound = false; boolean requestNewVibrate = false; long timeMillisNewVibrate;
+ String strEpcOld = "";
+ private ArrayList rx000pkgDataArrary = new ArrayList();
+ private String endingMessaage;
+
+ SaveList2ExternalTask saveExternalTask;
+ boolean serverConnectValid = false;
+ Handler handler = new Handler(); boolean bValidVibrateNewAll = false; boolean bUseVibrateMode0 = false;
+
+ void inventoryHandler_setup() {
+ MainActivity.csLibrary4A.appendToLog("InventoryRfidTask.inventoryHandler_setup set runningInventoryRfidTask as true ");
+ MainActivity.sharedObjects.runningInventoryRfidTask = true;
+ total = 0; allTotal = 0; yield = 0;
+ if (tagsList != null) {
+ yield = tagsList.size();
+ for (int i = 0; i < yield; i++) {
+ allTotal += tagsList.get(i).getCount();
+ }
+ MainActivity.csLibrary4A.appendToLog("yield = " + yield + ", allTotal = " + allTotal);
+ }
+ MainActivity.csLibrary4A.clearInvalidata();
+
+ timeMillis = System.currentTimeMillis(); startTimeMillis = System.currentTimeMillis(); runTimeMillis = startTimeMillis;
+ firstTime = 0;
+ lastTime = 0;
+
+ if (rfidVoltageLevel != null) rfidVoltageLevel.setText("");
+ if (rfidYieldView != null) rfidYieldView.setText("");
+ if (rfidRateView != null) rfidRateView.setText("");
+
+ taskCancelReason = TaskCancelRReason.NULL;
+ if (invalidRequest) {
+ cancel(true);
+ taskCancelReason = TaskCancelRReason.INVALD_REQUEST;
+ Toast.makeText(MainActivity.mContext, "Invalid Request.", Toast.LENGTH_SHORT).show();
+ }
+ if (button != null) button.setText("Stop");
+ MainActivity.mSensorConnector.mLocationDevice.turnOn(true);
+ MainActivity.mSensorConnector.mSensorDevice.turnOn(true);
+ if (ALLOW_RTSAVE) {
+ saveExternalTask = new SaveList2ExternalTask(false);
+ if (saveExternalTask.openServer(false)) {
+ serverConnectValid = true;
+ MainActivity.csLibrary4A.appendToLog("openServer is done");
+ } else {
+ MainActivity.csLibrary4A.appendToLog("openServer has Exception");
+ }
+ }
+ MainActivity.csLibrary4A.appendToLog("serverConnectValid = " + serverConnectValid);
+
+
+ MainActivity.csLibrary4A.appendToLog("getInventoryVibrate = " + MainActivity.csLibrary4A.getInventoryVibrate()
+ + ", bUseVibrate0 = " + bUseVibrateMode0
+ + ", getVibrateModeSetting = " + MainActivity.csLibrary4A.getVibrateModeSetting()
+ );
+ if (MainActivity.csLibrary4A.getInventoryVibrate() && bUseVibrateMode0 == false && MainActivity.csLibrary4A.getVibrateModeSetting() == 1) bValidVibrateNewAll = true;
+ MainActivity.csLibrary4A.appendToLog("setVibrateOn d 2 with bValidVibrateNewAll = " + bValidVibrateNewAll);
+ if (bValidVibrateNewAll) MainActivity.csLibrary4A.setVibrateOn(2);
+ }
+
+ @Override
+ protected void onPreExecute() {
+ //inventoryHandler_setup();
+ }
+
+ byte[] notificationData;
+ @Override
+ protected String doInBackground(Void... a) {
+ boolean ending = false, triggerReleased = false; long triggerReleaseTime = 0;
+ RfidReaderChipData.Rx000pkgData rx000pkgData = null;
+ while (MainActivity.csLibrary4A.onRFIDEvent() != null) { } //clear up possible message before operation
+ while (MainActivity.csLibrary4A.isBleConnected() && isCancelled() == false && ending == false && MainActivity.csLibrary4A.isRfidFailure() == false) {
+ int batteryCount = MainActivity.csLibrary4A.getBatteryCount();
+ if (batteryCountInventory_old != batteryCount) {
+ batteryCountInventory_old = batteryCount;
+ publishProgress("VV");
+ }
+ if (System.currentTimeMillis() > runTimeMillis + 1000) {
+ runTimeMillis = System.currentTimeMillis();
+ publishProgress("WW");
+ }
+
+ notificationData = MainActivity.csLibrary4A.onNotificationEvent();
+ rx000pkgData = MainActivity.csLibrary4A.onRFIDEvent();
+ if (rx000pkgData != null && MainActivity.csLibrary4A.mrfidToWriteSize() == 0) {
+ if (rx000pkgData.responseType == null) {
+ publishProgress("null response");
+ } else if (rx000pkgData.responseType == RfidReaderChipData.HostCmdResponseTypes.TYPE_18K6C_INVENTORY) {
+ {
+ if (rx000pkgData.decodedError != null) publishProgress(rx000pkgData.decodedError);
+ else {
+ if (firstTime == 0) firstTime = rx000pkgData.decodedTime;
+ else lastTime = rx000pkgData.decodedTime;
+ rx000pkgDataArrary.add(rx000pkgData); publishProgress(null, "", "");
+ }
+ }
+ } else if (rx000pkgData.responseType == RfidReaderChipData.HostCmdResponseTypes.TYPE_18K6C_INVENTORY_COMPACT) {
+ {
+ if (rx000pkgData.decodedError != null) publishProgress(rx000pkgData.decodedError);
+ else {
+ if (firstTime == 0) firstTime = rx000pkgData.decodedTime;
+ rx000pkgDataArrary.add(rx000pkgData); publishProgress(null, "", "");
+ }
+ }
+ } else if (rx000pkgData.responseType == RfidReaderChipData.HostCmdResponseTypes.TYPE_ANTENNA_CYCLE_END) {
+ timeMillis = System.currentTimeMillis();
+ } else if (rx000pkgData.responseType == RfidReaderChipData.HostCmdResponseTypes.TYPE_COMMAND_ABORT_RETURN) {
+ MainActivity.csLibrary4A.appendToLog("AAA: Abort return is received !!!");
+ ending = true;
+ } else if (rx000pkgData.responseType == RfidReaderChipData.HostCmdResponseTypes.TYPE_COMMAND_END) {
+ if (rx000pkgData.decodedError != null) endingMessaage = rx000pkgData.decodedError;
+ if (continousRequest) {
+ MainActivity.csLibrary4A.batteryLevelRequest();
+ MainActivity.csLibrary4A.appendToLog("Debug_Compact: InventoryRfidTask.doInBackground");
+ MainActivity.csLibrary4A.startOperation(RfidReaderChipData.OperationTypes.TAG_INVENTORY_COMPACT);
+ } else ending = true;
+ }
+ } else if (false && notificationData != null) {
+ MainActivity.csLibrary4A.appendToLog("matched Error: resultError=" + MainActivity.csLibrary4A.byteArrayToString(notificationData));
+ publishProgress("P");
+ taskCancelReason = TaskCancelRReason.ERROR;
+ }
+ if (false) {
+ if (MainActivity.csLibrary4A.mrfidToWriteSize() != 0) timeMillis = System.currentTimeMillis();
+ } else {
+ //suspend the current thread up to 5 seconds until all the commands on the output buffer got sent out
+ long toCnt = System.currentTimeMillis();
+ if (MainActivity.csLibrary4A.mrfidToWriteSize() != 0) {
+ while (System.currentTimeMillis() - toCnt < 50000 && MainActivity.csLibrary4A.mrfidToWriteSize() != 0) {
+ try {
+ Thread.sleep(200);
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ }
+ MainActivity.csLibrary4A.appendToLog("InventoryRfidTask: send commands elapsed time: " + String.format("%d", System.currentTimeMillis() - toCnt));
+ timeMillis = System.currentTimeMillis();
+ }
+ }
+ if (System.currentTimeMillis() - timeMillis > 10000 && false) { //no tag timeout handling during inventory
+ if (true) taskCancelReason = TaskCancelRReason.TIMEOUT;
+ else {
+ timeMillisSound = System.currentTimeMillis();
+ requestSound = true;
+ }
+ }
+ if (triggerReleased == false && taskCancelReason == TaskCancelRReason.BUTTON_RELEASE) {
+ triggerReleased = true; triggerReleaseTime = System.currentTimeMillis();
+ //taskCancelReason = TaskCancelRReason.NULL;
+ MainActivity.csLibrary4A.appendToLog("AAA: release is triggered !!!");
+ }
+ if (taskCancelReason != TaskCancelRReason.NULL) {
+ MainActivity.csLibrary4A.abortOperation();
+ publishProgress("XX");
+ if (popRequest) publishProgress("P");
+ timeMillis = 0;
+ boolean endStatus = true;
+ cancel(true);
+ } else if (triggerReleased && (System.currentTimeMillis() > (triggerReleaseTime + 2000))) {
+ MainActivity.csLibrary4A.appendToLog("AAA: triggerRelease Timeout !!!");
+ taskCancelReason = TaskCancelRReason.BUTTON_RELEASE;
+ }
+ }
+ String stringReturn = "End of Asynctask()";
+ if (MainActivity.csLibrary4A.isBleConnected() == false) stringReturn = "isBleConnected is false";
+ else if (isCancelled()) stringReturn = "isCancelled is true";
+ else if (MainActivity.csLibrary4A.isRfidFailure()) stringReturn = "isRfidFailure is true";
+ else if (ending) stringReturn = (rx000pkgData == null ? "null ending" : (rx000pkgData.responseType.toString() + " ending"));
+ return stringReturn;
+ }
+
+ long firstTimeOld = 0, timeMillisSound = 0; int totalOld = 0;
+ @Override
+ protected void onProgressUpdate(String... output) {
+ if (false) MainActivity.csLibrary4A.appendToLog("InventoryRfidTask: output[0] = " + output[0]);
+ if (output[0] != null) {
+ if (output[0].length() == 1) inventoryHandler_endReason();
+ else if (output[0].length() == 2) {
+ if (output[0].contains("XX")) MainActivity.csLibrary4A.appendToLogView("CANCELLING: PostProgressUpdate sent abortOperation");
+ else if (output[0].contains("WW")) inventoryHandler_runtime();
+ else if (output[0].contains("VV")) inventoryHandler_voltage();
+ } else
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("InventoryRfidTask.InventoryRfidTask.onProgressUpdate(): " + output[0]);
+ } else tagHandler();
+ }
+
+ void inventoryHandler_endReason() {
+ String message;
+ switch (taskCancelReason) {
+ case STOP:
+ message = "Stop button pressed";
+ break;
+ case BUTTON_RELEASE:
+ message = "Trigger Released";
+ break;
+ case TIMEOUT:
+ message = "Time Out";
+ break;
+ case ERROR:
+ message = "Inventory Notification Error code A101: " + MainActivity.csLibrary4A.byteArrayToString(notificationData);
+ break;
+ default:
+ message = taskCancelReason.name();
+ break;
+ }
+ CustomPopupWindow customPopupWindow = new CustomPopupWindow(MainActivity.mContext);
+ customPopupWindow.popupStart(message, false);
+ }
+ void inventoryHandler_runtime() {
+ long timePeriod = (System.currentTimeMillis() - startTimeMillis) / 1000;
+ if (timePeriod > 0) {
+ if (rfidRunTime != null) rfidRunTime.setText(String.format("Run time: %d sec", timePeriod));
+ yieldRate = yield4RateCount; yield4RateCount = 0;
+ }
+ }
+ void inventoryHandler_voltage() {
+ if (rfidVoltageLevel != null) rfidVoltageLevel.setText(MainActivity.csLibrary4A.getBatteryDisplay(true));
+ }
+
+ boolean bGotTagRate = false;
+ void tagHandler() {
+ boolean DEBUG = false;
+ {
+ long currentTime = 0;
+ {
+ while (rx000pkgDataArrary.size() != 0) {
+ RfidReaderChipData.Rx000pkgData rx000pkgData = rx000pkgDataArrary.get(0);
+ rx000pkgDataArrary.remove(0);
+ if (rx000pkgData == null) {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("InventoryRfidTask: null rx000pkgData !!!");
+ continue;
+ };
+
+ boolean match = false;
+ boolean updated = false;
+ currentTime = rx000pkgData.decodedTime;
+ int iFlag = rx000pkgData.flags;
+ String strPc = MainActivity.csLibrary4A.byteArrayToString(rx000pkgData.decodedPc);
+ if (strPc.length() != 4) {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("InventoryRfidTask: !!! rx000pkgData.Pc length = " + strPc.length());
+ continue;
+ }
+ /*int extraLength = 0;
+ if (extra1Bank != -1 && rx000pkgData.decodedData1 != null) extraLength += rx000pkgData.decodedData1.length;
+ if (extra2Bank != -1 && rx000pkgData.decodedData2 != null) extraLength += rx000pkgData.decodedData2.length;
+ if (extraLength != 0) {
+ byte[] decodedEpcNew = new byte[rx000pkgData.decodedEpc.length - extraLength];
+ System.arraycopy(rx000pkgData.decodedEpc, 0, decodedEpcNew, 0, decodedEpcNew.length);
+ rx000pkgData.decodedEpc = decodedEpcNew;
+ }*/
+ MainActivity.csLibrary4A.appendToLog("ApData: decodedEpc = " + MainActivity.csLibrary4A.byteArrayToString(rx000pkgData.decodedEpc) + ", data1,2 = " + MainActivity.csLibrary4A.byteArrayToString(rx000pkgData.decodedData1) + ", " + MainActivity.csLibrary4A.byteArrayToString(rx000pkgData.decodedData2));
+ String strEpc = MainActivity.csLibrary4A.byteArrayToString(rx000pkgData.decodedEpc);
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("HelloC: decodePc = " + strPc + ", decodedEpc = " + strEpc + ", iFlags = " + String.format("%2X", iFlag));
+ portstatus = INVALID_CODEVALUE; backport1 = INVALID_CODEVALUE; backport2 = INVALID_CODEVALUE; codeSensor = INVALID_CODEVALUE; codeRssi = INVALID_CODEVALUE; codeTempC = INVALID_CODEVALUE; brand = null;
+ String strExtra2 = null; if (rx000pkgData.decodedData2 != null) strExtra2 = MainActivity.csLibrary4A.byteArrayToString(rx000pkgData.decodedData2);
+ if (strExtra2 != null && strMdid != null) {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("HelloK: strExtra2 = " + strExtra2 + ", strMdid = " + strMdid);
+ if (strMdid.contains("E200B0")) portstatus = Integer.parseInt(strExtra2.substring(3, 4), 16);
+ }
+ String strExtra1 = null; if (rx000pkgData.decodedData1 != null) {
+ strExtra1 = MainActivity.csLibrary4A.byteArrayToString(rx000pkgData.decodedData1);
+ if (strMdid != null && strExtra1 != null && strExtra2 != null) {
+ MainActivity.csLibrary4A.appendToLog("strExtra1 = " + strExtra1 + ", strExtra2 = " + strExtra2);
+ decodeMicronData(strExtra1, strExtra2);
+ }
+ }
+ String strAddresss = strEpc;
+ String strCrc16 = null; if (rx000pkgData.decodedCrc != null) strCrc16 = MainActivity.csLibrary4A.byteArrayToString(rx000pkgData.decodedCrc);
+
+ int extra1Bank = this.extra1Bank;
+ int data1_offset = this.data1_offset;
+
+ if (strMdid != null) {
+ if (tagType == RfidReader.TagType.TAG_CTESIUS /*strMdid.indexOf("E203510") == 0*/) {
+ if (strEpc.length() == 24 && strExtra2 != null) {
+ codeTempC = MainActivity.csLibrary4A.decodeCtesiusTemperature(strEpc.substring(16, 24), strExtra2);
+ strEpc = strEpc.substring(0, 16); strAddresss = strEpc;
+ }
+ } else if (tagType == RfidReader.TagType.TAG_ASYGN /*strMdid.indexOf("E283A") == 0*/) {
+ MainActivity.csLibrary4A.appendToLog("E283A is found with extra1Bank = " + extra1Bank + ", strExtra1 = " + strExtra1 + ", extra2Bank = " + extra2Bank + ", strExtra2 = " + strExtra2);
+ if (strExtra2 != null && strExtra2.length() >= 28) codeTempC = MainActivity.csLibrary4A.decodeAsygnTemperature(strExtra2);
+ }
+ }
+
+ boolean bFastId = false; boolean bTempId = false;
+ MainActivity.csLibrary4A.appendToLog("bFastId is false with MainActivity.mDid = " + MainActivity.mDid + ", getFastId = " + MainActivity.csLibrary4A.getFastId());
+ if (MainActivity.mDid != null) {
+ if (MainActivity.mDid.indexOf("E28011") == 0) {
+ int iValue = Integer.valueOf(MainActivity.mDid.substring("E28011".length()), 16);
+ MainActivity.csLibrary4A.appendToLog(String.format("iValue = 0x%02X", iValue));
+ if ((iValue & 0x20) != 0) {
+ bFastId = true; MainActivity.csLibrary4A.appendToLog("bFastId is true");
+ }
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("HelloK: iValue = " + String.format("%02X", iValue));
+ }
+ } else if (MainActivity.csLibrary4A.getFastId() > 0) {
+ bFastId = true; MainActivity.csLibrary4A.appendToLog("bFastId is true");
+ }
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("HelloK: strMdid = " + strMdid + ", MainMdid = " + MainActivity.mDid + ", bFastId = " + bFastId);
+
+ int iPc = Integer.parseInt(strPc, 16);
+ String strXpc = null; int iSensorData = ReaderDevice.INVALID_SENSORDATA; if ((iPc & 0x0200) != 0 && strEpc != null && strEpc.length() >= 8) {
+ MainActivity.csLibrary4A.appendToLog("strPc = " + strPc + ", strEpc = " + strEpc);
+ int iXpcw1 = Integer.parseInt(strEpc.substring(0, 4), 16);
+ if ((iXpcw1 & 0x8000) != 0) {
+ strXpc = strEpc.substring(0, 8);
+ strEpc = strEpc.substring(8); strAddresss = strEpc;
+ if (strMdid != null) {
+ if (strMdid.indexOf("E280B12") == 0) {
+ int iXpcw2 = Integer.parseInt(strXpc.substring(4, 8), 16);
+ if ((iXpcw1 & 0x8100) != 0 && (iXpcw2 & 0xF000) == 0) {
+ if ((iXpcw2 & 0x0C00) == 0x0C00) {
+ //iXpcw2 |= 0x200;
+ iSensorData = iXpcw2 & 0x1FF;
+ if ((iXpcw2 & 0x200) != 0) {
+ iSensorData ^= 0x1FF; iSensorData++; iSensorData = -iSensorData;
+ //MainActivity.csLibrary4A.appendToLog(String.format("Hello123: iXpcw2 = %04X, iSensorData = %d", iXpcw2, iSensorData ));
+ }
+ }
+ }
+ }
+ }
+ } else {
+ strXpc = strEpc.substring(0, 4);
+ strEpc = strEpc.substring(4); strAddresss = strEpc;
+ }
+ }
+
+ if (bFastId) {
+ String strEpc1 = null, strTid = null;
+ boolean bValidFastId = false;
+ if (strEpc.length() > 24) {
+ strEpc1 = strEpc.substring(0, strEpc.length() - 24);
+ strTid = strEpc.substring(strEpc.length() - 24, strEpc.length());
+ if (strTid.indexOf("E28011") == 0 || strTid.indexOf("E2C011") == 0 ) {
+ strEpc = strEpc1; strAddresss = strEpc;
+ strExtra2 = strTid;
+ extra2Bank = 2;
+ data2_offset = 0;
+ bValidFastId = true;
+ }
+ }
+ if (bValidFastId == false) return;
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("HelloK: Doing IMPINJ Inventory with strMdid = " + strMdid + ", strEpc1 = " + strEpc1 + ":, strTid = " + strTid);
+ } else if (MainActivity.mDid != null) {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("HelloK: MainActivity.mDid = " + MainActivity.mDid);
+ if (MainActivity.mDid.matches("E2806894B")) {
+ if (strEpc.length() >= 24) {
+ String strEpc1 = strEpc.substring(0, strEpc.length() - 24);
+ String strTid = strEpc.substring(strEpc.length() - 24, strEpc.length());
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("HelloK: matched E2806894B with strEpc = " + strEpc + ", strEpc1 = " + strEpc1 + ", strTid = " + strTid + ", strExtra1 = " + strExtra1);
+ boolean matched = true;
+ if (strExtra1 != null) {
+ if (!(strExtra1.length() == 8 && strTid.contains(strExtra1))) matched = false;
+ }
+ if (matched) {
+ strEpc = strEpc1;
+ strAddresss = strEpc;
+ strExtra2 = strTid;
+ extra2Bank = 2;
+ data2_offset = 0;
+ }
+ /*if (strTid.contains("E2806894") == false) {
+ MainActivity.csLibrary4A.appendToLog("HelloK: Skip the record without strExtra1 E2806894: " + strEpc);
+ return;
+ }*/
+ }
+ } else if (MainActivity.mDid.matches("E2806894C") || MainActivity.mDid.matches("E2806894d")) {
+ if (strEpc.length() >= 4) {
+ String strEpc1 = strEpc.substring(0, strEpc.length() - 4);
+ String strBrand = strEpc.substring(strEpc.length() - 4, strEpc.length());
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("HelloK: matched E2806894B with strEpc = " + strEpc + ", strEpc1 = " + strEpc1 + ", strBrand = " + strBrand + ", strExtra1 = " + strExtra1);
+ boolean matched = true;
+ if (strExtra1 != null || MainActivity.mDid.matches("E2806894d")) {
+ if (!(strExtra1 != null && strExtra1.length() == 8 && strExtra1.contains("E2806894"))) {
+ matched = false;
+ /*if (MainActivity.mDid.matches("E2806894d")) {
+ MainActivity.csLibrary4A.appendToLog("HelloK: Skip the record without strExtra1 E2806894: " + strEpc);
+ return;
+ }*/
+ }
+ }
+ if (matched) {
+ strEpc = strEpc1; strAddresss = strEpc;
+ brand = strBrand;
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("HelloK: brand 1 = " + brand + ", strEpc = " + strEpc);
+ }
+ }
+ }
+ }
+
+ if (DEBUG || true) MainActivity.csLibrary4A.appendToLog("strMdid = " + strMdid + ", strTidCompared = " + strMdid + ", MainActivity.mDid = " + MainActivity.mDid + ", strExtra1 = " + strExtra1 + ", strExtra2 = " + strExtra2);
+ if (strMdid != null) {
+ String strTidCompared = strMdid;
+ if (strTidCompared.indexOf("E28011") == 0) {
+ int iValue = Integer.valueOf(MainActivity.mDid.substring("E28011".length()), 16);
+ MainActivity.csLibrary4A.appendToLog(String.format("iValue = 0x%02X", iValue));
+ if ((iValue & 0x40) != 0) strTidCompared = "E2C011";
+ else if ((iValue & 0x80) != 0) strTidCompared = "E280117";
+ else strTidCompared = "E28011";
+ }
+ MainActivity.csLibrary4A.appendToLog("strTidCompared = " + strTidCompared);
+ if (strTidCompared.matches("E28011")) { }
+ else if (strTidCompared.matches("E2806894") && MainActivity.mDid.matches("E2806894C")) { }
+ else if (strTidCompared.matches("E281D")) { }
+ else if (strTidCompared.matches("E282402")) { }
+ else if (strTidCompared.matches("E282403")) { }
+ else if (strTidCompared.matches("E282405")) { }
+ else { //if (strMdid.matches("E280B0"))
+ boolean bMatched = false;
+ if (strExtra1 != null && strExtra1.indexOf(strTidCompared) == 0) {
+ bMatched = true; if (DEBUG) MainActivity.csLibrary4A.appendToLog("strExtra1 contains strTidCompared");
+ } else if (strExtra2 != null && strExtra2.indexOf(strTidCompared) == 0) {
+ bMatched = true; if (DEBUG) MainActivity.csLibrary4A.appendToLog("strEXTRA2 contains strTidCompared");
+ }
+ MainActivity.csLibrary4A.appendToLog("bMatched = " + bMatched);
+ if (bMatched == false) return;
+ }
+ }
+
+ rssi = rx000pkgData.decodedRssi;
+ phase = rx000pkgData.decodedPhase;
+ chidx = rx000pkgData.decodedChidx;
+ port = rx000pkgData.decodedPort;
+
+ timeMillis = System.currentTimeMillis();
+
+ double rssiGeiger = rssi;
+ if (MainActivity.csLibrary4A.getRssiDisplaySetting() != 0)
+ rssiGeiger -= MainActivity.csLibrary4A.dBuV_dBm_constant;
+ if (geigerTagRssiView != null)
+ geigerTagRssiView.setText(String.format("%.1f", rssiGeiger));
+ if (geigerTagGotView != null) geigerTagGotView.setText(strEpc);
+
+ if (tagsList == null) {
+ if (strEpc.matches(strEpcOld)) {
+ match = true;
+ updated = true;
+ }
+ } else if (readerListAdapter.getSelectDupElim()) {
+ ReaderDevice readerDevice = null;
+ int iMatchItem = -1;
+ if (false) {
+ int index = Collections.binarySearch(MainActivity.sharedObjects.tagsIndexList, new SharedObjects.TagsIndex(strAddresss, 0));
+ if (index >= 0) {
+ iMatchItem = MainActivity.sharedObjects.tagsIndexList.size() - 1 - MainActivity.sharedObjects.tagsIndexList.get(index).getPosition();
+ }
+ } else {
+ String strCompare = null;
+ if (extra1Bank == 2) {
+ strCompare = strExtra1; //MainActivity.csLibrary4A.appendToLog("1strExtra = " + strExtra1 + ", " + readerDevice.getTid() + ", " + readerDevice.getTid().matches(strCompare));
+ } else if (extra2Bank == 2) {
+ strCompare = strExtra2; //MainActivity.csLibrary4A.appendToLog("2strExtra = " + strExtra2 + ", " + readerDevice.getTid() + ", " + readerDevice.getTid().matches(strCompare));
+ }
+ for (int i = 0; i < tagsList.size(); i++) {
+ //MainActivity.csLibrary4A.appendToLog("strEpc = " + strEpc + ", tagsList.get(" + i + ").getAdddress = " + tagsList.get(i).getAddress());
+ if (strEpc == null || tagsList.get(i).getAddress() == null) { }
+ else if (strEpc.matches(tagsList.get(i).getAddress())) {
+ boolean bTidMatched = true;
+ if (strCompare != null && tagsList.get(i).getTid() != null) bTidMatched = tagsList.get(i).getTid().matches(strCompare);
+ if (bTidMatched) {
+ iMatchItem = i;
+ break;
+ }
+ }
+ }
+ }
+ MainActivity.csLibrary4A.appendToLog("Doing duplicate elimination with iMatchItem = " + iMatchItem);
+ if (iMatchItem >= 0) {
+ readerDevice = tagsList.get(iMatchItem);
+ int count = readerDevice.getCount();
+ count++;
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("HelloK: updated Epc = " + readerDevice.getAddress() + ", brand = " + brand);
+ readerDevice.setCount(count);
+ readerDevice.setXpc(strXpc);
+ readerDevice.setRssi(rssi);
+ readerDevice.setPhase(phase);
+ readerDevice.setChannel(chidx);
+ readerDevice.setPort(port);
+ readerDevice.setStatus(portstatus);
+ readerDevice.setBackport1((backport1));
+ readerDevice.setBackport2(backport2);
+ readerDevice.setCodeSensor(codeSensor);
+ readerDevice.setCodeRssi(codeRssi);
+ readerDevice.setBrand(brand);
+ readerDevice.setCodeTempC(codeTempC);
+ readerDevice.setSensorData(iSensorData);
+ if (strExtra1 != null) readerDevice.setExtra1(strExtra1, extra1Bank, data1_offset);
+ else if (readerDevice.getstrExtra1() != null) {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("HelloK: no null replacement of StrExtra1");
+ }
+ if (strExtra2 != null) readerDevice.setExtra2(strExtra2, extra2Bank, data2_offset);
+ else if (readerDevice.getstrExtra2() != null) {
+ MainActivity.csLibrary4A.appendToLog("HelloK: no null replacement of StrExtra2");
+ }
+ tagsList.set(iMatchItem, readerDevice);
+ match = true;
+ updated = true;
+ }
+ }
+ if (ALLOW_WEDGE) MainActivity.sharedObjects.serviceArrayList.add(strEpc);
+
+ boolean bAddDevice = true; String strValue = null;
+ MainActivity.csLibrary4A.appendToLog("bProtectOnly = " + bProtectOnly);
+ if (bSgtinOnly) {
+ strValue = MainActivity.csLibrary4A.getUpcSerial(strEpc);
+ MainActivity.csLibrary4A.appendToLog("bSgtinOnly = " + bSgtinOnly + ", strValue = " + (strValue == null ? "null" : strValue));
+ if (strValue == null) bAddDevice = false;
+ } else if (bProtectOnly) {
+ bAddDevice = false;
+ if (strExtra1 != null) {
+ strValue = strExtra1.substring(strExtra1.length() - 1);
+ int iValue = Integer.parseInt(strValue, 16);
+ MainActivity.csLibrary4A.appendToLog("bProtectOnly = " + bProtectOnly + ", strExtra1 = " + (strExtra1 == null ? "null" : strExtra1) + ", iValue = " + iValue);
+ if ((iValue & 0x02) != 0) bAddDevice = true;
+ } else MainActivity.csLibrary4A.appendToLog("NULL strExtra1");
+ }
+ if (bAddDevice == false) { }
+ else if (match == false) {
+ if (tagsList == null) {
+ strEpcOld = strEpc;
+ updated = true;
+ } else {
+ MainActivity.csLibrary4A.appendToLog("HelloK: New Epc = " + strEpc + ", brand = " + brand);
+ ReaderDevice readerDevice = new ReaderDevice("", strEpc, false, null,
+ strPc, strXpc, strCrc16, strMdid,
+ strExtra1, extra1Bank, data1_offset,
+ strExtra2, extra2Bank, data2_offset,
+ new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS").format(new Date()), new SimpleDateFormat("z").format(new Date()).replaceAll("GMT", ""),
+ MainActivity.mSensorConnector.mLocationDevice.getLocation(), MainActivity.mSensorConnector.mSensorDevice.getEcompass(),
+ 1, rssi, phase, chidx, port, portstatus, backport1, backport2, codeSensor, codeRssi, codeTempC, brand, iSensorData);
+ if (bSgtinOnly && strValue != null) readerDevice.setUpcSerial(strValue);
+ if (strMdid != null) {
+ if (strMdid.indexOf("E282402") == 0) readerDevice.setCodeSensorMax(0x1F);
+ else readerDevice.setCodeSensorMax(0x1FF);
+ }
+ if (bAdd2End) tagsList.add(readerDevice);
+ else tagsList.add(0, readerDevice);
+ SharedObjects.TagsIndex tagsIndex = new SharedObjects.TagsIndex(strAddresss, tagsList.size() - 1); MainActivity.sharedObjects.tagsIndexList.add(tagsIndex); Collections.sort(MainActivity.sharedObjects.tagsIndexList);
+ MainActivity.csLibrary4A.appendToLog("openServer: serverConnectValid is " + serverConnectValid);
+ if (serverConnectValid && ALLOW_RTSAVE && true) {
+ try {
+// saveExternalTask = new SaveList2ExternalTask();
+// saveExternalTask.openServer();
+ String msgOutput = saveExternalTask.createJSON(null, readerDevice).toString(); MainActivity.csLibrary4A.appendToLog("Json = " + msgOutput);
+ saveExternalTask.write2Server(msgOutput);
+ MainActivity.csLibrary4A.appendToLog("openServer: write2Server data = " + msgOutput);
+
+ // saveExternalTask.closeServer();
+ MainActivity.csLibrary4A.appendToLog("write2Server is done");
+ } catch (Exception ex) {
+ MainActivity.csLibrary4A.appendToLog("write2Server has Exception");
+ }
+ }
+ }
+ yield++; yield4RateCount++;
+ updated = true;
+ requestNewSound = true; requestNewVibrate = true;
+ requestSound = true;
+ }
+ if (updated && bAddDevice) {
+ total++;
+ allTotal++;
+ }
+ }
+ }
+ if (++requestSoundCount >= MainActivity.csLibrary4A.getBeepCount()) {
+ requestSoundCount = 0;
+ requestSound = true;
+ }
+ if (requestSound && requestNewSound) requestSoundCount = 0;
+ if (readerListAdapter != null) readerListAdapter.notifyDataSetChanged();
+ if (invalidDisplay) {
+ if (rfidYieldView != null) rfidYieldView.setText(String.valueOf(total) + "," + String.valueOf(MainActivity.csLibrary4A.getValidata()));
+ if (rfidRateView != null) rfidRateView.setText(String.valueOf(MainActivity.csLibrary4A.getInvalidata()) + "," + String.valueOf(MainActivity.csLibrary4A.getInvalidUpdata()));
+ } else {
+ String stringTemp = "Unique:" + String.valueOf(yield);
+ stringTemp += "\nTotal:" + String.valueOf(allTotal) + "\n";
+ if (rfidYieldView != null) rfidYieldView.setText(stringTemp);
+ if (total != 0 && currentTime - firstTimeOld > 500) {
+ if (firstTimeOld == 0) firstTimeOld = firstTime;
+ if (totalOld == 0) totalOld = total;
+
+ String strRate = "Error:" + String.valueOf(MainActivity.csLibrary4A.getInvalidata()) + "/";
+ if (true) {
+ float fErrorRate = (float) MainActivity.csLibrary4A.getInvalidata() / ((float) MainActivity.csLibrary4A.getValidata() + (float) MainActivity.csLibrary4A.getInvalidata()) * 100;
+ strRate += String.valueOf(MainActivity.csLibrary4A.getValidata()) + "/" + String.valueOf((int) fErrorRate) + "%";
+ } else if (true) {
+ strRate += String.valueOf(MainActivity.csLibrary4A.getInvalidUpdata()) + "/" + String.valueOf(MainActivity.csLibrary4A.getValidata());
+ }
+
+ strRate += "\nRate/New:";
+ if (firstTimeOld != 0) {
+ long tagRate = MainActivity.csLibrary4A.getTagRate();
+ long tagRate2 = -1;
+ if (currentTime > firstTimeOld) tagRate2 = totalOld * 1000 / (currentTime - firstTimeOld);
+ if (tagRate >= 0 || bGotTagRate) {
+ bGotTagRate = true;
+ if (true) strRate += (tagRate != -1 ? String.valueOf(tagRate) : "___");
+ else strRate += (tagRate != -1 ? String.valueOf(tagRate) : "___") + "/" + String.valueOf(tagRate2);
+ strRate += "/" + String.valueOf(yieldRate);
+ } else {
+ if (lastTime == 0) {
+ tagRate = MainActivity.csLibrary4A.getStreamInRate() / 17;
+ //strRate += "rAte";
+ } else if (currentTime > firstTimeOld) {
+ tagRate = totalOld * 1000 / (currentTime - firstTimeOld);
+ //strRate += "Rate";
+ }
+ strRate += String.valueOf(tagRate) + "/" + String.valueOf(yieldRate);
+ }
+ }
+
+ if (rfidRateView != null) rfidRateView.setText(strRate);
+ //if (lastTime - firstTime > 1000) {
+ firstTimeOld = currentTime;
+ totalOld = total;
+ total = 0;
+ //}
+ }
+ }
+ if (false) MainActivity.csLibrary4A.appendToLogView("playerN = " + (playerN == null ? "Null" : "Valid") + ", playerO = " + (playerO == null ? "Null" : "Valid"));
+ if (playerN != null && playerO != null) {
+ if (false) MainActivity.csLibrary4A.appendToLogView("requestSound = " + requestSound + ", bStartBeepWaiting = " + bStartBeepWaiting + ", Op=" + playerO.isPlaying() + ", Np=" + playerN.isPlaying());
+ if (requestSound && playerO.isPlaying() == false && playerN.isPlaying() == false) {
+ if (true) {
+ if (bStartBeepWaiting == false) {
+ bStartBeepWaiting = true;
+ if (false) MainActivity.csLibrary4A.appendToLogView("Going to play old song");
+ handler.postDelayed(runnableStartBeep, 250);
+ }
+ if (MainActivity.csLibrary4A.getInventoryVibrate()) {
+ boolean validVibrate0 = false, validVibrate = false;
+ if (MainActivity.csLibrary4A.getVibrateModeSetting() == 0) {
+ if (requestNewVibrate) validVibrate0 = true;
+ } else if (bValidVibrateNewAll == false) validVibrate0 = true;
+ requestNewVibrate = false;
+
+ if (validVibrate0) {
+ if (bStartVibrateWaiting == false) {
+ validVibrate = true;
+ } else if (bUseVibrateMode0 == false) {
+ handler.removeCallbacks(runnableStartVibrate); int timeout = MainActivity.csLibrary4A.getVibrateWindow() * 1000;
+ handler.postDelayed(runnableStartVibrate, MainActivity.csLibrary4A.getVibrateWindow() * 1000);
+ }
+ }
+
+ if (validVibrate) {
+ MainActivity.csLibrary4A.appendToLog("setVibrateOn E with bUseVibrateMode0 as " + bUseVibrateMode0);
+ if (bUseVibrateMode0) MainActivity.csLibrary4A.setVibrateOn(1);
+ else MainActivity.csLibrary4A.setVibrateOn(2);
+ bStartVibrateWaiting = true; int timeout = MainActivity.csLibrary4A.getVibrateWindow() * 1000;
+ handler.postDelayed(runnableStartVibrate, MainActivity.csLibrary4A.getVibrateWindow() * 1000);
+ }
+ }
+ } else {
+ requestSound = false;
+ if (requestNewSound) {
+ requestNewSound = false;
+ playerN.start();
+ } else {
+ playerO.start();
+ }
+ }
+ }
+ }
+ }
+ }
+
+ boolean bStartBeepWaiting = false;
+ Runnable runnableStartBeep = new Runnable() {
+ @Override
+ public void run() {
+ if (false) MainActivity.csLibrary4A.appendToLogView("Playing old song");
+ bStartBeepWaiting = false;
+ requestSound = false;
+ if (requestNewSound) {
+ requestNewSound = false;
+ playerN.start(); //playerN.setVolume(300, 300);
+ } else {
+ playerO.start(); //playerO.setVolume(30, 30);
+ }
+ }
+ };
+
+ boolean bStartVibrateWaiting = false;
+ Runnable runnableStartVibrate = new Runnable() {
+ @Override
+ public void run() {
+ bStartVibrateWaiting = false;
+ MainActivity.csLibrary4A.appendToLog("setVibrateOn F1 with bUseVibrateMode0 as " + bUseVibrateMode0);
+ if (bUseVibrateMode0 == false) MainActivity.csLibrary4A.setVibrateOn(0);
+ }
+ };
+
+ @Override
+ protected void onCancelled() {
+ super.onCancelled();
+ if (DEBUG || true) MainActivity.csLibrary4A.appendToLogView("InventoryRfidTask.InventoryRfidTask.onCancelled()");
+
+ DeviceConnectTask4InventoryEnding(taskCancelReason);
+ }
+
+ @Override
+ protected void onPostExecute(String result) {
+ if (DEBUG || true) MainActivity.csLibrary4A.appendToLogView("InventoryRfidTask.InventoryRfidTask.onPostExecute(): " + result);
+
+ DeviceConnectTask4InventoryEnding(taskCancelReason);
+ }
+
+ public InventoryRfidTask() {
+ inventoryHandler_setup();
+ }
+ public InventoryRfidTask(Context context, int extra1Bank, int extra2Bank, int data1_count, int data2_count, int data1_offset, int data2_offset,
+ boolean invalidRequest, boolean beepEnable,
+ ArrayList tagsList, ReaderListAdapter readerListAdapter, TextView geigerTagRssiView,
+ RfidReader.TagType tagType, String strMdid,
+ TextView rfidRunTime, TextView geigerTagGotView, TextView rfidVoltageLevel,
+ TextView rfidYieldView, Button button, TextView rfidRateView) {
+ this.context = context;
+ this.extra1Bank = extra1Bank;
+ this.extra2Bank = extra2Bank;
+ this.data1_count = data1_count;
+ this.data2_count = data2_count;
+ this.data1_offset = data1_offset;
+ this.data2_offset = data2_offset;
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("data1_count = " + data1_count + ", data2_count = " + data2_count + ", extra1Bank = " + extra1Bank + ", extra2Bank = " + extra2Bank);
+
+ this.invalidRequest = invalidRequest;
+
+ this.geigerTagRssiView = geigerTagRssiView;
+ this.tagsList = tagsList;
+ this.readerListAdapter = readerListAdapter;
+ this.tagType = tagType;
+ this.strMdid = strMdid; MainActivity.csLibrary4A.appendToLog("HelloK: strMdid = " + strMdid);
+
+ this.rfidRunTime = rfidRunTime;
+ this.geigerTagGotView = geigerTagGotView;
+ this.rfidVoltageLevel = rfidVoltageLevel;
+ this.rfidYieldView = rfidYieldView;
+ this.button = button;
+ this.rfidRateView = rfidRateView;
+ this.beepEnable = beepEnable;
+
+ MainActivity.csLibrary4A.appendToLogView("going to create playerO and playerN with beepEnable = " + beepEnable);
+ if (tagsList != null && readerListAdapter != null && beepEnable) {
+ playerO = MainActivity.sharedObjects.playerO;
+ playerN = MainActivity.sharedObjects.playerN;
+ MainActivity.csLibrary4A.appendToLogView("playerO and playerN is created");
+ }
+ inventoryHandler_setup();
+ }
+
+ boolean popRequest = false; Toast mytoast;
+ void DeviceConnectTask4InventoryEnding(TaskCancelRReason taskCancelReason) {
+ MainActivity.csLibrary4A.appendToLogView("CANCELLING: TaskEnding sent abortOperation again with taskCancelReason = " + taskCancelReason.toString());
+ MainActivity.csLibrary4A.abortOperation(); //added in case previous command end is received with inventory stopped
+ MainActivity.csLibrary4A.appendToLog("serverConnectValid = " + serverConnectValid);
+ if (serverConnectValid && ALLOW_RTSAVE) {
+ if (saveExternalTask.closeServer()) MainActivity.csLibrary4A.appendToLog("closeServer is done");
+ else MainActivity.csLibrary4A.appendToLog("closeServer has Exception");
+ }
+ MainActivity.csLibrary4A.appendToLog("INVENDING: Ending with endingRequest = " + endingRequest);
+ if (MainActivity.mContext == null) return;
+ if (readerListAdapter != null) readerListAdapter.notifyDataSetChanged();
+ if (mytoast != null) mytoast.cancel();
+ if (endingRequest) {
+ switch (taskCancelReason) {
+ case NULL:
+ mytoast = Toast.makeText(MainActivity.mContext, R.string.toast_abort_by_END, Toast.LENGTH_SHORT);
+ break;
+ case STOP:
+ mytoast = Toast.makeText(MainActivity.mContext, R.string.toast_abort_by_STOP, Toast.LENGTH_SHORT);
+ break;
+ case BUTTON_RELEASE:
+ if (false) mytoast = Toast.makeText(MainActivity.mContext, R.string.toast_abort_by_BUTTON, Toast.LENGTH_SHORT);
+ break;
+ case TIMEOUT:
+ mytoast = Toast.makeText(MainActivity.mContext, R.string.toast_abort_by_TIMEOUT, Toast.LENGTH_SHORT);
+ break;
+ case RFID_RESET:
+ mytoast = Toast.makeText(MainActivity.mContext, R.string.toast_abort_by_RFIDRESET, Toast.LENGTH_SHORT);
+ break;
+ case INVALD_REQUEST:
+ mytoast = Toast.makeText(MainActivity.mContext, R.string.toast_invalid_sendHostRequest, Toast.LENGTH_SHORT);
+ break;
+ default:
+ mytoast = Toast.makeText(MainActivity.mContext, ("Finish reason as " + taskCancelReason.toString()), Toast.LENGTH_SHORT);
+ break;
+ }
+ MainActivity.csLibrary4A.appendToLog("INVENDING: Toasting");
+ if (mytoast != null) mytoast.show();
+ }
+ if (button != null) button.setText("Start");
+ MainActivity.csLibrary4A.appendToLog("InventoryRfidTask.DeviceConnectTask4InventoryEnding set runningInventoryRfidTask as false ");
+ MainActivity.sharedObjects.runningInventoryRfidTask = false;
+ if (endingMessaage != null) {
+ CustomPopupWindow customPopupWindow = new CustomPopupWindow(MainActivity.mContext);
+ customPopupWindow.popupStart(endingMessaage, false);
+ }
+ MainActivity.mSensorConnector.mLocationDevice.turnOn(false);
+ MainActivity.mSensorConnector.mSensorDevice.turnOn(false);
+ MainActivity.csLibrary4A.appendToLog("setVibrateOn F 0");
+ MainActivity.csLibrary4A.setVibrateOn(0);
+ }
+
+ String decodeMicronData(String strActData, String strCalData) {
+ int iTag35 = -1;
+ if (strMdid.contains("E282402")) iTag35 = 2;
+ else if (strMdid.contains("E282403")) iTag35 = 3;
+ else if (strMdid.contains("E282405")) iTag35 = 5;
+ if (iTag35 < 2) return "";
+
+ if (iTag35 == 5) {
+ backport1 = Integer.parseInt(strActData.substring(0, 4), 16); backport2 = Integer.parseInt(strActData.substring(4, 8), 16);
+ MainActivity.csLibrary4A.appendToLog("backport1 = " + backport1 + ", backport2 = " + backport2);
+ strActData = strActData.substring(8);
+ }
+ int iSensorCode = Integer.parseInt(strActData.substring(0,4), 16); iSensorCode &= 0x1FF; if (iTag35 == 2) iSensorCode &= 0x1F; codeSensor = iSensorCode;
+ int iRssi;
+ String strRetValue = "";
+ if (iTag35 == 2) {
+ iRssi = Integer.parseInt(strCalData.substring(0,4), 16); iRssi &= 0x1F; codeRssi = iRssi;
+ } else if (iTag35 == 3) {
+ iRssi = Integer.parseInt(strActData.substring(4,8), 16); iRssi &= 0x1F; codeRssi = iRssi;
+
+ if (true) {
+ if (strActData.length() < 8) return null;
+ codeTempC = MainActivity.csLibrary4A.decodeMicronTemperature(iTag35, strActData.substring(8, 12), strCalData);
+ } else {
+ int calCode1, calTemp1, calCode2, calTemp2, calVer = -1;
+ if (strCalData == null) return null;
+ if (strCalData.length() < 16) return null;
+ int crc = Integer.parseInt(strCalData.substring(0, 4), 16);
+ calCode1 = Integer.parseInt(strCalData.substring(4, 7), 16);
+ calTemp1 = Integer.parseInt(strCalData.substring(7, 10), 16);
+ calTemp1 >>= 1;
+ calCode2 = Integer.parseInt(strCalData.substring(9, 13), 16);
+ calCode2 >>= 1;
+ calCode2 &= 0xFFF;
+ calTemp2 = Integer.parseInt(strCalData.substring(12, 16), 16);
+ calTemp2 >>= 2;
+ calTemp2 &= 0x7FF;
+ calVer = Integer.parseInt(strCalData.substring(15, 16), 16);
+ calVer &= 0x3;
+
+ if (strActData == null) return null;
+ if (strActData.length() < 8) return null;
+
+ float fTemperature = Integer.parseInt(strActData.substring(8, 12), 16);
+ fTemperature = ((float) calTemp2 - (float) calTemp1) * (fTemperature - (float) calCode1);
+ fTemperature /= ((float) (calCode2) - (float) calCode1);
+ fTemperature += (float) calTemp1;
+ fTemperature -= 800;
+ fTemperature /= 10;
+ codeTempC = fTemperature;
+ }
+ } else if (iTag35 == 5) {
+ iRssi = Integer.parseInt(strActData.substring(4,8), 16); iRssi &= 0x1F; codeRssi = iRssi;
+
+ if (true) {
+ codeTempC = MainActivity.csLibrary4A.decodeMicronTemperature(iTag35, strActData.substring(8, 12), strCalData);
+ } else {
+ int iTemp;
+ float calCode2 = Integer.parseInt(strCalData.substring(0, 4), 16);
+ calCode2 /= 16;
+ iTemp = Integer.parseInt(strCalData.substring(4, 8), 16);
+ iTemp &= 0x7FF;
+ float calTemp2 = iTemp;
+ calTemp2 -= 600;
+ calTemp2 /= 10;
+ float calCode1 = Integer.parseInt(strCalData.substring(8, 12), 16);
+ calCode1 /= 16;
+ iTemp = Integer.parseInt(strCalData.substring(12, 16), 16);
+ iTemp &= 0x7FF;
+ float calTemp1 = iTemp;
+ calTemp1 -= 600;
+ calTemp1 /= 10;
+
+ float fTemperature = Integer.parseInt(strActData.substring(8, 12), 16);
+ fTemperature -= calCode1;
+ fTemperature *= (calTemp2 - calTemp1);
+ fTemperature /= (calCode2 - calCode1);
+ fTemperature += calTemp1;
+ codeTempC = fTemperature;
+ }
+ }
+ return "";
+ }
+}
+
+
+
+package com.csl.cs710ademoapp;
+
+import static com.csl.cslibrary4a.RfidReader.TagType.TAG_ALIEN;
+import static com.csl.cslibrary4a.RfidReader.TagType.TAG_ASYGN;
+import static com.csl.cslibrary4a.RfidReader.TagType.TAG_CTESIUS;
+import static com.csl.cslibrary4a.RfidReader.TagType.TAG_EM_BAP;
+
+import android.content.Context;
+import android.content.Intent;
+import android.net.Uri;
+import android.os.Bundle;
+import android.os.Handler;
+import android.util.Log;
+import android.view.Gravity;
+import android.view.View;
+import android.widget.AdapterView;
+import android.widget.ListView;
+import android.widget.TextView;
+import android.widget.Toast;
+
+import androidx.activity.EdgeToEdge;
+import androidx.appcompat.app.AppCompatActivity;
+import androidx.drawerlayout.widget.DrawerLayout;
+import androidx.fragment.app.Fragment;
+import androidx.fragment.app.FragmentManager;
+
+import com.csl.cs710ademoapp.DrawerListContent.DrawerPositions;
+import com.csl.cs710ademoapp.adapters.DrawerListAdapter;
+import com.csl.cs710ademoapp.fragments.AboutFragment;
+import com.csl.cs710ademoapp.fragments.AccessReadWriteFragment;
+import com.csl.cs710ademoapp.fragments.AccessReadWriteUserFragment;
+import com.csl.cs710ademoapp.fragments.AccessRegisterFragment;
+import com.csl.cs710ademoapp.fragments.AccessSecurityFragment;
+import com.csl.cs710ademoapp.fragments.AuraSenseFragment;
+import com.csl.cs710ademoapp.fragments.AxzonSelectorFragment;
+import com.csl.cs710ademoapp.fragments.ColdChainFragment;
+import com.csl.cs710ademoapp.fragments.ConnectionFragment;
+import com.csl.cs710ademoapp.fragments.DirectWedgeFragment;
+import com.csl.cs710ademoapp.fragments.FdmicroFragment;
+import com.csl.cs710ademoapp.fragments.HomeFragment;
+import com.csl.cs710ademoapp.fragments.HomeSpecialFragment;
+import com.csl.cs710ademoapp.fragments.ImpinjFragment;
+import com.csl.cs710ademoapp.fragments.ImpinjM775Fragment;
+import com.csl.cs710ademoapp.fragments.InventoryFragment;
+import com.csl.cs710ademoapp.fragments.InventoryRfidSearchFragment;
+import com.csl.cs710ademoapp.fragments.InventoryRfidSimpleFragment;
+import com.csl.cs710ademoapp.fragments.InventoryRfidiMultiFragment;
+import com.csl.cs710ademoapp.fragments.KilowayFragment;
+import com.csl.cs710ademoapp.fragments.LongjingFragment;
+import com.csl.cs710ademoapp.fragments.SettingFilterFragment;
+import com.csl.cs710ademoapp.fragments.SettingFragment;
+import com.csl.cs710ademoapp.fragments.TestFragment;
+import com.csl.cs710ademoapp.fragments.Ucode8Fragment;
+import com.csl.cs710ademoapp.fragments.UcodeFragment;
+import com.csl.cslibrary4a.CsLibrary4A;
+import com.csl.cslibrary4a.ReaderDevice;
+import com.csl.cslibrary4a.RfidReader;
+
+public class MainActivity extends AppCompatActivity {
+ final boolean DEBUG = false; final String TAG = "Hello";
+ public static boolean foregroundServiceEnable = false;
+ public static boolean activityActive = false;
+ public static DrawerPositions drawerPositionsDefault = DrawerPositions.MAIN;
+ public static int powerLevelMax = 320;
+
+ //Tag to identify the currently displayed fragment
+ Fragment fragment = null;
+ protected static final String TAG_CONTENT_FRAGMENT = "ContentFragment";
+ public static boolean isHomeFragment = false;
+
+ public static TextView mLogView;
+ private DrawerLayout mDrawerLayout;
+ private ListView mDrawerList;
+ private CharSequence mTitle;
+
+ public static Context mContext;
+ public static CsLibrary4A csLibrary4A;
+ public static SharedObjects sharedObjects;
+ public static SensorConnector mSensorConnector;
+ public static ReaderDevice tagSelected;
+
+ Handler mHandler = new Handler();
+
+ public static String mDid; public static int selectHold; public static int selectFor;
+ public static RfidReader.TagType tagType;
+ public static class Config {
+ public String configPassword, configPower, config0, config1, config2, config3;
+ };
+ public static Config config = new Config();
+
+ @Override
+ protected void onCreate(Bundle savedInstanceState) {
+ if (DEBUG) {
+ if (savedInstanceState == null) Log.i(TAG, "MainActivity.onCreate: NULL savedInstanceState");
+ else Log.i(TAG, "MainActivity.onCreate: VALID savedInstanceState");
+ }
+ Log.i("Hello", "PackageName is " + getPackageName());
+ if (getPackageName().matches("com.csl.updwedgeservice")) setContentView(R.layout.activity_main1);
+ else setContentView(R.layout.activity_main);
+
+ mTitle = getTitle();
+ mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
+ mDrawerList = (ListView) findViewById(R.id.left_drawer);
+
+ mLogView = (TextView) findViewById(R.id.log_view);
+
+ // set up the drawer's list view with items and click listener
+ mDrawerList.setAdapter(new DrawerListAdapter(this, R.layout.drawer_list_item, DrawerListContent.ITEMS));
+ mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
+
+ mContext = this;
+ sharedObjects = new SharedObjects(mContext);
+ csLibrary4A = new CsLibrary4A(mContext, mLogView);
+ mSensorConnector = new SensorConnector(mContext);
+
+ EdgeToEdge.enable(this);
+ super.onCreate(savedInstanceState);
+ if (savedInstanceState == null) selectItem(drawerPositionsDefault);
+ if (true) Log.i(TAG, "MainActivity.onCreate.onCreate: END");
+
+ getSupportActionBar().hide();
+ }
+
+ @Override
+ protected void onRestart() {
+ super.onRestart();
+ MainActivity.csLibrary4A.connect(null);
+ if (DEBUG) csLibrary4A.appendToLog("MainActivity.onRestart()");
+ }
+
+ @Override
+ protected void onStart() {
+ super.onStart();
+ if (DEBUG) csLibrary4A.appendToLog("MainActivity.onStart()");
+ }
+
+ @Override
+ protected void onResume() {
+ super.onResume();
+ activityActive = true; wedged = false;
+ if (DEBUG) csLibrary4A.appendToLog("MainActivity.onResume()");
+ }
+
+ @Override
+ protected void onPause() {
+ if (DEBUG) csLibrary4A.appendToLog("MainActivity.onPause()");
+ activityActive = false;
+ super.onPause();
+ }
+
+ @Override
+ protected void onStop() {
+ if (DEBUG) csLibrary4A.appendToLog("MainActivity.onStop()");
+ super.onStop();
+ }
+
+ @Override
+ protected void onDestroy() {
+ if (DEBUG) csLibrary4A.appendToLog("MainActivity.onDestroy()");
+ if (true) { csLibrary4A.disconnect(true); }
+ csLibrary4A = null;
+ super.onDestroy();
+ }
+
+ boolean configureDisplaying = false;
+ Toast configureToast;
+ private final Runnable configureRunnable = new Runnable() {
+ @Override
+ public void run() {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("AAA: mrfidToWriteSize = " + csLibrary4A.mrfidToWriteSize());
+ if (csLibrary4A.mrfidToWriteSize() != 0) {
+ MainActivity.csLibrary4A.mrfidToWritePrint();
+ configureDisplaying = true;
+ mHandler.postDelayed(configureRunnable, 500);
+ } else {
+ configureDisplaying = false;
+ progressDialog.dismiss();
+ }
+ }
+ };
+
+ CustomProgressDialog progressDialog;
+ private void selectItem(DrawerPositions position) {
+ if (DEBUG) Log.i(TAG, "MainActivity.selectItem: position = " + position);
+ if (position != DrawerPositions.MAIN
+ && position != DrawerPositions.SPECIAL
+ && position != DrawerPositions.ABOUT
+ && position != DrawerPositions.CONNECT
+ && position != DrawerPositions.DIRECTWEDGE && csLibrary4A.isBleConnected() == false) {
+ Toast.makeText(MainActivity.mContext, "Bluetooth Disconnected. Please Connect.", Toast.LENGTH_SHORT).show();
+ return;
+ }
+ switch (position) {
+ case MAIN:
+ fragment = new HomeFragment();
+ break;
+ case SPECIAL:
+ fragment = new HomeSpecialFragment();
+ break;
+
+ case ABOUT:
+ //fragment = new Test1Fragment();
+ fragment = new AboutFragment();
+ break;
+ case CONNECT:
+ fragment = new ConnectionFragment();
+ break;
+ case INVENTORY:
+ fragment = new InventoryFragment();
+ break;
+ case SEARCH:
+ fragment = new InventoryRfidSearchFragment(false);
+ break;
+ case MULTIBANK:
+ fragment = InventoryRfidiMultiFragment.newInstance(true, null, null);
+ break;
+ case SIMINVENTORY:
+ fragment = InventoryRfidSimpleFragment.newInstance(false, null);
+ break;
+ case SETTING:
+ fragment = new SettingFragment();
+ break;
+ case FILTER:
+ fragment = new SettingFilterFragment();
+ break;
+ case READWRITE:
+ fragment = new AccessReadWriteFragment();
+ break;
+ case SECURITY:
+ fragment = new AccessSecurityFragment();
+ break;
+
+ case IMPINVENTORY:
+ fragment = new ImpinjFragment();
+ break;
+ case IMP775:
+ fragment = new ImpinjM775Fragment();
+ break;
+ case ALIEN:
+ fragment = InventoryRfidiMultiFragment.newInstance(true, TAG_ALIEN, "E2003");
+ break;
+ case UCODE8:
+ fragment = new Ucode8Fragment();
+ break;
+ case UCODEDNA:
+ fragment = new UcodeFragment();
+ break;
+ case BAPCARD:
+ fragment = InventoryRfidiMultiFragment.newInstance(true, TAG_EM_BAP, "E200B0");
+ break;
+ case COLDCHAIN:
+ fragment = new ColdChainFragment();
+ break;
+ case AURASENSE:
+ fragment = new AuraSenseFragment();
+ break;
+ case KILOWAY:
+ fragment = new KilowayFragment();
+ break;
+ case LONGJING:
+ fragment = new LongjingFragment();
+ break;
+ case AXZON:
+ fragment = AxzonSelectorFragment.newInstance(true);
+ break;
+ case RFMICRON:
+ fragment = AxzonSelectorFragment.newInstance(false);
+ break;
+ case FDMICRO:
+ fragment = new FdmicroFragment();
+ break;
+ case CTESIUS:
+ fragment = InventoryRfidiMultiFragment.newInstance(true, TAG_CTESIUS, "E203510");
+ break;
+ case ASYGNTAG:
+ fragment = InventoryRfidiMultiFragment.newInstance(true, TAG_ASYGN, "E283A");
+ break;
+
+ case REGISTER:
+ fragment = new AccessRegisterFragment();
+ break;
+ case READWRITEUSER:
+ fragment = new AccessReadWriteUserFragment();
+ break;
+ case WEDGE:
+ case DIRECTWEDGE:
+ fragment = new DirectWedgeFragment();
+ break;
+ case BLANK:
+ fragment = new TestFragment();
+ break;
+ }
+
+ FragmentManager fragmentManager = getSupportFragmentManager();
+
+ if (position == drawerPositionsDefault) {
+ //Pop the back stack since we want to maintain only one level of the back stack
+ //Don't add the transaction to back stack since we are navigating to the first fragment
+ //being displayed and adding the same to the backstack will result in redundancy
+ fragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
+ fragmentManager.beginTransaction().replace(R.id.content_frame, fragment, TAG_CONTENT_FRAGMENT).commit();
+ } else {
+ //Pop the back stack since we want to maintain only one level of the back stack
+ //Add the transaction to the back stack since we want the state to be preserved in the back stack
+ //fragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
+ fragmentManager.beginTransaction().replace(R.id.content_frame, fragment, TAG_CONTENT_FRAGMENT).addToBackStack(null).commit();
+ }
+ mDrawerLayout.closeDrawer(mDrawerList);
+ }
+
+ @Override
+ public void setTitle(CharSequence title) {
+ mTitle = title;
+ getSupportActionBar().setTitle(mTitle);
+ }
+
+ @Override
+ public void onBackPressed() {
+ if (drawerPositionsDefault != DrawerPositions.MAIN) return;
+ mDrawerList.setItemChecked(0, true);
+ Fragment fragment = getSupportFragmentManager().findFragmentByTag(TAG_CONTENT_FRAGMENT);
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("MainActivity super.onBackPressed");
+ super.onBackPressed();
+ }
+
+ public static boolean permissionRequesting;
+ @Override
+ public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("permissionRequesting: requestCode = " + requestCode + ", permissions is " + (permissions == null ? "null" : "valid") + ", grantResults is " + (grantResults == null ? "null" : "valid") );
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("permissionRequesting: permissions[" + permissions.length + "] = " + (permissions != null && permissions.length > 0 ? permissions[0] : ""));
+ if (grantResults != null && grantResults.length != 0) {
+ boolean bNegative = false;
+ for (int i = 0; i < grantResults.length; i++) {
+ if (grantResults[i] < 0) bNegative = true;
+ if (DEBUG) csLibrary4A.appendToLog("permissionRequesting: grantResults[" + i + "] = " + grantResults[i] );
+ }
+ if (bNegative) {
+ Toast toast = Toast.makeText(this, R.string.toast_permission_not_granted, Toast.LENGTH_SHORT);
+ if (false) toast.setGravity(Gravity.TOP | Gravity.RIGHT, 100, 200);
+ toast.show();
+ }
+ }
+ super.onRequestPermissionsResult(requestCode, permissions, grantResults);
+ permissionRequesting = false;
+ }
+
+ public void sfnClicked(View view) {
+ selectItem(DrawerPositions.SPECIAL);
+ }
+
+ public void privacyClicked(View view) {
+ Intent intent = new Intent();
+ intent.setAction(Intent.ACTION_VIEW);
+ intent.addCategory(Intent.CATEGORY_BROWSABLE);
+ intent.setData(Uri.parse("https://www.convergence.com.hk/apps-privacy-policy"));
+ startActivity(intent);
+ }
+
+ public void aboutClicked(View view) { selectItem(DrawerPositions.ABOUT); }
+ public void connectClicked(View view) { selectItem(DrawerPositions.CONNECT); }
+ public void invClicked(View view) { selectItem(DrawerPositions.INVENTORY); }
+ public void locateClicked(View view) {
+ selectItem(DrawerPositions.SEARCH);
+ }
+ public void multiBankClicked(View view) { selectItem(DrawerPositions.MULTIBANK); }
+ public void settClicked(View view) {
+ selectItem(DrawerPositions.SETTING);
+ }
+ public void filterClicked(View view) {
+ selectItem(DrawerPositions.FILTER);
+ }
+ public void rrClicked(View view) {
+ selectItem(DrawerPositions.READWRITE);
+ }
+ public void rrUserClicked(View view) { selectItem(DrawerPositions.READWRITEUSER); }
+
+ public void accessClicked(View view) {
+ selectItem(DrawerPositions.SECURITY);
+ }
+
+ public void impInventoryClicked(View view) { selectItem(DrawerPositions.IMPINVENTORY); }
+ public void m775Clicked(View view) { selectItem(DrawerPositions.IMP775); }
+ public void alienClicked(View view) { selectItem(DrawerPositions.ALIEN); }
+ public void uCode8Clicked(View view) { selectItem(DrawerPositions.UCODE8); }
+ public void uCodeClicked(View view) { selectItem(DrawerPositions.UCODEDNA); }
+ public void bapCardClicked(View view) { selectItem(DrawerPositions.BAPCARD); }
+ public void coldChainClicked(View view) { selectItem(DrawerPositions.COLDCHAIN); }
+ public void aurasenseClicked(View view) { selectItem(DrawerPositions.AURASENSE); }
+ public void kilowayClicked(View view) { selectItem(DrawerPositions.KILOWAY); }
+ public void longjingClicked(View view) { selectItem(DrawerPositions.LONGJING); }
+ public void axzonClicked(View view) { selectItem(DrawerPositions.AXZON); }
+ public void rfMicronClicked(View view) { selectItem(DrawerPositions.RFMICRON); }
+ public void fdmicroClicked(View view) { selectItem(DrawerPositions.FDMICRO); }
+ public void ctesiusClicked(View view) { selectItem(DrawerPositions.CTESIUS); }
+ public void asygnClicked(View view) { selectItem(DrawerPositions.ASYGNTAG); }
+
+ public void regClicked(View view) { selectItem(DrawerPositions.REGISTER); }
+ public static boolean wedged = false;
+ public void wedgeClicked(View view) {
+ if (false) {
+ wedged = true;
+ Intent i = new Intent(Intent.ACTION_MAIN);
+ i.addCategory(Intent.CATEGORY_HOME);
+ startActivity(i);
+ } else selectItem(DrawerPositions.WEDGE);
+ }
+ public void directWedgeClicked(View view) {
+ selectItem(DrawerPositions.DIRECTWEDGE);
+ }
+
+ public void simpleInventoryClicked(View view) { selectItem(DrawerPositions.SIMINVENTORY); }
+
+ public void blankClicked(View view) { if (false) selectItem(DrawerPositions.BLANK); }
+
+ // The click listener for ListView in the navigation drawer
+ private class DrawerItemClickListener implements ListView.OnItemClickListener {
+ @Override
+ public void onItemClick(AdapterView> parent, View view, int position, long id) {
+ if (DEBUG) Log.i(TAG, "MainActivity.onItemClick: position = " + position + ", id = " + id);
+ selectItem(DrawerPositions.toDrawerPosition(position));
+ }
+ }
+
+ @Override
+ protected void onNewIntent(Intent intent) {
+ super.onNewIntent(intent);
+ if (DEBUG) csLibrary4A.appendToLog("onNewIntent !!! intent.getAction = " + intent.getAction());
+ readFromIntent(intent);
+ }
+ private void readFromIntent(Intent intent) {
+ if (DEBUG) csLibrary4A.appendToLog("onNewIntent !!! readFromIntent entry");
+ String action = intent.getAction();
+ }
+}
+
+
+
+package com.csl.cs710ademoapp;
+
+import static android.Manifest.permission.BLUETOOTH_CONNECT;
+import static android.Manifest.permission.BLUETOOTH_SCAN;
+import static com.csl.cs710ademoapp.MainActivity.mContext;
+import static com.csl.cs710ademoapp.MyForegroundService.ForegroundServiceState.CLOUDCONNECT;
+import static com.csl.cs710ademoapp.MyForegroundService.ForegroundServiceState.CONNECT;
+import static com.csl.cs710ademoapp.MyForegroundService.ForegroundServiceState.CONNECTED;
+import static com.csl.cs710ademoapp.MyForegroundService.ForegroundServiceState.INVENTORY;
+import static com.csl.cs710ademoapp.MyForegroundService.ForegroundServiceState.NULL;
+import static com.csl.cs710ademoapp.MyForegroundService.ForegroundServiceState.SCAN;
+import static com.csl.cs710ademoapp.MyForegroundService.ForegroundServiceState.WAIT;
+
+import android.app.Notification;
+import android.app.NotificationChannel;
+import android.app.NotificationManager;
+import android.app.PendingIntent;
+import android.app.Service;
+import android.content.Intent;
+import android.content.pm.PackageManager;
+import android.content.pm.ServiceInfo;
+import android.os.Binder;
+import android.os.Build;
+import android.os.Handler;
+import android.os.IBinder;
+import android.util.Log;
+import android.widget.Toast;
+
+import androidx.annotation.Nullable;
+import androidx.core.app.ActivityCompat;
+import androidx.core.app.NotificationCompat;
+
+import com.csl.cs710ademoapp.fragments.AboutFragment;
+import com.csl.cslibrary4a.BluetoothGatt;
+import com.csl.cslibrary4a.ReaderDevice;
+import com.csl.cslibrary4a.RfidReaderChipData;
+
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.List;
+import java.util.Random;
+
+public class MyForegroundService extends Service {
+ boolean DEBUG = false;
+ String TAG = "Hello";
+ Handler mHandler = new Handler();
+ public static final String CHANNEL_ID = "ForegroundServiceChannelA";
+ public static final int SERVICE_ID = 1;
+ NotificationManager notificationManager;
+ NotificationCompat.Builder notificationCompatBuilder;
+ ReaderDevice readerDevice;
+ SaveList2ExternalTask saveExternalTask; boolean isHttpServerOpened;
+ MyMqttClient myMqttClient;
+ ArrayList epcArrayList = new ArrayList();
+ ArrayList readerDeviceArrayList = new ArrayList<>();
+ long startTimeMillis, inventoryStartTimeMillis = 0;
+ int iConnectingCount = 0;
+
+ private final IBinder binder = new LocalBinder();
+ public class LocalBinder extends Binder {
+ MyForegroundService getService() {
+ // Return this instance of LocalService so clients can call public methods.
+ return MyForegroundService.this;
+ }
+ }
+
+ @Override
+ public void onCreate() {
+ super.onCreate();
+ mHandler.post(serviceRunnable);
+ }
+
+ @Override
+ public int onStartCommand(Intent intent, int flags, int startId) {
+ //String input = intent.getStringExtra("inputExtra");
+ if (MainActivity.csLibrary4A != null) Log.i(TAG, "MyForegroundService onStartCommand: csLibrary4A is created");
+ else Log.i(TAG, "MyForegroundService onStartCommand: null csLibrary4A");
+ Log.i(TAG, "MyForegroundService: onStartCommand");
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
+ Log.i(TAG, "MyForegroundService: createNotificationChannel");
+ NotificationChannel serviceChannel = new NotificationChannel(
+ CHANNEL_ID,
+ "Foreground Service Channel",
+ NotificationManager.IMPORTANCE_LOW
+ );
+ notificationManager = (NotificationManager) getSystemService(NotificationManager.class); //NotificationManager.class); //NOTIFICATION_SERVICE
+ List list = notificationManager.getNotificationChannels(); Log.i(TAG, "MyForegroundService onStartComand: getNotificationChannels.size = " + list.size());
+ notificationManager.createNotificationChannel(serviceChannel);
+ list = notificationManager.getNotificationChannels(); Log.i(TAG, "MyForegroundService onStartCommand: after createNotificationChannel, getNotificationChannels.size = " + list.size());
+ }
+
+ Intent notificationIntent = new Intent(this, AboutFragment.class);
+ //notificationIntent.setFlags((Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK));
+ PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, notificationIntent, PendingIntent.FLAG_IMMUTABLE);
+ notificationCompatBuilder = new NotificationCompat.Builder(this, CHANNEL_ID)
+ .setContentTitle("Cs710Reader Foreground Service")
+ .setSmallIcon(R.drawable.csl_logo_230510);
+ //.setPriority(NotificationCompat.PRIORITY_DEFAULT)
+ //.setContentIntent(pendingIntent)
+ //.setAutoCancel(true)
+ //.build();
+ Notification notification = updateNotification("MyForegroundService starts");
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
+ startForeground(SERVICE_ID, notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_LOCATION);
+ } else {
+ startForeground(SERVICE_ID, notification);
+ }
+
+ thread = new Thread(
+ new Runnable() {
+ @Override
+ public void run() {
+ while (true) {
+ int iRandom = getRandomNumber();
+ String strMessage = iRandom + ", ";
+ if (MainActivity.csLibrary4A == null) {
+ strMessage += "Cannot connect. Please restart App";
+ foregroundServiceState = NULL;
+ } else
+ {
+ ForegroundServiceState foregroundServiceStateOld = foregroundServiceState;
+ if (foregroundServiceState == NULL) {
+ strMessage += "ServiceState = " + foregroundServiceState.toString();
+ foregroundServiceState = WAIT;
+ } else if (foregroundServiceState == WAIT) {
+ strMessage += "Wait to enable Foreground Service";
+ if (isForegroundEnable()) {
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { //that is android 12 or above
+ if (ActivityCompat.checkSelfPermission(mContext, BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED
+ || ActivityCompat.checkSelfPermission(mContext, BLUETOOTH_SCAN) != PackageManager.PERMISSION_GRANTED) {
+ Log.i(TAG, "runnableStart: CANNOT start scanLeDevice as BLUETOOTH_CONNECT && BLUETOOTH_SCAN is NOT yet permitted");
+ } else if (MainActivity.csLibrary4A.isBleConnected()) {
+ foregroundServiceState = CONNECTED;
+ Log.i(TAG, "going to CONNECTED");
+ } else if (MainActivity.activityActive == false) {
+ Log.i(TAG, "runnableStartService: BLUETOOTH_CONNECT and BLUETOOTH_SCAN and (ACCESS_FINE_LOCATION or ACCESS_COARSE_LOCATION) is permitted");
+ } else {
+ Log.i(TAG, "Start ScanLeDevice");
+ MainActivity.csLibrary4A.scanLeDevice(true);
+ foregroundServiceState = SCAN;
+ }
+ }
+ }
+ } else if (foregroundServiceState == SCAN) {
+ strMessage += "Scanning reader";
+ if (MainActivity.csLibrary4A.isBleConnected()) {
+ foregroundServiceState = CONNECTED;
+ } else if (isForegroundEnable()) {
+ BluetoothGatt.CsScanData csScanData = null;
+ while (true) {
+ csScanData = MainActivity.csLibrary4A.getNewDeviceScanned();
+ Log.i(TAG, "cs108ScanData is " + (csScanData == null ? "null" : "valid") + ", foregroundReader = " + MainActivity.csLibrary4A.getForegroundReader());
+ if (csScanData == null) break;
+ strMessage += ("\n" + csScanData.device.getAddress());
+ if (csScanData.device.getAddress().matches(MainActivity.csLibrary4A.getForegroundReader())) { //"84:C6:92:9D:DD:52")) {
+ readerDevice = new ReaderDevice(csScanData.device.getName(), csScanData.device.getAddress(), false, "", 1, csScanData.rssi, csScanData.serviceUUID2p2);
+ String strInfo = "";
+ if (csScanData.device.getBondState() == 12) {
+ strInfo += "BOND_BONDED\n";
+ }
+ readerDevice.setDetails(strInfo + "scanRecord=" + MainActivity.csLibrary4A.byteArrayToString(csScanData.scanRecord));
+
+ MainActivity.csLibrary4A.scanLeDevice(false);
+ MainActivity.csLibrary4A.connect(readerDevice);
+ foregroundServiceState = CONNECT;
+ iConnectingCount = 0;
+ break;
+ }
+ }
+ if (foregroundServiceState != CONNECT && csScanData != null)
+ strMessage += ("\n" + csScanData.device.getAddress());
+ } else {
+ Log.i(TAG, "Stop ScanLeDevice");
+ MainActivity.csLibrary4A.scanLeDevice(false);
+ foregroundServiceState = NULL;
+ }
+ } else if (foregroundServiceState == CONNECT) {
+ strMessage += "Connecting Reader";
+ if (MainActivity.csLibrary4A.isBleConnected()) {
+ readerDevice.setConnected(true);
+ readerDevice.setSelected(true);
+ MainActivity.sharedObjects.readersList.add(readerDevice);
+ foregroundServiceState = CONNECTED;
+ } else if (++iConnectingCount > 10) {
+ MainActivity.csLibrary4A.disconnect(false);
+ foregroundServiceState = NULL;
+ }
+ } else if (foregroundServiceState == CLOUDCONNECT) {
+ strMessage += "Connecting MQTT Server";
+ if (!MainActivity.csLibrary4A.isBleConnected())
+ foregroundServiceState = CONNECTED;
+ else if (!isForegroundEnable())
+ foregroundServiceState = CONNECTED;
+ if (false && MainActivity.csLibrary4A.getInventoryCloudSave() == 1) {
+ saveExternalTask = new SaveList2ExternalTask(false);
+ Log.i(TAG, "Server: new saveExternalTask");
+ isHttpServerOpened = saveExternalTask.openServer(false);
+ Log.i(TAG, "Server: openServer is " + isHttpServerOpened);
+ foregroundServiceState = CONNECTED;
+ } else if (MainActivity.csLibrary4A.getInventoryCloudSave() == 2) {
+ if (myMqttClient != null && myMqttClient.isMqttServerConnected) {
+ Log.i(TAG, "MyForegroundService: Connecting MQTT 1");
+ foregroundServiceState = CONNECTED;
+ } else {
+ Log.i(TAG, "MyForegroundService: Connecting MQTT 2");
+ myMqttClient = new MyMqttClient(getApplicationContext());
+ myMqttClient.connect(null);
+ }
+ } else foregroundServiceState = NULL;
+ } else if (foregroundServiceState == CONNECTED) {
+ strMessage += "Connected";
+ if (MainActivity.csLibrary4A.isBleConnected()) {
+ if (isForegroundEnable()) {
+ boolean bStartInventory = false;
+ if (MainActivity.csLibrary4A.getInventoryCloudSave() == 1) {
+ if (false && !isHttpServerOpened) {
+ Log.i(TAG, "Server: going to CloudConnect");
+ foregroundServiceState = CLOUDCONNECT;
+ } else if (MainActivity.csLibrary4A.getTriggerButtonStatus()) {
+ strMessage += ("\n" + "H pressed trigger");
+ bStartInventory = true;
+ } else strMessage += ("\n" + "H released trigger");
+ } else if (MainActivity.csLibrary4A.getInventoryCloudSave() == 2
+ && MainActivity.csLibrary4A.getServerMqttLocation().length() > 0 && MainActivity.csLibrary4A.getTopicMqtt().length() > 0) {
+ if (myMqttClient == null || !myMqttClient.isMqttServerConnected)
+ foregroundServiceState = CLOUDCONNECT;
+ else if (MainActivity.csLibrary4A.getTriggerButtonStatus()) {
+ strMessage += (" with trigger pressed");
+ bStartInventory = true;
+ } else strMessage += (" with trigger released");
+ }
+ if (bStartInventory) {
+ Log.i(TAG, "Debug_Compact: MyForegroundService.onStartCommand");
+ MainActivity.csLibrary4A.startOperation(RfidReaderChipData.OperationTypes.TAG_INVENTORY_COMPACT);
+ Log.i(TAG, "Server:sss startOperation");
+ inventoryStartTimeMillis = System.currentTimeMillis();
+ foregroundServiceState = INVENTORY;
+ }
+ }
+ if (false) Log.i(TAG, "isForegroundEnable = " + isForegroundEnable()
+ + ", getInventoryCloudSave = " + MainActivity.csLibrary4A.getInventoryCloudSave()
+ + ", getServerMqttLocation = " + MainActivity.csLibrary4A.getServerMqttLocation()
+ + ", getTopicMqtt = " + MainActivity.csLibrary4A.getTopicMqtt());
+ } else {
+ Log.i(TAG, "Disconnecting");
+ MainActivity.csLibrary4A.disconnect(false);
+ if (isHttpServerOpened) {
+ if (saveExternalTask.closeServer())
+ Log.i(TAG, "Server: closeServer success");
+ else Log.i(TAG, "Server: closeServer failure");
+ isHttpServerOpened = false;
+ }
+ if (myMqttClient != null) myMqttClient.disconnect(null);
+ foregroundServiceState = NULL;
+ }
+ } else if (foregroundServiceState == INVENTORY) {
+ strMessage += "Doing inventory ";
+ Log.i(TAG, "inventory: isBleConnected = " + MainActivity.csLibrary4A.isBleConnected());
+ Log.i(TAG, "inventory: myMqttClient = " + (myMqttClient == null ? "null" : myMqttClient.isMqttServerConnected));
+ if (!MainActivity.csLibrary4A.isBleConnected())
+ foregroundServiceState = CONNECTED;
+// else if (csLibrary4A.getInventoryCloudSave() == 2 && (myMqttClient == null || !myMqttClient.isMqttServerConnected)) foregroundServiceState = CONNECTED;
+ else {
+ long timePeriod = System.currentTimeMillis() - startTimeMillis;
+ if (timePeriod > MainActivity.csLibrary4A.getForegroundDupElim() * 1000L) {
+ startTimeMillis = System.currentTimeMillis();
+ Log.i(TAG, "Foreground removes strEpcList of size " + epcArrayList.size());
+ epcArrayList.clear();
+ }
+ timePeriod = System.currentTimeMillis() - inventoryStartTimeMillis;
+ if (MainActivity.csLibrary4A.getInventoryCloudSave() == 2)
+ timePeriod = 0;
+ if (isForegroundEnable() && MainActivity.csLibrary4A.getTriggerButtonStatus() && timePeriod < 2000L) {
+ RfidReaderChipData.Rx000pkgData rx000pkgData = null, rx000pkgData1 = null;
+ while (MainActivity.csLibrary4A.getTriggerButtonStatus()) {
+ rx000pkgData = MainActivity.csLibrary4A.onRFIDEvent();
+ Log.i(TAG, "rx000pkgData is " + (rx000pkgData == null ? "null" : "valid") +
+ ", rx000pkgData1 is " + (rx000pkgData1 == null ? "null" : "valid"));
+ if (rx000pkgData == null) {
+ if (rx000pkgData1 == null)
+ strMessage += ("\n NO Tag is found");
+ break;
+ } else {
+ rx000pkgData1 = rx000pkgData;
+ String strEpc = MainActivity.csLibrary4A.byteArrayToString(rx000pkgData1.decodedEpc);
+ if (strEpc == null || strEpc.length() <= 0)
+ rx000pkgData1 = null;
+ else {
+ boolean match = false;
+ for (int i = 0; i < epcArrayList.size(); i++) {
+ if (strEpc.matches(epcArrayList.get(i))) {
+ match = true;
+ Log.i(TAG, "Foreground matches tag " + strEpc);
+ break;
+ }
+ }
+ if (!match) epcArrayList.add(strEpc);
+ else rx000pkgData1 = null;
+ }
+ if (rx000pkgData1 != null) {
+ Log.i(TAG, "Server: getInventoryCloudSave = " + MainActivity.csLibrary4A.getInventoryCloudSave());
+ if (MainActivity.csLibrary4A.getInventoryCloudSave() == 1) {
+ ReaderDevice readerDevice1 = new ReaderDevice("", MainActivity.csLibrary4A.byteArrayToString(rx000pkgData1.decodedEpc), false, null,
+ MainActivity.csLibrary4A.byteArrayToString(rx000pkgData1.decodedPc), null, MainActivity.csLibrary4A.byteArrayToString(rx000pkgData1.decodedCrc), null,
+ null, -1, -1,
+ null, -1, -1,
+ new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS").format(new Date()), new SimpleDateFormat("z").format(new Date()).replaceAll("GMT", ""),
+ MainActivity.mSensorConnector.mLocationDevice.getLocation(), MainActivity.mSensorConnector.mSensorDevice.getEcompass(),
+ 1, rx000pkgData1.decodedRssi, rx000pkgData1.decodedPhase, rx000pkgData1.decodedChidx, rx000pkgData1.decodedPort, -1, -1, -1, -1, -1, -1, null, -1);
+
+ readerDeviceArrayList.add(readerDevice1);
+ } else if (MainActivity.csLibrary4A.getInventoryCloudSave() == 2) {
+ myMqttClient.publish(MainActivity.csLibrary4A.byteArrayToString(rx000pkgData1.decodedEpc));
+ }
+ }
+ }
+ }
+ if (rx000pkgData1 != null)
+ strMessage += ("\n " + MainActivity.csLibrary4A.byteArrayToString(rx000pkgData1.decodedEpc));
+ } else { //isForegroundEnable() && csLibrary4A.getTriggerButtonStatus() && timePeriod
+ Log.i(TAG, "Server:sss abortOperation with isForegroundEnable = " + isForegroundEnable()
+ + ", getTriggerButtonStatus = " + MainActivity.csLibrary4A.getTriggerButtonStatus() + ", timePeriod = " + timePeriod + ", ");
+ MainActivity.csLibrary4A.abortOperation();
+ while (true) {
+ RfidReaderChipData.Rx000pkgData rx000pkgData = MainActivity.csLibrary4A.onRFIDEvent();
+ if (rx000pkgData == null) break;
+ }
+ if (readerDeviceArrayList.size() != 0) {
+ saveExternalTask = new SaveList2ExternalTask(false);
+ Log.i(TAG, "Server: new saveExternalTask");
+ isHttpServerOpened = saveExternalTask.openServer(false);
+ Log.i(TAG, "Server: openServer is " + isHttpServerOpened);
+ String messageStr = saveExternalTask.createJSON(readerDeviceArrayList, null).toString();
+ Log.i(TAG, "Server: Json = " + messageStr);
+ saveExternalTask.write2Server(messageStr);
+ Log.i(TAG, "Server: write2Server success");
+ if (saveExternalTask.closeServer())
+ Log.i(TAG, "Server: closeServer success");
+ else Log.i(TAG, "Server: closeServer failure");
+ }
+ foregroundServiceState = CONNECTED;
+ }
+ }
+ }
+ if (foregroundServiceState != foregroundServiceStateOld) {
+ strMessage += (", New ServiceState = " + foregroundServiceState.toString());
+ }
+ MainActivity.csLibrary4A.batteryLevelRequest(); //dummy reader access
+ }
+
+ updateNotification(strMessage);
+ try {
+ int iTime = 2000;
+ if (foregroundServiceState == INVENTORY) iTime = 100;
+ Thread.sleep(iTime);
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ }
+ }
+ }
+ );
+ thread.start();
+
+ // Builds the notification and issues it.
+ //do heavy work on a background thread
+ //stopSelf();
+ return super.onStartCommand(intent, flags, startId); //return START_NOT_STICKY;
+ }
+
+ @Override
+ public void onDestroy() {
+ Log.i(TAG, "MyForegroundService: onDestroy");
+ mHandler.removeCallbacks(serviceRunnable);
+ if (MainActivity.csLibrary4A != null) {
+ MainActivity.csLibrary4A.disconnect(false);
+ Log.i(TAG, "MyForegroundService: onDestroy 0");
+ }
+ thread.stop();
+ stopSelf();
+ super.onDestroy();
+ }
+
+ @Nullable
+ @Override
+ public IBinder onBind(Intent intent) {
+ Log.i(TAG, "MyForegroundService: onBind");
+ return binder; // null;
+ }
+
+ @Override
+ public void onTaskRemoved(Intent rootIntent) {
+ Log.i(TAG, "MyForegroundService: onTaskRemoved");
+ System.out.println("onTaskRemoved called");
+ super.onTaskRemoved(rootIntent);
+ //do something you want
+ //stop service
+ thread.stop();
+ this.stopSelf();
+ }
+
+ Thread thread = null;
+ Notification updateNotification(String string) {
+ if (DEBUG) Log.i(TAG, "MyForegroundService.updateNotification: " + string);
+ notificationCompatBuilder.setContentText(string);
+ Notification notification = notificationCompatBuilder.build();
+ notificationManager.notify(1, notification);
+ return notification;
+ }
+
+ int batteryCount_old; String strBatteryLow_old;
+ Runnable serviceRunnable = new Runnable() {
+ @Override
+ public void run() {
+ if (DEBUG) Log.i(TAG, "MyForegroundService.serviceRunnable starts");
+ mHandler.postDelayed(serviceRunnable, 2000);
+ if (!MainActivity.activityActive && MainActivity.csLibrary4A != null && MainActivity.csLibrary4A.isBleConnected()) {
+ int batteryCount = MainActivity.csLibrary4A.getBatteryCount();
+ String strBatteryLow = MainActivity.csLibrary4A.isBatteryLow();
+ if (DEBUG) Log.i(TAG, "MyForegroundService.serviceRunnable: batteryCount = " + batteryCount + ", batteryCount_old = " + batteryCount_old);
+ if (batteryCount_old != batteryCount) {
+ batteryCount_old = batteryCount;
+ if (strBatteryLow == null || strBatteryLow_old == null)
+ strBatteryLow_old = strBatteryLow;
+ else if (!strBatteryLow.matches(strBatteryLow_old))
+ strBatteryLow_old = strBatteryLow;
+ }
+ if (strBatteryLow != null) {
+ if (false) Log.i(TAG, "CustomIME Debug 112");
+ Toast.makeText(mContext,
+ "Battery Low: " + strBatteryLow + "% Battery Life Left",
+ Toast.LENGTH_SHORT).show();
+ }
+ }
+ }
+ };
+
+ final Random mGenerator = new Random();
+ int getRandomNumber() {
+ return mGenerator.nextInt(100);
+ }
+
+ boolean isForegroundEnable() {
+ if (MainActivity.csLibrary4A == null) return false;
+ if (DEBUG) Log.i(TAG, "MyForegroundService.isForegroundEnable: isHomeFragment = " + MainActivity.isHomeFragment + ", getForegroundReader = " + MainActivity.csLibrary4A.getForegroundReader());
+ return (MainActivity.isHomeFragment && MainActivity.csLibrary4A.getForegroundReader().length() != 0);
+ }
+
+ enum ForegroundServiceState {
+ NULL, WAIT, SCAN, CONNECT, CLOUDCONNECT, CONNECTED, INVENTORY, DISCONNECT
+ }
+ ForegroundServiceState foregroundServiceState = NULL;
+}
+
+
+
+package com.csl.cs710ademoapp;
+
+import android.content.Context;
+import android.util.Log;
+import android.view.View;
+
+import org.eclipse.paho.client.mqttv3.IMqttActionListener;
+import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
+import org.eclipse.paho.client.mqttv3.IMqttToken;
+import org.eclipse.paho.client.mqttv3.MqttCallback;
+import org.eclipse.paho.client.mqttv3.MqttClient;
+import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
+import org.eclipse.paho.client.mqttv3.MqttMessage;
+
+import info.mqtt.android.service.Ack;
+import info.mqtt.android.service.MqttAndroidClient;
+
+public class MyMqttClient {
+ final boolean DEBUG = false; final String TAG = "Hello";
+ boolean isMqttServerConnected = false;
+ Context context;
+ public MyMqttClient(Context context) {
+ this.context = context;
+
+ ///This here are the mqtt broker informations
+ String clientId = MqttClient.generateClientId();
+ Log.i(TAG, "MQTT: clientId is " + (clientId == null ? "null" : clientId));
+ //String serverMqttLocation = "tcp://192.168.25.153:1883";
+ //String serverMqttLocation = "tcp://localhost:1883";
+ String serverMqttLocation = "tcp://" + MainActivity.csLibrary4A.getServerMqttLocation() + ":1883";
+ Log.i(TAG, "MQTT: serverLocation is " + serverMqttLocation);
+ client = new MqttAndroidClient(context, serverMqttLocation, clientId, Ack.AUTO_ACK);
+ Log.i(TAG, "MQTT: client is " + (client == null ? "null" : "valid"));
+
+ if (true) {
+ MqttConnectOptions options = new MqttConnectOptions();
+ //options.setUserName("narada");
+ //options.setPassword("narada146551".toCharArray());
+ //options.setPassword("narada683796".toCharArray());
+ options.setKeepAliveInterval(60);//seconds
+ options.setCleanSession(true);
+ options.setAutomaticReconnect(true);
+ }
+
+ /*if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
+ ContextCompat.registerReceiver(this, mMessageReceiver,
+ new IntentFilter(AppConstants.INTENT_FILTERS.DASHBOARD_MESSAGE),RECEIVER_NOT_EXPORTED);
+ }else {
+ ContextCompat.registerReceiver(this, mMessageReceiver,
+ new IntentFilter(AppConstants.INTENT_FILTERS.DASHBOARD_MESSAGE));
+ }*/
+
+ client.setCallback(new MqttCallback() {
+ @Override
+ public void connectionLost(Throwable cause) {
+ Log.i(TAG, "MQTT: client.setCallback connectionLost");
+ isMqttServerConnected = false;
+ }
+
+ @Override
+ public void messageArrived(String topic, MqttMessage message) throws Exception {
+ Log.i(TAG, "MQTT: client.setCallback messageArrived");
+ }
+
+ @Override
+ public void deliveryComplete(IMqttDeliveryToken token) {
+ Log.i(TAG, "MQTT: client.setCallback deliveryComplete");
+ }
+ });
+ }
+ MqttAndroidClient client;
+ public void connect(View v) {
+ try {
+ IMqttToken token = client.connect();
+ token.setActionCallback(new IMqttActionListener() {
+ @Override
+ public void onSuccess(IMqttToken asyncActionToken) {
+ Log.i(TAG, "MQTT: client.connect.setActionCallback onSuccess");
+ //Toast.makeText(MainActivity.this,"connected!!",Toast.LENGTH_LONG).show();
+ subscribe();
+ isMqttServerConnected = true;
+ }
+
+ @Override
+ public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
+ Log.i(TAG, "MQTT: client.connect.setActionCallback onFailure");
+ //Toast.makeText(MainActivity.this,"connection failed!!",Toast.LENGTH_LONG).show();
+ }
+ });
+ } catch (Exception e) {
+ Log.i(TAG, "MQTT: conn Exception: " + e.toString());
+ }
+ }
+ public void disconnect(View v) {
+ try {
+ IMqttToken token = client.disconnect();
+ token.setActionCallback(new IMqttActionListener() {
+ @Override
+ public void onSuccess(IMqttToken asyncActionToken) {
+ isMqttServerConnected = false;
+ Log.i(TAG, "MQTT: client.disconnect.setActionCallback onSuccess");
+ //Toast.makeText(MainActivity.this,"Disconnected!!",Toast.LENGTH_LONG).show();
+ }
+
+ @Override
+ public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
+ Log.i(TAG, "MQTT: client.disconnect.setActionCallback onFailure");
+ //Toast.makeText(MainActivity.this,"Could not diconnect!!",Toast.LENGTH_LONG).show();
+ }
+ });
+ } catch (Exception e) {
+ Log.i(TAG, "MQTT: disconn Exception: " + e.toString());
+ }
+ }
+ private void subscribe() {
+ try{
+ client.subscribe("event",0);
+ Log.i(TAG, "MQTT: client.subscribe");
+ } catch (Exception e){
+ Log.i(TAG, "MQTT: setSubscription Exception: " + e.toString());
+ }
+ }
+ public void publish(String message) {
+ String topic = MainActivity.csLibrary4A.getTopicMqtt();
+ //String message = "the payload 11";
+ try {
+ client.publish(topic, message.getBytes(),0,false);
+ Log.i(TAG, "MQTT: client.publish");
+ //Toast.makeText(this,"Published Message",Toast.LENGTH_SHORT).show();
+ } catch (Exception e) {
+ Log.i(TAG, "MQTT: published Exception: " + e.toString());
+ }
+ }
+}
+
+
+
+package com.csl.cs710ademoapp;
+
+import static android.content.Context.WIFI_SERVICE;
+import static com.csl.cs710ademoapp.MainActivity.csLibrary4A;
+import static com.csl.cs710ademoapp.MainActivity.mContext;
+
+import android.bluetooth.BluetoothAdapter;
+import android.media.MediaScannerConnection;
+import android.net.wifi.WifiManager;
+import android.os.AsyncTask;
+import android.os.Build;
+import android.os.Environment;
+import android.provider.Settings;
+import android.util.Log;
+
+import com.csl.cslibrary4a.ReaderDevice;
+import com.csl.cslibrary4a.RfidReaderChipData;
+
+import org.json.JSONArray;
+import org.json.JSONObject;
+
+import java.io.BufferedReader;
+import java.io.DataOutputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.InputStreamReader;
+import java.io.OutputStream;
+import java.net.DatagramPacket;
+import java.net.DatagramSocket;
+import java.net.HttpURLConnection;
+import java.net.InetAddress;
+import java.net.NetworkInterface;
+import java.net.URL;
+import java.security.SecureRandom;
+import java.security.cert.CertificateException;
+import java.security.cert.X509Certificate;
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Date;
+import java.util.List;
+
+import javax.net.ssl.HostnameVerifier;
+import javax.net.ssl.HttpsURLConnection;
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.TrustManager;
+import javax.net.ssl.X509TrustManager;
+
+public class SaveList2ExternalTask extends AsyncTask {
+ public String messageStr;
+ String resultDisplay = "";
+ public String errorDisplay;
+ ArrayList tagsList; ReaderDevice tagDevice1;
+ CustomPopupWindow customPopupWindow;
+ boolean savedFile = false;
+ int fileFormat = 0;
+
+ public String url = null, strBearer = null;
+ HttpURLConnection con;
+ String stringBluetoothMAC, stringWifiMac;
+
+ public SaveList2ExternalTask(ArrayList tagsList) {
+ this.tagsList = tagsList;
+
+ stringBluetoothMAC = BluetoothAdapter.getDefaultAdapter().getAddress().replaceAll(":", "");
+ csLibrary4A.appendToLog("stringBluetoothMac from getMacAddress = " + stringBluetoothMAC);
+ if (Build.VERSION.SDK_INT > Build.VERSION_CODES.S) { }
+ else if (stringBluetoothMAC.contains("020000000000")) {
+ final String SECURE_SETTINGS_BLUETOOTH_ADDRESS = "bluetooth_address";
+ String macAddress = Settings.Secure.getString(mContext.getContentResolver(), SECURE_SETTINGS_BLUETOOTH_ADDRESS); //Not OK in android 8, >= 32
+ csLibrary4A.appendToLog("stringBluetoothMac from Settings.Secure.getString = " + macAddress);
+ stringBluetoothMAC = macAddress;
+ }
+
+ stringWifiMac = ((WifiManager) MainActivity.mContext.getSystemService(WIFI_SERVICE)).getConnectionInfo().getMacAddress().replaceAll(":", "");
+ csLibrary4A.appendToLog("stringWifMac from getMacAddress = " + stringWifiMac);
+ if (stringWifiMac.contains("020000000000")) {
+ try {
+ List all = Collections.list(NetworkInterface.getNetworkInterfaces());
+ for (NetworkInterface nif : all) {
+ csLibrary4A.appendToLog("nif.getName = " + nif.getName() + ", macByts = " + csLibrary4A.byteArrayToString(nif.getHardwareAddress()));
+ }
+
+ WifiManager wifiMan = (WifiManager) mContext.getSystemService(WIFI_SERVICE);
+ int wifiState = wifiMan.getWifiState();
+ //wifiMan.setWifiEnabled(true);
+ File fl = new File("/sys/class/net/wlan0/address");
+ FileInputStream fin = new FileInputStream(fl); //Not Ok in Amdroid 11
+ StringBuilder builder = new StringBuilder();
+ int ch;
+ while ((ch = fin.read()) != -1) {
+ builder.append((char) ch);
+ }
+ String fileMAC = builder.toString();
+ csLibrary4A.appendToLog("getName: file content = " + fileMAC);
+ fin.close();
+
+ stringWifiMac = fileMAC;
+ //boolean enabled = WifiManager.WIFI_STATE_ENABLED == wifiState;
+ //wifiMan.setWifiEnabled(enabled);
+ } catch (Exception ex) {
+ csLibrary4A.appendToLog("Exception : " + ex.getCause());
+ }
+ }
+ }
+ boolean bImpinjServer = false;
+ public SaveList2ExternalTask(boolean bImpinjServer) {
+ csLibrary4A.appendToLog("bImpinjServer = " + bImpinjServer);
+ this.bImpinjServer = bImpinjServer;
+ }
+
+ @Override
+ protected void onPreExecute() {
+ if (!bImpinjServer) {
+ if (tagsList == null) cancel(true);
+ if (MainActivity.csLibrary4A.getSavingFormatSetting() == 0)
+ messageStr = createJSON(tagsList, null).toString();
+ else messageStr = createCSV(tagsList, null);
+ resultDisplay = save2File(messageStr, true);
+ }
+ customPopupWindow = new CustomPopupWindow(mContext);
+ csLibrary4A.appendToLog("SaveList2ExternalTask: resultDisplay = " + resultDisplay);
+ if (resultDisplay == null) resultDisplay = "";
+ else {
+ resultDisplay += "\n";
+ savedFile = true;
+ customPopupWindow.popupStart(resultDisplay + "Connecting server. Please wait.", true);
+ csLibrary4A.appendToLog("SaveList2ExternalTask: popupStart is done");
+ }
+ }
+
+ protected String doInBackground(Void... params) {
+ Log.i("Hello", "bImpinjServer: doInBackground starts");
+ if (MainActivity.csLibrary4A.isBleConnected() == false) {
+ resultDisplay += "Error in sending data to server as the reader is not connected";
+ return null;
+ } else if (MainActivity.csLibrary4A.getSaveCloudEnable() == false && bImpinjServer == false) {
+ resultDisplay += "No saving to cloud as it is disabled";
+ return null;
+ }
+ try {
+ if (true) {
+ csLibrary4A.appendToLog("bImpinjServer: doInBackground starts doing");
+ openServer(bImpinjServer); csLibrary4A.appendToLog("bImpinjServer: doInBackground after openServer");
+ write2Server(messageStr); csLibrary4A.appendToLog("bImpinjServer: doInBackground after write2Server");
+ closeServer(); csLibrary4A.appendToLog("bImpinjServer: doInBackground after closeServer");
+ } else if (true) {
+ String serverAddress = "192.168.25.119:21";
+ String addressPort[];
+ InetAddress serverAddr = null;
+ int serverPort = 0;
+ boolean validLocation = false;
+ if (serverAddress != null) {
+ addressPort = serverAddress.trim().split(":");
+ if (addressPort.length == 2) {
+ try {
+ serverAddr = InetAddress.getByName(addressPort[0]);
+ serverPort = Integer.decode(addressPort[1]);
+ validLocation = true;
+ } catch (Exception ex) { }
+ }
+ }
+ if (validLocation == false) resultDisplay += "Error in creating server location from " + csLibrary4A.getServerLocation() + " !!!";
+ else {
+ DatagramSocket udpSocket = new DatagramSocket();
+ byte[] buf = messageStr.getBytes();
+ DatagramPacket packet = new DatagramPacket(buf, buf.length, serverAddr, serverPort);
+ udpSocket.send(packet);
+ resultDisplay += "Success in sending data to " + csLibrary4A.getServerLocation();
+ }
+ }
+ } catch (Exception e) {
+ errorDisplay += ": " + e.getMessage() + "\n";
+ }
+ if (errorDisplay != null) resultDisplay += "Error in sending data to server " + (url != null ? url : "") + " with " + errorDisplay;
+ while (MainActivity.permissionRequesting) { }
+ return null;
+ }
+ protected void onProgressUpdate(Void... output) { }
+ protected void onCancelled() { }
+ protected void onPostExecute(String output) {
+ if (savedFile == false) resultDisplay += "\n" + save2File(messageStr, false);
+ customPopupWindow.popupWindow.dismiss();
+ csLibrary4A.appendToLog("bImpinjServer = " + bImpinjServer + ", responseCode = " + responseCode + ", resultDisplay = " + resultDisplay);
+ if (resultDisplay != null && resultDisplay.length() != 0) {
+ if (!bImpinjServer || responseCode != 200) customPopupWindow.popupStart(resultDisplay, false);
+ }
+ }
+
+ public String createStrEpcList() {
+ String stringOutput = "";
+ if (tagsList != null) {
+ for (int i = 0; i < tagsList.size(); i++) {
+ ReaderDevice tagDevice = tagsList.get(i);
+ if (tagDevice.getAddress() != null) stringOutput += tagDevice.getAddress() + "\n";
+ }
+ }
+ return stringOutput;
+ }
+
+ int sequenceNumber;
+ public JSONObject createJSON(ArrayList tagsList0, ReaderDevice tagDevice0) {
+ JSONObject object = new JSONObject();
+ try {
+ object.put("sequenceNumber", sequenceNumber++);
+
+ if (tagsList0 != null || tagDevice0 != null) {
+ JSONArray jsonArray = new JSONArray();
+ int i = 1; if (tagsList0 != null) i = tagsList0.size();
+ object.put("numberOfTags", i);
+ while (--i >= 0) {
+ ReaderDevice tagDevice;
+ if (tagsList0 != null) tagDevice = tagsList0.get(i);
+ else tagDevice = tagDevice0;
+
+ String accessPassword = null, killPassword = null, pcData = null, epcData = null, resBankData = null, epcBankData = null, tidBankData = null, userBankData = null;
+ String timeOfRead = null, timeZone = null, location = null, compass = null;
+ int phase = -1, channel = -1;
+ if (tagDevice != null) {
+ pcData = tagDevice.getPc();
+ epcData = tagDevice.getAddress();
+ resBankData = tagDevice.getRes();
+ epcBankData = tagDevice.getEpc();
+ tidBankData = tagDevice.getTid();
+ userBankData = tagDevice.getUser();
+ timeOfRead = tagDevice.getTimeOfRead();
+ timeZone = tagDevice.getTimeZone();
+ location = tagDevice.getLocation();
+ compass = tagDevice.getCompass();
+ phase = tagDevice.getPhase();
+ channel = tagDevice.getChannel();
+ }
+
+ JSONObject objectTag = new JSONObject();
+
+ objectTag.put("accessPassword", accessPassword);
+ objectTag.put("killPassword", killPassword);
+
+ objectTag.put("pc", pcData);
+ objectTag.put("epc", epcData);
+
+ objectTag.put("resBank", resBankData);
+ objectTag.put("epcBank", epcBankData);
+ objectTag.put("tidBank", tidBankData);
+ objectTag.put("userBank", userBankData);
+ if (phase != -1) objectTag.put("phase", phase);
+ if (channel != -1) objectTag.put("channel", channel);
+
+ objectTag.put("timeOfRead", timeOfRead);
+ objectTag.put("timeZone", timeZone);
+ objectTag.put("locationOfRead", location);
+ objectTag.put("eCompass", compass);
+
+ objectTag.put("antennaPort", "0");
+ jsonArray.put(objectTag);
+ }
+ object.put("tags", jsonArray);
+ }
+
+ object.put("userDescription","this is example tag data");
+
+ object.put("rfidReaderName", MainActivity.csLibrary4A.getBluetoothICFirmwareName());
+ object.put("rfidReaderSerialNumber", MainActivity.csLibrary4A.getHostProcessorICSerialNumber());
+ object.put("rfidReaderInternalSerialNumber", MainActivity.csLibrary4A.getRadioSerial());
+
+ object.put("smartPhoneName", Build.MODEL);
+ String strPhoneSerial = Build.SERIAL;
+ object.put("smartPhoneSerialNumber", strPhoneSerial);
+ object.put("smartPhoneBluetoothMACAddress", stringBluetoothMAC);
+ object.put("smartPhoneWiFiMACAddress", stringWifiMac);
+
+ object.put("smartPhoneUUID", null);
+ object.put("pcName", null);
+ object.put("pcEthernetMACAddress", null);
+ object.put("pcWiFiMACAddress", null);
+
+ object.put("operatorId","Generic Operator");
+ object.put("operatorSiteId","Generic Site");
+ } catch (Exception ex) { }
+ return object;
+ }
+
+ public String createCSV(ArrayList tagsList0, ReaderDevice tagDevice0) {
+ String object = "";
+ int csvColumnSelect = MainActivity.csLibrary4A.getCsvColumnSelectSetting();
+ try {
+ if (tagsList0 != null || tagDevice0 != null) {
+ JSONArray jsonArray = new JSONArray();
+ int i = 1; if (tagsList0 != null) i = tagsList0.size();
+ if (true) {
+ String objectTag;
+ objectTag = "PC,";
+ objectTag += "EPC,";
+ if ((csvColumnSelect & (0x01 << RfidReaderChipData.CsvColumn.RESERVE_BANK.ordinal())) != 0) objectTag += "Reserve Bank,";
+ if ((csvColumnSelect & (0x01 << RfidReaderChipData.CsvColumn.EPC_BANK.ordinal())) != 0) objectTag += "EPC Bank,";
+ if ((csvColumnSelect & (0x01 << RfidReaderChipData.CsvColumn.TID_BANK.ordinal())) != 0) objectTag += "TID Bank,";
+ if ((csvColumnSelect & (0x01 << RfidReaderChipData.CsvColumn.USER_BANK.ordinal())) != 0) objectTag += "User Bank,";
+ if ((csvColumnSelect & (0x01 << RfidReaderChipData.CsvColumn.PHASE.ordinal())) != 0) objectTag += "Phase,";
+ if ((csvColumnSelect & (0x01 << RfidReaderChipData.CsvColumn.CHANNEL.ordinal())) != 0) objectTag += "Channel,";
+ if ((csvColumnSelect & (0x01 << RfidReaderChipData.CsvColumn.TIME.ordinal())) != 0) objectTag += "Time Of Read,";
+ if ((csvColumnSelect & (0x01 << RfidReaderChipData.CsvColumn.TIMEZONE.ordinal())) != 0) objectTag += "Time Zone,";
+ if ((csvColumnSelect & (0x01 << RfidReaderChipData.CsvColumn.LOCATION.ordinal())) != 0) objectTag += "location Of Read Latitude, Location of Read Longitude, ";
+ if ((csvColumnSelect & (0x01 << RfidReaderChipData.CsvColumn.DIRECTION.ordinal())) != 0) objectTag += "eCompass";
+ objectTag += "\n";
+ object += objectTag;
+ }
+
+ while (--i >= 0) {
+ ReaderDevice tagDevice;
+ if (tagsList0 != null) tagDevice = tagsList0.get(i);
+ else tagDevice = tagDevice0;
+
+ String accessPassword = null, killPassword = null, pcData = null, epcData = null, resBankData = null, epcBankData = null, tidBankData = null, userBankData = null;
+ String timeOfRead = null, timeZone = null, location = null, compass = null;
+ int phase = -1, channel = -1;
+ if (tagDevice != null) {
+ pcData = tagDevice.getPc();
+ epcData = tagDevice.getAddress();
+ resBankData = tagDevice.getRes();
+ epcBankData = tagDevice.getEpc();
+ tidBankData = tagDevice.getTid();
+ userBankData = tagDevice.getUser();
+ timeOfRead = tagDevice.getTimeOfRead(); MainActivity.csLibrary4A.appendToLog("timeOfRead = " + timeOfRead );
+ if (false) {
+ int index = timeOfRead.indexOf(".");
+ if (index >= 0) {
+ String string1 = timeOfRead.substring(0, index);
+ timeOfRead = string1;
+ MainActivity.csLibrary4A.appendToLog("index = " + index + ", revised timeOfRead = " + timeOfRead );
+ }
+ }
+ timeZone = tagDevice.getTimeZone();
+ location = tagDevice.getLocation();
+ compass = tagDevice.getCompass();
+ phase = tagDevice.getPhase();
+ channel = tagDevice.getChannel();
+ }
+
+ String objectTag;
+ objectTag = String.format("=\"%s\",", pcData);
+ objectTag += String.format("=\"%s\",", epcData);
+
+ if ((csvColumnSelect & (0x01 << RfidReaderChipData.CsvColumn.RESERVE_BANK.ordinal())) != 0) objectTag += String.format("=\"%s\",", resBankData);
+ if ((csvColumnSelect & (0x01 << RfidReaderChipData.CsvColumn.EPC_BANK.ordinal())) != 0) objectTag += String.format("=\"%s\",", epcBankData);
+ if ((csvColumnSelect & (0x01 << RfidReaderChipData.CsvColumn.TID_BANK.ordinal())) != 0) objectTag += String.format("=\"%s\",", tidBankData);
+ if ((csvColumnSelect & (0x01 << RfidReaderChipData.CsvColumn.USER_BANK.ordinal())) != 0) objectTag += String.format("=\"%s\",", userBankData);
+ if ((csvColumnSelect & (0x01 << RfidReaderChipData.CsvColumn.PHASE.ordinal())) != 0) objectTag += String.format("%d,", phase);
+ if ((csvColumnSelect & (0x01 << RfidReaderChipData.CsvColumn.CHANNEL.ordinal())) != 0) objectTag += String.format("%d,", channel);
+ if ((csvColumnSelect & (0x01 << RfidReaderChipData.CsvColumn.TIME.ordinal())) != 0) objectTag += String.format("=\"%s\",", timeOfRead);
+ if ((csvColumnSelect & (0x01 << RfidReaderChipData.CsvColumn.TIMEZONE.ordinal())) != 0) objectTag += String.format("%s,", timeZone);
+ if ((csvColumnSelect & (0x01 << RfidReaderChipData.CsvColumn.LOCATION.ordinal())) != 0) objectTag += String.format("%s,", location);
+ if ((csvColumnSelect & (0x01 << RfidReaderChipData.CsvColumn.DIRECTION.ordinal())) != 0)objectTag += String.format("%s", compass);
+ objectTag += "\n";
+ object += objectTag;
+ }
+
+ if ((csvColumnSelect & (0x01 << RfidReaderChipData.CsvColumn.OTHERS.ordinal())) != 0) {
+ object += "\nUser Description,this is example tag data\n";
+
+ object += String.format("RFID Reader Name,=\"%s\"\n", MainActivity.csLibrary4A.getBluetoothICFirmwareName());
+ object += String.format("RFID Reader Serial Number,=\"%s\"\n", MainActivity.csLibrary4A.getHostProcessorICSerialNumber());
+ object += String.format("RFID Reader Radio Serial Number,=\"%s\"\n", MainActivity.csLibrary4A.getRadioSerial());
+ if (true) {
+ object += String.format("RFID Reader Barcode Serial Number,=\"%s\"\n", MainActivity.csLibrary4A.getBarcodeSerial());
+ object += String.format("RFID Reader Bluetooth MAC address,=\"%s\"\n", MainActivity.csLibrary4A.getBluetoothDeviceAddress());
+ }
+ object += String.format("Smart Phone Name,=\"%s\"\n", Build.MODEL);
+ }
+ }
+ } catch (Exception ex) { }
+ return object;
+ }
+
+ public String save2File(String messageStr, boolean requestPermission) {
+ String resultDisplay = "";
+ if (MainActivity.csLibrary4A.getSaveFileEnable() == false) return "No saving file as it is disabled";
+ boolean writeExtPermission = true;
+/*
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
+ if (mContext.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
+ csLibrary4A.appendToLog("WRITE_EXTERNAL_STORAGE Permission is required !!!");
+ writeExtPermission = false;
+ if (requestPermission) {
+ csLibrary4A.appendToLog("requestPermissions WRITE_EXTERNAL_STORAGE 1");
+ MainActivity.permissionRequesting = true; requestPermissions((Activity) mContext, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
+ if (false) Toast.makeText(mContext, R.string.toast_permission_not_granted, Toast.LENGTH_SHORT).show();
+ return null;
+ }
+ } else csLibrary4A.appendToLog("WRITE_EXTERNAL_STORAGE Permission is GRANTED !!!");
+ }
+*/
+ errorDisplay = null;
+ if (writeExtPermission == false) {
+ errorDisplay = "denied WRITE_EXTERNAL_STORAGE Permission !!!";
+ } else if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) == false) errorDisplay = "Error in mouting external storage !!!";
+ else {
+ String strDir = "csReaderJava";
+ File path = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + Environment.DIRECTORY_DOWNLOADS + "/" + strDir);
+ if (path.exists() == false) path.mkdirs();
+ if (path.exists() == false) errorDisplay = "Error in making directory !!!";
+ else {
+ String dateTime = new SimpleDateFormat("yyMMdd_HHmmss").format(new Date());
+ String fileName = strDir + "_" + dateTime + (csLibrary4A.getSavingFormatSetting() == 0 ? ".txt" : ".csv");
+ File file = new File(path, fileName);
+ if (file == null) errorDisplay = "Error in making directory !!!";
+ else {
+ try {
+ errorDisplay = "Error in FileOutputStream()";
+ FileOutputStream outputStream = new FileOutputStream(file);
+ errorDisplay = "Error in write()";
+ outputStream.write(messageStr.getBytes());
+ errorDisplay = "Error in close()"; outputStream.close();
+ MediaScannerConnection.scanFile(mContext, new String[]{file.getAbsolutePath()}, null, null);
+ resultDisplay = "Success in saving data to Download/" + strDir + "/" + fileName;
+ errorDisplay = null;
+ } catch (Exception ex) {
+ errorDisplay += ex.getMessage();
+ }
+ }
+ }
+ }
+ if (errorDisplay != null) return "Error in saving file with " + errorDisplay;
+ return resultDisplay;
+ }
+
+ public boolean openServer(boolean bImpinjServer) {
+ boolean bValue = true;
+ try {
+ if (false) {
+ url = "https://";
+ url += "192.168.25.21:";
+ url += "29090/WebServiceRESTs/1.0/req/";
+ } else if (false) url = "http://ptsv2.com/t/10i1t-1519143332/post";
+ else if (bImpinjServer) {
+ } //url = "https://h9tqczg9-7275.asse.devtunnels.ms/api/Auth/login"; //"https://142.251.220.110"; //
+ else url = csLibrary4A.getServerLocation();
+ MainActivity.csLibrary4A.appendToLog("nnn 1: url is " + url);
+
+ errorDisplay = "Error in SSLContext.getInstance()";
+ SSLContext sc = SSLContext.getInstance("TLSv1.2");
+ MainActivity.csLibrary4A.appendToLog("nnn 2: SSLContext sc is " + (sc == null ? "null" : "valid"));
+ errorDisplay = "Error in SSLContext.init()";
+ sc.init(null, new TrustManager[]{
+ new X509TrustManager() {
+ @Override
+ public void checkClientTrusted(X509Certificate[] certs, String authType) throws CertificateException {
+ throw new UnsupportedOperationException("TrustManager.checkClientTrusted: Not supported yet."); //To change body of generated methods, choose Tools | Templates.
+ }
+
+ @Override
+ public void checkServerTrusted(X509Certificate[] certs, String authType) throws CertificateException {
+ }
+
+ @Override
+ public X509Certificate[] getAcceptedIssuers() {
+ return null;
+ }
+ }
+ }, new SecureRandom());
+ MainActivity.csLibrary4A.appendToLog("nnn 3: SSLContext sc.init is Okay");
+ if (true) {
+ errorDisplay = "Error in setDefaultSSLSocketFactory()";
+ MainActivity.csLibrary4A.appendToLog("nnn 4: sc.getSocketFactory is " + (sc.getSocketFactory() == null ? "null" : "valid"));
+ HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
+ MainActivity.csLibrary4A.appendToLog("nnn 5: HttpsURLConnection.setDefaultSSLSocketFactory is Okay");
+ errorDisplay = "Error in setDefaultHostnameVerifier()";
+ HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
+ @Override
+ public boolean verify(String hostname, javax.net.ssl.SSLSession sslSession) {
+ return true;
+ }
+ });
+ MainActivity.csLibrary4A.appendToLog("nnn 6: HttpsURLConnection.setDefaultHostnameVerifier is Okay");
+ }
+ HttpsURLConnection.setFollowRedirects(false);
+ MainActivity.csLibrary4A.appendToLog("nnn 7: HttpsURLConnection.setFollowRedirects is Okay");
+
+ errorDisplay = "Error in URL()";
+ URL obj = new URL(url);
+ MainActivity.csLibrary4A.appendToLog("nnn 8: URL(obj) is " + (obj != null ? "valid" : "NULL") + " with url = " + url);
+ errorDisplay = "Error in openConnection()";
+ boolean isHttps = false;
+ if (url.length() >= 6) {
+ if (url.substring(0, 6).matches("https:")) isHttps = true;
+ }
+ con = (HttpURLConnection) obj.openConnection();
+ MainActivity.csLibrary4A.appendToLog("nnn 9: HttpURLConnection obj.openConnection is " + (con == null ? "null" : "valid"));
+ if (isHttps) {
+ con = (HttpsURLConnection) obj.openConnection();
+ MainActivity.csLibrary4A.appendToLog("nnn 10: HttpsURLConnection obj.openConnection is " + (con == null ? "null" : "valid"));
+ }
+ errorDisplay = "Error in setConnectTimeout()";
+ con.setConnectTimeout(MainActivity.csLibrary4A.getServerTimeout() * 1000);
+ MainActivity.csLibrary4A.appendToLog("nnn 11: con.setConnectTimeout is Okay");
+ errorDisplay = "Error in setRequestMethod()";
+ con.setRequestMethod("POST");
+ MainActivity.csLibrary4A.appendToLog("nnn 12: con.setRequestMethod is Okay");
+ //errorDisplay = "Error in setRequestProperty(User-Agent)"; con.setRequestProperty("User-Agent", "Mozilla/5.0");
+ //errorDisplay = "Error in setRequestProperty(text/plain)"; con.setRequestProperty("text/plain", "text/plain");
+ //errorDisplay = "Error in setRequestProperty(Accept-Language)"; con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
+ MainActivity.csLibrary4A.appendToLog("nnn 13: authenticate in url position : " + url.indexOf("authenticate"));
+ if (url.indexOf("authenticate") >= 0) {
+ String string = strBearer;
+ MainActivity.csLibrary4A.appendToLog("nnn 14: Authorization value = " + string);
+ errorDisplay = "Error in setRequestProperty(Authorization)";
+ con.setRequestProperty("Authorization", string);
+ MainActivity.csLibrary4A.appendToLog("nnn 15 : con.setRequestProperty is Okay");
+ }
+ errorDisplay = "Error in setRequestProperty(Content)";
+ con.setRequestProperty("Content-Type", "application/json); //; charset=utf8");
+ MainActivity.csLibrary4A.appendToLog("nnn 16: con.setRequestProperty is Okay");
+ errorDisplay = "Error in setDoOutput()";
+ con.setDoOutput(true);
+ MainActivity.csLibrary4A.appendToLog("nnn 17: con.setDoOutput is Okay");
+ errorDisplay = "Error in setDoInput()";
+ con.setDoInput(true);
+ MainActivity.csLibrary4A.appendToLog("nnn 18: Finished openServer");
+ } catch (Exception ex) {
+ MainActivity.csLibrary4A.appendToLog("openServer Exception: " + ex.getMessage());
+ bValue = false;
+ }
+ return bValue;
+ }
+
+ boolean serverWritten = false;
+ public void write2Server(String messageStr0) {
+ csLibrary4A.appendToLog("messageStr0 = " + messageStr0);
+ try {
+ //InputStream is = con.getInputStream(); DataInputStream ir = new DataInputStream(is);
+ errorDisplay = "Error in getOutputStream()"; OutputStream os = con.getOutputStream();
+ errorDisplay = "Error in DataOutputStream()"; DataOutputStream wr = new DataOutputStream(os);
+
+ errorDisplay = "Error in writeBytes()"; wr.writeBytes(messageStr0);
+
+ errorDisplay = "Error in flush()"; wr.flush();
+ errorDisplay = "Error in close(wr)"; wr.close();
+ errorDisplay = "Error in close(os)"; os.close();
+ serverWritten = true;
+ //csLibrary4A.appendToLog("inputStream = " + ir.readUTF());
+ MainActivity.csLibrary4A.appendToLog("nnn 19: finished write2Server");
+ } catch (Exception ex) {
+ MainActivity.csLibrary4A.appendToLog("nnn 20: errorDisplay = " + errorDisplay + ", exception = " + ex.getMessage());
+ }
+ }
+
+ public int responseCode; public String response = null;
+ public boolean closeServer() {
+ boolean bValue = true;
+ if (serverWritten) {
+ try {
+ errorDisplay = "Error in getResponseCode()";
+ responseCode = con.getResponseCode();
+ //MainActivity.csLibrary4A.appendToLog("errorDisplay = " + errorDisplay);
+ MainActivity.csLibrary4A.appendToLog("responseCode = " + responseCode);
+ if (responseCode != 200)
+ errorDisplay = "Error in response code = " + responseCode;
+ else {
+ BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
+ //MainActivity.csLibrary4A.appendToLog("errorDisplay = " + errorDisplay);
+ String inputLine;
+ response = "";
+ while ((inputLine = in.readLine()) != null) {
+ response += inputLine;
+ }
+ in.close();
+ //MainActivity.csLibrary4A.appendToLog("errorDisplay = " + errorDisplay);
+ resultDisplay += "Success in sending data to server with response = " + response;
+ MainActivity.csLibrary4A.appendToLog("response = " + response);
+ errorDisplay = null;
+ }
+ } catch (Exception ex) {
+ bValue = false;
+ }
+ }
+ con.disconnect();
+ return bValue;
+ }
+}
+
+
+
+package com.csl.cs710ademoapp;
+
+import android.app.Activity;
+import android.view.View;
+import android.widget.AdapterView;
+import android.widget.ArrayAdapter;
+import android.widget.EditText;
+import android.widget.Spinner;
+import android.widget.TableRow;
+
+import static com.csl.cs710ademoapp.MainActivity.tagSelected;
+
+public class SelectTag {
+ public EditText editTextTagID, editTextSelectOffset, editTextAccessPassword, editTextAccessAntennaPower;
+ public Spinner spinnerSelectBank;
+ public TableRow tableRowSelectMemoryBank, tableRowSelectPassword;
+
+ public SelectTag(Activity activity, int index) {
+ if (index == 2) tableRowSelectMemoryBank = (TableRow) activity.findViewById(R.id.selectMemoryBankRow2);
+ else if (index == 1) tableRowSelectMemoryBank = (TableRow) activity.findViewById(R.id.selectMemoryBankRow1);
+ else tableRowSelectMemoryBank = (TableRow) activity.findViewById(R.id.selectMemoryBankRow);
+ if (index == 2) tableRowSelectPassword = (TableRow) activity.findViewById(R.id.selectPasswordRow2);
+ else if (index == 1) tableRowSelectPassword = (TableRow) activity.findViewById(R.id.selectPasswordRow1);
+ else tableRowSelectPassword = (TableRow) activity.findViewById(R.id.selectPasswordRow);
+
+ if (index == 2) editTextTagID = (EditText) activity.findViewById(R.id.selectTagID2);
+ else if (index == 1) editTextTagID = (EditText) activity.findViewById(R.id.selectTagID1);
+ else editTextTagID = (EditText) activity.findViewById(R.id.selectTagID);
+ if (index == 2) editTextSelectOffset = (EditText) activity.findViewById(R.id.selectMemoryOffset2);
+ else if (index == 1) editTextSelectOffset = (EditText) activity.findViewById(R.id.selectMemoryOffset1);
+ else editTextSelectOffset = (EditText) activity.findViewById(R.id.selectMemoryOffset);
+ //editTextRWSelectOffset.setVisibility(View.VISIBLE);
+
+ if (index == 2) spinnerSelectBank = (Spinner) activity.findViewById(R.id.selectMemoryBank2);
+ else if (index == 1) spinnerSelectBank = (Spinner) activity.findViewById(R.id.selectMemoryBank1);
+ else spinnerSelectBank = (Spinner) activity.findViewById(R.id.selectMemoryBank);
+ ArrayAdapter targetAdapter = ArrayAdapter.createFromResource(activity, R.array.read_memoryBank_options, R.layout.custom_spinner_layout);
+ targetAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+ spinnerSelectBank.setAdapter(targetAdapter);
+ spinnerSelectBank.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
+ @Override
+ public void onItemSelected(AdapterView> parent, View view, int position, long id) {
+ setBankSelected(position);
+ }
+
+ @Override
+ public void onNothingSelected(AdapterView> parent) {
+
+ }
+ });
+
+ if (index == 2) editTextAccessPassword = (EditText) activity.findViewById(R.id.selectPasswordValue2);
+ else if (index == 1) editTextAccessPassword = (EditText) activity.findViewById(R.id.selectPasswordValue1);
+ else editTextAccessPassword = (EditText) activity.findViewById(R.id.selectPasswordValue);
+ editTextAccessPassword.addTextChangedListener(new GenericTextWatcher(editTextAccessPassword, 8));
+ editTextAccessPassword.setText("00000000");
+
+ if (index == 2) editTextAccessAntennaPower = (EditText) activity.findViewById(R.id.selectAntennaPower2);
+ else if (index == 1) editTextAccessAntennaPower = (EditText) activity.findViewById(R.id.selectAntennaPower1);
+ else editTextAccessAntennaPower = (EditText) activity.findViewById(R.id.selectAntennaPower);
+ editTextAccessAntennaPower.setText(String.valueOf(300));
+ }
+
+ public void updateBankSelected() {
+ setBankSelected(-1);
+ }
+ void setBankSelected(int position) {
+ if (position < 0 || position > 2) position = spinnerSelectBank.getSelectedItemPosition();
+ switch (position) {
+ case 0: //if EPC
+ if (tagSelected != null) editTextTagID.setText(tagSelected.getAddress());
+ editTextSelectOffset.setText("32");
+ break;
+ case 1:
+ if (tagSelected != null) { if (tagSelected.getTid() != null) editTextTagID.setText(tagSelected.getTid()); }
+ editTextSelectOffset.setText("0");
+ break;
+ case 2:
+ if (tagSelected != null) { if (tagSelected.getUser() != null) editTextTagID.setText(tagSelected.getUser()); }
+ editTextSelectOffset.setText("0");
+ break;
+ default:
+ break;
+ }
+ }
+}
+
+
+
+package com.csl.cs710ademoapp;
+
+import android.Manifest;
+import android.content.Context;
+import android.content.pm.PackageManager;
+import android.hardware.Sensor;
+import android.hardware.SensorEvent;
+import android.hardware.SensorEventListener;
+import android.hardware.SensorManager;
+import android.location.Location;
+import android.location.LocationListener;
+import android.location.LocationManager;
+import android.os.Bundle;
+import androidx.core.app.ActivityCompat;
+import android.widget.Toast;
+
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import java.util.List;
+
+import static android.content.Context.LOCATION_SERVICE;
+import static android.content.Context.SENSOR_SERVICE;
+
+public class SensorConnector {
+ final boolean DEBUG = false;
+
+ public String getTimeStamp() {
+ SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
+ return sdf.format(new Date());
+ }
+
+ public LocationDevice mLocationDevice;
+ public SensorDevice mSensorDevice;
+
+ private Sensor mAccelerometer;
+ private Sensor mMagnetometer;
+
+ SensorConnector(Context context) {
+ mLocationDevice = new LocationDevice(context);
+ mSensorDevice = new SensorDevice(context);
+ }
+
+ public class LocationDevice {
+ private Context mContext;
+ private LocationManager locationManager;
+ private Location location;
+
+ public String getLocation() {
+ if (location != null) {
+ return Location.convert(location.getLatitude(), Location.FORMAT_DEGREES) + ", " + Location.convert(location.getLongitude(), Location.FORMAT_DEGREES);
+ } else {
+ return "";
+ }
+ }
+
+ private boolean onStatus = false;
+
+ LocationDevice(Context context) {
+ mContext = context;
+
+ PackageManager mPackageManager;
+ mPackageManager = (PackageManager) context.getPackageManager();
+ if (!(mPackageManager.hasSystemFeature(PackageManager.FEATURE_LOCATION))) {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("there is NO Feature_Location");
+ Toast.makeText(context.getApplicationContext(), "there is NO LOCATION_FEATURE in this phone !!! Please use another phone.", Toast.LENGTH_LONG).show();
+ } else locationManager = (LocationManager) context.getSystemService(LOCATION_SERVICE);
+ }
+
+ public void turnOn(boolean onStatus) {
+ if (locationManager != null) {
+ if (true) MainActivity.csLibrary4A.appendToLog("permission.ACCESS_FINE_LOCATION = " + ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION));
+ if (true) MainActivity.csLibrary4A.appendToLog("permission.ACCESS_COARSE_LOCATION = " + ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION));
+ if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
+ Toast.makeText(mContext.getApplicationContext(), "LOCATION_FEATURE permission is NOT GRANTED in this phone !!! Please go to Phone Setup and enable Location Services and Relaunch.", Toast.LENGTH_SHORT).show();
+ } else if (onStatus && this.onStatus == false) {
+ this.onStatus = onStatus;
+ if (true) MainActivity.csLibrary4A.appendToLog("LocationDevice.setRfidOn(): ON with LocationManager: ON");
+ if (true) MainActivity.csLibrary4A.appendToLog("LocationManager.PASSIVE_PROVIDER = " + LocationManager.PASSIVE_PROVIDER);
+ location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
+// locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, locationListener);
+ if (true) locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0, locationListener); //not working in iData2S phone
+ } else if (onStatus == false && this.onStatus) {
+ this.onStatus = onStatus;
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("LocationDevice.setRfidOn(): OFF");
+ locationManager.removeUpdates(locationListener);
+ }
+ }
+ }
+
+ private LocationListener locationListener = new LocationListener() {
+ @Override
+ public void onLocationChanged(Location location) {
+ if (true) MainActivity.csLibrary4A.appendToLog("onLocationChanged(): " + location.getProvider());
+ location = location;
+ }
+
+ @Override
+ public void onStatusChanged(String provider, int status, Bundle extras) {
+ }
+
+ @Override
+ public void onProviderEnabled(String provider) {
+ }
+
+ @Override
+ public void onProviderDisabled(String provider) {
+ }
+ };
+ }
+
+ public class SensorDevice {
+ private Context mContext;
+ private SensorManager mSensorManager;
+ private float[] mOrientation = new float[3];
+
+ public String getEcompass() {
+ String s0, s1, s2;
+ synchronized (mOrientation) {
+ float azimuthInRadians = mOrientation[0];
+ if (azimuthInRadians == 0) return null;
+ float azimuthInDegress = (float) (Math.toDegrees(azimuthInRadians) + 360) % 360;
+ s0 = String.format("%.1f", azimuthInDegress);
+ }
+ return s0; // + ", " + s1 + ", " + s2;
+ }
+
+ private boolean onStatus = false;
+
+ SensorDevice(Context context) {
+ mContext = context;
+
+ mSensorManager = (SensorManager) mContext.getSystemService(SENSOR_SERVICE);
+ List deviceSensors = mSensorManager.getSensorList(Sensor.TYPE_ALL);
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("SensorDevice(): List of sensors");
+ for (int i = 0; i < deviceSensors.size(); i++) {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog(deviceSensors.get(i).getType() + "," + deviceSensors.get(i).getName());
+ }
+ }
+
+ public void turnOn(boolean onStatus) {
+ if (onStatus && this.onStatus == false) {
+ Sensor mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
+ Sensor mMagnetometer = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
+ if (mSensorManager.registerListener(sensorEventListener, mAccelerometer, SensorManager.SENSOR_DELAY_UI) == false) {
+ Toast.makeText(mContext.getApplicationContext(), "ACCELEROMETER is NOT supported in this phone !!! Please use another phone.", Toast.LENGTH_LONG).show();
+ mAccelerometer = null;
+ }
+ if (mSensorManager.registerListener(sensorEventListener, mMagnetometer, SensorManager.SENSOR_DELAY_UI) == false) {
+ if (false) Toast.makeText(mContext.getApplicationContext(), "MAGNETOMETER is NOT supported in this phone !!! Please use another phone.", Toast.LENGTH_LONG).show();
+ mMagnetometer = null;
+ }
+ if (mAccelerometer == null || mMagnetometer == null) {
+ mSensorManager.unregisterListener(sensorEventListener);
+ } else {
+ this.onStatus = onStatus;
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("SensorDevice.setRfidOn(): ON");
+ }
+ } else if (this.onStatus && onStatus == false) {
+ this.onStatus = onStatus;
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("SensorDevice.setRfidOn(): OFF");
+ mSensorManager.unregisterListener(sensorEventListener);
+ }
+ }
+
+ private SensorEventListener sensorEventListener = new SensorEventListener() {
+ private float[] mLastAccelerometer = new float[3];
+ private boolean mLastAccelerometerSet = false;
+ private float[] mLastMagnetometer = new float[3];
+ private boolean mLastMagnetometerSet = false;
+
+ private float[] mR = new float[9];
+
+ @Override
+ public void onSensorChanged(SensorEvent event) {
+ if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
+ if (event.values.length == mLastAccelerometer.length) {
+ System.arraycopy(event.values, 0, mLastAccelerometer, 0, mLastAccelerometer.length);
+ mLastAccelerometerSet = true;
+// appendToLog("onSensorChanged(): updated mAccelerometer");
+ } else {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("onSensorChanged(): mAccelerometer: " + event.values.length);
+ }
+ } else if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
+ if (event.values.length == mLastMagnetometer.length) {
+ System.arraycopy(event.values, 0, mLastMagnetometer, 0, event.values.length);
+ mLastMagnetometerSet = true;
+// appendToLog("onSensorChanged(): updated mMagnetometer");
+ } else {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("onSensorChanged(): mMagnetometer: " + event.values.length);
+ }
+ } else {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("onSensorChanged(): " + event.sensor.getType() + "," + event.sensor.getName());
+ }
+
+ if (mLastAccelerometerSet && mLastMagnetometerSet) {
+ SensorManager.getRotationMatrix(mR, null, mLastAccelerometer, mLastMagnetometer);
+ synchronized (mOrientation) {
+ SensorManager.getOrientation(mR, mOrientation);
+ }
+ mLastAccelerometerSet = false;
+ mLastMagnetometerSet = false;
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("onSensorChanged(): updated mOrientation with mOrientation=" + mOrientation[0]);
+ }
+ }
+
+ @Override
+ public void onAccuracyChanged(Sensor sensor, int accuracy) {
+ }
+ };
+ }
+}
+
+
+
+package com.csl.cs710ademoapp;
+
+import android.os.AsyncTask;
+import android.view.View;
+import android.widget.Button;
+import android.widget.Toast;
+
+public class SettingTask extends AsyncTask {
+ final boolean DEBUG = false;
+ private enum TaskCancelRReason {
+ SAME_SETTING, INVALD_REQUEST, TIMEOUT
+ }
+ private TaskCancelRReason taskCancelReason;
+
+ Button button;
+ boolean sameSetting = false;
+ boolean invalidRequest = false;
+
+ public SettingTask(Button button, boolean sameSetting, boolean invalidRequest) {
+ button.setVisibility(View.INVISIBLE);
+ this.button = button;
+ this.sameSetting = sameSetting;
+ this.invalidRequest = invalidRequest;
+ }
+
+ @Override
+ protected void onPreExecute() {
+ if (sameSetting) {
+ taskCancelReason = TaskCancelRReason.SAME_SETTING;
+ cancel(true);
+ } else if (invalidRequest) {
+ taskCancelReason = TaskCancelRReason.INVALD_REQUEST;
+ cancel(true);
+ }
+ }
+
+ @Override
+ protected String doInBackground(Void... a) {
+ long timeMillis = System.currentTimeMillis();
+ int writeSize = MainActivity.csLibrary4A.mrfidToWriteSize();
+ while (true) {
+ int writeSizeN = MainActivity.csLibrary4A.mrfidToWriteSize();
+ if (writeSizeN == 0) break;
+ if (writeSizeN < writeSize) {
+ writeSize = writeSizeN;
+ timeMillis = System.currentTimeMillis();
+ } else if (System.currentTimeMillis() - timeMillis > 5000) {
+ taskCancelReason = TaskCancelRReason.TIMEOUT;
+ cancel(true);
+ }
+ }
+ return "End of Asynctask()";
+ }
+
+ @Override
+ protected void onProgressUpdate(String... output) { }
+
+ @Override
+ protected void onCancelled() {
+ super.onCancelled();
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("Setting0Fragment.SettingTask.onCancelled()");
+ if (taskCancelReason != null) {
+ switch (taskCancelReason) {
+ case SAME_SETTING:
+ Toast.makeText(MainActivity.mContext, R.string.toast_same_setting, Toast.LENGTH_SHORT).show();
+ break;
+ case INVALD_REQUEST:
+ Toast.makeText(MainActivity.mContext, R.string.toast_invalid_sendHostRequest, Toast.LENGTH_SHORT).show();
+ break;
+ case TIMEOUT:
+ Toast.makeText(MainActivity.mContext, R.string.toast_abort_by_TIMEOUT, Toast.LENGTH_SHORT).show();
+ break;
+ }
+ }
+ button.setVisibility(View.VISIBLE);
+ }
+
+ @Override
+ protected void onPostExecute(String result) {
+ if (DEBUG) MainActivity.csLibrary4A.appendToLog("Setting0Fragment.SettingTask.onPostExecute(): " + result);
+
+ Toast.makeText(MainActivity.mContext, R.string.toast_saved, Toast.LENGTH_SHORT).show();
+ button.setVisibility(View.VISIBLE);
+ }
+}
+
+
+
+package com.csl.cs710ademoapp;
+
+import android.content.Context;
+
+import androidx.annotation.Keep;
+import androidx.annotation.NonNull;
+
+import com.csl.cslibrary4a.ReaderDevice;
+
+import java.util.ArrayList;
+
+public class SharedObjects {
+ public static class TagsIndex implements Comparable {
+ private String address;
+ private int position;
+
+ @Keep
+ public TagsIndex(String address, int position) {
+ this.address = address;
+ this.position = position;
+ }
+
+ @Keep public String getAddress() {
+ return address;
+ }
+ @Keep public int getPosition() {
+ return position;
+ }
+
+ @Override
+ public int compareTo(@NonNull TagsIndex tagsIndex) {
+ return address.compareTo(tagsIndex.address);
+ }
+ }
+
+ Context context;
+
+ public ArrayList readersList = new ArrayList();
+ public String connectedBleAddressOld = "";
+ public boolean versionWarningShown = false;
+ public int batteryWarningShown = 0;
+
+ public boolean runningInventoryRfidTask = false;
+ public ArrayList tagsList = new ArrayList<>();
+ public ArrayList tagsIndexList = new ArrayList<>();
+ public ArrayList serviceArrayList = new ArrayList();
+
+ public boolean runningInventoryBarcodeTask = false;
+ public ArrayList barsList = new ArrayList<>();
+
+ public CustomMediaPlayer playerO, playerN, playerL;
+
+ public SharedObjects(Context context) {
+ this.context = context;
+ playerO = new CustomMediaPlayer(context, "beeplow.mp3");
+ playerN = new CustomMediaPlayer(context, "beephigh.mp3");
+ playerL = new CustomMediaPlayer(context, "beep3s1khz.wav");
+ }
+}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ #00529c
+ #07274a
+ #FFFFFF
+
+
+
+
+
+
+
+
+ 8dp
+
+
+
+
+
+
+
+
+
+
+ 18sp
+
+
+
+
+ 32sp
+ 15sp
+ 10dp
+ 10dp
+ 10dp
+ 10dp
+ 5dp
+ 2dp
+ 4dp
+ 8dp
+
+
+
+
+
+
+
+ English (US)
+
+ CSL Wedge
+ CS710S Java
+ CS108 Java
+ CSL Data Wedge
+ CSL Java Simple Wedge
+ CSL Java Wedge
+ CS108 Java Wedge
+
+
+ CSL Wedge
+ Java Reader
+ Convergence Systems
+
+ Special Functions
+
+ About
+ Connect
+ Inventory
+ Geiger search
+ Multibank
+ Settings
+ Filters
+ Read / Write
+ Security
+
+ Impinj
+ ImpinJ M775
+ ImpinJ Autotune
+ NXP UCODE 8
+ UCODE DNA
+ BAP
+ Cold Chain
+ Aura-sense
+
+ Select Tag Type
+ Configuration
+ Axzon
+ Magnus
+
+ FM13DT160
+ CTESIUS
+ KX2005X-BL
+ EL-N2ESL
+
+ Register tag
+ Long Read / Write
+ Simple Inventory
+
+
+
+ - Unchanged
+ - Unlock
+ - Permanent Unlock
+ - Lock
+ - Permanent Lock
+
+
+
+
+
+
+
+ - Reser
+ - EPC
+ - TID
+ - User
+
+
+
+ - EPC
+ - TID
+ - User
+
+
+
+ - EPC
+ - User
+
+
+
+ - SGTIN - Serialized Global Trade Item Number
+ - SSCC - Serial Shipping Container Code
+ - SGLN - Serialized Global Location Number
+ - GRAI - Global Returnable Asset Identifier
+ - GIAI - Global Individual Asset Identifier
+ - GSRN - Global Service Relation Number, Recipient
+ - GSRNP - Global Service Relation Number, Provider
+ - GDTI - Global Document Type Identifier
+ - CPI - Component Part Identifier
+ - SGCN - Serialized Globald Coupon Number
+
+
+
+ - No change
+ - Barcode before writing
+ - add 1 after writing
+
+
+
+ - Read/Write Memory
+ - Auth
+ - Get Temperature
+ - Start/Stop Logging
+ - Read/Write Reg
+ - Deep Sleep
+ - Op Mode Check
+ - Initial Regfile
+ - Led Ctrl
+
+
+
+ - user area
+ - unlock
+ - stop logging
+
+
+
+ - temperature
+ - battery voltage
+ - external voltage
+ - external pressure sensore voltage
+
+
+
+ - Hex
+ - Bit
+
+
+
+ - NB_RSSI value filtering
+ - RSSI value filtering
+
+
+
+ - NB_RSSI/RSSI "<"= threshold 1
+ - NB_RSSI/RSSI >= threshold 1
+ - NB_RSSI/RSSI == threshold 1
+ - NB_RSSI/RSSI "<"= threshold 2 and >= threshold 1
+ - NB_RSSI/RSSI "<"= threshold 1 and >= threshold 2
+
+
+
+ - NB_RSSI/RSSI "<"= threshold 1
+ - NB_RSSI/RSSI >= threshold 1
+
+
+
+ - Match(assert SL), else(deassert SL)
+ - Match(assert SL), else(do nothing)
+ - Match(do nothing), else(deassert SL)
+ - Match(invert SL), else(do nothing)
+ - Match(deassert SL), else(assert SL)
+ - Match(deassert SL), else(do nothing)
+ - Match(do nothing), else(assert SL)
+ - Match(do nothing), else(invert SL)
+
+
+
+ - Match(inventory A), else(set inventory B)
+ - Match(inventory A), else(do nothing)
+ - Match(do nothing), else(inventory B)
+ - Match(toggle AB), else(do nothing)
+ - Match(inventory B), else(inventory A)
+ - Match(inventory B), else(do nothing)
+ - Match(do nothing), else(inventory A)
+ - Match(do nothing), else(toggle AB)
+
+
+
+ - Inventoried S0
+ - Inventoried S1
+ - Inventoried S2
+ - Inventoried S3
+ - SL
+
+
+
+ - Voltage
+ - Percentage
+
+
+
+ - dBuV
+ - dBm
+
+
+
+ - New
+ - All
+
+
+
+ - JSON
+ - CSV
+
+
+
+ - Frequency hopping
+ - Fixed channel
+
+
+
+ - Frequency agile
+ - Fixed channel
+
+
+
+ - hide none
+ - hide some
+ - hide all
+
+
+
+ - A
+ - B
+ - Toggle A/B
+
+
+
+ - S0
+ - S1
+ - S2
+ - S3
+
+
+
+ - Dynamic
+ - Fixed
+
+
+
+ - 0
+ - 1
+ - 2
+ - 3
+
+
+
+ - 1 dB
+ - 7 dB
+ - 13 dB
+
+
+
+ - 24 dB
+ - 18 dB
+ - 12 dB
+ - 6 dB
+
+
+
+ - -12 dB
+ - -6 dB
+ - 0 dB
+ - 6 dB
+
+
+
+ - All
+ - All
+ - ~SL
+ - SL
+
+
+
+
+ - second
+ - minute
+ - hour
+ - sample interval
+
+
+
+
+ - second
+ - minute
+ - hour
+ - 5 minutes
+
+
+
+
+ - disable
+ - enable
+
+
+
+ - disable
+ - enable
+
+
+
+ - CS8300
+ - CS8304 Cold Chain
+ - Avery Maxdura
+
+
+
+ - All
+ - S2
+ - S3
+ - Xerxes
+
+
+
+ - code
+ - humidity
+
+
+
+ - \u2103
+ - \u2109
+
+
+
+ - All
+ - S2
+ - S3
+
+
+
+ - temperature
+ - snsor
+
+
+
+ - New line(0x0A)
+ - Tab(0x09)
+ - Comma(0x2C)
+ - Space(0x20)
+ - None
+
+
+
+ - RFID in EPC
+ - RFID in Sgtin-96
+ - Barcode
+
+
+
+ - M775
+ - M780/M781
+ - M830/M850
+ - M770
+ - M730/M750
+ - Monza R6-A/B
+ - Monza R6-P
+ - Monza X8K
+ - Others
+
+
+
+ - ucode 8
+ - ucode dna
+ - Others
+
+
+
+ - em4152 aura-sense
+ - em4325 custom cold-chain
+ - CS9010 BAP
+ - Others
+
+
+
+
+
+
+
+
+
+ No Device Found
+ No Tag Found
+ No BarCode Found
+
+
+ Available Readers
+
+
+
+
+ Bluetooth is Not Connected, Please Connect
+ Updating data. Please wait.
+ Finishing tag data upload
+ Finish as STOP is pressed
+ Finish as BUTTON is released
+ Finish as TIMEOUT
+ Finish as RFID RESET
+ Finish as COMMAND END is received
+ SUCCESS
+ FAILURE
+ BLE is connected
+ Setup problem after connection. Disconnect
+ Invalid Range. Operation is cancelled.
+ Invalid sendHostRequest. Operation is cancelled.
+ Same setting. Need no update. Operation is cancelled.
+ Saved new setting.
+ Please select reader first
+ "Permissions are not granted. Please allow them in system setting."
+
+
+ START
+ Tag Pattern
+ Password
+ Password
+ Memory Bank
+ READ
+ READ KEY
+ WRITE
+ WRITE KEY
+ Reserved Memory
+ Offset
+ Size
+ Kill PW
+ Access PW
+ EPC
+ PC
+ EPC
+ XPC
+ EPC Memory
+ TID Memory
+ User Memory
+ Tone
+ Threshold =
+ Profile(0-3)
+ Antenna cycle(0-65535)
+ Antenna dwell(0-65535ms)
+ Antenna power(0-300)
+ Battery Display
+ Query target
+ Query algorithm
+ Start Q(0-15)
+ Q Value(0-15)
+ Maximum Q(0-15)
+ Minimum Q(0-15)
+ Retry(0-255)
+ Run til zero
+ Mask data
+ KILL
+ SAVE
+ Bit Offset (decimal)
+ Index
+ Target
+ Action
+ Enable Filter
+ match on ~EPC (not EPC)
+ Convergence Systems Limited
+ Application Version
+ Library Version
+ Time stamp
+ GPS location
+ E-Compass
+ Bluetooth device address
+ Bluetooth Rssi level
+ Rfid module status
+ Barcode module status
+ Drawer Item
+ Read/Write
+ Inventory
+ Register Tag
+ Settings
+ Geiger Search
+ Filters
+ Press to Scan/Connect Reader
+ Security
+ Special Functions
+
+ Inventory\n
+ Configuration\n
+ Geiger Search\n
+
+ Longjing EL-N2ESL\nCS6861
+ EL-N2ESL CS6861
+
+ Unable to connect device
+ :
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ android.nfc.tech.Ndef
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+package com.csl.cslibrary4a;
+
+import androidx.fragment.app.Fragment;
+import androidx.fragment.app.FragmentManager;
+import androidx.fragment.app.FragmentStatePagerAdapter;
+import androidx.viewpager.widget.PagerAdapter;
+
+public class AdapterTab extends FragmentStatePagerAdapter {
+ private int iNumOfTabs;
+ public Fragment fragment0, fragment1, fragment2, fragment3, fragment4 = null;
+
+ public AdapterTab(FragmentManager fm, int iNumOfTabs) {
+ super(fm);
+ this.iNumOfTabs = iNumOfTabs;
+ }
+
+ @Override
+ public Fragment getItem(int index) {
+ Fragment fragment = null;
+ switch (index) {
+ case 0:
+ fragment = fragment0;
+ break;
+ case 1:
+ fragment = fragment1;
+ break;
+ case 2:
+ fragment = fragment2;
+ break;
+ case 3:
+ fragment = fragment3;
+ break;
+ case 4:
+ fragment = fragment4;
+ break;
+ default:
+ break;
+ }
+ return fragment;
+ }
+
+ @Override
+ public int getCount() {
+ return iNumOfTabs;
+ }
+
+ @Override
+ public int getItemPosition(Object object) {
+ return PagerAdapter.POSITION_NONE;
+ }
+
+ public void setFragment(int index, Fragment fragment) {
+ switch (index) {
+ case 0:
+ fragment0 = fragment;
+ break;
+ case 1:
+ fragment1 = fragment;
+ break;
+ case 2:
+ fragment2 = fragment;
+ break;
+ case 3:
+ fragment3 = fragment;
+ break;
+ case 4:
+ fragment4 = fragment;
+ break;
+ default:
+ break;
+ }
+ }
+}
+
+
+
+package com.csl.cslibrary4a;
+
+import java.security.InvalidKeyException;
+import java.security.Key;
+import java.security.NoSuchAlgorithmException;
+
+import javax.crypto.*;
+import javax.crypto.spec.IvParameterSpec;
+import javax.crypto.spec.SecretKeySpec;
+
+public class AesCmac {
+ private static final byte CONSTANT = (byte) 0x87;
+ private static final int BLOCK_SIZE = 16;
+
+ private int macLength;
+ private Cipher aesCipher;
+
+ private byte[] buffer;
+ private int bufferCount;
+
+ private byte[] k1;
+ private byte[] k2;
+
+ public AesCmac() throws NoSuchAlgorithmException {
+ this(BLOCK_SIZE);
+ }
+
+ public AesCmac(int length) throws NoSuchAlgorithmException {
+ if (length > BLOCK_SIZE) {
+ throw new NoSuchAlgorithmException("AES CMAC maximum length is " + BLOCK_SIZE);
+ }
+
+ try {
+ macLength = length;
+ aesCipher = Cipher.getInstance("AES/CBC/NOPADDING");
+ buffer = new byte[BLOCK_SIZE];
+ } catch (NoSuchPaddingException nspe) {
+ nspe.printStackTrace();
+ }
+ }
+
+ private byte[] doubleSubKey(byte[] k) {
+ byte[] ret = new byte[k.length];
+
+ boolean firstBitSet = ((k[0]&0x80) != 0);
+ for (int i=0; i 0) {
+ System.arraycopy(data, 0, buffer, bufferCount, BLOCK_SIZE-bufferCount);
+ try {
+ aesCipher.update(buffer, 0, BLOCK_SIZE, buffer, 0);
+ } catch (ShortBufferException sbe) {}
+ currentOffset += BLOCK_SIZE-bufferCount;
+ bufferCount = 0;
+ }
+
+ // Transform all the full blocks in data
+ while (currentOffset+BLOCK_SIZE < data.length) {
+ try {
+ aesCipher.update(data, currentOffset, BLOCK_SIZE, buffer, 0);
+ } catch (ShortBufferException sbe) {}
+ currentOffset += BLOCK_SIZE;
+ }
+
+ // Save the leftover bytes to buffer
+ if (currentOffset != data.length) {
+ System.arraycopy(data, currentOffset, buffer, 0, data.length-currentOffset);
+ bufferCount = data.length-currentOffset;
+ }
+ }
+
+ public final byte[] doFinal() {
+ byte[] subKey = k1;
+ if (bufferCount < BLOCK_SIZE) {
+ // Add padding and XOR with k2 instead
+ buffer[bufferCount] = (byte) 0x80;
+ for (int i=bufferCount+1; i
+
+
+package com.csl.cslibrary4a;
+
+import android.content.Context;
+import android.widget.TextView;
+import android.widget.Toast;
+
+import java.util.ArrayList;
+
+public class BarcodeConnector {
+ boolean DEBUG_PKDATA;
+ public boolean userDebugEnableDefault = false;
+ public boolean userDebugEnable = userDebugEnableDefault;
+
+ Context context; Utility utility;
+ public BarcodeConnector(Context context, Utility utility) {
+ this.context = context;
+ this.utility = utility;
+ }
+ private String byteArrayToString(byte[] packet) { return utility.byteArrayToString(packet); }
+ private boolean compareArray(byte[] array1, byte[] array2, int length) { return utility.compareByteArray(array1, array2, length); }
+ private void appendToLog(String s) { utility.appendToLog(s); }
+ private void appendToLogView(String s) { utility.appendToLogView(s); }
+
+ public enum BarcodePayloadEvents {
+ BARCODE_NULL,
+ BARCODE_POWER_ON, BARCODE_POWER_OFF, BARCODE_SCAN_START, BARCODE_COMMAND, BARCODE_VIBRATE_ON, BARCODE_VIBRATE_OFF,
+ BARCODE_DATA_READ, BARCODE_GOOD_READ,
+ }
+ public static class CsReaderBarcodeData {
+ public boolean waitUplinkResponse = false;
+ boolean downlinkResponsed = false;
+ public BarcodePayloadEvents barcodePayloadEvent;
+ public byte[] dataValues;
+ }
+
+ private boolean onStatus = false; public boolean getOnStatus() { return onStatus; }
+ private boolean vibrateStatus = false; boolean getVibrateStatus() { return vibrateStatus; }
+
+ public interface BarcodeConnectorCallback {
+ boolean callbackMethod(byte[] dataValues, CsReaderBarcodeData csReaderBarcodeData);
+ }
+ public BarcodeConnectorCallback barcodeConnectorCallback = null;
+
+ public ArrayList barcodeToWrite = new ArrayList<>();
+ public ArrayList mBarcodeToRead = new ArrayList<>();
+
+ private boolean arrayTypeSet(byte[] dataBuf, int pos, BarcodePayloadEvents event) {
+ boolean validEvent = false;
+ switch (event) {
+ case BARCODE_POWER_ON:
+ validEvent = true;
+ break;
+ case BARCODE_POWER_OFF:
+ dataBuf[pos] = 1;
+ validEvent = true;
+ break;
+ case BARCODE_SCAN_START:
+ dataBuf[pos] = 2;
+ validEvent = true;
+ break;
+ case BARCODE_COMMAND:
+ dataBuf[pos] = 3;
+ validEvent = true;
+ break;
+ case BARCODE_VIBRATE_ON:
+ dataBuf[pos] = 4;
+ validEvent = true;
+ break;
+ case BARCODE_VIBRATE_OFF:
+ dataBuf[pos] = 5;
+ validEvent = true;
+ break;
+ }
+ return validEvent;
+ }
+ private byte[] writeBarcode(CsReaderBarcodeData data, boolean usbConnection) {
+ boolean DEBUG = false;
+ int datalength = 0;
+ if (data.dataValues != null) datalength = data.dataValues.length;
+ byte[] dataOutRef = new byte[] { (byte) 0xA7, (byte) 0xB3, 2, (byte) 0x6A, (byte) 0x82, (byte) 0x37, 0, 0, (byte) 0x90, 0};
+ if (usbConnection) dataOutRef[1] = (byte) 0xE6;
+
+ byte[] dataOut = new byte[10 + datalength];
+ if (datalength != 0) {
+ System.arraycopy(data.dataValues, 0, dataOut, 10, datalength);
+ dataOutRef[2] += datalength;
+ }
+ System.arraycopy(dataOutRef, 0, dataOut, 0, dataOutRef.length);
+
+ if (arrayTypeSet(dataOut, 9, data.barcodePayloadEvent)) {
+ if (DEBUG) {
+ appendToLog("BarStreamOut: " + byteArrayToString(dataOut));
+ appendToLogView("BOut: " + byteArrayToString(dataOut));
+ }
+ if (DEBUG_PKDATA) appendToLog(String.format("PkData: write Barcode.%s.%s with mBarcodeDevice.sendDataToWriteSent = %d", data.barcodePayloadEvent.toString(), byteArrayToString(data.dataValues), sendDataToWriteSent));
+ if (sendDataToWriteSent != 0) appendToLog("!!! mBarcodeDevice.sendDataToWriteSent = " + sendDataToWriteSent);
+ return dataOut;
+ }
+ return null;
+ }
+ public int barcodePowerOnTimeOut = 0;
+ public boolean isMatchBarcodeToWrite(ConnectorData connectorData) {
+ boolean match = false, DEBUG = false;
+ if (barcodeToWrite.size() != 0 && connectorData.dataValues[0] == (byte)0x90) {
+ if (DEBUG) appendToLog("csReadData = " + byteArrayToString(connectorData.dataValues));
+ //if (DEBUG) appendToLog("tempDisconnect: icsModel = " + bluetoothConnector.getCsModel() + ", barcodeToWrite.size = " + barcodeToWrite.size());
+ if (barcodeToWrite.size() != 0) if (DEBUG) appendToLog("barcodeToWrite(0) = " + barcodeToWrite.get(0).barcodePayloadEvent.toString() + "," + byteArrayToString(barcodeToWrite.get(0).dataValues));
+ byte[] dataInCompare = new byte[]{(byte) 0x90, 0};
+ if (arrayTypeSet(dataInCompare, 1, barcodeToWrite.get(0).barcodePayloadEvent) && (connectorData.dataValues.length == dataInCompare.length + 1)) {
+ if (match = compareArray(connectorData.dataValues, dataInCompare, dataInCompare.length)) {
+ boolean bprocessed = false;
+ byte[] data1 = new byte[connectorData.dataValues.length - 2]; System.arraycopy(connectorData.dataValues, 2, data1, 0, data1.length);
+ if (DEBUG_PKDATA) appendToLog("PkData: matched Barcode.Reply with payload = " + byteArrayToString(connectorData.dataValues) + " for writeData Barcode." + barcodeToWrite.get(0).barcodePayloadEvent.toString());
+ if (connectorData.dataValues[2] != 0) {
+ if (DEBUG) appendToLog("Barcode.reply data is found with error");
+ } else if (true) { //testing bluetoothConnector.getCsModel() == 108) {
+ if (barcodeToWrite.get(0).barcodePayloadEvent == BarcodePayloadEvents.BARCODE_POWER_ON) {
+ barcodePowerOnTimeOut = 1000;
+ if (DEBUG) appendToLog("tempDisconnect: BARCODE_POWER_ON");
+ onStatus = true;
+ if (DEBUG_PKDATA | connectorData.dataValues[2] != 0) appendToLog("PkData: matched Barcode.Reply.PowerOn with result = " + connectorData.dataValues[2] + " and onStatus = " + onStatus);
+ bprocessed = true;
+ } else if (barcodeToWrite.get(0).barcodePayloadEvent == BarcodePayloadEvents.BARCODE_POWER_OFF) {
+ if (DEBUG) appendToLog("tempDisconnect: BARCODE_POWER_OFF");
+ onStatus = false;
+ if (DEBUG_PKDATA | connectorData.dataValues[2] != 0) appendToLog("PkData: matched Barcode.Reply.PowerOff with result = " + connectorData.dataValues[2] + " and onStatus = " + onStatus);
+ bprocessed = true;
+ } else if (barcodeToWrite.get(0).barcodePayloadEvent == BarcodePayloadEvents.BARCODE_VIBRATE_ON) {
+ vibrateStatus = true;
+ if (DEBUG_PKDATA | connectorData.dataValues[2] != 0) appendToLog("PkData: matched Barcode.Reply.VibrateOn with result = " + connectorData.dataValues[2] + " and vibrateStatus = " + vibrateStatus);
+ bprocessed = true;
+ } else if (barcodeToWrite.get(0).barcodePayloadEvent == BarcodePayloadEvents.BARCODE_VIBRATE_OFF) {
+ vibrateStatus = false;
+ if (DEBUG_PKDATA | connectorData.dataValues[2] != 0) appendToLog("PkData: matched Barcode.Reply.VibrateOff with result = " + connectorData.dataValues[2] + " and vibrateStatus = " + vibrateStatus);
+ bprocessed = true;
+ } else if (barcodeToWrite.get(0).barcodePayloadEvent == BarcodePayloadEvents.BARCODE_COMMAND) {
+ barcodePowerOnTimeOut = 500;
+ if (DEBUG_PKDATA | connectorData.dataValues[2] != 0) appendToLog("PkData: matched Barcode.Reply.Command with result = " + connectorData.dataValues[2] + " and barcodePowerOnTimeOut = " + barcodePowerOnTimeOut);
+ bprocessed = true;
+ } else {
+ bprocessed = true;
+ if (DEBUG_PKDATA) appendToLog("matched Barcode.Other.Reply data is found.");
+ }
+
+ CsReaderBarcodeData csReaderBarcodeData = barcodeToWrite.get(0);
+ if (csReaderBarcodeData.waitUplinkResponse) {
+ csReaderBarcodeData.downlinkResponsed = true; iOkCount = 0;
+ barcodeToWrite.set(0, csReaderBarcodeData);
+ if (DEBUG_PKDATA) appendToLog("PkData: barcodeToWrite.downlinkResponsed is set and waiting uplink data");
+ utility.writeDebug2File("Up31 " + barcodeToWrite.get(0).barcodePayloadEvent.toString() + ", " + byteArrayToString(data1));
+ return true;
+ }
+ } else {
+ barcodeFailure = true;
+ appendToLog("Not matched Barcode.Reply");
+ }
+ String string = "Up31 " + (bprocessed ? "" : "Unprocessed, ") + barcodeToWrite.get(0).barcodePayloadEvent.toString() + ", " + byteArrayToString(data1);
+ utility.writeDebug2File(string);
+ barcodeToWrite.remove(0); sendDataToWriteSent = 0; mDataToWriteRemoved = true; appendToLog("barcodeToWrite remove0 with length = " + barcodeToWrite.size());
+ if (DEBUG_PKDATA) appendToLog("PkData: new barcodeToWrite size = " + barcodeToWrite.size());
+ }
+ }
+ }
+ return match;
+ }
+
+ public int sendDataToWriteSent = 0; public boolean mDataToWriteRemoved = false;
+ public boolean barcodeFailure = false;
+ public byte[] sendBarcodeToWrite(boolean usbConnection) {
+ boolean DEBUG = false;
+ /*if (barcodePowerOnTimeOut != 0) {
+ if (DEBUG) appendToLog("barcodePowerOnTimeOut = " + barcodePowerOnTimeOut + ", barcodeToWrite.size() = " + barcodeToWrite.size());
+ return false;
+ }
+ if (barcodeToWrite.size() != 0) {*/
+ //if (DEBUG) appendToLog("barcodeToWrite.size = " + barcodeToWrite.size());
+ //appendToLog("testing 3"); appendToLog("testing 4");
+ //if (false) { //testing isBleConnected() == false) {
+ // barcodeToWrite.clear();
+ //} else if (false) { //testing System.currentTimeMillis() - btSendTime > btSendTimeOut) {
+ BarcodePayloadEvents barcodePayloadEvents = barcodeToWrite.get(0).barcodePayloadEvent;
+ //if (DEBUG) appendToLog("barcodePayloadEvents = " + barcodePayloadEvents.toString());
+ boolean isBarcodeData = false;
+ if (barcodePayloadEvents == BarcodePayloadEvents.BARCODE_SCAN_START || barcodePayloadEvents == BarcodePayloadEvents.BARCODE_COMMAND) isBarcodeData = true;
+ //appendToLog("BarcodePayloadEvents = " + barcodePayloadEvents.toString() + ", barcodeFailure = " + barcodeFailure + ", isBarcodeData = " + isBarcodeData + ", sendDataToWriteSent = " + sendDataToWriteSent);
+ if (barcodeFailure && isBarcodeData) {
+ barcodeToWrite.remove(0); sendDataToWriteSent = 0; mDataToWriteRemoved = true; appendToLog("barcodeToWrite remove0 with length = " + barcodeToWrite.size());
+ } else if (sendDataToWriteSent >= 5 && isBarcodeData) {
+ int oldSize = barcodeToWrite.size();
+ barcodeToWrite.remove(0); sendDataToWriteSent = 0; mDataToWriteRemoved = true; appendToLog("barcodeToWrite remove0 with length = " + barcodeToWrite.size());
+ if (DEBUG) appendToLog("Removed after sending count-out with oldSize = " + oldSize + ", updated barcodeToWrite.size() = " + barcodeToWrite.size());
+ if (DEBUG) appendToLog("Removed after sending count-out.");
+ String string = "Problem in sending data to Barcode Module. Removed data sending after count-out";
+ if (userDebugEnable) Toast.makeText(context, string, Toast.LENGTH_SHORT).show();
+ else appendToLogView(string);
+ //appendToLog("testing 5"); //testing if (bluetoothConnector.getCsModel() == 108) Toast.makeText(context, "No barcode present on Reader", Toast.LENGTH_LONG).show();
+ barcodeFailure = true; // disconnect(false);
+ } else {
+ if (DEBUG) appendToLog("size = " + barcodeToWrite.size() + ", PayloadEvents = " + barcodeToWrite.get(0).barcodePayloadEvent.toString());
+ sendDataToWriteSent++;
+ return writeBarcode(barcodeToWrite.get(0), usbConnection);
+ /*if (retValue) {
+ sendDataToWriteSent++;
+ mDataToWriteRemoved = false;
+ } else {
+ //if (DEBUG) appendToLogView("failure to send " + barcodeToWrite.get(0).barcodePayloadEvent.toString());
+ barcodeToWrite.remove(0); sendDataToWriteSent = 0; mDataToWriteRemoved = true; appendToLog("barcodeToWrite remove0 with length = " + barcodeToWrite.size());
+ }
+ return true;*/
+ }
+ //}
+ //}
+ return null;
+ }
+
+ int iOkCount = 0;
+ public boolean isBarcodeToRead(ConnectorData connectorData) {
+ boolean found = false, DEBUG = false;
+
+ if (connectorData.dataValues[0] == (byte) 0x91) {
+ if (DEBUG_PKDATA) appendToLog("PkData: found Barcode.Uplink with payload = " + byteArrayToString(connectorData.dataValues));
+ CsReaderBarcodeData csReaderBarcodeData = new CsReaderBarcodeData();
+ switch (connectorData.dataValues[1]) {
+ case 0:
+ csReaderBarcodeData.barcodePayloadEvent = BarcodePayloadEvents.BARCODE_DATA_READ;
+ byte[] dataValues = new byte[connectorData.dataValues.length - 2];
+ System.arraycopy(connectorData.dataValues, 2, dataValues, 0, dataValues.length);
+ if (DEBUG_PKDATA) appendToLog("PkData: found Barcode.Uplink.DataRead with payload = " + byteArrayToString(dataValues));
+ //commandType = null;
+ if (barcodeToWrite.size() > 0) {
+ if (barcodeToWrite.get(0).downlinkResponsed) {
+ if (barcodeConnectorCallback != null) found = barcodeConnectorCallback.callbackMethod(dataValues, csReaderBarcodeData);
+ break;
+ }
+ }
+ /*for (int i=0; false && commandType == null && i < dataValues.length; i++) {
+ if (dataValues[i] == 0x28 || dataValues[i] == 0x29 // ( )
+ || dataValues[i] == 0x5B || dataValues[i] == 0x5D || dataValues[i] == 0x5C
+ || dataValues[i] == 0x7B || dataValues[i] == 0x7D
+ ) dataValues[i] = 0x20;
+ }*/
+ csReaderBarcodeData.dataValues = dataValues;
+ mBarcodeToRead.add(csReaderBarcodeData);
+ if (DEBUG_PKDATA) appendToLog("PkData: uplink data Barcode.DataRead." + byteArrayToString(dataValues) + " is added to mBarcodeToRead");
+ found = true;
+ break;
+ case 1:
+ if (DEBUG) appendToLog("BarStream: matched Barcode.good data is found");
+ csReaderBarcodeData.barcodePayloadEvent = BarcodePayloadEvents.BARCODE_GOOD_READ;
+ csReaderBarcodeData.dataValues = null;
+ mBarcodeToRead.add(csReaderBarcodeData);
+ if (DEBUG_PKDATA) appendToLog("PkData: uplink data Barcode.GoodRead is added to mBarcodeToRead");
+ found = true;
+ break;
+ }
+ }
+ if (found && DEBUG) appendToLog("found Barcode.read data = " + byteArrayToString(connectorData.dataValues));
+ return found;
+ }
+}
+
+
+
+package com.csl.cslibrary4a;
+
+import android.content.Context;
+import android.widget.TextView;
+
+import androidx.annotation.Keep;
+
+import java.util.Arrays;
+
+public class BarcodeNewland {
+ public enum BarcodeCommandTypes {
+ COMMAND_COMMON, COMMAND_SETTING, COMMAND_QUERY
+ }
+ BarcodeCommandTypes commandType;
+
+ Context context; Utility utility; BarcodeConnector barcodeConnector; boolean barcode2TriggerMode;
+ public BarcodeNewland(Context context, Utility utility, BarcodeConnector barcodeConnector, boolean barcode2TriggerMode) {
+ this.context = context;
+ this.barcodeConnector = barcodeConnector;
+ this.barcode2TriggerMode = barcode2TriggerMode;
+ this.utility = utility;
+ }
+
+ void appendToLog(String s) { utility.appendToLog(s); }
+ String byteArrayToString(byte[] packet) { return utility.byteArrayToString(packet); }
+
+ public boolean barcodeSendCommand(byte[] barcodeCommandData) {
+ BarcodeConnector.CsReaderBarcodeData csReaderBarcodeData = new BarcodeConnector.CsReaderBarcodeData();
+ csReaderBarcodeData.barcodePayloadEvent = BarcodeConnector.BarcodePayloadEvents.BARCODE_COMMAND;
+ csReaderBarcodeData.waitUplinkResponse = true;
+ csReaderBarcodeData.dataValues = barcodeCommandData;
+ barcodeConnector.barcodeToWrite.add(csReaderBarcodeData); appendToLog("barcodeToWrite added with size = " + barcodeConnector.barcodeToWrite.size());
+ if (utility.DEBUG_PKDATA) {
+ //if (barcodeCommandData[0] == 'n')
+ appendToLog("PkData: add " + csReaderBarcodeData.barcodePayloadEvent.toString() + "." + byteArrayToString(csReaderBarcodeData.dataValues) + " to barcodeToWrite with length = " + barcodeConnector.barcodeToWrite.size());
+ }
+ return true;
+ }
+
+ public byte bBarcodeTriggerMode = (byte)0xff;
+ //public boolean barcode2TriggerModeDefault = true, barcode2TriggerMode = barcode2TriggerModeDefault;
+ boolean barcodeReadTriggerStart() {
+ BarcodeConnector.CsReaderBarcodeData csReaderBarcodeData = new BarcodeConnector.CsReaderBarcodeData();
+ csReaderBarcodeData.barcodePayloadEvent = BarcodeConnector.BarcodePayloadEvents.BARCODE_SCAN_START;
+ csReaderBarcodeData.waitUplinkResponse = false;
+ barcode2TriggerMode = false;
+ boolean bValue = barcodeConnector.barcodeToWrite.add(csReaderBarcodeData); appendToLog("barcodeToWrite added with size = " + barcodeConnector.barcodeToWrite.size());
+ appendToLog("add " + csReaderBarcodeData.barcodePayloadEvent.toString() + " to barcodeToWrite with length = " + barcodeConnector.barcodeToWrite.size());
+ return bValue;
+ }
+ public boolean barcodeSendCommandTrigger() {
+ boolean retValue = true;
+ barcode2TriggerMode = true; bBarcodeTriggerMode = 0x30; if (false) appendToLog("Set trigger reading mode to TRIGGER");
+ if (retValue) retValue = barcodeSendCommand("nls0006010;".getBytes());
+ if (retValue) retValue = barcodeSendCommand("nls0302000;".getBytes());
+ if (retValue) retValue = barcodeSendCommand("nls0313000=3000;nls0313010=1000;nls0313040=1000;nls0302000;nls0007010;".getBytes());
+ if (retValue) retValue = barcodeSendCommand("nls0001150;nls0006000;".getBytes());
+ return retValue;
+ }
+
+ public byte[] prefixRef = { 0x02, 0x00, 0x07, 0x10, 0x17, 0x13 };
+ public byte[] suffixRef = { 0x05, 0x01, 0x11, 0x16, 0x03, 0x04 };
+ public boolean barcodeSendCommandSetPreSuffix() {
+ boolean retValue = true;
+ appendToLog("BarStream: BarcodePrefix BarcodeSuffix are SET");
+ if (retValue) retValue = barcodeSendCommand("nls0006010;".getBytes());
+ if (retValue) retValue = barcodeSendCommand("nls0311010;".getBytes());
+ if (retValue) retValue = barcodeSendCommand("nls0317040;".getBytes());
+ if (retValue) retValue = barcodeSendCommand("nls0305010;".getBytes());
+ String string = "nls0300000=0x" + byteArrayToString(prefixRef) + ";"; appendToLog("Set Prefix string = " + string);
+ if (retValue) retValue = barcodeSendCommand(string.getBytes());
+ if (retValue) retValue = barcodeSendCommand("nls0306010;".getBytes());
+ string = "nls0301000=0x" + byteArrayToString(suffixRef) + ";"; appendToLog("Set Suffix string = " + string);
+ if (retValue) retValue = barcodeSendCommand(string.getBytes());
+ if (retValue) retValue = barcodeSendCommand("nls0308030;".getBytes());
+ if (retValue) retValue = barcodeSendCommand("nls0307010;".getBytes());
+ if (retValue) retValue = barcodeSendCommand("nls0309010;nls0310010;".getBytes()); //enable terminator, set terminator as 0x0D
+ if (retValue) retValue = barcodeSendCommand("nls0502110;".getBytes());
+ if (retValue) barcodeSendCommand("nls0001150;nls0006000;".getBytes());
+ if (retValue) {
+ bytesBarcodePrefix = prefixRef;
+ bytesBarcodeSuffix = suffixRef;
+ }
+ return retValue;
+ }
+
+ public boolean barcodeSendCommandResetPreSuffix() {
+ boolean retValue = true;
+ if (retValue) barcodeSendCommand("nls0006010;".getBytes());
+ if (retValue) barcodeSendCommand("nls0311000;".getBytes());
+ if (retValue) retValue = barcodeSendCommand("nls0300000=;".getBytes());
+ if (retValue) retValue = barcodeSendCommand("nls0301000=;".getBytes());
+ if (retValue) barcodeSendCommand("nls0006000;".getBytes());
+ if (retValue) {
+ bytesBarcodePrefix = null;
+ bytesBarcodeSuffix = null;
+ }
+ return retValue;
+ }
+
+ boolean barcodeSendCommandLoadUserDefault() {
+ boolean retValue = barcodeSendCommand("nls0006010;".getBytes());
+ if (retValue) retValue = barcodeSendCommand("nls0001160;".getBytes());
+ if (retValue) retValue = barcodeSendCommand("nls0006000;".getBytes());
+ return retValue;
+ }
+
+ public boolean barcodeSendCommandConinuous() {
+ boolean retValue = barcodeSendCommand("nls0006010;".getBytes());
+ if (retValue) retValue = barcodeSendCommand("nls0302020;".getBytes());
+ if (retValue) retValue = barcodeSendCommand("nls0006000;".getBytes());
+ return retValue;
+ }
+
+ boolean barcodeSendQuerySystem() {
+ byte[] datatt = new byte[] { 0x7E, 0x01, 0x30, 0x30, 0x30, 0x30, 0x40, 0x5F, 0x5F, 0x5F, 0x3F, 0x3B, 0x03 };
+ barcodeSendCommand(datatt);
+
+ byte[] datat = new byte[] { 0x7E, 0x01,
+ 0x30, 0x30, 0x30, 0x30,
+ 0x40, 0x51, 0x52, 0x59, 0x53, 0x59, 0x53, 0x2C, 0x50, 0x44, 0x4E, 0x2C, 0x50, 0x53, 0x4E, 0x3B,
+ 0X03 };
+// return barcodeSendQuery(datat);
+ return barcodeSendCommand(datat);
+ }
+ public boolean barcodeSendCommandItf14Cksum() {
+ return barcodeSendCommand("nls0006010;nls0405100;nls0006000".getBytes());
+ }
+
+ boolean barcodeSendQuery(byte[] data) {
+ byte bytelrc = (byte)0xff;
+ for (int i = 2; i < data.length - 1; i++) {
+ bytelrc ^= data[i];
+ }
+ if (false) appendToLog(String.format("BarStream: bytelrc = %02X, last = %02X", (byte)bytelrc, data[data.length-1]));
+ data[data.length-1] = bytelrc;
+ return barcodeSendCommand(data);
+ }
+
+ boolean barcodeSendQueryVersion() {
+ byte[] data = new byte[] { 0x7E, 0x00,
+ 0x00, 0x02,
+ 0x33, 0x47,
+ 0 };
+ return barcodeSendQuery(data);
+ }
+
+ public String getBarcodeVersion() {
+ String strValue = getVersion();
+ if (strValue == null) barcodeSendQueryVersion();
+ return strValue;
+ }
+
+ boolean barcodeSendQueryESN() {
+ byte[] datat = new byte[] { 0x7E, 0x00,
+ 0x00, 0x05,
+ 0x33, 0x48, 0x30, 0x32, 0x30,
+ (byte)0xb2 };
+ return barcodeSendQuery(datat);
+ }
+
+ public String getBarcodeESN() {
+ String strValue = getESN();
+ if (strValue == null) barcodeSendQueryESN();
+ return strValue;
+ }
+
+ boolean barcodeSendQuerySerialNumber() {
+ byte[] datat = new byte[] { 0x7E, 0x00,
+ 0x00, 0x05,
+ 0x33, 0x48, 0x30, 0x33, 0x30,
+ (byte)0xb2 };
+ return barcodeSendQuery(datat);
+ }
+ public String getBarcodeSerial() {
+ String strValue = getSerialNumber();
+ if (strValue == null) barcodeSendQuerySerialNumber();
+ return strValue;
+ }
+
+ boolean barcodeSendQueryDate() {
+ byte[] datat = new byte[] { 0x7E, 0x00,
+ 0x00, 0x05,
+ 0x33, 0x48, 0x30, 0x34, 0x30,
+ (byte)0xb2 };
+ return barcodeSendQuery(datat);
+ }
+ public String getBarcodeDate() {
+ String strValue = getDate();
+ if (strValue == null) barcodeSendQueryDate();
+ String strValue1 = getBarcodeESN();
+ if (strValue1 != null && strValue1.length() != 0) strValue += (", " + strValue1);
+ return strValue;
+ }
+ public boolean barcodeSendQuerySelfPreSuffix() {
+ byte[] data = new byte[] { 0x7E, 0x00,
+ 0x00, 0x02,
+ 0x33, 0x37,
+ (byte)0xf9 };
+ return barcodeSendQuery(data);
+ }
+ public boolean barcodeSendQueryReadingMode() {
+ byte[] data = new byte[] { 0x7E, 0x00,
+ 0x00, 0x05,
+ 0x33, 0x44, 0x30, 0x30, 0x30,
+ (byte)0xbd };
+ return barcodeSendQuery(data);
+ }
+ public boolean barcodeSendQueryPrefixOrder() {
+ byte[] data = new byte[] { 0x7E, 0x00,
+ 0x00, 0x02,
+ 0x33, 0x42,
+ 0 };
+ return barcodeSendQuery(data);
+ }
+ public boolean barcodeSendQueryEnable2dBarCodes() {
+ byte[] data = new byte[] { 0x7E, 0x00,
+ 0x00, 0x02,
+ 0x33, 0x33,
+ 0 };
+ return barcodeSendQuery(data);
+ }
+ public boolean barcodeSendQueryDelayTimeOfEachReading() {
+ byte[] data = new byte[] { 0x7E, 0x00,
+ 0x00, 0x05,
+ 0x33, 0x44, 0x30, 0x33, 0x30,
+ 0 };
+ return barcodeSendQuery(data);
+ }
+ public boolean barcodeSendQueryNoDuplicateReading() {
+ byte[] data = new byte[] { 0x7E, 0x00,
+ 0x00, 0x05,
+ 0x33, 0x44, 0x30, 0x33, 0x31,
+ 0 };
+ return barcodeSendQuery(data);
+ }
+
+ @Keep public void getBarcodePreSuffix() {
+ if (getPrefix() == null || getSuffix() == null) barcodeSendQuerySelfPreSuffix();
+ }
+
+ public String strVersion, strESN, strSerialNumber, strDate;
+ public String getVersion() { return strVersion; }
+ public String getESN() { return strESN; }
+ public String getSerialNumber() { return strSerialNumber; }
+ public String getDate() { return strDate; }
+ public byte[] bytesBarcodePrefix = null;
+ public byte[] bytesBarcodeSuffix = null;
+ public byte[] getPrefix() { return bytesBarcodePrefix; }
+ public byte[] getSuffix() { return bytesBarcodeSuffix; }
+ public boolean checkPreSuffix(byte[] prefix1, byte[] suffix1) {
+ boolean result = false;
+ if (prefix1 != null && bytesBarcodePrefix != null && suffix1 != null && bytesBarcodeSuffix != null) {
+ result = Arrays.equals(prefix1, bytesBarcodePrefix);
+ if (result) result = Arrays.equals(suffix1, bytesBarcodeSuffix);
+ }
+ return result;
+ }
+ public boolean decodeBarcodeUplinkData(byte[] dataValues, BarcodeConnector.CsReaderBarcodeData csReaderBarcodeData) {
+ appendToLog("decodeBarcodeUplinkData starts");
+ boolean found = false, DEBUG = false;
+ int count = 0; boolean matched = true;
+ if (barcodeConnector.barcodeToWrite.get(0).dataValues[0] == 0x1b) {
+ commandType = BarcodeCommandTypes.COMMAND_COMMON;
+ count = 1;
+ if (DEBUG) appendToLog("0x1b, Common response with count = " + count);
+ } else if (barcodeConnector.barcodeToWrite.get(0).dataValues[0] == 0x7E) {
+ if (DEBUG) appendToLog("0x7E, Barcode response with 0x7E barcodeToWrite.get(0).dataValues[0] and response data = " + byteArrayToString(dataValues));
+ matched = true;
+ commandType = BarcodeCommandTypes.COMMAND_QUERY;
+ int index = 0;
+ while (dataValues.length - index >= 5 + 1) {
+ if (dataValues[index+0] == 2 && dataValues[index+1] == 0 && dataValues[index+4] == 0x34) {
+ int length = dataValues[index+2] * 256 + dataValues[index+3];
+ if (dataValues.length - index >= length + 4 + 1) {
+ matched = true;
+ byte[] bytes = new byte[length-1];
+ System.arraycopy(dataValues, index + 5, bytes, 0, bytes.length);
+ byte[] requestBytes = new byte[barcodeConnector.barcodeToWrite.get(0).dataValues.length - 6];
+ System.arraycopy(barcodeConnector.barcodeToWrite.get(0).dataValues, 5, requestBytes, 0, requestBytes.length);
+ if (utility.DEBUG_PKDATA) appendToLog("PkData: found Barcode.Uplink.DataRead.QueryResponse with payload data1 = " + byteArrayToString(bytes) + " for QueryInput data1 = " + byteArrayToString(requestBytes));
+ if (barcodeConnector.barcodeToWrite.get(0).dataValues[5] == 0x37 && length >= 5) {
+ matched = true;
+ int prefixLength = dataValues[index+6];
+ int suffixLength = 0;
+ if (dataValues.length - index >= 5 + 2 + prefixLength + 2 + 1) {
+ suffixLength = dataValues[index + 6 + prefixLength + 2];
+ }
+ if (dataValues.length - index >= 5 + 2 + prefixLength + 2 + suffixLength + 1) {
+ bytesBarcodePrefix = null;
+ bytesBarcodeSuffix = null;
+ if (dataValues[index+5] == 1) {
+ bytesBarcodePrefix = new byte[prefixLength];
+ System.arraycopy(dataValues, index + 7, bytesBarcodePrefix, 0, bytesBarcodePrefix.length);
+ }
+ if (dataValues[index + 6 + prefixLength + 1] == 1) {
+ bytesBarcodeSuffix = new byte[suffixLength];
+ System.arraycopy(dataValues, index + 7 + prefixLength + 2, bytesBarcodeSuffix, 0, bytesBarcodeSuffix.length);
+ }
+ if (DEBUG) appendToLog("BarStream: BarcodePrefix = " + byteArrayToString(bytesBarcodePrefix) + ", BarcodeSuffix = " + byteArrayToString(bytesBarcodeSuffix));
+ }
+ if (utility.DEBUG_PKDATA) appendToLog("PkData: Barcode.Uplink.DataRead.QueryResponse.SelfPrefix_SelfSuffix is processed as Barcode Prefix = " + byteArrayToString(bytesBarcodePrefix) + ", Suffix = " + byteArrayToString(bytesBarcodeSuffix));
+ } else if (barcodeConnector.barcodeToWrite.get(0).dataValues[5] == 0x47 && length > 1) {
+ if (DEBUG) appendToLog("versionNumber is detected with length = " + length);
+ matched = true;
+ byte[] byteVersion = new byte[length - 1];
+ System.arraycopy(dataValues, index + 5, byteVersion, 0, byteVersion.length);
+ String versionNumber;
+ try {
+ versionNumber = new String(byteVersion, "UTF-8");
+ } catch (Exception e) {
+ versionNumber = null;
+ }
+ strVersion = versionNumber;
+ if (utility.DEBUG_PKDATA) appendToLog("PkData: uplink data " + byteArrayToString(byteVersion) + " is processsed as version = " + versionNumber);
+ } else if (barcodeConnector.barcodeToWrite.get(0).dataValues[5] == 0x48 && length >= 5) {
+ if (dataValues[index+5] == barcodeConnector.barcodeToWrite.get(0).dataValues[6] && dataValues[index+6] == barcodeConnector.barcodeToWrite.get(0).dataValues[7]) {
+ matched = true; //for ESN, S/N or Date
+ byte[] byteSN = new byte[length - 3];
+ System.arraycopy(dataValues, index + 7, byteSN, 0, byteSN.length);
+ String serialNumber;
+ try {
+ serialNumber = new String(byteSN, "UTF-8");
+ int snLength = Integer.parseInt(serialNumber.substring(0, 2));
+ if (DEBUG)
+ appendToLog("BarStream: serialNumber = " + serialNumber + ", snLength = " + snLength + ", serialNumber.length = " + serialNumber.length());
+ if (snLength + 2 == serialNumber.length()) {
+ serialNumber = serialNumber.substring(2);
+ } else serialNumber = null;
+ } catch (Exception e) {
+ serialNumber = null;
+ }
+ if (false) appendToLog("debug index = " + index + ", " + byteArrayToString(dataValues));
+ String strResponseType = "";
+ if (dataValues[index+6] == (byte)0x32) {
+ strESN = serialNumber;
+ strResponseType = "EquipmentSerialNumber";
+ } else if (dataValues[index+6] == (byte)0x33) {
+ strSerialNumber = serialNumber;
+ strResponseType = "SerialNumber";
+ } else if (dataValues[index+6] == (byte)0x34) {
+ strDate = serialNumber;
+ strResponseType = "DataCode";
+ }
+ if (false) appendToLog("strResponseType = " + strResponseType);
+ if (utility.DEBUG_PKDATA) appendToLog(String.format("PkData: Barcode.Uplink.DataRead.QueryResponse.%s is processed as %s[%s]", strResponseType, byteArrayToString(byteSN).substring(4), serialNumber));
+ } else appendToLog("Barcode.Uplink.DataRead.QueryResponse has mis-matched values");
+ } else if (barcodeConnector.barcodeToWrite.get(0).dataValues[5] == 0x44 && length >= 3) {
+ if (DEBUG) appendToLog("BarStream: dataValue = " + byteArrayToString(dataValues) + ", writeDataValue = " + byteArrayToString(barcodeConnector.barcodeToWrite.get(0).dataValues));
+ if (dataValues[index+5] == barcodeConnector.barcodeToWrite.get(0).dataValues[6] && dataValues[index+6] == barcodeConnector.barcodeToWrite.get(0).dataValues[7]) {
+ matched = true;
+ if (barcodeConnector.barcodeToWrite.get(0).dataValues[6] == 0x30 && barcodeConnector.barcodeToWrite.get(0).dataValues[7] == 0x30 && barcodeConnector.barcodeToWrite.get(0).dataValues[8] == 0x30) {
+ bBarcodeTriggerMode = dataValues[7];
+ String strModeType = "";
+ if (dataValues[index+7] == 0x30) strModeType = "trigger";
+ else if (dataValues[index+7] == 0x31) strModeType = "auto_Scan";
+ else if (dataValues[index+7] == 0x32) strModeType = "continue_Scan";
+ else if (dataValues[index+7] == 0x33) strModeType = "batch_Scan";
+ if (utility.DEBUG_PKDATA) appendToLog(String.format("PkData: Barcode.Uplink.DataRead.QueryResponse.ReadingMode is processed as last 0x%X[%s]", dataValues[index+7], strModeType));
+ } else appendToLog("Barcode.Uplink.DataRead.QueryResponse has mis-matched values");
+ } else appendToLog("Barcode.Uplink.DataRead.QueryResponse has mis-matched values");
+ } else appendToLog("Barcode.Uplink.DataRead.QueryResponse has mis-matched values");
+ index += (length + 5);
+ } else break;
+ } else index++;
+ }
+ if (matched) { if (DEBUG) appendToLog("Matched Query response"); }
+ else { if (DEBUG) appendToLog("Mis-matched Query response"); }
+ } else {
+ if (DEBUG) appendToLog("BarStream: Barcode response with barcodeToWrite.get(0).dataValues[0] = Others");
+ String strData = null;
+ try {
+ strData = new String(barcodeConnector.barcodeToWrite.get(0).dataValues, "UTF-8");
+ } catch (Exception ex) {
+ strData = "";
+ }
+ String findStr = "nls";
+ int lastIndex = 0;
+ while (lastIndex != -1) {
+ lastIndex = strData.indexOf(findStr, lastIndex);
+ if (lastIndex != -1) {
+ count++;
+ lastIndex += findStr.length();
+ }
+ }
+ if (DEBUG) appendToLog("Setting strData = " + strData + ", count = " + count);
+ }
+ if (count != 0) {
+ if (false) appendToLog("dataValues.length = " + dataValues.length + ", okCount = " + barcodeConnector.iOkCount + ", count = " + count + " for barcodeToWrite data = " + byteArrayToString(barcodeConnector.barcodeToWrite.get(0).dataValues));
+ matched = false; boolean foundOk = false;
+ for (int k = 0; k < dataValues.length; k++) {
+ boolean match06 = false;
+ if (dataValues[k] == 0x06 || dataValues[k] == 0x15) { match06 = true; if (++barcodeConnector.iOkCount == count) matched = true; }
+ if (match06 == false) break;
+ foundOk = true; found = true;
+ }
+ if (false) appendToLog("00 matcched = " + matched);
+ if (matched) { if (utility.DEBUG_PKDATA) appendToLog("PkData: Barcode.Uplink.DataRead." + byteArrayToString(dataValues) + " is processed with matched = " + matched + ", OkCount = " + barcodeConnector.iOkCount + ", expected count = " + count + " for " + byteArrayToString(barcodeConnector.barcodeToWrite.get(0).dataValues)); }
+ else if (foundOk) { if (utility.DEBUG_PKDATA) appendToLog("PkData: Barcode.Uplink.DataRead." + byteArrayToString(dataValues) + " is processed with matched = " + matched + ", but OkCount = " + barcodeConnector.iOkCount + ", expected count = " + count + " for " + byteArrayToString(barcodeConnector.barcodeToWrite.get(0).dataValues)); }
+ else {
+ barcodeConnector.mBarcodeToRead.add(csReaderBarcodeData);
+ if (utility.DEBUG_PKDATA) appendToLog("PkData: uplink data Barcode.DataRead." + byteArrayToString(csReaderBarcodeData.dataValues) + " is added to mBarcodeToRead");
+ }
+ }
+ if (matched) {
+ found = true;
+ barcodeConnector.barcodeToWrite.remove(0); barcodeConnector.sendDataToWriteSent = 0; barcodeConnector.mDataToWriteRemoved = true; appendToLog("barcodeToWrite remove0 with length = " + barcodeConnector.barcodeToWrite.size());
+ if (utility.DEBUG_PKDATA) appendToLog("PkData: new barcodeToWrite size = " + barcodeConnector.barcodeToWrite.size());
+ }
+ appendToLog("decodeBarcodeUplinkData found = " + found);
+ return found;
+ }
+}
+
+
+
+package com.csl.cslibrary4a;
+
+import android.content.Context;
+import android.widget.TextView;
+import android.widget.Toast;
+
+import java.util.ArrayList;
+
+public class BluetoothConnector {
+ boolean DEBUG_PKDATA;
+ final boolean DEBUG = false;
+// public boolean userDebugEnableDefault = false;
+// public boolean userDebugEnable = userDebugEnableDefault;
+
+ Context context; Utility utility; boolean userDebugEnable;
+ public BluetoothConnector(Context context, Utility utility, boolean userDebugEnable) {
+ this.context = context;
+ this.utility = utility; DEBUG_PKDATA = utility.DEBUG_PKDATA;
+ this.userDebugEnable = userDebugEnable;
+ }
+ private String byteArrayToString(byte[] packet) { return utility.byteArrayToString(packet); }
+ private boolean compareArray(byte[] array1, byte[] array2, int length) { return utility.compareByteArray(array1, array2, length); }
+ private void appendToLog(String s) { utility.appendToLog(s); }
+ private void appendToLogView(String s) { utility.appendToLogView(s); }
+
+ private int icsModel = -1;
+ public int getCsModel() {
+ if (false) appendToLog("icsModel = " + icsModel);
+ return icsModel;
+ }
+
+ public enum BluetoothIcPayloadEvents {
+ BLUETOOTH_GET_VERSION, BLUETOOTH_SET_DEVICE_NAME, BLUETOOTH_GET_DEVICE_NAME, BLUETOOTH_FORCE_BT_DISCONNECT
+ }
+
+ public class BluetoothIcData {
+ public BluetoothIcPayloadEvents bluetoothIcPayloadEvent;
+ public byte[] dataValues;
+ }
+
+ private byte[] mBluetoothIcVersion = new byte[]{-1, -1, -1};
+ private boolean mBluetoothIcVersionUpdated = false;
+ public String getBluetoothIcVersion() {
+ boolean DEBUG = false;
+ if (mBluetoothIcVersionUpdated == false) {
+ if (DEBUG) appendToLog("mBluetoothIcVersionUpdated is false");
+ boolean repeatRequest = false;
+ if (bluetoothIcToWrite.size() != 0) {
+ if (bluetoothIcToWrite.get(bluetoothIcToWrite.size() - 1).bluetoothIcPayloadEvent == BluetoothIcPayloadEvents.BLUETOOTH_GET_VERSION) {
+ repeatRequest = true;
+ }
+ }
+ if (repeatRequest == false) {
+ BluetoothIcData cs108BluetoothIcData = new BluetoothIcData();
+ cs108BluetoothIcData.bluetoothIcPayloadEvent = BluetoothIcPayloadEvents.BLUETOOTH_GET_VERSION;
+ bluetoothIcToWrite.add(cs108BluetoothIcData);
+ if (DEBUG_PKDATA) appendToLog("add " + cs108BluetoothIcData.bluetoothIcPayloadEvent.toString() + " to mBluetoothIcToWrite with length = " + bluetoothIcToWrite.size());
+ }
+ return "";
+ } else {
+ String retValue = String.valueOf(mBluetoothIcVersion[0]) + "." + String.valueOf(mBluetoothIcVersion[1]) + "." + String.valueOf(mBluetoothIcVersion[2]);
+ if (DEBUG) appendToLog("mBluetoothIcVersionUpdated is true with data = " + byteArrayToString(mBluetoothIcVersion) + ", icsModel = " + icsModel);
+ return retValue;
+ }
+ }
+
+ public byte[] deviceName = null;
+ public String getBluetoothIcName() {
+ boolean DEBBUG = false;
+ if (DEBBUG) appendToLog("3 deviceName = " + (deviceName == null ? "null" : byteArrayToString(deviceName)));
+ if (deviceName == null) {
+ boolean repeatRequest = false;
+ if (DEBBUG) appendToLog("3A mBluetoothIcToWrite.size = " + bluetoothIcToWrite.size());
+ if (bluetoothIcToWrite.size() != 0) {
+ if (bluetoothIcToWrite.get(bluetoothIcToWrite.size() - 1).bluetoothIcPayloadEvent == BluetoothIcPayloadEvents.BLUETOOTH_GET_DEVICE_NAME) {
+ repeatRequest = true;
+ }
+ }
+ if (DEBBUG) appendToLog("3b repeatRequest = " + repeatRequest);
+ if (repeatRequest == false) {
+ BluetoothIcData cs108BluetoothIcData = new BluetoothIcData();
+ cs108BluetoothIcData.bluetoothIcPayloadEvent = BluetoothIcPayloadEvents.BLUETOOTH_GET_DEVICE_NAME;
+ bluetoothIcToWrite.add(cs108BluetoothIcData);
+ if (DEBUG_PKDATA) appendToLog("add " + cs108BluetoothIcData.bluetoothIcPayloadEvent.toString() + " to mBluetoothIcToWrite with length = " + bluetoothIcToWrite.size());
+ }
+ return "";
+ } else {
+ return new String(deviceName).trim();
+ }
+ }
+ public boolean setBluetoothIcName(String name) {
+ if (name == null) return false;
+ if (name.length() == 0) return false;
+ if (name.length() > 20) return false;
+ BluetoothIcData cs108BluetoothIcData = new BluetoothIcData();
+ cs108BluetoothIcData.bluetoothIcPayloadEvent = BluetoothIcPayloadEvents.BLUETOOTH_SET_DEVICE_NAME;
+ if (DEBUG) appendToLog("deviceName.length = " + deviceName.length + ", name.getBytes = " + byteArrayToString(name.getBytes()));
+ cs108BluetoothIcData.dataValues = name.getBytes();
+ if (bluetoothIcToWrite.add(cs108BluetoothIcData) == false) return false;
+ deviceName = name.getBytes();
+ return true;
+ }
+
+ public boolean forceBTdisconnect() {
+ BluetoothIcData cs108BluetoothIcData = new BluetoothIcData();
+ cs108BluetoothIcData.bluetoothIcPayloadEvent = BluetoothIcPayloadEvents.BLUETOOTH_FORCE_BT_DISCONNECT;
+ if (bluetoothIcToWrite.add(cs108BluetoothIcData) == false) return false;
+ return true;
+ }
+
+ public ArrayList bluetoothIcToWrite = new ArrayList<>();
+ private ArrayList mBluetoothIcToRead = new ArrayList<>();
+
+ private boolean arrayTypeSet(byte[] dataBuf, int pos, BluetoothIcPayloadEvents event) {
+ boolean validEvent = false;
+ switch (event) {
+ case BLUETOOTH_GET_VERSION:
+ validEvent = true;
+ break;
+ case BLUETOOTH_SET_DEVICE_NAME:
+ dataBuf[pos] = 3;
+ validEvent = true;
+ break;
+ case BLUETOOTH_GET_DEVICE_NAME:
+ dataBuf[pos] = 4;
+ validEvent = true;
+ break;
+ case BLUETOOTH_FORCE_BT_DISCONNECT:
+ dataBuf[pos] = 5;
+ validEvent = true;
+ break;
+ }
+ return validEvent;
+ }
+
+ private byte[] writeBluetoothIc(BluetoothIcData data, boolean usbConnection) {
+ boolean DEBUG = false;
+ int datalength = 0;
+ if (DEBUG) appendToLog("data.bluetoothIcPayloadEvent=" + data.bluetoothIcPayloadEvent.toString() + ", data.dataValues=" + byteArrayToString(data.dataValues));
+ if (data.dataValues != null) datalength = data.dataValues.length;
+ byte[] dataOutRef = new byte[]{(byte) 0xA7, (byte) 0xB3, 2, (byte) 0x5F, (byte) 0x82, (byte) 0x37, 0, 0, (byte) 0xC0, 0};
+ if (usbConnection) dataOutRef[1] = (byte) 0xE6;
+ byte[] dataOut = new byte[10 + datalength];
+ if (datalength != 0) {
+ System.arraycopy(data.dataValues, 0, dataOut, 10, datalength);
+ dataOutRef[2] += datalength;
+ }
+ System.arraycopy(dataOutRef, 0, dataOut, 0, dataOutRef.length);
+ if (DEBUG) appendToLog("dataOut=" + byteArrayToString(dataOut));
+ if (arrayTypeSet(dataOut, 9, data.bluetoothIcPayloadEvent)) {
+ if (data.bluetoothIcPayloadEvent == BluetoothIcPayloadEvents.BLUETOOTH_SET_DEVICE_NAME && data.dataValues.length < 21) {
+ byte[] dataOut1 = new byte[10+21];
+ System.arraycopy(dataOut, 0, dataOut1, 0, dataOut.length);
+ dataOut1[2] = 23;
+ dataOut = dataOut1;
+ }
+ if (DEBUG) appendToLog(byteArrayToString(dataOut));
+ return dataOut;
+ }
+ return null;
+ }
+
+ public boolean isMatchBluetoothIcToWrite(ConnectorData connectorData) {
+ boolean match = false;
+ if (bluetoothIcToWrite.size() != 0 && connectorData.dataValues[0] == (byte)0xC0) {
+ byte[] dataInCompare = new byte[]{(byte) 0xC0, 0};
+ if (arrayTypeSet(dataInCompare, 1, bluetoothIcToWrite.get(0).bluetoothIcPayloadEvent) && (connectorData.dataValues.length >= dataInCompare.length + 1)) {
+ if (match = compareArray(connectorData.dataValues, dataInCompare, dataInCompare.length)) {
+ boolean bprocessed = false;
+ byte[] data1 = new byte[connectorData.dataValues.length - 2]; System.arraycopy(connectorData.dataValues, 2, data1, 0, data1.length);
+ if (DEBUG_PKDATA) appendToLog("PkData: matched BluetoothIc.Reply with payload = " + byteArrayToString(connectorData.dataValues) + " for writeData BluetoothIc." + bluetoothIcToWrite.get(0).bluetoothIcPayloadEvent.toString());
+ if (bluetoothIcToWrite.get(0).bluetoothIcPayloadEvent == BluetoothIcPayloadEvents.BLUETOOTH_GET_VERSION) {
+ if (connectorData.dataValues.length > 2) {
+ int length = mBluetoothIcVersion.length;
+ if (connectorData.dataValues.length - 2 < length) length = connectorData.dataValues.length - 2;
+ System.arraycopy(connectorData.dataValues, 2, mBluetoothIcVersion, 0, length);
+ if (mBluetoothIcVersion[0] == 3) icsModel = 463;
+ else if (mBluetoothIcVersion[0] == 1) icsModel = 108;
+ mBluetoothIcVersionUpdated = true;
+ if (DEBUG) appendToLog("mBluetoothIcVersionUpdated is true");
+ bprocessed = true;
+ }
+ if (DEBUG_PKDATA) appendToLog("PkData: matched BluetoothIc.Reply.GetVersion with version = " + byteArrayToString(mBluetoothIcVersion));
+ } else if (bluetoothIcToWrite.get(0).bluetoothIcPayloadEvent == BluetoothIcPayloadEvents.BLUETOOTH_GET_DEVICE_NAME) {
+ if (connectorData.dataValues.length > 2) {
+ byte[] deviceName1 = new byte[connectorData.dataValues.length - 2];
+ System.arraycopy(connectorData.dataValues, 2, deviceName1, 0, connectorData.dataValues.length - 2);
+ deviceName = deviceName1;
+ bprocessed = true;
+ }
+ if (DEBUG_PKDATA) appendToLog("PkData: matched mBluetoothIc.GetDeviceName.Reply data is found with name=" + byteArrayToString(deviceName) + ", dataValues.length=" + connectorData.dataValues.length + ", deviceName.length=" + deviceName.length);
+ } else {
+ bprocessed = true;
+ if (DEBUG) appendToLog("matched mBluetoothIc.Other.Reply data is found.");
+ }
+ String string = "Up3 " + (bprocessed ? "" : "Unprocessed, ") + bluetoothIcToWrite.get(0).bluetoothIcPayloadEvent.toString() + ", " + byteArrayToString(data1);
+ utility.writeDebug2File(string);
+ bluetoothIcToWrite.remove(0); sendDataToWriteSent = 0;
+ if (DEBUG_PKDATA) appendToLog("PkData: new mBluetoothIcToWrite size = " + bluetoothIcToWrite.size());
+ }
+ }
+ }
+ return match;
+ }
+
+ public int sendDataToWriteSent = 0;
+ boolean bluetoothFailure = false;
+ public byte[] sendBluetoothIcToWrite(boolean usbConnection) {
+ if (bluetoothFailure) {
+ bluetoothIcToWrite.remove(0); sendDataToWriteSent = 0;
+ } else if (sendDataToWriteSent >= 5) {
+ int oldSize = bluetoothIcToWrite.size();
+ bluetoothIcToWrite.remove(0); sendDataToWriteSent = 0;
+ if (DEBUG) appendToLog("Removed after sending count-out with oldSize = " + oldSize + ", updated mBluetoothIcToWrite.size() = " + bluetoothIcToWrite.size());
+ if (DEBUG) appendToLog("Removed after sending count-out.");
+ String string = "Problem in sending data to Bluetooth Module. Removed data sending after count-out";
+ if (userDebugEnable) Toast.makeText(context, string, Toast.LENGTH_SHORT).show();
+ else appendToLogView(string);
+ bluetoothFailure = true;
+ } else {
+ if (DEBUG) appendToLog("size = " + bluetoothIcToWrite.size() + ", PayloadEvents = " + bluetoothIcToWrite.get(0).bluetoothIcPayloadEvent.toString());
+ sendDataToWriteSent++;
+ return writeBluetoothIc(bluetoothIcToWrite.get(0), usbConnection);
+ }
+ return null;
+ }
+
+ void addBluetoothToWrite(BluetoothIcData cs108BluetoothIcData) {
+ boolean repeatRequest = false;
+ if (bluetoothIcToWrite.size() != 0) {
+ BluetoothIcData cs108BluetoothIcData1 = bluetoothIcToWrite.get(bluetoothIcToWrite.size() - 1);
+ if (cs108BluetoothIcData.bluetoothIcPayloadEvent == cs108BluetoothIcData1.bluetoothIcPayloadEvent) {
+ if (cs108BluetoothIcData.dataValues == null && cs108BluetoothIcData1.dataValues == null) {
+ repeatRequest = true;
+ } else if (cs108BluetoothIcData.dataValues != null && cs108BluetoothIcData1.dataValues != null) {
+ if (cs108BluetoothIcData.dataValues.length == cs108BluetoothIcData1.dataValues.length) {
+ if (compareArray(cs108BluetoothIcData.dataValues, cs108BluetoothIcData1.dataValues, cs108BluetoothIcData.dataValues.length)) {
+ repeatRequest = true;
+ }
+ }
+ }
+ }
+ }
+ if (repeatRequest == false) {
+ bluetoothIcToWrite.add(cs108BluetoothIcData);
+ appendToLog("2b GET_DEVICE_NAME");
+ if (DEBUG_PKDATA) appendToLog("add " + cs108BluetoothIcData.bluetoothIcPayloadEvent.toString() + " to mBluetoothIcToWrite with length = " + bluetoothIcToWrite.size());
+ }
+ }
+}
+
+
+
+package com.csl.cslibrary4a;
+
+import android.Manifest;
+import android.bluetooth.BluetoothAdapter;
+import android.bluetooth.BluetoothDevice;
+import android.bluetooth.BluetoothGattCallback;
+import android.bluetooth.BluetoothGattCharacteristic;
+import android.bluetooth.BluetoothGattDescriptor;
+import android.bluetooth.BluetoothGattService;
+import android.bluetooth.BluetoothManager;
+import android.bluetooth.BluetoothProfile;
+import android.bluetooth.le.BluetoothLeScanner;
+import android.bluetooth.le.ScanCallback;
+import android.content.Context;
+import android.content.pm.PackageManager;
+import android.location.LocationManager;
+import android.os.Build;
+import android.os.Handler;
+
+import androidx.core.app.ActivityCompat;
+
+import android.util.Log;
+import android.widget.PopupWindow;
+
+import java.lang.reflect.Method;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Set;
+import java.util.UUID;
+
+import static android.content.Context.LOCATION_SERVICE;
+
+public class BluetoothGatt extends BluetoothGattCallback {
+ boolean DEBUG_PKDATA, DEBUG_APDATA;
+ final boolean DEBUG = true, DEBUG_BTOP = false;
+ static final String TAG = "Hello";
+
+ private Handler mHandler = new Handler();
+
+ private ReaderDevice readerDeviceConnected;
+ public ReaderDevice getReaderDeviceConnected() {
+ return readerDeviceConnected;
+ }
+
+ public BluetoothManager bluetoothManager;
+ public BluetoothAdapter bluetoothAdapter;
+ public android.bluetooth.BluetoothGatt bluetoothGatt;
+ private BluetoothLeScanner bluetoothLeScanner;
+
+ public int bluetoothConnectionState;
+ public boolean isConnected() { return bluetoothConnectionState == BluetoothProfile.STATE_CONNECTED && mReaderStreamOutCharacteristic != null; }
+
+ private boolean scanning = false;
+ public boolean isScanning() { return scanning; }
+
+ int serviceUUID2p1 = 0;
+ public void setServiceUUIDType(int serviceUUID2p1) { this.serviceUUID2p1 = serviceUUID2p1; }
+
+ private final UUID UUID_READER_STREAM_OUT_CHARACTERISTIC = UUID.fromString("00009900-0000-1000-8000-00805f9b34fb");
+ private final UUID UUID_READER_STREAM_IN_CHARACTERISTIC = UUID.fromString("00009901-0000-1000-8000-00805f9b34fb");
+
+ private int mRssi;
+ public int getRssi() { return mRssi; }
+
+ private boolean characteristicListRead = false;
+
+ public boolean isCharacteristicListRead() {
+ return characteristicListRead;
+ }
+
+ public BluetoothGattCharacteristic mReaderStreamOutCharacteristic;
+ private BluetoothGattCharacteristic mReaderStreamInCharacteristic;
+ private long mStreamWriteCount, mStreamWriteCountOld;
+ private boolean _readCharacteristic_in_progress;
+ private boolean _writeCharacteristic_in_progress;
+ private ArrayList mBluetoothGattCharacteristicToRead = new ArrayList<>();
+
+ private final int STREAM_IN_BUFFER_MAX = 0x100000; //0xC00; //0x800; //0x400;
+ private byte[] streamInBuffer = new byte[STREAM_IN_BUFFER_MAX];
+ private int streamInBufferHead, streamInBufferTail;
+ private int streamInBufferSize = 0;
+
+ public int getStreamInBufferSize() {
+ return streamInBufferSize;
+ }
+
+ private long streamInOverflowTime = 0;
+
+ public long getStreamInOverflowTime() {
+ return streamInOverflowTime;
+ }
+
+ private int streamInBytesMissing = 0;
+
+ public int getStreamInBytesMissing() {
+ int missingByte = streamInBytesMissing;
+ streamInBytesMissing = 0;
+ return missingByte;
+ }
+
+ private int streamInTotalCounter = 0;
+
+ public int getStreamInTotalCounter() {
+ return streamInTotalCounter;
+ }
+
+ private int streamInAddCounter = 0;
+
+ public int getStreamInAddCounter() {
+ return streamInAddCounter;
+ }
+
+ private long streamInAddTime = 0;
+
+ public long getStreamInAddTime() {
+ return streamInAddTime;
+ }
+
+ private boolean connectionHSpeed = true;
+
+ public boolean getConnectionHSpeedA() {
+ return connectionHSpeed;
+ }
+
+ public boolean setConnectionHSpeedA(boolean connectionHSpeed) {
+ this.connectionHSpeed = connectionHSpeed;
+ return true;
+ }
+
+ @Override
+ public void onConnectionStateChange(android.bluetooth.BluetoothGatt gatt, int status, int newState) {
+ boolean DEBUG = false;
+ super.onConnectionStateChange(gatt, status, newState);
+ if (utility.DEBUG_CONNECT) appendToLog("newState = " + newState);
+ if (gatt != bluetoothGatt) {
+ if (DEBUG) appendToLog("abcc mismatched mBluetoothGatt = " + (gatt != bluetoothGatt) + ", status = " + status);
+ } else {
+ bluetoothConnectionState = newState;
+ switch (newState) {
+ case BluetoothProfile.STATE_DISCONNECTED:
+ if (utility.DEBUG_CONNECT) appendToLog("state=Disconnected with status = " + status);
+ if (disconnectRunning == false) {
+ if (DEBUG) appendToLog("disconnect b");
+ disconnect();
+ }
+ break;
+
+ case BluetoothProfile.STATE_CONNECTED:
+ if (utility.DEBUG_CONNECT) appendToLog("state=Connected with status = " + status);
+ if (disconnectRunning) {
+ if (DEBUG) appendToLog("abcc disconnectRunning !!!");
+ break;
+ }
+ mStreamWriteCount = mStreamWriteCountOld = 0;
+ _readCharacteristic_in_progress = _writeCharacteristic_in_progress = false;
+ if (bDiscoverStarted) {
+ if (DEBUG) appendToLog("abc discovery has been started before");
+ break;
+ }
+ if (utility.DEBUG_CONNECT) appendToLog("Start discoverServices");
+ if (discoverServices()) {
+ bDiscoverStarted = true;
+ if (utility.DEBUG_CONNECT) appendToLog("state=Connected. discoverServices starts with status = " + status);
+ } else {
+ if (DEBUG) appendToLog("state=Connected. discoverServices FAIL");
+ }
+ utility.setReferenceTimeMs();
+ mHandler.removeCallbacks(mReadRssiRunnable);
+ mHandler.post(mReadRssiRunnable);
+ break;
+ default:
+ if (DEBUG) appendToLog("state=" + newState);
+ break;
+ }
+ }
+ }
+
+ public boolean bDiscoverStarted = false;
+
+ @Override
+ public void onServicesDiscovered(android.bluetooth.BluetoothGatt gatt, int status) {
+ boolean DEBUG = false;
+ super.onServicesDiscovered(gatt, status);
+ if (gatt != bluetoothGatt) {
+ if (DEBUG) appendToLog("INVALID mBluetoothGatt");
+ } else if (status != android.bluetooth.BluetoothGatt.GATT_SUCCESS) {
+ if (DEBUG) appendToLog("status=" + status + ". restart discoverServices");
+ discoverServices();
+ } else {
+ UUID UUID_READER_SERVICE = UUID.fromString("0000" + strReaderServiceUUID + "-0000-1000-8000-00805f9b34fb");
+ mReaderStreamOutCharacteristic = getCharacteristic(UUID_READER_SERVICE, UUID_READER_STREAM_OUT_CHARACTERISTIC);
+ mReaderStreamInCharacteristic = getCharacteristic(UUID_READER_SERVICE, UUID_READER_STREAM_IN_CHARACTERISTIC);
+ if (DEBUG_BTOP) appendToLog("mReaderStreamOutCharacteristic flag = " + mReaderStreamOutCharacteristic.getProperties());
+ if (DEBUG_BTOP) appendToLog("mReaderStreamInCharacteristic flag = " + mReaderStreamInCharacteristic.getProperties());
+ if (mReaderStreamInCharacteristic == null || mReaderStreamOutCharacteristic == null) {
+ if (DEBUG_BTOP) appendToLog("restart discoverServices");
+ discoverServices();
+ return;
+ }
+
+ if (checkSelfPermissionBLUETOOTH() == false) return;
+ if (!bluetoothGatt.setCharacteristicNotification(mReaderStreamInCharacteristic, true)) {
+ if (DEBUG) appendToLog("setCharacteristicNotification() FAIL");
+ } else {
+ int mtu_requested = 255;
+ boolean bValue = gatt.requestMtu(mtu_requested);
+ if (DEBUG_BTOP) appendToLog("requestMtu[" + mtu_requested + "] with result=" + bValue);
+
+ if (DEBUG_BTOP) appendToLog("characteristicListRead = " + characteristicListRead);
+ if (characteristicListRead == false) {
+ if (DEBUG) appendToLog("with services");
+ mBluetoothGattCharacteristicToRead.clear();
+ List ss = bluetoothGatt.getServices();
+ for (BluetoothGattService service : ss) {
+ String uuid = service.getUuid().toString().substring(4, 8); //substring(0, 8)
+ List cc = service.getCharacteristics();
+ for (BluetoothGattCharacteristic characteristic : cc) {
+ String characteristicUuid = characteristic.getUuid().toString().substring(4, 8); //substring(0, 8)
+ int properties = characteristic.getProperties();
+ boolean do_something = false;
+ if ((properties & BluetoothGattCharacteristic.PROPERTY_READ) > 0) {
+ if (DEBUG)
+ appendToLog("service=" + uuid + ", characteristic=" + characteristicUuid + ", property=read");
+ mBluetoothGattCharacteristicToRead.add(characteristic);
+ do_something = true;
+ }
+ if ((properties & BluetoothGattCharacteristic.PROPERTY_WRITE) > 0) {
+ if (DEBUG)
+ appendToLog("service=" + uuid + ", characteristic=" + characteristicUuid + ", property=write");
+ do_something = true;
+ }
+ if ((properties & BluetoothGattCharacteristic.PROPERTY_NOTIFY) > 0) {
+ if (DEBUG)
+ appendToLog("service=" + uuid + ", characteristic=" + characteristicUuid + ", property=notify");
+ do_something = true;
+ }
+ if (!do_something) {
+ if (DEBUG)
+ appendToLog("service=" + uuid + ", characteristic=" + characteristicUuid + ", property=" + String.format("%X ", properties));
+ }
+ }
+ }
+ if (true) mBluetoothGattCharacteristicToRead.clear();
+ mHandler.removeCallbacks(mReadCharacteristicRunnable);
+ if (DEBUG) appendToLog("starts in onServicesDiscovered");
+ mHandler.postDelayed(mReadCharacteristicRunnable, 500);
+ }
+ }
+ }
+ }
+
+ @Override
+ public void onReadRemoteRssi(android.bluetooth.BluetoothGatt gatt, int rssi, int status) {
+ boolean DEBUG = false;
+ super.onReadRemoteRssi(gatt, rssi, status);
+ if (gatt != bluetoothGatt) {
+ if (DEBUG) utility.appendToLogRunnable("onReadRemoteRssi: INVALID mBluetoothGatt");
+ } else if (status != android.bluetooth.BluetoothGatt.GATT_SUCCESS) {
+ if (DEBUG) utility.appendToLogRunnable("onReadRemoteRssi: NOT GATT_SUCCESS");
+ } else {
+ if (DEBUG_BTOP) utility.appendToLogRunnable("onReadRemoteRssi: rssi=" + rssi);
+ mRssi = rssi;
+ }
+ }
+
+ private final Runnable mReadRssiRunnable = new Runnable() {
+ boolean DEBUG = false;
+ @Override
+ public void run() {
+ if (checkSelfPermissionBLUETOOTH() == false) return;
+ if (bluetoothGatt == null) {
+ if (DEBUG) appendToLog("mReadRssiRunnable: readRemoteRssi with null mBluetoothGatt");
+ return;
+ } else if (bluetoothGatt.readRemoteRssi()) {
+ if (DEBUG_BTOP) appendToLog("mReadRssiRunnable: readRemoteRssi starts");
+ } else {
+ if (DEBUG) appendToLog("mReadRssiRunnable: readRemoteRssi FAIL");
+ }
+ }
+ };
+
+ @Override
+ public void onDescriptorWrite(android.bluetooth.BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
+ super.onDescriptorWrite(gatt, descriptor, status);
+ if (gatt != bluetoothGatt) {
+ if (DEBUG) appendToLog("INVALID mBluetoothGatt");
+ } else if (status != android.bluetooth.BluetoothGatt.GATT_SUCCESS) {
+ if (DEBUG) appendToLog("status=" + status);
+ } else {
+ if (DEBUG) appendToLog("descriptor=" + descriptor.getUuid().toString().substring(4, 8));
+ }
+ }
+
+ private boolean writeDescriptor(BluetoothGattDescriptor descriptor, byte[] value) {
+ descriptor.setValue(value);
+ if (checkSelfPermissionBLUETOOTH() == false) return false;
+ if (!bluetoothGatt.writeDescriptor(descriptor))
+ return false;
+ return true;
+ }
+
+ @Override
+ public void onDescriptorRead(android.bluetooth.BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
+ super.onDescriptorRead(gatt, descriptor, status);
+ if (gatt != bluetoothGatt) {
+ if (DEBUG) utility.appendToLogRunnable("onDescriptorRead(): INVALID mBluetoothGatt");
+ } else if (status != android.bluetooth.BluetoothGatt.GATT_SUCCESS) {
+ if (DEBUG) utility.appendToLogRunnable("onDescriptorRead(): status=" + status);
+ } else {
+ if (DEBUG) utility.appendToLogRunnable("onDescriptorRead(): descriptor=" + descriptor.getUuid().toString().substring(4, 8));
+ }
+ }
+
+ @Override
+ public void onCharacteristicRead(android.bluetooth.BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
+ super.onCharacteristicRead(gatt, characteristic, status);
+ if (gatt != bluetoothGatt) {
+ if (DEBUG) appendToLog("INVALID mBluetoothGatt");
+ } else if (status != android.bluetooth.BluetoothGatt.GATT_SUCCESS) {
+ if (DEBUG) appendToLog("status=" + status);
+ } else {
+ _readCharacteristic_in_progress = false;
+
+ final String serviceUuidd = characteristic.getService().getUuid().toString().substring(4, 8);
+ final String characteristicUuid = characteristic.getUuid().toString().substring(4, 8);
+ final byte[] v = characteristic.getValue();
+ final long t = utility.getReferencedCurrentTimeMs();
+ mHandler.removeCallbacks(mReadCharacteristicRunnable);
+ StringBuilder stringBuilder = new StringBuilder();
+ if (v != null && v.length > 0) {
+ stringBuilder.ensureCapacity(v.length * 3);
+ for (byte b : v)
+ stringBuilder.append(String.format("%02X ", b));
+ }
+ if (DEBUG) appendToLog(serviceUuidd + ", " + characteristicUuid + " = " + stringBuilder.toString() + " = " + new String(v));
+ if (DEBUG) appendToLog("starts in onCharacteristicRead");
+ mReadCharacteristicRunnable.run();
+ }
+ }
+
+ private final Runnable mReadCharacteristicRunnable = new Runnable() {
+ @Override
+ public void run() {
+ if (mBluetoothGattCharacteristicToRead.size() == 0) {
+ if (DEBUG) appendToLog("mReadCharacteristicRunnable(): read finish");
+ characteristicListRead = true;
+ } else if (isBleBusy()) {
+ if (DEBUG) appendToLog("mReadCharacteristicRunnable(): PortBusy");
+ mHandler.postDelayed(mReadCharacteristicRunnable, 100);
+ } else if (readCharacteristic(mBluetoothGattCharacteristicToRead.get(0)) == false) {
+ if (DEBUG) appendToLog("mReadCharacteristicRunnable(): Read FAIL");
+ mHandler.postDelayed(mReadCharacteristicRunnable, 100);
+ } else {
+ mBluetoothGattCharacteristicToRead.remove(0);
+ if (DEBUG) appendToLog("mReadCharacteristicRunnable(): starts in mReadCharacteristicRunnable");
+ mHandler.postDelayed(mReadCharacteristicRunnable, 10000);
+ }
+ }
+ };
+
+ private boolean readCharacteristic(BluetoothGattCharacteristic characteristic) {
+ if (checkSelfPermissionBLUETOOTH() == false) return false;
+ if (bluetoothGatt.readCharacteristic(characteristic)) {
+ _readCharacteristic_in_progress = true;
+ return true;
+ }
+ return false;
+ }
+
+ @Override
+ public void onCharacteristicWrite(android.bluetooth.BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
+ boolean DEBUG = false;
+ super.onCharacteristicWrite(gatt, characteristic, status);
+ if (gatt != bluetoothGatt) {
+ if (DEBUG) appendToLog("INVALID mBluetoothGatt");
+ } else if (status != android.bluetooth.BluetoothGatt.GATT_SUCCESS) {
+ onCharacteristicWriteFailue++;
+ if (DEBUG) appendToLog("status=" + status);
+ } else {
+ onCharacteristicWriteFailue = 0;
+ if (DEBUG) appendToLog("characteristic=" + characteristic.getUuid().toString().substring(4, 8) + ", sent " + (mStreamWriteCount - mStreamWriteCountOld) + " bytes");
+ _writeCharacteristic_in_progress = false;
+ }
+ }
+
+ private int writeBleFailure = 0;
+ private int onCharacteristicWriteFailue = 0;
+ public boolean writeBleStreamOut(byte[] value) {
+ if (bluetoothGatt == null) {
+ if (DEBUG) appendToLog("ERROR with NULL mBluetoothGatt");
+ } else if (mReaderStreamOutCharacteristic == null) {
+ if (DEBUG) appendToLog("ERROR with NULL mReaderStreamOutCharacteristic");
+ } else if (isBleBusy() || characteristicListRead == false) {
+ if (true) appendToLog("isBleBusy() = " + isBleBusy() + ", characteristicListRead = " + characteristicListRead);
+ } else {
+ mReaderStreamOutCharacteristic.setValue(value);
+ if (checkSelfPermissionBLUETOOTH() == false) return false;
+ boolean bValue = bluetoothGatt.writeCharacteristic(mReaderStreamOutCharacteristic);
+ if (bValue == false) writeBleFailure++;
+ else {
+ writeBleFailure = 0;
+ if (utility.DEBUG_BTDATA || true) appendToLogView("BtDataOut: " + byteArrayToString(value));
+ writeDebug2File("Down " + byteArrayToString(value));
+ _writeCharacteristic_in_progress = true;
+ mStreamWriteCountOld = mStreamWriteCount;
+ mStreamWriteCount += value.length;
+ return true;
+ }
+ if (false && (writeBleFailure != 0 || onCharacteristicWriteFailue != 0)) {
+ appendToLogView("failure in writeCharacteristic(" + byteArrayToString(value) + "), writeBleFailure = " + writeBleFailure + ", onCharacteristicWriteFailue = " + onCharacteristicWriteFailue);
+ if (writeBleFailure > 5 || onCharacteristicWriteFailue > 5) {
+ appendToLogView("writeBleFailure is too much. start disconnect !!!");
+ appendToLog("disconnect C");
+ disconnect(); //mReaderStreamOutCharacteristic = null;
+ }
+ }
+ }
+ return false;
+ }
+
+ private boolean streamInRequest = false;
+ @Override
+ public void onCharacteristicChanged(android.bluetooth.BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
+ super.onCharacteristicChanged(gatt, characteristic);
+ if (gatt != bluetoothGatt) {
+ utility.writeDebug2File("Up1 Error, mismatched gatt");
+ if (DEBUG) {
+ byte[] v = characteristic.getValue();
+ utility.appendToLogRunnable("onCharacteristicChanged(): INVALID mBluetoothGatt, with address = " + gatt.getDevice().getAddress() + ", values =" + byteArrayToString(v));
+ }
+ } else if (!characteristic.equals(mReaderStreamInCharacteristic)) {
+ utility.writeDebug2File("Up1 Error, mismatched characteristic");
+ if (DEBUG) utility.appendToLogRunnable("onCharacteristicChanged(): characteristic is not ReaderSteamIn");
+ } else if (bluetoothConnectionState == BluetoothProfile.STATE_DISCONNECTED) {
+ utility.writeDebug2File("Up1 Error, disconnected bluetoothConnectionState");
+ streamInBufferHead = 0;
+ streamInBufferTail = 0;
+ streamInBufferSize = 0;
+ } else {
+ byte[] v = characteristic.getValue();
+ if (false) utility.appendToLogRunnable("onCharacteristicChanged(): VALID mBluetoothGatt, values =" + byteArrayToString(v));
+ synchronized (arrayListStreamIn) {
+ if (v.length != 0) {
+ streamInTotalCounter++;
+ }
+ if (streamInBufferReseting) {
+ if (DEBUG) utility.appendToLogRunnable("onCharacteristicChanged(): RESET.");
+ streamInBufferReseting = false;
+ streamInBufferSize = 0;
+ streamInBytesMissing = 0;
+ }
+ if (streamInBufferSize + v.length > streamInBuffer.length) {
+ utility.writeDebug2File("Up1 Error, insufficient buffer. missed " + byteArrayToString(v));
+ Log.i(TAG, ".Hello: missing data = " + byteArrayToString(v));
+ if (streamInBytesMissing == 0) {
+ streamInOverflowTime = utility.getReferencedCurrentTimeMs();
+ }
+ streamInBytesMissing += v.length;
+ } else {
+ if (true) utility.writeDebug2File("Up1 " + byteArrayToString(v));
+ if (utility.DEBUG_BTDATA) Log.i(TAG, "BtDataIn= " + byteArrayToString(v));
+ if (isStreamInBufferRing) {
+ streamInBufferPush(v, 0, v.length);
+ } else {
+ System.arraycopy(v, 0, streamInBuffer, streamInBufferSize, v.length);
+ }
+ streamInBufferSize += v.length;
+ streamInAddCounter++;
+ streamInAddTime = utility.getReferencedCurrentTimeMs();
+ if (streamInRequest == false) {
+ streamInRequest = true;
+ //appendToLog("post runnableProcessStreamInData after onCharacteristicChanged");
+ mHandler.removeCallbacks(runnableProcessStreamInData); mHandler.post(runnableProcessStreamInData);
+ }
+ }
+ }
+ }
+ }
+
+ private boolean streamInBufferReseting = false;
+ void setStreamInBufferReseting() { streamInBufferReseting = true; }
+
+ void processStreamInData() {
+ if (connectorCallback != null) connectorCallback.callbackMethod();
+ }
+
+ public interface ConnectorCallback {
+ void callbackMethod();
+ }
+ public ConnectorCallback connectorCallback = null;
+
+ private int intervalProcessBleStreamInData = 100; //50;
+ public int getIntervalProcessBleStreamInData() { return intervalProcessBleStreamInData; }
+ public final Runnable runnableProcessStreamInData = new Runnable() {
+ @Override
+ public void run() {
+ streamInRequest = false;
+ processStreamInData();
+ //appendToLog("post runnableProcessStreamInData within runnableProcessStreamInData");
+ mHandler.postDelayed(runnableProcessStreamInData, intervalProcessBleStreamInData);
+ }
+ };
+
+ @Override
+ public void onMtuChanged(android.bluetooth.BluetoothGatt gatt, int mtu, int status) {
+ super.onMtuChanged(gatt, mtu, status);
+ Log.i(TAG, "onMtuChanged starts");
+ if (gatt != bluetoothGatt) {
+ if (DEBUG) utility.appendToLogRunnable("onMtuChanged: INVALID mBluetoothGatt");
+ } else if (status != android.bluetooth.BluetoothGatt.GATT_SUCCESS) {
+ if (DEBUG) utility.appendToLogRunnable("onMtuChanged: status=" + status);
+ } else {
+ if (DEBUG_BTOP) utility.appendToLogRunnable("onMtuChanged: mtu=" + mtu);
+ }
+ }
+
+ @Override
+ public void onReliableWriteCompleted(android.bluetooth.BluetoothGatt gatt, int status) {
+ super.onReliableWriteCompleted(gatt, status);
+ if (gatt != bluetoothGatt) {
+ if (true) utility.appendToLogRunnable("INVALID mBluetoothGatt");
+ } else {
+ if (true) utility.appendToLogRunnable("onReliableWriteCompleted(): status=" + status);
+ //mBluetoothGatt.abortReliableWrite();
+ }
+ }
+
+ private Context context; Utility utility; String strReaderServiceUUID; //private Activity activity;
+ public BluetoothGatt(Context context, Utility utility, String strReaderServiceUUID) {
+ boolean DEBUG = false;
+ this.context = context; //activity = (Activity) mContext;
+ this.strReaderServiceUUID = strReaderServiceUUID;
+ this.utility = utility; DEBUG_PKDATA = utility.DEBUG_PKDATA; DEBUG_APDATA = utility.DEBUG_APDATA;
+
+// BluetoothConfigManager mConfigManager;
+// mConfigManager = BluetoothConfigManager.getInstance();
+// appendToLog("BluetoothConfigManager.getIoCapability = " + mConfigManager.getIoCapability());
+
+ PackageManager mPackageManager = this.context.getPackageManager();
+ if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
+ bluetoothManager = (BluetoothManager) this.context.getSystemService(Context.BLUETOOTH_SERVICE);
+ bluetoothAdapter = bluetoothManager.getAdapter();
+ if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
+ boolean isBle5 = bluetoothAdapter.isLeCodedPhySupported();
+ boolean isAdvertising5 = bluetoothAdapter.isLeExtendedAdvertisingSupported();
+ if (DEBUG) appendToLog("isBle5 = " + isBle5 + ", isAdvertising5 = " + isAdvertising5);
+ }
+ } else {
+ bluetoothAdapter = null;
+ if (DEBUG) appendToLog("NO BLUETOOTH_LE");
+ }
+
+ if (DEBUG) {
+ LocationManager locationManager = (LocationManager) this.context.getSystemService(LOCATION_SERVICE);
+ if (ActivityCompat.checkSelfPermission(this.context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) appendToLog("permitted ACCESS_FINE_LOCATION");
+ if (ActivityCompat.checkSelfPermission(this.context, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) appendToLog("permitted ACCESS_COARSE_LOCATION");
+
+ List stringProviderList = locationManager.getAllProviders();
+ for (String stringProvider : stringProviderList)
+ appendToLog("Provider = " + stringProvider);
+ if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER))
+ appendToLog("ProviderEnabled GPS_PROVIDER");
+ if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER))
+ appendToLog("ProviderEnabled NETWORK_PROVIDER");
+ if (locationManager.isProviderEnabled(LocationManager.PASSIVE_PROVIDER))
+ appendToLog("ProviderEnabled PASSIVE_PROVIDER");
+ }
+ }
+
+ private PopupWindow popupWindow;
+ private boolean /*bleEnableRequestShown0 = false, */bleEnableRequestShown = false;
+ private boolean isLocationAccepted = false;
+ boolean bAlerting = false; //CustomAlertDialog appdialog;
+ public boolean scanDevice(boolean enable, BluetoothAdapter.LeScanCallback mLeScanCallback, ScanCallback mScanCallBack) {
+ boolean DEBUG = false;
+ if (DEBUG) appendToLog("BluetoothGatt.scanDevice: StreamOut: enable = " + enable);
+ boolean result = false;
+ boolean locationReady = true;
+ if (enable && isConnected()) return true;
+ if (enable == false && isScanning() == false) return true;
+
+ if (enable) {
+ LocationManager locationManager = (LocationManager) context.getSystemService(LOCATION_SERVICE);
+ if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) == false && locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER) == false)
+ isLocationAccepted = false;
+ }
+ if (DEBUG || utility.DEBUG_SCAN) appendToLog("BluetoothGatt.scanLeDevice: isLocationAccepted = " + isLocationAccepted + ", bAlerting = " + bAlerting + ", bleEnableRequestShown = " + bleEnableRequestShown);
+ /*if (false && isLocationAccepted == false) {
+ if (bAlerting == false && bleEnableRequestShown0 == false) {
+ bAlerting = true;
+ if (DEBUG) appendToLog("StreamOut: new AlertDialog");
+ popupAlert();
+ }
+ return false;
+ }*/
+/*
+ if (DEBUG) appendToLog("StreamOut: Passed AlertDialog");
+ if (enable && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
+ if (DEBUG) appendToLog("Checking permission and grant !!!");
+ LocationManager locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
+ if (DEBUG_SCAN) appendToLog("locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) = " + locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER));
+ if (DEBUG_SCAN) appendToLog("locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER) = " + locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER));
+ if (DEBUG_SCAN) appendToLog("ActivityCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_FINE_LOCATION) = " + ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION));
+ if (DEBUG_SCAN) appendToLog("ActivityCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_COARSE_LOCATION) = " + ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION));
+ if (false && locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) == false && locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER) == false) {
+ boolean isShowing = false;
+ if (popupWindow != null) isShowing = popupWindow.isShowing();
+ if (isShowing == false) {
+ LayoutInflater layoutInflater = (LayoutInflater) mContext.getSystemService(LAYOUT_INFLATER_SERVICE);
+ View popupView = layoutInflater.inflate(R.layout.popup, null);
+ popupWindow = new PopupWindow(popupView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
+ popupWindow.showAtLocation(popupView, Gravity.CENTER, 0, 0);
+ TextView textViewDismiss = (TextView) popupView.findViewById(R.id.dismissMessage);
+ textViewDismiss.setText("Android OS 6.0+ requires to enable location service to find the nearby BLE devices");
+ Button btnDismiss = (Button) popupView.findViewById(R.id.dismiss);
+ if (DEBUG) appendToLog("Setting grant");
+ btnDismiss.setOnClickListener(new Button.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ popupWindow.dismiss();
+ if (DEBUG) appendToLog("Set GRANT");
+ Intent intent1 = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
+ mContext.startActivity(intent1);
+ }
+ });
+ }
+ return false;
+ } else if (
+ (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) == false
+ && locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER) == false)
+ || (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
+ && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)) {
+ if (true) {
+ if (bAlerting || bleEnableRequestShown0) return false;
+ bAlerting = true;
+ popupAlert();
+ return false;
+ }
+ }
+ }
+*/
+ if (isBLUETOOTH_CONNECTinvalid()) return false;
+
+ if (locationReady == false) {
+ if (DEBUG) appendToLog("BluetoothGatt.scanLeDevice: AccessCoarseLocatin is NOT granted");
+ } else if (bluetoothAdapter == null) {
+ if (DEBUG) appendToLog("BluetoothGatt.scanLeDevice: scanLeDevice(" + enable + ") with NULL mBluetoothAdapter");
+/* } else if (!bluetoothAdapter.isEnabled()) {
+ if (DEBUG) appendToLog("StreamOut: bleEnableRequestShown = " + bleEnableRequestShown);
+ if (bleEnableRequestShown == false) {
+ if (true) appendToLog("scanLeDevice(" + enable + ") with DISABLED mBluetoothAdapter");
+ Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
+ activity.startActivityForResult(enableBtIntent, 1);
+ if (DEBUG) appendToLog("StreamOut: bleEnableRequestShown is set");
+ bleEnableRequestShown = true; mHandler.postDelayed(mRquestAllowRunnable, 60000);
+ }
+*/
+ } else {
+ bleEnableRequestShown = false;
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
+ bluetoothLeScanner = bluetoothAdapter.getBluetoothLeScanner();
+ if (bluetoothLeScanner == null) {
+ if (DEBUG) appendToLog("BluetoothGatt.scanLeDevice: scanLeDevice(" + enable + ") with NULL BluetoothLeScanner");
+ return false;
+ }
+ }
+ if (enable == false) {
+ if (true) appendToLog("BluetoothGatt.scanLeDevice: scanLeDevice(" + enable + ") with mScanCallBack is " + (mScanCallBack != null ? "VALID" : "INVALID"));
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
+ if (mScanCallBack != null) bluetoothLeScanner.stopScan(mScanCallBack);
+ } else {
+ if (mLeScanCallback != null) bluetoothAdapter.stopLeScan(mLeScanCallback);
+ }
+ scanning = false; result = true;
+ } else {
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
+ if (true) appendToLog("BluetoothGatt.scanLeDevice: scanLeDevice(" + enable + "): START with mleScanner. ActivityCompat.checkSelfPermission(activity, Manifest.permission.BLUETOOTH_SCAN) = " + ActivityCompat.checkSelfPermission(context, Manifest.permission.BLUETOOTH_SCAN));
+ if (isBLUETOOTH_CONNECTinvalid()) return false;
+ else bluetoothLeScanner.startScan(mScanCallBack);
+ } else {
+ if (true) appendToLog("BluetoothGatt.scanLeDevice: scanLeDevice(" + enable + "): START with mBluetoothAdapter");
+ bluetoothAdapter.startLeScan(mLeScanCallback);
+ }
+ scanning = true; result = true;
+ }
+ }
+ return result;
+ }
+
+ private final Runnable mRquestAllowRunnable = new Runnable() {
+ @Override
+ public void run() {
+ //bleEnableRequestShown0 = false;
+ bleEnableRequestShown = false;
+ }
+ };
+/*
+ void popupAlert() {
+ appdialog = new CustomAlertDialog();
+ appdialog.Confirm(activity, "Use your location",
+ "This app collects location data in the background. In terms of the features using this location data in the background, this App collects location data when it is reading RFID tag in all inventory pages. The purpose of this is to correlate the RFID tag with the actual GNSS(GPS) location of the tag. In other words, this is to track the physical location of the logistics item tagged with the RFID tag.",
+ "No thanks", "Turn on",
+ new Runnable() {
+ @Override
+ public void run() {
+ isLocationAccepted = true;
+ appendToLog("StreamOut: This from FALSE proc");
+ if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
+// && ActivityCompat.checkSelfPermission(activity, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED
+ && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
+ appendToLog("requestPermissions ACCESS_FINE_LOCATION 123");
+ requestPermissions(activity, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 123);
+ if (false) Toast.makeText(mContext, R.string.toast_permission_not_granted, Toast.LENGTH_SHORT).show();
+ }
+ {
+ LocationManager locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
+ if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) == false && locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER) == false) {
+ appendToLog("StreamOut: start activity ACTION_LOCATION_SOURCE_SETTINGS");
+ Intent intent1 = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
+ mContext.startActivity(intent1);
+ }
+ }
+ bleEnableRequestShown0 = true; mHandler.postDelayed(mRquestAllowRunnable, 60000);
+ bAlerting = false;
+ }
+ },
+ new Runnable() {
+ @Override
+ public void run() {
+ appendToLog("StreamOut: This from FALSE proc");
+ bAlerting = false;
+ bleEnableRequestShown0 = true; mHandler.postDelayed(mRquestAllowRunnable, 60000);
+ }
+ });
+ }
+
+ BroadcastReceiver myReceiver = new BroadcastReceiver() {
+ @Override
+ public void onReceive(Context context, Intent intent) {
+ String action = intent.getAction();
+ appendToLog("action = " + action);
+ if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {
+ BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
+ if (device.getBondState() == BluetoothDevice.BOND_BONDED) {
+ // CONNECT
+ }
+ } else if (BluetoothDevice.ACTION_FOUND.equals(action)) {
+ BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
+ // Discover new device
+ }
+ }
+ };
+*/
+ public boolean connect(ReaderDevice readerDevice) {
+ boolean DEBUG = false;
+ if (DEBUG) appendToLog("abcc: start connecting " + readerDevice.getName());
+ if (readerDevice == null) {
+ if (DEBUG) appendToLog("with NULL readerDevice");
+ } else {
+ String address = readerDevice.getAddress();
+ if (bluetoothAdapter == null) {
+ if (DEBUG) appendToLog("connect[" + address + "] with NULL mBluetoothAdapter");
+ } else if (!bluetoothAdapter.isEnabled()) {
+ if (DEBUG) appendToLog("connect[" + address + "] with DISABLED mBluetoothAdapter");
+ } else {
+ utility.debugFileSetup(); utility.debugFileEnable(true);
+ utility.setReferenceTimeMs();
+ if (utility.DEBUG_CONNECT) appendToLog("connect[" + address + "]: connectGatt starts");
+ bluetoothConnectionState = -1;
+ if (checkSelfPermissionBLUETOOTH() == false) return false;
+ bluetoothGatt = bluetoothAdapter.getRemoteDevice(address).connectGatt(context, false, this);
+ if (bluetoothGatt != null) mBluetoothGattActive = true;
+ if (false && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
+ if (true) {
+ bluetoothGatt.requestConnectionPriority(android.bluetooth.BluetoothGatt.CONNECTION_PRIORITY_HIGH);
+ if (DEBUG) appendToLog("Stream Set to HIGH");
+ }
+ else {
+ bluetoothGatt.requestConnectionPriority(android.bluetooth.BluetoothGatt.CONNECTION_PRIORITY_BALANCED);
+ if (DEBUG) appendToLog("Stream Set to BALANCED");
+ }
+ }
+ readerDeviceConnected = readerDevice;
+ characteristicListRead = true; //skip in case there is problem in completing reading characteristic features, causing endless reading 0706 and 0C02
+ appendToLog("post runnableProcessStreamInData after connect");
+ mHandler.removeCallbacks(runnableProcessStreamInData); mHandler.post(runnableProcessStreamInData);
+ return true;
+ }
+ }
+ return false;
+ }
+
+ public void disconnect() {
+ appendToLog("abcc: start disconnect ");
+ if (bluetoothGatt == null) {
+ if (DEBUG) appendToLog("NULL mBluetoothGatt");
+ } else {
+ utility.debugFileClose();
+ mReaderStreamOutCharacteristic = null;
+ mHandler.removeCallbacks(mDisconnectRunnable);
+ mHandler.post(mDisconnectRunnable); disconnectRunning = true;
+ if (DEBUG) appendToLog("abcc done and start mDisconnectRunnable");
+ appendToLog("post runnableProcessStreamInData after disconnect");
+ mHandler.removeCallbacks(runnableProcessStreamInData);
+ }
+ }
+ boolean mBluetoothGattActive = false;
+ boolean forcedDisconnect1() {
+ mHandler.removeCallbacks(mReadRssiRunnable);
+ mHandler.removeCallbacks(mReadCharacteristicRunnable);
+ if (bluetoothGatt != null) {
+ if (mBluetoothGattActive) {
+ appendToLog("abcc mDisconnectRunnable(): close mBluetoothGatt");
+ if (checkSelfPermissionBLUETOOTH() == false) return false;
+ bluetoothGatt.close();
+ mBluetoothGattActive = false;
+ } else {
+ appendToLog("abcc mDisconnectRunnable(): Null mBluetoothGatt");
+ bluetoothGatt = null;
+ return true;
+ }
+ }
+ return false;
+ //mBluetoothConnectionState = -1;
+ }
+
+ private boolean disconnectRunning = false;
+ public BluetoothDevice bluetoothDeviceConnectOld;
+ private final Runnable mDisconnectRunnable = new Runnable() {
+ @Override
+ public void run() {
+ boolean done = false;
+ int bGattConnection = -1;
+ if (checkSelfPermissionBLUETOOTH() == false) return;
+ if (bluetoothDeviceConnectOld != null) bGattConnection = bluetoothManager.getConnectionState(bluetoothDeviceConnectOld, BluetoothProfile.GATT);
+ if (DEBUG) appendToLog("abcc DisconnectRunnable(): disconnect with mBluetoothConnectionState = " + bluetoothConnectionState + ", gattConnection = " + bGattConnection);
+ if (bluetoothConnectionState < 0) {
+ appendToLog("abcc DisconnectRunnable(): start mBluetoothGatt.disconnect");
+ bluetoothGatt.disconnect();
+ bluetoothConnectionState = BluetoothProfile.STATE_DISCONNECTED;
+ } else if (bluetoothConnectionState != BluetoothProfile.STATE_DISCONNECTED) {
+ appendToLog("abcc 2 DisconnectRunnable(): start mBluetoothGatt.disconnect");
+ if (checkSelfPermissionBLUETOOTH()) {
+ bluetoothGatt.disconnect(); //forcedDisconnect(true);
+ bluetoothConnectionState = BluetoothProfile.STATE_DISCONNECTED;
+ }
+ } else if (forcedDisconnect1()) {
+ if (DEBUG) appendToLog("abcc mDisconnectRunnable(): END");
+ disconnectRunning = false;
+ if (false) bluetoothAdapter.disable();
+ done = true;
+ }
+ if (done == false) mHandler.postDelayed(mDisconnectRunnable, 100);
+ }
+ };
+
+ boolean isBleBusy() {
+ return bluetoothConnectionState != BluetoothProfile.STATE_CONNECTED || _readCharacteristic_in_progress /*|| _writeCharacteristic_in_progress*/;
+ }
+
+ private BluetoothGattCharacteristic getCharacteristic(UUID service, UUID characteristic) {
+ BluetoothGattService s = bluetoothGatt.getService(service);
+ if (s == null)
+ return null;
+ BluetoothGattCharacteristic c = s.getCharacteristic(characteristic);
+ return c;
+ }
+
+ private long streamInDataMilliSecond;
+ public long getStreamInDataMilliSecond() { return streamInDataMilliSecond; }
+ public int readSteamIn(byte[] buffer, int byteOffset, int byteCount) {
+ synchronized (arrayListStreamIn) {
+ if (0 == streamInBufferSize) return 0;
+
+ if (isArrayListStreamInBuffering) {
+ int byteGot = 0;
+ int length1 = arrayListStreamIn.get(0).data.length;
+ if (arrayListStreamIn.size() != 0 && buffer.length - byteOffset > length1) {
+ System.arraycopy(arrayListStreamIn.get(0).data, 0, buffer, byteOffset, length1);
+ streamInDataMilliSecond = arrayListStreamIn.get(0).milliseconds;
+ arrayListStreamIn.remove(0);
+ byteOffset += length1;
+ byteGot += length1;
+ }
+ byteCount = byteGot;
+ } else {
+ if (byteCount > streamInBufferSize)
+ byteCount = streamInBufferSize;
+ if (byteOffset + byteCount > buffer.length) {
+ byteCount = buffer.length - byteOffset;
+ }
+ if (byteCount <= 0) return 0;
+
+ if (isStreamInBufferRing) {
+ streamInBufferPull(buffer, byteOffset, byteCount);
+ } else {
+ System.arraycopy(streamInBuffer, 0, buffer, byteOffset, byteCount);
+ System.arraycopy(streamInBuffer, byteCount, streamInBuffer, 0, streamInBufferSize - byteCount);
+ }
+ }
+ streamInBufferSize -= byteCount;
+ return byteCount;
+ }
+ }
+
+ private int totalTemp, totalReceived;
+ private long firstTime, totalTime; public long getStreamInRate() {
+ if (totalTime == 0 || totalReceived == 0) return 0;
+ return totalReceived * 1000 / totalTime;
+ }
+
+ private class StreamInData {
+ byte[] data;
+ long milliseconds;
+ }
+ private ArrayList arrayListStreamIn = new ArrayList(); private boolean isArrayListStreamInBuffering = true;
+ private boolean isStreamInBufferRing = true;
+ private void streamInBufferPush(byte[] inData, int inDataOffset, int length) {
+ int length1 = streamInBuffer.length - streamInBufferTail;
+ int totalCopy = 0;
+ if (isArrayListStreamInBuffering) {
+ StreamInData streamInData = new StreamInData();
+ streamInData.data = inData;
+ streamInData.milliseconds = System.currentTimeMillis();
+ arrayListStreamIn.add(streamInData);
+ totalCopy = length;
+ } else {
+ if (length > length1) {
+ totalCopy = length1;
+ System.arraycopy(inData, inDataOffset, streamInBuffer, streamInBufferTail, length1);
+ length -= length1;
+ inDataOffset += length1;
+ streamInBufferTail = 0;
+ }
+ if (length != 0) {
+ totalCopy += length;
+ System.arraycopy(inData, inDataOffset, streamInBuffer, streamInBufferTail, length);
+ streamInBufferTail += length;
+ }
+ }
+ if (totalCopy != 0) {
+ totalTemp += totalCopy;
+ long timeDifference = System.currentTimeMillis() - firstTime;
+ if (totalTemp > 17 && timeDifference > 1000) {
+ totalReceived = totalTemp;
+ totalTime = timeDifference;
+ //appendToLog("BtDataIn: totalReceived = " + totalReceived + ", totalTime = " + totalTime);
+ firstTime = System.currentTimeMillis();
+ totalTemp = 0;
+ }
+ }
+ }
+ private void streamInBufferPull(byte[] buffer, int byteOffset, int length) {
+ synchronized (arrayListStreamIn) {
+ int length1 = streamInBuffer.length - streamInBufferHead;
+ if (length > length1) {
+ System.arraycopy(streamInBuffer, streamInBufferHead, buffer, byteOffset, length1);
+ length -= length1;
+ byteOffset += length1;
+ streamInBufferHead = 0;
+ }
+ if (length != 0) {
+ System.arraycopy(streamInBuffer, streamInBufferHead, buffer, byteOffset, length);
+ streamInBufferHead += length;
+ }}
+ }
+
+ public boolean isBLUETOOTH_CONNECTinvalid() {
+ boolean bValue = false;
+/*
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S && (
+ ActivityCompat.checkSelfPermission(mContext, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED || ActivityCompat.checkSelfPermission(mContext, Manifest.permission.BLUETOOTH_SCAN) != PackageManager.PERMISSION_GRANTED
+ )) {
+ appendToLog("requestPermissions BLUETOOTH_CONNECT & BLUETOOTH_CONNECT 123");
+ requestPermissions(activity, new String[] {
+ Manifest.permission.BLUETOOTH_SCAN,
+ Manifest.permission.BLUETOOTH_CONNECT
+ }, 123);
+ if (false) Toast.makeText(mContext, R.string.toast_permission_not_granted, Toast.LENGTH_SHORT).show();
+ bValue = true;
+ }
+ //appendToLog("isBLUETOOTH_CONNECTinvalid returns " + bValue);
+*/
+ return bValue;
+ }
+
+ String byteArray2DisplayString(byte[] byteData) { return utility.byteArray2DisplayString(byteData); }
+ String byteArrayToString(byte[] packet) { return utility.byteArrayToString(packet); }
+ int byteArrayToInt(byte[] bytes) { return utility.byteArrayToInt(bytes); }
+ void appendToLog(String s) { utility.appendToLog(s); }
+ void appendToLogView(String s) { utility.appendToLogView(s); }
+ void writeDebug2File(String stringDebug) { utility.writeDebug2File(stringDebug); }
+ boolean compareArray(byte[] array1, byte[] array2, int length) { return utility.compareByteArray(array1, array2, length); }
+ void debugFileEnable(boolean enable) { utility.debugFileEnable(enable); }
+ String getlast3digitVersion(String str) { return utility.getlast3digitVersion(str); }
+ public boolean isVersionGreaterEqual(String version, int majorVersion, int minorVersion, int buildVersion) { return utility.isVersionGreaterEqual(version, majorVersion, minorVersion, buildVersion); }
+ double get2BytesOfRssi(byte[] bytes, int index) { return utility.get2BytesOfRssi(bytes, index); }
+
+ int getConnectionState(BluetoothDevice bluetoothDevice) {
+ if (checkSelfPermissionBLUETOOTH() == false) return -1;
+
+ return bluetoothManager.getConnectionState(bluetoothDevice, BluetoothProfile.GATT);
+ }
+
+ boolean discoverServices() {
+ if (checkSelfPermissionBLUETOOTH() == false) return false;
+ return bluetoothGatt.discoverServices();
+ }
+ boolean checkSelfPermissionBLUETOOTH() {
+ boolean bValue = false;
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
+ if (ActivityCompat.checkSelfPermission(context, Manifest.permission.BLUETOOTH_CONNECT) == PackageManager.PERMISSION_GRANTED) bValue = true;
+ } else if (ActivityCompat.checkSelfPermission(context.getApplicationContext(), Manifest.permission.BLUETOOTH) == PackageManager.PERMISSION_GRANTED) bValue = true;
+ if (false) Log.i("Hello3", "checkSelfPermissionBLUETOOTH bValue = " + bValue);
+ return bValue;
+ }
+
+ public static class CsScanData {
+ public BluetoothDevice device; public String name, address;
+ public int rssi;
+ public byte[] scanRecord;
+ public ArrayList decoded_scanRecord;
+ public int serviceUUID2p2;
+
+ public CsScanData(BluetoothDevice device, int rssi, byte[] scanRecord) {
+ this.device = device;
+ this.rssi = rssi;
+ this.scanRecord = scanRecord;
+ decoded_scanRecord = new ArrayList();
+ }
+ CsScanData(String name, String address, int rssi, byte[] scanRecord) {
+ this.device = device; this.name = name; this.address = address;
+ this.rssi = rssi;
+ this.scanRecord = scanRecord;
+ }
+ public BluetoothDevice getDevice() { return device; }
+ public String getName() {
+ return name;
+ }
+ public String getAddress() {
+ return address;
+ }
+ public byte[] getScanRecord() { return scanRecord; }
+ }
+
+ public void removeBond(ReaderDevice readerDevice) {
+ if (readerDevice == null) readerDevice = readerDeviceConnected;
+ if (readerDevice != null) {
+ BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
+ if (ActivityCompat.checkSelfPermission(context, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
+ appendToLog("BluetoothGatt.removeBond, Fragment: BLUETOOTH_CONNECT is not permitted");
+ // TODO: Consider calling
+ // ActivityCompat#requestPermissions
+ // here to request the missing permissions, and then overriding
+ // public void onRequestPermissionsResult(int requestCode, String[] permissions,
+ // int[] grantResults)
+ // to handle the case where the user grants the permission. See the documentation
+ // for ActivityCompat#requestPermissions for more details.
+ return;
+ }
+ Set bluetoothDevices = bluetoothAdapter.getBondedDevices();
+ appendToLog("BluetoothGatt.removeBond, Fragment: bluetoothDevices size = " + bluetoothDevices.size());
+ int i = 0;
+ for (BluetoothDevice bluetoothDevice : bluetoothDevices) {
+ appendToLog("BluetoothGatt.removeBond, Fragment: " + i + ", Address = " + bluetoothDevice.getAddress());
+ appendToLog("BluetoothGatt.removeBond, Fragment: readerDevice is " + (readerDevice == null ? "null" : "valid")
+ + ", bluetoothDevice is " + (bluetoothDevice == null ? "null" : "valid"));
+ if (readerDevice.getAddress().matches(bluetoothDevice.getAddress())) {
+ appendToLog("BluetoothGatt.removeBond, Fragment: matched address");
+ if (false) {
+ //bluetoothDevices.re
+ } else {
+ removeBond(bluetoothDevice);
+ }
+ appendToLog("BluetoothGatt.removeBond, Fragment: break");
+ break;
+ }
+ }
+ }
+ }
+
+ public void removeBond(BluetoothDevice bluetoothDevice) {
+ try {
+ if (true) {
+ //Method m = bluetoothDevice.getClass().getMethod("disconnect", (Class[]) null);
+ //m.invoke(bluetoothDevice, (Object[]) null);
+ Method m = bluetoothDevice.getClass().getMethod("removeBond", (Class[]) null);
+ m.invoke(bluetoothDevice, (Object[]) null);
+
+ appendToLog("BluetoothGatt.removeBond, Fragment: start to wait 2000ms");
+ Thread.sleep(1000); //1000 milliseconds is one second.
+ appendToLog("BluetoothGatt.removeBond, Fragment: end of timeout");
+ } else {
+ Method m = bluetoothDevice.getClass().getMethod("createBond", (Class[]) null);
+ m.invoke(bluetoothDevice, (Object[]) null);
+ }
+ } catch (Exception e) {
+ appendToLog("BluetoothGatt.removeBond, Fragment: exception " + e.toString());
+ e.printStackTrace();
+ }
+ }
+}
+
+
+
+package com.csl.cslibrary4a;
+
+public class ConnectorData {
+ public enum ConnectorTypes {
+ RFID, BARCODE, NOTIFICATION, SILICONLAB, BLUETOOTH, OTHER
+ }
+ public ConnectorTypes connectorTypes;
+ public byte[] dataValues;
+ public boolean invalidSequence;
+ public long milliseconds;
+}
+
+
+
+package com.csl.cslibrary4a;
+
+import android.content.Context;
+import android.widget.TextView;
+import android.widget.Toast;
+
+import java.util.ArrayList;
+
+public class ControllerConnector {
+ final boolean DEBUG = false;
+ boolean userDebugEnableDefault = false, userDebugEnable = userDebugEnableDefault;
+
+ Context context; Utility utility;
+ public ControllerConnector(Context context, Utility utility) {
+ this.context = context;
+ this.utility = utility;
+ }
+ private String byteArrayToString(byte[] packet) { return utility.byteArrayToString(packet); }
+ private boolean compareArray(byte[] array1, byte[] array2, int length) { return utility.compareByteArray(array1, array2, length); }
+ private void appendToLog(String s) { utility.appendToLog(s); }
+ private void appendToLogView(String s) { utility.appendToLogView(s); }
+
+ private int icsModel = -1;
+ int getCsModel() {
+ if (false) appendToLog("icsModel = " + icsModel);
+ return icsModel;
+ }
+
+ public enum ControllerPayloadEvents {
+ CONTROLLER_GET_VERSION, CONTROLLER_GET_SERIALNUMBER, CONTROLLER_GET_MODELNAME, CONTROLLER_RESET
+ }
+
+ class ControllerReadData {
+ ControllerPayloadEvents controllerPayloadEvents;
+ byte[] dataValues;
+ }
+
+ private byte[] controllerVersion = new byte[]{-1, -1, -1};
+
+ public String getVersion() {
+ boolean DEBUG = false;
+ if (controllerVersion[0] == -1) {
+ boolean repeatRequest = false;
+ if (controllerToWrite.size() != 0) {
+ if (controllerToWrite.get(controllerToWrite.size() - 1) == ControllerPayloadEvents.CONTROLLER_GET_VERSION) {
+ repeatRequest = true;
+ }
+ }
+ if (repeatRequest == false) {
+ controllerToWrite.add(ControllerPayloadEvents.CONTROLLER_GET_VERSION);
+ if (utility.DEBUG_PKDATA || DEBUG) appendToLog("PkData: add GET_VERSION to controllerWrite with length = " + controllerToWrite.size());
+ }
+ return "";
+ } else {
+ if (DEBUG) appendToLog("controllerVersion = " + byteArrayToString(controllerVersion));
+ String string = String.valueOf(controllerVersion[0]) + "." + String.valueOf(controllerVersion[1]) + "." + String.valueOf(controllerVersion[2]);
+ if (DEBUG) appendToLog("controllerVersion string = " + string);
+ return string;
+ }
+ }
+
+ private byte[] serialNumber = null;
+ public String getSerialNumber() {
+ if (serialNumber == null) {
+ boolean repeatRequest = false;
+ if (controllerToWrite.size() != 0) {
+ if (controllerToWrite.get(controllerToWrite.size() - 1) == ControllerPayloadEvents.CONTROLLER_GET_SERIALNUMBER) {
+ repeatRequest = true;
+ }
+ }
+ if (repeatRequest == false) {
+ controllerToWrite.add(ControllerPayloadEvents.CONTROLLER_GET_SERIALNUMBER);
+ if (utility.DEBUG_PKDATA) appendToLog("PkData: add GET_SERIALNUMBER to controllerToWrite with length = " + controllerToWrite.size());
+ }
+ return "";
+ } else {
+ byte[] bytes = new byte[serialNumber.length];
+ System.arraycopy(serialNumber, 0, bytes, 0, serialNumber.length);
+ if (bytes.length == 16) {
+ if (bytes[15] == 0) {
+ bytes[15] = serialNumber[14];
+ bytes[14] = serialNumber[13];
+ bytes[13] = 0;
+ }
+ for (int i = 13; i < 16; i++) {
+ if (bytes[i] == 0) bytes[i] = 0x30;
+ }
+ }
+ if (false) appendToLog("serialNumber = " + byteArrayToString(serialNumber) + ", revised = " + byteArrayToString(bytes));
+ String string = utility.byteArray2DisplayString(bytes);
+ if (string == null || string.length() == 0) {
+ string = byteArrayToString(bytes);
+ if (string.length() > 16) string = string.substring(0, 16);
+ }
+ if (false) appendToLog("string = " + string + " from serial " + byteArrayToString(serialNumber) + ", revised = " + byteArrayToString(bytes));
+ return string;
+ }
+ }
+
+ private byte[] modelName = null;
+ public String getModelName() {
+ if (false) appendToLog("modelName = " + byteArrayToString(modelName));
+ String strValue = null;
+ if (modelName == null) {
+ boolean repeatRequest = false;
+ if (controllerToWrite.size() != 0) {
+ if (controllerToWrite.get(controllerToWrite.size() - 1) == ControllerPayloadEvents.CONTROLLER_GET_MODELNAME) {
+ repeatRequest = true;
+ }
+ }
+ if (repeatRequest == false) {
+ controllerToWrite.add(ControllerPayloadEvents.CONTROLLER_GET_MODELNAME);
+ if (false) appendToLog("PkData: add GET_MODELNAME to controllerWrite with length = " + controllerToWrite.size());
+ }
+ } else {
+ strValue = utility.byteArray2DisplayString(modelName);
+ if (false) appendToLog("strValue 0 = " + strValue);
+ if (strValue == null || strValue.length() == 0) {
+ strValue = byteArrayToString(modelName).substring(0, 5);
+ }
+ }
+ if (false) appendToLog("strValue = " + strValue);
+ return strValue;
+ }
+
+ boolean resetSiliconLab() {
+ boolean bRetValue = false;
+ bRetValue = controllerToWrite.add(ControllerConnector.ControllerPayloadEvents.CONTROLLER_RESET);
+ appendToLog("add RESET to mSiliconLabIcWrite with length = " + controllerToWrite.size());
+ //mRfidDevice.setInventoring(false);
+ return bRetValue;
+ }
+
+ public ArrayList controllerToWrite = new ArrayList<>();
+
+ private boolean arrayTypeSet(byte[] dataBuf, int pos, ControllerPayloadEvents event) {
+ boolean validEvent = false;
+ switch (event) {
+ case CONTROLLER_GET_VERSION:
+ validEvent = true;
+ break;
+ case CONTROLLER_GET_SERIALNUMBER:
+ dataBuf[pos] = 4;
+ validEvent = true;
+ break;
+ case CONTROLLER_GET_MODELNAME:
+ dataBuf[pos] = 6;
+ validEvent = true;
+ break;
+ case CONTROLLER_RESET:
+ dataBuf[pos] = 12;
+ validEvent = true;
+ break;
+ }
+ return validEvent;
+ }
+
+ private byte[] writeController(ControllerPayloadEvents event, boolean usbConnection) {
+ boolean DEBUG = false;
+ byte[] dataOut = null;
+ if (event == ControllerPayloadEvents.CONTROLLER_GET_VERSION) {
+ dataOut = new byte[]{(byte) 0xA7, (byte) 0xB3, 2, (byte) 0xE8, (byte) 0x82, (byte) 0x37, 0, 0, (byte) 0xB0, 0};
+ } else if (event == ControllerPayloadEvents.CONTROLLER_GET_SERIALNUMBER) {
+ dataOut = new byte[]{(byte) 0xA7, (byte) 0xB3, 3, (byte) 0xE8, (byte) 0x82, (byte) 0x37, 0, 0, (byte) 0xB0, 4, 0};
+ } else if (event == ControllerPayloadEvents.CONTROLLER_GET_MODELNAME) {
+ dataOut = new byte[]{(byte) 0xA7, (byte) 0xB3, 2, (byte) 0xE8, (byte) 0x82, (byte) 0x37, 0, 0, (byte) 0xB0, 6};
+ } else if (event == ControllerPayloadEvents.CONTROLLER_RESET) {
+ dataOut = new byte[]{(byte) 0xA7, (byte) 0xB3, 2, (byte) 0xE8, (byte) 0x82, (byte) 0x37, 0, 0, (byte) 0xB0, 12};
+ }
+ if (usbConnection && dataOut != null) dataOut[1] = (byte) 0xE6;
+ if (DEBUG) appendToLog(byteArrayToString(dataOut) + " for " + event.toString());
+ return dataOut;
+ }
+
+ public boolean isMatchControllerToWrite(ConnectorData connectorData) {
+ boolean match = false;
+ if (controllerToWrite.size() != 0 && connectorData.dataValues[0] == (byte)0xB0) {
+ byte[] dataInCompare = new byte[]{(byte) 0xB0, 0};
+ if (arrayTypeSet(dataInCompare, 1, controllerToWrite.get(0)) && (connectorData.dataValues.length >= dataInCompare.length + 1)) {
+ if (match = compareArray(connectorData.dataValues, dataInCompare, dataInCompare.length)) {
+ if (utility.DEBUG_PKDATA) appendToLog("PkData: matched Controller.Reply with payload = " + byteArrayToString(connectorData.dataValues) + " for writeData.Controller." + controllerToWrite.get(0).toString());
+ if (controllerToWrite.get(0) == ControllerPayloadEvents.CONTROLLER_GET_VERSION) {
+ if (connectorData.dataValues.length >= 2 + controllerVersion.length) {
+ System.arraycopy(connectorData.dataValues, 2, controllerVersion, 0, controllerVersion.length);
+ if (utility.DEBUG_PKDATA) appendToLog("PkData: matched Controller.Reply.GetVersion with version = " + byteArrayToString(controllerVersion));
+ }
+ } else if (controllerToWrite.get(0) == ControllerPayloadEvents.CONTROLLER_GET_SERIALNUMBER) {
+ int length = connectorData.dataValues.length - 2;
+ serialNumber = new byte[length];
+ System.arraycopy(connectorData.dataValues, 2, serialNumber, 0, length);
+ if (utility.DEBUG_PKDATA) appendToLog("PkData: matched Controller.Reply.GetSerialNumber with serialNumber = " + byteArrayToString(serialNumber));
+ } else if (controllerToWrite.get(0) == ControllerPayloadEvents.CONTROLLER_GET_MODELNAME) {
+ int length = connectorData.dataValues.length - 2;
+ modelName = new byte[length];
+ System.arraycopy(connectorData.dataValues, 2, modelName, 0, length);
+ if (utility.DEBUG_PKDATA) appendToLog("PkData: matched controller.GetModelName.reply with modelName = " + byteArrayToString(modelName));
+ } else if (controllerToWrite.get(0) == ControllerPayloadEvents.CONTROLLER_RESET) {
+ if (connectorData.dataValues[2] != 0) {
+ appendToLog("Controller RESET is found with error");
+ } else appendToLog("matched Controller.reply data is found");
+ } else {
+ appendToLog("matched controller.Other.reply data is found.");
+ }
+ controllerToWrite.remove(0); sendDataToWriteSent = 0;
+ if (utility.DEBUG_PKDATA) appendToLog("PkData: new controllerToWrite size = " + controllerToWrite.size());
+
+ }
+ }
+ }
+ return match;
+ }
+
+ public int sendDataToWriteSent = 0;
+ boolean controllerFailure = false;
+ public byte[] sendControllerToWrite(boolean usbConnection) {
+ if (controllerFailure) {
+ controllerToWrite.remove(0); sendDataToWriteSent = 0;
+ } else if (sendDataToWriteSent >= 5) {
+ int oldSize = controllerToWrite.size();
+ controllerToWrite.remove(0); sendDataToWriteSent = 0;
+ if (DEBUG) appendToLog("Removed after sending count-out with oldSize = " + oldSize + ", updated controllerToWrite.size() = " + controllerToWrite.size());
+ if (DEBUG) appendToLog("Removed after sending count-out.");
+ String string = "Problem in sending data to Controller Module. Removed data sending after count-out";
+ if (userDebugEnable) Toast.makeText(context, string, Toast.LENGTH_SHORT).show();
+ else appendToLogView(string);
+ controllerFailure = true; // disconnect(false);
+ } else {
+ if (DEBUG) appendToLog("size = " + controllerToWrite.size());
+ sendDataToWriteSent++;
+ return writeController(controllerToWrite.get(0), usbConnection);
+ }
+ return null;
+ }
+}
+
+
+
+package com.csl.cslibrary4a;
+
+import android.bluetooth.BluetoothProfile;
+import android.content.Context;
+import android.os.Handler;
+import android.widget.TextView;
+
+import com.csl.cslibrary4a.RfidReader.RegionCodes;
+
+import java.io.File;
+import java.util.ArrayList;
+import java.util.List;
+
+public class Cs108Library4A {
+ final boolean DEBUG = false;
+ final boolean DEBUG_FILE = false;
+ private Handler mHandler = new Handler();
+
+ Context context;
+ CsReaderConnector csReaderConnector; Utility utility;
+ boolean DEBUG_CONNECT, DEBUG_SCAN;
+ BluetoothGatt bluetoothGatt;
+ BarcodeNewland barcodeNewland; BarcodeConnector barcodeConnector;
+ NotificationConnector notificationConnector;
+ ControllerConnector controllerConnector;
+ BluetoothConnector bluetoothConnector;
+ public Cs108Library4A(Context context, TextView mLogView) {
+ this.context = context;
+ utility = new Utility(context, mLogView);
+ csReaderConnector = new CsReaderConnector(context, mLogView, utility, true); csReaderConnector.setScanType(0x01);
+ bluetoothGatt = csReaderConnector.bluetoothGatt; DEBUG_CONNECT = utility.DEBUG_CONNECT; DEBUG_SCAN = utility.DEBUG_SCAN;
+/*
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
+ mScanCallback = new ScanCallback() {
+ @Override
+ public void onBatchScanResults(List results) {
+ if (DEBUG) appendToLog("onBatchScanResults()");
+ }
+
+ @Override
+ public void onScanFailed(int errorCode) {
+ if (DEBUG) appendToLog("onScanFailed()");
+ }
+
+ @Override
+ public void onScanResult(int callbackType, ScanResult result) {
+ boolean DEBUG = false;
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
+ BluetoothGatt.CsScanData scanResultA = new BluetoothGatt.CsScanData(result.getDevice(), result.getRssi(), result.getScanRecord().getBytes());
+ boolean found98 = true;
+ if (true) found98 = check9800(scanResultA);
+ if (DEBUG) appendToLog("found98 = " + found98 + ", mScanResultList 0 = " + (mScanResultList != null ? "VALID" : "NULL"));
+ if (mScanResultList != null && found98) {
+ scanResultA.serviceUUID2p2 = check9800_serviceUUID2p1;
+ mScanResultList.add(scanResultA);
+ if (DEBUG) appendToLog("mScanResultList 0 = " + mScanResultList.size());
+ }
+ }
+ }
+ };
+ } else {
+ mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
+ @Override
+ public void onLeScan(final BluetoothDevice device, final int rssi, final byte[] scanRecord) {
+ if (true) appendToLog("onLeScan()");
+ BluetoothGatt.CsScanData scanResultA = new BluetoothGatt.CsScanData(device, rssi, scanRecord);
+ boolean found98 = true;
+ if (true) found98 = check9800(scanResultA);
+ appendToLog("found98 = " + found98 + ", mScanResultList 1 = " + (mScanResultList != null ? "VALID" : "NULL"));
+ if (mScanResultList != null && found98) {
+ scanResultA.serviceUUID2p2 = check9800_serviceUUID2p1;
+ mScanResultList.add(scanResultA);
+ appendToLog("mScanResultList 1 = " + mScanResultList.size());
+ }
+ }
+ };
+ }
+*/
+ File path = context.getFilesDir();
+ File[] fileArray = path.listFiles();
+ boolean deleteFiles = false;
+ if (true || DEBUG)
+ appendToLog("Number of file in data storage sub-directory = " + fileArray.length);
+ boolean bProfileInstalledFound = false;
+ for (int i = 0; i < fileArray.length; i++) {
+ String fileName = fileArray[i].toString();
+ if (true) appendToLog("Stored file (" + i + ") = " + fileName);
+ if (fileName.contains("profileInstalled") || fileName.contains("profileinstaller")) {
+ bProfileInstalledFound = true;
+ appendToLog("Found profileInstalled or profileinstaller file");
+ }
+ File file = new File(fileName);
+ if (deleteFiles) file.delete();
+ }
+ if (!bProfileInstalledFound) {
+ for (int i = 0; i < fileArray.length; i++) {
+ String fileName = fileArray[i].toString();
+ File file = new File(fileName);
+ file.delete();
+ appendToLog("Deleted " + fileName);
+ }
+ }
+ }
+ public String getlibraryVersion() {
+ String version = BuildConfig.VERSION_NAME;
+ //int iVersion = Integer.parseInt(version) + 10;
+ version = "15.0"; //+ String.valueOf(iVersion);
+ appendToLog("version = " + version);
+ return utility.getCombinedVersion(version);
+ }
+ public String checkVersion() {
+ return csReaderConnector.checkVersion();
+ }
+
+ //============ utility ============
+ public String byteArrayToString(byte[] packet) {
+ return utility.byteArrayToString(packet);
+ }
+ public void appendToLog(String s) {
+ utility.appendToLog(s);
+ }
+ public void appendToLogView(String s) {
+ utility.appendToLogView(s);
+ }
+ public String strFloat16toFloat32(String strData) {
+ return utility.strFloat16toFloat32(strData);
+ }
+ public String str2float16(String strData) {
+ return utility.str2float16(strData);
+ }
+ public float decodeCtesiusTemperature(String strActData, String strCalData) {
+ return utility.decodeCtesiusTemperature(strActData, strCalData);
+ }
+ public float decodeMicronTemperature(int iTag35, String strActData, String strCalData) {
+ return utility.decodeMicronTemperature(iTag35, strActData, strCalData);
+ }
+ public float decodeAsygnTemperature(String string) {
+ return utility.decodeAsygnTemperature(string);
+ }
+ public String temperatureC2F(String strValue) {
+ return utility.temperatureC2F(strValue);
+ }
+ public String temperatureF2C(String strValue) {
+ return utility.temperatureF2C(strValue);
+ }
+ public String getUpcSerial(String strEpc) {
+ return utility.getUpcSerial(strEpc);
+ }
+ public String getUpcSerialDetail(String strUpcSerial) {
+ return utility.getUpcSerialDetail(strUpcSerial);
+ }
+ public String getEpc4upcSerial(Utility.EpcClass epcClass, String filter, String companyPrefix, String itemReference, String serialNumber) {
+ return utility.getEpc4upcSerial(epcClass, filter, companyPrefix, itemReference, serialNumber);
+ }
+ public boolean checkHostProcessorVersion(String version, int majorVersion, int minorVersion, int buildVersion) {
+ return utility.checkHostProcessorVersion(version, majorVersion, minorVersion, buildVersion);
+ }
+
+ //============ android bluetooth ============
+ ArrayList mScanResultList = new ArrayList<>();
+ int check9800_serviceUUID2p1 = 0;
+ boolean bleConnection = false;
+ ReaderDevice readerDeviceConnect;
+ boolean bNeedReconnect = false;
+ int iConnectStateTimer = 0;
+/*
+ boolean check9800(BluetoothGatt.CsScanData scanResultA) {
+ boolean found98 = false, DEBUG = false;
+ if (DEBUG) appendToLog("decoded data size = " + scanResultA.decoded_scanRecord.size());
+ int iNewADLength = 0;
+ byte[] newAD = new byte[0];
+ int iNewADIndex = 0;
+ check9800_serviceUUID2p1 = -1;
+ if (bluetoothGatt.isBLUETOOTH_CONNECTinvalid()) return true;
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S && ActivityCompat.checkSelfPermission(context, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED)
+ return true;
+ String strTemp = scanResultA.getDevice().getName();
+ if (strTemp != null && DEBUG)
+ appendToLog("Found name = " + strTemp + ", length = " + String.valueOf(strTemp.length()));
+ for (byte bdata : scanResultA.getScanRecord()) {
+ if (iNewADIndex >= iNewADLength && iNewADLength != 0) {
+ scanResultA.decoded_scanRecord.add(newAD);
+ iNewADIndex = 0;
+ iNewADLength = 0;
+ if (DEBUG)
+ appendToLog("Size = " + scanResultA.decoded_scanRecord.size() + ", " + byteArrayToString(newAD));
+ }
+ if (iNewADLength == 0) {
+ iNewADLength = bdata;
+ newAD = new byte[iNewADLength];
+ iNewADIndex = 0;
+ } else newAD[iNewADIndex++] = bdata;
+ }
+ if (DEBUG) appendToLog("decoded data size = " + scanResultA.decoded_scanRecord.size());
+ for (int i = 0; i < scanResultA.decoded_scanRecord.size(); i++) {
+ byte[] currentAD = scanResultA.decoded_scanRecord.get(i);
+ if (DEBUG) appendToLog("Processing decoded data = " + byteArrayToString(currentAD));
+ if (currentAD[0] == 2) {
+ if (DEBUG) appendToLog("Processing UUIDs");
+ if ((currentAD[1] == 0) && currentAD[2] == (byte) 0x98) {
+ if (DEBUG) appendToLog("Found 9800");
+ found98 = true;
+ check9800_serviceUUID2p1 = currentAD[1];
+ if (DEBUG) appendToLog("serviceUD1D2p1 = " + check9800_serviceUUID2p1);
+ break;
+ }
+ }
+ }
+ if (found98 == false && DEBUG)
+ appendToLog("No 9800: with scanData = " + byteArrayToString(scanResultA.getScanRecord()));
+ else if (DEBUG_SCAN)
+ appendToLog("Cs108Library4A, Found 9800: with scanData = " + byteArrayToString(scanResultA.getScanRecord()));
+ return found98;
+ }
+*/
+ boolean connect1(ReaderDevice readerDevice) {
+ boolean DEBUG = true;
+ if (DEBUG || DEBUG_CONNECT)
+ appendToLog("Debug_Connect, Cs108Library4A.Connect1: with " + (readerDevice == null ? "null" : "valid") + " readerDevice, " + (readerDeviceConnect == null ? "null" : "valid" + "readerDeviceConnect"));
+ if (readerDevice == null && readerDeviceConnect != null) readerDevice = readerDeviceConnect;
+ boolean result = false;
+ if (readerDevice != null) {
+ bNeedReconnect = false;
+ iConnectStateTimer = 0;
+ bluetoothGatt.bDiscoverStarted = false;
+ bluetoothGatt.setServiceUUIDType(readerDevice.getServiceUUID2p1());
+ appendToLog("Cs108Library4A.connect1 is going to connect");
+ result = csReaderConnector.connect(readerDevice);
+ }
+ if (DEBUG || DEBUG_CONNECT) appendToLog("Debug_Connect, Cs108Library4A.connect1: Result = " + result);
+ return result;
+ }
+ final Runnable connectRunnable = new Runnable() {
+ boolean DEBUG = true;
+
+ @Override
+ public void run() {
+ if (DEBUG || DEBUG_CONNECT) {
+ appendToLog("Debug_Connect, Cs108Library4A.connectRunnable: isBleScanning = " + isBleScanning());
+ appendToLog("Debug_Connect, Cs108Library4A.connectRunnable: bNeedReconnect = " + bNeedReconnect);
+ appendToLog("Debug_Connect, Cs108Library4A.connectRunnable: deviceFinderConnectState = " + csReaderConnector.deviceFinder.deviceFinderConnectState);
+ appendToLog("Debug_Connect, Cs108Library4A.connectRunnable: bluetoothConnectionState = " + bluetoothGatt.bluetoothConnectionState) ;
+ }
+ if (isBleScanning()) {
+ if (DEBUG) appendToLog("Cs108Library4A.connectRunnable: still scanning. Stop scanning first");
+ scanLeDevice(false);
+ } else if (bNeedReconnect) {
+ if (bluetoothGatt.bluetoothGatt != null) {
+ if (DEBUG) appendToLog("Cs108Library4A.connectRunnable: mBluetoothGatt is null before connect. disconnect first");
+ csReaderConnector.disconnect();
+ } else if (readerDeviceConnect == null) {
+ if (DEBUG) appendToLog("Cs108Library4A.connectRunnable: exit with null readerDeviceConnect");
+ return;
+ } else if (bluetoothGatt.bluetoothGatt == null) {
+ if (DEBUG || DEBUG_CONNECT) appendToLog("Debug_Connect, Cs108Library4A.connectRunnable: connect1 starts");
+ connect1(null);
+ bNeedReconnect = false;
+ }
+ } else if (csReaderConnector.deviceFinder.deviceFinderConnectState) return;
+ else if (bluetoothGatt.bluetoothConnectionState == BluetoothProfile.STATE_DISCONNECTED) { //mReaderStreamOutCharacteristic valid around 1500ms
+ iConnectStateTimer = 0;
+ if (DEBUG)
+ appendToLog("Cs108Library4A.connectRunnable: disconnect as disconnected connectionState is received");
+ bNeedReconnect = true;
+ //if (true || bluetoothGatt.bluetoothGatt != null) {
+ //if (DEBUG) appendToLog("Cs108Library4A.connectRunnable: disconnect F");
+ csReaderConnector.disconnect();
+ //}
+ } else if (bluetoothGatt.mReaderStreamOutCharacteristic == null) {
+ if (DEBUG_CONNECT)
+ appendToLog("Debug_Connect, Cs108Library4A.connectRunnable: wait as not yet discovery, with iConnectStateTimer = " + iConnectStateTimer);
+ if (++iConnectStateTimer > 10) {
+ }
+ } else {
+ if (DEBUG_CONNECT) appendToLog("Debug_Connect, Cs108Library4A.connectRunnable: end of ConnectRunnable");
+ return;
+ }
+ mHandler.postDelayed(connectRunnable, 500);
+ }
+ };
+ final Runnable disconnectRunnable = new Runnable() {
+ @Override
+ public void run() {
+ if (barcodeConnector == null) return;
+ appendToLog("abcc disconnectRunnable with barcodeToWrite.size = " + barcodeConnector.barcodeToWrite.size());
+ if (barcodeConnector.barcodeToWrite.size() != 0)
+ mHandler.postDelayed(disconnectRunnable, 100);
+ else {
+ appendToLog("disconnect G");
+ csReaderConnector.disconnect();
+ }
+ }
+ };
+ public boolean isBleScanning() {
+ return bluetoothGatt.isScanning();
+ }
+ public boolean scanLeDevice(boolean enable) {
+ boolean DEBUG = true;
+ if (enable) mHandler.removeCallbacks(connectRunnable);
+
+ if (DEBUG || DEBUG_SCAN) appendToLog("Cs108Library.scanLeDevice[" + enable + "]");
+ if (bluetoothGatt.bluetoothDeviceConnectOld != null) {
+ if (DEBUG) appendToLog("Cs108Library.scanLeDevice: bluetoothDeviceConnectOld connection state = " + bluetoothGatt.bluetoothManager.getConnectionState(bluetoothGatt.bluetoothDeviceConnectOld, BluetoothProfile.GATT));
+ }
+ if (enable && csReaderConnector.deviceFinder != null) csReaderConnector.deviceFinder.scanDevice(enable);
+ boolean bValue = bluetoothGatt.scanDevice(enable, csReaderConnector.mLeScanCallback, csReaderConnector.mScanCallback);
+ if (DEBUG || DEBUG_SCAN) appendToLog("Cs108Library.scanLeDevice: isScanning = " + isBleScanning());
+ return bValue;
+ }
+ public BluetoothGatt.CsScanData getNewDeviceScanned() {
+ return csReaderConnector.getNewDeviceScanned();
+/*
+ if (mScanResultList.size() != 0) {
+ if (DEBUG_SCAN) appendToLog("mScanResultList.size() = " + mScanResultList.size());
+ BluetoothGatt.CsScanData csScanData = mScanResultList.get(0); mScanResultList.remove(0);
+ return csScanData;
+ } else return null;
+*/
+ }
+ public String getBluetoothDeviceAddress() {
+ if (bluetoothGatt.getReaderDeviceConnected() == null) return null;
+ return bluetoothGatt.getReaderDeviceConnected().getAddress();
+ }
+ public String getBluetoothDeviceName() {
+ if (bluetoothGatt.getReaderDeviceConnected() == null) return null;
+ return bluetoothGatt.getReaderDeviceConnected().getName();
+ }
+ public boolean isBleConnected() {
+ boolean DEBUG = true;
+ boolean bleConnectionNew = csReaderConnector.isConnected();
+ if (DEBUG) appendToLog("Cs108Library4A.isBleConnected: bleConnectionNew = " + bleConnectionNew);
+ if (bleConnectionNew) {
+ if (bleConnection == false) {
+ bleConnection = bleConnectionNew;
+ if (DEBUG || DEBUG_CONNECT) appendToLog("Debug_Connect, Cs108Library4A.isBleConnected: Newly connected");
+
+ csReaderConnector.csConnectorDataInit();
+ barcodeNewland = csReaderConnector.barcodeNewland;
+ barcodeConnector = csReaderConnector.barcodeConnector;
+ notificationConnector = csReaderConnector.notificationConnector;
+ controllerConnector = csReaderConnector.controllerConnector;
+ bluetoothConnector = csReaderConnector.bluetoothConnector;
+
+ setRfidOn(true);
+ setBarcodeOn(true);
+ hostProcessorICGetFirmwareVersion();
+ getBluetoothICFirmwareVersion();
+ csReaderConnector.rfidReader.channelOrderType = -1;
+ {
+ // getBarcodePreSuffix();
+ // getBarcodeReadingMode();
+ // getBarcodeSerial();
+ //getBarcodeNoDuplicateReading();
+ //getBarcodeDelayTimeOfEachReading();
+ //getBarcodeEnable2dBarCodes();
+ //getBarcodePrefixOrder();
+ //getBarcodeVersion();
+ //barcodeSendCommandLoadUserDefault();
+ //barcodeSendQuerySystem();
+ // barcodeNewland.barcodeSendCommandItf14Cksum();
+
+ notificationConnector.setBatteryAutoReport(true); //0xA003
+ }
+ //abortOperation();
+ //getHostProcessorICSerialNumber(); //0xb004 (but access Oem as bluetooth version is not got)
+ getMacVer();
+ if (false) { //following two instructions seems not used
+ int iValue = csReaderConnector.rfidReader.getDiagnosticConfiguration();
+ if (DEBUG) appendToLog("Cs108Library4A.isBleConnected: diagnostic data = " + iValue);
+ macWrite(0xC08, 0x100);
+ }
+ csReaderConnector.rfidReader.regionCode = null;
+ getModelNumber();
+ getCountryCode();
+ {
+ getFreqModifyCode();
+ csReaderConnector.rfidReader.getSpecialCountryVersion();
+ }
+ //getSerialNumber();
+ getQueryTarget();
+ csReaderConnector.rfidReader.getImpinjExtension();
+ csReaderConnector.rfidReader.getInvAlgoInChip();
+ csReaderConnector.rfidReader.getFreqChannelConfig();
+ if (DEBUG_CONNECT || DEBUG) appendToLog("Debug_Connect, Cs108Library4A.isBleConnected: Start checkVersionRunnable");
+ mHandler.postDelayed(checkVersionRunnable, 500);
+
+ if (csReaderConnector.settingData.strForegroundReader.trim().length() != 0) {
+ csReaderConnector.settingData.strForegroundReader = bluetoothGatt.getReaderDeviceConnected().getAddress();
+ }
+ csReaderConnector.settingData.saveForegroundSetting2File();
+ } else if (csReaderConnector.rfidReader == null) {
+ bleConnection = false;
+ appendToLog("Cs108Library4A.isBleConnnected: csReaderConnector.rfidReader is NULL");
+ } else if (csReaderConnector.rfidReader.bFirmware_reset_before) {
+ csReaderConnector.rfidReader.bFirmware_reset_before = false;
+ mHandler.postDelayed(reinitaliseDataRunnable, 500);
+ }
+ } else if (bleConnection) {
+ barcodeNewland = null; barcodeConnector = null;
+ notificationConnector = null;
+ controllerConnector = null;
+ bluetoothConnector = null;
+ bleConnection = bleConnectionNew;
+ if (DEBUG) appendToLog("Cs108Library4A.isBleConnnected: Newly disconnected");
+ }
+ return(bleConnection);
+ }
+ public void connect(ReaderDevice readerDevice) {
+ if (isBleConnected()) return;
+ if (bluetoothGatt.bluetoothGatt != null) csReaderConnector.disconnect();
+ if (readerDevice != null) readerDeviceConnect = readerDevice;
+ mHandler.removeCallbacks(connectRunnable);
+ bNeedReconnect = true; mHandler.post(connectRunnable);
+ if (true || DEBUG_CONNECT) appendToLog("Debug_Connect: Cs108Library4A.connect Start ConnectRunnable");
+ }
+ public void disconnect(boolean tempDisconnect) {
+ appendToLog("abcc tempDisconnect: getBarcodeOnStatus = " + (getBarcodeOnStatus() ? "on" : "off"));
+ if (DEBUG) appendToLog("tempDisconnect = " + tempDisconnect);
+ mHandler.removeCallbacks(checkVersionRunnable);
+ mHandler.removeCallbacks(runnableToggleConnection);
+ if (getBarcodeOnStatus()) {
+ appendToLog("tempDisconnect: setBarcodeOn(false)");
+ if (barcodeConnector.barcodeToWrite.size() != 0) {
+ appendToLog("going to disconnectRunnable with remaining barcodeToWrite.size = " + barcodeConnector.barcodeToWrite.size() + ", data = " + byteArrayToString(barcodeConnector.barcodeToWrite.get(0).dataValues));
+ }
+ barcodeConnector.barcodeToWrite.clear(); appendToLog("barcodeToWrite is clear");
+ setBarcodeOn(false);
+ setRfidOn(false);
+ } else appendToLog("tempDisconnect: getBarcodeOnStatus is false");
+ mHandler.postDelayed(disconnectRunnable, 100);
+ appendToLog("done with tempDisconnect = " + tempDisconnect);
+ if (tempDisconnect == false) {
+ mHandler.removeCallbacks(connectRunnable);
+ bluetoothGatt.bluetoothDeviceConnectOld = null;
+ if (readerDeviceConnect != null) bluetoothGatt.bluetoothDeviceConnectOld = bluetoothGatt.bluetoothAdapter.getRemoteDevice(readerDeviceConnect.getAddress());
+ readerDeviceConnect = null;
+ }
+ }
+ public boolean forceBTdisconnect() {
+ return bluetoothConnector.forceBTdisconnect();
+ }
+ public int getRssi() {
+ return bluetoothGatt.getRssi();
+ }
+ boolean getConnectionHSpeed() {
+ return bluetoothGatt.getConnectionHSpeedA();
+ }
+ boolean setConnectionHSpeed(boolean on) {
+ return bluetoothGatt.setConnectionHSpeedA(on);
+ }
+ public long getStreamInRate() {
+ return csReaderConnector.getStreamInRate();
+ }
+ public int get98XX() {
+ return 0;
+ }
+
+ //============ Rfid ============
+ //============ Rfid ============
+ //============ Rfid ============
+
+ boolean setInvAlgoNoSave(boolean dynamicAlgo) {
+ return csReaderConnector.rfidReader.setInvAlgoNoSave(dynamicAlgo);
+ }
+ boolean setInvAlgo1(boolean dynamicAlgo) {
+ return csReaderConnector.rfidReader.setInvAlgo1(dynamicAlgo);
+ }
+ public String getAuthMatchData() {
+ return csReaderConnector.rfidReader.getAuthMatchData();
+ }
+ public boolean setAuthMatchData(String mask) {
+ return csReaderConnector.rfidReader.setAuthMatchData(mask);
+ }
+ public int getStartQValue() {
+ return csReaderConnector.rfidReader.getStartQValue();
+ }
+ public int getMaxQValue() {
+ return csReaderConnector.rfidReader.getMaxQValue();
+ }
+ public int getMinQValue() {
+ return csReaderConnector.rfidReader.getMinQValue();
+ }
+ public boolean setDynamicQParms(int startQValue, int minQValue, int maxQValue, int retryCount) {
+ return csReaderConnector.rfidReader.setDynamicQParms(startQValue, minQValue, maxQValue, retryCount);
+ }
+ public int getFixedQValue() {
+ return csReaderConnector.rfidReader.getFixedQValue();
+ }
+ public int getFixedRetryCount() {
+ return csReaderConnector.rfidReader.getFixedRetryCount();
+ }
+ public boolean getRepeatUnitNoTags() {
+ return csReaderConnector.rfidReader.getRepeatUnitNoTags();
+ }
+ public boolean setFixedQParms(int qValue, int retryCount, boolean repeatUnitNoTags) {
+ return csReaderConnector.rfidReader.setFixedQParms(qValue, retryCount, repeatUnitNoTags);
+ }
+ RegionCodes[] getRegionList() {
+ return csReaderConnector.rfidReader.getRegionList();
+ }
+ boolean toggledConnection = false;
+ Runnable runnableToggleConnection = new Runnable() {
+ boolean DEBUG = true;
+ @Override
+ public void run() {
+ if (DEBUG) appendToLog("Cs108Library4A.runnableToggleConnection: toggledConnection = " + toggledConnection + ", isBleConnected() = " + isBleConnected());
+ if (isBleConnected() == false) toggledConnection = true;
+ if (toggledConnection) {
+ if (isBleConnected() == false) {
+ if (connect1(null) == false) return;
+ } else return;
+ } else { appendToLog("Cs108Library4A.runnableToggleConnection: disconnect H"); csReaderConnector.disconnect(); appendToLog("done"); }
+ mHandler.postDelayed(runnableToggleConnection, 500);
+ }
+ };
+ public boolean getChannelHoppingDefault() {
+ return csReaderConnector.rfidReader.getChannelHoppingDefault();
+ }
+ int getCountryCode() {
+ return csReaderConnector.rfidReader.getCountryCode();
+ }
+ int getFreqModifyCode() {
+ return csReaderConnector.rfidReader.getFreqModifyCode();
+ }
+ public boolean getRfidOnStatus() {
+ return csReaderConnector.rfidReader.getRfidOnStatus();
+ }
+ public boolean isRfidFailure() {
+ //appendToLog("BtDataOut: isRfidFailure rfidReader is " + (csReaderConnector.rfidReader == null ? "null" : csReaderConnector.rfidReader.isRfidFailure()));
+ if (csReaderConnector.rfidReader == null) return false;
+ return csReaderConnector.rfidReader.isRfidFailure();
+ }
+ public void setReaderDefault() {
+ csReaderConnector.rfidReader.setReaderDefault();
+ String string = bluetoothGatt.getReaderDeviceConnected().getAddress();
+ string = string.replaceAll("[^a-zA-Z0-9]","");
+ string = string.substring(string.length()-6, string.length());
+ setBluetoothICFirmwareName("CS108Reader" + string);
+ //getlibraryVersion()
+ if (false) {
+ setCountryInList(csReaderConnector.rfidReader.countryInListDefault);
+ setChannel(0);
+
+ //getAntennaPower(0)
+ //getPopulation()
+ //getQuerySession()
+ //getQueryTarget()
+ setTagFocus(false);
+ setFastId(false);
+ //getInvAlgo()
+ //\\getRetryCount()
+ //getCurrentProfile() + "\n"));
+ //\\getRxGain() + "\n"));
+ }
+ //getBluetoothICFirmwareName() + "\n");
+ setTagDelay(csReaderConnector.rfidReader.tagDelaySettingDefault);
+ setCycleDelay((long)0);
+ setIntraPkDelay((byte)4);
+ setDupDelay((byte)0);
+
+ setBatteryDisplaySetting(csReaderConnector.settingData.batteryDisplaySelectDefault);
+ setRssiDisplaySetting(csReaderConnector.settingData.rssiDisplaySelectDefault);
+ setTriggerReporting(csReaderConnector.settingData.triggerReportingDefault);
+ setTriggerReportingCount(csReaderConnector.settingData.triggerReportingCountSettingDefault);
+ setInventoryBeep(csReaderConnector.settingData.inventoryBeepDefault);
+ setBeepCount(csReaderConnector.settingData.beepCountSettingDefault);
+ setInventoryVibrate(csReaderConnector.settingData.inventoryVibrateDefault);
+ setVibrateTime(csReaderConnector.settingData.vibrateTimeSettingDefault);
+ setVibrateModeSetting(csReaderConnector.settingData.vibrateModeSelectDefault);
+ setVibrateWindow(csReaderConnector.settingData.vibrateWindowSettingDefault);
+
+ setSavingFormatSetting(csReaderConnector.settingData.savingFormatSelectDefault);
+ setCsvColumnSelectSetting(csReaderConnector.settingData.csvColumnSelectDefault);
+ setSaveFileEnable(csReaderConnector.settingData.saveFileEnableDefault);
+ setSaveCloudEnable(csReaderConnector.settingData.saveCloudEnableDefault);
+ setSaveNewCloudEnable(csReaderConnector.settingData.saveNewCloudEnableDefault);
+ setSaveAllCloudEnable(csReaderConnector.settingData.saveAllCloudEnableDefault);
+ setServerLocation(csReaderConnector.settingData.serverLocationDefault);
+ setServerTimeout(csReaderConnector.settingData.serverTimeoutDefault);
+ csReaderConnector.settingData.barcode2TriggerMode = csReaderConnector.settingData.barcode2TriggerModeDefault;
+
+ setUserDebugEnable(csReaderConnector.settingData.userDebugEnableDefault);
+ csReaderConnector.settingData.preFilterData = null;
+ }
+ public String getMacVer() {
+ appendToLog("Cs108Library4A.getMacVer");
+ return csReaderConnector.rfidReader.getMacVer();
+ }
+ public String getRadioSerial() {
+ return csReaderConnector.rfidReader.getRadioSerial();
+ }
+ public String getRadioBoardVersion() {
+ return csReaderConnector.rfidReader.getRadioBoardVersion();
+ }
+ public int getPortNumber() {
+ if (bluetoothConnector.getCsModel() == 463) return 4;
+ else return 1;
+ }
+ public int getAntennaSelect() {
+ return csReaderConnector.rfidReader.getAntennaSelect();
+ }
+ public boolean setAntennaSelect(int number) {
+ return csReaderConnector.rfidReader.setAntennaSelect(number);
+ }
+ public boolean getAntennaEnable() {
+ return csReaderConnector.rfidReader.getAntennaEnable();
+ }
+ public boolean setAntennaEnable(boolean enable) {
+ return csReaderConnector.rfidReader.setAntennaEnable(enable);
+ }
+ public long getAntennaDwell() {
+ return csReaderConnector.rfidReader.getAntennaDwell();
+ }
+ public boolean setAntennaDwell(long antennaDwell) {
+ return csReaderConnector.rfidReader.setAntennaDwell(antennaDwell);
+ }
+ public long getPwrlevel() {
+ return csReaderConnector.rfidReader.getPwrlevel();
+ }
+ public boolean setPowerLevel(long pwrlevel) {
+ return csReaderConnector.rfidReader.setPowerLevel(pwrlevel);
+ }
+ public int getQueryTarget() {
+ return csReaderConnector.rfidReader.getQueryTarget();
+ }
+ public int getQuerySession() {
+ return csReaderConnector.rfidReader.getQuerySession();
+ }
+ public int getQuerySelect() {
+ return csReaderConnector.rfidReader.getQuerySelect();
+ }
+ public boolean setTagGroup(int sL, int session, int target1) {
+ return csReaderConnector.rfidReader.setTagGroup(sL, session, target1);
+ }
+ public int getTagFocus() {
+ return csReaderConnector.rfidReader.getTagFocus();
+ }
+ public boolean setTagFocus(boolean tagFocusNew) {
+ return csReaderConnector.rfidReader.setTagFocus(tagFocusNew);
+ }
+ public int getFastId() {
+ return csReaderConnector.rfidReader.getFastId();
+ }
+ public boolean setFastId(boolean fastIdNew) {
+ appendToLog("bFastId: setFastId[" + fastIdNew);
+ return csReaderConnector.rfidReader.setFastId(fastIdNew);
+ }
+ public boolean getInvAlgo() {
+ return csReaderConnector.rfidReader.getInvAlgo();
+ }
+ public boolean setInvAlgo(boolean dynamicAlgo) {
+ return csReaderConnector.rfidReader.setInvAlgo(dynamicAlgo);
+ }
+ public List getProfileList() {
+ return csReaderConnector.rfidReader.getProfileList();
+ }
+ public int getCurrentProfile() {
+ return csReaderConnector.rfidReader.getCurrentProfile();
+ }
+ public boolean setBasicCurrentLinkProfile() {
+ return csReaderConnector.rfidReader.setBasicCurrentLinkProfile();
+ }
+ public boolean setCurrentLinkProfile(int profile) {
+ return csReaderConnector.rfidReader.setCurrentLinkProfile(profile);
+ }
+ public void resetEnvironmentalRSSI() {
+ csReaderConnector.rfidReader.resetEnvironmentalRSSI();
+ }
+ public String getEnvironmentalRSSI() {
+ return csReaderConnector.rfidReader.getEnvironmentalRSSI();
+ }
+ public int getHighCompression() {
+ return csReaderConnector.rfidReader.getHighCompression();
+ }
+ public int getRflnaGain() {
+ return csReaderConnector.rfidReader.getRflnaGain();
+ }
+ public int getIflnaGain() {
+ return csReaderConnector.rfidReader.getIflnaGain();
+ }
+ public int getAgcGain() {
+ return csReaderConnector.rfidReader.getAgcGain();
+ }
+ public int getRxGain() {
+ return csReaderConnector.rfidReader.getRxGain();
+ }
+ public boolean setRxGain(int highCompression, int rflnagain, int iflnagain, int agcgain) {
+ return csReaderConnector.rfidReader.setRxGain(highCompression, rflnagain, iflnagain, agcgain);
+ }
+ public boolean setRxGain(int rxGain) {
+ return csReaderConnector.rfidReader.setRxGain(rxGain);
+ }
+ public int FreqChnCnt() {
+ return csReaderConnector.rfidReader.FreqChnCnt(csReaderConnector.rfidReader.regionCode);
+ }
+ public double getLogicalChannel2PhysicalFreq(int channel) {
+ return csReaderConnector.rfidReader.getLogicalChannel2PhysicalFreq(channel);
+ }
+ public byte getTagDelay() {
+ return csReaderConnector.rfidReader.getTagDelay();
+ }
+ public boolean setTagDelay(byte tagDelay) {
+ return csReaderConnector.rfidReader.setTagDelay(tagDelay);
+ }
+ public byte getIntraPkDelay() {
+ return csReaderConnector.rfidReader.getIntraPkDelay();
+ }
+ public boolean setIntraPkDelay(byte intraPkDelay) {
+ return csReaderConnector.rfidReader.setIntraPkDelay(intraPkDelay);
+ }
+ public byte getDupDelay() {
+ return csReaderConnector.rfidReader.getDupDelay();
+ }
+ public boolean setDupDelay(byte dupElim) {
+ return csReaderConnector.rfidReader.setDupDelay(dupElim);
+ }
+ public long getCycleDelay() {
+ return csReaderConnector.rfidReader.getCycleDelay();
+ }
+ public boolean setCycleDelay(long cycleDelay) {
+ return csReaderConnector.rfidReader.setCycleDelay(cycleDelay);
+ }
+ public void getAuthenticateReplyLength() {
+ csReaderConnector.rfidReader.getAuthenticateReplyLength();
+ }
+ public boolean setTamConfiguration(boolean header, String matchData) {
+ return csReaderConnector.rfidReader.setTamConfiguration(header, matchData);
+ }
+ public boolean setTam1Configuration(int keyId, String matchData) {
+ return csReaderConnector.rfidReader.setTam1Configuration(keyId, matchData);
+ }
+ public boolean setTam2Configuration(int keyId, String matchData, int profile, int offset, int blockId, int protMode) {
+ return csReaderConnector.rfidReader.setTam2Configuration(keyId, matchData, profile, offset, blockId, protMode);
+ }
+ public int getUntraceableEpcLength() {
+ return csReaderConnector.rfidReader.getUntraceableEpcLength();
+ }
+ public boolean setUntraceable(boolean bHideEpc, int ishowEpcSize, int iHideTid, boolean bHideUser, boolean bHideRange) {
+ return csReaderConnector.rfidReader.setUntraceable(bHideEpc, ishowEpcSize, iHideTid, bHideUser, bHideRange);
+ }
+ public boolean setUntraceable(int range, boolean user, int tid, int epcLength, boolean epc, boolean uxpc) {
+ return csReaderConnector.rfidReader.setUntraceable(range, user, tid, epcLength, epc, uxpc);
+ }
+ public boolean setAuthenticateConfiguration() {
+ return csReaderConnector.rfidReader.setAuthenticateConfiguration();
+ }
+ public int getRetryCount() {
+ return csReaderConnector.rfidReader.getRetryCount();
+ }
+ public boolean setRetryCount(int retryCount) {
+ return csReaderConnector.rfidReader.setRetryCount(retryCount);
+ }
+ public int getInvSelectIndex() {
+ return csReaderConnector.rfidReader.getInvSelectIndex();
+ }
+ public boolean getSelectEnable() {
+ return csReaderConnector.rfidReader.getSelectEnable();
+ }
+ public int getSelectTarget() {
+ return csReaderConnector.rfidReader.getSelectTarget();
+ }
+ public int getSelectAction() {
+ return csReaderConnector.rfidReader.getSelectAction();
+ }
+ public int getSelectMaskBank() {
+ return csReaderConnector.rfidReader.getSelectMaskBank();
+ }
+ public int getSelectMaskOffset() {
+ return csReaderConnector.rfidReader.getSelectMaskOffset();
+ }
+ public String getSelectMaskData() {
+ return csReaderConnector.rfidReader.getSelectMaskData();
+ }
+ public boolean setInvSelectIndex(int invSelect) {
+ return csReaderConnector.rfidReader.setInvSelectIndex(invSelect);
+ }
+ public boolean setSelectCriteriaDisable(int index) {
+ if (utility.DEBUG_SELECT) appendToLog("Debug_Select: Cs108Library4A.setSelectCriteriaDisable[" + index + "] goes to setSelectCriteriaDisable");
+ return csReaderConnector.rfidReader.setSelectCriteriaDisable(index);
+ }
+ int findFirstEmptySelect() {
+ return csReaderConnector.rfidReader.findFirstEmptySelect();
+ }
+ public boolean setSelectCriteria(int index, boolean enable, int target, int action, int bank, int offset, String mask, boolean maskbit) {
+ return csReaderConnector.rfidReader.setSelectCriteria(index, enable, target, action, bank, offset, mask, maskbit);
+ }
+ public boolean setSelectCriteria(int index, boolean enable, int target, int action, int delay, int bank, int offset, String mask) {
+ return csReaderConnector.rfidReader.setSelectCriteria(index, enable, target, action, delay, bank, offset, mask);
+ }
+ public boolean getRssiFilterEnable() {
+ return csReaderConnector.rfidReader.getRssiFilterEnable();
+ }
+ public int getRssiFilterType() {
+ return csReaderConnector.rfidReader.getRssiFilterType();
+ }
+ public int getRssiFilterOption() {
+ return csReaderConnector.rfidReader.getRssiFilterOption();
+ }
+ public boolean setRssiFilterConfig(boolean enable, int rssiFilterType, int rssiFilterOption) {
+ return csReaderConnector.rfidReader.setRssiFilterConfig(enable, rssiFilterType, rssiFilterOption);
+ }
+ public double getRssiFilterThreshold1() {
+ return csReaderConnector.rfidReader.getRssiFilterThreshold1();
+ }
+ public double getRssiFilterThreshold2() {
+ return csReaderConnector.rfidReader.getRssiFilterThreshold2();
+ }
+ public boolean setRssiFilterThreshold(double rssiFilterThreshold1, double rssiFilterThreshold2) {
+ return csReaderConnector.rfidReader.setRssiFilterThreshold(rssiFilterThreshold1, rssiFilterThreshold2);
+ }
+ public long getRssiFilterCount() {
+ return csReaderConnector.rfidReader.getRssiFilterCount();
+ }
+ public boolean setRssiFilterCount(long rssiFilterCount) {
+ return csReaderConnector.rfidReader.setRssiFilterCount(rssiFilterCount);
+ }
+ public boolean getInvMatchEnable() {
+ return csReaderConnector.rfidReader.getInvMatchEnable();
+ }
+ public boolean getInvMatchType() {
+ return csReaderConnector.rfidReader.getInvMatchType();
+ }
+ public int getInvMatchOffset() {
+ return csReaderConnector.rfidReader.getInvMatchOffset();
+ }
+ public String getInvMatchData() {
+ return csReaderConnector.rfidReader.getInvMatchData();
+ }
+ public boolean setPostMatchCriteria(boolean enable, boolean target, int offset, String mask) {
+ return csReaderConnector.rfidReader.setPostMatchCriteria(enable, target, offset, mask);
+ }
+ public int mrfidToWriteSize() {
+ if (isBleConnected() == false) return -1;
+ if (csReaderConnector.rfidReader == null) return -1;
+ return csReaderConnector.rfidReader.rfidToWriteSize();
+ }
+ public void mrfidToWritePrint() {
+ if (true) { csReaderConnector.rfidReader.rfidToWriteSize(); return; }
+ for (int i = 0; i < csReaderConnector.rfidReader.mRfidToWrite.size(); i++) {
+ appendToLog(byteArrayToString(csReaderConnector.rfidReader.mRfidToWrite.get(i).dataValues));
+ }
+ }
+ public long getTagRate() {
+ return csReaderConnector.rfidReader.getTagRate();
+ }
+ public boolean startOperation(RfidReaderChipData.OperationTypes operationTypes) {
+ return csReaderConnector.rfidReader.startOperation(operationTypes);
+ }
+ public boolean abortOperation() {
+ return csReaderConnector.rfidReader.abortOperation();
+ }
+ public void restoreAfterTagSelect() {
+ if (!isBleConnected()) return;
+ if (utility.DEBUG_SELECT) appendToLog("Debug_Select: Cs108Library4A.restoreAfterTagSelect goes to setSelectCriteriaDisable");
+ setSelectCriteriaDisable(0); setSelectCriteriaDisable(1); setSelectCriteriaDisable(2);
+ loadSetting1File();
+ setAccessCount(0);
+ setRx000AccessPassword("00000000");
+ if (checkHostProcessorVersion(getMacVer(), 2, 6, 8)) {
+ setMatchRep(0);
+ setTagDelay(csReaderConnector.rfidReader.tagDelaySetting);
+ setCycleDelay(csReaderConnector.rfidReader.cycleDelaySetting);
+ setInvModeCompact(true);
+ }
+ if (csReaderConnector.rfidReader.postMatchDataChanged) {
+ csReaderConnector.rfidReader.postMatchDataChanged = false;
+ setPostMatchCriteria(csReaderConnector.rfidReader.postMatchDataOld.enable, csReaderConnector.rfidReader.postMatchDataOld.target, csReaderConnector.rfidReader.postMatchDataOld.offset, csReaderConnector.rfidReader.postMatchDataOld.mask);
+ appendToLog("PowerLevel");
+ setPowerLevel(csReaderConnector.rfidReader.postMatchDataOld.pwrlevel);
+ appendToLog("writeBleStreamOut: invAlgo = " + csReaderConnector.rfidReader.postMatchDataOld.invAlgo); setInvAlgo1(csReaderConnector.rfidReader.postMatchDataOld.invAlgo);
+ setQValue1(csReaderConnector.rfidReader.postMatchDataOld.qValue);
+ }
+ }
+ public boolean setSelectedTagByTID(String strTagId, long pwrlevel) {
+ return csReaderConnector.rfidReader.setSelectedTagByTID(strTagId, pwrlevel);
+ }
+ public boolean setSelectedTag(String strTagId, int selectBank, long pwrlevel) {
+ return csReaderConnector.rfidReader.setSelectedTag(strTagId, selectBank, pwrlevel);
+ }
+ public boolean setSelectedTag(boolean selectOne, String selectMask, int selectBank, int selectOffset, long pwrlevel, int qValue, int matchRep) {
+ return csReaderConnector.rfidReader.setSelectedTag4Access(selectOne, selectMask, selectBank, selectOffset, pwrlevel, qValue, matchRep);
+ }
+ public boolean setMatchRep(int matchRep) {
+ if (utility.DEBUG_INVCFG) appendToLog("Debug_InvCfg: Cs108Library4A.setMatchRep goes to setMatchRep with matchRep = " + matchRep);
+ return csReaderConnector.rfidReader.setMatchRep(matchRep);
+ }
+ public String[] getCountryList() {
+ return csReaderConnector.rfidReader.getCountryList();
+ }
+ public int getCountryNumberInList() {
+ return csReaderConnector.rfidReader.countryInList;
+ }
+ public boolean setCountryInList(int countryInList) {
+ return csReaderConnector.rfidReader.setCountryInList(countryInList);
+ }
+ public boolean getChannelHoppingStatus() {
+ return csReaderConnector.rfidReader.getChannelHoppingStatus();
+ }
+ public boolean setChannelHoppingStatus(boolean channelOrderHopping) {
+ return csReaderConnector.rfidReader.setChannelHoppingStatus(channelOrderHopping);
+ }
+ public String[] getChannelFrequencyList() {
+ return csReaderConnector.rfidReader.getChannelFrequencyList();
+ }
+ public int getChannel() {
+ return csReaderConnector.settingData.channel;
+ }
+ public boolean setChannel(int channelSelect) {
+ return csReaderConnector.rfidReader.setChannel(channelSelect);
+ }
+ public byte getPopulation2Q(int population) {
+ return csReaderConnector.rfidReader.getPopulation2Q(population);
+ }
+ public int getPopulation() {
+ return csReaderConnector.rfidReader.getPopulation();
+ }
+ public boolean setPopulation(int population) {
+ return csReaderConnector.rfidReader.setPopulation(population);
+ }
+ public byte getQValue() {
+ return csReaderConnector.rfidReader.qValueSetting;
+ }
+ public boolean setQValue(byte byteValue) {
+ return csReaderConnector.rfidReader.setQValue(byteValue);
+ }
+ int getQValue1() {
+ return csReaderConnector.rfidReader.getQValue();
+ }
+ boolean setQValue1(int iValue) {
+ return csReaderConnector.rfidReader.setQValue1(iValue);
+ }
+ public RfidReaderChipData.Rx000pkgData onRFIDEvent() {
+ return csReaderConnector.rfidReader.onRFIDEvent();
+ }
+ public String getModelNumber() {
+ return csReaderConnector.rfidReader.getModelNumber(getModelName());
+ }
+ public boolean setRx000KillPassword(String password) {
+ return csReaderConnector.rfidReader.setRx000KillPassword(password);
+ }
+ public boolean setRx000AccessPassword(String password) {
+ return csReaderConnector.rfidReader.setRx000AccessPassword(password);
+ }
+ public boolean setAccessRetry(boolean accessVerfiy, int accessRetry) {
+ return csReaderConnector.rfidReader.setAccessRetry(accessVerfiy, accessRetry);
+ }
+ public boolean setInvModeCompact(boolean invModeCompact) {
+ if (utility.DEBUG_COMPACT) appendToLog("Debug_Compact: Cs108Library4A.setInvModeCompact goes to setInvModeCompact");
+ return csReaderConnector.rfidReader.setInvModeCompact(invModeCompact);
+ }
+ public boolean setAccessLockAction(int accessLockAction, int accessLockMask) {
+ return csReaderConnector.rfidReader.setAccessLockAction(accessLockAction, accessLockMask);
+ }
+ public boolean setAccessBank(int accessBank) {
+ return csReaderConnector.rfidReader.setAccessBank(accessBank);
+ }
+ public boolean setAccessBank(int accessBank, int accessBank2) {
+ return csReaderConnector.rfidReader.setAccessBank(accessBank, accessBank2);
+ }
+ public boolean setAccessOffset(int accessOffset) {
+ return csReaderConnector.rfidReader.setAccessOffset(accessOffset);
+ }
+ public boolean setAccessOffset(int accessOffset, int accessOffset2) {
+ return csReaderConnector.rfidReader.setAccessOffset(accessOffset, accessOffset2);
+ }
+ public boolean setAccessCount(int accessCount) {
+ return csReaderConnector.rfidReader.setAccessCount(accessCount);
+ }
+ public boolean setAccessCount(int accessCount, int accessCount2) {
+ return csReaderConnector.rfidReader.setAccessCount(accessCount, accessCount2);
+ }
+ public boolean setAccessWriteData(String dataInput) {
+ return csReaderConnector.rfidReader.setAccessWriteData(dataInput);
+ }
+ public boolean setResReadNoReply(boolean resReadNoReply) {
+ return false;
+ }
+ public boolean setTagRead(int tagRead) {
+ return csReaderConnector.rfidReader.setTagRead(tagRead);
+ }
+ public boolean setInvBrandId(boolean invBrandId) {
+ return csReaderConnector.rfidReader.setInvBrandId(invBrandId);
+ }
+ public boolean setInvAuthenticate(boolean invAuthenticate) {
+ return csReaderConnector.rfidReader.setInvAuthenticate(invAuthenticate);
+ }
+ public boolean sendHostRegRequestHST_CMD(RfidReaderChipData.HostCommands hostCommand) {
+ if (checkHostProcessorVersion(getMacVer(), 2, 6, 8)) setInvModeCompact(false);
+ return csReaderConnector.rfidReader.sendHostRegRequestHST_CMD(hostCommand);
+ }
+ public boolean setPwrManagementMode(boolean bLowPowerStandby) {
+ if (isBleConnected() == false) return false;
+ return csReaderConnector.rfidReader.setPwrManagementMode(bLowPowerStandby);
+ }
+ public void macWrite(int address, long value) {
+ csReaderConnector.rfidReader.macWrite(address, value);
+ }
+ public void set_fdCmdCfg(int value) {
+ csReaderConnector.rfidReader.set_fdRegAddr(value);
+ }
+ public void set_fdRegAddr(int addr) {
+ csReaderConnector.rfidReader.set_fdRegAddr(addr);
+ }
+ public void set_fdWrite(int addr, long value) {
+ csReaderConnector.rfidReader.set_fdWrite(addr, value);
+ }
+ public void set_fdPwd(int value) {
+ csReaderConnector.rfidReader.set_fdPwd(value);
+ }
+ public void set_fdBlockAddr4GetTemperature(int addr) {
+ csReaderConnector.rfidReader.set_fdBlockAddr4GetTemperature(addr);
+ }
+ public void set_fdReadMem(int addr, long len) {
+ csReaderConnector.rfidReader.set_fdReadMem(addr, len);
+ }
+ public void set_fdWriteMem(int addr, int len, long value) {
+ csReaderConnector.rfidReader.set_fdWriteMem(addr, len, value);
+ }
+ public void setImpinJExtension(boolean tagFocus, boolean fastId) {
+ csReaderConnector.rfidReader.setImpinJExtension(tagFocus, fastId);
+ }
+
+ //============ Barcode ============
+ public void getBarcodePreSuffix() {
+ barcodeNewland.getBarcodePreSuffix();
+ }
+ public void getBarcodeReadingMode() {
+ barcodeNewland.barcodeSendQueryReadingMode();
+ }
+ void getBarcodeEnable2dBarCodes() {
+ barcodeNewland.barcodeSendQueryEnable2dBarCodes();
+ }
+ void getBarcodePrefixOrder() {
+ barcodeNewland.barcodeSendQueryPrefixOrder();
+ }
+ void getBarcodeDelayTimeOfEachReading() {
+ barcodeNewland.barcodeSendQueryDelayTimeOfEachReading();
+ }
+ void getBarcodeNoDuplicateReading() {
+ barcodeNewland.barcodeSendQueryNoDuplicateReading();
+ }
+
+ public boolean isBarcodeFailure() {
+ if (barcodeConnector == null) return false;
+ return barcodeConnector.barcodeFailure;
+ }
+ public String getBarcodeDate() {
+ return barcodeNewland.getBarcodeDate();
+ }
+ public boolean getBarcodeOnStatus() {
+ if (barcodeConnector == null) return false;
+ return barcodeConnector.getOnStatus();
+ }
+ public boolean setBarcodeOn(boolean on) {
+ boolean retValue;
+ BarcodeConnector.CsReaderBarcodeData csReaderBarcodeData = new BarcodeConnector.CsReaderBarcodeData();
+ if (on) csReaderBarcodeData.barcodePayloadEvent = BarcodeConnector.BarcodePayloadEvents.BARCODE_POWER_ON;
+ else csReaderBarcodeData.barcodePayloadEvent = BarcodeConnector.BarcodePayloadEvents.BARCODE_POWER_OFF;
+ csReaderBarcodeData.waitUplinkResponse = false;
+ retValue = barcodeConnector.barcodeToWrite.add(csReaderBarcodeData); appendToLog("barcodeToWrite added with size = " + barcodeConnector.barcodeToWrite.size());
+ if (DEBUG_FILE) appendToLog("add " + csReaderBarcodeData.barcodePayloadEvent.toString() + " to barcodeToWrite with length = " + barcodeConnector.barcodeToWrite.size());
+ boolean continuousAfterOn = false;
+ if (retValue && on && continuousAfterOn) {
+ if (checkHostProcessorVersion(getBluetoothICFirmwareVersion(), 1, 0, 2)) {
+ if (DEBUG) appendToLog("to barcodeSendCommandConinuous()");
+ retValue = barcodeNewland.barcodeSendCommandConinuous();
+ } else retValue = false;
+ }
+ if (DEBUG) appendToLog("barcodeToWrite size = " + barcodeConnector.barcodeToWrite.size());
+ return retValue;
+ }
+ int iModeSet = -1, iVibratieTimeSet = -1;
+ public boolean setVibrateOn(int mode) {
+ boolean retValue;
+ if (true) appendToLog("setVibrateOn with mode = " + mode + ", and isInventoring = " + csReaderConnector.rfidReader.isInventoring());
+ if (csReaderConnector.rfidReader.isInventoring()) return false;
+ BarcodeConnector.CsReaderBarcodeData csReaderBarcodeData = new BarcodeConnector.CsReaderBarcodeData();
+ if (mode > 0) csReaderBarcodeData.barcodePayloadEvent = BarcodeConnector.BarcodePayloadEvents.BARCODE_VIBRATE_ON;
+ else csReaderBarcodeData.barcodePayloadEvent = BarcodeConnector.BarcodePayloadEvents.BARCODE_VIBRATE_OFF;
+ csReaderBarcodeData.waitUplinkResponse = false;
+ if (iModeSet == mode && iVibratieTimeSet == getVibrateTime()) {
+ appendToLog("writeBleStreamOut: A7B3: Skip saving vibration data");
+ return true;
+ }
+ if (mode > 0) {
+ byte[] barcodeCommandData = new byte[3];
+ barcodeCommandData[0] = (byte) (mode - 1);
+ barcodeCommandData[1] = (byte) (getVibrateTime() / 256);
+ barcodeCommandData[2] = (byte) (getVibrateTime() % 256);
+ csReaderBarcodeData.dataValues = barcodeCommandData;
+ }
+ retValue = barcodeConnector.barcodeToWrite.add(csReaderBarcodeData); appendToLog("barcodeToWrite added with size = " + barcodeConnector.barcodeToWrite.size());
+ if (DEBUG) appendToLog("barcodeToWrite size = " + barcodeConnector.barcodeToWrite.size());
+ if (retValue) {
+ iModeSet = mode; iVibratieTimeSet = getVibrateTime();
+ }
+ return retValue;
+ }
+ public boolean getInventoryVibrate() {
+ return csReaderConnector.settingData.inventoryVibrate;
+ }
+ public boolean setInventoryVibrate(boolean inventoryVibrate) {
+ boolean DEBUG = false;
+ if (DEBUG) appendToLog("this.inventoryVibrate = " + csReaderConnector.settingData.inventoryVibrate + ", inventoryVibrate = " + inventoryVibrate);
+ csReaderConnector.settingData.inventoryVibrate = inventoryVibrate;
+ if (DEBUG) appendToLog("this.inventoryVibrate = " + csReaderConnector.settingData.inventoryVibrate + ", inventoryVibrate = " + inventoryVibrate);
+ return true;
+ }
+ public int getVibrateTime() {
+ return csReaderConnector.settingData.vibrateTimeSetting;
+ }
+ public boolean setVibrateTime(int vibrateTime) {
+ csReaderConnector.settingData.vibrateTimeSetting = vibrateTime;
+ return true;
+ }
+ public int getVibrateWindow() {
+ return csReaderConnector.settingData.vibrateWindowSetting;
+ }
+ public boolean setVibrateWindow(int vibrateWindow) {
+ csReaderConnector.settingData.vibrateWindowSetting = vibrateWindow;
+ return true;
+ }
+ public boolean barcodeSendCommandTrigger() {
+ return barcodeNewland.barcodeSendCommandTrigger();
+ }
+ public boolean barcodeSendCommandSetPreSuffix() {
+ return barcodeNewland.barcodeSendCommandSetPreSuffix();
+ }
+ public boolean barcodeSendCommandResetPreSuffix() {
+ return barcodeNewland.barcodeSendCommandResetPreSuffix();
+ }
+ public boolean barcodeSendCommandConinuous() {
+ return barcodeNewland.barcodeSendCommandConinuous();
+ }
+ public String getBarcodeVersion() {
+ return barcodeNewland.getBarcodeVersion();
+ }
+ public String getBarcodeSerial() {
+ return barcodeNewland.getBarcodeSerial();
+ }
+ boolean barcodeAutoStarted = false;
+ public boolean barcodeInventory(boolean start) {
+ boolean result = true;
+ appendToLog("TTestPoint 0: " + start);
+ if (start) {
+ barcodeConnector.mBarcodeToRead.clear(); barcodeDataStore = null;
+ if (getBarcodeOnStatus() == false) { result = setBarcodeOn(true); appendToLog("TTestPoint 1"); }
+ if (csReaderConnector.settingData.barcode2TriggerMode && result) {
+ if (getTriggerButtonStatus() && notificationConnector.getAutoBarStartSTop()) { appendToLog("TTestPoint 2"); barcodeAutoStarted = true; result = true; }
+ else { appendToLog("TTestPoint 3"); result = barcodeNewland.barcodeSendCommand(new byte[]{0x1b, 0x33}); }
+ } else appendToLog("TTestPoint 4");
+ appendToLog("TTestPoint 5");
+ } else {
+ appendToLog("getBarcodeOnStatus = " + getBarcodeOnStatus() + ", result = " + result);
+ if (csReaderConnector.settingData.barcode2TriggerMode == false) { appendToLog("TTestPoint 6"); result = setBarcodeOn(false); }
+ else if (getBarcodeOnStatus() == false && result) { appendToLog("TTestPoint 7"); result = setBarcodeOn(true); }
+ appendToLog("barcode2TriggerMode = " + csReaderConnector.settingData.barcode2TriggerMode + ", result = " + result + ", barcodeAutoStarted = " + barcodeAutoStarted);
+ if (csReaderConnector.settingData.barcode2TriggerMode && result) {
+ if (barcodeAutoStarted && result) { appendToLog("TTestPoint 8"); barcodeAutoStarted = false; result = true; }
+ else { appendToLog("TTestPoint 9"); result = barcodeNewland.barcodeSendCommand(new byte[] { 0x1b, 0x30 }); }
+ } else appendToLog("TTestPoint 10");
+ }
+ return result;
+ }
+ byte[] barcodeDataStore = null; long timeBarcodeData;
+ public byte[] onBarcodeEvent() {
+ byte[] barcodeData = null;
+ if (barcodeConnector.mBarcodeToRead.size() != 0) {
+ BarcodeConnector.CsReaderBarcodeData csReaderBarcodeData = barcodeConnector.mBarcodeToRead.get(0);
+ barcodeConnector.mBarcodeToRead.remove(0);
+ if (csReaderBarcodeData != null) {
+ if (csReaderBarcodeData.barcodePayloadEvent == BarcodeConnector.BarcodePayloadEvents.BARCODE_GOOD_READ) {
+ if (false) barcodeData = "".getBytes();
+ } else if (csReaderBarcodeData.barcodePayloadEvent == BarcodeConnector.BarcodePayloadEvents.BARCODE_DATA_READ) {
+ barcodeData = csReaderBarcodeData.dataValues;
+ }
+ }
+ }
+
+ byte[] barcodeCombined = null;
+ if (false) barcodeCombined = barcodeData;
+ else if (barcodeData != null) {
+ appendToLog("BarStream: barcodeData = " + byteArrayToString(barcodeData) + ", barcodeDataStore = " + byteArrayToString(barcodeDataStore));
+ int barcodeDataStoreIndex = 0;
+ int length = barcodeData.length;
+ if (barcodeDataStore != null) {
+ barcodeDataStoreIndex = barcodeDataStore.length;
+ length += barcodeDataStoreIndex;
+ }
+ barcodeCombined = new byte[length];
+ if (barcodeDataStore != null)
+ System.arraycopy(barcodeDataStore, 0, barcodeCombined, 0, barcodeDataStore.length);
+ System.arraycopy(barcodeData, 0, barcodeCombined, barcodeDataStoreIndex, barcodeData.length);
+ barcodeDataStore = barcodeCombined;
+ timeBarcodeData = System.currentTimeMillis();
+ barcodeCombined = new byte[0];
+ }
+ if (barcodeDataStore != null) {
+ barcodeCombined = new byte[barcodeDataStore.length];
+ System.arraycopy(barcodeDataStore, 0, barcodeCombined, 0, barcodeCombined.length);
+
+ if (System.currentTimeMillis() - timeBarcodeData < 300) barcodeCombined = null;
+ else barcodeDataStore = null;
+ }
+ if (barcodeCombined != null && barcodeNewland.getPrefix() != null && barcodeNewland.getSuffix() != null) {
+ if (barcodeCombined.length == 0) barcodeCombined = null;
+ else {
+ byte[] prefixExpected = barcodeNewland.getPrefix(); boolean prefixFound = false;
+ byte[] suffixExpected = barcodeNewland.getSuffix(); boolean suffixFound = false;
+ int codeTypeLength = 4;
+ appendToLog("BarStream: barcodeCombined = " + byteArrayToString(barcodeCombined) + ", Expected Prefix = " + byteArrayToString(prefixExpected) + ", Expected Suffix = " + byteArrayToString(suffixExpected));
+ if (barcodeCombined.length > prefixExpected.length + suffixExpected.length + codeTypeLength) {
+ int i = 0;
+ for (; i <= barcodeCombined.length - prefixExpected.length - suffixExpected.length; i++) {
+ int j = 0;
+ for (; j < prefixExpected.length; j++) {
+ if (barcodeCombined[i+j] != prefixExpected[j]) break;
+ }
+ if (j == prefixExpected.length) { prefixFound = true; break; }
+ }
+ int k = i + prefixExpected.length;
+ for (; k <= barcodeCombined.length - suffixExpected.length; k++) {
+ int j = 0;
+ for (; j < suffixExpected.length; j++) {
+ if (barcodeCombined[k+j] != suffixExpected[j]) break;
+ }
+ if (j == suffixExpected.length) { suffixFound = true; break; }
+ }
+ appendToLog("BarStream: iPrefix = " + i + ", iSuffix = " + k + ", with prefixFound = " + prefixFound + ", suffixFound = " + suffixFound);
+ if (prefixFound && suffixFound) {
+ byte[] barcodeCombinedNew = new byte[k - i - prefixExpected.length - codeTypeLength];
+ System.arraycopy(barcodeCombined, i + prefixExpected.length + codeTypeLength, barcodeCombinedNew, 0, barcodeCombinedNew.length);
+ barcodeCombined = barcodeCombinedNew;
+ appendToLog("BarStream: barcodeCombinedNew = " + byteArrayToString(barcodeCombinedNew));
+
+ if (true) {
+ byte[] prefixExpected1 = {0x5B, 0x29, 0x3E, 0x1E};
+ prefixFound = false;
+ byte[] suffixExpected1 = {0x1E, 0x04};
+ suffixFound = false;
+ appendToLog("BarStream: barcodeCombined = " + byteArrayToString(barcodeCombined) + ", Expected Prefix = " + byteArrayToString(prefixExpected1) + ", Expected Suffix = " + byteArrayToString(suffixExpected1));
+ if (barcodeCombined.length > prefixExpected1.length + suffixExpected1.length) {
+ i = 0;
+ for (; i <= barcodeCombined.length - prefixExpected1.length - suffixExpected1.length; i++) {
+ int j = 0;
+ for (; j < prefixExpected1.length; j++) {
+ if (barcodeCombined[i + j] != prefixExpected1[j]) break;
+ }
+ if (j == prefixExpected1.length) {
+ prefixFound = true;
+ break;
+ }
+ }
+ k = i + prefixExpected1.length;
+ for (; k <= barcodeCombined.length - suffixExpected1.length; k++) {
+ int j = 0;
+ for (; j < suffixExpected1.length; j++) {
+ if (barcodeCombined[k + j] != suffixExpected1[j]) break;
+ }
+ if (j == suffixExpected1.length) {
+ suffixFound = true;
+ break;
+ }
+ }
+ appendToLog("BarStream: iPrefix = " + i + ", iSuffix = " + k + ", with prefixFound = " + prefixFound + ", suffixFound = " + suffixFound);
+ if (prefixFound && suffixFound) {
+ barcodeCombinedNew = new byte[k - i - prefixExpected1.length];
+ System.arraycopy(barcodeCombined, i + prefixExpected1.length, barcodeCombinedNew, 0, barcodeCombinedNew.length);
+ barcodeCombined = barcodeCombinedNew;
+ appendToLog("BarStream: barcodeCombinedNew = " + byteArrayToString(barcodeCombinedNew));
+ }
+ }
+ }
+ }
+ } else barcodeCombined = null;
+ }
+ }
+ return barcodeCombined;
+ }
+
+ //============ Android General ============
+ public void setSameCheck(boolean sameCheck1) {
+ if (csReaderConnector.sameCheck == sameCheck1) return;
+ if (false) appendToLog("new sameCheck = " + sameCheck1 + ", with old sameCheck = " + csReaderConnector.sameCheck);
+ csReaderConnector.sameCheck = sameCheck1; //sameCheck = false;
+ }
+
+ public int getBeepCount() {
+ return csReaderConnector.settingData.beepCountSetting;
+ }
+ public boolean setBeepCount(int beepCount) {
+ csReaderConnector.settingData.beepCountSetting = beepCount;
+ return true;
+ }
+
+ public boolean getInventoryBeep() {
+ return csReaderConnector.settingData.inventoryBeep;
+ }
+ public boolean setInventoryBeep(boolean inventoryBeep) {
+ csReaderConnector.settingData.inventoryBeep = inventoryBeep;
+ return true;
+ }
+
+ public boolean getSaveFileEnable() {
+ return csReaderConnector.settingData.saveFileEnable;
+ }
+ public boolean setSaveFileEnable(boolean saveFileEnable) {
+ appendToLog("this.saveFileEnable = " + csReaderConnector.settingData.saveFileEnable + ", saveFileEnable = " + saveFileEnable);
+ csReaderConnector.settingData.saveFileEnable = saveFileEnable;
+ appendToLog("this.saveFileEnable = " + csReaderConnector.settingData.saveFileEnable + ", saveFileEnable = " + saveFileEnable);
+ return true;
+ }
+ public boolean getSaveCloudEnable() {
+ return csReaderConnector.settingData.saveCloudEnable;
+ }
+ public boolean setSaveCloudEnable(boolean saveCloudEnable) {
+ csReaderConnector.settingData.saveCloudEnable = saveCloudEnable;
+ return true;
+ }
+ public boolean getSaveNewCloudEnable() {
+ return csReaderConnector.settingData.saveNewCloudEnable;
+ }
+ public boolean setSaveNewCloudEnable(boolean saveNewCloudEnable) {
+ csReaderConnector.settingData.saveNewCloudEnable = saveNewCloudEnable;
+ return true;
+ }
+ public boolean getSaveAllCloudEnable() {
+ return csReaderConnector.settingData.saveAllCloudEnable;
+ }
+ public boolean setSaveAllCloudEnable(boolean saveAllCloudEnable) {
+ csReaderConnector.settingData.saveAllCloudEnable = saveAllCloudEnable;
+ return true;
+ }
+ public boolean getUserDebugEnable() {
+ boolean bValue = csReaderConnector.settingData.userDebugEnable; appendToLog("bValue = " + bValue); return bValue;
+ }
+ public boolean setUserDebugEnable(boolean userDebugEnable) {
+ appendToLog("new userDebug = " + userDebugEnable);
+ csReaderConnector.settingData.userDebugEnable = userDebugEnable;
+ return true;
+ }
+ public String getForegroundReader() {
+ return csReaderConnector.settingData.strForegroundReader;
+ }
+ public boolean getForegroundServiceEnable() {
+ String string = csReaderConnector.settingData.strForegroundReader;
+ return (string.trim().length() == 0 ? false : true);
+ }
+ public boolean setForegroundServiceEnable(boolean bForegroundService) {
+ if (bForegroundService) csReaderConnector.settingData.strForegroundReader = csReaderConnector.bluetoothGatt.getReaderDeviceConnected().getAddress();
+ else csReaderConnector.settingData.strForegroundReader = "";
+ return true;
+ }
+ public String getServerLocation() {
+ return csReaderConnector.settingData.serverLocation;
+ }
+ public boolean setServerLocation(String serverLocation) {
+ csReaderConnector.settingData.serverLocation = serverLocation;
+ return true;
+ }
+ public int getServerTimeout() {
+ return csReaderConnector.settingData.serverTimeout;
+ }
+ public boolean setServerTimeout(int serverTimeout) {
+ csReaderConnector.settingData.serverTimeout = serverTimeout;
+ return true;
+ }
+ public String getServerMqttLocation() {
+ return csReaderConnector.settingData.serverMqttLocation;
+ }
+ public boolean setServerMqttLocation(String serverLocation) {
+ csReaderConnector.settingData.serverMqttLocation = serverLocation;
+ return true;
+ }
+ public String getTopicMqtt() {
+ return csReaderConnector.settingData.topicMqtt;
+ }
+ public boolean setTopicMqtt(String topicMqtt) {
+ csReaderConnector.settingData.topicMqtt = topicMqtt;
+ return true;
+ }
+ public int getForegroundDupElim() {
+ return csReaderConnector.settingData.iForegroundDupElim;
+ }
+ public boolean setForegroundDupElim(int iForegroundDupElim) {
+ csReaderConnector.settingData.iForegroundDupElim = iForegroundDupElim;
+ return true;
+ }
+ public int getInventoryCloudSave() {
+ return csReaderConnector.settingData.inventoryCloudSave;
+ }
+ public boolean setInventoryCloudSave(int inventoryCloudSave) {
+ csReaderConnector.settingData.inventoryCloudSave = inventoryCloudSave;
+ return true;
+ }
+ public String getServerImpinjLocation() {
+ return csReaderConnector.settingData.serverImpinjLocation;
+ }
+ public boolean setServerImpinjLocation(String serverImpinjLocation) {
+ csReaderConnector.settingData.serverImpinjLocation = serverImpinjLocation;
+ return true;
+ }
+ public String getServerImpinjName() {
+ appendToLog("serverImpinjName = " + csReaderConnector.settingData.serverImpinjName);
+ return csReaderConnector.settingData.serverImpinjName;
+ }
+ public boolean setServerImpinjName(String serverImpinjName) {
+ csReaderConnector.settingData.serverImpinjName = serverImpinjName;
+ appendToLog("serverImpinjName = " + serverImpinjName);
+ return true;
+ }
+ public String getServerImpinjPassword() {
+ return csReaderConnector.settingData.serverImpinjPassword;
+ }
+ public boolean setServerImpinjPassword(String serverImpinjPassword) {
+ csReaderConnector.settingData.serverImpinjPassword = serverImpinjPassword;
+ return true;
+ }
+ public int getBatteryDisplaySetting() {
+ return csReaderConnector.settingData.batteryDisplaySelect;
+ }
+ public boolean setBatteryDisplaySetting(int batteryDisplaySelect) {
+ return csReaderConnector.settingData.setBatteryDisplaySetting(batteryDisplaySelect);
+ }
+ public double dBuV_dBm_constant = RfidReader.dBuV_dBm_constant; //106.98;
+ public int getRssiDisplaySetting() {
+ return csReaderConnector.settingData.rssiDisplaySelect;
+ }
+ public boolean setRssiDisplaySetting(int rssiDisplaySelect) {
+ return csReaderConnector.settingData.setRssiDisplaySetting(rssiDisplaySelect);
+ }
+ public int getVibrateModeSetting() {
+ return csReaderConnector.settingData.vibrateModeSelect;
+ }
+ public boolean setVibrateModeSetting(int vibrateModeSelect) {
+ if (vibrateModeSelect < 0 || vibrateModeSelect > 1) return false;
+ csReaderConnector.settingData.vibrateModeSelect = vibrateModeSelect;
+ return true;
+ }
+ public int getSavingFormatSetting() {
+ return csReaderConnector.settingData.savingFormatSelect;
+ }
+ public boolean setSavingFormatSetting(int savingFormatSelect) {
+ if (false) appendToLog("savingFormatSelect = " + savingFormatSelect);
+ if (savingFormatSelect < 0 || savingFormatSelect > 1) return false;
+ csReaderConnector.settingData.savingFormatSelect = savingFormatSelect;
+ return true;
+ }
+ public int getCsvColumnSelectSetting() {
+ return csReaderConnector.settingData.csvColumnSelect;
+ }
+ public boolean setCsvColumnSelectSetting(int csvColumnSelect) {
+ csReaderConnector.settingData.csvColumnSelect = csvColumnSelect;
+ return true;
+ }
+ public String getWedgeDeviceName() {
+ return csReaderConnector.settingData.wedgeDeviceName;
+ }
+ public String getWedgeDeviceAddress() {
+ return csReaderConnector.settingData.wedgeDeviceAddress;
+ }
+ public int getWedgeDeviceUUID2p1() {
+ return csReaderConnector.settingData.wedgeDeviceUUID2p1;
+ }
+ public int getWedgePower() {
+ return csReaderConnector.settingData.wedgePower;
+ }
+ public String getWedgePrefix() {
+ return csReaderConnector.settingData.wedgePrefix;
+ }
+ public String getWedgeSuffix() {
+ return csReaderConnector.settingData.wedgeSuffix;
+ }
+ public int getWedgeDelimiter() {
+ return csReaderConnector.settingData.wedgeDelimiter;
+ }
+ public int getWedgeOutput() {
+ return csReaderConnector.settingData.wedgeOutput;
+ }
+ public void setWedgeDeviceName(String wedgeDeviceName) {
+ csReaderConnector.settingData.wedgeDeviceName = wedgeDeviceName;
+ }
+ public void setWedgeDeviceAddress(String wedgeDeviceAddress) {
+ csReaderConnector.settingData.wedgeDeviceAddress = wedgeDeviceAddress;
+ }
+ public void setWedgeDeviceUUID2p1(int wedgeDeviceUUID2p1) {
+ csReaderConnector.settingData.wedgeDeviceUUID2p1 = wedgeDeviceUUID2p1;;
+ }
+ public void setWedgePower(int iPower) {
+ csReaderConnector.settingData.wedgePower = iPower;
+ }
+ public void setWedgePrefix(String string) {
+ csReaderConnector.settingData.wedgePrefix = string;
+ }
+ public void setWedgeSuffix(String string) {
+ csReaderConnector.settingData.wedgeSuffix = string;
+ }
+ public void setWedgeDelimiter(int iValue) {
+ csReaderConnector.settingData.wedgeDelimiter = iValue;
+ }
+ public void setWedgeOutput(int iOutput) {
+ csReaderConnector.settingData.wedgeOutput = iOutput;
+ }
+ public void saveWedgeSetting2File() {
+ csReaderConnector.settingData.saveWedgeSetting2File();
+ }
+
+ //============ Bluetooth ============
+ public String getBluetoothICFirmwareVersion() {
+ return bluetoothConnector.getBluetoothIcVersion();
+ }
+ public String getBluetoothICFirmwareName() {
+ return bluetoothConnector.getBluetoothIcName();
+ }
+ public boolean setBluetoothICFirmwareName(String name) {
+ return bluetoothConnector.setBluetoothIcName(name);
+ }
+
+ //============ Controller ============
+ public String hostProcessorICGetFirmwareVersion() {
+ return controllerConnector.getVersion();
+ }
+ public String getHostProcessorICSerialNumber() {
+ String str;
+ if (bluetoothConnector.getCsModel() != 463) str = controllerConnector.getSerialNumber();
+ else str = csReaderConnector.rfidReader.getProductSerialNumber();
+ if (str != null) {
+ if (str.length() > 13) return str.substring(0, 13);
+ }
+ return null;
+ }
+ public String getHostProcessorICBoardVersion() {
+ String str;
+ if (bluetoothConnector.getCsModel() != 463) str = controllerConnector.getSerialNumber();
+ else str = csReaderConnector.rfidReader.getProductSerialNumber();
+ if (false) appendToLog("str = " + str);
+ if (str != null) {
+ if (str.length() == 16) {
+ String strOut = "";
+ if (str.substring(13, 14).matches("0") == false) strOut = str.substring(13, 14);
+ strOut += (strOut.length() != 0 ? "." : "") + str.substring(14, 15);
+ if (str.substring(15, 16).matches("0") == false || strOut.length() < 3) strOut += (strOut.length() < 3 ? "." : "") + str.substring(15, 16);
+ if (false) appendToLog("getBoardVersion 1 = " + str);
+ return strOut;
+ }
+ }
+ return null;
+ }
+
+ //============ Controller notification ============
+ int iBatteryCount;
+ int getBatteryValue2Percent(float floatValue) {
+ boolean DEBUG = false;
+ if (DEBUG) appendToLog("getHostProcessorICBoardVersion = " + getHostProcessorICBoardVersion() + ", strVersionMBoard = " + strVersionMBoard);
+ if (false || checkHostProcessorVersion(getHostProcessorICBoardVersion(), Integer.parseInt(strMBoardVersions[0].trim()), Integer.parseInt(strMBoardVersions[1].trim()), 0)) {
+ final float[] fValueStbyRef = {
+ (float) 4.212, (float) 4.175, (float) 4.154, (float) 4.133, (float) 4.112,
+ (float) 4.085, (float) 4.069, (float) 4.054, (float) 4.032, (float) 4.011,
+ (float) 3.990, (float) 3.969, (float) 3.953, (float) 3.937, (float) 3.922,
+ (float) 3.901, (float) 3.885, (float) 3.869, (float) 3.853, (float) 3.837,
+ (float) 3.821, (float) 3.806, (float) 3.790, (float) 3.774, (float) 3.769,
+ (float) 3.763, (float) 3.758, (float) 3.753, (float) 3.747, (float) 3.742,
+ (float) 3.732, (float) 3.721, (float) 3.705, (float) 3.684, (float) 3.668,
+ (float) 3.652, (float) 3.642, (float) 3.626, (float) 3.615, (float) 3.605,
+ (float) 3.594, (float) 3.584, (float) 3.568, (float) 3.557, (float) 3.542,
+ (float) 3.531, (float) 3.510, (float) 3.494, (float) 3.473, (float) 3.457,
+ (float) 3.436, (float) 3.410, (float) 3.362, (float) 3.235, (float) 2.987,
+ (float) 2.982
+ };
+ final float[] fPercentStbyRef = {
+ (float) 100, (float) 98, (float) 96, (float) 95, (float) 93,
+ (float) 91, (float) 89, (float) 87, (float) 85, (float) 84,
+ (float) 82, (float) 80, (float) 78, (float) 76, (float) 75,
+ (float) 73, (float) 71, (float) 69, (float) 67, (float) 65,
+ (float) 64, (float) 62, (float) 60, (float) 58, (float) 56,
+ (float) 55, (float) 53, (float) 51, (float) 49, (float) 47,
+ (float) 45, (float) 44, (float) 42, (float) 40, (float) 38,
+ (float) 36, (float) 35, (float) 33, (float) 31, (float) 29,
+ (float) 27, (float) 25, (float) 24, (float) 22, (float) 20,
+ (float) 18, (float) 16, (float) 15, (float) 13, (float) 11,
+ (float) 9, (float) 7, (float) 5, (float) 4, (float) 2,
+ (float) 0
+ };
+ final float[] fValueRunRef = {
+ (float) 4.106, (float) 4.017, (float) 3.98 , (float) 3.937, (float) 3.895,
+ (float) 3.853, (float) 3.816, (float) 3.779, (float) 3.742, (float) 3.711,
+ (float) 3.679, (float) 3.658, (float) 3.637, (float) 3.626, (float) 3.61 ,
+ (float) 3.584, (float) 3.547, (float) 3.515, (float) 3.484, (float) 3.457,
+ (float) 3.431, (float) 3.399, (float) 3.362, (float) 3.32 , (float) 3.251,
+ (float) 3.135
+ };
+ final float[] fPercentRunRef = {
+ (float) 100, (float) 96, (float) 92, (float) 88, (float) 84,
+ (float) 80, (float) 76, (float) 72, (float) 67, (float) 63,
+ (float) 59, (float) 55, (float) 51, (float) 47, (float) 43,
+ (float) 39, (float) 35, (float) 31, (float) 27, (float) 23,
+ (float) 19, (float) 15, (float) 11, (float) 7, (float) 2,
+ (float) 0
+ };
+ float[] fValueRef = fValueStbyRef;
+ float[] fPercentRef = fPercentStbyRef;
+
+ if (true && iBatteryCount != getBatteryCount()) {
+ iBatteryCount = getBatteryCount();
+ iBatteryNewCurveDelay++;
+ }
+ if (csReaderConnector.rfidReader.mRfidToWrite.size() != 0) iBatteryNewCurveDelay = 0;
+ else if (csReaderConnector.rfidReader.isInventoring()) {
+ if (bUsingInventoryBatteryCurve == false) { if (iBatteryNewCurveDelay > 1) { iBatteryNewCurveDelay = 0; bUsingInventoryBatteryCurve = true; } }
+ else iBatteryNewCurveDelay = 0;
+ } else if (bUsingInventoryBatteryCurve) { if (iBatteryNewCurveDelay > 2) { iBatteryNewCurveDelay = 0; bUsingInventoryBatteryCurve = false; } }
+ else iBatteryNewCurveDelay = 0;
+
+ if (bUsingInventoryBatteryCurve) {
+ fValueRef = fValueRunRef;
+ fPercentRef = fPercentRunRef;
+ }
+ if (DEBUG) appendToLog("NEW Percentage cureve is USED with bUsingInventoryBatteryCurve = " + bUsingInventoryBatteryCurve + ", iBatteryNewCurveDelay = " + iBatteryNewCurveDelay);
+
+ int index = 0;
+ while (index < fValueRef.length) {
+ if (floatValue > fValueRef[index]) break;
+ index++;
+ }
+ if (DEBUG) appendToLog("Index = " + index);
+ if (index == 0) return 100;
+ if (index == fValueRef.length) return 0;
+ float value = ((fValueRef[index - 1] - floatValue) / (fValueRef[index - 1] - fValueRef[index]));
+ if (true) {
+ value *= (fPercentRef[index -1] - fPercentRef[index]);
+ value = fPercentRef[index - 1] - value;
+ } else {
+ value += (float) (index - 1);
+ value /= (float) (fValueRef.length - 1);
+ value *= 100;
+ value = 100 - value;
+ }
+ value += 0.5;
+ int iValue = (int) (value);
+ if (iBatteryNewCurveDelay != 0) iValue = iBatteryPercentOld;
+ else if (bUsingInventoryBatteryCurve && floatValue <= fBatteryValueOld && iValue >= iBatteryPercentOld) iValue = iBatteryPercentOld;
+ fBatteryValueOld = floatValue; iBatteryPercentOld = iValue;
+ return iValue;
+ } else {
+ if (DEBUG) appendToLog("OLD Percentage cureve is USED");
+ if (floatValue >= 4) return 100;
+ else if (floatValue < 3.4) return 0;
+ else {
+ float result = (float) 166.67 * floatValue - (float) 566.67;
+ return (int) result;
+ }
+ }
+ }
+ public int getBatteryLevel() {
+ return csReaderConnector.getBatteryLevel();
+ }
+ public boolean setAutoTriggerReporting(byte timeSecond) {
+ return notificationConnector.setAutoTriggerReporting(timeSecond);
+ }
+ public boolean getAutoBarStartSTop() {
+ return notificationConnector.getAutoBarStartStopStatus();
+ }
+
+ public boolean batteryLevelRequest() {
+ if (csReaderConnector.rfidReader == null) return false;
+ if (notificationConnector == null) return false;
+ if (csReaderConnector.rfidReader.isInventoring()) {
+ appendToLog("Skip batteryLevelREquest as inventoring !!!");
+ return true;
+ }
+ if (mrfidToWriteSize() != 0) return false;
+ return notificationConnector.batteryLevelRequest();
+ }
+ public boolean setAutoBarStartSTop(boolean enable) {
+ return notificationConnector.setAutoBarStartSTop(enable);
+ }
+ public boolean getTriggerReporting() {
+ return csReaderConnector.settingData.triggerReporting;
+ }
+ public boolean setTriggerReporting(boolean triggerReporting) {
+ return notificationConnector.setTriggerReporting(triggerReporting);
+ }
+ public final int iNO_SUCH_SETTING = 10000;
+ public short getTriggerReportingCount() {
+ boolean bValue = false;
+ if (getcsModel() != 463) bValue = checkHostProcessorVersion(hostProcessorICGetFirmwareVersion(), 1, 0, 16);
+ if (bValue == false) return iNO_SUCH_SETTING; else
+ return csReaderConnector.settingData.triggerReportingCountSetting;
+ }
+ public boolean setTriggerReportingCount(short triggerReportingCount) {
+ return notificationConnector.setTriggerReportingCount(triggerReportingCount);
+ }
+ public String getBatteryDisplay(boolean voltageDisplay) {
+ float floatValue = (float) getBatteryLevel() / 1000;
+ if (floatValue == 0) return " ";
+ String retString = null;
+ if (voltageDisplay || (getBatteryDisplaySetting() == 0)) retString = String.format("%.3f V", floatValue);
+ else retString = (String.format("%d", getBatteryValue2Percent(floatValue)) + "%");
+ if (voltageDisplay == false) retString += String.format("\r\n P=%d", getPwrlevel());
+ return retString;
+ }
+ String strVersionMBoard = "1.8"; String[] strMBoardVersions = strVersionMBoard.split("\\.");
+ int iBatteryNewCurveDelay; boolean bUsingInventoryBatteryCurve = false; float fBatteryValueOld; int iBatteryPercentOld;
+ public String isBatteryLow() {
+ boolean batterylow = false;
+ int iValue = getBatteryLevel();
+ if (iValue == 0) return null;
+ float fValue = (float) iValue / 1000;
+ int iPercent = getBatteryValue2Percent(fValue);
+ if (checkHostProcessorVersion(getHostProcessorICBoardVersion(), Integer.parseInt(strMBoardVersions[0].trim()), Integer.parseInt(strMBoardVersions[1].trim()), 0)) {
+ if (true) {
+ if (csReaderConnector.rfidReader.isInventoring()) {
+ if (fValue < 3.520) batterylow = true;
+ } else if (bUsingInventoryBatteryCurve == false) {
+ if (fValue < 3.626) batterylow = true;
+ }
+ } else if (iPercent <= 20) batterylow = true;
+ } else if (true) {
+ if (csReaderConnector.rfidReader.isInventoring()) {
+ if (fValue < 3.45) batterylow = true;
+ } else if (bUsingInventoryBatteryCurve == false) {
+ if (fValue < 3.6) batterylow = true;
+ }
+ } else if (iPercent <= 8) batterylow = true;
+ if (batterylow) return String.valueOf(iPercent);
+ return null;
+ }
+ public int getBatteryCount() {
+ return csReaderConnector.csConnectorData.getVoltageCnt();
+ }
+ public boolean getTriggerButtonStatus() {
+ return notificationConnector.getTriggerStatus();
+ }
+ public int getTriggerCount() {
+ return csReaderConnector.csConnectorData.getTriggerCount();
+ }
+ //public interface NotificationListener { void onChange(); }
+ public void setNotificationListener(NotificationConnector.NotificationListener listener) {
+ notificationConnector.setNotificationListener0(listener);
+ }
+ public byte[] onNotificationEvent() {
+ byte[] notificationData = null;
+ if (notificationConnector == null) {
+ appendToLog("notificationConnector is null");
+ return null;
+ }
+ if (notificationConnector.notificationToRead.size() != 0) {
+ NotificationConnector.CsReaderNotificationData csReaderNotificationData = notificationConnector.notificationToRead.get(0);
+ notificationConnector.notificationToRead.remove(0);
+ if (csReaderNotificationData != null) notificationData = csReaderNotificationData.dataValues;
+ }
+ return notificationData;
+ }
+
+ //============ to be modified ============
+ String getModelName() {
+ return csReaderConnector.getModelName();
+ }
+ public String getSerialNumber() {
+ return csReaderConnector.rfidReader.getSerialNumber();
+ }
+ public boolean setRfidOn(boolean onStatus) {
+ return csReaderConnector.rfidReader.turnOn(onStatus);
+ }
+ private final Runnable reinitaliseDataRunnable = new Runnable() {
+ @Override
+ public void run() {
+ appendToLog("reset before: reinitaliseDataRunnable starts with inventoring=" + csReaderConnector.rfidReader.isInventoring() + ", mrfidToWriteSize=" + mrfidToWriteSize());
+ if (csReaderConnector.rfidReader.isInventoring() || mrfidToWriteSize() != 0) {
+ mHandler.removeCallbacks(reinitaliseDataRunnable);
+ mHandler.postDelayed(reinitaliseDataRunnable, 500);
+ } else {
+ if (DEBUG_CONNECT) appendToLog("Debug_Connect: Cs108Library4A.reinitaliseDataRunnable Start checkVersionRunnable");
+ mHandler.postDelayed(checkVersionRunnable, 500);
+ }
+ }
+ };
+ private final Runnable checkVersionRunnable = new Runnable() {
+ boolean DEBUG = false;
+ @Override
+ public void run() {
+ if (DEBUG_CONNECT || true) appendToLog("Debug_Connect: Cs108Library4A.checkVersionRunnable with mrfidToWriteSize = " + mrfidToWriteSize());
+ if (mrfidToWriteSize() > 0) {
+ mHandler.removeCallbacks(checkVersionRunnable);
+ mHandler.postDelayed(checkVersionRunnable, 500);
+ } else {
+ //setSameCheck(false);
+ setAccessCount(0); //appendToLog("btDataOut: setAccessCount as 0");
+ notificationConnector.setVersion(hostProcessorICGetFirmwareVersion());
+ if (false && isBarcodeFailure() == false) {
+ if (DEBUG) appendToLog("checkVersionRunnable: Checkpoint 2");
+ if (barcodeNewland.checkPreSuffix(barcodeNewland.prefixRef, barcodeNewland.suffixRef) == false) barcodeNewland.barcodeSendCommandSetPreSuffix();
+ if (barcodeNewland.bBarcodeTriggerMode != 0x30) barcodeNewland.barcodeSendCommandTrigger();
+ notificationConnector.getAutoRFIDAbort(); notificationConnector.getAutoBarStartSTop(); //setAutoRFIDAbort(false); setAutoBarStartSTop(true);
+ }
+ setAntennaCycle(0xffff);
+ if (true) {
+ if (bluetoothConnector.getCsModel() == 463) {
+ if (DEBUG_CONNECT) appendToLog("Debug_Connect: Cs108Library4A.checkVersionRunnable 4");
+ setAntennaDwell(2000);
+ setAntennaInvCount(0);
+ } else {
+ if (DEBUG_CONNECT) appendToLog("Debug_Connect: Cs108Library4A.checkVersionRunnable 5");
+ setAntennaDwell(0);
+ setAntennaInvCount(0xfffffffeL);
+ }
+ }
+ csReaderConnector.settingData.loadWedgeSettingFile();
+ if (loadSetting1File()) loadSetting1File();
+ if (DEBUG_CONNECT) appendToLog("Debug_Connect: Cs108Library4A.checkVersionRunnable with macVersion [" + getMacVer());
+ if (checkHostProcessorVersion(getMacVer(), 2, 6, 8)) {
+ setTagDelay(csReaderConnector.rfidReader.tagDelaySetting);
+ setCycleDelay(csReaderConnector.rfidReader.cycleDelaySetting);
+ setInvModeCompact(true);
+ } else {
+ setTagDelay(csReaderConnector.rfidReader.tagDelayDefaultNormalSetting);
+ setCycleDelay(csReaderConnector.rfidReader.cycleDelaySetting);
+ }
+ csReaderConnector.rfidReader.setDiagnosticConfiguration(true);
+ if (DEBUG_CONNECT) appendToLog("Debug_Connect: Cs108Library4A.checkVersionRunnable ends with mRfidToWrite.size = " + csReaderConnector.rfidReader.mRfidToWrite.size());
+ //setSameCheck(true);
+ }
+ }
+ };
+
+ boolean loadSetting1File() {
+ return csReaderConnector.settingData.loadSettingFile(bluetoothGatt.getReaderDeviceConnected().getAddress(), getlibraryVersion(), getChannelHoppingStatus(), getCurrentProfile());
+ }
+ public void saveSetting2File() {
+ csReaderConnector.settingData.saveSetting2File(getlibraryVersion(), getChannelHoppingStatus(), getCurrentProfile());
+ }
+
+ public int getcsModel() {
+ return bluetoothConnector.getCsModel();
+ }
+ public int getAntennaCycle() {
+ return csReaderConnector.rfidReader.getAntennaCycle();
+ }
+ public boolean setAntennaCycle(int antennaCycle) {
+ return csReaderConnector.rfidReader.setAntennaCycle(antennaCycle);
+ }
+ public boolean setAntennaInvCount(long antennaInvCount) {
+ return csReaderConnector.rfidReader.setAntennaInvCount(antennaInvCount);
+ }
+
+ public void clearInvalidata() {
+ csReaderConnector.clearInvalidata();
+ }
+ public int getInvalidata() {
+ return csReaderConnector.invalidata;
+ }
+ public int getInvalidUpdata() {
+ return csReaderConnector.invalidUpdata;
+ }
+ public int getValidata() {
+ return csReaderConnector.validata;
+ }
+
+ public int setSelectData(RfidReader.TagType tagType, String mDid, boolean bNeedSelectedTagByTID, String stringProtectPassword, int selectFor, int selectHold) {
+ return csReaderConnector.rfidReader.setSelectData4Inventory(tagType, mDid, bNeedSelectedTagByTID, stringProtectPassword, selectFor, selectHold);
+ }
+ public int setOtherInventoryData(RfidReader.TagType tagType, String mDid) {
+ return -1;
+ }
+}
+
+
+
+package com.csl.cslibrary4a;
+
+import android.bluetooth.BluetoothAdapter;
+import android.bluetooth.BluetoothProfile;
+import android.bluetooth.le.ScanCallback;
+import android.content.Context;
+import android.os.Handler;
+import android.widget.TextView;
+
+import com.csl.cslibrary4a.RfidReader.RegionCodes;
+
+import java.io.File;
+import java.util.ArrayList;
+import java.util.List;
+
+public class Cs710Library4A {
+ final boolean DEBUG = false;
+ final boolean DEBUG_FILE = false;
+ private Handler mHandler = new Handler();
+ BluetoothAdapter.LeScanCallback mLeScanCallback = null;
+ ScanCallback mScanCallback = null;
+
+ Context context;
+ CsReaderConnector csReaderConnector; Utility utility;
+ boolean DEBUG_CONNECT, DEBUG_SCAN;
+ BluetoothGatt bluetoothGatt;
+ BarcodeNewland barcodeNewland; BarcodeConnector barcodeConnector;
+ NotificationConnector notificationConnector;
+ ControllerConnector controllerConnector;
+ BluetoothConnector bluetoothConnector;
+ TextView mLogView = null;
+
+ void setCsReaderConnectorCombo() { csReaderConnector.setScanType(0x03); }
+ public Cs710Library4A(Context context, TextView mLogView) {
+ this.context = context;
+ this.mLogView = mLogView;
+ utility = new Utility(context, mLogView);
+ csReaderConnector = new CsReaderConnector(context, mLogView, utility, false); csReaderConnector.setScanType(0x02);
+ bluetoothGatt = csReaderConnector.bluetoothGatt; DEBUG_CONNECT = utility.DEBUG_CONNECT; DEBUG_SCAN = utility.DEBUG_SCAN;
+/*
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
+ mScanCallback = new ScanCallback() {
+ @Override
+ public void onBatchScanResults(List results) {
+ if (DEBUG) appendToLog("onBatchScanResults()");
+ }
+
+ @Override
+ public void onScanFailed(int errorCode) {
+ if (DEBUG) appendToLog("onScanFailed()");
+ }
+
+ @Override
+ public void onScanResult(int callbackType, ScanResult result) {
+ boolean DEBUG = false;
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
+ BluetoothGatt.CsScanData scanResultA = new BluetoothGatt.CsScanData(result.getDevice(), result.getRssi(), result.getScanRecord().getBytes());
+ boolean found98 = true;
+ if (true) found98 = check9800(scanResultA);
+ if (DEBUG) appendToLog("found98 = " + found98 + ", mScanResultList 0 = " + (mScanResultList != null ? "VALID" : "NULL"));
+ if (mScanResultList != null && found98) {
+ scanResultA.serviceUUID2p2 = check9800_serviceUUID2p1;
+ mScanResultList.add(scanResultA);
+ if (DEBUG) appendToLog("mScanResultList 0 = " + mScanResultList.size());
+ }
+ }
+ }
+ };
+ } else {
+ mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
+ @Override
+ public void onLeScan(final BluetoothDevice device, final int rssi, final byte[] scanRecord) {
+ if (true) appendToLog("onLeScan()");
+ BluetoothGatt.CsScanData scanResultA = new BluetoothGatt.CsScanData(device, rssi, scanRecord);
+ boolean found98 = true;
+ if (true) found98 = check9800(scanResultA);
+ appendToLog("found98 = " + found98 + ", mScanResultList 1 = " + (mScanResultList != null ? "VALID" : "NULL"));
+ if (mScanResultList != null && found98) {
+ scanResultA.serviceUUID2p2 = check9800_serviceUUID2p1;
+ mScanResultList.add(scanResultA);
+ appendToLog("mScanResultList 1 = " + mScanResultList.size());
+ }
+ }
+ };
+ }
+*/
+ File path = context.getFilesDir();
+ File[] fileArray = path.listFiles();
+ boolean deleteFiles = false;
+ if (true || DEBUG)
+ appendToLog("Number of file in data storage sub-directory = " + fileArray.length);
+ boolean bProfileInstalledFound = false;
+ for (int i = 0; i < fileArray.length; i++) {
+ String fileName = fileArray[i].toString();
+ if (true) appendToLog("Stored file (" + i + ") = " + fileName);
+ if (fileName.contains("profileInstalled") || fileName.contains("profileinstaller")) {
+ bProfileInstalledFound = true;
+ appendToLog("Found profileInstalled or profileinstaller file");
+ }
+ File file = new File(fileName);
+ if (deleteFiles) file.delete();
+ }
+ if (!bProfileInstalledFound) {
+ for (int i = 0; i < fileArray.length; i++) {
+ String fileName = fileArray[i].toString();
+ File file = new File(fileName);
+ file.delete();
+ appendToLog("Deleted " + fileName);
+ }
+ }
+ }
+ public String getlibraryVersion() {
+ String version = BuildConfig.VERSION_NAME;
+ //int iVersion = Integer.parseInt(version) + 10;
+ version = "15.0"; //+ String.valueOf(iVersion);
+ appendToLog("version = " + version);
+ return utility.getCombinedVersion(version);
+ }
+ public String checkVersion() {
+ return csReaderConnector.checkVersion();
+ }
+
+ //============ utility ============
+ public String byteArrayToString(byte[] packet) {
+ return utility.byteArrayToString(packet);
+ }
+ public void appendToLog(String s) {
+ utility.appendToLog(s);
+ }
+ public void appendToLogView(String s) {
+ utility.appendToLogView(s);
+ }
+ public String strFloat16toFloat32(String strData) {
+ return utility.strFloat16toFloat32(strData);
+ }
+ public String str2float16(String strData) {
+ return utility.str2float16(strData);
+ }
+ public float decodeCtesiusTemperature(String strActData, String strCalData) {
+ return utility.decodeCtesiusTemperature(strActData, strCalData);
+ }
+ public float decodeMicronTemperature(int iTag35, String strActData, String strCalData) {
+ return utility.decodeMicronTemperature(iTag35, strActData, strCalData);
+ }
+ public float decodeAsygnTemperature(String string) {
+ return utility.decodeAsygnTemperature(string);
+ }
+ public String temperatureC2F(String strValue) {
+ return utility.temperatureC2F(strValue);
+ }
+ public String temperatureF2C(String strValue) {
+ return utility.temperatureF2C(strValue);
+ }
+ public String getUpcSerial(String strEpc) {
+ return utility.getUpcSerial(strEpc);
+ }
+ public String getUpcSerialDetail(String strUpcSerial) {
+ return utility.getUpcSerialDetail(strUpcSerial);
+ }
+ public String getEpc4upcSerial(Utility.EpcClass epcClass, String filter, String companyPrefix, String itemReference, String serialNumber) {
+ return utility.getEpc4upcSerial(epcClass, filter, companyPrefix, itemReference, serialNumber);
+ }
+ public boolean checkHostProcessorVersion(String version, int majorVersion, int minorVersion, int buildVersion) {
+ return utility.checkHostProcessorVersion(version, majorVersion, minorVersion, buildVersion);
+ }
+
+ //============ android bluetooth ============
+ ArrayList mScanResultList = new ArrayList<>();
+ int check9800_serviceUUID2p1 = 0;
+ boolean deviceConnection = false;
+ ReaderDevice readerDeviceConnect;
+ boolean bNeedReconnect = false;
+ int iConnectStateTimer = 0;
+/*
+ boolean check9800(BluetoothGatt.CsScanData scanResultA) {
+ boolean found98 = false, DEBUG = false;
+ if (DEBUG) appendToLog("decoded data size = " + scanResultA.decoded_scanRecord.size());
+ int iNewADLength = 0;
+ byte[] newAD = new byte[0];
+ int iNewADIndex = 0;
+ check9800_serviceUUID2p1 = -1;
+ if (bluetoothGatt.isBLUETOOTH_CONNECTinvalid()) return true;
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S && ActivityCompat.checkSelfPermission(context, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED)
+ return true;
+ String strTemp = scanResultA.getDevice().getName();
+ if (strTemp != null && DEBUG)
+ appendToLog("Found name = " + strTemp + ", length = " + String.valueOf(strTemp.length()));
+ for (byte bdata : scanResultA.getScanRecord()) {
+ if (iNewADIndex >= iNewADLength && iNewADLength != 0) {
+ scanResultA.decoded_scanRecord.add(newAD);
+ iNewADIndex = 0;
+ iNewADLength = 0;
+ if (DEBUG)
+ appendToLog("Size = " + scanResultA.decoded_scanRecord.size() + ", " + byteArrayToString(newAD));
+ }
+ if (iNewADLength == 0) {
+ iNewADLength = bdata;
+ newAD = new byte[iNewADLength];
+ iNewADIndex = 0;
+ } else newAD[iNewADIndex++] = bdata;
+ }
+ if (DEBUG) appendToLog("decoded data size = " + scanResultA.decoded_scanRecord.size());
+ for (int i = 0; i < scanResultA.decoded_scanRecord.size(); i++) {
+ byte[] currentAD = scanResultA.decoded_scanRecord.get(i);
+ if (DEBUG) appendToLog("Processing decoded data = " + byteArrayToString(currentAD));
+ if (currentAD[0] == 2) {
+ if (DEBUG) appendToLog("Processing UUIDs 02");
+ if ((currentAD[1] == 2) && currentAD[2] == (byte) 0x98) {
+ if (DEBUG) appendToLog("Found 9802");
+ found98 = true;
+ check9800_serviceUUID2p1 = currentAD[1];
+ if (DEBUG) appendToLog("serviceUD1D2p1 = " + check9800_serviceUUID2p1);
+ break;
+ }
+ }
+ }
+ if (found98 == false && DEBUG)
+ appendToLog("No 9800: with scanData = " + byteArrayToString(scanResultA.getScanRecord()));
+ else if (DEBUG_SCAN)
+ appendToLog("Cs710Library4A, Found 9800: with scanData = " + byteArrayToString(scanResultA.getScanRecord()));
+ return found98;
+ }
+*/
+ boolean connect1(ReaderDevice readerDevice) {
+ boolean DEBUG = true;
+ if (DEBUG || DEBUG_CONNECT)
+ appendToLog("Debug_Connect: Cs710Library4A.Connect1 with " + (readerDevice == null ? "null" : "valid") + " readerDevice, " + (readerDeviceConnect == null ? "null" : "valid") + " readerDeviceConnect");
+ if (readerDevice == null && readerDeviceConnect != null) readerDevice = readerDeviceConnect;
+ boolean result = false;
+ if (readerDevice != null) {
+ bNeedReconnect = false;
+ iConnectStateTimer = 0;
+ bluetoothGatt.bDiscoverStarted = false;
+ if (DEBUG) appendToLog("connect1: going to connectBle with " + (readerDevice == null ? "null" : "valid"));
+ bluetoothGatt.setServiceUUIDType(readerDevice.getServiceUUID2p1());
+ appendToLog("Cs710Library4A.connect1 is going to connect");
+ result = csReaderConnector.connect(readerDevice);
+ }
+ if (DEBUG || DEBUG_CONNECT) appendToLog("Debug_Connect: Cs710Library4A.connect1 Result = " + result);
+ return result;
+ }
+ final Runnable connectRunnable = new Runnable() {
+ boolean DEBUG = true;
+
+ @Override
+ public void run() {
+ if (DEBUG || DEBUG_CONNECT) {
+ appendToLog("Debug_Connect: Cs710Library4A.connectRunnable: isBleScanning = " + isBleScanning());
+ appendToLog("Debug_Connect: Cs710Library4A.connectRunnable: bNeedReconnect = " + bNeedReconnect);
+ appendToLog("Debug_Connect, Cs108Library4A.connectRunnable: usbConnectState = " + (csReaderConnector.usbConnector == null ? "null" : csReaderConnector.usbConnector.usbConnectionState));
+ appendToLog("Debug_Connect: Cs710Library4A.connectRunnable: bluetoothConnectionState = " + bluetoothGatt.bluetoothConnectionState);
+ }
+ if (isBleScanning()) {
+ if (DEBUG) appendToLog("Cs710Library4A.connectRunnable: still scanning. Stop scanning first");
+ scanLeDevice(false);
+ } else if (bNeedReconnect) {
+ if (bluetoothGatt.bluetoothGatt != null) {
+ if (DEBUG) appendToLog("Cs710Library4A.connectRunnable: mBluetoothGatt is null before connect. disconnect first");
+ csReaderConnector.disconnect();
+ } else if (readerDeviceConnect == null) {
+ if (DEBUG) appendToLog("Cs710Library4A.connectRunnable: exit with null readerDeviceConnect");
+ return;
+ } else if (bluetoothGatt.bluetoothGatt == null) {
+ if (DEBUG || DEBUG_CONNECT) appendToLog("Debug_Connect, Cs710Library4A.connectRunnable: connect1 starts");
+ connect1(null);
+ bNeedReconnect = false;
+ }
+ } else if (csReaderConnector.usbConnector != null && csReaderConnector.usbConnector.usbConnectionState) return;
+ else if (bluetoothGatt.bluetoothConnectionState == BluetoothProfile.STATE_DISCONNECTED) { //mReaderStreamOutCharacteristic valid around 1500ms
+ iConnectStateTimer = 0;
+ if (DEBUG)
+ appendToLog("Cs710Library4A.connectRunnable: disconnect as disconnected connectionState is received");
+ bNeedReconnect = true;
+ if (DEBUG)
+ appendToLog("Cs710Library4A.connectRunnable: bluetoothGatt is " + (bluetoothGatt.bluetoothGatt != null ? "valid" : "null"));
+ if (bluetoothGatt.bluetoothGatt != null) {
+ if (DEBUG) appendToLog("Cs710Library4A.connectRunnable: disconnect F");
+ csReaderConnector.disconnect();
+ }
+ } else if (bluetoothGatt.mReaderStreamOutCharacteristic == null) {
+ if (DEBUG_CONNECT)
+ appendToLog("Debug_Connect, Cs710Library4A.connectRunnable: wait as not yet discovery, with iConnectStateTimer = " + iConnectStateTimer);
+ if (++iConnectStateTimer > 10) {
+ }
+ } else {
+ if (DEBUG_CONNECT) appendToLog("Debug_Connect, Cs710Library4A.connectRunnable: end of ConnectRunnable");
+ return;
+ }
+ mHandler.postDelayed(connectRunnable, 500);
+ }
+ };
+ final Runnable disconnectRunnable = new Runnable() {
+ @Override
+ public void run() {
+ if (barcodeConnector == null) return;
+ appendToLog("abcc disconnectRunnable with barcodeToWrite.size = " + barcodeConnector.barcodeToWrite.size());
+ if (barcodeConnector.barcodeToWrite.size() != 0)
+ mHandler.postDelayed(disconnectRunnable, 100);
+ else {
+ appendToLog("disconnect G");
+ csReaderConnector.disconnect();
+ }
+ }
+ };
+ public boolean isBleScanning() {
+ return bluetoothGatt.isScanning();
+ }
+ public boolean scanLeDevice(boolean enable) {
+ boolean DEBUG = true;
+ if (enable) mHandler.removeCallbacks(connectRunnable);
+
+ if (DEBUG || DEBUG_SCAN) appendToLog("Cs710Library4A.scanLeDevice[" + enable + "]");
+ if (bluetoothGatt.bluetoothDeviceConnectOld != null) {
+ if (DEBUG) appendToLog("Cs710Library4A.scanLeDevice: bluetoothDeviceConnectOld connection state = " + bluetoothGatt.bluetoothManager.getConnectionState(bluetoothGatt.bluetoothDeviceConnectOld, BluetoothProfile.GATT));
+ }
+ if (enable && csReaderConnector.usbConnector != null) csReaderConnector.usbConnector.scanDevice(enable);
+ boolean bValue = bluetoothGatt.scanDevice(enable, csReaderConnector.mLeScanCallback, csReaderConnector.mScanCallback);
+ if (DEBUG || DEBUG_SCAN) appendToLog("Cs710Library4A.scanLeDevice: isScanning = " + isBleScanning());
+ return bValue;
+ }
+ public BluetoothGatt.CsScanData getNewDeviceScanned() {
+ return csReaderConnector.getNewDeviceScanned();
+/*
+ if (mScanResultList.size() != 0) {
+ if (DEBUG_SCAN) appendToLog("mScanResultList.size() = " + mScanResultList.size());
+ BluetoothGatt.CsScanData csScanData = mScanResultList.get(0); mScanResultList.remove(0);
+ return csScanData;
+ } else return null;
+*/
+ }
+ public String getBluetoothDeviceAddress() {
+ if (bluetoothGatt.getReaderDeviceConnected() == null) return null;
+ return bluetoothGatt.getReaderDeviceConnected().getAddress();
+ }
+ public String getBluetoothDeviceName() {
+ if (bluetoothGatt.getReaderDeviceConnected() == null) return null;
+ return bluetoothGatt.getReaderDeviceConnected().getName();
+ }
+ public boolean isBleConnected() {
+ boolean DEBUG = false;
+ boolean deviceConnectionNew = csReaderConnector.isConnected();
+ if (DEBUG && false) appendToLog("Cs710Library4A.isBleConnected: ConnectionNew = " + deviceConnectionNew + ", connection = " + deviceConnection);
+ if (DEBUG && false) appendToLog("Cs710Library4A.isBleConnected: rfidReader is " + (csReaderConnector.rfidReader == null ? "null" : "valid"));
+ if (DEBUG && csReaderConnector.rfidReader != null) appendToLog("Cs710Library4A.isBleConnected: bFirmware_reset_before is " + csReaderConnector.rfidReader.bFirmware_reset_before);
+ if (deviceConnectionNew) {
+ if (deviceConnection == false) {
+ deviceConnection = deviceConnectionNew;
+ if (DEBUG || DEBUG_CONNECT) appendToLog("Debug_Connect, Cs710Library4A.isBleConnected: Newly connected");
+
+ csReaderConnector.csConnectorDataInit();
+ barcodeNewland = csReaderConnector.barcodeNewland;
+ barcodeConnector = csReaderConnector.barcodeConnector;
+ notificationConnector = csReaderConnector.notificationConnector;
+ controllerConnector = csReaderConnector.controllerConnector;
+ bluetoothConnector = csReaderConnector.bluetoothConnector;
+
+ setRfidOn(true);
+ setBarcodeOn(true);
+ //hostProcessorICGetFirmwareVersion();
+ getBluetoothICFirmwareVersion();
+ csReaderConnector.rfidReader.channelOrderType = -1;
+ {
+ // getBarcodePreSuffix();
+ // getBarcodeReadingMode();
+ // getBarcodeSerial();
+ //getBarcodeNoDuplicateReading();
+ //getBarcodeDelayTimeOfEachReading();
+ //getBarcodeEnable2dBarCodes();
+ //getBarcodePrefixOrder();
+ //getBarcodeVersion();
+ //barcodeSendCommandLoadUserDefault();
+ //barcodeSendQuerySystem();
+ // barcodeNewland.barcodeSendCommandItf14Cksum();
+
+ notificationConnector.setBatteryAutoReport(true); //0xA003
+ }
+ abortOperation();
+ //getHostProcessorICSerialNumber(); //0xb004 (but access Oem as bluetooth version is not got)
+ getMacVer();
+ csReaderConnector.rfidReader.getReaderDefault();
+ csReaderConnector.rfidReader.regionCode = null;
+ getModelNumber();
+ getCountryCode();
+ //getSerialNumber();
+ getQueryTarget();
+ csReaderConnector.rfidReader.getImpinjExtension();
+ csReaderConnector.rfidReader.getInvAlgoInChip();
+ if (DEBUG || DEBUG_CONNECT) appendToLog("Debug_Connect, Cs710Library4A.isBleConnected: Start checkVersionRunnable");
+ mHandler.postDelayed(checkVersionRunnable, 500);
+
+ if (csReaderConnector.settingData.strForegroundReader.trim().length() != 0) {
+ csReaderConnector.settingData.strForegroundReader = bluetoothGatt.getReaderDeviceConnected().getAddress();
+ }
+ csReaderConnector.settingData.saveForegroundSetting2File();
+ } else if (csReaderConnector.rfidReader == null) {
+ deviceConnection = false;
+ appendToLog("Cs710Library4A.isBleConnected: csReaderConnector.rfidReader is NULL");
+ } else if (csReaderConnector.rfidReader.bFirmware_reset_before) {
+ csReaderConnector.rfidReader.bFirmware_reset_before = false;
+ mHandler.postDelayed(reinitaliseDataRunnable, 500);
+ }
+ } else if (deviceConnection) {
+ barcodeNewland = null; barcodeConnector = null;
+ notificationConnector = null;
+ controllerConnector = null;
+ bluetoothConnector = null;
+ deviceConnection = deviceConnectionNew;
+ if (DEBUG) appendToLog("Cs710Library4A.isBleConnected: Newly disconnected");
+ }
+ return(deviceConnection);
+ }
+ public void connect(ReaderDevice readerDevice) {
+ if (isBleConnected()) return;
+ if (bluetoothGatt.bluetoothGatt != null) csReaderConnector.disconnect();
+ if (readerDevice != null) readerDeviceConnect = readerDevice;
+ mHandler.removeCallbacks(connectRunnable);
+ bNeedReconnect = true; mHandler.post(connectRunnable);
+ if (DEBUG_CONNECT) appendToLog("Debug_Connect: Cs710Library4A.connect Start ConnectRunnable");
+ }
+ public void disconnect(boolean tempDisconnect) {
+ appendToLog("abcc tempDisconnect: getBarcodeOnStatus = " + (getBarcodeOnStatus() ? "on" : "off"));
+ if (DEBUG) appendToLog("tempDisconnect = " + tempDisconnect);
+ mHandler.removeCallbacks(checkVersionRunnable);
+ mHandler.removeCallbacks(runnableToggleConnection);
+ if (getBarcodeOnStatus()) {
+ appendToLog("tempDisconnect: setBarcodeOn(false)");
+ if (barcodeConnector.barcodeToWrite.size() != 0) {
+ appendToLog("going to disconnectRunnable with remaining barcodeToWrite.size = " + barcodeConnector.barcodeToWrite.size() + ", data = " + byteArrayToString(barcodeConnector.barcodeToWrite.get(0).dataValues));
+ }
+ barcodeConnector.barcodeToWrite.clear(); appendToLog("barcodeToWrite is clear");
+ setBarcodeOn(false);
+ setRfidOn(false);
+ } else appendToLog("tempDisconnect: getBarcodeOnStatus is false");
+ mHandler.postDelayed(disconnectRunnable, 100);
+ appendToLog("done with tempDisconnect = " + tempDisconnect);
+ if (tempDisconnect == false) {
+ mHandler.removeCallbacks(connectRunnable);
+ bluetoothGatt.bluetoothDeviceConnectOld = null;
+ if (readerDeviceConnect != null) bluetoothGatt.bluetoothDeviceConnectOld = bluetoothGatt.bluetoothAdapter.getRemoteDevice(readerDeviceConnect.getAddress());
+ readerDeviceConnect = null;
+ }
+ }
+ public boolean forceBTdisconnect() {
+ return bluetoothConnector.forceBTdisconnect();
+ }
+ public int getRssi() {
+ return bluetoothGatt.getRssi();
+ }
+ boolean getConnectionHSpeed() {
+ return bluetoothGatt.getConnectionHSpeedA();
+ }
+ boolean setConnectionHSpeed(boolean on) {
+ return bluetoothGatt.setConnectionHSpeedA(on);
+ }
+ public long getStreamInRate() {
+ return csReaderConnector.getStreamInRate();
+ }
+ public int get98XX() {
+ return 2;
+ }
+
+ //============ Rfid ============
+ //============ Rfid ============
+ //============ Rfid ============
+
+ boolean setInvAlgoNoSave(boolean dynamicAlgo) {
+ return csReaderConnector.rfidReader.setInvAlgoNoSave(dynamicAlgo);
+ }
+ boolean setInvAlgo1(boolean dynamicAlgo) {
+ return csReaderConnector.rfidReader.setInvAlgo1(dynamicAlgo);
+ }
+ public String getAuthMatchData() {
+ return csReaderConnector.rfidReader.getAuthMatchData();
+ }
+ public boolean setAuthMatchData(String mask) {
+ return csReaderConnector.rfidReader.setAuthMatchData(mask);
+ }
+ public int getStartQValue() {
+ return csReaderConnector.rfidReader.getStartQValue();
+ }
+ public int getMaxQValue() {
+ return csReaderConnector.rfidReader.getMaxQValue();
+ }
+ public int getMinQValue() {
+ return csReaderConnector.rfidReader.getMinQValue();
+ }
+ public boolean setDynamicQParms(int startQValue, int minQValue, int maxQValue, int retryCount) {
+ return csReaderConnector.rfidReader.setDynamicQParms(startQValue, minQValue, maxQValue, retryCount);
+ }
+ public int getFixedQValue() {
+ return csReaderConnector.rfidReader.getFixedQValue();
+ }
+ public int getFixedRetryCount() {
+ return csReaderConnector.rfidReader.getFixedRetryCount();
+ }
+ public boolean getRepeatUnitNoTags() {
+ return csReaderConnector.rfidReader.getRepeatUnitNoTags();
+ }
+ public boolean setFixedQParms(int qValue, int retryCount, boolean repeatUnitNoTags) {
+ return csReaderConnector.rfidReader.setFixedQParms(qValue, retryCount, repeatUnitNoTags);
+ }
+ RegionCodes[] getRegionList() {
+ return csReaderConnector.rfidReader.getRegionList();
+ }
+ boolean toggledConnection = false;
+ Runnable runnableToggleConnection = new Runnable() {
+ @Override
+ public void run() {
+ if (DEBUG) appendToLog("runnableToggleConnection(): toggledConnection = " + toggledConnection + ", isBleConnected() = " + isBleConnected());
+ if (isBleConnected() == false) toggledConnection = true;
+ if (toggledConnection) {
+ if (isBleConnected() == false) {
+ if (connect1(null) == false) return;
+ } else return;
+ } else { appendToLog("disconnect H"); csReaderConnector.disconnect(); appendToLog("done"); }
+ mHandler.postDelayed(runnableToggleConnection, 500);
+ }
+ };
+ public boolean getChannelHoppingDefault() {
+ return csReaderConnector.rfidReader.getChannelHoppingDefault();
+ }
+ int getCountryCode() {
+ return csReaderConnector.rfidReader.getCountryCode();
+ }
+ int getFreqModifyCode() {
+ return csReaderConnector.rfidReader.getFreqModifyCode();
+ }
+ public boolean getRfidOnStatus() {
+ return csReaderConnector.rfidReader.getRfidOnStatus();
+ }
+ public boolean isRfidFailure() {
+ //appendToLog("BtDataOut: isRfidFailure rfidReader is " + (csReaderConnector.rfidReader == null ? "null" : csReaderConnector.rfidReader.isRfidFailure()));
+ if (csReaderConnector.rfidReader == null) return false;
+ return csReaderConnector.rfidReader.isRfidFailure();
+ }
+ public void setReaderDefault() {
+ csReaderConnector.rfidReader.setReaderDefault();
+ String string = bluetoothGatt.getReaderDeviceConnected().getAddress();
+ string = string.replaceAll("[^a-zA-Z0-9]","");
+ string = string.substring(string.length()-6, string.length());
+ setBluetoothICFirmwareName("CS710Sreader" + string);
+ //getlibraryVersion()
+ if (false) {
+ setCountryInList(csReaderConnector.rfidReader.countryInListDefault);
+ setChannel(0);
+
+ //getAntennaPower(0)
+ //getPopulation()
+ //getQuerySession()
+ //getQueryTarget()
+ setTagFocus(false);
+ setFastId(false);
+ //getInvAlgo()
+ //\\getRetryCount()
+ //getCurrentProfile() + "\n"));
+ //\\getRxGain() + "\n"));
+ }
+ //getBluetoothICFirmwareName() + "\n");
+ setTagDelay(csReaderConnector.rfidReader.tagDelaySettingDefault);
+ setCycleDelay((long)0);
+ setIntraPkDelay((byte)4);
+ setDupDelay((byte)0);
+
+ setBatteryDisplaySetting(csReaderConnector.settingData.batteryDisplaySelectDefault);
+ setRssiDisplaySetting(csReaderConnector.settingData.rssiDisplaySelectDefault);
+ setTriggerReporting(csReaderConnector.settingData.triggerReportingDefault);
+ setTriggerReportingCount(csReaderConnector.settingData.triggerReportingCountSettingDefault);
+ setInventoryBeep(csReaderConnector.settingData.inventoryBeepDefault);
+ setBeepCount(csReaderConnector.settingData.beepCountSettingDefault);
+ setInventoryVibrate(csReaderConnector.settingData.inventoryVibrateDefault);
+ setVibrateTime(csReaderConnector.settingData.vibrateTimeSettingDefault);
+ setVibrateModeSetting(csReaderConnector.settingData.vibrateModeSelectDefault);
+ setVibrateWindow(csReaderConnector.settingData.vibrateWindowSettingDefault);
+
+ setSavingFormatSetting(csReaderConnector.settingData.savingFormatSelectDefault);
+ setCsvColumnSelectSetting(csReaderConnector.settingData.csvColumnSelectDefault);
+ setSaveFileEnable(csReaderConnector.settingData.saveFileEnableDefault);
+ setSaveCloudEnable(csReaderConnector.settingData.saveCloudEnableDefault);
+ setSaveNewCloudEnable(csReaderConnector.settingData.saveNewCloudEnableDefault);
+ setSaveAllCloudEnable(csReaderConnector.settingData.saveAllCloudEnableDefault);
+ setServerLocation(csReaderConnector.settingData.serverLocationDefault);
+ setServerTimeout(csReaderConnector.settingData.serverTimeoutDefault);
+ csReaderConnector.settingData.barcode2TriggerMode = csReaderConnector.settingData.barcode2TriggerModeDefault;
+
+ setUserDebugEnable(csReaderConnector.settingData.userDebugEnableDefault);
+ csReaderConnector.settingData.preFilterData = null;
+ }
+ public String getMacVer() {
+ appendToLog("Cs710Library4A.getMacVer");
+ return csReaderConnector.rfidReader.getMacVer();
+ }
+ public String getRadioSerial() {
+ return csReaderConnector.rfidReader.getRadioSerial();
+ }
+ public String getRadioBoardVersion() {
+ return csReaderConnector.rfidReader.getRadioBoardVersion();
+ }
+ public int getPortNumber() {
+ if (bluetoothConnector.getCsModel() == 463) return 4;
+ else return 1;
+ }
+ public int getAntennaSelect() {
+ return csReaderConnector.rfidReader.getAntennaSelect();
+ }
+ public boolean setAntennaSelect(int number) {
+ return csReaderConnector.rfidReader.setAntennaSelect(number);
+ }
+ public boolean getAntennaEnable() {
+ return csReaderConnector.rfidReader.getAntennaEnable();
+ }
+ public boolean setAntennaEnable(boolean enable) {
+ return csReaderConnector.rfidReader.setAntennaEnable(enable);
+ }
+ public long getAntennaDwell() {
+ return csReaderConnector.rfidReader.getAntennaDwell();
+ }
+ public boolean setAntennaDwell(long antennaDwell) {
+ return csReaderConnector.rfidReader.setAntennaDwell(antennaDwell);
+ }
+ public long getPwrlevel() {
+ return csReaderConnector.rfidReader.getPwrlevel();
+ }
+ public boolean setPowerLevel(long pwrlevel) {
+ return csReaderConnector.rfidReader.setPowerLevel(pwrlevel);
+ }
+ public int getQueryTarget() {
+ return csReaderConnector.rfidReader.getQueryTarget();
+ }
+ public int getQuerySession() {
+ return csReaderConnector.rfidReader.getQuerySession();
+ }
+ public int getQuerySelect() {
+ return csReaderConnector.rfidReader.getQuerySelect();
+ }
+ public boolean setTagGroup(int sL, int session, int target1) {
+ return csReaderConnector.rfidReader.setTagGroup(sL, session, target1);
+ }
+ public int getTagFocus() {
+ return csReaderConnector.rfidReader.getTagFocus();
+ }
+ public boolean setTagFocus(boolean tagFocusNew) {
+ return csReaderConnector.rfidReader.setTagFocus(tagFocusNew);
+ }
+ public int getFastId() {
+ return csReaderConnector.rfidReader.getFastId();
+ }
+ public boolean setFastId(boolean fastIdNew) {
+ appendToLog("bFastId: setFastId[" + fastIdNew);
+ return csReaderConnector.rfidReader.setFastId(fastIdNew);
+ }
+ public boolean getInvAlgo() {
+ return csReaderConnector.rfidReader.getInvAlgo();
+ }
+ public boolean setInvAlgo(boolean dynamicAlgo) {
+ return csReaderConnector.rfidReader.setInvAlgo(dynamicAlgo);
+ }
+ public List getProfileList() {
+ return csReaderConnector.rfidReader.getProfileList();
+ }
+ public int getCurrentProfile() {
+ return csReaderConnector.rfidReader.getCurrentProfile();
+ }
+ public boolean setBasicCurrentLinkProfile() {
+ return csReaderConnector.rfidReader.setBasicCurrentLinkProfile();
+ }
+ public boolean setCurrentLinkProfile(int profile) {
+ return csReaderConnector.rfidReader.setCurrentLinkProfile(profile);
+ }
+ public void resetEnvironmentalRSSI() {
+ csReaderConnector.rfidReader.resetEnvironmentalRSSI();
+ }
+ public String getEnvironmentalRSSI() {
+ return csReaderConnector.rfidReader.getEnvironmentalRSSI();
+ }
+ public int getHighCompression() {
+ return csReaderConnector.rfidReader.getHighCompression();
+ }
+ public int getRflnaGain() {
+ return csReaderConnector.rfidReader.getRflnaGain();
+ }
+ public int getIflnaGain() {
+ return csReaderConnector.rfidReader.getIflnaGain();
+ }
+ public int getAgcGain() {
+ return csReaderConnector.rfidReader.getAgcGain();
+ }
+ public int getRxGain() {
+ return csReaderConnector.rfidReader.getRxGain();
+ }
+ public boolean setRxGain(int highCompression, int rflnagain, int iflnagain, int agcgain) {
+ return csReaderConnector.rfidReader.setRxGain(highCompression, rflnagain, iflnagain, agcgain);
+ }
+ public boolean setRxGain(int rxGain) {
+ return csReaderConnector.rfidReader.setRxGain(rxGain);
+ }
+ public int FreqChnCnt() {
+ return csReaderConnector.rfidReader.FreqChnCnt(csReaderConnector.rfidReader.regionCode);
+ }
+ public double getLogicalChannel2PhysicalFreq(int channel) {
+ return csReaderConnector.rfidReader.getLogicalChannel2PhysicalFreq(channel);
+ }
+ public byte getTagDelay() {
+ return csReaderConnector.rfidReader.getTagDelay();
+ }
+ public boolean setTagDelay(byte tagDelay) {
+ return csReaderConnector.rfidReader.setTagDelay(tagDelay);
+ }
+ public byte getIntraPkDelay() {
+ return csReaderConnector.rfidReader.getIntraPkDelay();
+ }
+ public boolean setIntraPkDelay(byte intraPkDelay) {
+ return csReaderConnector.rfidReader.setIntraPkDelay(intraPkDelay);
+ }
+ public byte getDupDelay() {
+ return csReaderConnector.rfidReader.getDupDelay();
+ }
+ public boolean setDupDelay(byte dupElim) {
+ return csReaderConnector.rfidReader.setDupDelay(dupElim);
+ }
+ public long getCycleDelay() {
+ return csReaderConnector.rfidReader.getCycleDelay();
+ }
+ public boolean setCycleDelay(long cycleDelay) {
+ return csReaderConnector.rfidReader.setCycleDelay(cycleDelay);
+ }
+ public void getAuthenticateReplyLength() {
+ csReaderConnector.rfidReader.getAuthenticateReplyLength();
+ }
+ public boolean setTamConfiguration(boolean header, String matchData) {
+ return csReaderConnector.rfidReader.setTamConfiguration(header, matchData);
+ }
+ public boolean setTam1Configuration(int keyId, String matchData) {
+ return csReaderConnector.rfidReader.setTam1Configuration(keyId, matchData);
+ }
+ public boolean setTam2Configuration(int keyId, String matchData, int profile, int offset, int blockId, int protMode) {
+ return csReaderConnector.rfidReader.setTam2Configuration(keyId, matchData, profile, offset, blockId, protMode);
+ }
+ public int getUntraceableEpcLength() {
+ return csReaderConnector.rfidReader.getUntraceableEpcLength();
+ }
+ public boolean setUntraceable(boolean bHideEpc, int ishowEpcSize, int iHideTid, boolean bHideUser, boolean bHideRange) {
+ return csReaderConnector.rfidReader.setUntraceable(bHideEpc, ishowEpcSize, iHideTid, bHideUser, bHideRange);
+ }
+ public boolean setUntraceable(int range, boolean user, int tid, int epcLength, boolean epc, boolean uxpc) {
+ return csReaderConnector.rfidReader.setUntraceable(range, user, tid, epcLength, epc, uxpc);
+ }
+ public boolean setAuthenticateConfiguration() {
+ return csReaderConnector.rfidReader.setAuthenticateConfiguration();
+ }
+ public int getRetryCount() {
+ return csReaderConnector.rfidReader.getRetryCount();
+ }
+ public boolean setRetryCount(int retryCount) {
+ return csReaderConnector.rfidReader.setRetryCount(retryCount);
+ }
+ public int getInvSelectIndex() {
+ return csReaderConnector.rfidReader.getInvSelectIndex();
+ }
+ public boolean getSelectEnable() {
+ return csReaderConnector.rfidReader.getSelectEnable();
+ }
+ public int getSelectTarget() {
+ return csReaderConnector.rfidReader.getSelectTarget();
+ }
+ public int getSelectAction() {
+ return csReaderConnector.rfidReader.getSelectAction();
+ }
+ public int getSelectMaskBank() {
+ return csReaderConnector.rfidReader.getSelectMaskBank();
+ }
+ public int getSelectMaskOffset() {
+ return csReaderConnector.rfidReader.getSelectMaskOffset();
+ }
+ public String getSelectMaskData() {
+ return csReaderConnector.rfidReader.getSelectMaskData();
+ }
+ public boolean setInvSelectIndex(int invSelect) {
+ return csReaderConnector.rfidReader.setInvSelectIndex(invSelect);
+ }
+ public boolean setSelectCriteriaDisable(int index) {
+ if (utility.DEBUG_SELECT) appendToLog("Debug_Select: Cs710Library4A.setSelectCriteriaDisable[" + index + "] goes to setSelectCriteriaDisable");
+ return csReaderConnector.rfidReader.setSelectCriteriaDisable(index);
+ }
+ int findFirstEmptySelect() {
+ return csReaderConnector.rfidReader.findFirstEmptySelect();
+ }
+ public boolean setSelectCriteria(int index, boolean enable, int target, int action, int bank, int offset, String mask, boolean maskbit) {
+ return csReaderConnector.rfidReader.setSelectCriteria(index, enable, target, action, bank, offset, mask, maskbit);
+ }
+ public boolean setSelectCriteria(int index, boolean enable, int target, int action, int delay, int bank, int offset, String mask) {
+ return csReaderConnector.rfidReader.setSelectCriteria(index, enable, target, action, delay, bank, offset, mask);
+ }
+ public boolean getRssiFilterEnable() {
+ return csReaderConnector.rfidReader.getRssiFilterEnable();
+ }
+ public int getRssiFilterType() {
+ return csReaderConnector.rfidReader.getRssiFilterType();
+ }
+ public int getRssiFilterOption() {
+ return csReaderConnector.rfidReader.getRssiFilterOption();
+ }
+ public boolean setRssiFilterConfig(boolean enable, int rssiFilterType, int rssiFilterOption) {
+ return csReaderConnector.rfidReader.setRssiFilterConfig(enable, rssiFilterType, rssiFilterOption);
+ }
+ public double getRssiFilterThreshold1() {
+ return csReaderConnector.rfidReader.getRssiFilterThreshold1();
+ }
+ public double getRssiFilterThreshold2() {
+ return csReaderConnector.rfidReader.getRssiFilterThreshold2();
+ }
+ public boolean setRssiFilterThreshold(double rssiFilterThreshold1, double rssiFilterThreshold2) {
+ return csReaderConnector.rfidReader.setRssiFilterThreshold(rssiFilterThreshold1, rssiFilterThreshold2);
+ }
+ public long getRssiFilterCount() {
+ return csReaderConnector.rfidReader.getRssiFilterCount();
+ }
+ public boolean setRssiFilterCount(long rssiFilterCount) {
+ return csReaderConnector.rfidReader.setRssiFilterCount(rssiFilterCount);
+ }
+ public boolean getInvMatchEnable() {
+ return csReaderConnector.rfidReader.getInvMatchEnable();
+ }
+ public boolean getInvMatchType() {
+ return csReaderConnector.rfidReader.getInvMatchType();
+ }
+ public int getInvMatchOffset() {
+ return csReaderConnector.rfidReader.getInvMatchOffset();
+ }
+ public String getInvMatchData() {
+ return csReaderConnector.rfidReader.getInvMatchData();
+ }
+ public boolean setPostMatchCriteria(boolean enable, boolean target, int offset, String mask) {
+ return csReaderConnector.rfidReader.setPostMatchCriteria(enable, target, offset, mask);
+ }
+ public int mrfidToWriteSize() {
+ if (isBleConnected() == false) return -1;
+ if (csReaderConnector.rfidReader == null) return -1;
+ return csReaderConnector.rfidReader.rfidToWriteSize();
+ }
+ public void mrfidToWritePrint() {
+ if (true) { csReaderConnector.rfidReader.rfidToWriteSize(); return; }
+ for (int i = 0; i < csReaderConnector.rfidReader.mRfidToWrite.size(); i++) {
+ appendToLog(byteArrayToString(csReaderConnector.rfidReader.mRfidToWrite.get(i).dataValues));
+ }
+ }
+ public long getTagRate() {
+ return csReaderConnector.rfidReader.getTagRate();
+ }
+ public boolean startOperation(RfidReaderChipData.OperationTypes operationTypes) {
+ return csReaderConnector.rfidReader.startOperation(operationTypes);
+ }
+ public boolean abortOperation() {
+ return csReaderConnector.rfidReader.abortOperation();
+ }
+ public void restoreAfterTagSelect() {
+ if (!isBleConnected()) return;
+ if (utility.DEBUG_SELECT) appendToLog("Debug_Select: Cs710Library4A.restoreAfterTagSelect goes to setSelectCriteriaDisable");
+ setSelectCriteriaDisable(0); setSelectCriteriaDisable(1); setSelectCriteriaDisable(2);
+ loadSetting1File();
+ setAccessCount(0);
+ setRx000AccessPassword("00000000");
+ if (true) {
+ setMatchRep(0);
+ setTagDelay(csReaderConnector.rfidReader.tagDelaySetting);
+ setCycleDelay(csReaderConnector.rfidReader.cycleDelaySetting);
+ setInvModeCompact(true);
+ }
+ if (csReaderConnector.rfidReader.postMatchDataChanged) {
+ csReaderConnector.rfidReader.postMatchDataChanged = false;
+ setPostMatchCriteria(csReaderConnector.rfidReader.postMatchDataOld.enable, csReaderConnector.rfidReader.postMatchDataOld.target, csReaderConnector.rfidReader.postMatchDataOld.offset, csReaderConnector.rfidReader.postMatchDataOld.mask);
+ appendToLog("PowerLevel");
+ setPowerLevel(csReaderConnector.rfidReader.postMatchDataOld.pwrlevel);
+ appendToLog("writeBleStreamOut: invAlgo = " + csReaderConnector.rfidReader.postMatchDataOld.invAlgo); setInvAlgo1(csReaderConnector.rfidReader.postMatchDataOld.invAlgo);
+ setQValue1(csReaderConnector.rfidReader.postMatchDataOld.qValue);
+ }
+ }
+ public boolean setSelectedTagByTID(String strTagId, long pwrlevel) {
+ return csReaderConnector.rfidReader.setSelectedTagByTID(strTagId, pwrlevel);
+ }
+ public boolean setSelectedTag(String strTagId, int selectBank, long pwrlevel) {
+ return csReaderConnector.rfidReader.setSelectedTag(strTagId, selectBank, pwrlevel);
+ }
+ public boolean setSelectedTag(String selectMask, int selectBank, int selectOffset, long pwrlevel, int qValue, int matchRep) {
+ return csReaderConnector.rfidReader.setSelectedTag4Access(false, selectMask, selectBank, selectOffset, pwrlevel, qValue, matchRep);
+ }
+ public boolean setMatchRep(int matchRep) {
+ if (utility.DEBUG_INVCFG) appendToLog("Debug_InvCfg: Cs710Library4A.setMatchRep goes to setMatchRep with matchRep = " + matchRep);
+ return csReaderConnector.rfidReader.setMatchRep(matchRep);
+ }
+ public String[] getCountryList() {
+ return csReaderConnector.rfidReader.getCountryList();
+ }
+ public int getCountryNumberInList() {
+ return csReaderConnector.rfidReader.countryInList;
+ }
+ public boolean setCountryInList(int countryInList) {
+ return csReaderConnector.rfidReader.setCountryInList(countryInList);
+ }
+ public boolean getChannelHoppingStatus() {
+ return csReaderConnector.rfidReader.getChannelHoppingStatus();
+ }
+ public boolean setChannelHoppingStatus(boolean channelOrderHopping) {
+ return csReaderConnector.rfidReader.setChannelHoppingStatus(channelOrderHopping);
+ }
+ public String[] getChannelFrequencyList() {
+ return csReaderConnector.rfidReader.getChannelFrequencyList();
+ }
+ public int getChannel() {
+ return csReaderConnector.settingData.channel;
+ }
+ public boolean setChannel(int channelSelect) {
+ return csReaderConnector.rfidReader.setChannel(channelSelect);
+ }
+ public byte getPopulation2Q(int population) {
+ return csReaderConnector.rfidReader.getPopulation2Q(population);
+ }
+ public int getPopulation() {
+ return csReaderConnector.rfidReader.getPopulation();
+ }
+ public boolean setPopulation(int population) {
+ return csReaderConnector.rfidReader.setPopulation(population);
+ }
+ public byte getQValue() {
+ return csReaderConnector.rfidReader.qValueSetting;
+ }
+ public boolean setQValue(byte byteValue) {
+ return csReaderConnector.rfidReader.setQValue(byteValue);
+ }
+ int getQValue1() {
+ return csReaderConnector.rfidReader.getQValue();
+ }
+ boolean setQValue1(int iValue) {
+ return csReaderConnector.rfidReader.setQValue1(iValue);
+ }
+ public RfidReaderChipData.Rx000pkgData onRFIDEvent() {
+ return csReaderConnector.rfidReader.onRFIDEvent();
+ }
+ public String getModelNumber() {
+ return csReaderConnector.rfidReader.getModelNumber(getModelName());
+ }
+ public boolean setRx000KillPassword(String password) {
+ return csReaderConnector.rfidReader.setRx000KillPassword(password);
+ }
+ public boolean setRx000AccessPassword(String password) {
+ return csReaderConnector.rfidReader.setRx000AccessPassword(password);
+ }
+ public boolean setAccessRetry(boolean accessVerfiy, int accessRetry) {
+ return csReaderConnector.rfidReader.setAccessRetry(accessVerfiy, accessRetry);
+ }
+ public boolean setInvModeCompact(boolean invModeCompact) {
+ if (utility.DEBUG_COMPACT) appendToLog("Debug_Compact: Cs710Library4A.setInvModeCompact goes to setInvModeCompact");
+ return csReaderConnector.rfidReader.setInvModeCompact(invModeCompact);
+ }
+ public boolean setAccessLockAction(int accessLockAction, int accessLockMask) {
+ return csReaderConnector.rfidReader.setAccessLockAction(accessLockAction, accessLockMask);
+ }
+ public boolean setAccessBank(int accessBank) {
+ return csReaderConnector.rfidReader.setAccessBank(accessBank);
+ }
+ public boolean setAccessBank(int accessBank, int accessBank2) {
+ return csReaderConnector.rfidReader.setAccessBank(accessBank, accessBank2);
+ }
+ public boolean setAccessOffset(int accessOffset) {
+ return csReaderConnector.rfidReader.setAccessOffset(accessOffset);
+ }
+ public boolean setAccessOffset(int accessOffset, int accessOffset2) {
+ return csReaderConnector.rfidReader.setAccessOffset(accessOffset, accessOffset2);
+ }
+ public boolean setAccessCount(int accessCount) {
+ return csReaderConnector.rfidReader.setAccessCount(accessCount);
+ }
+ public boolean setAccessCount(int accessCount, int accessCount2) {
+ return csReaderConnector.rfidReader.setAccessCount(accessCount, accessCount2);
+ }
+ public boolean setAccessWriteData(String dataInput) {
+ return csReaderConnector.rfidReader.setAccessWriteData(dataInput);
+ }
+ public boolean setResReadNoReply(boolean resReadNoReply) {
+ return csReaderConnector.rfidReader.setResReadNoReply(resReadNoReply);
+ }
+ public boolean setTagRead(int tagRead) {
+ return csReaderConnector.rfidReader.setTagRead(tagRead);
+ }
+ public boolean setInvBrandId(boolean invBrandId) {
+ return csReaderConnector.rfidReader.setInvBrandId(invBrandId);
+ }
+ public boolean setInvAuthenticate(boolean invAuthenticate) {
+ return csReaderConnector.rfidReader.setInvAuthenticate(invAuthenticate);
+ }
+ public boolean sendHostRegRequestHST_CMD(RfidReaderChipData.HostCommands hostCommand) {
+ if (true) setInvModeCompact(false);
+ return csReaderConnector.rfidReader.sendHostRegRequestHST_CMD(hostCommand);
+ }
+ public boolean setPwrManagementMode(boolean bLowPowerStandby) {
+ if (isBleConnected() == false) return false;
+ return csReaderConnector.rfidReader.setPwrManagementMode(bLowPowerStandby);
+ }
+ public void macWrite(int address, long value) {
+ csReaderConnector.rfidReader.macWrite(address, value);
+ }
+ public void set_fdCmdCfg(int value) {
+ csReaderConnector.rfidReader.set_fdRegAddr(value);
+ }
+ public void set_fdRegAddr(int addr) {
+ csReaderConnector.rfidReader.set_fdRegAddr(addr);
+ }
+ public void set_fdWrite(int addr, long value) {
+ csReaderConnector.rfidReader.set_fdWrite(addr, value);
+ }
+ public void set_fdPwd(int value) {
+ csReaderConnector.rfidReader.set_fdPwd(value);
+ }
+ public void set_fdBlockAddr4GetTemperature(int addr) {
+ csReaderConnector.rfidReader.set_fdBlockAddr4GetTemperature(addr);
+ }
+ public void set_fdReadMem(int addr, long len) {
+ csReaderConnector.rfidReader.set_fdReadMem(addr, len);
+ }
+ public void set_fdWriteMem(int addr, int len, long value) {
+ csReaderConnector.rfidReader.set_fdWriteMem(addr, len, value);
+ }
+ public void setImpinJExtension(boolean tagFocus, boolean fastId) {
+ csReaderConnector.rfidReader.setImpinJExtension(tagFocus, fastId);
+ }
+
+ //============ Barcode ============
+ public void getBarcodePreSuffix() {
+ barcodeNewland.getBarcodePreSuffix();
+ }
+ public void getBarcodeReadingMode() {
+ barcodeNewland.barcodeSendQueryReadingMode();
+ }
+ void getBarcodeEnable2dBarCodes() {
+ barcodeNewland.barcodeSendQueryEnable2dBarCodes();
+ }
+ void getBarcodePrefixOrder() {
+ barcodeNewland.barcodeSendQueryPrefixOrder();
+ }
+ void getBarcodeDelayTimeOfEachReading() {
+ barcodeNewland.barcodeSendQueryDelayTimeOfEachReading();
+ }
+ void getBarcodeNoDuplicateReading() {
+ barcodeNewland.barcodeSendQueryNoDuplicateReading();
+ }
+
+ public boolean isBarcodeFailure() {
+ if (barcodeConnector == null) return false;
+ return barcodeConnector.barcodeFailure;
+ }
+ public String getBarcodeDate() {
+ return barcodeNewland.getBarcodeDate();
+ }
+ public boolean getBarcodeOnStatus() {
+ if (barcodeConnector == null) return false;
+ return barcodeConnector.getOnStatus();
+ }
+ public boolean setBarcodeOn(boolean on) {
+ boolean retValue;
+ BarcodeConnector.CsReaderBarcodeData csReaderBarcodeData = new BarcodeConnector.CsReaderBarcodeData();
+ if (on) csReaderBarcodeData.barcodePayloadEvent = BarcodeConnector.BarcodePayloadEvents.BARCODE_POWER_ON;
+ else csReaderBarcodeData.barcodePayloadEvent = BarcodeConnector.BarcodePayloadEvents.BARCODE_POWER_OFF;
+ csReaderBarcodeData.waitUplinkResponse = false;
+ retValue = barcodeConnector.barcodeToWrite.add(csReaderBarcodeData); appendToLog("barcodeToWrite added with size = " + barcodeConnector.barcodeToWrite.size());
+ if (DEBUG_FILE) appendToLog("add " + csReaderBarcodeData.barcodePayloadEvent.toString() + " to barcodeToWrite with length = " + barcodeConnector.barcodeToWrite.size());
+ boolean continuousAfterOn = false;
+ if (retValue && on && continuousAfterOn) {
+ if (checkHostProcessorVersion(getBluetoothICFirmwareVersion(), 1, 0, 2)) {
+ if (DEBUG) appendToLog("to barcodeSendCommandConinuous()");
+ retValue = barcodeNewland.barcodeSendCommandConinuous();
+ } else retValue = false;
+ }
+ if (DEBUG) appendToLog("barcodeToWrite size = " + barcodeConnector.barcodeToWrite.size());
+ return retValue;
+ }
+ int iModeSet = -1, iVibratieTimeSet = -1;
+ public boolean setVibrateOn(int mode) {
+ boolean retValue;
+ if (true) appendToLog("setVibrateOn with mode = " + mode + ", and isInventoring = " + csReaderConnector.rfidReader.isInventoring());
+ if (csReaderConnector.rfidReader.isInventoring()) return false;
+ BarcodeConnector.CsReaderBarcodeData csReaderBarcodeData = new BarcodeConnector.CsReaderBarcodeData();
+ if (mode > 0) csReaderBarcodeData.barcodePayloadEvent = BarcodeConnector.BarcodePayloadEvents.BARCODE_VIBRATE_ON;
+ else csReaderBarcodeData.barcodePayloadEvent = BarcodeConnector.BarcodePayloadEvents.BARCODE_VIBRATE_OFF;
+ csReaderBarcodeData.waitUplinkResponse = false;
+ if (iModeSet == mode && iVibratieTimeSet == getVibrateTime()) {
+ appendToLog("writeBleStreamOut: A7B3: Skip saving vibration data");
+ return true;
+ }
+ if (mode > 0) {
+ byte[] barcodeCommandData = new byte[3];
+ barcodeCommandData[0] = (byte) (mode - 1);
+ barcodeCommandData[1] = (byte) (getVibrateTime() / 256);
+ barcodeCommandData[2] = (byte) (getVibrateTime() % 256);
+ csReaderBarcodeData.dataValues = barcodeCommandData;
+ }
+ retValue = barcodeConnector.barcodeToWrite.add(csReaderBarcodeData); appendToLog("barcodeToWrite added with size = " + barcodeConnector.barcodeToWrite.size());
+ if (DEBUG) appendToLog("barcodeToWrite size = " + barcodeConnector.barcodeToWrite.size());
+ if (retValue) {
+ iModeSet = mode; iVibratieTimeSet = getVibrateTime();
+ }
+ return retValue;
+ }
+ public boolean getInventoryVibrate() {
+ return csReaderConnector.settingData.inventoryVibrate;
+ }
+ public boolean setInventoryVibrate(boolean inventoryVibrate) {
+ boolean DEBUG = false;
+ if (DEBUG) appendToLog("this.inventoryVibrate = " + csReaderConnector.settingData.inventoryVibrate + ", inventoryVibrate = " + inventoryVibrate);
+ csReaderConnector.settingData.inventoryVibrate = inventoryVibrate;
+ if (DEBUG) appendToLog("this.inventoryVibrate = " + csReaderConnector.settingData.inventoryVibrate + ", inventoryVibrate = " + inventoryVibrate);
+ return true;
+ }
+ public int getVibrateTime() {
+ return csReaderConnector.settingData.vibrateTimeSetting;
+ }
+ public boolean setVibrateTime(int vibrateTime) {
+ csReaderConnector.settingData.vibrateTimeSetting = vibrateTime;
+ return true;
+ }
+ public int getVibrateWindow() {
+ return csReaderConnector.settingData.vibrateWindowSetting;
+ }
+ public boolean setVibrateWindow(int vibrateWindow) {
+ csReaderConnector.settingData.vibrateWindowSetting = vibrateWindow;
+ return true;
+ }
+ public boolean barcodeSendCommandTrigger() {
+ return barcodeNewland.barcodeSendCommandTrigger();
+ }
+ public boolean barcodeSendCommandSetPreSuffix() {
+ return barcodeNewland.barcodeSendCommandSetPreSuffix();
+ }
+ public boolean barcodeSendCommandResetPreSuffix() {
+ return barcodeNewland.barcodeSendCommandResetPreSuffix();
+ }
+ public boolean barcodeSendCommandConinuous() {
+ return barcodeNewland.barcodeSendCommandConinuous();
+ }
+ public String getBarcodeVersion() {
+ return barcodeNewland.getBarcodeVersion();
+ }
+ public String getBarcodeSerial() {
+ return barcodeNewland.getBarcodeSerial();
+ }
+ boolean barcodeAutoStarted = false;
+ public boolean barcodeInventory(boolean start) {
+ boolean result = true;
+ appendToLog("TTestPoint 0: " + start);
+ if (start) {
+ barcodeConnector.mBarcodeToRead.clear(); barcodeDataStore = null;
+ if (getBarcodeOnStatus() == false) { result = setBarcodeOn(true); appendToLog("TTestPoint 1"); }
+ if (csReaderConnector.settingData.barcode2TriggerMode && result) {
+ if (getTriggerButtonStatus() && notificationConnector.getAutoBarStartSTop()) { appendToLog("TTestPoint 2"); barcodeAutoStarted = true; result = true; }
+ else { appendToLog("TTestPoint 3"); result = barcodeNewland.barcodeSendCommand(new byte[]{0x1b, 0x33}); }
+ } else appendToLog("TTestPoint 4");
+ appendToLog("TTestPoint 5");
+ } else {
+ appendToLog("getBarcodeOnStatus = " + getBarcodeOnStatus() + ", result = " + result);
+ if (csReaderConnector.settingData.barcode2TriggerMode == false) { appendToLog("TTestPoint 6"); result = setBarcodeOn(false); }
+ else if (getBarcodeOnStatus() == false && result) { appendToLog("TTestPoint 7"); result = setBarcodeOn(true); }
+ appendToLog("barcode2TriggerMode = " + csReaderConnector.settingData.barcode2TriggerMode + ", result = " + result + ", barcodeAutoStarted = " + barcodeAutoStarted);
+ if (csReaderConnector.settingData.barcode2TriggerMode && result) {
+ if (barcodeAutoStarted && result) { appendToLog("TTestPoint 8"); barcodeAutoStarted = false; result = true; }
+ else { appendToLog("TTestPoint 9"); result = barcodeNewland.barcodeSendCommand(new byte[] { 0x1b, 0x30 }); }
+ } else appendToLog("TTestPoint 10");
+ }
+ return result;
+ }
+ byte[] barcodeDataStore = null; long timeBarcodeData;
+ public byte[] onBarcodeEvent() {
+ byte[] barcodeData = null;
+ if (barcodeConnector.mBarcodeToRead.size() != 0) {
+ BarcodeConnector.CsReaderBarcodeData csReaderBarcodeData = barcodeConnector.mBarcodeToRead.get(0);
+ barcodeConnector.mBarcodeToRead.remove(0);
+ if (csReaderBarcodeData != null) {
+ if (csReaderBarcodeData.barcodePayloadEvent == BarcodeConnector.BarcodePayloadEvents.BARCODE_GOOD_READ) {
+ if (false) barcodeData = "".getBytes();
+ } else if (csReaderBarcodeData.barcodePayloadEvent == BarcodeConnector.BarcodePayloadEvents.BARCODE_DATA_READ) {
+ barcodeData = csReaderBarcodeData.dataValues;
+ }
+ }
+ }
+
+ byte[] barcodeCombined = null;
+ if (false) barcodeCombined = barcodeData;
+ else if (barcodeData != null) {
+ appendToLog("BarStream: barcodeData = " + byteArrayToString(barcodeData) + ", barcodeDataStore = " + byteArrayToString(barcodeDataStore));
+ int barcodeDataStoreIndex = 0;
+ int length = barcodeData.length;
+ if (barcodeDataStore != null) {
+ barcodeDataStoreIndex = barcodeDataStore.length;
+ length += barcodeDataStoreIndex;
+ }
+ barcodeCombined = new byte[length];
+ if (barcodeDataStore != null)
+ System.arraycopy(barcodeDataStore, 0, barcodeCombined, 0, barcodeDataStore.length);
+ System.arraycopy(barcodeData, 0, barcodeCombined, barcodeDataStoreIndex, barcodeData.length);
+ barcodeDataStore = barcodeCombined;
+ timeBarcodeData = System.currentTimeMillis();
+ barcodeCombined = new byte[0];
+ }
+ if (barcodeDataStore != null) {
+ barcodeCombined = new byte[barcodeDataStore.length];
+ System.arraycopy(barcodeDataStore, 0, barcodeCombined, 0, barcodeCombined.length);
+
+ if (System.currentTimeMillis() - timeBarcodeData < 300) barcodeCombined = null;
+ else barcodeDataStore = null;
+ }
+ if (barcodeCombined != null && barcodeNewland.getPrefix() != null && barcodeNewland.getSuffix() != null) {
+ if (barcodeCombined.length == 0) barcodeCombined = null;
+ else {
+ byte[] prefixExpected = barcodeNewland.getPrefix(); boolean prefixFound = false;
+ byte[] suffixExpected = barcodeNewland.getSuffix(); boolean suffixFound = false;
+ int codeTypeLength = 4;
+ appendToLog("BarStream: barcodeCombined = " + byteArrayToString(barcodeCombined) + ", Expected Prefix = " + byteArrayToString(prefixExpected) + ", Expected Suffix = " + byteArrayToString(suffixExpected));
+ if (barcodeCombined.length > prefixExpected.length + suffixExpected.length + codeTypeLength) {
+ int i = 0;
+ for (; i <= barcodeCombined.length - prefixExpected.length - suffixExpected.length; i++) {
+ int j = 0;
+ for (; j < prefixExpected.length; j++) {
+ if (barcodeCombined[i+j] != prefixExpected[j]) break;
+ }
+ if (j == prefixExpected.length) { prefixFound = true; break; }
+ }
+ int k = i + prefixExpected.length;
+ for (; k <= barcodeCombined.length - suffixExpected.length; k++) {
+ int j = 0;
+ for (; j < suffixExpected.length; j++) {
+ if (barcodeCombined[k+j] != suffixExpected[j]) break;
+ }
+ if (j == suffixExpected.length) { suffixFound = true; break; }
+ }
+ appendToLog("BarStream: iPrefix = " + i + ", iSuffix = " + k + ", with prefixFound = " + prefixFound + ", suffixFound = " + suffixFound);
+ if (prefixFound && suffixFound) {
+ byte[] barcodeCombinedNew = new byte[k - i - prefixExpected.length - codeTypeLength];
+ System.arraycopy(barcodeCombined, i + prefixExpected.length + codeTypeLength, barcodeCombinedNew, 0, barcodeCombinedNew.length);
+ barcodeCombined = barcodeCombinedNew;
+ appendToLog("BarStream: barcodeCombinedNew = " + byteArrayToString(barcodeCombinedNew));
+
+ if (true) {
+ byte[] prefixExpected1 = {0x5B, 0x29, 0x3E, 0x1E};
+ prefixFound = false;
+ byte[] suffixExpected1 = {0x1E, 0x04};
+ suffixFound = false;
+ appendToLog("BarStream: barcodeCombined = " + byteArrayToString(barcodeCombined) + ", Expected Prefix = " + byteArrayToString(prefixExpected1) + ", Expected Suffix = " + byteArrayToString(suffixExpected1));
+ if (barcodeCombined.length > prefixExpected1.length + suffixExpected1.length) {
+ i = 0;
+ for (; i <= barcodeCombined.length - prefixExpected1.length - suffixExpected1.length; i++) {
+ int j = 0;
+ for (; j < prefixExpected1.length; j++) {
+ if (barcodeCombined[i + j] != prefixExpected1[j]) break;
+ }
+ if (j == prefixExpected1.length) {
+ prefixFound = true;
+ break;
+ }
+ }
+ k = i + prefixExpected1.length;
+ for (; k <= barcodeCombined.length - suffixExpected1.length; k++) {
+ int j = 0;
+ for (; j < suffixExpected1.length; j++) {
+ if (barcodeCombined[k + j] != suffixExpected1[j]) break;
+ }
+ if (j == suffixExpected1.length) {
+ suffixFound = true;
+ break;
+ }
+ }
+ appendToLog("BarStream: iPrefix = " + i + ", iSuffix = " + k + ", with prefixFound = " + prefixFound + ", suffixFound = " + suffixFound);
+ if (prefixFound && suffixFound) {
+ barcodeCombinedNew = new byte[k - i - prefixExpected1.length];
+ System.arraycopy(barcodeCombined, i + prefixExpected1.length, barcodeCombinedNew, 0, barcodeCombinedNew.length);
+ barcodeCombined = barcodeCombinedNew;
+ appendToLog("BarStream: barcodeCombinedNew = " + byteArrayToString(barcodeCombinedNew));
+ }
+ }
+ }
+ }
+ } else barcodeCombined = null;
+ }
+ }
+ return barcodeCombined;
+ }
+
+ //============ Android General ============
+ public void setSameCheck(boolean sameCheck1) {
+ if (csReaderConnector.sameCheck == sameCheck1) return;
+ if (false) appendToLog("new sameCheck = " + sameCheck1 + ", with old sameCheck = " + csReaderConnector.sameCheck);
+ csReaderConnector.sameCheck = sameCheck1; //sameCheck = false;
+ }
+
+ public int getBeepCount() {
+ return csReaderConnector.settingData.beepCountSetting;
+ }
+ public boolean setBeepCount(int beepCount) {
+ csReaderConnector.settingData.beepCountSetting = beepCount;
+ return true;
+ }
+
+ public boolean getInventoryBeep() {
+ return csReaderConnector.settingData.inventoryBeep;
+ }
+ public boolean setInventoryBeep(boolean inventoryBeep) {
+ csReaderConnector.settingData.inventoryBeep = inventoryBeep;
+ return true;
+ }
+
+ public boolean getSaveFileEnable() {
+ return csReaderConnector.settingData.saveFileEnable;
+ }
+ public boolean setSaveFileEnable(boolean saveFileEnable) {
+ appendToLog("this.saveFileEnable = " + csReaderConnector.settingData.saveFileEnable + ", saveFileEnable = " + saveFileEnable);
+ csReaderConnector.settingData.saveFileEnable = saveFileEnable;
+ appendToLog("this.saveFileEnable = " + csReaderConnector.settingData.saveFileEnable + ", saveFileEnable = " + saveFileEnable);
+ return true;
+ }
+ public boolean getSaveCloudEnable() {
+ return csReaderConnector.settingData.saveCloudEnable;
+ }
+ public boolean setSaveCloudEnable(boolean saveCloudEnable) {
+ csReaderConnector.settingData.saveCloudEnable = saveCloudEnable;
+ return true;
+ }
+ public boolean getSaveNewCloudEnable() {
+ return csReaderConnector.settingData.saveNewCloudEnable;
+ }
+ public boolean setSaveNewCloudEnable(boolean saveNewCloudEnable) {
+ csReaderConnector.settingData.saveNewCloudEnable = saveNewCloudEnable;
+ return true;
+ }
+ public boolean getSaveAllCloudEnable() {
+ return csReaderConnector.settingData.saveAllCloudEnable;
+ }
+ public boolean setSaveAllCloudEnable(boolean saveAllCloudEnable) {
+ csReaderConnector.settingData.saveAllCloudEnable = saveAllCloudEnable;
+ return true;
+ }
+ public boolean getUserDebugEnable() {
+ boolean bValue = csReaderConnector.settingData.userDebugEnable; appendToLog("bValue = " + bValue); return bValue;
+ }
+ public boolean setUserDebugEnable(boolean userDebugEnable) {
+ appendToLog("new userDebug = " + userDebugEnable);
+ csReaderConnector.settingData.userDebugEnable = userDebugEnable;
+ return true;
+ }
+ public String getForegroundReader() {
+ return csReaderConnector.settingData.strForegroundReader;
+ }
+ public boolean getForegroundServiceEnable() {
+ String string = csReaderConnector.settingData.strForegroundReader;
+ return (string.trim().length() == 0 ? false : true);
+ }
+ public boolean setForegroundServiceEnable(boolean bForegroundService) {
+ if (bForegroundService) csReaderConnector.settingData.strForegroundReader = csReaderConnector.bluetoothGatt.getReaderDeviceConnected().getAddress();
+ else csReaderConnector.settingData.strForegroundReader = "";
+ return true;
+ }
+ public String getServerLocation() {
+ return csReaderConnector.settingData.serverLocation;
+ }
+ public boolean setServerLocation(String serverLocation) {
+ csReaderConnector.settingData.serverLocation = serverLocation;
+ return true;
+ }
+ public int getServerTimeout() {
+ return csReaderConnector.settingData.serverTimeout;
+ }
+ public boolean setServerTimeout(int serverTimeout) {
+ csReaderConnector.settingData.serverTimeout = serverTimeout;
+ return true;
+ }
+ public String getServerMqttLocation() {
+ return csReaderConnector.settingData.serverMqttLocation;
+ }
+ public boolean setServerMqttLocation(String serverLocation) {
+ csReaderConnector.settingData.serverMqttLocation = serverLocation;
+ return true;
+ }
+ public String getTopicMqtt() {
+ return csReaderConnector.settingData.topicMqtt;
+ }
+ public boolean setTopicMqtt(String topicMqtt) {
+ csReaderConnector.settingData.topicMqtt = topicMqtt;
+ return true;
+ }
+ public int getForegroundDupElim() {
+ return csReaderConnector.settingData.iForegroundDupElim;
+ }
+ public boolean setForegroundDupElim(int iForegroundDupElim) {
+ csReaderConnector.settingData.iForegroundDupElim = iForegroundDupElim;
+ return true;
+ }
+ public int getInventoryCloudSave() {
+ return csReaderConnector.settingData.inventoryCloudSave;
+ }
+ public boolean setInventoryCloudSave(int inventoryCloudSave) {
+ csReaderConnector.settingData.inventoryCloudSave = inventoryCloudSave;
+ return true;
+ }
+ public String getServerImpinjLocation() {
+ return csReaderConnector.settingData.serverImpinjLocation;
+ }
+ public boolean setServerImpinjLocation(String serverImpinjLocation) {
+ csReaderConnector.settingData.serverImpinjLocation = serverImpinjLocation;
+ return true;
+ }
+ public String getServerImpinjName() {
+ appendToLog("serverImpinjName = " + csReaderConnector.settingData.serverImpinjName);
+ return csReaderConnector.settingData.serverImpinjName;
+ }
+ public boolean setServerImpinjName(String serverImpinjName) {
+ csReaderConnector.settingData.serverImpinjName = serverImpinjName;
+ appendToLog("serverImpinjName = " + serverImpinjName);
+ return true;
+ }
+ public String getServerImpinjPassword() {
+ return csReaderConnector.settingData.serverImpinjPassword;
+ }
+ public boolean setServerImpinjPassword(String serverImpinjPassword) {
+ csReaderConnector.settingData.serverImpinjPassword = serverImpinjPassword;
+ return true;
+ }
+ public int getBatteryDisplaySetting() {
+ return csReaderConnector.settingData.batteryDisplaySelect;
+ }
+ public boolean setBatteryDisplaySetting(int batteryDisplaySelect) {
+ return csReaderConnector.settingData.setBatteryDisplaySetting(batteryDisplaySelect);
+ }
+ public double dBuV_dBm_constant = RfidReader.dBuV_dBm_constant; //106.98;
+ public int getRssiDisplaySetting() {
+ return csReaderConnector.settingData.rssiDisplaySelect;
+ }
+ public boolean setRssiDisplaySetting(int rssiDisplaySelect) {
+ return csReaderConnector.settingData.setRssiDisplaySetting(rssiDisplaySelect);
+ }
+ public int getVibrateModeSetting() {
+ return csReaderConnector.settingData.vibrateModeSelect;
+ }
+ public boolean setVibrateModeSetting(int vibrateModeSelect) {
+ if (vibrateModeSelect < 0 || vibrateModeSelect > 1) return false;
+ csReaderConnector.settingData.vibrateModeSelect = vibrateModeSelect;
+ return true;
+ }
+ public int getSavingFormatSetting() {
+ return csReaderConnector.settingData.savingFormatSelect;
+ }
+ public boolean setSavingFormatSetting(int savingFormatSelect) {
+ if (false) appendToLog("savingFormatSelect = " + savingFormatSelect);
+ if (savingFormatSelect < 0 || savingFormatSelect > 1) return false;
+ csReaderConnector.settingData.savingFormatSelect = savingFormatSelect;
+ return true;
+ }
+ public int getCsvColumnSelectSetting() {
+ return csReaderConnector.settingData.csvColumnSelect;
+ }
+ public boolean setCsvColumnSelectSetting(int csvColumnSelect) {
+ csReaderConnector.settingData.csvColumnSelect = csvColumnSelect;
+ return true;
+ }
+ public String getWedgeDeviceName() {
+ return csReaderConnector.settingData.wedgeDeviceName;
+ }
+ public String getWedgeDeviceAddress() {
+ return csReaderConnector.settingData.wedgeDeviceAddress;
+ }
+ public int getWedgeDeviceUUID2p1() {
+ return csReaderConnector.settingData.wedgeDeviceUUID2p1;
+ }
+ public int getWedgePower() {
+ return csReaderConnector.settingData.wedgePower;
+ }
+ public String getWedgePrefix() {
+ return csReaderConnector.settingData.wedgePrefix;
+ }
+ public String getWedgeSuffix() {
+ return csReaderConnector.settingData.wedgeSuffix;
+ }
+ public int getWedgeDelimiter() {
+ return csReaderConnector.settingData.wedgeDelimiter;
+ }
+ public int getWedgeOutput() {
+ return csReaderConnector.settingData.wedgeOutput;
+ }
+ public void setWedgeDeviceName(String wedgeDeviceName) {
+ csReaderConnector.settingData.wedgeDeviceName = wedgeDeviceName;
+ }
+ public void setWedgeDeviceAddress(String wedgeDeviceAddress) {
+ csReaderConnector.settingData.wedgeDeviceAddress = wedgeDeviceAddress;
+ }
+ public void setWedgeDeviceUUID2p1(int wedgeDeviceUUID2p1) {
+ csReaderConnector.settingData.wedgeDeviceUUID2p1 = wedgeDeviceUUID2p1;;
+ }
+ public void setWedgePower(int iPower) {
+ csReaderConnector.settingData.wedgePower = iPower;
+ }
+ public void setWedgePrefix(String string) {
+ csReaderConnector.settingData.wedgePrefix = string;
+ }
+ public void setWedgeSuffix(String string) {
+ csReaderConnector.settingData.wedgeSuffix = string;
+ }
+ public void setWedgeDelimiter(int iValue) {
+ csReaderConnector.settingData.wedgeDelimiter = iValue;
+ }
+ public void setWedgeOutput(int iOutput) {
+ csReaderConnector.settingData.wedgeOutput = iOutput;
+ }
+ public void saveWedgeSetting2File() {
+ csReaderConnector.settingData.saveWedgeSetting2File();
+ }
+
+ //============ Bluetooth ============
+ public String getBluetoothICFirmwareVersion() {
+ return bluetoothConnector.getBluetoothIcVersion();
+ }
+ public String getBluetoothICFirmwareName() {
+ return bluetoothConnector.getBluetoothIcName();
+ }
+ public boolean setBluetoothICFirmwareName(String name) {
+ return bluetoothConnector.setBluetoothIcName(name);
+ }
+
+ //============ Controller ============
+ public String hostProcessorICGetFirmwareVersion() {
+ return controllerConnector.getVersion();
+ }
+ public String getHostProcessorICSerialNumber() {
+ String str;
+ if (bluetoothConnector.getCsModel() != 463) str = controllerConnector.getSerialNumber();
+ else str = csReaderConnector.rfidReader.getProductSerialNumber();
+ if (str != null) {
+ if (str.length() >= 16) return str.substring(0, 16);
+ }
+ return null;
+ }
+ public String getHostProcessorICBoardVersion() {
+ String str;
+ if (bluetoothConnector.getCsModel() != 463) str = controllerConnector.getSerialNumber();
+ else str = csReaderConnector.rfidReader.getProductSerialNumber();
+ if (false) appendToLog("str = " + str);
+ if (str == null) return null;
+ if (str.length() < 16+4) return null;
+ str = str.substring(16);
+ if (true) {
+ String string = "";
+ if (str.length() >= 1) string = str.substring(0,1);
+ if (str.length() >= 3) string += ("." + str.substring(1, 3));
+ if (str.length() >= 4) string += ("." + str.substring(3, 4));
+
+ if (false) {
+ if (str.length() >= 5) string += (", " + str.substring(4, 5));
+ if (str.length() >= 7) string += ("." + str.substring(5, 7));
+ if (str.length() >= 8) string += ("." + str.substring(7, 8));
+ }
+ str = string;
+ }
+ return str;
+ }
+
+ //============ Controller notification ============
+ int iBatteryCount;
+ int getBatteryValue2Percent(float floatValue) {
+ boolean DEBUG = false;
+ if (DEBUG) appendToLog("getHostProcessorICBoardVersion = " + getHostProcessorICBoardVersion() + ", strVersionMBoard = " + strVersionMBoard);
+ if (false || checkHostProcessorVersion(getHostProcessorICBoardVersion(), Integer.parseInt(strMBoardVersions[0].trim()), Integer.parseInt(strMBoardVersions[1].trim()), 0)) {
+ final float[] fValueStbyRef = {
+ (float) 4.212, (float) 4.175, (float) 4.154, (float) 4.133, (float) 4.112,
+ (float) 4.085, (float) 4.069, (float) 4.054, (float) 4.032, (float) 4.011,
+ (float) 3.990, (float) 3.969, (float) 3.953, (float) 3.937, (float) 3.922,
+ (float) 3.901, (float) 3.885, (float) 3.869, (float) 3.853, (float) 3.837,
+ (float) 3.821, (float) 3.806, (float) 3.790, (float) 3.774, (float) 3.769,
+ (float) 3.763, (float) 3.758, (float) 3.753, (float) 3.747, (float) 3.742,
+ (float) 3.732, (float) 3.721, (float) 3.705, (float) 3.684, (float) 3.668,
+ (float) 3.652, (float) 3.642, (float) 3.626, (float) 3.615, (float) 3.605,
+ (float) 3.594, (float) 3.584, (float) 3.568, (float) 3.557, (float) 3.542,
+ (float) 3.531, (float) 3.510, (float) 3.494, (float) 3.473, (float) 3.457,
+ (float) 3.436, (float) 3.410, (float) 3.362, (float) 3.235, (float) 2.987,
+ (float) 2.982
+ };
+ final float[] fPercentStbyRef = {
+ (float) 100, (float) 98, (float) 96, (float) 95, (float) 93,
+ (float) 91, (float) 89, (float) 87, (float) 85, (float) 84,
+ (float) 82, (float) 80, (float) 78, (float) 76, (float) 75,
+ (float) 73, (float) 71, (float) 69, (float) 67, (float) 65,
+ (float) 64, (float) 62, (float) 60, (float) 58, (float) 56,
+ (float) 55, (float) 53, (float) 51, (float) 49, (float) 47,
+ (float) 45, (float) 44, (float) 42, (float) 40, (float) 38,
+ (float) 36, (float) 35, (float) 33, (float) 31, (float) 29,
+ (float) 27, (float) 25, (float) 24, (float) 22, (float) 20,
+ (float) 18, (float) 16, (float) 15, (float) 13, (float) 11,
+ (float) 9, (float) 7, (float) 5, (float) 4, (float) 2,
+ (float) 0
+ };
+ final float[] fValueRunRef = {
+ (float) 4.106, (float) 4.017, (float) 3.98 , (float) 3.937, (float) 3.895,
+ (float) 3.853, (float) 3.816, (float) 3.779, (float) 3.742, (float) 3.711,
+ (float) 3.679, (float) 3.658, (float) 3.637, (float) 3.626, (float) 3.61 ,
+ (float) 3.584, (float) 3.547, (float) 3.515, (float) 3.484, (float) 3.457,
+ (float) 3.431, (float) 3.399, (float) 3.362, (float) 3.32 , (float) 3.251,
+ (float) 3.135
+ };
+ final float[] fPercentRunRef = {
+ (float) 100, (float) 96, (float) 92, (float) 88, (float) 84,
+ (float) 80, (float) 76, (float) 72, (float) 67, (float) 63,
+ (float) 59, (float) 55, (float) 51, (float) 47, (float) 43,
+ (float) 39, (float) 35, (float) 31, (float) 27, (float) 23,
+ (float) 19, (float) 15, (float) 11, (float) 7, (float) 2,
+ (float) 0
+ };
+ float[] fValueRef = fValueStbyRef;
+ float[] fPercentRef = fPercentStbyRef;
+
+ if (true && iBatteryCount != getBatteryCount()) {
+ iBatteryCount = getBatteryCount();
+ iBatteryNewCurveDelay++;
+ }
+ if (csReaderConnector.rfidReader.mRfidToWrite.size() != 0) iBatteryNewCurveDelay = 0;
+ else if (csReaderConnector.rfidReader.isInventoring()) {
+ if (bUsingInventoryBatteryCurve == false) { if (iBatteryNewCurveDelay > 1) { iBatteryNewCurveDelay = 0; bUsingInventoryBatteryCurve = true; } }
+ else iBatteryNewCurveDelay = 0;
+ } else if (bUsingInventoryBatteryCurve) { if (iBatteryNewCurveDelay > 2) { iBatteryNewCurveDelay = 0; bUsingInventoryBatteryCurve = false; } }
+ else iBatteryNewCurveDelay = 0;
+
+ if (bUsingInventoryBatteryCurve) {
+ fValueRef = fValueRunRef;
+ fPercentRef = fPercentRunRef;
+ }
+ if (DEBUG) appendToLog("NEW Percentage cureve is USED with bUsingInventoryBatteryCurve = " + bUsingInventoryBatteryCurve + ", iBatteryNewCurveDelay = " + iBatteryNewCurveDelay);
+
+ int index = 0;
+ while (index < fValueRef.length) {
+ if (floatValue > fValueRef[index]) break;
+ index++;
+ }
+ if (DEBUG) appendToLog("Index = " + index);
+ if (index == 0) return 100;
+ if (index == fValueRef.length) return 0;
+ float value = ((fValueRef[index - 1] - floatValue) / (fValueRef[index - 1] - fValueRef[index]));
+ if (true) {
+ value *= (fPercentRef[index -1] - fPercentRef[index]);
+ value = fPercentRef[index - 1] - value;
+ } else {
+ value += (float) (index - 1);
+ value /= (float) (fValueRef.length - 1);
+ value *= 100;
+ value = 100 - value;
+ }
+ value += 0.5;
+ int iValue = (int) (value);
+ if (iBatteryNewCurveDelay != 0) iValue = iBatteryPercentOld;
+ else if (bUsingInventoryBatteryCurve && floatValue <= fBatteryValueOld && iValue >= iBatteryPercentOld) iValue = iBatteryPercentOld;
+ fBatteryValueOld = floatValue; iBatteryPercentOld = iValue;
+ return iValue;
+ } else {
+ if (DEBUG) appendToLog("OLD Percentage cureve is USED");
+ if (floatValue >= 4) return 100;
+ else if (floatValue < 3.4) return 0;
+ else {
+ float result = (float) 166.67 * floatValue - (float) 566.67;
+ return (int) result;
+ }
+ }
+ }
+ public int getBatteryLevel() {
+ return csReaderConnector.getBatteryLevel();
+ }
+ public boolean setAutoTriggerReporting(byte timeSecond) {
+ return notificationConnector.setAutoTriggerReporting(timeSecond);
+ }
+ public boolean getAutoBarStartSTop() {
+ return notificationConnector.getAutoBarStartStopStatus();
+ }
+
+ public boolean batteryLevelRequest() {
+ if (csReaderConnector.rfidReader == null) return false;
+ if (notificationConnector == null) return false;
+ if (csReaderConnector.rfidReader.isInventoring()) {
+ appendToLog("Skip batteryLevelREquest as inventoring !!!");
+ return true;
+ }
+ if (mrfidToWriteSize() != 0) return false;
+ return notificationConnector.batteryLevelRequest();
+ }
+ public boolean setAutoBarStartSTop(boolean enable) {
+ return notificationConnector.setAutoBarStartSTop(enable);
+ }
+ public boolean getTriggerReporting() {
+ return csReaderConnector.settingData.triggerReporting;
+ }
+ public boolean setTriggerReporting(boolean triggerReporting) {
+ return notificationConnector.setTriggerReporting(triggerReporting);
+ }
+ public final int iNO_SUCH_SETTING = 10000;
+ public short getTriggerReportingCount() {
+ boolean bValue = false;
+ if (getcsModel() != 463) bValue = checkHostProcessorVersion(hostProcessorICGetFirmwareVersion(), 1, 0, 16);
+ if (bValue == false) return iNO_SUCH_SETTING; else
+ return csReaderConnector.settingData.triggerReportingCountSetting;
+ }
+ public boolean setTriggerReportingCount(short triggerReportingCount) {
+ return notificationConnector.setTriggerReportingCount(triggerReportingCount);
+ }
+ public String getBatteryDisplay(boolean voltageDisplay) {
+ float floatValue = (float) getBatteryLevel() / 1000;
+ if (floatValue == 0) return " ";
+ String retString = null;
+ if (voltageDisplay || (getBatteryDisplaySetting() == 0)) retString = String.format("%.3f V", floatValue);
+ else retString = (String.format("%d", getBatteryValue2Percent(floatValue)) + "%");
+ if (voltageDisplay == false) retString += String.format("\r\n P=%d", getPwrlevel());
+ return retString;
+ }
+ String strVersionMBoard = "1.8"; String[] strMBoardVersions = strVersionMBoard.split("\\.");
+ int iBatteryNewCurveDelay; boolean bUsingInventoryBatteryCurve = false; float fBatteryValueOld; int iBatteryPercentOld;
+ public String isBatteryLow() {
+ boolean batterylow = false;
+ int iValue = getBatteryLevel();
+ if (iValue == 0) return null;
+ float fValue = (float) iValue / 1000;
+ int iPercent = getBatteryValue2Percent(fValue);
+ if (checkHostProcessorVersion(getHostProcessorICBoardVersion(), Integer.parseInt(strMBoardVersions[0].trim()), Integer.parseInt(strMBoardVersions[1].trim()), 0)) {
+ if (true) {
+ if (csReaderConnector.rfidReader.isInventoring()) {
+ if (fValue < 3.520) batterylow = true;
+ } else if (bUsingInventoryBatteryCurve == false) {
+ if (fValue < 3.626) batterylow = true;
+ }
+ } else if (iPercent <= 20) batterylow = true;
+ } else if (true) {
+ if (csReaderConnector.rfidReader.isInventoring()) {
+ if (fValue < 3.45) batterylow = true;
+ } else if (bUsingInventoryBatteryCurve == false) {
+ if (fValue < 3.6) batterylow = true;
+ }
+ } else if (iPercent <= 8) batterylow = true;
+ if (batterylow) return String.valueOf(iPercent);
+ return null;
+ }
+ public int getBatteryCount() {
+ return csReaderConnector.csConnectorData.getVoltageCnt();
+ }
+ public boolean getTriggerButtonStatus() {
+ return notificationConnector.getTriggerStatus();
+ }
+ public int getTriggerCount() {
+ return csReaderConnector.csConnectorData.getTriggerCount();
+ }
+ //public interface NotificationListener { void onChange(); }
+ public void setNotificationListener(NotificationConnector.NotificationListener listener) {
+ notificationConnector.setNotificationListener0(listener);
+ }
+ public byte[] onNotificationEvent() {
+ byte[] notificationData = null;
+ if (notificationConnector == null) {
+ appendToLog("notificationConnector is null");
+ return null;
+ }
+ if (notificationConnector.notificationToRead.size() != 0) {
+ NotificationConnector.CsReaderNotificationData csReaderNotificationData = notificationConnector.notificationToRead.get(0);
+ notificationConnector.notificationToRead.remove(0);
+ if (csReaderNotificationData != null) notificationData = csReaderNotificationData.dataValues;
+ }
+ return notificationData;
+ }
+
+ //============ to be modified ============
+ String getModelName() {
+ return csReaderConnector.getModelName();
+ }
+ public String getSerialNumber() {
+ return csReaderConnector.rfidReader.getSerialNumber();
+ }
+ public boolean setRfidOn(boolean onStatus) {
+ return csReaderConnector.rfidReader.turnOn(onStatus);
+ }
+ private final Runnable reinitaliseDataRunnable = new Runnable() {
+ @Override
+ public void run() {
+ appendToLog("reset before: reinitaliseDataRunnable starts with inventoring=" + csReaderConnector.rfidReader.isInventoring() + ", mrfidToWriteSize=" + mrfidToWriteSize());
+ if (csReaderConnector.rfidReader.isInventoring() || mrfidToWriteSize() != 0) {
+ mHandler.removeCallbacks(reinitaliseDataRunnable);
+ mHandler.postDelayed(reinitaliseDataRunnable, 500);
+ } else {
+ if (DEBUG_CONNECT) appendToLog("Debug_Connect: Cs710Library4A.reinitaliseDataRunnable Start checkVersionRunnable");
+ mHandler.postDelayed(checkVersionRunnable, 500);
+ }
+ }
+ };
+ private final Runnable checkVersionRunnable = new Runnable() {
+ boolean DEBUG = false;
+ @Override
+ public void run() {
+ if (DEBUG_CONNECT) appendToLog("Debug_Connect: Cs710Library4A.checkVersionRunnable with mrfidToWriteSize = " + mrfidToWriteSize());
+ if (csReaderConnector.rfidReader == null || barcodeNewland == null || csReaderConnector.rfidReader.mRfidToWrite.size() != 0) {
+ mHandler.removeCallbacks(checkVersionRunnable);
+ mHandler.postDelayed(checkVersionRunnable, 500);
+ } else {
+ //bluetoothGatt.removeBond(null);
+ setSameCheck(false);
+ if (DEBUG_CONNECT) appendToLog("Debug_Connect: Cs710Library4A.checkVersionRunnable with BarcodeFailure = " + isBarcodeFailure()); ///
+ if (false && isBarcodeFailure() == false) {
+ if (DEBUG_CONNECT) appendToLog("Debug_Connect: Cs710Library4A.checkVersionRunnable"); ///5
+ if (barcodeNewland.checkPreSuffix(barcodeNewland.prefixRef, barcodeNewland.suffixRef) == false) barcodeNewland.barcodeSendCommandSetPreSuffix();
+ if (barcodeNewland.bBarcodeTriggerMode != 0x30) barcodeNewland.barcodeSendCommandTrigger();
+ notificationConnector.getAutoRFIDAbort(); notificationConnector.getAutoBarStartSTop(); //setAutoRFIDAbort(false); setAutoBarStartSTop(true);
+ }
+ setAntennaCycle(0xffff);
+ if (false) {
+ if (bluetoothConnector.getCsModel() == 463) {
+ if (DEBUG_CONNECT) appendToLog("Debug_Connect: Cs710Library4A.checkVersionRunnable 4");
+ setAntennaDwell(2000);
+ setAntennaInvCount(0);
+ } else {
+ if (DEBUG_CONNECT) appendToLog("Debug_Connect: Cs710Library4A.checkVersionRunnable 5");
+ setAntennaDwell(0);
+ setAntennaInvCount(0xfffffffeL);
+ }
+ }
+ csReaderConnector.settingData.loadWedgeSettingFile();
+ if (loadSetting1File()) loadSetting1File();
+ appendToLog("Cs710Library4A.checkVersionRunnable, getMacVer");
+ if (DEBUG_CONNECT) appendToLog("Debug_Connect: Cs710Library4A.checkVersionRunnable with macVersion = " + getMacVer());
+ if (true) {
+ setTagDelay(csReaderConnector.rfidReader.tagDelaySetting);
+ setCycleDelay(csReaderConnector.rfidReader.cycleDelaySetting);
+ setInvModeCompact(true);
+ } else {
+ setTagDelay(csReaderConnector.rfidReader.tagDelayDefaultNormalSetting);
+ setCycleDelay(csReaderConnector.rfidReader.cycleDelaySetting);
+ }
+ if (DEBUG_CONNECT) appendToLog("Debug_Connect: Cs710Library4A.checkVersionRunnable ends with mRfidToWrite.size = " + csReaderConnector.rfidReader.mRfidToWrite.size());
+ setSameCheck(true);
+ }
+ }
+ };
+
+ boolean loadSetting1File() {
+ String stringMacAddress = null;
+ appendToLog("Cs710Library4A.loadSetting1File, loadSettingFile: starts with bluetoothGatt is " + (bluetoothGatt == null ? "null" : "valid"));
+ if (bluetoothGatt != null) {
+ appendToLog("Cs710Library4A.loadSetting1File, loadSettingFile: bluetoothConnectionState = " + bluetoothGatt.bluetoothConnectionState);
+ appendToLog("Cs710Library4A.loadSetting1File, loadSettingFile: starts with bluetoothGatt.getmBluetoothDevice is " + (bluetoothGatt.getReaderDeviceConnected() == null ? "null" : "valid"));
+ if (bluetoothGatt.getReaderDeviceConnected() != null) stringMacAddress = bluetoothGatt.getReaderDeviceConnected().getAddress();
+ }
+ if (stringMacAddress == null) {
+ appendToLog("Cs710Library4A.loadSetting1File, loadSettingFile: starts with usbConnector is " + (csReaderConnector.usbConnector == null ? "null" : "valid"));
+ if (csReaderConnector.usbConnector != null) {
+ appendToLog("Cs710Library4A.loadSetting1File, loadSettingFile: usbConnectionState = " + csReaderConnector.usbConnector.usbConnectionState);
+ stringMacAddress = readerDeviceConnect.getAddress();
+ }
+ }
+ appendToLog("Cs710Library4A.loadSetting1File, loadSettingFile: stringMacAddress = " + stringMacAddress);
+ return csReaderConnector.settingData.loadSettingFile(stringMacAddress, getlibraryVersion(), getChannelHoppingStatus(), getCurrentProfile());
+ }
+ public void saveSetting2File() {
+ csReaderConnector.settingData.saveSetting2File(getlibraryVersion(), getChannelHoppingStatus(), getCurrentProfile());
+ }
+
+ public int getcsModel() {
+ return bluetoothConnector.getCsModel();
+ }
+ public int getAntennaCycle() {
+ return csReaderConnector.rfidReader.getAntennaCycle();
+ }
+ public boolean setAntennaCycle(int antennaCycle) {
+ return csReaderConnector.rfidReader.setAntennaCycle(antennaCycle);
+ }
+ public boolean setAntennaInvCount(long antennaInvCount) {
+ return csReaderConnector.rfidReader.setAntennaInvCount(antennaInvCount);
+ }
+
+ public void clearInvalidata() {
+ csReaderConnector.clearInvalidata();
+ }
+ public int getInvalidata() {
+ return csReaderConnector.invalidata;
+ }
+ public int getInvalidUpdata() {
+ return csReaderConnector.invalidUpdata;
+ }
+ public int getValidata() {
+ return csReaderConnector.validata;
+ }
+
+ public int setSelectData(RfidReader.TagType tagType, String mDid, boolean bNeedSelectedTagByTID, String stringProtectPassword, int selectFor, int selectHold) {
+ return csReaderConnector.rfidReader.setSelectData4Inventory(tagType, mDid, bNeedSelectedTagByTID, stringProtectPassword, selectFor, selectHold);
+ }
+ public int setOtherInventoryData(RfidReader.TagType tagType, String mDid) {
+ if (tagType == RfidReader.TagType.TAG_ASYGN) { //mDid.matches("E283A")) {
+ long iValue = csReaderConnector.rfidReader.getAntennaDwell();
+ if (iValue == 0) {
+ csReaderConnector.rfidReader.setAntennaDwell(2000);
+ }
+ }
+ return -1;
+ }
+}
+
+
+
+package com.csl.cslibrary4a;
+
+import static android.bluetooth.BluetoothClass.Service.LE_AUDIO;
+import static android.bluetooth.BluetoothClass.Service.LIMITED_DISCOVERABILITY;
+import static android.bluetooth.BluetoothDevice.BOND_BONDED;
+import static android.bluetooth.BluetoothDevice.BOND_BONDING;
+import static android.bluetooth.BluetoothDevice.BOND_NONE;
+import static android.bluetooth.BluetoothDevice.DEVICE_TYPE_CLASSIC;
+import static android.bluetooth.BluetoothDevice.DEVICE_TYPE_DUAL;
+import static android.bluetooth.BluetoothDevice.DEVICE_TYPE_LE;
+import static android.bluetooth.BluetoothDevice.DEVICE_TYPE_UNKNOWN;
+import static android.bluetooth.BluetoothProfile.GATT;
+
+import android.Manifest;
+import android.bluetooth.BluetoothAdapter;
+import android.bluetooth.BluetoothClass;
+import android.bluetooth.BluetoothDevice;
+import android.bluetooth.BluetoothGattCallback;
+import android.bluetooth.BluetoothGattCharacteristic;
+import android.bluetooth.BluetoothGattService;
+import android.bluetooth.BluetoothManager;
+import android.content.Context;
+import android.content.pm.PackageManager;
+import android.os.Build;
+import android.os.ParcelUuid;
+import android.util.Log;
+import android.widget.TextView;
+
+import androidx.core.app.ActivityCompat;
+
+import java.lang.reflect.Method;
+import java.util.List;
+import java.util.Set;
+
+public class CsLibrary4A {
+ boolean DEBUG = false, DEBUG2 = false;
+ String stringVersion = "18.0";
+ Utility utility;
+ Cs710Library4A cs710Library4A;
+ Cs108Library4A cs108Library4A;
+ Context context; TextView textViewLog;
+
+ public CsLibrary4A(Context context, TextView textViewLog) {
+ this.context = context;
+ this.textViewLog = textViewLog;
+ cs710Library4A = new Cs710Library4A(context, textViewLog); utility = cs710Library4A.utility;
+ cs710Library4A.setCsReaderConnectorCombo();
+ //cs108Library4A = new Cs108Library4A(context, textViewLog);
+ stringNOTCONNECT = " is called before Connection !!!";
+ dBuV_dBm_constant = RfidReader.dBuV_dBm_constant;
+ iNO_SUCH_SETTING = cs710Library4A.iNO_SUCH_SETTING;
+ }
+ public String getlibraryVersion() {
+ if (DEBUG) Log.i("Hello2", "getlibraryVersion");
+ String string710 = cs710Library4A.getlibraryVersion(); appendToLog("string710 = " + string710);
+ int iPos0 = string710.indexOf(".");
+ int iPos1 = string710.substring(iPos0 + 1).indexOf(".");
+ String string108 = (cs108Library4A != null ? cs108Library4A.getlibraryVersion() : string710); appendToLog("string108 = " + string108);
+ int iPos2 = string108.indexOf(".");
+ int iPos3 = string108.substring(iPos2 + 1).indexOf(".");
+ return stringVersion + "-" + string710.substring(iPos0 + iPos1 + 2) + "-" + string108.substring(iPos2 + iPos3 + 2);
+ }
+ public String checkVersion() {
+ if (DEBUG) Log.i("Hello2", "checkVersion");
+ if (isCs108Connected()) return cs108Library4A.checkVersion();
+ else if (isCs710Connected()) return cs710Library4A.checkVersion();
+ else Log.i("Hello2", "checkVersion" + stringNOTCONNECT);
+ return null;
+ }
+
+ //============ utility ============
+ public String byteArrayToString(byte[] packet) {
+ return utility.byteArrayToString(packet);
+ }
+ public void appendToLog(String s) {
+ utility.appendToLog(s);
+ }
+ public void appendToLogView(String s) {
+ utility.appendToLogView(s);
+ }
+ public String strFloat16toFloat32(String strData) {
+ return utility.strFloat16toFloat32(strData);
+ }
+ public String str2float16(String strData) {
+ return utility.str2float16(strData);
+ }
+ public float decodeCtesiusTemperature(String strActData, String strCalData) {
+ return utility.decodeCtesiusTemperature(strActData, strCalData);
+ }
+ public float decodeMicronTemperature(int iTag35, String strActData, String strCalData) {
+ return utility.decodeMicronTemperature(iTag35, strActData, strCalData);
+ }
+ public float decodeAsygnTemperature(String string) {
+ return utility.decodeAsygnTemperature(string);
+ }
+ public String temperatureC2F(String strValue) {
+ return utility.temperatureC2F(strValue);
+ }
+ public String temperatureF2C(String strValue) {
+ return utility.temperatureF2C(strValue);
+ }
+ public String getUpcSerial(String strEpc) {
+ return utility.getUpcSerial(strEpc);
+ }
+ public String getUpcSerialDetail(String strUpcSerial) {
+ return utility.getUpcSerialDetail(strUpcSerial);
+ }
+ public String getEpc4upcSerial(Utility.EpcClass epcClass, String filter, String companyPrefix, String itemReference, String serialNumber) {
+ return utility.getEpc4upcSerial(epcClass, filter, companyPrefix, itemReference, serialNumber);
+ }
+ public boolean checkHostProcessorVersion(String version, int majorVersion, int minorVersion, int buildVersion) {
+ return utility.checkHostProcessorVersion(version, majorVersion, minorVersion, buildVersion);
+ }
+
+ //============ android bluetooth ============
+ public boolean isBleScanning() {
+ if (DEBUG) Log.i("Hello2", "isBleScanning");
+ boolean bValue = false, bValue1 = false, bValue7 = false;
+ bValue1 = (cs108Library4A != null && cs108Library4A.isBleScanning());
+ bValue7 = cs710Library4A.isBleScanning();
+ if (bValue1 || bValue7) bValue = true;
+ return bValue;
+ }
+ public boolean scanLeDevice(final boolean enable) {
+ boolean bValue = false, bValue1 = false, bValue7 = false, DEBUG = true;
+ if (DEBUG) appendToLog("CsLibrary.scanLeDevice[" + enable + "]");
+
+ BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
+ if (bluetoothAdapter == null) {
+ appendToLog("CsLibrary.scanLeDevice: bluetoothAdapter is null");
+ // device doesn't support bluetooth
+ } else {
+ appendToLog("CsLibrary.scanLeDevice: bluetoothAdapter is valid");
+/*
+ if(!bluetoothAdapter.isEnabled()) {
+ Intent enableAdapter;
+ enableAdapter = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
+ startActivityForResult(enableAdapter, 0);
+ }
+*/
+ // Do whatever you want to do with your bluetoothAdapter
+ if (ActivityCompat.checkSelfPermission(context, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
+ // TODO: Consider calling
+ // ActivityCompat#requestPermissions
+ // here to request the missing permissions, and then overriding
+ // public void onRequestPermissionsResult(int requestCode, String[] permissions,
+ // int[] grantResults)
+ // to handle the case where the user grants the permission. See the documentation
+ // for ActivityCompat#requestPermissions for more details.
+ appendToLog("CsLibrary.scanLeDevice: bluetoothConnect permission is not granted");
+ } else {
+ appendToLog("CsLibrary.scanLeDevice: bluetoothConnect permission is granted");
+
+ BluetoothManager bluetoothManager = (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE);
+ //List bluetoothDevices = bluetoothManager.getConnectedDevices(GATT);
+ Set bluetoothDevices = bluetoothAdapter.getBondedDevices();
+ appendToLog("CsLibrary.scanLeDevice: bluetoothDevices size = " + bluetoothDevices.size());
+ int i = 0;
+ for (BluetoothDevice bluetoothDevice : bluetoothDevices) {
+ appendToLog("CsLibrary.scanLeDevice: " + i + ", Name = " + bluetoothDevice.getName());
+ appendToLog("CsLibrary.scanLeDevice: " + i + ", Address = " + bluetoothDevice.getAddress());
+ String string = "CsLibrary.scanLeDevice: " + i + ", Type = " + bluetoothDevice.getType();
+ switch (bluetoothDevice.getType()) {
+ case DEVICE_TYPE_CLASSIC:
+ string += " Classic - BR/EDR device";
+ break;
+ case DEVICE_TYPE_LE:
+ string += " Low Energy - LE only device";
+ break;
+ case DEVICE_TYPE_DUAL:
+ string += " Dual Mode - BR/EDR/LE device";
+ break;
+ default:
+ case DEVICE_TYPE_UNKNOWN:
+ string += " Unknown device";
+ break;
+ }
+ appendToLog(string);
+ appendToLog("CsLibrary.scanLeDevice: " + i + ", bluetoothClass = " + bluetoothDevice.getBluetoothClass().toString());
+ int iDeviceClass = bluetoothDevice.getBluetoothClass().getDeviceClass();
+ int iDeviceClassService = iDeviceClass >> 13;
+ int iDeviceClassMajor = (iDeviceClass & 0x1F00) >> 8;
+ int iDeviceClassMinor = (iDeviceClass & 0xFF) >> 2;
+ appendToLog("CsLibrary.scanLeDevice: " + i + ", bluetoothClass = " + String.format("%X", iDeviceClass)
+ + ", " + String.format("%X", iDeviceClassService)
+ + ", " + String.format("%X", iDeviceClassMajor)
+ + ", " + String.format("%X", iDeviceClassMinor));
+ appendToLog("CsLibrary.scanLeDevice: " + i + ", doesClassMatch[Profile_HID] = " + bluetoothDevice.getBluetoothClass().doesClassMatch(BluetoothClass.PROFILE_HID));
+ appendToLog("CsLibrary.scanLeDevice: " + i + ", doesClassMatch[Profile_HEADSET] = " + bluetoothDevice.getBluetoothClass().doesClassMatch(BluetoothClass.PROFILE_HEADSET));
+ appendToLog("CsLibrary.scanLeDevice: " + i + ", doesClassMatch[Profile_A2DP] = " + bluetoothDevice.getBluetoothClass().doesClassMatch(BluetoothClass.PROFILE_A2DP));
+ appendToLog("CsLibrary.scanLeDevice: " + i + ", hasService[LIMITED_DISCOVERABILITY] = " + bluetoothDevice.getBluetoothClass().hasService(LIMITED_DISCOVERABILITY));
+ appendToLog("CsLibrary.scanLeDevice: " + i + ", hasService[LE_AUDIO] = " + bluetoothDevice.getBluetoothClass().hasService(LE_AUDIO));
+ appendToLog("CsLibrary.scanLeDevice: " + i + ", describeContents = " + bluetoothDevice.describeContents());
+ boolean connected = false;
+ try {
+ Method m = bluetoothDevice.getClass().getMethod("isConnected", (Class[]) null);
+ connected = (boolean) m.invoke(bluetoothDevice, (Object[]) null);
+ } catch (Exception ex) {
+ appendToLog("CsLibrary.scanLeDevice: Exception " + ex.toString());
+ }
+ appendToLog("CsLibrary.scanLeDevice: " + i + ", connected = " + connected);
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.VANILLA_ICE_CREAM) {
+ appendToLog("CsLibrary.scanLeDevice: " + i + ", AddressType = " + bluetoothDevice.getAddressType());
+ }
+ string = "CsLibrary.scanLeDevice: " + i + ", BondState = ";
+ switch (bluetoothDevice.getBondState()) {
+ case BOND_NONE:
+ string += "None";
+ break;
+ case BOND_BONDING:
+ string += "Bonding";
+ break;
+ case BOND_BONDED:
+ string += "Bonded";
+ break;
+ default:
+ string += "Unknown";
+ break;
+ }
+ appendToLog(string);
+ ParcelUuid[] parcelUuids = bluetoothDevice.getUuids();
+ appendToLog("CsLibrary.scanLeDevice: " + i + ", Uuids.size = " + (parcelUuids == null ? "null" : parcelUuids.length));
+ for (int k = 0; parcelUuids != null && k < parcelUuids.length; k++) {
+ String string0 = "", string1 = "", string2 = parcelUuids[k].toString();
+ String string3 = string2.split("-")[0];
+ appendToLog("CsLibrary.scanLeDevice: string3 = " + string3);
+ int iString2 = 0;
+ if (string3.substring(0, 4).matches("0000")) iString2 = Integer.parseInt(string3, 16);
+ if (iString2 >= 0x1000 && iString2 < 0x1410) string0 = "SDP ";
+ else if (iString2 >= 0x1800 && iString2 < 0x1860) string0 = "GATT ";
+ if (iString2 == 0x1101) string1 = "Serial Port, ";
+ else if (iString2 == 0x110b) string1 = "Audio Sink, ";
+ else if (iString2 == 0x110e) string1 = "A/V Remote Control, ";
+ else if (iString2 == 0x1124) string1 = "HID, ";
+ else if (iString2 == 0x180f) string1 = "Battery, ";
+ else if (iString2 == 0x1812) {
+ string1 = "Human Interface Device, ";
+/*
+ UUID UUID_READER_SERVICE = UUID.fromString(string2);
+ BluetoothGattService s = bluetoothGatt.getService(service);
+ mReaderStreamOutCharacteristic = getCharacteristic(UUID_READER_SERVICE, UUID_READER_STREAM_OUT_CHARACTERISTIC);
+ mReaderStreamInCharacteristic = getCharacteristic(UUID_READER_SERVICE, UUID_READER_STREAM_IN_CHARACTERISTIC);
+*/
+ }
+ appendToLog("CsLibrary.scanLeDevice: " + i + "," + k + ", " + string0 + "Service Class: " + string1 + string2);
+ }
+
+ if (false) {
+ android.bluetooth.BluetoothGatt bluetoothGatt = bluetoothDevice.connectGatt(context, false, new BluetoothGattCallback() {
+ @Override
+ public void onCharacteristicChanged(android.bluetooth.BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
+ appendToLog("CsLibrary.scanLeDevice: onCharacteristicChanged");
+ super.onCharacteristicChanged(gatt, characteristic);
+ }
+ });
+ appendToLog("CsLibrary.scanLeDevice: " + i + ", connectGatt is " + (bluetoothGatt != null ? "valid" : "false"));
+ if (bluetoothGatt != null) {
+ List bluetoothGattServices = bluetoothGatt.getServices();
+ appendToLog("CsLibrary.scanLeDevice: " + i + ", bluetoothGattServices size is " + bluetoothGattServices.size());
+ for (int a = 0; a < bluetoothGattServices.size(); a++) {
+ appendToLog("CsLibrary.scanLeDevice: " + i + "," + a + " bluetoothGattService is " + bluetoothGattServices.get(a).toString());
+ }
+ }
+ }
+
+ String stringClassCode = bluetoothDevice.getBluetoothClass().toString().toUpperCase();
+ if (connected && (stringClassCode.matches("1F00") || stringClassCode.matches("540"))) {
+ if (false) {
+ BluetoothGatt.CsScanData scanResultA = new BluetoothGatt.CsScanData(bluetoothDevice, 0, null);
+ scanResultA.serviceUUID2p2 = 6;
+ cs710Library4A.csReaderConnector.mScanResultList.add(scanResultA);
+ appendToLog("CsLibrary.scanLeDevice: mScanResultList.size = " + cs710Library4A.mScanResultList.size());
+ } else {
+ cs710Library4A.bluetoothGatt.removeBond(bluetoothDevice);
+ }
+ }
+ i++;
+ }
+ }
+ }
+
+ bValue1 = (cs108Library4A != null && cs108Library4A.scanLeDevice(enable));
+ bValue7 = cs710Library4A.scanLeDevice(enable);
+ if (bValue1 || bValue7) bValue = true;
+ return bValue;
+ }
+ public BluetoothGatt.CsScanData getNewDeviceScanned() {
+ if (DEBUG2) Log.i("Hello2", "getNewDeviceScanned");
+ BluetoothGatt.CsScanData csScanData1;
+ BluetoothGatt.CsScanData csScanData7 = cs710Library4A.getNewDeviceScanned();
+ BluetoothGatt.CsScanData csScanData = null;
+ if (csScanData7 == null) {
+ csScanData1 = (cs108Library4A == null ? null : cs108Library4A.getNewDeviceScanned());
+ if (true) csScanData = csScanData1;
+ else if (csScanData1 != null) {
+ csScanData = new BluetoothGatt.CsScanData(csScanData1.getDevice(), csScanData1.rssi, csScanData1.getScanRecord());
+ csScanData.serviceUUID2p2 = csScanData1.serviceUUID2p2;
+ }
+ } else if (true) {
+ csScanData = csScanData7;
+ } else {
+ csScanData = new BluetoothGatt.CsScanData(csScanData7.getDevice(), csScanData7.rssi, csScanData7.getScanRecord());
+ csScanData.serviceUUID2p2 = csScanData7.serviceUUID2p2;
+ }
+ if (csScanData != null) {
+ //appendToLog("DeviceFinder, CsLibrary4A.getNewDeviceScanned: csScanData.getAddress is " + csScanData.getAddress());
+ }
+ if (csScanData != null) appendToLog("found982 with name = " + csScanData.name + ", device.name = " + csScanData.device.getName());
+ return csScanData;
+ }
+ public String getBluetoothDeviceAddress() {
+ if (DEBUG) Log.i("Hello2", "getBluetoothDeviceAddress");
+ if (isCs108Connected()) return cs108Library4A.getBluetoothDeviceAddress();
+ else if (isCs710Connected()) return cs710Library4A.getBluetoothDeviceAddress();
+ else Log.i("Hello2", "getBluetoothDeviceAddress" + stringNOTCONNECT);
+ return null;
+ }
+ public String getBluetoothDeviceName() {
+ if (DEBUG) Log.i("Hello2", "getBluetoothDeviceName");
+ if (isCs108Connected()) return cs108Library4A.getBluetoothDeviceName();
+ else if (isCs710Connected()) return cs710Library4A.getBluetoothDeviceName();
+ else Log.i("Hello2", "getBluetoothDeviceName" + stringNOTCONNECT);
+ return null;
+ }
+ public boolean isBleConnected() {
+ boolean bValue = false, DEBUG = true;
+ if (DEBUG && false) Log.i("Hello2", "CsLibrary4A.isBleConnected");
+ if (isCs108Connected()) {
+ bValue = cs108Library4A.isBleConnected();
+ if (bValue == false) bConnectStatus = 0;
+ } else if (isCs710Connected()) {
+ bValue = cs710Library4A.isBleConnected();
+ if (bValue == false) bConnectStatus = 0;
+ } else {
+ bValue = cs710Library4A.isBleConnected();
+ if (bValue) bConnectStatus = 7;
+ else {
+ bValue = (cs108Library4A != null && cs108Library4A.isBleConnected());
+ if (bValue) bConnectStatus = 1;
+ else bConnectStatus = 0;
+ }
+ }
+ return bValue;
+ }
+ public void connect(ReaderDevice readerDevice) {
+ if (DEBUG || true) Log.i("Hello", "CsLibrary4A.connect: readerDevice is " + (readerDevice != null ? "valid" : "null") + ", iServiceUuidConnectedBefore = " + iServiceUuidConnectedBefore);
+ cs710Library4A.bluetoothGatt.removeBond(readerDevice);
+ int iServiceUuid = -1;
+ if (readerDevice == null) iServiceUuid = iServiceUuidConnectedBefore;
+ else iServiceUuid = readerDevice.getServiceUUID2p1();
+ Log.i("Hello", "CsLibrary4A.connect: iServiceUuid = " + iServiceUuid);
+ if (iServiceUuid == 0 || iServiceUuid == 1 || iServiceUuid == 4) {
+ if (true) {
+ appendToLog("CsLibrary4A.connect: going to connect cs108");
+ if (cs108Library4A == null) cs108Library4A = new Cs108Library4A(context, textViewLog);
+ cs108Library4A.connect(readerDevice); iServiceUuidConnectedBefore = 0;
+ } else {
+ if (true) {
+ cs108Library4A.connect(readerDevice);
+ iServiceUuidConnectedBefore = 0;
+ } else {
+ ReaderDevice readerDevice1 = null;
+ if (readerDevice != null) readerDevice1 = new ReaderDevice(
+ readerDevice.getName(), readerDevice.getAddress(), readerDevice.getSelected(),
+ readerDevice.getDetails(), readerDevice.getCount(), readerDevice.getRssi(),
+ readerDevice.getServiceUUID2p1());
+ cs108Library4A.connect(readerDevice1);
+ iServiceUuidConnectedBefore = 0;
+ }
+ }
+ } else if (iServiceUuid == 2 || iServiceUuid == 3 || iServiceUuid == 5 || iServiceUuid == 6) {
+ appendToLog("CsLibrary4A.connect: going to connect cs710");
+ cs710Library4A.connect(readerDevice); iServiceUuidConnectedBefore = 2;
+ } else appendToLog("CsLibrary4A.connect: invalid serviceUUID = " + (readerDevice == null ? "null" : readerDevice.getServiceUUID2p1()));
+ }
+ public void disconnect(boolean tempDisconnect) {
+ //appendToLog("CsLibrary4A.disconnect, Fragment: Starts");
+ //ReaderDevice readerDevice = null;
+ //if (isCs108Connected() && cs108Library4A != null) readerDevice = cs108Library4A.readerDeviceConnect;
+ //else if (isCs710Connected() && cs710Library4A != null) readerDevice = cs710Library4A.readerDeviceConnect;
+ //cs710Library4A.bluetoothGatt.removeBond(readerDevice);
+
+ if (isCs108Connected()) cs108Library4A.disconnect(tempDisconnect);
+ else if (isCs710Connected()) cs710Library4A.disconnect(tempDisconnect);
+ }
+ public boolean forceBTdisconnect() {
+ if (DEBUG) Log.i("Hello2", "forceBTdisconnect");
+ if (isCs108Connected()) return cs108Library4A.forceBTdisconnect();
+ else if (isCs710Connected()) return cs710Library4A.forceBTdisconnect();
+ else Log.i("Hello2", "forceBTdisconnect" + stringNOTCONNECT);
+ return false;
+ }
+ public int getRssi() {
+ if (DEBUG) Log.i("Hello2", "getRssi");
+ if (isCs108Connected()) return cs108Library4A.getRssi();
+ else if (isCs710Connected()) return cs710Library4A.getRssi();
+ else Log.i("Hello2", "getRssi" + stringNOTCONNECT);
+ return -1;
+ } //411
+ public long getStreamInRate() {
+ if (DEBUG) Log.i("Hello2", "getStreamInRate");
+ if (isCs108Connected()) return cs108Library4A.getStreamInRate();
+ else if (isCs710Connected()) return cs710Library4A.getStreamInRate();
+ else Log.i("Hello2", "getStreamInRate" + stringNOTCONNECT);
+ return -1;
+ }
+ public int get98XX() {
+ if (DEBUG) Log.i("Hello2", "get98XX");
+ if (isCs108Connected()) return cs108Library4A.get98XX();
+ else if (isCs710Connected()) return cs710Library4A.get98XX();
+ else Log.i("Hello2", "get98XX" + stringNOTCONNECT);
+ return -1;
+ }
+
+
+ //============ Rfid ============
+ public String getAuthMatchData() {
+ if (DEBUG) Log.i("Hello2", "getAuthMatchData");
+ if (isCs108Connected()) return cs108Library4A.getAuthMatchData();
+ else if (isCs710Connected()) return cs710Library4A.getAuthMatchData();
+ else Log.i("Hello2", "getAuthMatchData" + stringNOTCONNECT);
+ return null;
+ }
+ public boolean setAuthMatchData(String mask) {
+ if (DEBUG) Log.i("Hello2", "setAuthMatchData");
+ if (isCs108Connected()) return cs108Library4A.setAuthMatchData(mask);
+ else if (isCs710Connected()) return cs710Library4A.setAuthMatchData(mask);
+ else Log.i("Hello2", "setAuthMatchData" + stringNOTCONNECT);
+ return false;
+ }
+ public int getStartQValue() {
+ if (DEBUG) Log.i("Hello2", "getStartQValue");
+ if (isCs108Connected()) return cs108Library4A.getStartQValue();
+ else if (isCs710Connected()) return cs710Library4A.getStartQValue();
+ else Log.i("Hello2", "getStartQValue" + stringNOTCONNECT);
+ return -1;
+ }
+ public int getMaxQValue() {
+ if (DEBUG) Log.i("Hello2", "getMaxQValue");
+ if (isCs108Connected()) return cs108Library4A.getMaxQValue();
+ else if (isCs710Connected()) return cs710Library4A.getMaxQValue();
+ else Log.i("Hello2", "getMaxQValue" + stringNOTCONNECT);
+ return -1;
+ }
+ public int getMinQValue() {
+ if (DEBUG) Log.i("Hello2", "getMinQValue");
+ if (isCs108Connected()) return cs108Library4A.getMinQValue();
+ else if (isCs710Connected()) return cs710Library4A.getMinQValue();
+ else Log.i("Hello2", "getMinQValue" + stringNOTCONNECT);
+ return -1;
+ }
+ public boolean setDynamicQParms(int startQValue, int minQValue, int maxQValue, int retryCount) {
+ if (DEBUG) Log.i("Hello2", "setDynamicQParms");
+ if (isCs108Connected()) return cs108Library4A.setDynamicQParms(startQValue, minQValue, maxQValue, retryCount);
+ else if (isCs710Connected()) return cs710Library4A.setDynamicQParms(startQValue, minQValue, maxQValue, retryCount);
+ else Log.i("Hello2", "setDynamicQParms" + stringNOTCONNECT);
+ return false;
+ }
+ public int getFixedQValue() {
+ if (DEBUG) Log.i("Hello2", "getFixedQValue");
+ if (isCs108Connected()) return cs108Library4A.getFixedQValue();
+ else if (isCs710Connected()) return cs710Library4A.getFixedQValue();
+ else Log.i("Hello2", "getFixedQValue" + stringNOTCONNECT);
+ return -1;
+ }
+ public int getFixedRetryCount() {
+ if (DEBUG) Log.i("Hello2", "getFixedRetryCount");
+ if (isCs108Connected()) return cs108Library4A.getFixedRetryCount();
+ else if (isCs710Connected()) return cs710Library4A.getFixedRetryCount();
+ else Log.i("Hello2", "getFixedRetryCount" + stringNOTCONNECT);
+ return -1;
+ }
+ public boolean getRepeatUnitNoTags() {
+ if (DEBUG) Log.i("Hello2", "getRepeatUnitNoTags");
+ if (isCs108Connected()) return cs108Library4A.getRepeatUnitNoTags();
+ else if (isCs710Connected()) return cs710Library4A.getRepeatUnitNoTags();
+ else Log.i("Hello2", "getRepeatUnitNoTags" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean setFixedQParms(int qValue, int retryCount, boolean repeatUnitNoTags) {
+ if (DEBUG) Log.i("Hello2", "setFixedQParms");
+ if (isCs108Connected()) return cs108Library4A.setFixedQParms(qValue, retryCount, repeatUnitNoTags);
+ else if (isCs710Connected()) return cs710Library4A.setFixedQParms(qValue, retryCount, repeatUnitNoTags);
+ else Log.i("Hello2", "setFixedQParms" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean getChannelHoppingDefault() {
+ if (DEBUG) Log.i("Hello2", "getChannelHoppingDefault");
+ if (isCs108Connected()) return cs108Library4A.getChannelHoppingDefault();
+ else if (isCs710Connected()) return cs710Library4A.getChannelHoppingDefault();
+ else Log.i("Hello2", "getChannelHoppingDefault" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean getRfidOnStatus() {
+ if (DEBUG) Log.i("Hello2", "getRfidOnStatus");
+ if (isCs108Connected()) return cs108Library4A.getRfidOnStatus();
+ else if (isCs710Connected()) return cs710Library4A.getRfidOnStatus();
+ else Log.i("Hello2", "getRfidOnStatus" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean isRfidFailure() {
+ if (DEBUG2) Log.i("Hello2", "isRfidFailure");
+ if (isCs108Connected()) return cs108Library4A.isRfidFailure();
+ else if (isCs710Connected()) return cs710Library4A.isRfidFailure();
+ return false;
+ }
+ public void setReaderDefault() {
+ if (DEBUG) Log.i("Hello2", "setReaderDefault");
+ if (isCs108Connected()) cs108Library4A.setReaderDefault();
+ else if (isCs710Connected()) cs710Library4A.setReaderDefault();
+ else Log.i("Hello2", "setReaderDefault" + stringNOTCONNECT);
+ }
+ public String getMacVer() {
+ if (DEBUG) Log.i("Hello2", "getMacVer");
+ appendToLog("CsLibrary4A.getMacVer");
+ if (isCs108Connected()) return cs108Library4A.getMacVer();
+ else if (isCs710Connected()) return cs710Library4A.getMacVer();
+ else Log.i("Hello2", "getMacVer" + stringNOTCONNECT);
+ return null;
+ }
+ public String getRadioSerial() {
+ if (DEBUG) Log.i("Hello2", "getRadioSerial");
+ if (isCs108Connected()) return cs108Library4A.getRadioSerial();
+ else if (isCs710Connected()) return cs710Library4A.getRadioSerial();
+ else Log.i("Hello2", "getRadioSerial" + stringNOTCONNECT);
+ return null;
+ }
+ public String getRadioBoardVersion() {
+ if (DEBUG) Log.i("Hello2", "getRadioBoardVersion");
+ if (isCs108Connected()) return cs108Library4A.getRadioBoardVersion();
+ else if (isCs710Connected()) return cs710Library4A.getRadioBoardVersion();
+ else Log.i("Hello2", "getRadioBoardVersion" + stringNOTCONNECT);
+ return null;
+ }
+ public int getPortNumber() {
+ if (DEBUG) Log.i("Hello2", "getPortNumber");
+ if (isCs108Connected()) return cs108Library4A.getPortNumber();
+ else if (isCs710Connected()) return cs710Library4A.getPortNumber();
+ else Log.i("Hello2", "getPortNumber" + stringNOTCONNECT);
+ return -1;
+ }
+ public int getAntennaSelect() {
+ if (DEBUG) Log.i("Hello2", "getAntennaSelect");
+ if (isCs108Connected()) return cs108Library4A.getAntennaSelect();
+ else if (isCs710Connected()) return cs710Library4A.getAntennaSelect();
+ else Log.i("Hello2", "getAntennaSelect" + stringNOTCONNECT);
+ return -1;
+ }
+ public boolean setAntennaSelect(int number) {
+ if (DEBUG) Log.i("Hello2", "setAntennaSelect");
+ if (isCs108Connected()) return cs108Library4A.setAntennaSelect(number);
+ else if (isCs710Connected()) return cs710Library4A.setAntennaSelect(number);
+ else Log.i("Hello2", "setAntennaSelect" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean getAntennaEnable() {
+ if (DEBUG) Log.i("Hello2", "getAntennaEnable");
+ if (isCs108Connected()) return cs108Library4A.getAntennaEnable();
+ else if (isCs710Connected()) return cs710Library4A.getAntennaEnable();
+ else Log.i("Hello2", "getAntennaEnable" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean setAntennaEnable(boolean enable) {
+ if (DEBUG) Log.i("Hello2", "setAntennaEnable");
+ if (isCs108Connected()) return cs108Library4A.setAntennaEnable(enable);
+ else if (isCs710Connected()) return cs710Library4A.setAntennaEnable(enable);
+ else Log.i("Hello2", "setAntennaEnable" + stringNOTCONNECT);
+ return false;
+ }
+ public long getAntennaDwell() {
+ if (DEBUG) Log.i("Hello2", "getAntennaDwell");
+ if (isCs108Connected()) return cs108Library4A.getAntennaDwell();
+ else if (isCs710Connected()) return cs710Library4A.getAntennaDwell();
+ else Log.i("Hello2", "getAntennaDwell" + stringNOTCONNECT);
+ return -1;
+ }
+ public boolean setAntennaDwell(long antennaDwell) {
+ if (DEBUG) Log.i("Hello2", "setAntennaDwell");
+ if (isCs108Connected()) return cs108Library4A.setAntennaDwell(antennaDwell);
+ else if (isCs710Connected()) return cs710Library4A.setAntennaDwell(antennaDwell);
+ else Log.i("Hello2", "setAntennaDwell" + stringNOTCONNECT);
+ return false;
+ }
+ public long getPwrlevel() {
+ if (DEBUG) Log.i("Hello2", "getPwrlevel");
+ if (isCs108Connected()) return cs108Library4A.getPwrlevel();
+ else if (isCs710Connected()) return cs710Library4A.getPwrlevel();
+ else Log.i("Hello2", "getPwrlevel" + stringNOTCONNECT);
+ return -1;
+ }
+ public boolean setPowerLevel(long pwrlevel) {
+ if (DEBUG) Log.i("Hello2", "setPowerLevel");
+ if (isCs108Connected()) return cs108Library4A.setPowerLevel(pwrlevel);
+ else if (isCs710Connected()) return cs710Library4A.setPowerLevel(pwrlevel);
+ else Log.i("Hello2", "setPowerLevel" + stringNOTCONNECT);
+ return false;
+ }
+ public int getQueryTarget() {
+ if (DEBUG) Log.i("Hello2", "getQueryTarget");
+ if (isCs108Connected()) return cs108Library4A.getQueryTarget();
+ else if (isCs710Connected()) return cs710Library4A.getQueryTarget();
+ else Log.i("Hello2", "getQueryTarget" + stringNOTCONNECT);
+ return -1;
+ }
+ public int getQuerySession() {
+ if (DEBUG) Log.i("Hello2", "getQuerySession");
+ if (isCs108Connected()) return cs108Library4A.getQuerySession();
+ else if (isCs710Connected()) return cs710Library4A.getQuerySession();
+ else Log.i("Hello2", "getQuerySession" + stringNOTCONNECT);
+ return -1;
+ }
+ public int getQuerySelect() {
+ if (DEBUG) Log.i("Hello2", "getQuerySelect");
+ if (isCs108Connected()) return cs108Library4A.getQuerySelect();
+ else if (isCs710Connected()) return cs710Library4A.getQuerySelect();
+ else Log.i("Hello2", "getQuerySelect" + stringNOTCONNECT);
+ return -1;
+ }
+ public boolean setTagGroup(int sL, int session, int target1) {
+ if (DEBUG) Log.i("Hello2", "setTagGroup");
+ if (isCs108Connected()) return cs108Library4A.setTagGroup(sL, session, target1);
+ else if (isCs710Connected()) return cs710Library4A.setTagGroup(sL, session, target1);
+ else Log.i("Hello2", "setTagGroup" + stringNOTCONNECT);
+ return false;
+ }
+ public int getTagFocus() {
+ if (DEBUG) Log.i("Hello2", "getTagFocus");
+ if (isCs108Connected()) return cs108Library4A.getTagFocus();
+ else if (isCs710Connected()) return cs710Library4A.getTagFocus();
+ else Log.i("Hello2", "getTagFocus" + stringNOTCONNECT);
+ return -1;
+ }
+ public boolean setTagFocus(boolean tagFocusNew) {
+ if (DEBUG) Log.i("Hello2", "setTagFocus");
+ if (isCs108Connected()) return cs108Library4A.setTagFocus(tagFocusNew);
+ else if (isCs710Connected()) return cs710Library4A.setTagFocus(tagFocusNew);
+ else Log.i("Hello2", "setTagFocus" + stringNOTCONNECT);
+ return false;
+ }
+ public int getFastId() {
+ if (DEBUG) Log.i("Hello2", "getFastId");
+ if (isCs108Connected()) return cs108Library4A.getFastId();
+ else if (isCs710Connected()) return cs710Library4A.getFastId();
+ else Log.i("Hello2", "getFastId" + stringNOTCONNECT);
+ return -1;
+ }
+ public boolean setFastId(boolean fastIdNew) {
+ if (DEBUG) Log.i("Hello2", "setFastId");
+ if (isCs108Connected()) return cs108Library4A.setFastId(fastIdNew);
+ else if (isCs710Connected()) return cs710Library4A.setFastId(fastIdNew);
+ else Log.i("Hello2", "setFastId" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean getInvAlgo() {
+ if (DEBUG) Log.i("Hello2", "getInvAlgo");
+ if (isCs108Connected()) return cs108Library4A.getInvAlgo();
+ else if (isCs710Connected()) return cs710Library4A.getInvAlgo();
+ else Log.i("Hello2", "getInvAlgo" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean setInvAlgo(boolean dynamicAlgo) {
+ if (DEBUG) Log.i("Hello2", "setInvAlgo");
+ if (isCs108Connected()) return cs108Library4A.setInvAlgo(dynamicAlgo);
+ else if (isCs710Connected()) return cs710Library4A.setInvAlgo(dynamicAlgo);
+ else Log.i("Hello2", "setInvAlgo" + stringNOTCONNECT);
+ return false;
+ }
+ public List getProfileList() {
+ if (DEBUG) Log.i("Hello2", "getProfileList");
+ if (isCs108Connected()) return cs108Library4A.getProfileList();
+ else if (isCs710Connected()) return cs710Library4A.getProfileList();
+ else Log.i("Hello2", "getProfileList" + stringNOTCONNECT);
+ return null;
+ }
+ public int getCurrentProfile() {
+ if (DEBUG) Log.i("Hello2", "getCurrentProfile");
+ if (isCs108Connected()) return cs108Library4A.getCurrentProfile();
+ else if (isCs710Connected()) return cs710Library4A.getCurrentProfile();
+ else Log.i("Hello2", "getCurrentProfile" + stringNOTCONNECT);
+ return -1;
+ }
+ public boolean setBasicCurrentLinkProfile() {
+ if (DEBUG) Log.i("Hello2", "setBasicCurrentLinkProfile");
+ if (isCs108Connected()) return true;
+ else if (isCs710Connected()) return cs710Library4A.setBasicCurrentLinkProfile();
+ else Log.i("Hello2", "setBasicCurrentLinkProfile" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean setCurrentLinkProfile(int profile) {
+ if (DEBUG) Log.i("Hello2", "setCurrentLinkProfile to " + profile);
+ if (isCs108Connected()) return cs108Library4A.setCurrentLinkProfile(profile);
+ else if (isCs710Connected()) return cs710Library4A.setCurrentLinkProfile(profile);
+ else Log.i("Hello2", "setCurrentLinkProfile" + stringNOTCONNECT);
+ return false;
+ }
+ public void resetEnvironmentalRSSI() {
+ if (DEBUG) Log.i("Hello2", "resetEnvironmentalRSSI");
+ if (isCs108Connected()) cs108Library4A.resetEnvironmentalRSSI();
+ else if (isCs710Connected()) cs710Library4A.resetEnvironmentalRSSI();
+ else Log.i("Hello2", "resetEnvironmentalRSSI" + stringNOTCONNECT);
+ }
+ public String getEnvironmentalRSSI() {
+ if (DEBUG) Log.i("Hello2", "getEnvironmentalRSSI");
+ if (isCs108Connected()) return cs108Library4A.getEnvironmentalRSSI();
+ else if (isCs710Connected()) return cs710Library4A.getEnvironmentalRSSI();
+ else Log.i("Hello2", "getEnvironmentalRSSI" + stringNOTCONNECT);
+ return null;
+ }
+ public int getHighCompression() {
+ if (DEBUG) Log.i("Hello2", "getHighCompression");
+ if (isCs108Connected()) return cs108Library4A.getHighCompression();
+ else if (isCs710Connected()) return cs710Library4A.getHighCompression();
+ else Log.i("Hello2", "getHighCompression" + stringNOTCONNECT);
+ return -1;
+ }
+ public int getRflnaGain() {
+ if (DEBUG) Log.i("Hello2", "getRflnaGain");
+ if (isCs108Connected()) return cs108Library4A.getRflnaGain();
+ else if (isCs710Connected()) return cs710Library4A.getRflnaGain();
+ else Log.i("Hello2", "getRflnaGain" + stringNOTCONNECT);
+ return -1;
+ }
+ public int getIflnaGain() {
+ if (DEBUG) Log.i("Hello2", "getIflnaGain");
+ if (isCs108Connected()) return cs108Library4A.getIflnaGain();
+ else if (isCs710Connected()) return cs710Library4A.getIflnaGain();
+ else Log.i("Hello2", "getIflnaGain" + stringNOTCONNECT);
+ return -1;
+ }
+ public int getAgcGain() {
+ if (DEBUG) Log.i("Hello2", "getAgcGain");
+ if (isCs108Connected()) return cs108Library4A.getAgcGain();
+ else if (isCs710Connected()) return cs710Library4A.getAgcGain();
+ else Log.i("Hello2", "getAgcGain" + stringNOTCONNECT);
+ return -1;
+ }
+ public int getRxGain() {
+ if (DEBUG) Log.i("Hello2", "getRxGain");
+ if (isCs108Connected()) return cs108Library4A.getRxGain();
+ else if (isCs710Connected()) return cs710Library4A.getRxGain();
+ else Log.i("Hello2", "getRxGain" + stringNOTCONNECT);
+ return -1;
+ }
+ public boolean setRxGain(int highCompression, int rflnagain, int iflnagain, int agcgain) {
+ if (DEBUG) Log.i("Hello2", "setRxGain");
+ if (isCs108Connected()) return cs108Library4A.setRxGain(highCompression, rflnagain, iflnagain, agcgain);
+ else if (isCs710Connected()) return cs710Library4A.setRxGain(highCompression, rflnagain, iflnagain, agcgain);
+ else Log.i("Hello2", "setRxGain" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean setRxGain(int rxGain) {
+ if (DEBUG) Log.i("Hello2", "setRxGain");
+ if (isCs108Connected()) return cs108Library4A.setRxGain(rxGain);
+ else if (isCs710Connected()) return cs710Library4A.setRxGain(rxGain);
+ else Log.i("Hello2", "setRxGain" + stringNOTCONNECT);
+ return false;
+ }
+ public int FreqChnCnt() {
+ if (DEBUG) Log.i("Hello2", "FreqChnCnt");
+ if (isCs108Connected()) return cs108Library4A.FreqChnCnt();
+ else if (isCs710Connected()) return cs710Library4A.FreqChnCnt();
+ else Log.i("Hello2", "FreqChnCnt" + stringNOTCONNECT);
+ return -1;
+ }
+ public double getLogicalChannel2PhysicalFreq(int channel) {
+ if (DEBUG) Log.i("Hello2", "getLogicalChannel2PhysicalFreq");
+ if (isCs108Connected()) return cs108Library4A.getLogicalChannel2PhysicalFreq(channel);
+ else if (isCs710Connected()) return cs710Library4A.getLogicalChannel2PhysicalFreq(channel);
+ else Log.i("Hello2", "getLogicalChannel2PhysicalFreq" + stringNOTCONNECT);
+ return -1;
+ }
+ public byte getTagDelay() {
+ if (DEBUG) Log.i("Hello2", "getTagDelay");
+ if (isCs108Connected()) return cs108Library4A.getTagDelay();
+ else if (isCs710Connected()) return cs710Library4A.getTagDelay();
+ else Log.i("Hello2", "getTagDelay" + stringNOTCONNECT);
+ return -1;
+ }
+ public boolean setTagDelay(byte tagDelay) {
+ if (DEBUG) Log.i("Hello2", "setTagDelay");
+ if (isCs108Connected()) return cs108Library4A.setTagDelay(tagDelay);
+ else if (isCs710Connected()) return cs710Library4A.setTagDelay(tagDelay);
+ else Log.i("Hello2", "setTagDelay" + stringNOTCONNECT);
+ return false;
+ }
+ public byte getIntraPkDelay() {
+ if (DEBUG) Log.i("Hello2", "getIntraPkDelay");
+ if (isCs108Connected()) return cs108Library4A.getIntraPkDelay();
+ else if (isCs710Connected()) return cs710Library4A.getIntraPkDelay();
+ else Log.i("Hello2", "getIntraPkDelay" + stringNOTCONNECT);
+ return -1;
+ }
+ public boolean setIntraPkDelay(byte intraPkDelay) {
+ if (DEBUG) Log.i("Hello2", "setIntraPkDelay");
+ if (isCs108Connected()) return cs108Library4A.setIntraPkDelay(intraPkDelay);
+ else if (isCs710Connected()) return cs710Library4A.setIntraPkDelay(intraPkDelay);
+ else Log.i("Hello2", "setIntraPkDelay" + stringNOTCONNECT);
+ return false;
+ }
+ public byte getDupDelay() {
+ if (DEBUG) Log.i("Hello2", "getDupDelay");
+ if (isCs108Connected()) return cs108Library4A.getDupDelay();
+ else if (isCs710Connected()) return cs710Library4A.getDupDelay();
+ else Log.i("Hello2", "getDupDelay" + stringNOTCONNECT);
+ return -1;
+ }
+ public boolean setDupDelay(byte dupElim) {
+ if (DEBUG) Log.i("Hello2", "setDupDelay");
+ if (isCs108Connected()) return cs108Library4A.setDupDelay(dupElim);
+ else if (isCs710Connected()) return cs710Library4A.setDupDelay(dupElim);
+ else Log.i("Hello2", "setDupDelay" + stringNOTCONNECT);
+ return false;
+ }
+ public long getCycleDelay() {
+ if (DEBUG) Log.i("Hello2", "getCycleDelay");
+ if (isCs108Connected()) return cs108Library4A.getCycleDelay();
+ else if (isCs710Connected()) return cs710Library4A.getCycleDelay();
+ else Log.i("Hello2", "getCycleDelay" + stringNOTCONNECT);
+ return -1;
+ }
+ public boolean setCycleDelay(long cycleDelay) {
+ if (DEBUG) Log.i("Hello2", "setCycleDelay");
+ if (isCs108Connected()) return cs108Library4A.setCycleDelay(cycleDelay);
+ else if (isCs710Connected()) return cs710Library4A.setCycleDelay(cycleDelay);
+ return false;
+ }
+ public void getAuthenticateReplyLength() {
+ if (DEBUG) Log.i("Hello2", "getAuthenticateReplyLength");
+ if (isCs108Connected()) cs108Library4A.getAuthenticateReplyLength();
+ else if (isCs710Connected()) cs710Library4A.getAuthenticateReplyLength();
+ else Log.i("Hello2", "getAuthenticateReplyLength" + stringNOTCONNECT);
+ }
+ public boolean setTamConfiguration(boolean header, String matchData) {
+ if (DEBUG | true) Log.i("Hello2", "setTamConfiguration with header = " + header + ", matchData = " + matchData);
+ if (isCs108Connected()) return cs108Library4A.setTamConfiguration(header, matchData);
+ else if (isCs710Connected()) return cs710Library4A.setTamConfiguration(header, matchData);
+ else Log.i("Hello2", "setTam1Configuration");
+ return false;
+ }
+ public boolean setTam1Configuration(int keyId, String matchData) {
+ if (DEBUG | true) Log.i("Hello2", "setTam1Configuration with KeyId = " + keyId + ", matchData = " + matchData);
+ if (isCs108Connected()) return cs108Library4A.setTam1Configuration(keyId, matchData);
+ else if (isCs710Connected()) return cs710Library4A.setTam1Configuration(keyId, matchData);
+ else Log.i("Hello2", "setTam1Configuration");
+ return false;
+ }
+ public boolean setTam2Configuration(int keyId, String matchData, int profile, int offset, int blockId, int protMode) {
+ if (DEBUG) Log.i("Hello2", "setTam2Configuration");
+ if (isCs108Connected()) return cs108Library4A.setTam2Configuration(keyId, matchData, profile, offset, blockId, protMode);
+ else if (isCs710Connected()) return cs710Library4A.setTam2Configuration(keyId, matchData, profile, offset, blockId, protMode);
+ else Log.i("Hello2", "setTam2Configuration");
+ return false;
+ }
+ public int getUntraceableEpcLength() {
+ if (DEBUG) Log.i("Hello2", "getUntraceableEpcLength");
+ if (isCs108Connected()) return cs108Library4A.getUntraceableEpcLength();
+ else if (isCs710Connected()) return cs710Library4A.getUntraceableEpcLength();
+ else Log.i("Hello2", "getUntraceableEpcLength" + stringNOTCONNECT);
+ return -1;
+ }
+ public boolean setUntraceable(boolean bHideEpc, int ishowEpcSize, int iHideTid, boolean bHideUser, boolean bHideRange) {
+ Log.i("Hello2", "setUntraceable 1");
+ return false;
+ }
+ public boolean setUntraceable(int range, boolean user, int tid, int epcLength, boolean epc, boolean uxpc) {
+ if (DEBUG) Log.i("Hello2", "setUntraceable");
+ if (isCs108Connected()) return cs108Library4A.setUntraceable(range, user, tid, epcLength, epc, uxpc);
+ else if (isCs710Connected()) return false;
+ else Log.i("Hello2", "setUntraceable" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean setAuthenticateConfiguration() {
+ if (DEBUG) Log.i("Hello2", "setAuthenticateConfiguration");
+ if (isCs108Connected()) return cs108Library4A.setAuthenticateConfiguration();
+ else if (isCs710Connected()) return cs710Library4A.setAuthenticateConfiguration();
+ else Log.i("Hello2", "setAuthenticateConfiguration" + stringNOTCONNECT);
+ return false;
+ }
+ public int getRetryCount() {
+ if (DEBUG) Log.i("Hello2", "getRetryCount");
+ if (isCs108Connected()) return cs108Library4A.getRetryCount();
+ else if (isCs710Connected()) return cs710Library4A.getRetryCount();
+ else Log.i("Hello2", "getRetryCount" + stringNOTCONNECT);
+ return -1;
+ }
+ public boolean setRetryCount(int retryCount) {
+ if (DEBUG) Log.i("Hello2", "setRetryCount");
+ if (isCs108Connected()) return cs108Library4A.setRetryCount(retryCount);
+ else if (isCs710Connected()) return cs710Library4A.setRetryCount(retryCount);
+ else Log.i("Hello2", "setRetryCount" + stringNOTCONNECT);
+ return false;
+ }
+ public int getInvSelectIndex() {
+ if (DEBUG) Log.i("Hello2", "getInvSelectIndex");
+ if (isCs108Connected()) return cs108Library4A.getInvSelectIndex();
+ else if (isCs710Connected()) return cs710Library4A.getInvSelectIndex();
+ else Log.i("Hello2", "getInvSelectIndex" + stringNOTCONNECT);
+ return -1;
+ } //2286
+ public boolean getSelectEnable() {
+ if (DEBUG) Log.i("Hello2", "getSelectEnable");
+ if (isCs108Connected()) return cs108Library4A.getSelectEnable();
+ else if (isCs710Connected()) return cs710Library4A.getSelectEnable();
+ else Log.i("Hello2", "getSelectEnable" + stringNOTCONNECT);
+ return false;
+ }
+ public int getSelectTarget() {
+ if (DEBUG) Log.i("Hello2", "getSelectTarget");
+ if (isCs108Connected()) return cs108Library4A.getSelectTarget();
+ else if (isCs710Connected()) return cs710Library4A.getSelectTarget();
+ else Log.i("Hello2", "getSelectTarget" + stringNOTCONNECT);
+ return -1;
+ }
+ public int getSelectAction() {
+ if (DEBUG) Log.i("Hello2", "getSelectAction");
+ if (isCs108Connected()) return cs108Library4A.getSelectAction();
+ else if (isCs710Connected()) return cs710Library4A.getSelectAction();
+ else Log.i("Hello2", "getSelectAction" + stringNOTCONNECT);
+ return -1;
+ }
+ public int getSelectMaskBank() {
+ if (DEBUG) Log.i("Hello2", "getSelectMaskBank");
+ if (isCs108Connected()) return cs108Library4A.getSelectMaskBank();
+ else if (isCs710Connected()) return cs710Library4A.getSelectMaskBank();
+ else Log.i("Hello2", "getSelectMaskBank" + stringNOTCONNECT);
+ return -1;
+ }
+ public int getSelectMaskOffset() {
+ if (DEBUG) Log.i("Hello2", "getSelectMaskOffset");
+ if (isCs108Connected()) return cs108Library4A.getSelectMaskOffset();
+ else if (isCs710Connected()) return cs710Library4A.getSelectMaskOffset();
+ else Log.i("Hello2", "getSelectMaskOffset" + stringNOTCONNECT);
+ return -1;
+ }
+ public String getSelectMaskData() {
+ if (DEBUG) Log.i("Hello2", "getSelectMaskData");
+ if (isCs108Connected()) return cs108Library4A.getSelectMaskData();
+ else if (isCs710Connected()) return cs710Library4A.getSelectMaskData();
+ else Log.i("Hello2", "getSelectMaskData" + stringNOTCONNECT);
+ return null;
+ }
+ public boolean setInvSelectIndex(int invSelect) {
+ if (DEBUG) Log.i("Hello2", "setInvSelectIndex");
+ if (isCs108Connected()) return cs108Library4A.setInvSelectIndex(invSelect);
+ else if (isCs710Connected()) return cs710Library4A.setInvSelectIndex(invSelect);
+ else Log.i("Hello2", "setInvSelectIndex" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean setSelectCriteriaDisable(int index) {
+ if (DEBUG || true) appendToLog("csLibrary4A: setSelectCriteria Disable with index = " + index);
+ if (isCs108Connected()) return cs108Library4A.setSelectCriteriaDisable(index);
+ else if (isCs710Connected()) return cs710Library4A.setSelectCriteriaDisable(index);
+ else Log.i("Hello2", "setSelectCriteriaDisable" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean setSelectCriteria(int index, boolean enable, int target, int action, int bank, int offset, String mask, boolean maskbit) {
+ appendToLog("csLibrary4A: setSelectCriteria 1 with index = " + index + ", enable = " + enable + ", target = " + target + ", action = " + action + ", bank = " + bank + ", offset = " + offset + ", mask = " + mask + ", maskbit = " + maskbit);
+ if (isCs108Connected()) return cs108Library4A.setSelectCriteria(index, enable, target, action, bank, offset, mask, maskbit);
+ else if (isCs710Connected()) return cs710Library4A.setSelectCriteria(index, enable, target, action, bank, offset, mask, maskbit);
+ else Log.i("Hello2", "setSelectCriteria 1" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean setSelectCriteria(int index, boolean enable, int target, int action, int delay, int bank, int offset, String mask) {
+ appendToLog("csLibrary4A: setSelectCriteria 2 with index = " + index + ", enable = " + enable + ", target = " + target + ", action = " + action + ", delay = " + delay + ", bank = " + bank + ", offset = " + offset + ", mask = " + mask);
+ if (isCs108Connected()) return cs108Library4A.setSelectCriteria(index, enable, target, action, delay, bank, offset, mask);
+ else if (isCs710Connected()) return cs710Library4A.setSelectCriteria(index, enable, target, action, delay, bank, offset, mask);
+ else Log.i("Hello2", "setSelectCriteria" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean getRssiFilterEnable() {
+ if (DEBUG) Log.i("Hello2", "getRssiFilterEnable");
+ if (isCs108Connected()) return cs108Library4A.getRssiFilterEnable();
+ else if (isCs710Connected()) return cs710Library4A.getRssiFilterEnable();
+ else Log.i("Hello2", "getRssiFilterEnable" + stringNOTCONNECT);
+ return false;
+ }
+ public int getRssiFilterType() {
+ if (DEBUG) Log.i("Hello2", "getRssiFilterType");
+ if (isCs108Connected()) return cs108Library4A.getRssiFilterType();
+ else if (isCs710Connected()) return cs710Library4A.getRssiFilterType();
+ else Log.i("Hello2", "getRssiFilterType" + stringNOTCONNECT);
+ return -1;
+ }
+ public int getRssiFilterOption() {
+ if (DEBUG) Log.i("Hello2", "getRssiFilterOption");
+ if (isCs108Connected()) return cs108Library4A.getRssiFilterOption();
+ else if (isCs710Connected()) return cs710Library4A.getRssiFilterOption();
+ return -1;
+ }
+ public boolean setRssiFilterConfig(boolean enable, int rssiFilterType, int rssiFilterOption) {
+ if (DEBUG) Log.i("Hello2", "setRssiFilterConfig");
+ if (isCs108Connected()) return cs108Library4A.setRssiFilterConfig(enable, rssiFilterType, rssiFilterOption);
+ else if (isCs710Connected()) return cs710Library4A.setRssiFilterConfig(enable, rssiFilterType, rssiFilterOption);
+ else Log.i("Hello2", "setRssiFilterConfig" + stringNOTCONNECT);
+ return false;
+ }
+ public double getRssiFilterThreshold1() {
+ if (DEBUG) Log.i("Hello2", "getRssiFilterThreshold1");
+ if (isCs108Connected()) return cs108Library4A.getRssiFilterThreshold1();
+ else if (isCs710Connected()) return cs710Library4A.getRssiFilterThreshold1();
+ else Log.i("Hello2", "getRssiFilterThreshold1" + stringNOTCONNECT);
+ return -1;
+ }
+ public double getRssiFilterThreshold2() {
+ if (DEBUG) Log.i("Hello2", "getRssiFilterThreshold2");
+ if (isCs108Connected()) return cs108Library4A.getRssiFilterThreshold2();
+ else if (isCs710Connected()) return cs710Library4A.getRssiFilterThreshold2();
+ else Log.i("Hello2", "getRssiFilterThreshold2" + stringNOTCONNECT);
+ return -1;
+ }
+ public boolean setRssiFilterThreshold(double rssiFilterThreshold1, double rssiFilterThreshold2) {
+ if (DEBUG) Log.i("Hello2", "setRssiFilterThreshold");
+ if (isCs108Connected()) return cs108Library4A.setRssiFilterThreshold(rssiFilterThreshold1, rssiFilterThreshold2);
+ else if (isCs710Connected()) return cs710Library4A.setRssiFilterThreshold(rssiFilterThreshold1, rssiFilterThreshold2);
+ else Log.i("Hello2", "setRssiFilterThreshold" + stringNOTCONNECT);
+ return false;
+ }
+ public long getRssiFilterCount() {
+ if (DEBUG) Log.i("Hello2", "getRssiFilterCount");
+ if (isCs108Connected()) return cs108Library4A.getRssiFilterCount();
+ else if (isCs710Connected()) return cs710Library4A.getRssiFilterCount();
+ else Log.i("Hello2", "getRssiFilterCount" + stringNOTCONNECT);
+ return -1;
+ }
+ public boolean setRssiFilterCount(long rssiFilterCount) {
+ Log.i("Hello2", "setRssiFilterCount");
+ return false;
+ }
+ public boolean getInvMatchEnable() {
+ if (DEBUG) Log.i("Hello2", "getInvMatchEnable");
+ if (isCs108Connected()) return cs108Library4A.getInvMatchEnable();
+ else if (isCs710Connected()) return cs710Library4A.getInvMatchEnable();
+ else Log.i("Hello2", "getInvMatchEnable" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean getInvMatchType() {
+ if (DEBUG) Log.i("Hello2", "getInvMatchType");
+ if (isCs108Connected()) return cs108Library4A.getInvMatchType();
+ else if (isCs710Connected()) return cs710Library4A.getInvMatchType();
+ else Log.i("Hello2", "getInvMatchType" + stringNOTCONNECT);
+ return false;
+ }
+ public int getInvMatchOffset() {
+ if (DEBUG) Log.i("Hello2", "getInvMatchOffset");
+ if (isCs108Connected()) return cs108Library4A.getInvMatchOffset();
+ else if (isCs710Connected()) return cs710Library4A.getInvMatchOffset();
+ else Log.i("Hello2", "getInvMatchOffset" + stringNOTCONNECT);
+ return -1;
+ }
+ public String getInvMatchData() {
+ if (DEBUG) Log.i("Hello2", "getInvMatchData");
+ if (isCs108Connected()) return cs108Library4A.getInvMatchData();
+ else if (isCs710Connected()) return cs710Library4A.getInvMatchData();
+ else Log.i("Hello2", "getInvMatchData" + stringNOTCONNECT);
+ return null;
+ }
+ public boolean setPostMatchCriteria(boolean enable, boolean target, int offset, String mask) {
+ if (DEBUG) Log.i("Hello2", "setPostMatchCriteria");
+ if (isCs108Connected()) return cs108Library4A.setPostMatchCriteria(enable, target, offset, mask);
+ else if (isCs710Connected()) return cs710Library4A.setPostMatchCriteria(enable, target, offset, mask);
+ else Log.i("Hello2", "setPostMatchCriteria" + stringNOTCONNECT);
+ return false;
+ }
+ public int mrfidToWriteSize() {
+ if (DEBUG2) Log.i("Hello2", "mrfidToWriteSize");
+ if (isCs108Connected()) return cs108Library4A.mrfidToWriteSize();
+ else if (isCs710Connected()) return cs710Library4A.mrfidToWriteSize();
+ else Log.i("Hello2", "mrfidToWriteSize" + stringNOTCONNECT);
+ return -1;
+ }
+ public void mrfidToWritePrint() {
+ Log.i("Hello2", "mrfidToWritePrint");
+ }
+ public long getTagRate() {
+ if (DEBUG) Log.i("Hello2", "getTagRate");
+ if (isCs108Connected()) return cs108Library4A.getTagRate();
+ else if (isCs710Connected()) return cs710Library4A.getTagRate();
+ else Log.i("Hello2", "getTagRate" + stringNOTCONNECT);
+ return -1;
+ }
+ public boolean startOperation(RfidReaderChipData.OperationTypes operationTypes) {
+ if (DEBUG) Log.i("Hello2", "startOperation");
+ if (isCs108Connected()) {
+ return cs108Library4A.startOperation(operationTypes);
+ } else if (isCs710Connected()) {
+ return cs710Library4A.startOperation(operationTypes);
+ }
+ else Log.i("Hello2", "startOperation" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean abortOperation() {
+ if (DEBUG) Log.i("Hello2", "abortOperation");
+ if (isCs108Connected()) return cs108Library4A.abortOperation();
+ else if (isCs710Connected()) return cs710Library4A.abortOperation();
+ else Log.i("Hello2", "abortOperation" + stringNOTCONNECT);
+ return false;
+ }
+ public void restoreAfterTagSelect() {
+ if (DEBUG | true) Log.i("Hello2", "restoreAfterTagSelect");
+ if (isCs108Connected()) cs108Library4A.restoreAfterTagSelect();
+ else if (isCs710Connected()) cs710Library4A.restoreAfterTagSelect();
+ else Log.i("Hello2", "restoreAfterTagSelect" + stringNOTCONNECT);
+ }
+ public boolean setSelectedTagByTID(String strTagId, long pwrlevel) {
+ appendToLog("csLibrary4A: setSelectCriteria setSelectedByTID strTagId = " + strTagId + ", pwrlevel = " + pwrlevel);
+ if (isCs108Connected()) return cs108Library4A.setSelectedTagByTID(strTagId, pwrlevel);
+ else if (isCs710Connected()) return cs710Library4A.setSelectedTagByTID(strTagId, pwrlevel);
+ else Log.i("Hello2", "setSelectedTagByTID" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean setSelectedTag(String strTagId, int selectBank, long pwrlevel) {
+ if (DEBUG) Log.i("Hello2", "setSelectedTag 1");
+ if (isCs108Connected()) return cs108Library4A.setSelectedTag(strTagId, selectBank, pwrlevel);
+ else if (isCs710Connected()) return cs710Library4A.setSelectedTag(strTagId, selectBank, pwrlevel);
+ else Log.i("Hello2", "setSelectedTag 1" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean setSelectedTag(boolean selectOne, String selectMask, int selectBank, int selectOffset, long pwrlevel, int qValue, int matchRep) {
+ appendToLog("csLibraryA: setSelectCriteria strTagId = " + selectMask + ", selectBank = " + selectBank + ", selectOffset = " + selectOffset + ", pwrlevel = " + pwrlevel + ", qValue = " + qValue + ", matchRep = " + matchRep);
+ if (isCs108Connected()) return cs108Library4A.setSelectedTag(selectOne, selectMask, selectBank, selectOffset, pwrlevel, qValue, matchRep);
+ else if (isCs710Connected()) return cs710Library4A.setSelectedTag(selectMask, selectBank, selectOffset, pwrlevel, qValue, matchRep);
+ else Log.i("Hello2", "setSelectedTag 2" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean setMatchRep(int matchRep) {
+ if (DEBUG) Log.i("Hello2", "setMatchRep");
+ if (isCs108Connected()) return cs108Library4A.setMatchRep(matchRep);
+ else if (isCs710Connected()) return cs710Library4A.setMatchRep(matchRep);
+ else Log.i("Hello2", "setMatchRep" + stringNOTCONNECT);
+ return false;
+ }
+ public String[] getCountryList() {
+ if (DEBUG) Log.i("Hello2", "getCountryList");
+ if (isCs108Connected()) return cs108Library4A.getCountryList();
+ else if (isCs710Connected()) return cs710Library4A.getCountryList();
+ else Log.i("Hello2", "getCountryList" + stringNOTCONNECT);
+ return null;
+ }
+ public int getCountryNumberInList() {
+ if (DEBUG) Log.i("Hello2", "getCountryNumberInList");
+ if (isCs108Connected()) return cs108Library4A.getCountryNumberInList();
+ else if (isCs710Connected()) return cs710Library4A.getCountryNumberInList();
+ else Log.i("Hello2", "getCountryNumberInList" + stringNOTCONNECT);
+ return -1;
+ }
+ public boolean setCountryInList(int countryInList) {
+ if (DEBUG || true) Log.i("Hello2", "setCountryInList");
+ if (isCs108Connected()) return cs108Library4A.setCountryInList(countryInList);
+ else if (isCs710Connected()) return cs710Library4A.setCountryInList(countryInList);
+ else Log.i("Hello2", "setCountryInList" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean getChannelHoppingStatus() {
+ if (DEBUG) Log.i("Hello2", "getChannelHoppingStatus");
+ if (isCs108Connected()) return cs108Library4A.getChannelHoppingStatus();
+ else if (isCs710Connected()) return cs710Library4A.getChannelHoppingStatus();
+ else Log.i("Hello2", "getChannelHoppingStatus" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean setChannelHoppingStatus(boolean channelOrderHopping) {
+ Log.i("Hello2", "setChannelHoppingStatus");
+ return false;
+ }
+ public String[] getChannelFrequencyList() {
+ if (isCs108Connected()) return cs108Library4A.getChannelFrequencyList();
+ else if (isCs710Connected()) return cs710Library4A.getChannelFrequencyList();
+ else Log.i("Hello2", "getChannelFrequencyList" + stringNOTCONNECT);
+ return null;
+ }
+ public int getChannel() {
+ if (DEBUG) Log.i("Hello2", "getChannel");
+ if (isCs108Connected()) return cs108Library4A.getChannel();
+ else if (isCs710Connected()) return cs710Library4A.getChannel();
+ else Log.i("Hello2", "getChannel" + stringNOTCONNECT);
+ return -1;
+ }
+ public boolean setChannel(int channelSelect) {
+ if (DEBUG) Log.i("Hello2", "setChannel");
+ if (isCs108Connected()) return cs108Library4A.setChannel(channelSelect);
+ else if (isCs710Connected()) return cs710Library4A.setChannel(channelSelect);
+ else Log.i("Hello2", "setChannel" + stringNOTCONNECT);
+ return false;
+ }
+ public byte getPopulation2Q(int population) {
+ if (DEBUG) Log.i("Hello2", "getPopulation2Q");
+ if (isCs108Connected()) return cs108Library4A.getPopulation2Q(population);
+ else if (isCs710Connected()) return cs710Library4A.getPopulation2Q(population);
+ else Log.i("Hello2", "getPopulation2Q" + stringNOTCONNECT);
+ return -1;
+ }
+ public int getPopulation() {
+ if (DEBUG) Log.i("Hello2", "getPopulation");
+ if (isCs108Connected()) return cs108Library4A.getPopulation();
+ else if (isCs710Connected()) return cs710Library4A.getPopulation();
+ else Log.i("Hello2", "getPopulation" + stringNOTCONNECT);
+ return -1;
+ } //3348
+ public boolean setPopulation(int population) {
+ if (DEBUG || true) Log.i("Hello2", "setPopulation " + population);
+ if (isCs108Connected()) return cs108Library4A.setPopulation(population);
+ else if (isCs710Connected()) return cs710Library4A.setPopulation(population);
+ else Log.i("Hello2", "setPopulation" + stringNOTCONNECT);
+ return false;
+ }
+ public byte getQValue() {
+ if (DEBUG) Log.i("Hello2", "getQValue");
+ if (isCs108Connected()) return cs108Library4A.getQValue();
+ else if (isCs710Connected()) return cs710Library4A.getQValue();
+ else Log.i("Hello2", "getQValue" + stringNOTCONNECT);
+ return -1;
+ }
+ public boolean setQValue(byte byteValue) {
+ if (DEBUG) Log.i("Hello2", "setQValue");
+ if (isCs108Connected()) return cs108Library4A.setQValue(byteValue);
+ else if (isCs710Connected()) return cs710Library4A.setQValue(byteValue);
+ else Log.i("Hello2", "setQValue" + stringNOTCONNECT);
+ return false;
+ }
+ public RfidReaderChipData.Rx000pkgData onRFIDEvent() {
+ if (DEBUG2) Log.i("Hello2", "onRFIDEvent");
+ if (isCs108Connected()) {
+ RfidReaderChipData.Rx000pkgData rx000pkgData = null;
+ RfidReaderChipData.Rx000pkgData rx000pkgData1 = cs108Library4A.onRFIDEvent();
+ if (rx000pkgData1 != null) {
+ rx000pkgData = new RfidReaderChipData.Rx000pkgData();
+ switch (rx000pkgData1.responseType) {
+ case TYPE_18K6C_INVENTORY_COMPACT:
+ rx000pkgData.responseType = RfidReaderChipData.HostCmdResponseTypes.TYPE_18K6C_INVENTORY_COMPACT;
+ break;
+ case TYPE_18K6C_INVENTORY:
+ rx000pkgData.responseType = RfidReaderChipData.HostCmdResponseTypes.TYPE_18K6C_INVENTORY;
+ break;
+ case TYPE_COMMAND_ABORT_RETURN:
+ rx000pkgData.responseType = RfidReaderChipData.HostCmdResponseTypes.TYPE_COMMAND_ABORT_RETURN;
+ break;
+ case TYPE_COMMAND_END:
+ rx000pkgData.responseType = RfidReaderChipData.HostCmdResponseTypes.TYPE_COMMAND_END;
+ break;
+ case TYPE_18K6C_TAG_ACCESS:
+ rx000pkgData.responseType = RfidReaderChipData.HostCmdResponseTypes.TYPE_18K6C_TAG_ACCESS;
+ break;
+ default:
+ Log.i("Hello2", "onRFIDEvent: responseType = " + rx000pkgData1.responseType.toString());
+ }
+ rx000pkgData.flags = rx000pkgData1.flags;
+ rx000pkgData.dataValues = rx000pkgData1.dataValues;
+ rx000pkgData.decodedTime = rx000pkgData1.decodedTime;
+ rx000pkgData.decodedRssi = rx000pkgData1.decodedRssi;
+ rx000pkgData.decodedPhase = rx000pkgData1.decodedPhase;
+ rx000pkgData.decodedChidx = rx000pkgData1.decodedChidx;
+ rx000pkgData.decodedPort = rx000pkgData1.decodedPort;
+ rx000pkgData.decodedPc = rx000pkgData1.decodedPc;
+ rx000pkgData.decodedEpc = rx000pkgData1.decodedEpc;
+ rx000pkgData.decodedCrc = rx000pkgData1.decodedCrc;
+ rx000pkgData.decodedData1 = rx000pkgData1.decodedData1;
+ rx000pkgData.decodedData2 = rx000pkgData1.decodedData2;
+ rx000pkgData.decodedResult = rx000pkgData1.decodedResult;
+ rx000pkgData.decodedError = rx000pkgData1.decodedError;
+ }
+ return rx000pkgData;
+ } else if (isCs710Connected()) {
+ RfidReaderChipData.Rx000pkgData rx000pkgData = null;
+ RfidReaderChipData.Rx000pkgData rx000pkgData1 = cs710Library4A.onRFIDEvent();
+ if (rx000pkgData1 != null) {
+ rx000pkgData = new RfidReaderChipData.Rx000pkgData();
+ switch (rx000pkgData1.responseType) {
+ case TYPE_18K6C_INVENTORY_COMPACT:
+ rx000pkgData.responseType = RfidReaderChipData.HostCmdResponseTypes.TYPE_18K6C_INVENTORY_COMPACT;
+ break;
+ case TYPE_18K6C_INVENTORY:
+ rx000pkgData.responseType = RfidReaderChipData.HostCmdResponseTypes.TYPE_18K6C_INVENTORY;
+ break;
+ case TYPE_COMMAND_ABORT_RETURN:
+ rx000pkgData.responseType = RfidReaderChipData.HostCmdResponseTypes.TYPE_COMMAND_ABORT_RETURN;
+ break;
+ case TYPE_COMMAND_END:
+ rx000pkgData.responseType = RfidReaderChipData.HostCmdResponseTypes.TYPE_COMMAND_END;
+ break;
+ case TYPE_18K6C_TAG_ACCESS:
+ rx000pkgData.responseType = RfidReaderChipData.HostCmdResponseTypes.TYPE_18K6C_TAG_ACCESS;
+ break;
+ default:
+ Log.i("Hello2", "onRFIDEvent: responseType = " + rx000pkgData1.responseType.toString());
+ }
+ rx000pkgData.flags = rx000pkgData1.flags;
+ rx000pkgData.dataValues = rx000pkgData1.dataValues;
+ rx000pkgData.decodedTime = rx000pkgData1.decodedTime;
+ rx000pkgData.decodedRssi = rx000pkgData1.decodedRssi;
+ rx000pkgData.decodedPhase = rx000pkgData1.decodedPhase;
+ rx000pkgData.decodedChidx = rx000pkgData1.decodedChidx;
+ rx000pkgData.decodedPort = rx000pkgData1.decodedPort;
+ rx000pkgData.decodedPc = rx000pkgData1.decodedPc;
+ rx000pkgData.decodedEpc = rx000pkgData1.decodedEpc;
+ rx000pkgData.decodedCrc = rx000pkgData1.decodedCrc;
+ rx000pkgData.decodedData1 = rx000pkgData1.decodedData1;
+ rx000pkgData.decodedData2 = rx000pkgData1.decodedData2;
+ rx000pkgData.decodedResult = rx000pkgData1.decodedResult;
+ rx000pkgData.decodedError = rx000pkgData1.decodedError;
+ }
+ if (rx000pkgData != null) appendToLog("response0 = " + rx000pkgData.responseType.toString() + ", " + byteArrayToString(rx000pkgData.dataValues));
+ return rx000pkgData;
+ }
+ else Log.i("Hello2", "onRFIDEvent" + stringNOTCONNECT);
+ return null;
+ }
+ public String getModelNumber() {
+ if (DEBUG) Log.i("Hello2", "getModelNumber");
+ if (isCs108Connected()) return cs108Library4A.getModelNumber();
+ else if (isCs710Connected()) return cs710Library4A.getModelNumber();
+ else Log.i("Hello2", "getModelNumber" + stringNOTCONNECT);
+ return null;
+ }
+ public boolean setRx000KillPassword(String password) {
+ if (DEBUG) Log.i("Hello2", "setRx000KillPassword");
+ if (isCs108Connected()) return cs108Library4A.setRx000KillPassword(password);
+ else if (isCs710Connected()) return cs710Library4A.setRx000KillPassword(password);
+ else Log.i("Hello2", "setRx000KillPassword" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean setRx000AccessPassword(String password) {
+ if (DEBUG) Log.i("Hello2", "setRx000AccessPassword");
+ if (isCs108Connected()) return cs108Library4A.setRx000AccessPassword(password);
+ else if (isCs710Connected()) return cs710Library4A.setRx000AccessPassword(password);
+ else Log.i("Hello2", "setRx000AccessPassword" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean setAccessRetry(boolean accessVerfiy, int accessRetry) {
+ if (DEBUG) Log.i("Hello2", "setAccessRetry");
+ if (isCs108Connected()) return cs108Library4A.setAccessRetry(accessVerfiy, accessRetry);
+ else if (isCs710Connected()) return cs710Library4A.setAccessRetry(accessVerfiy, accessRetry);
+ else Log.i("Hello2", "setAccessRetry" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean setInvModeCompact(boolean invModeCompact) {
+ if (DEBUG) Log.i("Hello2", "setInvModeCompact");
+ if (isCs108Connected()) return cs108Library4A.setInvModeCompact(invModeCompact);
+ else if (isCs710Connected()) return cs710Library4A.setInvModeCompact(invModeCompact);
+ else Log.i("Hello2", "setInvModeCompact" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean setAccessLockAction(int accessLockAction, int accessLockMask) {
+ if (DEBUG) Log.i("Hello2", "setAccessLockAction");
+ if (isCs108Connected()) return cs108Library4A.setAccessLockAction(accessLockAction, accessLockMask);
+ else if (isCs710Connected()) return cs710Library4A.setAccessLockAction(accessLockAction, accessLockMask);
+ else Log.i("Hello2", "setAccessLockAction" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean setAccessBank(int accessBank) {
+ if (DEBUG) Log.i("Hello2", "setAccessBank 1");
+ if (isCs108Connected()) return cs108Library4A.setAccessBank(accessBank);
+ else if (isCs710Connected()) return cs710Library4A.setAccessBank(accessBank);
+ else Log.i("Hello2", "setAccessBank 1" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean setAccessBank(int accessBank, int accessBank2) {
+ if (DEBUG) Log.i("Hello2", "setAccessBank 2");
+ if (isCs108Connected()) return cs108Library4A.setAccessBank(accessBank, accessBank2);
+ else if (isCs710Connected()) return cs710Library4A.setAccessBank(accessBank, accessBank2);
+ else Log.i("Hello2", "setAccessBank 2" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean setAccessOffset(int accessOffset) {
+ if (DEBUG) Log.i("Hello2", "setAccessOffset 1");
+ if (isCs108Connected()) return cs108Library4A.setAccessOffset(accessOffset);
+ else if (isCs710Connected()) return cs710Library4A.setAccessOffset(accessOffset);
+ else Log.i("Hello2", "setAccessOffset 1" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean setAccessOffset(int accessOffset, int accessOffset2) {
+ if (DEBUG) Log.i("Hello2", "setAccessOffset 2");
+ if (isCs108Connected()) return cs108Library4A.setAccessOffset(accessOffset, accessOffset2);
+ else if (isCs710Connected()) return cs710Library4A.setAccessOffset(accessOffset, accessOffset2);
+ else Log.i("Hello2", "setAccessOffset 2" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean setAccessCount(int accessCount) {
+ if (DEBUG) Log.i("Hello2", "setAccessCount 1");
+ if (isCs108Connected()) return cs108Library4A.setAccessCount(accessCount);
+ else if (isCs710Connected()) return cs710Library4A.setAccessCount(accessCount);
+ else Log.i("Hello2", "setAccessCount 1" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean setAccessCount(int accessCount, int accessCount2) {
+ if (DEBUG) Log.i("Hello2", "setAccessCount 2");
+ if (isCs108Connected()) return cs108Library4A.setAccessCount(accessCount, accessCount2);
+ else if (isCs710Connected()) return cs710Library4A.setAccessCount(accessCount, accessCount2);
+ else Log.i("Hello2", "setAccessCount 2" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean setAccessWriteData(String dataInput) {
+ if (DEBUG) Log.i("Hello2", "setAccessWriteData");
+ if (isCs108Connected()) return cs108Library4A.setAccessWriteData(dataInput);
+ else if (isCs710Connected()) return cs710Library4A.setAccessWriteData(dataInput);
+ else Log.i("Hello2", "setAccessWriteData" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean setResReadNoReply(boolean resReadNoReply) {
+ if (DEBUG) Log.i("Hello2", "setResReadNoReply");
+ if (isCs108Connected()) return false;
+ else if (isCs710Connected()) return cs710Library4A.setResReadNoReply(resReadNoReply);
+ else Log.i("Hello2", "setResReadNoReply" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean setTagRead(int tagRead) {
+ if (DEBUG) Log.i("Hello2", "setTagRead");
+ if (isCs108Connected()) return cs108Library4A.setTagRead(tagRead);
+ else if (isCs710Connected()) return cs710Library4A.setTagRead(tagRead);
+ else Log.i("Hello2", "setTagRead" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean setInvBrandId(boolean invBrandId) {
+ if (DEBUG) Log.i("Hello2", "setInvBrandId");
+ if (isCs108Connected()) return cs108Library4A.setInvBrandId(invBrandId);
+ else if (isCs710Connected()) return cs710Library4A.setInvBrandId(invBrandId);
+ else Log.i("Hello2", "setInvBrandId" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean setInvAuthenticate(boolean invAuthenticate) {
+ if (DEBUG) Log.i("Hello2", "setInvBrandId");
+ if (isCs108Connected()) return cs108Library4A.setInvAuthenticate(invAuthenticate);
+ else if (isCs710Connected()) return cs710Library4A.setInvAuthenticate(invAuthenticate);
+ else Log.i("Hello2", "setInvAuthenticate" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean sendHostRegRequestHST_CMD(RfidReaderChipData.HostCommands hostCommand) {
+ if (DEBUG | true) Log.i("Hello2", "sendHostRegRequestHST_CMD with hostCommand = " + hostCommand.toString());
+ if (isCs108Connected()) {
+ RfidReaderChipData.HostCommands hostCommands1 = null;
+ switch (hostCommand) {
+ case CMD_18K6CREAD:
+ hostCommands1 = RfidReaderChipData.HostCommands.CMD_18K6CREAD;
+ break;
+ case CMD_18K6CWRITE:
+ hostCommands1 = RfidReaderChipData.HostCommands.CMD_18K6CWRITE;
+ break;
+ case CMD_18K6CLOCK:
+ hostCommands1 = RfidReaderChipData.HostCommands.CMD_18K6CLOCK;
+ break;
+ case CMD_18K6CKILL:
+ hostCommands1 = RfidReaderChipData.HostCommands.CMD_18K6CKILL;
+ break;
+ case CMD_18K6CAUTHENTICATE:
+ hostCommands1 = RfidReaderChipData.HostCommands.CMD_18K6CAUTHENTICATE;
+ break;
+ case CMD_UNTRACEABLE:
+ hostCommands1 = RfidReaderChipData.HostCommands.CMD_UNTRACEABLE;
+ break;
+ case CMD_GETSENSORDATA:
+ hostCommands1 = RfidReaderChipData.HostCommands.CMD_GETSENSORDATA;
+ break;
+ case CMD_FDM_RDMEM:
+ hostCommands1 = RfidReaderChipData.HostCommands.CMD_FDM_RDMEM;
+ break;
+ case CMD_FDM_WRMEM:
+ hostCommands1 = RfidReaderChipData.HostCommands.CMD_FDM_WRMEM;
+ break;
+ case CMD_FDM_AUTH:
+ hostCommands1 = RfidReaderChipData.HostCommands.CMD_FDM_AUTH;
+ break;
+ case CMD_FDM_GET_TEMPERATURE:
+ hostCommands1 = RfidReaderChipData.HostCommands.CMD_FDM_GET_TEMPERATURE;
+ break;
+ case CMD_FDM_START_LOGGING:
+ hostCommands1 = RfidReaderChipData.HostCommands.CMD_FDM_START_LOGGING;
+ break;
+ case CMD_FDM_STOP_LOGGING:
+ hostCommands1 = RfidReaderChipData.HostCommands.CMD_FDM_STOP_LOGGING;
+ break;
+ case CMD_FDM_WRREG:
+ hostCommands1 = RfidReaderChipData.HostCommands.CMD_FDM_WRREG;
+ break;
+ case CMD_FDM_RDREG:
+ hostCommands1 = RfidReaderChipData.HostCommands.CMD_FDM_RDREG;
+ break;
+ case CMD_FDM_DEEP_SLEEP:
+ hostCommands1 = RfidReaderChipData.HostCommands.CMD_FDM_DEEP_SLEEP;
+ break;
+ case CMD_FDM_OPMODE_CHECK:
+ hostCommands1 = RfidReaderChipData.HostCommands.CMD_FDM_OPMODE_CHECK;
+ break;
+ case CMD_FDM_INIT_REGFILE:
+ hostCommands1 = RfidReaderChipData.HostCommands.CMD_FDM_INIT_REGFILE;
+ break;
+ case CMD_FDM_LED_CTRL:
+ hostCommands1 = RfidReaderChipData.HostCommands.CMD_FDM_LED_CTRL;
+ break;
+ default:
+ Log.i("Hello2", "Skip sendHostRegRequestHST_CMD: hostCommand = " + hostCommand.toString());
+ break;
+ }
+ if (hostCommands1 == null) return false;
+ else return cs108Library4A.sendHostRegRequestHST_CMD(hostCommands1);
+ } else if (isCs710Connected()) {
+ RfidReaderChipData.HostCommands hostCommands1 = null;
+ switch (hostCommand) {
+ case CMD_18K6CREAD:
+ hostCommands1 = RfidReaderChipData.HostCommands.CMD_18K6CREAD;
+ break;
+ case CMD_18K6CWRITE:
+ hostCommands1 = RfidReaderChipData.HostCommands.CMD_18K6CWRITE;
+ break;
+ case CMD_18K6CLOCK:
+ hostCommands1 = RfidReaderChipData.HostCommands.CMD_18K6CLOCK;
+ break;
+ case CMD_18K6CKILL:
+ hostCommands1 = RfidReaderChipData.HostCommands.CMD_18K6CKILL;
+ break;
+ case CMD_18K6CAUTHENTICATE:
+ hostCommands1 = RfidReaderChipData.HostCommands.CMD_18K6CAUTHENTICATE;
+ break;
+ case CMD_UNTRACEABLE:
+ hostCommands1 = RfidReaderChipData.HostCommands.CMD_UNTRACEABLE;
+ break;
+ case CMD_GETSENSORDATA:
+ hostCommands1 = RfidReaderChipData.HostCommands.CMD_GETSENSORDATA;
+ default:
+ Log.i("Hello2", "sendHostRegRequestHST_CMD: hostCommand = " + hostCommand.toString());
+ break;
+ }
+ if (hostCommands1 == null) return false;
+ return cs710Library4A.sendHostRegRequestHST_CMD(hostCommands1);
+ }
+ else Log.i("Hello2", "sendHostRegRequestHST_CMD" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean setPwrManagementMode(boolean bLowPowerStandby) {
+ if (DEBUG) Log.i("Hello2", "setPwrManagementMode");
+ if (isCs108Connected()) return cs108Library4A.setPwrManagementMode(bLowPowerStandby);
+ else if (isCs710Connected()) return cs710Library4A.setPwrManagementMode(bLowPowerStandby);
+ return false;
+ }
+ public void macWrite(int address, long value) {
+ if (DEBUG) Log.i("Hello2", "macWrite");
+ if (isCs108Connected()) cs108Library4A.macWrite(address, value);
+ else if (isCs710Connected()) { }
+ }
+ public void set_fdCmdCfg(int value) {
+ if (DEBUG) Log.i("Hello2", "set_fdCmdCfg");
+ if (isCs108Connected()) cs108Library4A.set_fdCmdCfg(value);
+ else if (isCs710Connected()) { }
+ }
+ public void set_fdRegAddr(int addr) {
+ if (DEBUG) Log.i("Hello2", "set_fdRegAddr");
+ if (isCs108Connected()) cs108Library4A.set_fdRegAddr(addr);
+ else if (isCs710Connected()) { }
+ }
+ public void set_fdWrite(int addr, long value) {
+ if (DEBUG) Log.i("Hello2", "set_fdWrite");
+ if (isCs108Connected()) cs108Library4A.set_fdWrite(addr, value);
+ else if (isCs710Connected()) { }
+ }
+ public void set_fdPwd(int value) {
+ if (DEBUG) Log.i("Hello2", "set_fdPwd");
+ if (isCs108Connected()) cs108Library4A.set_fdPwd(value);
+ else if (isCs710Connected()) { }
+ }
+ public void set_fdBlockAddr4GetTemperature(int addr) {
+ if (DEBUG) Log.i("Hello2", "set_fdBlockAddr4GetTemperature");
+ if (isCs108Connected()) cs108Library4A.set_fdBlockAddr4GetTemperature(addr);
+ else if (isCs710Connected()) { }
+ }
+ public void set_fdReadMem(int addr, long len) {
+ if (DEBUG) Log.i("Hello2", "set_fdReadMem");
+ if (isCs108Connected()) cs108Library4A.set_fdReadMem(addr, len);
+ else if (isCs710Connected()) { }
+ }
+ public void set_fdWriteMem(int addr, int len, long value) {
+ if (DEBUG) Log.i("Hello2", "set_fdWriteMem");
+ if (isCs108Connected()) cs108Library4A.set_fdWriteMem(addr, len, value);
+ else if (isCs710Connected()) { }
+ }
+ public void setImpinJExtension(boolean tagFocus, boolean fastId) {
+ if (DEBUG) Log.i("Hello2", "setImpinJExtension with tagFocus = " + tagFocus + ", fastId = " + fastId);
+ if (isCs108Connected()) cs108Library4A.setImpinJExtension(tagFocus, fastId);
+ else if (isCs710Connected()) cs710Library4A.setImpinJExtension(tagFocus, fastId);
+ else Log.i("Hello2", "setImpinJExtension" + stringNOTCONNECT);
+ }
+
+ //============ Barcode ============
+ public void getBarcodePreSuffix() {
+ if (DEBUG) Log.i("Hello2", "getBarcodePreSuffix");
+ if (isCs108Connected()) cs108Library4A.getBarcodePreSuffix();
+ else if (isCs710Connected()) cs710Library4A.getBarcodePreSuffix();
+ else Log.i("Hello2", "getBarcodePreSuffix" + stringNOTCONNECT);
+ }
+ public void getBarcodeReadingMode() {
+ if (DEBUG) Log.i("Hello2", "getBarcodeReadingMode");
+ if (isCs108Connected()) cs108Library4A.getBarcodeReadingMode();
+ else if (isCs710Connected()) cs710Library4A.getBarcodeReadingMode();
+ else Log.i("Hello2", "getBarcodeReadingMode" + stringNOTCONNECT);
+ }
+ public boolean isBarcodeFailure() {
+ if (DEBUG) Log.i("Hello2", "isBarcodeFailure");
+ if (isCs108Connected()) return cs108Library4A.isBarcodeFailure();
+ else if (isCs710Connected()) return cs710Library4A.isBarcodeFailure();
+ else Log.i("Hello2", "isBarcodeFailure" + stringNOTCONNECT);
+ return false;
+ }
+ public String getBarcodeDate() {
+ if (DEBUG) Log.i("Hello2", "getBarcodeDate");
+ if (isCs108Connected()) return cs108Library4A.getBarcodeDate();
+ else if (isCs710Connected()) return cs710Library4A.getBarcodeDate();
+ else Log.i("Hello2", "getBarcodeDate" + stringNOTCONNECT);
+ return null;
+ }
+ public boolean getBarcodeOnStatus() {
+ if (DEBUG) Log.i("Hello2", "getBarcodeOnStatus");
+ if (isCs108Connected()) return cs108Library4A.getBarcodeOnStatus();
+ else if (isCs710Connected()) return cs710Library4A.getBarcodeOnStatus();
+ else Log.i("Hello2", "getBarcodeOnStatus" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean setBarcodeOn(boolean on) {
+ if (DEBUG) Log.i("Hello2", "setBarcodeOn");
+ if (isCs108Connected()) return cs108Library4A.setBarcodeOn(on);
+ else if (isCs710Connected()) return cs710Library4A.setBarcodeOn(on);
+ else Log.i("Hello2", "setBarcodeOn" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean setVibrateOn(int mode) {
+ if (DEBUG || true) Log.i("Hello2", "setVibrateOn with mode = " + mode);
+ if (isCs108Connected()) return cs108Library4A.setVibrateOn(mode);
+ else if (isCs710Connected()) return cs710Library4A.setVibrateOn(mode);
+ else Log.i("Hello2", "setVibrateOn" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean getInventoryVibrate() {
+ if (DEBUG) Log.i("Hello2", "getInventoryVibrate");
+ if (isCs108Connected()) return cs108Library4A.getInventoryVibrate();
+ else if (isCs710Connected()) return cs710Library4A.getInventoryVibrate();
+ else Log.i("Hello2", "getInventoryVibrate" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean setInventoryVibrate(boolean inventoryVibrate) {
+ if (DEBUG) Log.i("Hello2", "setInventoryVibrate");
+ if (isCs108Connected()) return cs108Library4A.setInventoryVibrate(inventoryVibrate);
+ else if (isCs710Connected()) return cs710Library4A.setInventoryVibrate(inventoryVibrate);
+ else Log.i("Hello2", "setInventoryVibrate" + stringNOTCONNECT);
+ return false;
+ }
+ public int getVibrateTime() {
+ if (DEBUG) Log.i("Hello2", "getVibrateTime");
+ if (isCs108Connected()) return cs108Library4A.getVibrateTime();
+ else if (isCs710Connected()) return cs710Library4A.getVibrateTime();
+ else Log.i("Hello2", "getVibrateTime" + stringNOTCONNECT);
+ return -1;
+ }
+ public boolean setVibrateTime(int vibrateTime) {
+ if (DEBUG) Log.i("Hello2", "setVibrateTime");
+ if (isCs108Connected()) return cs108Library4A.setVibrateTime(vibrateTime);
+ else if (isCs710Connected()) return cs710Library4A.setVibrateTime(vibrateTime);
+ else Log.i("Hello2", "setVibrateTime" + stringNOTCONNECT);
+ return false;
+ }
+ public int getVibrateWindow() {
+ if (DEBUG) Log.i("Hello2", "getVibrateWindow");
+ if (isCs108Connected()) return cs108Library4A.getVibrateWindow();
+ else if (isCs710Connected()) return cs710Library4A.getVibrateWindow();
+ else Log.i("Hello2", "getVibrateWindow" + stringNOTCONNECT);
+ return -1;
+ }
+ public boolean setVibrateWindow(int vibrateWindow) {
+ if (DEBUG) Log.i("Hello2", "setVibrateWindow");
+ if (isCs108Connected()) return cs108Library4A.setVibrateWindow(vibrateWindow);
+ else if (isCs710Connected()) return cs710Library4A.setVibrateWindow(vibrateWindow);
+ else Log.i("Hello2", "setVibrateWindow" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean barcodeSendCommandTrigger() {
+ if (DEBUG) Log.i("Hello2", "barcodeSendCommandTrigger");
+ if (isCs108Connected()) return cs108Library4A.barcodeSendCommandTrigger();
+ else if (isCs710Connected()) return cs710Library4A.barcodeSendCommandTrigger();
+ else Log.i("Hello2", "barcodeSendCommandTrigger" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean barcodeSendCommandSetPreSuffix() {
+ if (DEBUG) Log.i("Hello2", "barcodeSendCommandSetPreSuffix");
+ if (isCs108Connected()) return cs108Library4A.barcodeSendCommandSetPreSuffix();
+ else if (isCs710Connected()) return cs710Library4A.barcodeSendCommandSetPreSuffix();
+ else Log.i("Hello2", "barcodeSendCommandSetPreSuffix" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean barcodeSendCommandResetPreSuffix() {
+ if (DEBUG) Log.i("Hello2", "barcodeSendCommandResetPreSuffix");
+ if (isCs108Connected()) return cs108Library4A.barcodeSendCommandResetPreSuffix();
+ else if (isCs710Connected()) return cs710Library4A.barcodeSendCommandResetPreSuffix();
+ else Log.i("Hello2", "barcodeSendCommandResetPreSuffix" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean barcodeSendCommandConinuous() {
+ if (DEBUG) Log.i("Hello2", "barcodeSendCommandConinuous");
+ if (isCs108Connected()) return cs108Library4A.barcodeSendCommandConinuous();
+ else if (isCs710Connected()) return cs710Library4A.barcodeSendCommandConinuous();
+ else Log.i("Hello2", "barcodeSendCommandConinuous" + stringNOTCONNECT);
+ return false;
+ }
+ public String getBarcodeVersion() {
+ if (DEBUG) Log.i("Hello2", "getBarcodeVersion");
+ if (isCs108Connected()) return cs108Library4A.getBarcodeVersion();
+ else if (isCs710Connected()) return cs710Library4A.getBarcodeVersion();
+ else Log.i("Hello2", "getBarcodeVersion" + stringNOTCONNECT);
+ return null;
+ }
+ public String getBarcodeSerial() {
+ if (DEBUG) Log.i("Hello2", "getBarcodeSerial");
+ if (isCs108Connected()) return cs108Library4A.getBarcodeSerial();
+ else if (isCs710Connected()) return cs710Library4A.getBarcodeSerial();
+ else Log.i("Hello2", "getBarcodeSerial" + stringNOTCONNECT);
+ return null;
+ }
+ public boolean barcodeInventory(boolean start) {
+ if (DEBUG) Log.i("Hello2", "barcodeInventory");
+ if (isCs108Connected()) return cs108Library4A.barcodeInventory(start);
+ else if (isCs710Connected()) return cs710Library4A.barcodeInventory(start);
+ else Log.i("Hello2", "barcodeInventory" + stringNOTCONNECT);
+ return false;
+ }
+ public byte[] onBarcodeEvent() {
+ if (DEBUG) Log.i("Hello2", "onBarcodeEvent");
+ if (isCs108Connected()) return cs108Library4A.onBarcodeEvent();
+ else if (isCs710Connected()) return cs710Library4A.onBarcodeEvent();
+ else Log.i("Hello2", "onBarcodeEvent" + stringNOTCONNECT);
+ return null;
+ }
+
+ //============ Android General ============
+ public void setSameCheck(boolean sameCheck1) {
+ if (DEBUG) Log.i("Hello2", "setSameCheck");
+ if (isCs108Connected()) cs108Library4A.setSameCheck(sameCheck1);
+ else if (isCs710Connected()) cs710Library4A.setSameCheck(sameCheck1);
+ else Log.i("Hello2", "setSameCheck" + stringNOTCONNECT);
+ }
+ public void saveSetting2File() {
+ if (DEBUG) Log.i("Hello2", "saveSetting2File");
+ if (isCs108Connected()) cs108Library4A.saveSetting2File();
+ else if (isCs710Connected()) cs710Library4A.saveSetting2File();
+ else Log.i("Hello2", "saveSetting2File" + stringNOTCONNECT);
+ }
+ public int getBeepCount() {
+ if (DEBUG) Log.i("Hello2", "getBeepCount");
+ if (isCs108Connected()) return cs108Library4A.getBeepCount();
+ else if (isCs710Connected()) return cs710Library4A.getBeepCount();
+ else Log.i("Hello2", "getBeepCount" + stringNOTCONNECT);
+ return -1;
+ }
+ public boolean setBeepCount(int beepCount) {
+ if (DEBUG) Log.i("Hello2", "setBeepCount");
+ if (isCs108Connected()) return cs108Library4A.setBeepCount(beepCount);
+ else if (isCs710Connected()) return cs710Library4A.setBeepCount(beepCount);
+ else Log.i("Hello2", "setBeepCount" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean getInventoryBeep() {
+ if (DEBUG) Log.i("Hello2", "getInventoryBeep");
+ if (isCs108Connected()) return cs108Library4A.getInventoryBeep();
+ else if (isCs710Connected()) return cs710Library4A.getInventoryBeep();
+ else Log.i("Hello2", "getInventoryBeep" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean setInventoryBeep(boolean inventoryBeep) {
+ if (DEBUG) Log.i("Hello2", "setInventoryBeep");
+ if (isCs108Connected()) return cs108Library4A.setInventoryBeep(inventoryBeep);
+ else if (isCs710Connected()) return cs710Library4A.setInventoryBeep(inventoryBeep);
+ else Log.i("Hello2", "setInventoryBeep" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean getSaveFileEnable() {
+ if (DEBUG) Log.i("Hello2", "getSaveFileEnable");
+ if (isCs108Connected()) return cs108Library4A.getSaveFileEnable();
+ else if (isCs710Connected()) return cs710Library4A.getSaveFileEnable();
+ else Log.i("Hello2", "getSaveFileEnable" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean setSaveFileEnable(boolean saveFileEnable) {
+ if (DEBUG) Log.i("Hello2", "setSaveFileEnable");
+ if (isCs108Connected()) return cs108Library4A.setSaveFileEnable(saveFileEnable);
+ else if (isCs710Connected()) return cs710Library4A.setSaveFileEnable(saveFileEnable);
+ else Log.i("Hello2", "setSaveFileEnable" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean getSaveCloudEnable() {
+ if (DEBUG) Log.i("Hello2", "getSaveCloudEnable");
+ if (isCs108Connected()) return cs108Library4A.getSaveCloudEnable();
+ else if (isCs710Connected()) return cs710Library4A.getSaveCloudEnable();
+ else Log.i("Hello2", "getSaveCloudEnable" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean setSaveCloudEnable(boolean saveCloudEnable) {
+ if (DEBUG) Log.i("Hello2", "setSaveCloudEnable");
+ if (isCs108Connected()) return cs108Library4A.setSaveCloudEnable(saveCloudEnable);
+ else if (isCs710Connected()) return cs710Library4A.setSaveCloudEnable(saveCloudEnable);
+ else Log.i("Hello2", "setSaveCloudEnable" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean getSaveNewCloudEnable() {
+ if (DEBUG) Log.i("Hello2", "getSaveNewCloudEnable");
+ if (isCs108Connected()) return cs108Library4A.getSaveNewCloudEnable();
+ else if (isCs710Connected()) return cs710Library4A.getSaveNewCloudEnable();
+ else Log.i("Hello2", "getSaveNewCloudEnable" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean setSaveNewCloudEnable(boolean saveNewCloudEnable) {
+ Log.i("Hello2", "setSaveNewCloudEnable");
+ return false;
+ }
+ public boolean getSaveAllCloudEnable() {
+ if (DEBUG) Log.i("Hello2", "getSaveAllCloudEnable");
+ if (isCs108Connected()) return cs108Library4A.getSaveAllCloudEnable();
+ else if (isCs710Connected()) return cs710Library4A.getSaveAllCloudEnable();
+ else Log.i("Hello2", "getSaveAllCloudEnable" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean setSaveAllCloudEnable(boolean saveAllCloudEnable) {
+ Log.i("Hello2", "setSaveAllCloudEnable");
+ return false;
+ }
+ public boolean getUserDebugEnable() {
+ if (DEBUG) Log.i("Hello2", "getUserDebugEnable");
+ if (isCs108Connected()) return cs108Library4A.getUserDebugEnable();
+ else if (isCs710Connected()) return cs710Library4A.getUserDebugEnable();
+ else Log.i("Hello2", "getUserDebugEnable" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean setUserDebugEnable(boolean userDebugEnable) {
+ if (DEBUG) Log.i("Hello2", "setUserDebugEnable");
+ if (isCs108Connected()) return cs108Library4A.setUserDebugEnable(userDebugEnable);
+ else if (isCs710Connected()) return cs710Library4A.setUserDebugEnable(userDebugEnable);
+ else Log.i("Hello2", "getUserDebugEnable" + stringNOTCONNECT);
+ return false;
+ }
+ public String getForegroundReader() {
+ String string = null;
+ if (isCs710Connected()) string = cs710Library4A.getForegroundReader().trim();
+ else string = (cs108Library4A == null ? null : cs108Library4A.getForegroundReader().trim());
+ return string;
+ }
+ public boolean getForegroundServiceEnable() {
+ if (DEBUG) Log.i("Hello2", "getForegroundEnable");
+ if (isCs108Connected()) return cs108Library4A.getForegroundServiceEnable();
+ else if (isCs710Connected()) return cs710Library4A.getForegroundServiceEnable();
+ else Log.i("Hello2", "getForegroundEnable" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean setForegroundServiceEnable(boolean forgroundServiceEnable) {
+ if (DEBUG) Log.i("Hello2", "setForegroundServiceEnable");
+ if (isCs108Connected()) return cs108Library4A.setForegroundServiceEnable(forgroundServiceEnable);
+ else if (isCs710Connected()) return cs710Library4A.setForegroundServiceEnable(forgroundServiceEnable);
+ else Log.i("Hello2", "setForegroundServiceEnable" + stringNOTCONNECT);
+ return false;
+ }
+ public String getServerLocation() {
+ if (DEBUG) Log.i("Hello2", "getServerLocation");
+ if (isCs108Connected()) return cs108Library4A.getServerLocation();
+ else if (isCs710Connected()) return cs710Library4A.getServerLocation();
+ else Log.i("Hello2", "getServerLocation" + stringNOTCONNECT);
+ return null;
+ }
+ public boolean setServerLocation(String serverLocation) {
+ if (DEBUG) Log.i("Hello2", "setServerLocation");
+ if (isCs108Connected()) return cs108Library4A.setServerLocation(serverLocation);
+ else if (isCs710Connected()) return cs710Library4A.setServerLocation(serverLocation);
+ else Log.i("Hello2", "setServerLocation" + stringNOTCONNECT);
+ return false;
+ }
+ public int getServerTimeout() {
+ if (DEBUG) Log.i("Hello2", "getServerTimeout");
+ if (isCs108Connected()) return cs108Library4A.getServerTimeout();
+ else if (isCs710Connected()) return cs710Library4A.getServerTimeout();
+ else Log.i("Hello2", "getServerTimeout" + stringNOTCONNECT);
+ return -1;
+ }
+ public boolean setServerTimeout(int serverTimeout) {
+ if (DEBUG) Log.i("Hello2", "setServerTimeout");
+ if (isCs108Connected()) return cs108Library4A.setServerTimeout(serverTimeout);
+ else if (isCs710Connected()) return cs710Library4A.setServerTimeout(serverTimeout);
+ else Log.i("Hello2", "setServerTimeout" + stringNOTCONNECT);
+ return false;
+ }
+ public String getServerMqttLocation() {
+ if (DEBUG) Log.i("Hello2", "getServerMqttLocation");
+ if (isCs108Connected()) return cs108Library4A.getServerMqttLocation();
+ else if (isCs710Connected()) return cs710Library4A.getServerMqttLocation();
+ else Log.i("Hello2", "getServerMqttLocation" + stringNOTCONNECT);
+ return null;
+ }
+ public boolean setServerMqttLocation(String serverLocation) {
+ if (DEBUG) Log.i("Hello2", "setServerMqttLocation");
+ if (isCs108Connected()) return cs108Library4A.setServerMqttLocation(serverLocation);
+ else if (isCs710Connected()) return cs710Library4A.setServerMqttLocation(serverLocation);
+ else Log.i("Hello2", "setServerMqttLocation" + stringNOTCONNECT);
+ return false;
+ }
+ public String getTopicMqtt() {
+ if (DEBUG) Log.i("Hello2", "getServerTopicMqtt");
+ if (isCs108Connected()) return cs108Library4A.getTopicMqtt();
+ else if (isCs710Connected()) return cs710Library4A.getTopicMqtt();
+ else Log.i("Hello2", "getServerTopicMqtt" + stringNOTCONNECT);
+ return null;
+ }
+ public boolean setTopicMqtt(String topic) {
+ if (DEBUG) Log.i("Hello2", "setServerTopicMqtt");
+ if (isCs108Connected()) return cs108Library4A.setTopicMqtt(topic);
+ else if (isCs710Connected()) return cs710Library4A.setTopicMqtt(topic);
+ else Log.i("Hello2", "setServerTopicMqtt" + stringNOTCONNECT);
+ return false;
+ }
+ public int getForegroundDupElim() {
+ if (DEBUG) Log.i("Hello2", "getForegroundDupElim");
+ if (isCs108Connected()) return cs108Library4A.getForegroundDupElim();
+ else if (isCs710Connected()) return cs710Library4A.getForegroundDupElim();
+ else Log.i("Hello2", "getForegroundDupElim" + stringNOTCONNECT);
+ return -1;
+ }
+ public boolean setForegroundDupElim(int iForegroundDupElim) {
+ if (DEBUG) Log.i("Hello2", "setForegroundDupElim");
+ if (isCs108Connected()) return cs108Library4A.setForegroundDupElim(iForegroundDupElim);
+ else if (isCs710Connected()) return cs710Library4A.setForegroundDupElim(iForegroundDupElim);
+ else Log.i("Hello2", "setForegroundDupElim" + stringNOTCONNECT);
+ return false;
+ }
+ public int getInventoryCloudSave() {
+ if (DEBUG) Log.i("Hello2", "getInventoryCloudSave");
+ if (isCs108Connected()) return cs108Library4A.getInventoryCloudSave();
+ else if (isCs710Connected()) return cs710Library4A.getInventoryCloudSave();
+ else Log.i("Hello2", "getInventoryCloudSave" + stringNOTCONNECT);
+ return -1;
+ }
+ public boolean setInventoryCloudSave(int inventoryCloudSave) {
+ if (DEBUG) Log.i("Hello2", "setInventoryCloudSave");
+ if (isCs108Connected()) return cs108Library4A.setInventoryCloudSave(inventoryCloudSave);
+ else if (isCs710Connected()) return cs710Library4A.setInventoryCloudSave(inventoryCloudSave);
+ else Log.i("Hello2", "setInventoryCloudSave" + stringNOTCONNECT);
+ return false;
+ }
+ public String getServerImpinjLocation() {
+ if (DEBUG) Log.i("Hello2", "getServerImpinjLocation");
+ if (isCs108Connected()) return cs108Library4A.getServerImpinjLocation();
+ else if (isCs710Connected()) return cs710Library4A.getServerImpinjLocation();
+ else Log.i("Hello2", "getServerImpinjLocation" + stringNOTCONNECT);
+ return null;
+ }
+ public boolean setServerImpinjLocation(String serverImpinjLocation) {
+ if (DEBUG) Log.i("Hello2", "setServerImpinjLocation");
+ if (isCs108Connected()) return cs108Library4A.setServerImpinjLocation(serverImpinjLocation);
+ else if (isCs710Connected()) return cs710Library4A.setServerImpinjLocation(serverImpinjLocation);
+ else Log.i("Hello2", "setServerImpinjLocation" + stringNOTCONNECT);
+ return false;
+ }
+ public String getServerImpinjName() {
+ if (DEBUG) Log.i("Hello2", "getServerImpinjName");
+ if (isCs108Connected()) return cs108Library4A.getServerImpinjName();
+ else if (isCs710Connected()) return cs710Library4A.getServerImpinjName();
+ else Log.i("Hello2", "getServerImpinjName" + stringNOTCONNECT);
+ return null;
+ }
+ public boolean setServerImpinjName(String serverImpinjName) {
+ if (DEBUG) Log.i("Hello2", "setServerImpinjName");
+ if (isCs108Connected()) return cs108Library4A.setServerImpinjName(serverImpinjName);
+ else if (isCs710Connected()) return cs710Library4A.setServerImpinjName(serverImpinjName);
+ else Log.i("Hello2", "setServerImpinjName" + stringNOTCONNECT);
+ return false;
+ }
+ public String getServerImpinjPassword() {
+ if (DEBUG) Log.i("Hello2", "getServerImpinjPassword");
+ if (isCs108Connected()) return cs108Library4A.getServerImpinjPassword();
+ else if (isCs710Connected()) return cs710Library4A.getServerImpinjPassword();
+ else Log.i("Hello2", "getServerImpinjPassword" + stringNOTCONNECT);
+ return null;
+ }
+ public boolean setServerImpinjPassword(String serverImpinjPassword) {
+ if (DEBUG) Log.i("Hello2", "setServerImpinjPassword");
+ if (isCs108Connected()) return cs108Library4A.setServerImpinjPassword(serverImpinjPassword);
+ else if (isCs710Connected()) return cs710Library4A.setServerImpinjPassword(serverImpinjPassword);
+ else Log.i("Hello2", "setServerImpinjPassword" + stringNOTCONNECT);
+ return false;
+ }
+
+ public int getBatteryDisplaySetting() {
+ if (DEBUG) Log.i("Hello2", "getBatteryDisplaySetting");
+ if (isCs108Connected()) return cs108Library4A.getBatteryDisplaySetting();
+ else if (isCs710Connected()) return cs710Library4A.getBatteryDisplaySetting();
+ else Log.i("Hello2", "getBatteryDisplaySetting" + stringNOTCONNECT);
+ return -1;
+ }
+ public boolean setBatteryDisplaySetting(int batteryDisplaySelect) {
+ if (DEBUG) Log.i("Hello2", "setBatteryDisplaySetting");
+ if (isCs108Connected()) return cs108Library4A.setBatteryDisplaySetting(batteryDisplaySelect);
+ else if (isCs710Connected()) return cs710Library4A.setBatteryDisplaySetting(batteryDisplaySelect);
+ else Log.i("Hello2", "setBatteryDisplaySetting" + stringNOTCONNECT);
+ return false;
+ }
+ public double dBuV_dBm_constant = RfidReader.dBuV_dBm_constant; //106.98;
+ public int getRssiDisplaySetting() {
+ if (DEBUG) Log.i("Hello2", "getRssiDisplaySetting");
+ if (isCs108Connected()) return cs108Library4A.getRssiDisplaySetting();
+ else if (isCs710Connected()) return cs710Library4A.getRssiDisplaySetting();
+ return 0;
+ }
+ public boolean setRssiDisplaySetting(int rssiDisplaySelect) {
+ if (DEBUG) Log.i("Hello2", "setRssiDisplaySetting");
+ if (isCs108Connected()) return cs108Library4A.setRssiDisplaySetting(rssiDisplaySelect);
+ else if (isCs710Connected()) return cs710Library4A.setRssiDisplaySetting(rssiDisplaySelect);
+ else Log.i("Hello2", "setRssiDisplaySetting" + stringNOTCONNECT);
+ return false;
+ }
+ public int getVibrateModeSetting() {
+ if (DEBUG) Log.i("Hello2", "getVibrateModeSetting");
+ if (isCs108Connected()) return cs108Library4A.getVibrateModeSetting();
+ else if (isCs710Connected()) return cs710Library4A.getVibrateModeSetting();
+ else Log.i("Hello2", "getVibrateModeSetting" + stringNOTCONNECT);
+ return -1;
+ }
+ public boolean setVibrateModeSetting(int vibrateModeSelect) {
+ if (DEBUG) Log.i("Hello2", "setVibrateModeSetting");
+ if (isCs108Connected()) return cs108Library4A.setVibrateModeSetting(vibrateModeSelect);
+ else if (isCs710Connected()) return cs710Library4A.setVibrateModeSetting(vibrateModeSelect);
+ else Log.i("Hello2", "setVibrateModeSetting" + stringNOTCONNECT);
+ return false;
+ }
+ public int getSavingFormatSetting() {
+ if (DEBUG) Log.i("Hello2", "getSavingFormatSetting");
+ if (isCs108Connected()) return cs108Library4A.getSavingFormatSetting();
+ else if (isCs710Connected()) return cs710Library4A.getSavingFormatSetting();
+ else Log.i("Hello2", "getSavingFormatSetting" + stringNOTCONNECT);
+ return -1;
+ }
+ public boolean setSavingFormatSetting(int savingFormatSelect) {
+ if (DEBUG) Log.i("Hello2", "setSavingFormatSetting");
+ if (isCs108Connected()) return cs108Library4A.setSavingFormatSetting(savingFormatSelect);
+ else if (isCs710Connected()) return cs710Library4A.setSavingFormatSetting(savingFormatSelect);
+ else Log.i("Hello2", "setSavingFormatSetting" + stringNOTCONNECT);
+ return false;
+ }
+ public int getCsvColumnSelectSetting() {
+ if (DEBUG) Log.i("Hello2", "getCsvColumnSelectSetting");
+ if (isCs108Connected()) return cs108Library4A.getCsvColumnSelectSetting();
+ else if (isCs710Connected()) return cs710Library4A.getCsvColumnSelectSetting();
+ else Log.i("Hello2", "getCsvColumnSelectSetting" + stringNOTCONNECT);
+ return -1;
+ }
+ public boolean setCsvColumnSelectSetting(int csvColumnSelect) {
+ if (DEBUG) Log.i("Hello2", "setCsvColumnSelectSetting");
+ if (isCs108Connected()) return cs108Library4A.setCsvColumnSelectSetting(csvColumnSelect);
+ else if (isCs710Connected()) return cs710Library4A.setCsvColumnSelectSetting(csvColumnSelect);
+ else Log.i("Hello2", "setCsvColumnSelectSetting" + stringNOTCONNECT);
+ return false;
+ }
+ public String getWedgeDeviceName() {
+ if (isCs108Connected()) return cs108Library4A.getWedgeDeviceName();
+ else return cs710Library4A.getWedgeDeviceName();
+ }
+ public String getWedgeDeviceAddress() {
+ if (isCs108Connected()) return cs108Library4A.getWedgeDeviceAddress();
+ else return cs710Library4A.getWedgeDeviceAddress();
+ }
+ public int getWedgeDeviceUUID2p1() {
+ if (isCs108Connected()) return cs108Library4A.getWedgeDeviceUUID2p1();
+ else return cs710Library4A.getWedgeDeviceUUID2p1();
+ }
+ public int getWedgePower() {
+ if (isCs108Connected()) return cs108Library4A.getWedgePower();
+ else return cs710Library4A.getWedgePower();
+ }
+ public String getWedgePrefix() {
+ if (isCs108Connected()) return cs108Library4A.getWedgePrefix();
+ else return cs710Library4A.getWedgePrefix();
+ }
+ public String getWedgeSuffix() {
+ if (isCs108Connected()) return cs108Library4A.getWedgeSuffix();
+ else return cs710Library4A.getWedgeSuffix();
+ }
+ public int getWedgeDelimiter() {
+ if (isCs108Connected()) return cs108Library4A.getWedgeDelimiter();
+ else return cs710Library4A.getWedgeDelimiter();
+ }
+ public int getWedgeOutput() {
+ if (isCs108Connected()) return cs108Library4A.getWedgeOutput();
+ else return cs710Library4A.getWedgeOutput();
+ }
+ public void setWedgeDeviceName(String wedgeDeviceName) {
+ if (isCs108Connected()) cs108Library4A.setWedgeDeviceName(wedgeDeviceName);
+ else cs710Library4A.setWedgeDeviceName(wedgeDeviceName);
+ }
+ public void setWedgeDeviceAddress(String wedgeDeviceAddress) {
+ if (isCs108Connected()) cs108Library4A.setWedgeDeviceAddress(wedgeDeviceAddress);
+ else cs710Library4A.setWedgeDeviceAddress(wedgeDeviceAddress);
+ }
+ public void setWedgeDeviceUUID2p1(int wedgeDeviceUUID2p1) {
+ if (isCs108Connected()) cs108Library4A.setWedgeDeviceUUID2p1(wedgeDeviceUUID2p1);
+ else cs710Library4A.setWedgeDeviceUUID2p1(wedgeDeviceUUID2p1);
+ }
+ public void setWedgePower(int iPower) {
+ if (isCs108Connected()) cs108Library4A.setWedgePower(iPower);
+ else cs710Library4A.setWedgePower(iPower);
+ }
+ public void setWedgePrefix(String string) {
+ if (isCs108Connected()) cs108Library4A.setWedgePrefix(string);
+ else cs710Library4A.setWedgePrefix(string);
+ }
+ public void setWedgeSuffix(String string) {
+ if (isCs108Connected()) cs108Library4A.setWedgeSuffix(string);
+ else cs710Library4A.setWedgeSuffix(string);
+ }
+ public void setWedgeDelimiter(int iValue) {
+ if (isCs108Connected()) cs108Library4A.setWedgeDelimiter(iValue);
+ else cs710Library4A.setWedgeDelimiter(iValue);
+ }
+ public void setWedgeOutput(int iOutput) {
+ if (isCs108Connected()) cs108Library4A.setWedgeOutput(iOutput);
+ else cs710Library4A.setWedgeOutput(iOutput);
+ }
+ public void saveWedgeSetting2File() {
+ if (isCs108Connected()) cs108Library4A.saveWedgeSetting2File();
+ else cs710Library4A.saveWedgeSetting2File();
+ }
+
+ //============ Bluetooth ============
+ public String getBluetoothICFirmwareVersion() {
+ if (DEBUG) Log.i("Hello2", "getBluetoothICFirmwareVersion");
+ if (isCs108Connected()) return cs108Library4A.getBluetoothICFirmwareVersion();
+ else if (isCs710Connected()) return cs710Library4A.getBluetoothICFirmwareVersion();
+ else Log.i("Hello2", "getBluetoothICFirmwareVersion" + stringNOTCONNECT);
+ return null;
+ }
+ public String getBluetoothICFirmwareName() {
+ if (DEBUG) Log.i("Hello2", "getBluetoothICFirmwareName");
+ if (isCs108Connected()) return cs108Library4A.getBluetoothICFirmwareName();
+ else if (isCs710Connected()) return cs710Library4A.getBluetoothICFirmwareName();
+ else Log.i("Hello2", "getBluetoothICFirmwareName" + stringNOTCONNECT);
+ return null;
+ }
+ public boolean setBluetoothICFirmwareName(String name) {
+ if (DEBUG) Log.i("Hello2", "setBluetoothICFirmwareName");
+ if (isCs108Connected()) return cs108Library4A.setBluetoothICFirmwareName(name);
+ else if (isCs710Connected()) return cs710Library4A.setBluetoothICFirmwareName(name);
+ else Log.i("Hello2", "setBluetoothICFirmwareName" + stringNOTCONNECT);
+ return false;
+ }
+
+ //============ Controller ============
+ public String hostProcessorICGetFirmwareVersion() {
+ if (DEBUG) Log.i("Hello2", "hostProcessorICGetFirmwareVersion");
+ if (isCs108Connected()) return cs108Library4A.hostProcessorICGetFirmwareVersion();
+ else if (isCs710Connected()) return cs710Library4A.hostProcessorICGetFirmwareVersion();
+ else Log.i("Hello2", "hostProcessorICGetFirmwareVersion" + stringNOTCONNECT);
+ return null;
+ }
+ public String getHostProcessorICSerialNumber() {
+ if (DEBUG) Log.i("Hello2", "getHostProcessorICSerialNumber");
+ if (isCs108Connected()) return cs108Library4A.getHostProcessorICSerialNumber();
+ else if (isCs710Connected()) return cs710Library4A.getHostProcessorICSerialNumber();
+ else Log.i("Hello2", "getHostProcessorICSerialNumber" + stringNOTCONNECT);
+ return null;
+ }
+ public String getHostProcessorICBoardVersion() {
+ if (DEBUG) Log.i("Hello2", "getHostProcessorICBoardVersion");
+ if (isCs108Connected()) return cs108Library4A.getHostProcessorICBoardVersion();
+ else if (isCs710Connected()) return cs710Library4A.getHostProcessorICBoardVersion();
+ else Log.i("Hello2", "getHostProcessorICBoardVersion" + stringNOTCONNECT);
+ return null;
+ }
+
+ //============ Controller notification ============
+ public int getBatteryLevel() {
+ if (DEBUG) Log.i("Hello2", "getBatteryLevel");
+ if (isCs108Connected()) return cs108Library4A.getBatteryLevel();
+ else if (isCs710Connected()) return cs710Library4A.getBatteryLevel();
+ else Log.i("Hello2", "getBatteryLevel" + stringNOTCONNECT);
+ return -1;
+ }
+ public boolean setAutoTriggerReporting(byte timeSecond) {
+ if (DEBUG) Log.i("Hello2", "setAutoTriggerReporting");
+ if (isCs108Connected()) return cs108Library4A.setAutoTriggerReporting(timeSecond);
+ else if (isCs710Connected()) return cs710Library4A.setAutoTriggerReporting(timeSecond);
+ else Log.i("Hello2", "setAutoTriggerReporting" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean getAutoBarStartSTop() {
+ if (DEBUG) Log.i("Hello2", "getAutoBarStartSTop");
+ if (isCs108Connected()) return cs108Library4A.getAutoBarStartSTop();
+ else if (isCs710Connected()) return cs710Library4A.getAutoBarStartSTop();
+ else Log.i("Hello2", "getAutoBarStartSTop" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean batteryLevelRequest() {
+ if (DEBUG) Log.i("Hello2", "batteryLevelRequest");
+ if (isCs108Connected()) return cs108Library4A.batteryLevelRequest();
+ else if (isCs710Connected()) return cs710Library4A.batteryLevelRequest();
+ else Log.i("Hello2", "batteryLevelRequest" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean setAutoBarStartSTop(boolean enable) {
+ if (DEBUG) Log.i("Hello2", "setAutoBarStartSTop");
+ if (isCs108Connected()) return cs108Library4A.setAutoBarStartSTop(enable);
+ else if (isCs710Connected()) return cs710Library4A.setAutoBarStartSTop(enable);
+ else Log.i("Hello2", "setAutoBarStartSTop" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean getTriggerReporting() {
+ if (DEBUG) Log.i("Hello2", "getTriggerReporting");
+ if (isCs108Connected()) cs108Library4A.getTriggerReporting();
+ else if (isCs710Connected()) cs710Library4A.getTriggerReporting();
+ else Log.i("Hello2", "getTriggerReporting" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean setTriggerReporting(boolean triggerReporting) {
+ if (DEBUG) Log.i("Hello2", "setTriggerReporting");
+ if (isCs108Connected()) return cs108Library4A.setTriggerReporting(triggerReporting);
+ else if (isCs710Connected()) return cs710Library4A.setTriggerReporting(triggerReporting);
+ else Log.i("Hello2", "setTriggerReporting" + stringNOTCONNECT);
+ return false;
+ }
+ public int iNO_SUCH_SETTING = -1;
+ public short getTriggerReportingCount() {
+ if (DEBUG) Log.i("Hello2", "getTriggerReportingCount");
+ if (isCs108Connected()) return cs108Library4A.getTriggerReportingCount();
+ else if (isCs710Connected()) return cs710Library4A.getTriggerReportingCount();
+ else Log.i("Hello2", "getTriggerReportingCount" + stringNOTCONNECT);
+ return 5;
+ }
+ public boolean setTriggerReportingCount(short triggerReportingCount) {
+ if (DEBUG) Log.i("Hello2", "setTriggerReportingCount");
+ if (isCs108Connected()) return cs108Library4A.setTriggerReportingCount(triggerReportingCount);
+ else if (isCs710Connected()) return cs710Library4A.setTriggerReportingCount(triggerReportingCount);
+ else Log.i("Hello2", "setTriggerReportingCount" + stringNOTCONNECT);
+ return false;
+ }
+ public String getBatteryDisplay(boolean voltageDisplay) {
+ if (DEBUG) Log.i("Hello2", "getBatteryDisplay");
+ if (isCs108Connected()) return cs108Library4A.getBatteryDisplay(voltageDisplay);
+ else if (isCs710Connected()) return cs710Library4A.getBatteryDisplay(voltageDisplay);
+ else Log.i("Hello2", "getBatteryDisplay is called befoe connection !!!");
+ return null;
+ }
+ String stringNOTCONNECT;
+ public String isBatteryLow() {
+ if (DEBUG) Log.i("Hello2", "isBatteryLow");
+ if (isCs108Connected()) return cs108Library4A.isBatteryLow();
+ else if (isCs710Connected()) return cs710Library4A.isBatteryLow();
+ else Log.i("Hello2", "isBatteryLow" + stringNOTCONNECT);
+ return null;
+ }
+ public int getBatteryCount() {
+ if (DEBUG2) Log.i("Hello2", "getBatteryCount");
+ if (isCs108Connected()) return cs108Library4A.getBatteryCount();
+ else if (isCs710Connected()) return cs710Library4A.getBatteryCount();
+ else Log.i("Hello2", "getBatteryCount" + stringNOTCONNECT);
+ return -1;
+ }
+ public boolean getTriggerButtonStatus() {
+ if (DEBUG2) Log.i("Hello2", "getTriggerButtonStatus");
+ if (isCs108Connected()) return cs108Library4A.getTriggerButtonStatus();
+ else if (isCs710Connected()) return cs710Library4A.getTriggerButtonStatus();
+ else Log.i("Hello2", "getTriggerButtonStatus" + stringNOTCONNECT);
+ return false;
+ }
+ public int getTriggerCount() {
+ if (DEBUG2) Log.i("Hello2", "getTriggerCount");
+ if (isCs108Connected()) return cs108Library4A.getTriggerCount();
+ else if (isCs710Connected()) return cs710Library4A.getTriggerCount();
+ else Log.i("Hello2", "getTriggerCount" + stringNOTCONNECT);
+ return -1;
+ }
+ //public interface NotificationListener { void onChange(); }
+ public void setNotificationListener(NotificationConnector.NotificationListener listener) {
+ if (DEBUG) Log.i("Hello2", "setNotificationListener");
+ if (isCs108Connected()) {
+ cs108Library4A.setNotificationListener(new NotificationConnector.NotificationListener() {
+ @Override
+ public void onChange() {
+ listener.onChange();
+ }
+ });
+ } else if (isCs710Connected()) {
+ cs710Library4A.setNotificationListener(new NotificationConnector.NotificationListener() {
+ @Override
+ public void onChange() {
+ listener.onChange();
+ }
+ });
+ }
+ else Log.i("Hello2", "setNotificationListener" + stringNOTCONNECT);
+ }
+ public byte[] onNotificationEvent() {
+ if (DEBUG2) Log.i("Hello2", "onNotificationEvent");
+ if (isCs108Connected()) return cs108Library4A.onNotificationEvent();
+ else if (isCs710Connected()) return cs710Library4A.onNotificationEvent();
+ else Log.i("Hello2", "onNotificationEvent" + stringNOTCONNECT);
+ return null;
+ }
+
+ //============ to be modified ============
+ public String getSerialNumber() {
+ if (DEBUG2) Log.i("Hello2", "getSerialNumber");
+ if (isCs108Connected()) return cs108Library4A.getSerialNumber();
+ else if (isCs710Connected()) return cs710Library4A.getSerialNumber();
+ else Log.i("Hello2", "getSerialNumber" + stringNOTCONNECT);
+ return null;
+ }
+ public boolean setRfidOn(boolean onStatus) {
+ if (DEBUG2) Log.i("Hello2", "setRfidOn");
+ if (isCs108Connected()) return cs108Library4A.setRfidOn(onStatus);
+ else if (isCs710Connected()) return cs710Library4A.setRfidOn(onStatus);
+ else Log.i("Hello2", "setRfidOn" + stringNOTCONNECT);
+ return false;
+ }
+ public int getcsModel() {
+ if (DEBUG2) Log.i("Hello2", "getcsModel");
+ if (isCs108Connected()) return cs108Library4A.getcsModel();
+ else if (isCs710Connected()) return cs710Library4A.getcsModel();
+ else Log.i("Hello2", "getcsModel" + stringNOTCONNECT);
+ return -1;
+ }
+ public int getAntennaCycle() {
+ if (DEBUG2) Log.i("Hello2", "getAntennaCycle");
+ if (isCs108Connected()) return cs108Library4A.getAntennaCycle();
+ else if (isCs710Connected()) return cs710Library4A.getAntennaCycle();
+ else Log.i("Hello2", "getAntennaCycle" + stringNOTCONNECT);
+ return -1;
+ }
+ public boolean setAntennaCycle(int antennaCycle) {
+ if (DEBUG2) Log.i("Hello2", "setAntennaCycle");
+ if (isCs108Connected()) return cs108Library4A.setAntennaCycle(antennaCycle);
+ else if (isCs710Connected()) return cs710Library4A.setAntennaCycle(antennaCycle);
+ else Log.i("Hello2", "setAntennaCycle" + stringNOTCONNECT);
+ return false;
+ }
+ public boolean setAntennaInvCount(long antennaInvCount) {
+ if (DEBUG2) Log.i("Hello2", "setAntennaInvCount");
+ if (isCs108Connected()) return cs108Library4A.setAntennaInvCount(antennaInvCount);
+ else if (isCs710Connected()) return cs710Library4A.setAntennaInvCount(antennaInvCount);
+ else Log.i("Hello2", "setAntennaInvCount" + stringNOTCONNECT);
+ return false;
+ }
+ public void clearInvalidata() {
+ if (DEBUG2) Log.i("Hello2", "clearInvalidata");
+ if (isCs108Connected()) cs108Library4A.clearInvalidata();
+ else if (isCs710Connected()) cs710Library4A.clearInvalidata();
+ else Log.i("Hello2", "clearInvalidata" + stringNOTCONNECT);
+ }
+ public int getInvalidata() {
+ if (DEBUG2) Log.i("Hello2", "getInvalidata");
+ if (isCs108Connected()) return cs108Library4A.getInvalidata();
+ else if (isCs710Connected()) return cs710Library4A.getInvalidata();
+ else Log.i("Hello2", "getInvalidata" + stringNOTCONNECT);
+ return -1;
+ }
+ public int getInvalidUpdata() {
+ if (DEBUG2) Log.i("Hello2", "getInvalidUpdata");
+ if (isCs108Connected()) return cs108Library4A.getInvalidUpdata();
+ else if (isCs710Connected()) return cs710Library4A.getInvalidUpdata();
+ else Log.i("Hello2", "getInvalidUpdata" + stringNOTCONNECT);
+ return -1;
+ }
+ public int getValidata() {
+ if (DEBUG2) Log.i("Hello2", "getValidata");
+ if (isCs108Connected()) return cs108Library4A.getValidata();
+ else if (isCs710Connected()) return cs710Library4A.getValidata();
+ else Log.i("Hello2", "getValidata" + stringNOTCONNECT);
+ return -1;
+ }
+
+ //============ not public ============
+ int bConnectStatus = 0;
+ int iServiceUuidConnectedBefore = -1;
+ private boolean isCs108Connected() { return (bConnectStatus == 1); }
+ private boolean isCs710Connected() { return (bConnectStatus == 7); }
+
+ public int setSelectData(RfidReader.TagType tagType, String mDid, boolean bNeedSelectedTagByTID, String stringProtectPassword, int selectFor, int selectHold) {
+ if (DEBUG2) Log.i("Hello2", "setSelectData");
+ if (isCs108Connected()) return cs108Library4A.setSelectData(tagType, mDid, bNeedSelectedTagByTID, stringProtectPassword, selectFor, selectHold);
+ else if (isCs710Connected()) return cs710Library4A.setSelectData(tagType, mDid, bNeedSelectedTagByTID, stringProtectPassword, selectFor, selectHold);
+ else Log.i("Hello2", "setSelectData" + stringNOTCONNECT);
+ return -1;
+ }
+ public int setOtherInventoryData(RfidReader.TagType tagType, String mDid) {
+ if (DEBUG2) Log.i("Hello2", "setOtherInventoryData");
+ //appendToLog("BtDataOut: tagType = " + (tagType == null ? "null" : tagType.toString()) + ", mDid = " + mDid);
+ if (isCs108Connected()) return cs108Library4A.setOtherInventoryData(tagType, mDid);
+ else if (isCs710Connected()) return cs710Library4A.setOtherInventoryData(tagType, mDid);
+ else Log.i("Hello2", "setOtherInventoryData" + stringNOTCONNECT);
+ return -1;
+ }
+}
+
+
+
+package com.csl.cslibrary4a;
+
+import android.Manifest;
+import android.bluetooth.BluetoothAdapter;
+import android.bluetooth.BluetoothDevice;
+import android.bluetooth.le.ScanCallback;
+import android.content.Context;
+import android.content.pm.PackageManager;
+import android.os.Build;
+import android.os.Handler;
+import android.widget.TextView;
+
+import java.nio.charset.StandardCharsets;
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Date;
+import java.util.List;
+
+import android.bluetooth.le.ScanResult;
+
+import androidx.core.app.ActivityCompat;
+
+public class CsReaderConnector {
+ final boolean appendToLogViewDisable = false;
+ final boolean DEBUG = false; final boolean DEBUGTHREAD = false;
+ boolean DEBUG_CONNECT, DEBUG_SCAN;
+ boolean DEBUG_APDATA;
+ public boolean sameCheck = true;
+
+ String byteArrayToString(byte[] packet) { return utility.byteArrayToString(packet); }
+ void appendToLog(String s) { utility.appendToLog(s); }
+ public boolean connect(ReaderDevice readerDevice) {
+ boolean result = false, DEBUG = true;
+ if (DEBUG) appendToLog("csReaderConnector.connect: readerDevice is " + (readerDevice == null ? "null" : "valid"));
+ int iNumberColon = readerDevice.getAddress().split(":").length;
+ int iNumberDot = readerDevice.getAddress().split("\\.").length;
+ if (DEBUG) appendToLog("csReaderConnector.connect with split[:].length = " + iNumberColon + ", split[.].length = " + iNumberDot);
+ if (DEBUG || DEBUG_CONNECT) appendToLog("csReaderConnector.connect(" + readerDevice.getAddress() + ")");
+ if (iNumberColon == 6 && iNumberDot == 4) { result = deviceFinder.connect(readerDevice); } //for http
+ else if (iNumberColon == 1 && iNumberDot == 1) { result = usbConnector.connect(readerDevice); } //for usb
+ else if (iNumberColon == 6 && iNumberDot == 1) result = bluetoothGatt.connect(readerDevice); //for bluetooth
+ if (result) writeDataCount = 0;
+ return result;
+ }
+
+ public boolean isConnected() {
+ if (bluetoothGatt.isConnected()) return true;
+ if (usbConnector != null && usbConnector.isConnected()) return true;
+ return false;
+ }
+
+ public void disconnect() {
+ bluetoothGatt.disconnect();
+ appendToLog("abcc done");
+ if (rfidConnector != null) {
+ rfidConnector.mRfidToWrite.clear(); appendToLog("BtDataOut: mRfidToWrite.clear 1");
+ }
+ if (rfidReader != null) rfidReader.mRx000ToWrite.clear();
+ }
+
+ public long getStreamInRate() { return bluetoothGatt.getStreamInRate(); }
+
+ int writeDataCount; int btSendTimeOut = 0; long btSendTime = 0; int BTSENDDELAY = 20;
+ boolean writeData(byte[] buffer, int timeout) {
+ if (rfidReader.isInventoring()) {
+ utility.appendToLogView("BtData: isInventoring is true when writeData " + byteArrayToString(buffer));
+ }
+ boolean result = false;
+ if (usbConnector != null && usbConnector.isConnected()) {
+ appendToLog("CsReaderConnector.writeData, UsbData: going to writeStreamOut with " + byteArrayToString(buffer));
+ result = usbConnector.writeStreamOut(buffer);
+ }
+ else result = bluetoothGatt.writeBleStreamOut(buffer);
+ if (!result) appendToLog("!!! failure to writeData with previous btSendTimeout = " + btSendTimeOut + ", btSendTime = " + btSendTime);
+ if (true) {
+ btSendTime = System.currentTimeMillis();
+ btSendTimeOut = timeout + BTSENDDELAY;
+ utility.appendToLog("csReaderConnector.writeData: UsbConnector: btSendTimeOut 0 = " + btSendTimeOut);
+ if ((usbConnector != null && !usbConnector.isConnected()) && !bluetoothGatt.isCharacteristicListRead()) btSendTimeOut += 3000;
+ utility.appendToLog("csReaderConnector.writeData: UsbConnector: btSendTimeOut 1 = " + btSendTimeOut);
+ }
+ utility.appendToLog("csReaderConnector.writeData: UsbConnector: result = " + result);
+ return result;
+ }
+
+ int[] crc_lookup_table = new int[]{
+ 0x0000, 0x1189, 0x2312, 0x329b, 0x4624, 0x57ad, 0x6536, 0x74bf,
+ 0x8c48, 0x9dc1, 0xaf5a, 0xbed3, 0xca6c, 0xdbe5, 0xe97e, 0xf8f7,
+ 0x1081, 0x0108, 0x3393, 0x221a, 0x56a5, 0x472c, 0x75b7, 0x643e,
+ 0x9cc9, 0x8d40, 0xbfdb, 0xae52, 0xdaed, 0xcb64, 0xf9ff, 0xe876,
+ 0x2102, 0x308b, 0x0210, 0x1399, 0x6726, 0x76af, 0x4434, 0x55bd,
+ 0xad4a, 0xbcc3, 0x8e58, 0x9fd1, 0xeb6e, 0xfae7, 0xc87c, 0xd9f5,
+ 0x3183, 0x200a, 0x1291, 0x0318, 0x77a7, 0x662e, 0x54b5, 0x453c,
+ 0xbdcb, 0xac42, 0x9ed9, 0x8f50, 0xfbef, 0xea66, 0xd8fd, 0xc974,
+ 0x4204, 0x538d, 0x6116, 0x709f, 0x0420, 0x15a9, 0x2732, 0x36bb,
+ 0xce4c, 0xdfc5, 0xed5e, 0xfcd7, 0x8868, 0x99e1, 0xab7a, 0xbaf3,
+ 0x5285, 0x430c, 0x7197, 0x601e, 0x14a1, 0x0528, 0x37b3, 0x263a,
+ 0xdecd, 0xcf44, 0xfddf, 0xec56, 0x98e9, 0x8960, 0xbbfb, 0xaa72,
+ 0x6306, 0x728f, 0x4014, 0x519d, 0x2522, 0x34ab, 0x0630, 0x17b9,
+ 0xef4e, 0xfec7, 0xcc5c, 0xddd5, 0xa96a, 0xb8e3, 0x8a78, 0x9bf1,
+ 0x7387, 0x620e, 0x5095, 0x411c, 0x35a3, 0x242a, 0x16b1, 0x0738,
+ 0xffcf, 0xee46, 0xdcdd, 0xcd54, 0xb9eb, 0xa862, 0x9af9, 0x8b70,
+ 0x8408, 0x9581, 0xa71a, 0xb693, 0xc22c, 0xd3a5, 0xe13e, 0xf0b7,
+ 0x0840, 0x19c9, 0x2b52, 0x3adb, 0x4e64, 0x5fed, 0x6d76, 0x7cff,
+ 0x9489, 0x8500, 0xb79b, 0xa612, 0xd2ad, 0xc324, 0xf1bf, 0xe036,
+ 0x18c1, 0x0948, 0x3bd3, 0x2a5a, 0x5ee5, 0x4f6c, 0x7df7, 0x6c7e,
+ 0xa50a, 0xb483, 0x8618, 0x9791, 0xe32e, 0xf2a7, 0xc03c, 0xd1b5,
+ 0x2942, 0x38cb, 0x0a50, 0x1bd9, 0x6f66, 0x7eef, 0x4c74, 0x5dfd,
+ 0xb58b, 0xa402, 0x9699, 0x8710, 0xf3af, 0xe226, 0xd0bd, 0xc134,
+ 0x39c3, 0x284a, 0x1ad1, 0x0b58, 0x7fe7, 0x6e6e, 0x5cf5, 0x4d7c,
+ 0xc60c, 0xd785, 0xe51e, 0xf497, 0x8028, 0x91a1, 0xa33a, 0xb2b3,
+ 0x4a44, 0x5bcd, 0x6956, 0x78df, 0x0c60, 0x1de9, 0x2f72, 0x3efb,
+ 0xd68d, 0xc704, 0xf59f, 0xe416, 0x90a9, 0x8120, 0xb3bb, 0xa232,
+ 0x5ac5, 0x4b4c, 0x79d7, 0x685e, 0x1ce1, 0x0d68, 0x3ff3, 0x2e7a,
+ 0xe70e, 0xf687, 0xc41c, 0xd595, 0xa12a, 0xb0a3, 0x8238, 0x93b1,
+ 0x6b46, 0x7acf, 0x4854, 0x59dd, 0x2d62, 0x3ceb, 0x0e70, 0x1ff9,
+ 0xf78f, 0xe606, 0xd49d, 0xc514, 0xb1ab, 0xa022, 0x92b9, 0x8330,
+ 0x7bc7, 0x6a4e, 0x58d5, 0x495c, 0x3de3, 0x2c6a, 0x1ef1, 0x0f78};
+
+ boolean dataRead = false; int dataReadDisplayCount = 0; boolean mCs108DataReadRequest = false;
+ int inventoryLength = 0;
+ int iSequenceNumber; boolean bDifferentSequence = false, bFirstSequence = true;
+ public int invalidata, invalidUpdata, validata;
+ public void clearInvalidata() {
+ invalidata = 0;
+ invalidUpdata = 0;
+ validata = 0;
+ }
+ //boolean dataInBufferResetting;
+
+ void processStreamInData() {
+ final boolean DEBUG = false;
+ int cs108DataReadStartOld = 0;
+ int cs108DataReadStart = 0;
+ boolean validHeader = false;
+
+ if (DEBUG) appendToLog("CsReaderConnector.processStreamInData: starts with cs108DataLeft " + (cs108DataLeft == null ? "null" : "valid"));
+ if (cs108DataLeft == null) return;
+ /*if (false && dataInBufferResetting) {
+ if (utility.DEBUG_FMDATA) appendToLog("FmData: RESET.");
+ dataInBufferResetting = false;
+ cs108DataLeftOffset = 0;
+ connectorDataList.clear();
+ }*/
+ if (DEBUG) appendToLog("CsReaderConnector.processStreamInData: " + (usbConnector == null ? "null" : (usbConnector.isConnected() ? "connected" : "not connected")) + " usbConnector");
+ int iStreamInBufferSize = ((usbConnector == null || !usbConnector.isConnected()) ? bluetoothGatt.getStreamInBufferSize() : usbConnector.getStreamInBufferSize());
+ if (DEBUG) appendToLog("CsReaderConnector.processStreamInData: iStreamInBufferSize = " + iStreamInBufferSize);
+ //boolean bFirst = true;
+ long lTime = System.currentTimeMillis();
+ boolean bLooping = false;
+ while (((usbConnector == null || !usbConnector.isConnected()) ? bluetoothGatt.getStreamInBufferSize() : usbConnector.getStreamInBufferSize()) != 0) {
+ if (DEBUG) appendToLog("CsReaderConnector.processStreamInData: while loop starts");
+ if (utility.DEBUG_FMDATA && bLooping == false) appendToLog("FmData: Enter loop with cs108DataLeftOffset=" + cs108DataLeftOffset + ", streamInBufferSize=" + iStreamInBufferSize);
+ bLooping = true;
+
+ if ((usbConnector == null || !usbConnector.isConnected()) && (System.currentTimeMillis() - lTime > (bluetoothGatt.getIntervalProcessBleStreamInData()/2))) {
+ appendToLog("CsReaderConnector.processStreamInData: timeout");
+ utility.writeDebug2File("Up2 " + bluetoothGatt.getIntervalProcessBleStreamInData()/2 + "ms Timeout");
+ utility.appendToLogView("FmData: Timeout !!!");
+ break;
+ }
+
+ if (usbConnector != null && !usbConnector.isConnected()) {
+ appendToLog("CsReaderConnector.processStreamInData: going to bluetoothGatt.getStreamInOverflowTime");
+ long streamInOverflowTime = bluetoothGatt.getStreamInOverflowTime();
+ int streamInMissing = bluetoothGatt.getStreamInBytesMissing();
+ if (streamInMissing != 0)
+ utility.appendToLogView("FmData: processCs108DataIn(" + bluetoothGatt.getStreamInTotalCounter() + ", " + bluetoothGatt.getStreamInAddCounter() + "): len=0, getStreamInOverflowTime()=" + streamInOverflowTime + ", MissBytes=" + streamInMissing + ", Offset=" + cs108DataLeftOffset);
+ }
+ if (DEBUG) appendToLog("CsReaderConnector.processStreamInData: going to readData");
+ int len = readData(cs108DataLeft, cs108DataLeftOffset, cs108DataLeft.length);
+ if (DEBUG) appendToLog("CsReaderConnector.processStreamInData: readData len = " + len);
+ if (utility.DEBUG_FMDATA && len != 0) {
+ byte[] debugData = new byte[len];
+ System.arraycopy(cs108DataLeft, cs108DataLeftOffset, debugData, 0, len);
+ appendToLog("FmData: " + len + " dataIn = " + byteArrayToString(debugData));
+ }
+ //if (len != 0 && bFirst) { bFirst = false; } //writeDebug2File("B" + String.valueOf(getIntervalProcessBleStreamInData()) + ", " + System.currentTimeMillis()); }
+ cs108DataLeftOffset += len;
+ if (len == 0) {
+ appendToLog("FmData: len is zero !!!");
+ if (zeroLenDisplayed == false) {
+ zeroLenDisplayed = true;
+ if (!usbConnector.isConnected()) {
+ if (bluetoothGatt.getStreamInTotalCounter() != bluetoothGatt.getStreamInAddCounter() || bluetoothGatt.getStreamInAddTime() != 0 || cs108DataLeftOffset != 0) {
+ if (DEBUG)
+ appendToLog("FmData: processCs108DataIn(" + bluetoothGatt.getStreamInTotalCounter() + "," + bluetoothGatt.getStreamInAddCounter() + "): len=0, getStreamInAddTime()=" + bluetoothGatt.getStreamInAddTime() + ", Offset=" + cs108DataLeftOffset);
+ }
+ }
+ }
+ if (cs108DataLeftOffset == cs108DataLeft.length) {
+ if (DEBUG) appendToLog("FmData: cs108DataLeftOffset=" + cs108DataLeftOffset + ", cs108DataLeft=" + byteArrayToString(cs108DataLeft));
+ }
+ break;
+ } else {
+ dataRead = true;
+ zeroLenDisplayed = false;
+
+ if (utility.DEBUG_FMDATA) appendToLog("FmData: cs108DataLeftOffset = " + cs108DataLeftOffset + ", cs108DataReadStart = " + cs108DataReadStart);
+ while (cs108DataLeftOffset >= cs108DataReadStart + 8) {
+ if (DEBUG) appendToLog("FmData: while looping");
+ validHeader = false;
+ byte[] dataIn = cs108DataLeft;
+ int iPayloadLength = (dataIn[cs108DataReadStart + 2] & 0xFF);
+ if ((dataIn[cs108DataReadStart + 0] == (byte) 0xA7)
+ && (dataIn[cs108DataReadStart + 1] == ((usbConnector != null && usbConnector.isConnected()) ? (byte) 0xE6 : (byte) 0xB3))
+ && (dataIn[cs108DataReadStart + 3] == (byte) 0xC2
+ || dataIn[cs108DataReadStart + 3] == (byte) 0x6A
+ || dataIn[cs108DataReadStart + 3] == (byte) 0xD9
+ || dataIn[cs108DataReadStart + 3] == (byte) 0xE8
+ || dataIn[cs108DataReadStart + 3] == (byte) 0x5F)
+ //&& ((dataIn[cs108DataReadStart + 4] == (byte) 0x82) || ((dataIn[cs108DataReadStart + 3] == (byte) 0xC2) && (dataIn[cs108DataReadStart + 8] == (byte) 0x81)))
+ && (dataIn[cs108DataReadStart + 5] == (byte) 0x9E)) {
+ if (DEBUG) appendToLog("FmData: matched header with cs108DataLeftOffset = " + cs108DataLeftOffset + ", cs108DataReadStart = " + cs108DataReadStart + ", iPayloadLength = " + iPayloadLength);
+ if (cs108DataLeftOffset - cs108DataReadStart < (iPayloadLength + 8))
+ break;
+
+ boolean bcheckChecksum = true;
+ int checksum = ((byte) dataIn[cs108DataReadStart + 6] & 0xFF) * 256 + ((byte) dataIn[cs108DataReadStart + 7] & 0xFF);
+ int checksum2 = 0;
+ if (bcheckChecksum) {
+ for (int i = cs108DataReadStart; i < cs108DataReadStart + 8 + iPayloadLength; i++) {
+ if (i != (cs108DataReadStart + 6) && i != (cs108DataReadStart + 7)) {
+ int index = (checksum2 ^ ((byte) dataIn[i] & 0x0FF)) & 0x0FF;
+ int table_value = crc_lookup_table[index];
+ checksum2 = (checksum2 >> 8) ^ table_value;
+ }
+ }
+ if (DEBUG) appendToLog("FmData: checksum = " + String.format("%04X", checksum) + ", checksum2 = " + String.format("%04X", checksum2));
+ }
+ if (DEBUG) appendToLog("FmData: bcheckChecksum = " + bcheckChecksum + ", checksum = " + checksum + ", checksum2 = " + checksum2);
+ if (bcheckChecksum && checksum != checksum2) {
+ if (utility.DEBUG_FMDATA) {
+ if (iPayloadLength < 0) {
+ appendToLog("FmData: CheckSum ERROR, iPayloadLength=" + iPayloadLength + ", cs108DataLeftOffset=" + cs108DataLeftOffset + ", dataIn=" + byteArrayToString(dataIn));
+ }
+ byte[] invalidPart = new byte[8 + iPayloadLength];
+ System.arraycopy(dataIn, cs108DataReadStart, invalidPart, 0, invalidPart.length);
+ appendToLog("FmData: processCs108DataIn_ERROR, INCORRECT RevChecksum=" + Integer.toString(checksum, 16) + ", CalChecksum2=" + Integer.toString(checksum2, 16) + ",data=" + byteArrayToString(invalidPart));
+ }
+ } else {
+ validHeader = true;
+ if (cs108DataReadStart > cs108DataReadStartOld) {
+ if (utility.DEBUG_FMDATA) {
+ byte[] invalidPart = new byte[cs108DataReadStart - cs108DataReadStartOld];
+ System.arraycopy(dataIn, cs108DataReadStartOld, invalidPart, 0, invalidPart.length);
+ appendToLog("FmData: processCs108DataIn_ERROR, before valid data, invalid unused data: " + invalidPart.length + ", " + byteArrayToString(invalidPart));
+ }
+ } else if (cs108DataReadStart < cs108DataReadStartOld)
+ if (utility.DEBUG_FMDATA) appendToLog("FmData: processCs108DataIn_ERROR, invalid cs108DataReadStartdata=" + cs108DataReadStart + " < cs108DataReadStartOld=" + cs108DataReadStartOld);
+ cs108DataReadStartOld = cs108DataReadStart;
+
+ ConnectorData connectorData = new ConnectorData();
+ byte[] dataValues = new byte[iPayloadLength];
+ System.arraycopy(dataIn, cs108DataReadStart + 8, dataValues, 0, dataValues.length);
+ connectorData.dataValues = dataValues;
+ connectorData.milliseconds = System.currentTimeMillis();
+ if (utility.DEBUG_FMDATA) {
+ byte[] headerbytes = new byte[8];
+ System.arraycopy(dataIn, cs108DataReadStart, headerbytes, 0, headerbytes.length);
+ appendToLog("FmData: Got formatted dataIn = " + byteArrayToString(headerbytes) + " " + byteArrayToString(dataValues));
+ }
+ switch (dataIn[cs108DataReadStart + 3]) {
+ case (byte) 0xC2:
+ case (byte) 0x6A:
+ if (dataIn[cs108DataReadStart + 3] == (byte) 0xC2) connectorData.connectorTypes = ConnectorData.ConnectorTypes.RFID;
+ else connectorData.connectorTypes = ConnectorData.ConnectorTypes.BARCODE;
+ if (dataIn[cs108DataReadStart + 8] == (byte) 0x81 || (bis108 == false && dataIn[cs108DataReadStart + 8] == (byte) 0x91)) {
+ int iSequenceNumber = (int) (dataIn[cs108DataReadStart + 4] & 0xFF);
+ int itemp = iSequenceNumber;
+ if (itemp < this.iSequenceNumber) {
+ itemp += 256;
+ }
+ itemp -= (this.iSequenceNumber + 1);
+ if (DEBUG) appendToLog("FmData: iSequenceNumber = " + iSequenceNumber + ", old iSequenceNumber = " + this.iSequenceNumber + ", difference = " + itemp);
+ if (itemp != 0) {
+ if (DEBUG) appendToLog("FmData: Non-zero iSequenceNumber difference = " + itemp);
+ connectorData.invalidSequence = true;
+ if (bFirstSequence == false) {
+ invalidata += itemp;
+ String stringSequenceList = "";
+ for (int i = 0; i < itemp; i++) {
+ int iMissedNumber = (iSequenceNumber - i - 1);
+ if (iMissedNumber < 0) iMissedNumber += 256;
+ stringSequenceList += (i != 0 ? ", " : "") + String.format("%X", iMissedNumber);
+ }
+ if (DEBUG) utility.appendToLogView("FmData: " + String.format("ERROR !!!: invalidata = %d, %X - %X, miss %d: ", invalidata, iSequenceNumber, this.iSequenceNumber, itemp) + stringSequenceList);
+ }
+ }
+ bFirstSequence = false;
+ this.iSequenceNumber = iSequenceNumber;
+ }
+ if (DEBUG) utility.appendToLogView("FmData: Rin: " + (connectorData.invalidSequence ? "invalid sequence" : "ok") + "," + byteArrayToString(connectorData.dataValues));
+ validata++;
+ break;
+ case (byte) 0xD9:
+ if (DEBUG) appendToLog("FmData: BARTRIGGER NotificationData = " + byteArrayToString(connectorData.dataValues));
+ connectorData.connectorTypes = ConnectorData.ConnectorTypes.NOTIFICATION;
+ break;
+ case (byte) 0xE8:
+ connectorData.connectorTypes = ConnectorData.ConnectorTypes.SILICONLAB;
+ break;
+ case (byte) 0x5F:
+ connectorData.connectorTypes = ConnectorData.ConnectorTypes.BLUETOOTH;
+ break;
+ }
+ this.connectorDataList.add(connectorData);
+ if (utility.DEBUG_FMDATA) appendToLog("FmData: Got PackageIn with connectorData Type = " + connectorData.connectorTypes.toString() + ", Data = " + byteArrayToString(connectorData.dataValues));
+ utility.writeDebug2File("Up2 " + connectorData.connectorTypes.toString() + ", " + byteArrayToString(connectorData.dataValues));
+ cs108DataReadStart += ((8 + iPayloadLength));
+
+ byte[] cs108DataLeftNew = new byte[CS108DATALEFT_SIZE];
+ if (cs108DataLeftOffset - cs108DataReadStart < 0) {
+ if (utility.DEBUG_FMDATA) appendToLog("FmData: cs108DataLeftOffset = " + cs108DataLeftOffset + ", cs108DataReadStart = " + cs108DataReadStart + ", buffer = " + byteArrayToString(cs108DataLeft));
+ break;
+ }
+ System.arraycopy(cs108DataLeft, cs108DataReadStart, cs108DataLeftNew, 0, cs108DataLeftOffset - cs108DataReadStart);
+ cs108DataLeft = cs108DataLeftNew;
+ cs108DataLeftOffset -= cs108DataReadStart;
+ cs108DataReadStart = 0;
+ cs108DataReadStart = -1;
+ if (true || mCs108DataReadRequest == false) {
+ mCs108DataReadRequest = true;
+ if (DEBUGTHREAD && DEBUG) appendToLog("ready2Write: start immediate mReadWriteRunnable");
+ //appendToLog("post mReadWriteRunnable within processBleStreamInData");
+ mHandler.removeCallbacks(mReadWriteRunnable); mHandler.post(mReadWriteRunnable);
+ if (utility.DEBUG_BTDATA && DEBUG) appendToLog("BtData: CsReaderConnector.processBleStreamOut starts mReadWriteRunnable as mCs108DataReadRequest");
+ } //appendToLog("BtData: processBleStreamOut cannot start mReadWriteRunnable as mCs108DataReadRequest is true");
+ }
+ }
+ if (DEBUG) appendToLog("FmData: going to loop again with validHeader = " + validHeader + ", cs108DataReadStart = " + cs108DataReadStart + ", cs108DataReadStartOld = " + cs108DataReadStartOld);
+ if (validHeader && cs108DataReadStart < 0) {
+ cs108DataReadStart = 0;
+ cs108DataReadStartOld = 0;
+ } else {
+ cs108DataReadStart++;
+ }
+ }
+ if (DEBUG) appendToLog("FmData: end of while loop with cs108DataReadStart = " + cs108DataReadStart + ", cs108DataLeftOffset = " + cs108DataLeftOffset);
+ if (cs108DataReadStart != 0 && cs108DataLeftOffset >= 8) {
+ if (utility.DEBUG_FMDATA) {
+ byte[] invalidPart = new byte[cs108DataReadStart];
+ System.arraycopy(cs108DataLeft, 0, invalidPart, 0, invalidPart.length);
+ byte[] validPart = new byte[cs108DataLeftOffset - cs108DataReadStart];
+ System.arraycopy(cs108DataLeft, cs108DataReadStart, validPart, 0, validPart.length);
+ appendToLog("FmData: processCs108DataIn_ERROR, ENDLOOP invalid unused data: " + invalidPart.length + ", " + byteArrayToString(invalidPart) + ", with valid data length=" + validPart.length + ", " + byteArrayToString(validPart));
+ utility.writeDebug2File("Up2 Invalid " + invalidPart.length + ", " + byteArrayToString(invalidPart));
+ }
+
+ byte[] cs108DataLeftNew = new byte[CS108DATALEFT_SIZE];
+ System.arraycopy(cs108DataLeft, cs108DataReadStart, cs108DataLeftNew, 0, cs108DataLeftOffset - cs108DataReadStart);
+ cs108DataLeft = cs108DataLeftNew;
+ cs108DataLeftOffset -= cs108DataReadStart; cs108DataReadStart = 0;
+ }
+ }
+ }
+ if (DEBUG) appendToLog("CsReaderConnector.processStreamInData: while loop ending");
+ if (utility.DEBUG_FMDATA && bLooping) appendToLog("FmData: Exit loop with cs108DataLeftOffset=" + cs108DataLeftOffset);
+ }
+
+ private int readData(byte[] buffer, int byteOffset, int byteCount) {
+ if (usbConnector != null && usbConnector.isConnected()) return usbConnector.readSteamIn(buffer, byteOffset, byteCount);
+ return bluetoothGatt.readSteamIn(buffer, byteOffset, byteCount); }
+
+ public class CsConnectorData {
+ public int getVoltageMv() { return notificationConnector.mVoltageValue; }
+ public int getVoltageCnt() { return notificationConnector.mVoltageCount; }
+ boolean getTriggerButtonStatus() { return notificationConnector.triggerButtonStatus; }
+ public int getTriggerCount() { return notificationConnector.iTriggerCount; }
+ Date timeStamp;
+ String getTimeStamp() {
+ SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
+ return sdf.format(csConnectorData.timeStamp);
+ }
+
+ }
+ public CsConnectorData csConnectorData;
+ public SettingData settingData;
+
+ RfidConnector rfidConnector; public RfidReader rfidReader;
+ public BarcodeConnector barcodeConnector; public BarcodeNewland barcodeNewland;
+ public NotificationConnector notificationConnector;
+ public ControllerConnector controllerConnector;
+ public BluetoothConnector bluetoothConnector;
+
+ private Handler mHandler = new Handler();
+
+ public void csConnectorDataInit() {
+ connectorDataList = new ArrayList<>();
+ cs108DataLeft = new byte[CS108DATALEFT_SIZE];
+ cs108DataLeftOffset = 0;
+ zeroLenDisplayed = false;
+
+ invalidata = 0;
+ validata = 0;
+ //dataInBufferResetting = false;
+
+ writeDataCount = 0;
+
+ csConnectorData = new CsConnectorData();
+ notificationConnector = new NotificationConnector(context, utility, settingData.triggerReporting, settingData.triggerReportingCountSetting);
+ controllerConnector = new ControllerConnector(context, utility);
+ bluetoothConnector = new BluetoothConnector(context, utility, settingData.userDebugEnable);
+ //settingData = new SettingData(context, utility);
+
+ rfidReader = new RfidReader(context, utility, this, bis108, bluetoothGatt, settingData, notificationConnector);
+ rfidConnector = rfidReader.rfidConnector;
+ barcodeConnector = new BarcodeConnector(context, utility);
+ barcodeNewland = new BarcodeNewland(context, utility, barcodeConnector, settingData.barcode2TriggerMode);
+ barcodeConnector.barcodeConnectorCallback = new BarcodeConnector.BarcodeConnectorCallback(){
+ @Override
+ public boolean callbackMethod(byte[] dataValues, BarcodeConnector.CsReaderBarcodeData csReaderBarcodeData) {
+ barcodeNewland.decodeBarcodeUplinkData(dataValues, csReaderBarcodeData);
+ return false;
+ }
+ };
+ settingData.setConnectedConnectors(notificationConnector, rfidReader);
+ mHandler.removeCallbacks(mReadWriteRunnable); mHandler.post(mReadWriteRunnable);
+ appendToLog("!!! all major classes are initialised");
+ }
+
+ final int CS108DATALEFT_SIZE = 300; //4000; //100;
+ private ArrayList connectorDataList;
+ byte[] cs108DataLeft;
+ int cs108DataLeftOffset;
+ boolean zeroLenDisplayed;
+
+ public UsbConnector usbConnector;
+ public DeviceFinder deviceFinder;
+ public BluetoothGatt bluetoothGatt;
+ ScanCallback mScanCallback = null;
+ BluetoothAdapter.LeScanCallback mLeScanCallback = null;
+ Context context; TextView mLogView; Utility utility; boolean bis108; int iScanType;
+ void setScanType(int iScanType) { this.iScanType = iScanType; }
+ public CsReaderConnector(Context context, TextView mLogView, Utility utility, boolean bis108) {
+ this.context = context;
+ this.mLogView = mLogView;
+ this.utility = utility;
+ this.bis108 = bis108;
+ this.iScanType = iScanType;
+ appendToLog("CsReaderConnector.CsReaderConnector with bis108 = " + (bis108 ? "true" : "false"));
+
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
+ mScanCallback = new ScanCallback() {
+ @Override
+ public void onBatchScanResults(List results) {
+ if (DEBUG) appendToLog("onBatchScanResults()");
+ }
+
+ @Override
+ public void onScanFailed(int errorCode) {
+ if (DEBUG) appendToLog("onScanFailed()");
+ }
+
+ @Override
+ public void onScanResult(int callbackType, ScanResult result) {
+ boolean DEBUG = true;
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
+ BluetoothGatt.CsScanData scanResultA = new BluetoothGatt.CsScanData(result.getDevice(), result.getRssi(), result.getScanRecord().getBytes());
+ boolean found98 = true;
+ if (true) {
+ CheckResult resultc = check9800(scanResultA);
+ if (resultc != null) {
+ found98 = resultc.is9802;
+ scanResultA.name = resultc.stringName;
+ }
+ }
+ if (DEBUG) appendToLog("CsReaderConnector " + bis108 + ", found98 = " + found98 + ", mScanResultList 0 = " + (mScanResultList != null ? "VALID" : "NULL"));
+ if (mScanResultList != null && found98) {
+ scanResultA.serviceUUID2p2 = check9800_serviceUUID2p1;
+ appendToLog("found980 with name = " + scanResultA.name + ", device.name = " + scanResultA.device.getName());
+ mScanResultList.add(scanResultA);
+ if (DEBUG) appendToLog("CsReaderConnector, bis108 = " + bis108 + ", mScanResultList 0 = " + mScanResultList.size() + ", serviceUUID2p2 = " + scanResultA.serviceUUID2p2);
+ }
+ }
+ }
+ };
+ } else {
+ mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
+ @Override
+ public void onLeScan(final BluetoothDevice device, final int rssi, final byte[] scanRecord) {
+ if (true) appendToLog("onLeScan()");
+ BluetoothGatt.CsScanData scanResultA = new BluetoothGatt.CsScanData(device, rssi, scanRecord);
+ boolean found98 = true;
+ if (true) {
+ CheckResult resultc = check9800(scanResultA);
+ if (resultc != null) {
+ found98 = resultc.is9802;
+ scanResultA.name = resultc.stringName;
+ }
+ }
+ appendToLog("found98 = " + found98 + ", mScanResultList 1 = " + (mScanResultList != null ? "VALID" : "NULL"));
+ if (mScanResultList != null && found98) {
+ scanResultA.serviceUUID2p2 = check9800_serviceUUID2p1;
+ mScanResultList.add(scanResultA);
+ appendToLog("mScanResultList 1 = " + mScanResultList.size());
+ }
+ }
+ };
+ }
+
+ DEBUG_APDATA = utility.DEBUG_APDATA;
+ if (utility.ENABLE_USBDATA && !bis108) {
+ usbConnector = new UsbConnector(this, context, null, -1, -1, utility);
+ usbConnector.connectorCallback = new UsbConnector.ConnectorCallback() {
+ @Override
+ public void callbackMethod() {
+ //appendToLog("going to processBleStreamInData with bis108 " + bis108 + " and connected " + isBleConnected());
+ processStreamInData();
+ }
+ };
+ }
+ if (bis108) {
+ deviceFinder = new DeviceFinder(this, utility);
+ }
+ bluetoothGatt = new BluetoothGatt(context, utility, (bis108 ? "9800" : "9802"));
+ bluetoothGatt.connectorCallback = new BluetoothGatt.ConnectorCallback() {
+ @Override
+ public void callbackMethod() {
+ //appendToLog("going to processBleStreamInData with bis108 " + bis108 + " and connected " + isBleConnected());
+ processStreamInData();
+ }
+ };
+ DEBUG_CONNECT = utility.DEBUG_CONNECT; DEBUG_SCAN = utility.DEBUG_SCAN;
+
+ //cs108ConnectorDataInit();
+ //mHandler.removeCallbacks(bluetoothGatt.runnableProcessBleStreamInData); mHandler.post(bluetoothGatt.runnableProcessBleStreamInData);
+ //if (DEBUGTHREAD) appendToLog("start immediate mReadWriteRunnable");
+ //mHandler.removeCallbacks(mReadWriteRunnable); mHandler.post(mReadWriteRunnable);
+ //mHandler.removeCallbacks(runnableRx000UplinkHandler); mHandler.post(runnableRx000UplinkHandler);
+ appendToLog("foregroundReader: new SettingData for bis108 as " + bis108);
+ settingData = new SettingData(context, utility, this);
+ }
+
+ public BluetoothGatt.CsScanData getNewDeviceScanned() {
+ if (!mScanResultList.isEmpty()) {
+ if (DEBUG_SCAN) appendToLog("mScanResultList.size() = " + mScanResultList.size());
+ BluetoothGatt.CsScanData csScanData = mScanResultList.get(0); mScanResultList.remove(0);
+ if (csScanData != null) {
+ appendToLog("found981 with name = " + csScanData.name + ", device.name = " + csScanData.device.getName());
+ //appendToLog("DeviceFinder, CsReaderConnector.getNewDeviceScanned: csScanData.getAddress is " + csScanData.getAddress());
+ }
+ return csScanData;
+ } else return null;
+ }
+ ArrayList mScanResultList = new ArrayList<>();
+ int check9800_serviceUUID2p1 = 0;
+ class CheckResult {
+ boolean is9802;
+ String stringName;
+ }
+ CheckResult check9800(BluetoothGatt.CsScanData scanResultA) {
+ boolean found98 = false, DEBUG = true;
+ if (DEBUG) appendToLog("decoded data size = " + scanResultA.decoded_scanRecord.size());
+ int iNewADLength = 0;
+ byte[] newAD = new byte[0];
+ int iNewADIndex = 0;
+ check9800_serviceUUID2p1 = -1;
+ if (bluetoothGatt.isBLUETOOTH_CONNECTinvalid()) return null;
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S && ActivityCompat.checkSelfPermission(context, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED)
+ return null;
+ CheckResult checkResult = new CheckResult(); checkResult.is9802 = false;
+ String strTemp = scanResultA.getDevice().getName();
+ if (strTemp != null && DEBUG)
+ appendToLog("Found name = " + strTemp + ", length = " + String.valueOf(strTemp.length()));
+ for (byte bdata : scanResultA.getScanRecord()) {
+ if (iNewADIndex >= iNewADLength && iNewADLength != 0) {
+ scanResultA.decoded_scanRecord.add(newAD);
+ iNewADIndex = 0;
+ iNewADLength = 0;
+ if (DEBUG) {
+ String stringADType = "";
+ if (newAD[0] == 1) stringADType = "Flags";
+ else if (newAD[0] == 2) stringADType = "Incomplete List of 16-bit Service UUIDs";
+ else if (newAD[0] == 3) stringADType = "Complete list of 16-bit service UUIDs";
+ else if (newAD[0] == 9) {
+ byte[] byteString = new byte[newAD.length - 1];
+ System.arraycopy(newAD, 1, byteString, 0, byteString.length);
+ checkResult.stringName = new String(byteString, StandardCharsets.UTF_8);
+ stringADType = "Complete local name, " + checkResult.stringName;
+ }
+ else if (newAD[0] == 0x0A) stringADType = "Tx power level";
+ else if (newAD[0] == 0x12) stringADType = "Peripheral connection interval range";
+ else if (newAD[0] == 0x16) stringADType = "Service data - 16-bit UUID";
+ else if (newAD[0] == 0x19) stringADType = "Appearance";
+ else if (newAD[0] == (byte)0xFF) {
+ String stringManufactuer = "Unknown";
+ if (newAD[2] == 0x00 && newAD[1] == 0x06) stringManufactuer = "Microsoft";
+ else if (newAD[2] == 0x00 && newAD[1] == 0x4C) stringManufactuer = "Apple";
+ stringADType = stringManufactuer + " manufacturer specific Data";
+ }
+ else stringADType = "Unhandled";
+ appendToLog("Size = " + scanResultA.decoded_scanRecord.size() + ", " + byteArrayToString(newAD) + ", " + stringADType);
+ }
+ }
+ if (iNewADLength == 0) {
+ iNewADLength = bdata;
+ newAD = new byte[iNewADLength];
+ iNewADIndex = 0;
+ } else newAD[iNewADIndex++] = bdata;
+ }
+ if (DEBUG) appendToLog("decoded data size = " + scanResultA.decoded_scanRecord.size());
+ for (int i = 0; /*scanResultA.device.getType() == BluetoothDevice.DEVICE_TYPE_LE &&*/ i < scanResultA.decoded_scanRecord.size(); i++) {
+ byte[] currentAD = scanResultA.decoded_scanRecord.get(i);
+ if (DEBUG) appendToLog("Processing decoded data = " + byteArrayToString(currentAD));
+ if (currentAD[0] == 2) {
+ if (DEBUG) appendToLog("Processing UUIDs 0" + (bis108 ? "0" : "2"));
+ if (((currentAD[1] == 0 && ((iScanType & 0x01) != 0)) || (currentAD[1] == 2 && ((iScanType & 0x02) != 0))) && currentAD[2] == (byte) 0x98) {
+ if (DEBUG) appendToLog("Found 980" + (bis108 ? "0" : "2"));
+ found98 = true;
+ check9800_serviceUUID2p1 = currentAD[1];
+ if (DEBUG) appendToLog("serviceUD1D2p1 = " + check9800_serviceUUID2p1);
+ break;
+ }
+ }
+ }
+ if (found98 == false && DEBUG)
+ appendToLog("No 9800: with scanData = " + byteArrayToString(scanResultA.getScanRecord()));
+ else if (DEBUG_SCAN)
+ appendToLog("CsReaderConnector " + bis108 + ", Found 9800: with scanData = " + byteArrayToString(scanResultA.getScanRecord()));
+ checkResult.is9802 = found98;
+ return checkResult;
+ }
+
+ long timeReady; boolean aborting = false, sendFailure = false;
+ private final Runnable mReadWriteRunnable = new Runnable() {
+ boolean ready2Write = false, DEBUG = false;
+ int timer2Write = 0;
+ boolean validBuffer;
+
+ @Override
+ public void run() {
+ if (DEBUGTHREAD || utility.DEBUG_BTDATA) appendToLog("BtData: CsReaderConnector.mReadWriteRunnable starts");
+ if (rfidConnector == null) {
+ mHandler.postDelayed(mReadWriteRunnable, 500);
+ if (utility.DEBUG_BTDATA) appendToLog("BtData: CsReaderConnector.mReadWriteRunnable restart after 500ms");
+ return;
+ }
+ if (timer2Write != 0 || bluetoothGatt.getStreamInBufferSize() != 0 || rfidConnector.mRfidToRead.size() != 0) {
+ validBuffer = true;
+ if (DEBUG) appendToLog("mReadWriteRunnable(): START, timer2Write=" + timer2Write + ", streamInBufferSize = " + bluetoothGatt.getStreamInBufferSize() + ", mRfidToRead.size=" + rfidConnector.mRfidToRead.size() + ", mRx000ToRead.size=" + rfidReader.mRx000ToRead.size());
+ } else validBuffer = false;
+ int intervalReadWrite = 250; //50; //50; //500; //500, 100;
+ if (rfidConnector.rfidPowerOnTimeOut >= intervalReadWrite) {
+ rfidConnector.rfidPowerOnTimeOut -= intervalReadWrite;
+ if (rfidConnector.rfidPowerOnTimeOut <= 0) {
+ rfidConnector.rfidPowerOnTimeOut = 0;
+ }
+ }
+ if (barcodeConnector.barcodePowerOnTimeOut >= intervalReadWrite) {
+ barcodeConnector.barcodePowerOnTimeOut -= intervalReadWrite;
+ if (barcodeConnector.barcodePowerOnTimeOut <= 0) {
+ barcodeConnector.barcodePowerOnTimeOut = 0;
+ }
+ }
+ if (barcodeConnector.barcodePowerOnTimeOut != 0)
+ if (DEBUG) appendToLog("mReadWriteRunnable(): barcodePowerOnTimeOut = " + barcodeConnector.barcodePowerOnTimeOut);
+
+ long lTime = System.currentTimeMillis();
+ if (DEBUGTHREAD) appendToLog("start new mReadWriteRunnable after " + intervalReadWrite + " ms");
+ //appendToLog("postDelayed mReadWriteRunnable within mReadWriteRunnable");
+ mHandler.removeCallbacks(mReadWriteRunnable); mHandler.postDelayed(mReadWriteRunnable, intervalReadWrite);
+ if (utility.DEBUG_BTDATA) appendToLog("BtData: CsReaderConnector.mReadWriteRunnable restart after 250ms");
+ if (rfidReader == null) return;
+
+ boolean bFirst = true;
+ boolean bLooping = false;
+ mCs108DataReadRequest = false;
+ while (!connectorDataList.isEmpty()) {
+ if (utility.DEBUG_PKDATA && bLooping == false) appendToLog("PkData: Entering loop with connectorDataList.size = " + connectorDataList.size());
+ bLooping = true;
+
+ if (!isConnected()) {
+ connectorDataList.clear();
+ } else if (System.currentTimeMillis() - lTime > (intervalRx000UplinkHandler / 2)) {
+ utility.writeDebug2File("Up3 " + "Timeout");
+ utility.appendToLogView("PkData: mReadWriteRunnable: TIMEOUT !!! mCs108DataRead.size() = " + connectorDataList.size());
+ break;
+ } else {
+ if (bFirst) { bFirst = false; } //writeDebug2File("C" + String.valueOf(intervalReadWrite) + ", " + System.currentTimeMillis()); }
+ try {
+ ConnectorData connectorData = connectorDataList.get(0);
+ connectorDataList.remove(0);
+ boolean bValid = true;
+ if (utility.DEBUG_PKDATA) appendToLog("PkData: connectorData.type = " + connectorData.connectorTypes.toString() + ", connectorData.dataValues = " + byteArrayToString(connectorData.dataValues));
+ if (rfidConnector.isMatchRfidToWrite(connectorData)) {
+ if (false) {
+ for (int i = 0; i < rfidReader.mRx000ToRead.size(); i++) {
+ if (rfidReader.mRx000ToRead.get(i).responseType == RfidReaderChipData.HostCmdResponseTypes.TYPE_COMMAND_END)
+ if (DEBUG) appendToLog("mRx0000ToRead with COMMAND_END is removed");
+ }
+ if (DEBUG) appendToLog("mRx000ToRead.clear !!!");
+ }
+ rfidReader.mRx000ToRead.clear(); if (DEBUG) appendToLog("mRx000ToRead.clear !!!");
+ if (writeDataCount > 0) writeDataCount--; if (bis108) ready2Write = true; //btSendTime = 0; aborting = false;
+ } else if (barcodeConnector.isMatchBarcodeToWrite(connectorData)) {
+ if (writeDataCount > 0) writeDataCount--; if (bis108) ready2Write = true; if (true) appendToLog("true isMatchBarcodeToWrite "); //btSendTime = 0;
+ } else if (notificationConnector.isMatchNotificationToWrite(connectorData)) {
+ if (writeDataCount > 0) writeDataCount--; ready2Write = true; if (true) appendToLog("true isMatchNotificationToWrite"); btSendTime = 0; if (utility.DEBUG_PKDATA) appendToLog("PkData: mReadWriteRunnable: matched notification. btSendTime is set to 0 to allow new sending.");
+ } else if (controllerConnector.isMatchControllerToWrite(connectorData)) {
+ if (writeDataCount > 0) writeDataCount--; ready2Write = true; if (false) appendToLog("true isMatchSiliconLabIcToWrite"); btSendTime = 0; if (utility.DEBUG_PKDATA) appendToLog("PkData: mReadWriteRunnable: matched AtmelIc. btSendTime is set to 0 to allow new sending.");
+ } else if (bluetoothConnector.isMatchBluetoothIcToWrite(connectorData)) {
+ if (writeDataCount > 0) writeDataCount--; ready2Write = true; appendToLog("ready2Write is set true after true isMatchBluetoothIcToWrite "); btSendTime = 0; if (utility.DEBUG_PKDATA) appendToLog("PKData: mReadWriteRunnable: matched bluetoothIc. btSendTime is set to 0 to allow new sending.");
+ } else if (rfidConnector.isRfidToRead(connectorData)) { rfidConnector.rfidValid = true;
+ } else if (barcodeConnector.isBarcodeToRead(connectorData)) {
+ } else if (notificationConnector.isNotificationToRead(connectorData)) {
+ /* if (mRfidDevice.mRfidToWrite.size() != 0 && mNotificationDevice.mNotificationToRead.size() != 0) {
+ mNotificationDevice.mNotificationToRead.remove(0);
+ mRfidDevice.mRfidToWrite.clear();
+ mSiliconLabIcDevice.mSiliconLabIcToWrite.add(SiliconLabIcPayloadEvents.RESET);
+
+ timeReady = System.currentTimeMillis() - 1500;
+ appendToLog("mReadWriteRunnable: endingMessage: changed timeReady");
+ }*/
+ } else bValid = false;
+ if (bValid) {
+ //writeDebug2File("Up33 " + cs108ReadData.cs108ConnectedDevices.toString() + ", " + byteArrayToString(cs108ReadData.dataValues));
+ } else {
+ appendToLog("mReadWriteRunnable: !!! CANNOT process " + byteArrayToString(connectorData.dataValues) + " with mDataToWriteRemoved = " + barcodeConnector.mDataToWriteRemoved);
+ utility.writeDebug2File("Up3 Invalid " + connectorData.dataValues.length + ", " + byteArrayToString(connectorData.dataValues));
+ }
+ if (barcodeConnector.mDataToWriteRemoved) {
+ barcodeConnector.mDataToWriteRemoved = false; ready2Write = true; btSendTime = 0;
+ appendToLog("ready2Write is set true after true mBarcodeDevice.mDataToWriteRemoved ");
+ if (utility.DEBUG_PKDATA) appendToLog("PkData: mReadWriteRunnable: processed barcode. btSendTime is set to 0 to allow new sending.");
+ }
+ } catch (Exception ex) {
+ }
+ }
+ }
+ if (utility.DEBUG_PKDATA && bLooping) appendToLog("PkData: Exiting loop with connectorDataList.size = " + connectorDataList.size());
+
+ lTime = System.currentTimeMillis();
+ if (rfidConnector.mRfidToWriteRemoved) {
+ rfidConnector.mRfidToWriteRemoved = false; ready2Write = true; btSendTime = 0; if (false) appendToLog("ready2Write is set true after true mRfidDevice.mRfidToWriteRemoved ");
+ btSendTime = (lTime - btSendTimeOut + BTSENDDELAY);
+ if (DEBUGTHREAD) appendToLog("ready2Write: start new mReadWriteRunnable after " + BTSENDDELAY + " ms");
+ //appendToLog("postDelayed mReadWriteRunnable within mReadWriteRunnable 2");
+ mHandler.removeCallbacks(mReadWriteRunnable); mHandler.postDelayed(mReadWriteRunnable, BTSENDDELAY + 2);
+ if (utility.DEBUG_BTDATA) appendToLog("BtData: CsReaderConnector.mReadWriteRunnable restart after " + (BTSENDDELAY + 2) +"ms") ;
+ if (utility.DEBUG_PKDATA) appendToLog("PkData: mReadWriteRunnable: processed Rfidcode. btSendTime is set to 0 to allow new sending with systime = " + lTime);
+ }
+ if (bis108) {
+ int timeout2Ready = 2000;
+ if (aborting || sendFailure) timeout2Ready = 200;
+ if (System.currentTimeMillis() > timeReady + timeout2Ready) ready2Write = true;
+ } else {
+ if (ready2Write == false && lTime - btSendTime > btSendTimeOut) {
+ appendToLog("ready2Write is set to true from false with difference = " + (lTime - btSendTime) + ", systime = " + lTime + ", btSendTime = " + btSendTime + ", btSendTimeOut = " + btSendTime);
+ ready2Write = true;
+ }
+ }
+ if (DEBUG) appendToLog("BtData: ready2Write = " + ready2Write);
+ if (ready2Write) {
+ timeReady = System.currentTimeMillis();
+ timer2Write = 0;
+ if (rfidConnector.rfidFailure) {
+ rfidConnector.mRfidToWrite.clear(); appendToLog("BtDataOut: mRfidToWrite.clear 2");
+ }
+ //if (barcodeConnector.barcodeFailure) { barcodeConnector.barcodeToWrite.clear(); appendToLog("barcodeToWrite is clear"); }
+ if (rfidReader.mRx000ToWrite.size() != 0 && rfidConnector.mRfidToWrite.size() == 0) {
+ if (DEBUG)
+ appendToLog("mReadWriteRunnable(): mRx000ToWrite.size=" + rfidReader.mRx000ToWrite.size() + ", mRfidToWrite.size=" + rfidConnector.mRfidToWrite.size());
+ rfidReader.addRfidToWrite(rfidReader.mRx000ToWrite.get(0));
+ }
+ boolean bisRfidCommandStop = false, bisRfidCommandExecute = false;
+ if (rfidConnector.mRfidToWrite.size() != 0 && DEBUG)
+ appendToLog("mRfidToWrite = " + rfidConnector.mRfidToWrite.get(0).rfidPayloadEvent.toString() + "." + byteArrayToString(rfidConnector.mRfidToWrite.get(0).dataValues) + ", ready2write = " + ready2Write);
+ if (rfidConnector.mRfidToWrite.size() != 0) {
+ RfidConnector.CsReaderRfidData csReaderRfidData = rfidConnector.mRfidToWrite.get(0);
+ if (csReaderRfidData.rfidPayloadEvent == RfidConnector.RfidPayloadEvents.RFID_COMMAND) {
+ int ii;
+ if (false) {
+ byte[] byCommandExeccute = new byte[]{0x70, 1, 0, (byte) 0xF0};
+ for (ii = 0; ii < 4; ii++) {
+ if (byCommandExeccute[ii] != csReaderRfidData.dataValues[ii]) break;
+ }
+ if (ii == 4) bisRfidCommandExecute = true;
+ }
+
+ byte[] byCommandStop = new byte[]{(byte) 0x40, 3, 0, 0, 0, 0, 0, 0};
+ for (ii = 0; ii < 4; ii++) {
+ if (byCommandStop[ii] != csReaderRfidData.dataValues[ii]) break;
+ }
+ if (ii == 4) bisRfidCommandStop = true;
+ if (DEBUG)
+ appendToLog("mRfidToWrite(0).dataValues = " + byteArrayToString(rfidConnector.mRfidToWrite.get(0).dataValues) + ", bisRfidCommandExecute = " + bisRfidCommandExecute + ", bisRfidCommandStop = " + bisRfidCommandStop);
+ }
+ }
+ if (barcodeConnector.barcodeToWrite.size() != 0 && true)
+ appendToLog("AAA 1 barcodeToWrite.size = " + barcodeConnector.barcodeToWrite.size() + ", bisRfidCommandStop = " + bisRfidCommandStop + ", barcodePowerOnTimeOut = " + barcodeConnector.barcodePowerOnTimeOut);
+ if (DEBUG) appendToLog("BtData: bisRfidCommandStop is " + bisRfidCommandStop);
+ if (bisRfidCommandStop) {
+ if (rfidConnector.rfidPowerOnTimeOut != 0) {
+ if (DEBUG) appendToLog("rfidPowerOnTimeOut = " + rfidConnector.rfidPowerOnTimeOut + ", mRfidToWrite.size() = " + rfidConnector.mRfidToWrite.size());
+ } else if (rfidConnector.rfidFailure == false && rfidConnector.mRfidToWrite.size() != 0) {
+ if (isConnected() == false) {
+ rfidConnector.mRfidToWrite.clear(); appendToLog("BtDataOut: mRfidToWrite.clear 3");
+ } else {
+ if (utility.DEBUG_BTDATA) appendToLog("BtData: CsReaderConnector.mReadWriteRunnable 1: currentTime = " + System.currentTimeMillis() + ", btSendTime = " + btSendTime + ", difference = " + (System.currentTimeMillis() - btSendTime) + ", btSendTimeOut = " + btSendTimeOut);
+ if (System.currentTimeMillis() - btSendTime > btSendTimeOut) {
+ boolean retValue = false;
+ appendToLog("aabb 5A");
+ byte[] dataOut = rfidConnector.sendRfidToWrite(usbConnector != null && usbConnector.isConnected());
+ if (dataOut != null) {
+ appendToLog("CsReaderConnector.mReadWriteRunnable: UsbConnector: going to writeData 1");
+ retValue = writeData(dataOut, (rfidConnector.mRfidToWrite.get(0).waitUplinkResponse ? 500 : 0));
+ if (false) appendToLog("BtData: done writeData with waitUplinkResponse = " + rfidConnector.mRfidToWrite.get(0).waitUplinkResponse);
+ }
+ appendToLog("BtData: done writeRfid with size = " + rfidConnector.mRfidToWrite.size() + ", PayloadEvents = " + rfidConnector.mRfidToWrite.get(0).rfidPayloadEvent.toString() + ", data=" + byteArrayToString(rfidConnector.mRfidToWrite.get(0).dataValues));
+ rfidConnector.sendRfidToWriteSent++;
+ if (retValue) {
+ rfidConnector.mRfidToWriteRemoved = false;
+ if (DEBUG) appendToLog("writeRfid() with sendRfidToWriteSent = " + rfidConnector.sendRfidToWriteSent);
+ sendFailure = false;
+ //bValue = true;
+ } else sendFailure = true;
+ ready2Write = false; //
+ appendToLog("ready2Write is set false after sendRfidToWrite");
+ }
+ }
+ }
+ } else if (!bis108 && rfidReader.isInventoring()) {
+ if (rfidConnector.rfidPowerOnTimeOut != 0) {
+ if (DEBUG) appendToLog("rfidPowerOnTimeOut = " + rfidConnector.rfidPowerOnTimeOut + ", mRfidToWrite.size() = " + rfidConnector.mRfidToWrite.size());
+ } else if (rfidConnector.rfidFailure == false && rfidConnector.mRfidToWrite.size() != 0) {
+ if (isConnected() == false) {
+ rfidConnector.mRfidToWrite.clear(); appendToLog("BtDataOut: mRfidToWrite.clear 4");
+ } else {
+ if (DEBUG)
+ appendToLog("BtDataOut 2: currentTime = " + System.currentTimeMillis() + ", btSendTime = " + btSendTime + ", difference = " + (System.currentTimeMillis() - btSendTime) + ", btSendTimeOut = " + btSendTimeOut);
+ if (System.currentTimeMillis() - btSendTime > btSendTimeOut) {
+ boolean retValue = false;
+ appendToLog("aabb 5b");
+ byte[] dataOut = rfidConnector.sendRfidToWrite(usbConnector != null && usbConnector.isConnected());
+ if (dataOut != null) {
+ appendToLog("CsReaderConnector.mReadWriteRunnable: UsbConnector: going to writeData 2");
+ retValue = writeData(dataOut, (rfidConnector.mRfidToWrite.get(0).waitUplinkResponse ? 500 : 0));
+ if (false) appendToLog("done writeData with waitUplinkResponse = " + rfidConnector.mRfidToWrite.get(0).waitUplinkResponse);
+ }
+ if (DEBUG) appendToLog("BtDataOut: done writeRfid with size = " + rfidConnector.mRfidToWrite.size() + ", PayloadEvents = " + rfidConnector.mRfidToWrite.get(0).rfidPayloadEvent.toString() + ", data=" + byteArrayToString(rfidConnector.mRfidToWrite.get(0).dataValues));
+ rfidConnector.sendRfidToWriteSent++;
+ if (retValue) {
+ rfidConnector.mRfidToWriteRemoved = false;
+ if (DEBUG) appendToLog("writeRfid() with sendRfidToWriteSent = " + rfidConnector.sendRfidToWriteSent);
+ sendFailure = false;
+ //bValue = true;
+ } else sendFailure = true;
+
+ if (retValue) {
+ ready2Write = false;
+ if (false) appendToLog("ready2Write is set false after true sendRfidToWrite");
+ }
+ }
+ }
+ }
+ } else if (notificationConnector.notificationToWrite.size() != 0) {
+ appendToLog("aabb 3n");
+ if (isConnected() == false) {
+ notificationConnector.notificationToWrite.clear(); appendToLog("notificationToWrite is clear"); }
+ else if (System.currentTimeMillis() - btSendTime > btSendTimeOut) {
+ appendToLog("aabb 3n1");
+ appendToLog("1 UsbConnector is " + (usbConnector == null ? "null" : "valid") + "with bis108 as " + bis108);
+ byte[] dataOut = notificationConnector.sendNotificationToWrite((usbConnector != null && usbConnector.isConnected()));
+ boolean retValue = false;
+
+ if (utility.DEBUG_PKDATA && notificationConnector.sendDataToWriteSent != 0)
+ appendToLog("!!! notificationToWrite.sendDataToWriteSent = " + controllerConnector.sendDataToWriteSent);
+ if (utility.DEBUG_PKDATA)
+ appendToLog(String.format("PkData: write notificationToWrite.%s with notificationConnector.sendDataToWriteSent = %d",
+ notificationConnector.notificationToWrite.get(0).notificationPayloadEvent.toString(),
+ notificationConnector.sendDataToWriteSent));
+ if (false && notificationConnector.sendDataToWriteSent != 0)
+ appendToLog("!!! mSiliconLabIcDevice.sendDataToWriteSent = " + notificationConnector.sendDataToWriteSent);
+
+ if (dataOut != null) {
+ appendToLog("aabb 3n2");
+ appendToLog("CsReaderConnector.mReadWriteRunnable: UsbConnector: going to writeData 3 " + byteArrayToString(dataOut));
+ retValue = writeData(dataOut, 0);
+ }
+ if (retValue) {
+ //notificationController.sendDataToWriteSent++;
+ } else {
+ //if (DEBUG) appendToLogView("failure to send " + notificationController.notificationToWrite.get(0).toString());
+ //notificationController.notificationToWrite.remove(0); notificationController.sendDataToWriteSent = 0; appendToLog("notificationToWrite remove0 with length = " + notificationToWrite.size());
+ }
+ }
+ ready2Write = false; //
+ if (false) appendToLog("ready2Write is set false after true sendSiliconLabIcToWrite");
+ } else if (controllerConnector.controllerToWrite.size() != 0) {
+ appendToLog("AAA 5");
+ if (isConnected() == false) controllerConnector.controllerToWrite.clear();
+ else if (System.currentTimeMillis() - btSendTime > btSendTimeOut) {
+ byte[] dataOut = controllerConnector.sendControllerToWrite(usbConnector != null && usbConnector.isConnected());
+ boolean retValue = false;
+
+ if (utility.DEBUG_PKDATA && controllerConnector.sendDataToWriteSent != 0)
+ appendToLog("!!! siliconLabIcDevice.sendDataToWriteSent = " + controllerConnector.sendDataToWriteSent);
+ if (utility.DEBUG_PKDATA)
+ appendToLog(String.format("PkData: write mSiliconLabIcDevice.%s with mSiliconLabIcDevice.sendDataToWriteSent = %d",
+ controllerConnector.controllerToWrite.get(0).toString(),
+ controllerConnector.sendDataToWriteSent));
+ if (false && controllerConnector.sendDataToWriteSent != 0)
+ appendToLog("!!! mSiliconLabIcDevice.sendDataToWriteSent = " + controllerConnector.sendDataToWriteSent);
+
+ if (dataOut != null) {
+ appendToLog("CsReaderConnector.mReadWriteRunnable: UsbConnector: going to writeData 4");
+ retValue = writeData(dataOut, 0);
+ }
+ if (retValue) {
+ //controllerConnector.sendDataToWriteSent++;
+ } else {
+ //if (DEBUG) appendToLogView("failure to send " + controllerConnector.controllerToWrite.get(0).toString());
+ //controllerConnector.controllerToWrite.remove(0); controllerConnector.sendDataToWriteSent = 0;
+ }
+ }
+ ready2Write = false; //
+ if (false) appendToLog("ready2Write is set false after true sendSiliconLabIcToWrite");
+ } else if (bluetoothConnector.bluetoothIcToWrite.size() != 0) { //Bluetooth version affects Barcode operation
+ appendToLog("AAA 6");
+ if (isConnected() == false) bluetoothConnector.bluetoothIcToWrite.clear();
+ else if (System.currentTimeMillis() - btSendTime > btSendTimeOut) {
+ byte[] dataOut = bluetoothConnector.sendBluetoothIcToWrite(usbConnector != null && usbConnector.isConnected());
+ boolean retValue = false;
+
+ if (utility.DEBUG_PKDATA && bluetoothConnector.sendDataToWriteSent != 0)
+ appendToLog("!!! mBluetoothIcDevice.sendDataToWriteSent = " + bluetoothConnector.sendDataToWriteSent);
+ if (utility.DEBUG_PKDATA)
+ appendToLog(String.format("PkData: write mBluetoothIcDevice.%s.%s with mBluetoothIcDevice.sendDataToWriteSent = %d",
+ bluetoothConnector.bluetoothIcToWrite.get(0).bluetoothIcPayloadEvent.toString(),
+ byteArrayToString(bluetoothConnector.bluetoothIcToWrite.get(0).dataValues),
+ bluetoothConnector.sendDataToWriteSent));
+ if (bluetoothConnector.sendDataToWriteSent != 0)
+ appendToLog("!!! mBluetoothIcDevice.sendDataToWriteSent = " + bluetoothConnector.sendDataToWriteSent);
+
+ if (dataOut != null) {
+ appendToLog("CsReaderConnector.mReadWriteRunnable: UsbConnector: going to writeData 5");
+ retValue = writeData(dataOut, 0);
+ }
+ if (retValue) {
+ //bluetoothConnector.sendDataToWriteSent++;
+ } else {
+ //if (DEBUG) appendToLogView("failure to send " + bluetoothConnector.bluetoothIcToWrite.get(0).bluetoothIcPayloadEvent.toString());
+ //bluetoothConnector.bluetoothIcToWrite.remove(0); bluetoothConnector.sendDataToWriteSent = 0;
+ }
+ }
+ ready2Write = false;
+ appendToLog("ready2Write is set false after non-zero mBluetoothIcToWrite.size()");
+ } else if (barcodeConnector.barcodeToWrite.size() != 0 && barcodeConnector.barcodePowerOnTimeOut == 0) {
+ appendToLog("AAA 7 barcodeToWrite.size = " + barcodeConnector.barcodeToWrite.size());
+ if (isConnected() == false) { barcodeConnector.barcodeToWrite.clear(); appendToLog("barcodeToWrite is clear"); }
+ else if (System.currentTimeMillis() - btSendTime > btSendTimeOut) {
+ appendToLog("2 UsbConnector is " + (usbConnector == null ? "null" : "valid"));
+ byte[] dataOut = barcodeConnector.sendBarcodeToWrite( usbConnector != null && usbConnector.isConnected());
+ if (dataOut != null) {
+ appendToLog("CsReaderConnector.mReadWriteRunnable: UsbConnector: going to writeData 6");
+ writeData(dataOut, (barcodeConnector.barcodeToWrite.get(0).waitUplinkResponse ? 500 : 0));
+ }
+ }
+ ready2Write = false;
+ appendToLog("ready2Write is set false after true sendBarcodeToWrite");
+ } else if (rfidConnector.rfidPowerOnTimeOut != 0) {
+ if (DEBUG || true) appendToLog("rfidPowerOnTimeOut = " + rfidConnector.rfidPowerOnTimeOut + ", mRfidToWrite.size() = " + rfidConnector.mRfidToWrite.size());
+ } else if (rfidConnector.rfidFailure == false && rfidConnector.mRfidToWrite.size() != 0) {
+ appendToLog("aabb 3");
+ if (utility.DEBUG_BTDATA) appendToLog("BtData: CsReaderConnector.mReadWriteRunnable rfidFailure is false and mRfidToWrite.size is " + rfidConnector.mRfidToWrite.size());
+ if (isConnected() == false) {
+ rfidConnector.mRfidToWrite.clear(); appendToLog("BtDataOut: mRfidToWrite.clear 5");
+ } else {
+ if (utility.DEBUG_BTDATA)
+ appendToLog("BtData: CsReaderConnector.mReadWriteRunnable 3 currentTime = " + System.currentTimeMillis() + ", btSendTime = " + btSendTime + ", difference = " + (System.currentTimeMillis() - btSendTime) + ", btSendTimeOut = " + btSendTimeOut);
+ appendToLog("aabb 4");
+ if (System.currentTimeMillis() - btSendTime > btSendTimeOut) {
+ boolean retValue = false;
+ appendToLog("aabb 5c");
+ byte[] dataOut = rfidConnector.sendRfidToWrite(usbConnector != null && usbConnector.isConnected());
+ if (dataOut != null) {
+ appendToLog("CsReaderConnector.mReadWriteRunnable: UsbConnector: going to writeData 7");
+ retValue = writeData(dataOut, (rfidConnector.mRfidToWrite.get(0).waitUplinkResponse ? 500 : 0));
+ if (false) appendToLog("done writeData with waitUplinkResponse = " + rfidConnector.mRfidToWrite.get(0).waitUplinkResponse);
+
+ if (false) appendToLog("AAA sending rifd data = " + byteArrayToString(dataOut));
+ String string = byteArrayToString(dataOut).substring(16);
+ String stringCompare = "800280B310A";
+ if (bis108) stringCompare = "8002700100F00F000000";
+ if (false) appendToLog("AAA sending rifd data portion = " + string + ", " + string.indexOf(stringCompare));
+ if (string.indexOf(stringCompare) == 0)
+ rfidReader.setInventoring(true);
+ }
+ if (DEBUG && !rfidConnector.mRfidToWrite.isEmpty())
+ appendToLog("BtDataOut: done writeRfid with size = " + rfidConnector.mRfidToWrite.size() + ", PayloadEvents = " + rfidConnector.mRfidToWrite.get(0).rfidPayloadEvent.toString() + ", data=" + byteArrayToString(rfidConnector.mRfidToWrite.get(0).dataValues));
+ rfidConnector.sendRfidToWriteSent++;
+ if (retValue) {
+ rfidConnector.mRfidToWriteRemoved = false;
+ if (DEBUG)
+ appendToLog("writeRfid() with sendRfidToWriteSent = " + rfidConnector.sendRfidToWriteSent);
+ sendFailure = false;
+ //bValue = true;
+ } else sendFailure = true;
+
+ if (retValue) {
+ if (false) appendToLog("ready2Write is set false after true sendRfidToWrite");
+ ready2Write = false;
+ }
+ }
+ }
+ }
+ }
+ /*if (validBuffer) {
+ if (DEBUG) appendToLog("mReadWriteRunnable: END, timer2Write=" + timer2Write + ", streamInBufferSize = " + bluetoothGatt.getStreamInBufferSize() + ", mRfidToRead.size=" + rfidConnector.mRfidToRead.size() + ", mRx000ToRead.size=" + rfidReader.mRx000ToRead.size());
+ }*/
+ //appendToLog("mRfidDevice is " + (mRfidDevice == null ? "null" : "valid"));
+ //appendToLog("mRfidDevice.mRfidReaderChip is " + (mRfidDevice.mRfidReaderChip == null ? "null" : "valid"));
+ //appendToLog("mRfidDevice.mRfidReaderChip.mRfidReaderChip is " + (mRfidDevice.mRfidReaderChip.mRfidReaderChip == null ? "null" : "valid"));
+ if (rfidReader != null) rfidReader.uplinkHandler();
+ if (DEBUGTHREAD) appendToLog("mReadWriteRunnable: mReadWriteRunnable ends");
+ }
+ };
+
+ int intervalRx000UplinkHandler = 250;
+ /*private final Runnable runnableRx000UplinkHandler = new Runnable() {
+ @Override
+ public void run() {
+// mRfidDevice.mRx000Device.mRx000UplinkHandler();
+ mHandler.postDelayed(runnableRx000UplinkHandler, intervalRx000UplinkHandler);
+ }
+ };
+ */
+
+ public String getModelName() {
+ boolean DEBUG = true;
+ if (bis108) return controllerConnector.getModelName();
+ String strModelName = controllerConnector.getModelName();
+ if (DEBUG) appendToLog("Cs710Library4A.getModelName 0xb006 = " + strModelName);
+ if (true) {
+ String strModelName1 = rfidReader.rfidReaderChipE710.rx000Setting.getModelCode();
+ if (DEBUG) appendToLog("Cs710Library4A.getModelName strModelName1 = " + strModelName1);
+ if (strModelName == null || strModelName.length() == 0) {
+ if (DEBUG) appendToLog("Cs710Library4A.getModelName strModeName is updated as modeCode");
+ strModelName = strModelName1;
+ }
+ }
+ return strModelName;
+ }
+
+ public int getBatteryLevel() {
+ int iValue = csConnectorData.getVoltageMv();
+ if (!bis108) {
+ String hostVersion = controllerConnector.getVersion(); //false if lower, true if equal or higher
+ String strVersionHost = "2.1.5";
+ String[] strHostVersions = strVersionHost.split("\\.");
+ boolean bResult = utility.checkHostProcessorVersion(hostVersion, Integer.parseInt(strHostVersions[0].trim()), Integer.parseInt(strHostVersions[1].trim()), Integer.parseInt(strHostVersions[2].trim()));
+ if (false)
+ appendToLog("getBatteryLevel: hostVersion = " + hostVersion + ", bResult = " + bResult + ", level = " + iValue);
+ if (!bResult) {
+ if (iValue >= 4450) iValue -= 430;
+ else if (iValue > 350) iValue -= 350;
+ }
+ }
+ return iValue;
+ }
+
+ public String checkVersion() {
+ appendToLog("CsReaderConnector.checkVersion, getMacVer");
+ String macVersion = rfidReader.getMacVer();
+ String hostVersion = controllerConnector.getVersion();
+ String bluetoothVersion = bluetoothConnector.getBluetoothIcVersion();
+ String stringPopup = "";
+ int icsModel = bluetoothConnector.getCsModel();
+
+ if (!rfidReader.isRfidFailure()) {
+ if (bis108) return null; //Assume no checking
+ if (bis108) {
+ String strVersionRFID = "2.6.46"; String[] strRFIDVersions = strVersionRFID.split("\\.");
+ String strVersionBT = "1.0.22"; String[] strBTVersions = strVersionBT.split("\\.");
+ String strVersionHost = "1.0.17"; String[] strHostVersions = strVersionHost.split("\\.");
+ if (true) {
+ if (utility.checkHostProcessorVersion(macVersion, Integer.parseInt(strRFIDVersions[0].trim()), Integer.parseInt(strRFIDVersions[1].trim()), Integer.parseInt(strRFIDVersions[2].trim())) == false)
+ stringPopup += "\nRFID processor firmware: V" + strVersionRFID;
+ if (icsModel != 463) {
+ if (utility.checkHostProcessorVersion(hostVersion, Integer.parseInt(strHostVersions[0].trim()), Integer.parseInt(strHostVersions[1].trim()), Integer.parseInt(strHostVersions[2].trim())) == false)
+ stringPopup += "\nSiliconLab firmware: V" + strVersionHost;
+ if (utility.checkHostProcessorVersion(bluetoothVersion, Integer.parseInt(strBTVersions[0].trim()), Integer.parseInt(strBTVersions[1].trim()), Integer.parseInt(strBTVersions[2].trim())) == false)
+ stringPopup += "\nBluetooth firmware: V" + strVersionBT;
+ }
+ }
+ } else {
+ String strVersionRFID = "0.0.0";
+ String strVersionHost = "0.0.0";
+ String strVersionBT = "1.0.8"; String[] strBTVersions = strVersionBT.split("\\.");
+ boolean bValidMac = true;
+ if (macVersion.indexOf("2.01") == 0) {
+ strVersionRFID = "2.1.0";
+ strVersionHost = "2.1.5";
+ } else if (macVersion.indexOf("2.00") == 0) {
+ strVersionRFID = "2.0.0";
+ strVersionHost = "2.0.6";
+ } else if (macVersion.indexOf("1.2.") == 0) {
+ strVersionRFID = "1.2.0";
+ strVersionHost = "0.2.20";
+ } else {
+ bValidMac = false;
+ stringPopup += "Unknown RFID firmware version";
+ }
+ if (bValidMac) {
+ String[] strRFIDVersions = strVersionRFID.split("\\.");
+ if (false && !utility.checkHostProcessorVersion(macVersion, Integer.parseInt(strRFIDVersions[0].trim()), Integer.parseInt(strRFIDVersions[1].trim()), Integer.parseInt(strRFIDVersions[2].trim())))
+ stringPopup += "\nRFID processor firmware: V" + strVersionRFID;
+ String[] strHostVersions = strVersionHost.split("\\.");
+ if (hostVersion.indexOf(strVersionHost.substring(0, 4)) != 0 ||
+ utility.checkHostProcessorVersion(hostVersion, Integer.parseInt(strHostVersions[0].trim()), Integer.parseInt(strHostVersions[1].trim()), Integer.parseInt(strHostVersions[2].trim())) == false)
+ stringPopup += "\nAtmel firmware: V" + strVersionHost;
+
+ if (icsModel != 463) {
+ if (false && utility.checkHostProcessorVersion(bluetoothVersion, Integer.parseInt(strBTVersions[0].trim()), Integer.parseInt(strBTVersions[1].trim()), Integer.parseInt(strBTVersions[2].trim())) == false)
+ stringPopup += "\nBluetooth firmware: V" + strVersionBT;
+ }
+ }
+ }
+ }
+ return stringPopup;
+ }
+}
+
+
+
+package com.csl.cslibrary4a;
+
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.net.DatagramPacket;
+import java.net.DatagramSocket;
+import java.net.InetAddress;
+import java.net.Socket;
+import java.nio.charset.StandardCharsets;
+import java.util.Random;
+
+public class DeviceFinder{
+ CsReaderConnector csReaderConnector;
+ Utility utility;
+ BluetoothGatt.CsScanData scanResultA = null;
+
+ public DeviceFinder(CsReaderConnector csReaderConnector, Utility utility) {
+ this.csReaderConnector = csReaderConnector;
+ this.utility = utility;
+ appendToLog("DeviceFinder.DeviceFinder");
+ }
+
+ void scanDevice(boolean enable) {
+ if (enable) {
+ Thread thread = new Thread(runnable);
+ thread.start();
+ }
+ }
+
+ Runnable runnable = new Runnable() {
+ @Override
+ public void run() {
+ appendToLog("DeviceFinder.runnable");
+
+ DatagramSocket udpSocket = null;
+ Socket tcpSocket = null;
+ ReaderSetting readerSetting = null;
+ try {
+ String strDestip = "255.255.255.255"; //"255.255.255.255", "192.168.25.197"
+
+ udpSocket = new DatagramSocket();
+ appendToLog("DeviceFinder.runnable: new udpSocket is " + (udpSocket == null ? "null" : "valid"));
+// udpSocket.setBroadcast(true);
+// appendToLog("DeviceFinder.runnable: done udpSocket.setBoardcast");
+ udpSocket.setSoTimeout(1000);
+ appendToLog("DeviceFinder.runnable: done udpSocket.setSoTimeout");
+
+ byte[] sbuffer = null; InetAddress address = null; int portnum = -1; DatagramPacket packet = null;
+ DatagramPacket p = null; byte[] message = null;
+ if (true) {
+ sbuffer = getBytesUdpSearch();
+
+ address = InetAddress.getByName(strDestip);
+ portnum = 3040;
+ appendToLog("DeviceFinder.runnable: done InetAddress.getByName with strDestip as " + strDestip + ", port as " + portnum);
+ packet = new DatagramPacket(sbuffer, sbuffer.length, address, portnum);
+
+ //Exception here
+ udpSocket.send(packet);
+ appendToLog("DeviceFinder.runnable: done udpSocket.send with sent data as " + utility.byteArrayToString(sbuffer));
+
+ message = new byte[200];
+ p = new DatagramPacket(message, message.length);
+ udpSocket.receive(p); //keeps on waiting here but i am sending data back from server, but it never receives
+ appendToLog("DeviceFinder.runnable: done udpSocket.receive");
+
+ final byte[] rxbuffer = p.getData();
+ appendToLog("DeviceFinder.runnable: with received " + (rxbuffer == null ? "null data" : ("data length as " + rxbuffer.length)));
+
+ readerSetting = decodeSearchReply(sbuffer, rxbuffer);
+ if (readerSetting != null) {
+ BluetoothGatt.CsScanData scanResultA = new BluetoothGatt.CsScanData(null, 0, readerSetting.rxbuffer1);
+ StringBuilder sb = new StringBuilder(300);
+ for (int k = 0; k < readerSetting.mac.length; k++) {
+ if (k != 0) sb.append(":");
+ sb.append(String.format("%02X", readerSetting.mac[k]));
+ }
+ sb.append(" ");
+ for (int k = 0; k < readerSetting.ip.length; k++) {
+ if (k != 0) sb.append(".");
+ sb.append(String.valueOf(readerSetting.ip[k] & 0xFF));
+ }
+ scanResultA.address = sb.toString();
+ appendToLog("DeviceFinder.runnable: scanResultA.address is " + scanResultA.address);
+
+ sb = new StringBuilder(100);
+ for (int k = 0; k < 4; k++) {
+ if (readerSetting.device_name[k] != null) {
+ if (k != 0) sb.append(", ");
+ sb.append(readerSetting.device_name[k]);
+ }
+ }
+ scanResultA.name = sb.toString();
+ appendToLog("DeviceFinder.runnable: scanResultA.name is " + scanResultA.name);
+ scanResultA.serviceUUID2p2 = 4;
+
+ if (csReaderConnector.mScanResultList != null) {
+ csReaderConnector.mScanResultList.add(scanResultA);
+ //appendToLog("DeviceFinder.runnable: scanResultA.getAddress is " + csReaderConnector.mScanResultList.get(0).getAddress());
+ }
+ }
+ } //3040 UdpSearch
+ if (false && readerSetting != null) {
+ sbuffer = getBytesUdpAssignment(readerSetting);
+
+ address = InetAddress.getByAddress(readerSetting.ip);
+ portnum = 3040;
+ appendToLog("DeviceFinder.runnable: done InetAddress.getByName with ip as " + utility.byteArrayToString(readerSetting.ip) + ", port as " + portnum);
+ packet = new DatagramPacket(sbuffer, sbuffer.length, address, portnum);
+
+ udpSocket.send(packet);
+ appendToLog("DeviceFinder.runnable: done udpSocket.send with sent data as " + utility.byteArrayToString(sbuffer));
+
+ p = new DatagramPacket(message, message.length);
+ udpSocket.receive(p); //keeps on waiting here but i am sending data back from server, but it never receives
+ appendToLog("DeviceFinder.runnable: done udpSocket.receive");
+
+ final byte[] rxbuffer = p.getData(); //exception here as java.net.SocketTimeoutException: Poll timed out
+ appendToLog("DeviceFinder.runnable: with received " + (rxbuffer == null ? "null data" : ("data length as " + rxbuffer.length)));
+
+ if (decodeAssignmentReply(sbuffer, rxbuffer)) appendToLog("DeviceFinder.runnable: decodeAssignmentReply is Okay");
+ else appendToLog("DeviceFinder.runnable: decodeAssignmentReply is invalid");
+ } //3040 UdpAssignment -- no reply
+ if (false && readerSetting != null) {
+ sbuffer = getBytesUdpControl(readerSetting.ip, UpdControlCommands.CheckStatus);
+
+ address = InetAddress.getByAddress(readerSetting.ip);
+ portnum = 3041;
+ appendToLog("DeviceFinder.runnable: done InetAddress.getByName with ip as " + utility.byteArrayToString(readerSetting.ip) + ", port as " + portnum);
+ packet = new DatagramPacket(sbuffer, sbuffer.length, address, portnum);
+
+ udpSocket.send(packet);
+ appendToLog("DeviceFinder.runnable: done udpSocket.send with sent data as " + utility.byteArrayToString(sbuffer));
+
+ p = new DatagramPacket(message, message.length);
+ udpSocket.receive(p); //keeps on waiting here but i am sending data back from server, but it never receives
+ appendToLog("DeviceFinder.runnable: done udpSocket.receive");
+
+ final byte[] rxbuffer2 = p.getData(); //exception here as java.net.SocketTimeoutException: Poll timed out
+ appendToLog("DeviceFinder.runnable: with received " + (rxbuffer2 == null ? "null data" : ("data length as " + rxbuffer2.length)));
+
+ if (decodeUdpControlReply(sbuffer, rxbuffer2)) appendToLog("DeviceFinder.runnable: decodeUdpControlReply is Okay");
+ else appendToLog("DeviceFinder.runnable: decodeUdpControlReply is invalid");
+ } //3041 UdpControl CheckStatus
+ if (false && readerSetting != null) {
+ sbuffer = getBytesUdpControl(readerSetting.ip, UpdControlCommands.GetBootloaderVersion);
+
+ address = InetAddress.getByAddress(readerSetting.ip);
+ portnum = 3041;
+ appendToLog("DeviceFinder.runnable: done InetAddress.getByName with ip as " + utility.byteArrayToString(readerSetting.ip) + ", port as " + portnum);
+ packet = new DatagramPacket(sbuffer, sbuffer.length, address, portnum);
+
+ udpSocket.send(packet);
+ appendToLog("DeviceFinder.runnable: done udpSocket.send with sent data as " + utility.byteArrayToString(sbuffer));
+
+ p = new DatagramPacket(message, message.length);
+ udpSocket.receive(p); //keeps on waiting here but i am sending data back from server, but it never receives
+ appendToLog("DeviceFinder.runnable: done udpSocket.receive");
+
+ final byte[] rxbuffer2 = p.getData(); //exception here as java.net.SocketTimeoutException: Poll timed out
+ appendToLog("DeviceFinder.runnable: with received " + (rxbuffer2 == null ? "null data" : ("data length as " + rxbuffer2.length)));
+
+ if (decodeUdpControlReply(sbuffer, rxbuffer2)) appendToLog("DeviceFinder.runnable: decodeUdpControlReply is Okay");
+ else appendToLog("DeviceFinder.runnable: decodeUdpControlReply is invalid");
+ } //3041 UdpControl GetBootloaderVersion
+ if (false && readerSetting != null) {
+ sbuffer = getBytesUdpControl(readerSetting.ip, UpdControlCommands.GetImageVersion);
+
+ address = InetAddress.getByAddress(readerSetting.ip);
+ portnum = 3041;
+ appendToLog("DeviceFinder.runnable: done InetAddress.getByName with ip as " + utility.byteArrayToString(readerSetting.ip) + ", port as " + portnum);
+ packet = new DatagramPacket(sbuffer, sbuffer.length, address, portnum);
+
+ udpSocket.send(packet);
+ appendToLog("DeviceFinder.runnable: done udpSocket.send with sent data as " + utility.byteArrayToString(sbuffer));
+
+ p = new DatagramPacket(message, message.length);
+ udpSocket.receive(p); //keeps on waiting here but i am sending data back from server, but it never receives
+ appendToLog("DeviceFinder.runnable: done udpSocket.receive");
+
+ final byte[] rxbuffer2 = p.getData(); //exception here as java.net.SocketTimeoutException: Poll timed out
+ appendToLog("DeviceFinder.runnable: with received " + (rxbuffer2 == null ? "null data" : ("data length as " + rxbuffer2.length)));
+
+ if (decodeUdpControlReply(sbuffer, rxbuffer2)) appendToLog("DeviceFinder.runnable: decodeUdpControlReply is Okay");
+ else appendToLog("DeviceFinder.runnable: decodeUdpControlReply is invalid");
+ } //3041 UdpControl GetImageVersion
+ } catch (Exception ex) {
+ appendToLog("DeviceFinder.runnable upd exception as " + ex.toString());
+ }
+ if (udpSocket != null && !udpSocket.isClosed()) {
+ udpSocket.close();
+ appendToLog("DeviceFinder.runnable: done udpSocket.close");
+ }
+
+ if (false && readerSetting != null) {
+ String stringIp = String.format("%d.%d.%d.%d", (readerSetting.ip[0] & 0xFF),
+ (readerSetting.ip[1] & 0xFF), (readerSetting.ip[2] & 0xFF), (readerSetting.ip[3] & 0xFF));
+ appendToLog("DeviceFinder.runnable: stringIp is " + stringIp);
+ byte[] data = null; InputStream input = null; byte[] dataIn = null; int iValue;
+ try {
+ tcpSocket = new Socket(stringIp, 1515);
+ appendToLog("DeviceFinder.runnable: done new Socket with Ip " + stringIp + " and port 1515");
+ OutputStream output = tcpSocket.getOutputStream();
+ appendToLog("DeviceFinder.runnable: done socket.getOutputStream");
+
+ if (true) {
+ data = getBytesTcpReader(TcpReaderCommands.Reset);
+ output.write(data);
+ appendToLog("DeviceFinder.runnable: done outputStream.write with sent data as " + utility.byteArrayToString(data));
+
+ input = tcpSocket.getInputStream();
+ appendToLog("DeviceFinder.runnable: done socket.getInputStream");
+
+ dataIn = new byte[64];
+ iValue = input.read(dataIn);
+ appendToLog("DeviceFinder.runnable: done inputStream.read with output value as " + iValue);
+ if (iValue > 0) {
+ byte[] dataIn1 = new byte[iValue];
+ System.arraycopy(dataIn, 0, dataIn1, 0, dataIn1.length);
+ appendToLog("DeviceFinder.runnable: with data as " + utility.byteArrayToString(dataIn1));
+ }
+ } //1515 TcpReaderCommand.Reset
+ if (false) {
+ data = getBytesTcpReader(TcpReaderCommands.WriteCommandClearError);
+ output.write(data);
+ appendToLog("DeviceFinder.runnable: done outputStream.write with data as " + utility.byteArrayToString(data));
+
+ input = tcpSocket.getInputStream();
+ appendToLog("DeviceFinder.runnable: done socket.getInputStream");
+
+ dataIn = new byte[64];
+ iValue = input.read(dataIn);
+ appendToLog("DeviceFinder.runnable: done inputStream.read with output value as " + iValue);
+ if (iValue > 0) {
+ byte[] dataIn1 = new byte[iValue];
+ System.arraycopy(dataIn, 0, dataIn1, 0, dataIn1.length);
+ appendToLog("DeviceFinder.runnable: with data as " + utility.byteArrayToString(dataIn1));
+ }
+ } //1515 TcpReaderCommandClearError
+ if (false) {
+ data = getBytesTcpReader(TcpReaderCommands.WriteOemAddress);
+ output.write(data);
+ appendToLog("DeviceFinder.runnable: done outputStream.write with data as " + utility.byteArrayToString(data));
+ data = getBytesTcpReader(TcpReaderCommands.WriteCommandOemRead);
+ output.write(data);
+ appendToLog("DeviceFinder.runnable: done outputStream.write with data as " + utility.byteArrayToString(data));
+
+ input = tcpSocket.getInputStream();
+ appendToLog("DeviceFinder.runnable: done socket.getInputStream");
+
+ dataIn = new byte[64];
+ iValue = input.read(dataIn);
+ appendToLog("DeviceFinder.runnable: done inputStream.read with output value as " + iValue);
+ if (iValue > 0) {
+ byte[] dataIn1 = new byte[iValue];
+ System.arraycopy(dataIn, 0, dataIn1, 0, dataIn1.length);
+ appendToLog("DeviceFinder.runnable: with data as " + utility.byteArrayToString(dataIn1));
+ }
+ } //1515 TcpReaderCommandWriteOemAddress, WriteCommandOemRead
+ if (false) {
+ data = getBytesTcpReader(TcpReaderCommands.ReadMac705);
+ output.write(data);
+ appendToLog("DeviceFinder.runnable: done outputStream.write with data as " + utility.byteArrayToString(data));
+
+ input = tcpSocket.getInputStream();
+ appendToLog("DeviceFinder.runnable: done socket.getInputStream");
+
+ dataIn = new byte[64];
+ iValue = input.read(dataIn);
+ appendToLog("DeviceFinder.runnable: done inputStream.read with output value as " + iValue);
+ if (iValue > 0) {
+ byte[] dataIn1 = new byte[iValue];
+ System.arraycopy(dataIn, 0, dataIn1, 0, dataIn1.length);
+ appendToLog("DeviceFinder.runnable: with data as " + utility.byteArrayToString(dataIn1));
+ }
+ } //1515 TcpReaderCommandReadMac705
+ } catch (Exception ex) {
+ appendToLog("DeviceFinder.runnable tcp exception as " + ex.toString());
+ }
+ if (tcpSocket != null && !tcpSocket.isClosed()) {
+ try {
+ tcpSocket.close();
+ appendToLog("DeviceFinder.runnable: done tcpSocket.close");
+ } catch (Exception ex) {
+ appendToLog("DeviceFinder.runnable tcp exception as " + ex.toString());
+ }
+ }
+
+ if (false) {
+ try {
+ tcpSocket = new Socket(stringIp, 1516); //failed to connect with port 1516
+ appendToLog("DeviceFinder.runnable: done new Socket with Ip " + stringIp + " and port 1515");
+ OutputStream output = tcpSocket.getOutputStream();
+ appendToLog("DeviceFinder.runnable: done socket.getOutputStream");
+
+ if (true) {
+ data = getBytesTcpControl();
+ output.write(data);
+ appendToLog("DeviceFinder.runnable: done outputStream.write with data as " + utility.byteArrayToString(data));
+
+ input = tcpSocket.getInputStream();
+ appendToLog("DeviceFinder.runnable: done socket.getInputStream");
+
+ dataIn = new byte[64];
+ iValue = input.read(dataIn);
+ appendToLog("DeviceFinder.runnable: done inputStream.read with output value as " + iValue);
+ if (iValue > 0) {
+ byte[] dataIn1 = new byte[iValue];
+ System.arraycopy(dataIn, 0, dataIn1, 0, dataIn1.length);
+ appendToLog("DeviceFinder.runnable: with data as " + utility.byteArrayToString(dataIn1));
+ }
+ } //1516 TcpControlCommand -- failed to connect with port 1516
+ } catch (Exception ex) {
+ appendToLog("DeviceFinder.runnable tcp exception as " + ex.toString());
+ }
+ if (tcpSocket != null && !tcpSocket.isClosed()) {
+ try {
+ tcpSocket.close();
+ appendToLog("DeviceFinder.runnable: done tcpSocket.close");
+ } catch (Exception ex) {
+ appendToLog("DeviceFinder.runnable tcp exception as " + ex.toString());
+ }
+ }
+ } //1516 TcpCommand -- failed to connect with port 1516
+ }
+ }
+ };
+
+ static class ReaderSetting {
+ byte[] rxbuffer1 = null;
+ byte mode; //for search only
+ byte connection_mode; //for search only
+ byte dhcp_retry; //for search only
+ //byte[] device_name1, device_name2, device_name3; //for Search only
+ byte[] ip = new byte[4]; //
+ byte[] trusted_host_ip = new byte[4]; //
+ byte tcp_timeout;
+ byte ip_mode; //
+ byte[] mac = new byte[6]; //
+ byte trusted_host_mode; //
+ //byte[] device_name = new byte[32]; //
+ String[] device_name = new String[4];
+ byte[] subnet = new byte[4]; //
+ byte[] gateway = new byte[4]; //
+ byte gateway_check; //
+ }
+ byte[] getBytesUdpSearch() {
+ Random randomNumber = new Random();
+ byte[] sbuffer = new byte[4];
+ randomNumber.nextBytes(sbuffer);
+ sbuffer[0] = 0;
+ sbuffer[1] = 0;
+ return sbuffer;
+ }
+ ReaderSetting decodeSearchReply(byte[] sbuffer, byte[] rxbuffer) {
+ boolean DEBUG = false;
+ ReaderSetting readerSetting = null;
+ boolean bValue = false;
+ int iLengthMin = 45;
+ int iNull = 0, index = 40, i = index;
+ if (rxbuffer != null && rxbuffer.length >= iLengthMin) {
+ if (rxbuffer[0] == 1 && rxbuffer[1] == 0 && rxbuffer[2] == sbuffer[2] && rxbuffer[3] == sbuffer[3]) {
+ for (; i < rxbuffer.length; i++) {
+ if (rxbuffer[i] == 0) {
+ if (DEBUG) appendToLog("DeviceFinder.decodeSearchReply: i = " + i);
+ if (++iNull == 4) break;
+ }
+ }
+ if (iNull == 4 && rxbuffer.length > i) bValue = true;
+ }
+ }
+ if (bValue) {
+ byte[] rxbuffer1 = new byte[i + 2];
+ System.arraycopy(rxbuffer, 0, rxbuffer1, 0, rxbuffer1.length);
+
+ readerSetting = new ReaderSetting();
+
+ readerSetting.rxbuffer1 = rxbuffer1;
+ appendToLog("DeviceFinder.decodeSearchReply: " + rxbuffer1.length + " data received " + utility.byteArrayToString(rxbuffer1));
+
+ readerSetting.mode = rxbuffer1[1];
+
+ System.arraycopy(rxbuffer1, 14, readerSetting.mac, 0, readerSetting.mac.length);
+ if (DEBUG) appendToLog("DeviceFinder.decodeSearchReply: mac address is " + utility.byteArrayToString(readerSetting.mac));
+
+ System.arraycopy(rxbuffer1, 20, readerSetting.ip, 0, readerSetting.ip.length);
+ if (DEBUG) appendToLog("DeviceFinder.decodeSearchReply: ip address is " + utility.byteArrayToString(readerSetting.ip));
+
+ System.arraycopy(rxbuffer1, 4, readerSetting.trusted_host_ip, 0, readerSetting.trusted_host_ip.length);
+ readerSetting.trusted_host_mode = rxbuffer1[28];
+ readerSetting.connection_mode = rxbuffer1[29];
+ readerSetting.dhcp_retry = rxbuffer1[30];
+ readerSetting.ip_mode = rxbuffer1[31];
+ System.arraycopy(rxbuffer1, 32, readerSetting.subnet, 0, readerSetting.ip.length);
+ System.arraycopy(rxbuffer1, 36, readerSetting.gateway, 0, readerSetting.ip.length);
+
+ i = index;
+ int indexString = 0;
+ for (; i < rxbuffer1.length; i++) {
+ if (rxbuffer1[i] == 0) {
+ if (i > index) {
+ byte[] bytesName = new byte[i - index];
+ System.arraycopy(rxbuffer1, index, bytesName, 0, bytesName.length);
+ if (DEBUG) appendToLog("DeviceFinder.decodeSearchReply: name is " + utility.byteArrayToString(bytesName) + " " + new String(bytesName, StandardCharsets.UTF_8));
+ readerSetting.device_name[indexString++] = new String(bytesName, StandardCharsets.UTF_8);
+ }
+ if (++iNull == 4) break;
+ index = i + 1;
+ }
+ }
+ readerSetting.gateway_check = rxbuffer1[rxbuffer1.length-1];
+ }
+ return readerSetting;
+ }
+ byte[] getBytesUdpAssignment(ReaderSetting readerSetting) {
+ Random randomNumber = new Random();
+ byte[] sbuffer = new byte[65];
+ sbuffer[0] = 2; sbuffer[1] = 0;
+
+ byte[] sbuffer1 = new byte[2];
+ randomNumber.nextBytes(sbuffer1);
+ System.arraycopy(sbuffer1, 0, sbuffer, 2, sbuffer1.length);
+ System.arraycopy(readerSetting.ip, 0, sbuffer, 4, readerSetting.ip.length);
+ System.arraycopy(readerSetting.trusted_host_ip, 0, sbuffer, 8, readerSetting.trusted_host_ip.length);
+ sbuffer[14] = readerSetting.tcp_timeout;
+ sbuffer[15] = readerSetting.ip_mode;
+ System.arraycopy(readerSetting.mac, 0, sbuffer, 16, readerSetting.mac.length);
+ sbuffer[22] = readerSetting.trusted_host_mode;
+ byte[] deviceName = readerSetting.device_name[0].getBytes();
+ int length = deviceName.length;
+ if (length > 32) length = 32;
+ System.arraycopy(deviceName, 0, sbuffer, 24, length);
+ System.arraycopy(readerSetting.subnet, 0, sbuffer, 56, readerSetting.subnet.length);
+ System.arraycopy(readerSetting.gateway, 0, sbuffer, 60, readerSetting.gateway.length);
+ sbuffer[64] = readerSetting.gateway_check;
+ return sbuffer;
+ }
+ boolean decodeAssignmentReply(byte[] sbuffer, byte[] rxbuffer) {
+ boolean bValue = false;;
+ if (rxbuffer != null && rxbuffer.length >= 4) {
+ if (rxbuffer[0] == 3 && rxbuffer[1] == 0 && rxbuffer[2] == sbuffer[2] && rxbuffer[3] == sbuffer[3]) {
+ bValue = true;
+ }
+ }
+ return bValue;
+ }
+ byte[] getBytesUdpControl(byte[] ip, UpdControlCommands updControlCommands) {
+ byte[] bytes = new byte[7];
+ int length = ip.length;
+ appendToLog("DeviceFinder length is " + length);
+ if (length == 4) {
+ bytes[0] = (byte) 0x80;
+ System.arraycopy(ip, 0, bytes, 1, length);
+ bytes[5] = 0;
+ if (updControlCommands == UpdControlCommands.CheckStatus) bytes[6] = 1;
+ else if (updControlCommands == UpdControlCommands.GetBootloaderVersion) bytes[6] = 0x15;
+ else if (updControlCommands == UpdControlCommands.GetImageVersion) bytes[6] = 0x16;
+ } else bytes = null;
+ return bytes;
+ }
+ public enum UpdControlCommands { CheckStatus, GetBootloaderVersion, GetImageVersion }
+ boolean decodeUdpControlReply(byte[] sBuffer, byte[] rxbufferRaw) {
+ boolean bValue = false;
+ byte[] rxbuffer = new byte[4 + rxbufferRaw[2]];
+ System.arraycopy(rxbufferRaw, 0, rxbuffer, 0, rxbuffer.length);
+ appendToLog("DeviceFinder.decodeUdpControlReply: data received as " + utility.byteArrayToString(rxbuffer));
+ if (rxbuffer[0] == (byte) 0x81 && rxbuffer[3] == sBuffer[6]) {
+ if (rxbuffer[1] == 1) bValue = true;
+ }
+ return bValue;
+ }
+ enum TcpReaderCommands { Reset, WriteCommandClearError, WriteOemAddress, WriteCommandOemRead, ReadMac705 }
+ byte[] getBytesTcpReader(TcpReaderCommands tcpReaderCommands) {
+ byte[] bytes = null;
+ if (tcpReaderCommands == TcpReaderCommands.Reset) bytes = new byte[] { 0x40, 0x03, 0, 0, 0, 0, 0, 0 };
+ else if (tcpReaderCommands == TcpReaderCommands.WriteCommandClearError) bytes = new byte[] { 1, 0, 0, (byte) 0xf0, 0x15, 0, 0, 0 };
+ else if (tcpReaderCommands == TcpReaderCommands.WriteOemAddress) bytes = new byte[] { 1, 0, 0, 5, (byte) 0xA4, 0, 0, 0 };
+ else if (tcpReaderCommands == TcpReaderCommands.WriteCommandOemRead) bytes = new byte[] { 1, 0, 0, (byte) 0xf0, 3, 0, 0, 0 };
+ else if (tcpReaderCommands == TcpReaderCommands.ReadMac705) bytes = new byte[] { 0, 0, 0x05, 0x07, 0, 0, 0, 0 };
+ return bytes;
+ }
+ byte[] getBytesTcpControl() {
+ return new byte[] { (byte) 0x80, 0, 0, 0x12 };
+ }
+
+ boolean deviceFinderConnectState = false;
+ boolean connect(ReaderDevice readerDevice) {
+ boolean DEBUG = true, bValue = true;
+ if (DEBUG) appendToLog("DeviceFinder.connect: readerDevice is " + (readerDevice == null ? "null" : "valid"));
+ if (readerDevice == null) {
+ bValue = false;
+ if (DEBUG) appendToLog("DeviceFinder.connect with NULL readerDevice");
+ } else deviceFinderConnectState = true;
+ return bValue;
+ }
+ //============ utility ============
+ public void appendToLog(String s) {
+ utility.appendToLog(s);
+ }
+}
+
+
+
+package com.csl.cslibrary4a;
+
+import android.content.Context;
+import android.widget.Toast;
+
+import java.util.ArrayList;
+
+public class NotificationConnector {
+ boolean DEBUG_PKDATA;
+ boolean userDebugEnableDefault = false, userDebugEnable = userDebugEnableDefault;
+ public int mVoltageValue;
+ public int mVoltageCount;
+ public boolean triggerButtonStatus; public int iTriggerCount;
+ String stringVersion;
+ public enum NotificationPayloadEvents {
+ NOTIFICATION_GET_BATTERY_VOLTAGE, NOTIFICATION_GET_TRIGGER_STATUS,
+ NOTIFICATION_AUTO_BATTERY_VOLTAGE, NOTIFICATION_STOPAUTO_BATTERY_VOLTAGE,
+ NOTIFICATION_AUTO_RFIDINV_ABORT, NOTIFICATION_GET_AUTO_RFIDINV_ABORT,
+ NOTIFICATION_AUTO_BARINV_STARTSTOP, NOTIFICATION_GET_AUTO_BARINV_STARTSTOP,
+ NOTIFICATION_AUTO_TRIGGER_REPORT, NOTIFICATION_STOP_TRIGGER_REPORT,
+
+ NOTIFICATION_BATTERY_FAILED, NOTIFICATION_BATTERY_ERROR,
+ NOTIFICATION_TRIGGER_PUSHED, NOTIFICATION_TRIGGER_RELEASED
+ }
+ public class CsReaderNotificationData {
+ public NotificationPayloadEvents notificationPayloadEvent;
+ public byte[] dataValues;
+ }
+
+ public interface NotificationListener { void onChange(); }
+
+ NotificationListener listener;
+ public void setNotificationListener0(NotificationListener listener) { this.listener = listener; }
+
+ //NotificationListener getListener() { return listener; }
+ boolean mTriggerStatus;
+ public boolean getTriggerStatus() { return mTriggerStatus; }
+ void setTriggerStatus(boolean mTriggerStatus) {
+ if (this.mTriggerStatus != mTriggerStatus) {
+ this.mTriggerStatus = mTriggerStatus;
+ if (listener != null) listener.onChange();
+ }
+ }
+
+ boolean autoRfidAbortStatus = true, autoRfidAbortStatusUpdate = false;
+ boolean getAutoRfidAbortStatus() {
+ if (!autoRfidAbortStatusUpdate) {
+ CsReaderNotificationData csReaderNotificationData = new CsReaderNotificationData();
+ csReaderNotificationData.notificationPayloadEvent = NotificationPayloadEvents.NOTIFICATION_GET_AUTO_RFIDINV_ABORT;
+ notificationToWrite.add(csReaderNotificationData); if (true) appendToLog("notificationToWrite is added with length = " + notificationToWrite.size());
+ if (DEBUG_PKDATA) appendToLog("PkData: add NOTIFICATION_GET_AUTO_RFIDINV_ABORT to mNotificationToWrite with length = " + notificationToWrite.size());
+ }
+ return autoRfidAbortStatus;
+ }
+ void setAutoRfidAbortStatus(boolean mAutoRfidAbortStatus) { this.autoRfidAbortStatus = mAutoRfidAbortStatus; autoRfidAbortStatusUpdate = true; }
+
+ boolean mAutoBarStartStopStatus = false, mAutoBarStartStopStatusUpdated = false;
+ public boolean getAutoBarStartStopStatus() {
+ if (mAutoBarStartStopStatusUpdated == false) {
+ CsReaderNotificationData csReaderNotificationData = new CsReaderNotificationData();
+ csReaderNotificationData.notificationPayloadEvent = NotificationPayloadEvents.NOTIFICATION_GET_AUTO_BARINV_STARTSTOP;
+ notificationToWrite.add(csReaderNotificationData); if (true) appendToLog("notificationToWrite is added with length = " + notificationToWrite.size());
+ if (DEBUG_PKDATA) appendToLog("PkData: add NOTIFICATION_GET_AUTO_BARINV_STARTSTOP to mNotificationToWrite with length = " + notificationToWrite.size());
+ }
+ return mAutoBarStartStopStatus;
+ }
+ void setAutoBarStartStopStatus(boolean mAutoBarStartStopStatus) { this.mAutoBarStartStopStatus = mAutoBarStartStopStatus; mAutoBarStartStopStatusUpdated = true; }
+
+ public ArrayList notificationToWrite = new ArrayList<>();
+ public ArrayList notificationToRead = new ArrayList<>();
+
+ private boolean arrayTypeSet(byte[] dataBuf, int pos, NotificationPayloadEvents event) {
+ boolean validEvent = false;
+ switch (event) {
+ case NOTIFICATION_GET_BATTERY_VOLTAGE:
+ validEvent = true;
+ break;
+ case NOTIFICATION_GET_TRIGGER_STATUS:
+ dataBuf[pos] = 1;
+ validEvent = true;
+ break;
+ case NOTIFICATION_AUTO_BATTERY_VOLTAGE:
+ //if (false && checkHostProcessorVersion(controllerConnector.getVersion(), 0, 0, 2) == false) {
+ // validEvent = false;
+ //} else {
+ dataBuf[pos] = 2;
+ validEvent = true;
+ //}
+ break;
+ case NOTIFICATION_STOPAUTO_BATTERY_VOLTAGE:
+ //if (false && checkHostProcessorVersion(controllerConnector.getVersion(), 0, 0, 1) == false) {
+ // validEvent = false;
+ //} else {
+ dataBuf[pos] = 3;
+ validEvent = true;
+ //}
+ break;
+ case NOTIFICATION_AUTO_RFIDINV_ABORT:
+ //if (false && checkHostProcessorVersion(bluetoothConnector.getBluetoothIcVersion(), 0, 0, 13) == false) {
+ // validEvent = false;
+ //} else {
+ dataBuf[pos] = 4;
+ validEvent = true;
+ //}
+ break;
+ case NOTIFICATION_GET_AUTO_RFIDINV_ABORT:
+ //if (false && checkHostProcessorVersion(bluetoothConnector.getBluetoothIcVersion(), 1, 0, 13) == false) {
+ // validEvent = false;
+ //} else {
+ dataBuf[pos] = 5;
+ validEvent = true;
+ //}
+ break;
+ case NOTIFICATION_AUTO_BARINV_STARTSTOP:
+ //if (false && checkHostProcessorVersion(bluetoothConnector.getBluetoothIcVersion(), 1, 0, 14) == false) {
+ // validEvent = false;
+ //} else {
+ dataBuf[pos] = 6;
+ validEvent = true;
+ //}
+ break;
+ case NOTIFICATION_GET_AUTO_BARINV_STARTSTOP:
+ //if (false && checkHostProcessorVersion(bluetoothConnector.getBluetoothIcVersion(), 1, 0, 14) == false) {
+ // validEvent = false;
+ //} else {
+ dataBuf[pos] = 7;
+ validEvent = true;
+ //}
+ break;
+ case NOTIFICATION_AUTO_TRIGGER_REPORT:
+ //if (false && checkHostProcessorVersion(controllerConnector.getVersion(), 1, 0, 16) == false) {
+ // validEvent = false;
+ //} else {
+ dataBuf[pos] = 8;
+ validEvent = true;
+ //}
+ break;
+ case NOTIFICATION_STOP_TRIGGER_REPORT:
+ //if (false && checkHostProcessorVersion(controllerConnector.getVersion(), 1, 0, 16) == false) {
+ // validEvent = false;
+ //} else {
+ dataBuf[pos] = 9;
+ validEvent = true;
+ //}
+ break;
+ }
+ return validEvent;
+ }
+
+ private byte[] writeNotification(CsReaderNotificationData data, boolean usbConnection) {
+ int datalength = 0; boolean DEBUG = true;
+ if (data.dataValues != null) datalength = data.dataValues.length;
+ byte[] dataOutRef = new byte[]{(byte) 0xA7, (byte) 0xB3, 2, (byte) 0xD9, (byte) 0x82, (byte) 0x37, 0, 0, (byte) 0xA0, 0};
+ if (usbConnection) dataOutRef[1] = (byte) 0xE6;
+ byte[] dataOut = new byte[10 + datalength];
+ if (DEBUG) appendToLog("event = " + data.notificationPayloadEvent.toString() + ", with datalength = " + datalength);
+ if (datalength != 0) {
+ System.arraycopy(data.dataValues, 0, dataOut, 10, datalength);
+ dataOutRef[2] += datalength;
+ }
+ System.arraycopy(dataOutRef, 0, dataOut, 0, dataOutRef.length);
+ if (arrayTypeSet(dataOut, 9, data.notificationPayloadEvent)) {
+ if (DEBUG_PKDATA) appendToLog(String.format("PkData: write mNotificationDevice.%s.%s with mNotificationDevice.sendDataToWriteSent = %d", data.notificationPayloadEvent.toString(), byteArrayToString(data.dataValues), sendDataToWriteSent));
+ if (DEBUG) appendToLogView("NOut: " + byteArrayToString(dataOut));
+ return dataOut;
+ }
+ return null;
+ }
+ public boolean isMatchNotificationToWrite(ConnectorData connectorData) {
+ boolean match = false;
+ if (notificationToWrite.size() != 0 && connectorData.dataValues[0] == (byte)0xA0) {
+ byte[] dataInCompare = new byte[]{(byte) 0xA0, 0};
+ if (arrayTypeSet(dataInCompare, 1, notificationToWrite.get(0).notificationPayloadEvent) && (connectorData.dataValues.length >= dataInCompare.length + 1)) {
+ if (match = compareArray(connectorData.dataValues, dataInCompare, dataInCompare.length)) {
+ boolean bprocessed = false;
+ byte[] data1 = new byte[connectorData.dataValues.length - 2]; System.arraycopy(connectorData.dataValues, 2, data1, 0, data1.length);
+ if (DEBUG_PKDATA) appendToLog("PkData: matched Notification.Reply with payload = " + byteArrayToString(connectorData.dataValues) + " for writeData Notification." + notificationToWrite.get(0).notificationPayloadEvent.toString());
+ if (notificationToWrite.get(0).notificationPayloadEvent == NotificationPayloadEvents.NOTIFICATION_GET_BATTERY_VOLTAGE) {
+ if (connectorData.dataValues.length >= dataInCompare.length + 2) {
+ mVoltageValue = (connectorData.dataValues[2] & 0xFF) * 256 + (connectorData.dataValues[3] & 0xFF);
+ mVoltageCount++;
+ bprocessed = true;
+ }
+ if (DEBUG_PKDATA) appendToLog("PkData: matched Notification.Reply.GetBatteryVoltage with result = " + String.format("%X", mVoltageValue));
+ } else if (notificationToWrite.get(0).notificationPayloadEvent == NotificationPayloadEvents.NOTIFICATION_GET_TRIGGER_STATUS) {
+ if (connectorData.dataValues[2] != 0) {
+ setTriggerStatus(true); //mTriggerStatus = true;
+ triggerButtonStatus = true;
+ } else {
+ setTriggerStatus(false); //mTriggerStatus = false;
+ triggerButtonStatus = false;
+ }
+ iTriggerCount++;
+ if (DEBUG_PKDATA) appendToLog("PkData: BARTRIGGER: isMatchNotificationToWrite finds trigger = " + getTriggerStatus());
+ bprocessed = true;
+ } else if (notificationToWrite.get(0).notificationPayloadEvent == NotificationPayloadEvents.NOTIFICATION_GET_AUTO_RFIDINV_ABORT) {
+ if (connectorData.dataValues[2] != 0) setAutoRfidAbortStatus(true);
+ else setAutoRfidAbortStatus(false);
+ if (DEBUG_PKDATA) appendToLog("PkData: matched Notification.Reply.GetAutoRfidinvAbort with result = " + connectorData.dataValues[2] + " and autoRfidAbortStatus = " + getAutoRfidAbortStatus());
+ bprocessed = true;
+ } else if (notificationToWrite.get(0).notificationPayloadEvent == NotificationPayloadEvents.NOTIFICATION_GET_AUTO_BARINV_STARTSTOP) {
+ if (connectorData.dataValues[2] != 0) setAutoBarStartStopStatus(true);
+ else setAutoBarStartStopStatus(false);
+ if (DEBUG_PKDATA) appendToLog("PkData: matched Notification.Reply.GetAutoBarinvStartstop with result = " + connectorData.dataValues[2] + " and " + getAutoBarStartStopStatus());
+ bprocessed = true;
+ } else {
+ bprocessed = true;
+ if (DEBUG_PKDATA) appendToLog("PkData: matched Notification.Reply." + notificationToWrite.get(0).notificationPayloadEvent.toString() + " with result = " + connectorData.dataValues[2]);
+ }
+ String string = "Up31 " + (bprocessed ? "" : "Unprocessed, ") + notificationToWrite.get(0).notificationPayloadEvent.toString() + ", " + byteArrayToString(data1);
+ utility.writeDebug2File(string);
+ appendToLog("Notification.isMatchNotificationToWrite: UsbConnector: going to notificationToWrite.remove[0] 1");
+ notificationToWrite.remove(0); sendDataToWriteSent = 0; if (false) appendToLog("notificationToWrite remove0 with length = " + notificationToWrite.size());
+ if (DEBUG_PKDATA) appendToLog("PkData: new mNotificationToWrite size = " + notificationToWrite.size());
+ }
+ }
+ }
+ return match;
+ }
+
+ public int sendDataToWriteSent = 0;
+ boolean notificationFailure = false;
+ public byte[] sendNotificationToWrite(boolean usbConnection) {
+ boolean DEBUG = false;
+ appendToLog("NotificationConnector.sendNotificationToWrite: starts");
+ if (notificationFailure) {
+ appendToLog("Notification.sendNotificationToWrite: UsbConnector: going to notificationToWrite.remove[0] 1");
+ notificationToWrite.remove(0); sendDataToWriteSent = 0; if (false) appendToLog("notificationToWrite remove0 with length = " + notificationToWrite.size());
+ } else if (sendDataToWriteSent >= 5) {
+ int oldSize = notificationToWrite.size();
+ CsReaderNotificationData csReaderNotificationData = notificationToWrite.get(0);
+ appendToLog("Notification.sendNotificationToWrite: UsbConnector: going to notificationToWrite.remove[0] 2");
+ notificationToWrite.remove(0); sendDataToWriteSent = 0; if (true) appendToLog("notificationToWrite remove0 with length = " + notificationToWrite.size());
+ if (DEBUG) appendToLog("Removed after sending count-out with oldSize = " + oldSize + ", updated mNotificationToWrite.size() = " + notificationToWrite.size());
+ if (DEBUG) appendToLog("Removed after sending count-out.");
+ String string = "Problem in sending data to Notification Module. Removed data sending after count-out";
+ if (userDebugEnable) Toast.makeText(context, string, Toast.LENGTH_SHORT).show();
+ else appendToLogView(string);
+ if (true) Toast.makeText(context, csReaderNotificationData.notificationPayloadEvent.toString(), Toast.LENGTH_LONG).show();
+ notificationFailure = true; // disconnect(false);
+ } else {
+ sendDataToWriteSent++;
+ return writeNotification(notificationToWrite.get(0), usbConnection);
+ }
+ return null;
+ }
+
+ long timeTriggerRelease;
+ public boolean isNotificationToRead(ConnectorData connectorData) {
+ boolean found = false, DEBUG = false;
+ CsReaderNotificationData csReaderNotificationData = new CsReaderNotificationData();
+ byte[] data1 = new byte[connectorData.dataValues.length - 2]; System.arraycopy(connectorData.dataValues, 2, data1, 0, data1.length);
+ if (connectorData.dataValues[0] == (byte) 0xA0 && connectorData.dataValues[1] == (byte) 0x00 && connectorData.dataValues.length >= 4) {
+ mVoltageValue = (connectorData.dataValues[2] & 0xFF) * 256 + (connectorData.dataValues[3] & 0xFF);
+ mVoltageCount++;
+ csReaderNotificationData.notificationPayloadEvent = NotificationPayloadEvents.NOTIFICATION_GET_BATTERY_VOLTAGE;
+ csReaderNotificationData.dataValues = data1;
+ if (false) notificationToRead.add(csReaderNotificationData);
+ if (DEBUG_PKDATA) appendToLog("PkData: found Notification.Uplink with payload = " + byteArrayToString(connectorData.dataValues));
+ if (DEBUG_PKDATA) appendToLog("PkData: Notification.Uplink.GetCurrentBattteryVoltage is processed as mVoltageValue = " + mVoltageValue + " and mVoltageCount = " + mVoltageCount);
+ found = true;
+ } else if (connectorData.dataValues[0] == (byte) 0xA0 && connectorData.dataValues[1] == (byte) 0x01 && connectorData.dataValues.length >= 3) {
+ if (connectorData.dataValues[2] == 0) triggerButtonStatus = false;
+ else triggerButtonStatus = true;
+ iTriggerCount++;
+ csReaderNotificationData.notificationPayloadEvent = NotificationPayloadEvents.NOTIFICATION_GET_TRIGGER_STATUS;
+ csReaderNotificationData.dataValues = data1;
+ if (DEBUG_PKDATA) appendToLog("PkData: found Notification.Uplink with payload = " + byteArrayToString(connectorData.dataValues));
+ if (DEBUG_PKDATA) appendToLog("PkData: Notification.Uplink.GetCurrentTriggerState is processed as triggerButtonStatus = " + triggerButtonStatus + " and iTriggerCount = " + iTriggerCount);
+ found = true;
+ } else if (connectorData.dataValues[0] == (byte) 0xA1) {
+ if (DEBUG_PKDATA) appendToLog("PkData: found Notification.Uplink with payload = " + byteArrayToString(connectorData.dataValues));
+ //Cs108NotificatiionData cs108NotificatiionData = new Cs108NotificatiionData();
+ switch (connectorData.dataValues[1]) {
+ case 0:
+ if (DEBUG) appendToLog("matched batteryFailed data is found.");
+ csReaderNotificationData.notificationPayloadEvent = NotificationPayloadEvents.NOTIFICATION_BATTERY_FAILED;
+ csReaderNotificationData.dataValues = null;
+ if (true) notificationToRead.add(csReaderNotificationData);
+ if (DEBUG_PKDATA) appendToLog("PkData: Notification.Uplink.Reserve is processed");
+ found = true;
+ break;
+ case 1:
+ if (DEBUG) appendToLog("matched Error data is found, " + byteArrayToString(connectorData.dataValues));
+ csReaderNotificationData.notificationPayloadEvent = NotificationPayloadEvents.NOTIFICATION_BATTERY_ERROR;
+ csReaderNotificationData.dataValues = data1;
+ if (true) notificationToRead.add(csReaderNotificationData);
+ //btSendTime = System.currentTimeMillis() - btSendTimeOut + 50;
+ if (DEBUG_PKDATA) appendToLog("PkData: Notification.Uplink.ErrorCode with value = " + byteArrayToString(data1) + " is addded to mNotificationToRead");
+ found = true;
+ break;
+ case 2:
+ csReaderNotificationData.notificationPayloadEvent = NotificationPayloadEvents.NOTIFICATION_TRIGGER_PUSHED;
+ csReaderNotificationData.dataValues = data1;
+ setTriggerStatus(true);
+ if (DEBUG) appendToLog("BARTRIGGER: isNotificationToRead finds trigger = " + getTriggerStatus());
+ if (false) notificationToRead.add(csReaderNotificationData);
+ if (DEBUG_PKDATA) appendToLog("PkData: Notification.Uplink.TriggerPushed is processed as trigger = " + getTriggerStatus());
+ found = true;
+ break;
+ case 3:
+ csReaderNotificationData.notificationPayloadEvent = NotificationPayloadEvents.NOTIFICATION_TRIGGER_RELEASED;
+ csReaderNotificationData.dataValues = data1;
+ setTriggerStatus(false);
+ if (DEBUG) appendToLog("BARTRIGGER: isNotificationToRead finds trigger = " + getTriggerStatus());
+ if (false) notificationToRead.add(csReaderNotificationData);
+ if (DEBUG_PKDATA) appendToLog("PkData: Notification.Uplink.TriggerReleased is processed as trigger = " + getTriggerStatus());
+ found = true;
+ break;
+ default:
+ appendToLog("Notification.Uplink with mis-matched result");
+ break;
+ }
+ }
+ if (DEBUG_PKDATA && found) appendToLog("found Notification.read data = " + byteArrayToString(connectorData.dataValues));
+ if (found) utility.writeDebug2File("Up32 " + csReaderNotificationData.notificationPayloadEvent.toString() + ", " + byteArrayToString(csReaderNotificationData.dataValues));
+ return found;
+ }
+ Context context; Utility utility; boolean triggerReporting; short triggerReportingCountSetting;
+ public NotificationConnector(Context context, Utility utility, boolean triggerReporting, short triggerReportingCountSetting) {
+ this.context = context;
+ this.utility = utility; DEBUG_PKDATA = utility.DEBUG_PKDATA;
+ this.triggerReporting = triggerReporting;
+ this.triggerReportingCountSetting = triggerReportingCountSetting;
+ }
+ private void appendToLog(String s) { utility.appendToLog(s); }
+ private String byteArrayToString(byte[] packet) { return utility.byteArrayToString(packet); }
+ private boolean compareArray(byte[] array1, byte[] array2, int length) { return utility.compareByteArray(array1, array2, length); }
+ private void appendToLogView(String s) { utility.appendToLogView(s); }
+ public boolean batteryLevelRequest() {
+ CsReaderNotificationData csReaderNotificationData = new CsReaderNotificationData();
+ csReaderNotificationData.notificationPayloadEvent = NotificationPayloadEvents.NOTIFICATION_GET_BATTERY_VOLTAGE;
+ boolean bValue = notificationToWrite.add(csReaderNotificationData); if (true) appendToLog("notificationToWrite is added with length = " + notificationToWrite.size());
+ if (DEBUG_PKDATA) appendToLog("PkData: add NOTIFICATION_GET_BATTERY_VOLTAGE to mNotificationToWrite with length = " + notificationToWrite.size());
+ return bValue;
+ }
+ public boolean triggerButtoneStatusRequest() {
+ CsReaderNotificationData csReaderNotificationData = new CsReaderNotificationData();
+ csReaderNotificationData.notificationPayloadEvent = NotificationPayloadEvents.NOTIFICATION_GET_TRIGGER_STATUS;
+ boolean bValue = notificationToWrite.add(csReaderNotificationData); if (true) appendToLog("notificationToWrite is added with length = " + notificationToWrite.size());
+ if (DEBUG_PKDATA) appendToLog("PkData: add NOTIFICATION_GET_TRIGGER_STATUS to mNotificationToWrite with length = " + notificationToWrite.size());
+ return bValue;
+ }
+ public boolean setBatteryAutoReport(boolean on) {
+ CsReaderNotificationData csReaderNotificationData = new CsReaderNotificationData();
+ csReaderNotificationData.notificationPayloadEvent = (on ? NotificationPayloadEvents.NOTIFICATION_AUTO_BATTERY_VOLTAGE: NotificationPayloadEvents.NOTIFICATION_STOPAUTO_BATTERY_VOLTAGE);
+ boolean bValue = notificationToWrite.add(csReaderNotificationData); appendToLog("notificationToWrite is added with length = " + notificationToWrite.size());
+ if (DEBUG_PKDATA) appendToLog("PkData: add " + csReaderNotificationData.notificationPayloadEvent.toString() + " to mNotificationToWrite with length = " + notificationToWrite.size());
+ return bValue;
+ }
+ public boolean setAutoRFIDAbort(boolean enable) {
+ if (false) appendToLog("BtDataOut: setAutoRFIDAbort with enable = " + enable + ", current autoRFIDAbort is " + autoRfidAbortStatus);
+ if (autoRfidAbortStatusUpdate) {
+ if ((enable && autoRfidAbortStatus) || (!enable && !autoRfidAbortStatus))
+ return true;
+ }
+ CsReaderNotificationData csReaderNotificationData = new CsReaderNotificationData();
+ csReaderNotificationData.notificationPayloadEvent = NotificationPayloadEvents.NOTIFICATION_AUTO_RFIDINV_ABORT;
+ csReaderNotificationData.dataValues = new byte[1];
+ setAutoRfidAbortStatus(enable);
+ csReaderNotificationData.dataValues[0] = (enable ? (byte)1 : 0);
+ boolean bValue = notificationToWrite.add(csReaderNotificationData); appendToLog("notificationToWrite is added with length = " + notificationToWrite.size());
+ if (DEBUG_PKDATA) appendToLog("PkData: add NOTIFICATION_AUTO_RFIDINV_ABORT." + byteArrayToString(csReaderNotificationData.dataValues) + " to mNotificationToWrite with length = " + notificationToWrite.size());
+ return bValue;
+ }
+ public boolean getAutoRFIDAbort() {
+ return getAutoRfidAbortStatus(); }
+
+ public boolean setAutoBarStartSTop(boolean enable) {
+ boolean autoBarStartStopStatus = getAutoBarStartSTop();
+ if (enable & autoBarStartStopStatus) return true;
+ else if (enable == false && autoBarStartStopStatus == false) return true;
+
+ CsReaderNotificationData csReaderNotificationData = new CsReaderNotificationData();
+ csReaderNotificationData.notificationPayloadEvent = NotificationPayloadEvents.NOTIFICATION_AUTO_BARINV_STARTSTOP;
+ csReaderNotificationData.dataValues = new byte[1];
+ setAutoBarStartStopStatus(enable);
+ csReaderNotificationData.dataValues[0] = (enable ? (byte)1 : 0);
+ boolean bValue = notificationToWrite.add(csReaderNotificationData); appendToLog("notificationToWrite is added with length = " + notificationToWrite.size());
+ if (DEBUG_PKDATA) appendToLog("PkData: add NOTIFICATION_AUTO_BARINV_STARTSTOP." + byteArrayToString(csReaderNotificationData.dataValues) + " to mNotificationToWrite with length = " + notificationToWrite.size());
+ return bValue;
+ }
+ public boolean getAutoBarStartSTop() { return getAutoBarStartStopStatus(); }
+
+ public boolean getTriggerReporting() { return triggerReporting; }
+ public boolean setTriggerReporting(boolean triggerReporting) {
+ boolean bValue = false;
+ appendToLog("FileA setTriggerReporting starts with triggerReporting as " + triggerReporting);
+ //if (this.triggerReporting == triggerReporting) return true;
+ if (triggerReporting) {
+ appendToLog("FileA going to setAutoTriggerReporting 3 with triggerReportingCountSetting as " + triggerReportingCountSetting);
+ byte byteWord = (byte) triggerReportingCountSetting;
+ appendToLog("FileA going to setAutoTriggerReporting 4 with byteWord as " + byteWord);
+ bValue = setAutoTriggerReporting(byteWord);
+ } else {
+ appendToLog("FileA going to stopAutoTriggerReporting 3");
+ bValue = stopAutoTriggerReporting();
+ }
+ if (bValue) this.triggerReporting = triggerReporting;
+ appendToLog("FileA setTriggerReporting ends");
+ return bValue;
+ }
+
+ public final int iNO_SUCH_SETTING = 10000;
+ //public short triggerReportingCountSettingDefault = 1;
+ //public short triggerReportingCountSetting = triggerReportingCountSettingDefault;
+ public short getTriggerReportingCount() {
+ //if (getcsModel() == 108) bValue = checkHostProcessorVersion(hostProcessorICGetFirmwareVersion(), 1, 0, 16);
+ //if (bValue == false) return iNO_SUCH_SETTING; else
+ return triggerReportingCountSetting;
+ }
+ public boolean setTriggerReportingCount(short triggerReportingCount) {
+ boolean bValue = false;
+ if (triggerReportingCount < 0 || triggerReportingCount > 255) return false;
+ if (getTriggerReporting()) {
+ if (triggerReportingCountSetting == triggerReportingCount) return true;
+ bValue = setAutoTriggerReporting((byte)(triggerReportingCount & 0xFF));
+ } else bValue = true;
+ if (bValue) triggerReportingCountSetting = triggerReportingCount;
+ return true;
+ }
+ byte timeSecondAutoTriggerReporting = 0;
+ public boolean setAutoTriggerReporting(byte timeSecond) {
+ boolean DEBUG = false;
+ if (DEBUG) appendToLog("NotificationConnector.setAutoTriggerReporting with checkVersion = " + checkVersion() + ", timeSecond = " + timeSecond);
+ if (!checkVersion()) return false;
+ if (timeSecond == timeSecondAutoTriggerReporting) {
+ if (DEBUG) appendToLog("NotificationConnector.setAutoTriggerReporting matched timeSecond");
+ return true;
+ }
+ CsReaderNotificationData csReaderNotificationData = new CsReaderNotificationData();
+ csReaderNotificationData.notificationPayloadEvent = NotificationPayloadEvents.NOTIFICATION_AUTO_TRIGGER_REPORT;
+ csReaderNotificationData.dataValues = new byte[1];
+ csReaderNotificationData.dataValues[0] = timeSecond;
+ boolean bValue = notificationToWrite.add(csReaderNotificationData); if (true) appendToLog("notificationToWrite is added with length = " + notificationToWrite.size());
+ if (bValue) timeSecondAutoTriggerReporting = timeSecond;
+ if (DEBUG_PKDATA) appendToLog("PkData: add NOTIFICATION_AUTO_TRIGGER_REPORT." + byteArrayToString(csReaderNotificationData.dataValues) + " to mNotificationToWrite with length = " + notificationToWrite.size());
+ return bValue;
+ }
+ public boolean stopAutoTriggerReporting() {
+ boolean DEBUG = false;
+ if (DEBUG) appendToLog("NotificationConnector.stopAutoTriggerReporting ***");
+ if (!checkVersion()) return false;
+ if (timeSecondAutoTriggerReporting == 0) {
+ if (DEBUG) appendToLog("NotificationConnector.setAutoTriggerReporting matched timeSecond");
+ return true;
+ }
+ CsReaderNotificationData csReaderNotificationData = new CsReaderNotificationData();
+ csReaderNotificationData.notificationPayloadEvent = NotificationPayloadEvents.NOTIFICATION_STOP_TRIGGER_REPORT;
+ boolean bValue = notificationToWrite.add(csReaderNotificationData); if (true) appendToLog("notificationToWrite is added with length = " + notificationToWrite.size());
+ if (bValue) timeSecondAutoTriggerReporting = 0;
+ if (DEBUG_PKDATA) appendToLog("PkData: add NOTIFICATION_STOP_TRIGGER_REPORT to mNotificationToWrite with length = " + notificationToWrite.size());
+ return bValue;
+ }
+ public void setVersion(String stringVersion) {
+ this.stringVersion = stringVersion;
+ }
+ boolean checkVersion() {
+ boolean DEBUG = true, bValue = false;
+ String stringCompare = "1.0.";
+ if (stringVersion == null) return true;
+ appendToLog("FileA setVersion with stringVersion as " + stringVersion + ", stringCompare as " + stringCompare);
+ int index = stringVersion.indexOf(stringCompare);
+ if (DEBUG) appendToLog("index = " + index);
+ if (index >= 0) {
+ if (DEBUG) appendToLog("substring = " + stringVersion.substring(index + stringCompare.length()));
+ if (Integer.parseInt(stringVersion.substring(index + stringCompare.length())) >= 16) bValue = true;
+ } else return true;
+ return bValue;
+ }
+}
+
+
+
+package com.csl.cslibrary4a;
+
+public class ReaderDevice implements Comparable {
+ private String name;
+ private String address; private String upcSerial;
+ boolean selected;
+ private String details;
+ int extra1Bank, extra2Bank, extra1Offset, extra2Offset;
+ String strPc, strXpc, strCrc16, strMdid, strExtra1, strExtra2;
+ private int count;
+ private double rssi;
+ private int serviceUUID2p1;
+ private int phase, channel, port;
+ public final int INVALID_STATUS = -1;
+ private int status = INVALID_STATUS;
+ public static final int INVALID_BACKPORT = -1, INVALID_CODESENSOR = -1, INVALID_CODERSSI = -1, INVALID_BRAND = -1, INVALID_SENSORDATA = 0x1000; public final float INVALID_CODETEMPC = -300;
+ private int backport1 = INVALID_BACKPORT, backport2 = INVALID_BACKPORT;
+ private int codeSensor = INVALID_CODESENSOR, codeSensorMax = INVALID_CODESENSOR, codeRssi = INVALID_CODERSSI, sensorData = INVALID_SENSORDATA; private float codeTempC = INVALID_CODETEMPC; private String brand;
+ private boolean isConnected;
+ private String timeOfRead, timeZone;
+ private String location;
+ private String compass;
+
+ public ReaderDevice(String name, String address, boolean selected, String details,
+ String strPc, String strXpc, String strCrc16, String strMdid,
+ String strExtra1, int extra1Bank, int extra1Offset,
+ String strExtra2, int extra2Bank, int extra2Offset,
+ String strTimeOfRead, String strTimeZone, String strLocation, String strCompass,
+ int count, double rssi, int phase, int channel, int port, int status, int backPort1, int backPort2, int codeSensor, int codeRssi, float codeTempC, String brand, int sensorData) {
+ this.name = name;
+ this.address = address;
+ this.selected = selected;
+ this.details = details;
+ this.strPc = strPc;
+ this.strXpc = strXpc;
+ this.strCrc16 = strCrc16;
+ this.strMdid = strMdid;
+ this.strExtra1 = strExtra1;
+ this.extra1Bank = extra1Bank;
+ this.extra1Offset = extra1Offset;
+ this.strExtra2 = strExtra2;
+ this.extra2Bank = extra2Bank;
+ this.extra2Offset = extra2Offset;
+
+ timeOfRead = strTimeOfRead;
+ timeZone = strTimeZone;
+ location = strLocation;
+ compass = strCompass;
+
+ this.count = count;
+ this.rssi = rssi;
+
+ this.phase = phase;
+ this.channel = channel;
+ this.port = port;
+ this.status = status;
+ this.backport1 = backPort1;
+ this.backport2 = backPort2;
+ this.codeSensor = codeSensor;
+ this.codeRssi = codeRssi;
+ this.codeTempC = codeTempC;
+ this.brand = brand;
+ this.sensorData = sensorData;
+ }
+
+ public ReaderDevice(String name, String address, boolean selected, String details, int count, double rssi, int serviceUUID2p1) {
+ this.name = name;
+ this.address = address;
+ this.selected = selected;
+ this.details = details;
+ this.count = count;
+ this.rssi = rssi;
+ this.serviceUUID2p1 = serviceUUID2p1;
+ }
+
+ public ReaderDevice(String name, String address, boolean selected, String details, int count, double rssi) {
+ this.name = name;
+ this.address = address;
+ this.selected = selected;
+ this.details = details;
+ this.count = count;
+ this.rssi = rssi;
+ }
+
+ public String getName() {
+ String strName = name;
+ if (strName != null) {
+ strName = strName.replaceAll("\\r|\\n", "");
+ strName = strName.trim();
+ }
+ return strName;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getAddress() { return address; }
+
+ public void setAddress(String address) {
+ this.address = address;
+ }
+
+ public String getUpcSerial() { return upcSerial; }
+
+ public void setUpcSerial(String upcSerial) {
+ this.upcSerial = upcSerial;
+ }
+
+ public boolean getSelected() {
+ return selected;
+ }
+
+ public void setSelected(boolean selected) {
+ this.selected = selected;
+ }
+
+ public String getDetails() {
+ if (details == null) {
+ String strDetail = "PC=" + strPc + ", CRC16=" + strCrc16; // + ", Port=" + String.valueOf(port+1);
+ if (strXpc != null) strDetail += "\nXPC=" + strXpc;
+ if (strExtra1 != null) {
+ String strHeader = null;
+ switch (extra1Bank) {
+ case 0:
+ strHeader = "RES";
+ break;
+ case 1:
+ strHeader = "EPC";
+ break;
+ case 2:
+ strHeader = "TID";
+ break;
+ case 3:
+ strHeader = "USER";
+ break;
+ }
+ if (strHeader != null)
+ strDetail += "\n" + strHeader + "=" + strExtra1;
+ }
+ if (strExtra2 != null) {
+ String strHeader = null;
+ switch (extra2Bank) {
+ case 0:
+ strHeader = "RES";
+ break;
+ case 1:
+ strHeader = "EPC";
+ break;
+ case 2:
+ strHeader = "TID";
+ break;
+ case 3:
+ strHeader = "USER";
+ break;
+ }
+ if (strHeader != null)
+ strDetail += "\n" + strHeader + "=" + strExtra2;
+ }
+ details = strDetail;
+ }
+ return details;
+ }
+
+ public void setDetails(String details) {
+ this.details = details;
+ }
+
+ public String getPc() { return strPc; }
+
+ public String getXpc() {
+ return strXpc;
+ }
+ public void setXpc(String strXpc) {
+ this.strXpc = strXpc;
+ }
+
+ public String getRes() {
+ if (extra1Bank == 0) return strExtra1;
+ else if (extra2Bank == 0) return strExtra2;
+ else return null;
+ }
+ public String getRes2() {
+ if (extra2Bank == 0) return strExtra2;
+ else if (extra1Bank == 0) return strExtra1;
+ else return null;
+ }
+ public String getEpc() {
+ if (extra1Bank == 1) return strExtra1;
+ else if (extra2Bank == 1) return strExtra2;
+ else return null;
+ }
+ public String getTid() {
+ if (extra1Bank == 2) return strExtra1;
+ else if (extra2Bank == 2) return strExtra2;
+ else return null;
+ }
+ public String getUser() {
+ if (extra1Bank == 3) return strExtra1;
+ else if (extra2Bank == 3) return strExtra2;
+ else return null;
+ }
+ public String getMdid() {
+ return strMdid;
+ }
+
+ public int getCount() {
+ return count;
+ }
+ public void setCount(int count) {
+ this.count = count;
+ }
+
+ public double getRssi() {
+ return rssi;
+ }
+ public void setRssi(double rssi) {
+ this.rssi = rssi;
+ }
+
+ public int getServiceUUID2p1() { return serviceUUID2p1; }
+ public void setServiceUUID2p1(int serviceUUID2p1) { this.serviceUUID2p1 = serviceUUID2p1; }
+
+ public int getPhase() { return phase; }
+ public void setPhase(int phase) { this.phase = phase; }
+
+ public int getChannel() {
+ return channel;
+ }
+ public void setChannel(int channel) {
+ this.channel = channel;
+ }
+
+ public int getPort() {
+ return port;
+ }
+ public void setPort(int port) {
+ this.port = port;
+ }
+
+ public int getStatus() { return status; }
+ public void setStatus(int status) {
+ this.status = status;
+ }
+
+ public int getBackport1() {
+ return backport1;
+ }
+ public void setBackport1(int backport1) {
+ this.backport1 = backport1;
+ }
+ public int getBackport2() {
+ return backport2;
+ }
+ public void setBackport2(int backport2) {
+ this.backport2 = backport2;
+ }
+
+ public int getCodeSensor() { return codeSensor; }
+ public void setCodeSensor(int codeSensor) {
+ this.codeSensor = codeSensor;
+ }
+
+ public int getCodeSensorMax() { return codeSensorMax; }
+ public void setCodeSensorMax(int codeSensor) {
+ this.codeSensorMax = codeSensor;
+ }
+
+ public int getCodeRssi() {
+ return codeRssi;
+ }
+ public void setCodeRssi(int codeRssi) {
+ this.codeRssi = codeRssi;
+ }
+
+ public float getCodeTempC() { return codeTempC; }
+ public void setCodeTempC(float codeTempC) {
+ this.codeTempC = codeTempC;
+ }
+
+ public String getBrand() {
+ return brand;
+ }
+ public void setBrand(String brand) { this.brand = brand; }
+
+ public int getSensorData() {
+ return sensorData;
+ }
+ public void setSensorData(int sensorData) { this.sensorData = sensorData; }
+
+ public String getstrExtra1() { return strExtra1; }
+ public void setExtra1(String strExtra1, int extra1Bank, int extra1Offset) {
+ this.strExtra1 = strExtra1;
+ this.extra1Bank = extra1Bank;
+ this.extra1Offset = extra1Offset;
+ }
+ public String getstrExtra2() { return strExtra2; }
+ public void setExtra2(String strExtra2, int extra2Bank, int extra2Offset) {
+ this.strExtra2 = strExtra2;
+ this.extra2Bank = extra2Bank;
+ this.extra2Offset = extra2Offset;
+ }
+ void setExtra(String strExtra1, int extra1Bank, int extra1Offset, String strExtra2, int extra2Bank, int extra2Offset) {
+ this.strExtra1 = strExtra1;
+ this.extra1Bank = extra1Bank;
+ this.extra1Offset = extra1Offset;
+ this.strExtra2 = strExtra2;
+ this.extra2Bank = extra2Bank;
+ this.extra2Offset = extra2Offset;
+ this.details = null; getDetails();
+ }
+
+ public boolean isConnected() {
+ return isConnected;
+ }
+
+ public void setConnected(boolean isConnected) {
+ this.isConnected = isConnected;
+ }
+
+ public String getTimeOfRead() { return timeOfRead; }
+ public String getTimeZone() { return timeZone; }
+ public String getLocation() { return location; }
+ public void setLocation(String location) { this.location = location; }
+ public String getCompass() { return compass; }
+ public void setCcompass(String compass) { this.compass = compass; }
+
+ @Override
+ public boolean equals(Object o) {
+ if (o == null || !(o instanceof ReaderDevice)) {
+ return false;
+ }
+ final ReaderDevice readerDevice = (ReaderDevice) o;
+ return ((this.getAddress() != null && readerDevice.getAddress() != null) && (readerDevice.getAddress().equalsIgnoreCase(this.getAddress())));
+ }
+
+ @Override
+ public int hashCode() {
+ int hash = 4;
+ hash = 53 * hash + (this.getAddress() != null ? this.getAddress().hashCode() : 0);
+ return hash;
+ }
+
+ public int compareTo(ReaderDevice other) {
+ return address.compareTo(other.address);
+ }
+}
+
+
+
+package com.csl.cslibrary4a;
+
+import android.content.Context;
+import android.widget.TextView;
+import android.widget.Toast;
+
+import java.util.ArrayList;
+
+public class RfidConnector {
+ Context context; Utility utility;
+ public RfidConnector(Context context, Utility utility) {
+ this.context = context;
+ this.utility = utility;
+ }
+ private String byteArrayToString(byte[] packet) { return utility.byteArrayToString(packet); }
+ private boolean compareArray(byte[] array1, byte[] array2, int length) { return utility.compareByteArray(array1, array2, length); }
+ private void appendToLog(String s) { utility.appendToLog(s); }
+ private void appendToLogView(String s) { utility.appendToLogView(s); }
+
+ public enum RfidPayloadEvents {
+ RFID_POWER_ON, RFID_POWER_OFF, RFID_COMMAND,
+ RFID_DATA_READ
+ }
+ public static class CsReaderRfidData {
+ public boolean waitUplinkResponse = false;
+ public boolean downlinkResponded = false;
+
+ public boolean uplinkResponded = false;
+ public boolean waitUplink1Response = false;
+
+ public RfidPayloadEvents rfidPayloadEvent;
+ public byte[] dataValues;
+ public boolean invalidSequence;
+ public long milliseconds;
+ }
+
+ public boolean onStatus = false; public boolean getOnStatus() { return onStatus; }
+
+ public interface RfidConnectorCallback {
+ boolean callbackMethod(byte[] dataValues);
+ }
+ public RfidConnectorCallback rfidConnectorCallback = null;
+
+ public ArrayList mRfidToWrite = new ArrayList<>();
+ public ArrayList mRfidToRead = new ArrayList<>();
+
+ public boolean arrayTypeSet(byte[] dataBuf, int pos, RfidPayloadEvents event) {
+ boolean validEvent = false;
+ switch (event) {
+ case RFID_POWER_ON:
+ validEvent = true;
+ break;
+ case RFID_POWER_OFF:
+ dataBuf[pos] = 1;
+ validEvent = true;
+ break;
+ case RFID_COMMAND:
+ dataBuf[pos] = 2;
+ validEvent = true;
+ break;
+ }
+ return validEvent;
+ }
+ public byte[] writeRfid(RfidConnector.CsReaderRfidData data, boolean usbConnection) {
+ boolean DEBUG = true;
+ int datalength = 0;
+ if (data.dataValues != null) datalength = data.dataValues.length;
+ byte[] dataOutRef = new byte[]{(byte) 0xA7, (byte) 0xB3, 2, (byte) 0xC2, (byte) 0x82, (byte) 0x37, 0, 0, (byte) 0x80, 0};
+ if (usbConnection) dataOutRef[1] = (byte) 0xE6;
+
+ byte[] dataOut = new byte[10 + datalength];
+ if (datalength != 0) {
+ System.arraycopy(data.dataValues, 0, dataOut, 10, datalength);
+ dataOutRef[2] += datalength;
+ }
+ System.arraycopy(dataOutRef, 0, dataOut, 0, dataOutRef.length);
+ /*if (data.rfidPayloadEvent == RfidConnector.RfidPayloadEvents.RFID_COMMAND) {
+ if (data.dataValues != null) {
+ byte[] dataOut1 = new byte[dataOut.length + data.dataValues.length];
+ System.arraycopy(dataOut, 0, dataOut1, 0, dataOut.length);
+ dataOut1[2] += data.dataValues.length;
+ System.arraycopy(data.dataValues, 0, dataOut1, dataOut.length, data.dataValues.length);
+ dataOut = dataOut1;
+ }
+ }*/
+ appendToLog("aabb 8");
+ if (arrayTypeSet(dataOut, 9, data.rfidPayloadEvent)) {
+ if (utility.DEBUG_PKDATA) appendToLog(String.format("PkData: write Rfid.%s.%s with mRfidDevice.sendRfidToWriteSent = %d", data.rfidPayloadEvent.toString(), byteArrayToString(data.dataValues), sendRfidToWriteSent));
+ if (sendRfidToWriteSent != 0) appendToLog("!!! mRfidDevice.sendRfidToWriteSent = " + sendRfidToWriteSent);
+ appendToLog("aabb 9");
+ if (DEBUG) appendToLogView("NOut: " + byteArrayToString(dataOut));
+ return dataOut;
+ }
+ return null;
+ }
+ public int rfidPowerOnTimeOut = 0; //int barcodePowerOnTimeOut = 0;
+ public boolean isMatchRfidToWrite(ConnectorData connectorData) {
+ boolean match = false, DEBUG = false;
+ if (mRfidToWrite.size() != 0 && connectorData.dataValues[0] == (byte)0x80) {
+ byte[] dataInCompare = new byte[]{(byte) 0x80, 0};
+ if (arrayTypeSet(dataInCompare, 1, mRfidToWrite.get(0).rfidPayloadEvent) && (connectorData.dataValues.length == dataInCompare.length + 1)) {
+ if (match = compareArray(connectorData.dataValues, dataInCompare, dataInCompare.length)) {
+ boolean bprocessed = false;
+ byte[] data1 = new byte[connectorData.dataValues.length - 2]; System.arraycopy(connectorData.dataValues, 2, data1, 0, data1.length);
+ if (utility.DEBUG_PKDATA) appendToLog("PkData: matched Rfid.Reply with payload = " + byteArrayToString(connectorData.dataValues) + " for writeData Rfid." + mRfidToWrite.get(0).rfidPayloadEvent.toString() + "." + byteArrayToString(mRfidToWrite.get(0).dataValues));
+ if (connectorData.dataValues[2] != 0) {
+ if (DEBUG) appendToLog("Rfid.reply data is found with error");
+ } else {
+ if (mRfidToWrite.get(0).rfidPayloadEvent == RfidConnector.RfidPayloadEvents.RFID_POWER_ON) {
+ rfidPowerOnTimeOut = 3000;
+ onStatus = true;
+ if (utility.DEBUG_PKDATA) appendToLog("PkData: matched Rfid.Reply.PowerOn with result 0 and onStatus = " + onStatus);
+ bprocessed = true;
+ } else if (mRfidToWrite.get(0).rfidPayloadEvent == RfidConnector.RfidPayloadEvents.RFID_POWER_OFF) {
+ onStatus = false;
+ if (utility.DEBUG_PKDATA) appendToLog("PkData: matched Rfid.Reply.PowerOff with result 0 and onStatus = " + onStatus);
+ bprocessed = true;
+ } else {
+ bprocessed = true;
+ if (utility.DEBUG_PKDATA) appendToLog("PkData: matched Rfid.Other.Reply data is found.");
+ }
+ RfidConnector.CsReaderRfidData csReaderRfidData = mRfidToWrite.get(0);
+ if (csReaderRfidData.waitUplinkResponse) {
+ csReaderRfidData.downlinkResponded = true;
+ mRfidToWrite.set(0, csReaderRfidData);
+ if (utility.DEBUG_PKDATA) appendToLog("PkData: mRfidToWrite.downlinkResponsed is set and waiting uplink data");
+ /*if (false) {
+ for (int i = 0; i < rfidReaderChip.mRfidReaderChip.mRx000ToRead.size(); i++) {
+ if (rfidReaderChip.mRfidReaderChip.mRx000ToRead.get(i).responseType == Cs710Library4A.HostCmdResponseTypes.TYPE_COMMAND_END)
+ if (DEBUG) appendToLog("mRx0000ToRead with COMMAND_END is removed");
+ }
+ if (DEBUG) appendToLog("mRx000ToRead.clear !!!");
+ }
+ rfidReaderChip.mRfidReaderChip.mRx000ToRead.clear(); if (DEBUG) appendToLog("mRx000ToRead.clear !!!");*/
+ utility.writeDebug2File("Up31 " + mRfidToWrite.get(0).rfidPayloadEvent.toString() + ", " + byteArrayToString(data1));
+ return true;
+ }
+ if (DEBUG) appendToLog("matched Rfid.reply data is found with mRfidToWrite.size=" + mRfidToWrite.size());
+ }
+
+ String string = "Up31 " + (bprocessed ? "" : "Unprocessed, ") + mRfidToWrite.get(0).rfidPayloadEvent.toString() + ", " + byteArrayToString(data1);
+ utility.writeDebug2File(string);
+ mRfidToWrite.remove(0); sendRfidToWriteSent = 0; mRfidToWriteRemoved = true; if (DEBUG) appendToLog("mmRfidToWrite remove 1 with remained write size = " + mRfidToWrite.size());
+ appendToLog("RfidConnector.isMatchRfidToWrite, UsbData: remove one");
+ if (utility.DEBUG_PKDATA) appendToLog("PkData: new mRfidToWrite size = " + mRfidToWrite.size());
+ /*if (false) {
+ for (int i = 0; i < rfidReaderChip.mRfidReaderChip.mRx000ToRead.size(); i++) {
+ if (rfidReaderChip.mRfidReaderChip.mRx000ToRead.get(i).responseType == Cs710Library4A.HostCmdResponseTypes.TYPE_COMMAND_END)
+ if (DEBUG) appendToLog("mRx0000ToRead with COMMAND_END is removed");
+ }
+ if (DEBUG) appendToLog("mRx000ToRead.clear !!!");
+ }
+ rfidReaderChip.mRfidReaderChip.mRx000ToRead.clear(); if (DEBUG) appendToLog("mRx000ToRead.clear !!!");*/
+ }
+ }
+ }
+ return match;
+ }
+
+ public int sendRfidToWriteSent = 0; public boolean mRfidToWriteRemoved = false;
+ public boolean rfidFailure = false; public boolean rfidValid = false;
+ public byte[] sendRfidToWrite(boolean usbConnection) {
+ boolean DEBUG = false;
+ boolean bValue = false;
+ //if (DEBUG) appendToLog("Timeout: btSendTimeOut = " + btSendTimeOut);
+ RfidConnector.RfidPayloadEvents rfidPayloadEvents = mRfidToWrite.get(0).rfidPayloadEvent;
+ int sendRfidToWriteSentMax = 5;
+ if (rfidPayloadEvents == RfidConnector.RfidPayloadEvents.RFID_COMMAND /*&& mRfidToWrite.get(0).dataValues[0] == 0x40*/) sendRfidToWriteSentMax = 5;
+ appendToLog("aabb 6");
+ if (sendRfidToWriteSent >= sendRfidToWriteSentMax) {
+ mRfidToWrite.remove(0); sendRfidToWriteSent = 0; mRfidToWriteRemoved = true; if (DEBUG) appendToLog("mmRfidToWrite remove 2");
+ if (DEBUG) appendToLog("Removed after sending count-out.");
+ if (true) {
+ appendToLog("Rfdid data transmission failure !!! clear mRfidToWrite buffer !!!");
+ //utility.writeDebug2File("Down fails to transmit " + byteArrayToString(mRfidToWrite.get(0).dataValues));
+ //appendToLog("BtDataOut: sendRfidToWrite 1 set rfidFailure as true with dataValues as " + byteArrayToString(mRfidToWrite.get(0).dataValues));
+ rfidFailure = true; appendToLog("BtDataOut: rfidFailure 1");
+ mRfidToWrite.clear(); appendToLog("BtDataOut: mRfidToWrite.clear 6");
+ } else if (rfidValid == false) {
+ Toast.makeText(context, "Problem in sending data to Rfid Module. Rfid is disabled.", Toast.LENGTH_SHORT).show();
+ appendToLog("BtDataOut: sendRfidToWrite 2 set rfidFailure as true");
+ rfidFailure = true; appendToLog("BtDataOut: rfidFailure 2");
+ } /*else {
+ Toast.makeText(context, "Problem in Sending Commands to RFID Module. Bluetooth Disconnected. Please Reconnect", Toast.LENGTH_SHORT).show();
+ appendToLog("disconnect d");
+ disconnect();
+ }*/
+ if (DEBUG) appendToLog("done");
+ } else {
+ if (DEBUG)
+ appendToLog("BtDataOut: size = " + mRfidToWrite.size() + ", PayloadEvents = " + rfidPayloadEvents.toString() + ", data=" + byteArrayToString(mRfidToWrite.get(0).dataValues));
+ appendToLog("aabb 7");
+ boolean retValue = false;
+ return writeRfid(mRfidToWrite.get(0), usbConnection);
+ }
+ return null;
+ }
+
+ public boolean found;
+ public int invalidUpdata;
+ public boolean isRfidToRead(ConnectorData connectorData) {
+ boolean DEBUG = false;
+ found = false;
+ if (connectorData.dataValues[0] == (byte) 0x81) {
+ appendToLog("BtData: RfidConnector.isRfidToRead dataValue = " + byteArrayToString(connectorData.dataValues));
+ RfidConnector.CsReaderRfidData cs108RfidReadData = new RfidConnector.CsReaderRfidData();
+ byte[] dataValues = new byte[connectorData.dataValues.length - 2];
+ System.arraycopy(connectorData.dataValues, 2, dataValues, 0, dataValues.length);
+ switch (connectorData.dataValues[1]) {
+ case 0:
+ appendToLog("BtData: RfidConnector.isRfidToRead rfidConnectorCallback is " + (rfidConnectorCallback == null ? "null" : "valid"));
+ if (rfidConnectorCallback != null) {
+ if (rfidConnectorCallback.callbackMethod(dataValues)) break;
+ }
+ cs108RfidReadData.rfidPayloadEvent = RfidConnector.RfidPayloadEvents.RFID_DATA_READ;
+ cs108RfidReadData.dataValues = dataValues;
+ cs108RfidReadData.invalidSequence = connectorData.invalidSequence;
+ cs108RfidReadData.milliseconds = connectorData.milliseconds;
+ mRfidToRead.add(cs108RfidReadData);
+ if (utility.DEBUG_PKDATA || true) appendToLog("PkData: Got Rfid.Uplink.DataRead with updated mRfidToRead data as " + byteArrayToString(dataValues));
+ found = true;
+ break;
+ default:
+ invalidUpdata++;
+ if (utility.DEBUG_PKDATA) appendToLog("PkData: !!! found INVALID Rfid.Uplink with payload = " + byteArrayToString(connectorData.dataValues));
+ break;
+ }
+ if (found) {
+ String string = "Up32 " + (found ? "" : "Unprocessed, ") + cs108RfidReadData.rfidPayloadEvent.toString() + ", " + byteArrayToString(dataValues);
+ utility.writeDebug2File(string);
+ }
+ }
+ return found;
+ }
+}
+
+
+
+package com.csl.cslibrary4a;
+
+import static java.lang.Math.log10;
+
+import android.content.Context;
+import android.util.Log;
+
+import androidx.annotation.NonNull;
+
+import java.math.BigInteger;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+
+public class RfidReader {
+ final boolean DEBUG = false;
+ public boolean bFirmware_reset_before = false;
+ RfidConnector rfidConnector; public RfidReaderChipR2000 rfidReaderChipR2000; public RfidReaderChipE710 rfidReaderChipE710;
+ ArrayList mRx000ToWrite;
+ ArrayList mRx000ToRead;
+ public ArrayList mRfidToWrite;
+ CountryChannelData countryChannelData;
+ Context context; Utility utility; boolean bis108; BluetoothGatt bluetoothGatt; SettingData settingData; NotificationConnector notificationConnector;
+ public RfidReader(Context context, Utility utility, CsReaderConnector csReaderConnector, boolean bis108, BluetoothGatt bluetoothGatt, SettingData settingData, NotificationConnector notificationConnector) {
+ this.context = context;
+ this.utility = utility;
+ this.bis108 = bis108;
+ this.bluetoothGatt = bluetoothGatt;
+ this.settingData = settingData;
+ this.notificationConnector = notificationConnector;
+
+ rfidConnector = new RfidConnector(context, utility); mRfidToWrite = rfidConnector.mRfidToWrite;
+ if (bis108) {
+ appendToLog("bis108: new RfidReaderChipR2000 is created");
+ rfidReaderChipR2000 = new RfidReaderChipR2000(context, utility, csReaderConnector);
+ mRx000ToWrite = rfidReaderChipR2000.mRx000ToWrite;
+ mRx000ToRead = rfidReaderChipR2000.mRx000ToRead;
+ } else {
+ appendToLog("bis108: new RfidReaderChipE710 is created");
+ rfidReaderChipE710 = new RfidReaderChipE710(context, utility, csReaderConnector);
+ mRx000ToWrite = rfidReaderChipE710.mRx000ToWrite;
+ mRx000ToRead = rfidReaderChipE710.mRx000ToRead;
+ rfidConnector.rfidConnectorCallback = new RfidConnector.RfidConnectorCallback(){
+ @Override
+ public boolean callbackMethod(byte[] dataValues) {
+ return rfidReaderChipE710.decode710Data(dataValues);
+ }
+ };
+ }
+ countryChannelData = new CountryChannelData();
+ countryChannelData.fccFreqTableIdx = new int[50];
+ int[] freqSortedINx = countryChannelData.fccFreqSortedIdx;
+ for (int i = 0; i < 50; i++) {
+ countryChannelData.fccFreqTableIdx[countryChannelData.fccFreqSortedIdx[i]] = i;
+ }
+ for (int i = 0; i < 50; i++) {
+ if (false) appendToLog("fccFreqTableIdx[" + i + "] = " + countryChannelData.fccFreqTableIdx[i]);
+ }
+ }
+
+ public enum TagType {
+ TAG_NULL,
+ TAG_IMPINJ, TAG_IMPINJ_M755, //E28011, E2C011
+ TAG_ALIEN, //E2003
+ TAG_NXP, TAG_NXP_UCODEDNA, TAG_NXP_UCODE8, //E2806, E2C06, E2806894
+ TAG_NXP_UCODE8_EPC, TAG_NXP_UCODE8_EPCTID, TAG_NXP_UCODE8_EPCBRAND, TAG_NXP_UCODE8_EPCBRANDTID, //E2806894A, E2806894B, E2806894C, E2806894d
+ TAG_EM, TAG_EM_BAP, TAG_EM_COLDCHAIN, TAG_EM_AURASENSE, TAG_EM_AURASENSE_ATBOOT, TAG_EM_AURASENSE_ATSELECT, //E280B, E200B0, E280B0, E280B12, E280B12A, E280B12B
+ TAG_KILOWAY, //E281D
+ TAG_LONGJING, //E201E
+ TAG_FDMICRO, //E2827001
+ TAG_CTESIUS, //E203510
+ TAG_ASYGN, //E283A
+ TAG_AXZON, TAG_MAGNUS_S2, TAG_MAGNUS_S3, TAG_AXZON_XERXES, //E2824, E282402, E282403, E282405
+ }
+ public static class ExtraBankData {
+ public int extra1Bank;
+ public int extra2Bank;
+ public int extra1Count;
+ public int extra2Count;
+ public int extra1Offset;
+ public int extra2Offset;
+
+ public ExtraBankData() {
+ extra1Bank = -1; extra2Bank = -1;
+ extra1Count = 0; extra2Count = 0;
+ extra1Offset = 0; extra2Offset = 0;
+ }
+
+ public void setExtraBankData(int extra1Bank, int extra1Count, int extra1Offset, int extra2Bank, int extra2Count, int extra2Offset) {
+ this.extra1Bank = extra1Bank; this.extra2Bank = extra2Bank;
+ this.extra1Count = extra1Count; this.extra2Count = extra2Count;
+ this.extra1Offset = extra1Offset; this.extra2Offset = extra2Offset;
+ }
+ public void setExtraBankData(RfidReader.TagType tagType, String mDid) {
+ extra2Bank = 2;
+ extra2Offset = 0;
+ extra2Count = 2;
+ Log.i("Hello", "tagType = " + (tagType == null ? "null" : tagType.toString()) + ", mDid = " + mDid);
+ if (mDid == null) mDid = "";
+ if (mDid.matches("E2801101") || mDid.matches("E2801102") || mDid.matches("E2801103") || mDid.matches("E2801104") || mDid.matches("E2801105")) {
+ extra1Bank = 0;
+ extra1Offset = 4;
+ extra1Count = 1;
+ if (mDid.matches("E2801101")) extra2Count = 6;
+ } else if (mDid.matches("E200B0")) {
+ extra1Bank = 2;
+ extra1Offset = 0;
+ extra1Count = 2;
+ extra2Bank = 3;
+ extra2Offset = 0x2d;
+ extra2Count = 1;
+ } else if (mDid.matches("E203510")) {
+ extra1Bank = 2;
+ extra1Offset = 0;
+ extra1Count = 2;
+ extra2Bank = 3;
+ extra2Offset = 8;
+ extra2Count = 2;
+ } else if (mDid.matches("E283A")) {
+ extra1Bank = 2;
+ extra1Offset = 0;
+ extra1Count = 2;
+ extra2Bank = 3;
+ extra2Offset = 0;
+ extra2Count = 8;
+ } else if (mDid.indexOf("E280B12") == 0) {
+ extra1Bank = 2;
+ extra1Offset = 0;
+ extra1Count = 2;
+ extra2Bank = 3;
+ extra2Offset = 0x120;
+ extra2Count = 1;
+ } else if (mDid.indexOf("E280B0") == 0) {
+ extra1Bank = 3;
+ extra1Offset = 188;
+ extra1Count = 2;
+ //extra2Bank = 3;
+ //extra2Offset = 0x10d;
+ //extra2Count = 1;
+ } else if (mDid.indexOf("E281D") == 0) { //need atmel firmware 0.2.20
+ extra1Bank = 0;
+ extra1Offset = 4;
+ extra1Count = 1;
+ extra2Count = 6;
+ } else if (mDid.indexOf("E201E") == 0) {
+ extra1Bank = 3;
+ extra1Offset = 112;
+ extra1Count = 1;
+ extra2Count = 6;
+ } else if (mDid.matches("E282402")) {
+ extra1Bank = 0;
+ extra1Offset = 11;
+ extra1Count = 1;
+ extra2Bank = 0;
+ extra2Offset = 13;
+ extra2Count = 1;
+ } else if (mDid.matches("E282403")) {
+ extra1Bank = 0;
+ extra1Offset = 12;
+ extra1Count = 3;
+ extra2Bank = 3;
+ extra2Offset = 8;
+ extra2Count = 4;
+ } else if (mDid.matches("E282405")) {
+ extra1Bank = 0;
+ extra1Offset = 10;
+ extra1Count = 5;
+ extra2Bank = 3;
+ extra2Offset = 0x12;
+ extra2Count = 4;
+ }
+ }
+
+ public void adjustExtraBank1() {
+ if (extra1Bank == -1 || extra1Count == 0) {
+ extra1Bank = extra2Bank;
+ extra2Bank = 0;
+ extra1Count = extra2Count;
+ extra2Count = 0;
+ extra1Offset = extra2Offset;
+ extra2Offset = 0;
+ }
+ if (extra1Bank == 1) extra1Offset += 2;
+ if (extra2Bank == 1) extra2Offset += 2;
+ }
+ }
+ public int setSelectData4Inventory(RfidReader.TagType tagType, String mDid, boolean bNeedSelectedTagByTID, String stringProtectPassword, int selectFor, int selectHold) {
+ int iValue = -1;
+ if (utility.DEBUG_SELECT) appendToLog("Debug_Select: RfidReader.setSelectData4Inventory with mDid = " + mDid);
+ if (mDid != null) {
+ setSelectCriteriaDisable(-1);
+ if (mDid.indexOf("E280B12") == 0) {
+ if (mDid.matches("E280B12B")) {
+ setSelectCriteria(0, true, 4, 0, 5, 1, 0x220, "8321");
+ appendToLog("Hello123: Set Sense at Select !!!");
+ } else { //if (MainActivity.mDid.matches("E280B12A")) {
+ //setSelectCriteriaDisable(-1);
+ appendToLog("Hello123: Set Sense at BOOT !!!");
+ }
+ } else if (mDid.matches("E203510")) {
+ setSelectCriteria(0, true, 7, 4, 0, 2, 0, mDid);
+ } else if (mDid.matches("E28240")) {
+ if (true || selectFor != 0) {
+ //setSelectCriteriaDisable(-1);
+ selectFor = 0;
+ iValue = selectFor;
+ }
+ } else if (mDid.matches("E282402")) {
+ appendToLog("selectFor = " + selectFor);
+ if (true || selectFor != 2) {
+ setSelectCriteria(0, true, 4, 2, 0, 3, 0xA0, "20");
+ selectFor = 2;
+ iValue = selectFor;
+ }
+ } else if (mDid.matches("E282403")) {
+ if (utility.DEBUG_SELECT) appendToLog("Debug_Select: RfidReader.setSelectData4Inventory selectFor = " + selectFor);
+ if (true || selectFor != 3) {
+ setSelectCriteria(0, true, 4, 2, 0, 3, 0xD0, "1F");
+ int delay = 0; if (bis108) delay = 5; //if delay in 710 causes no inventory after leaving and returning
+ setSelectCriteria(1, true, 4, 2, delay, 3, 0xE0, "");
+ selectFor = 3;
+ iValue = selectFor;
+ }
+ } else if (mDid.matches("E282405")) {
+ if (true || selectFor != 5) {
+ setSelectCriteria(0, true, 4, 5, selectHold, 3, 0x3B0, "00");
+ //setSelectCriteriaDisable(2);
+ selectFor = 5;
+ iValue = selectFor;
+ }
+ } else {
+ appendToLog("MainActivity.selectFor = " + selectFor);
+ if (true || selectFor != -1) {
+ //setSelectCriteriaDisable(-1);
+ selectFor = -1;
+ iValue = selectFor;
+ }
+ }
+
+ if (mDid.indexOf("E2806894") == 0) {
+ appendToLog("RfidReader.setSelectData 0 found " + mDid + ".indexOf[E2806894] == 0");
+ if (mDid.matches("E2806894A")) {
+ appendToLog("RfidReader.setSelectData 1 found E2806894A");
+ //setSelectCriteriaDisable(1);
+ } else if (mDid.matches("E2806894B")) {
+ appendToLog("RfidReader.setSelectData 2 found E2806894B");
+ appendToLog("BtDataOut BBB 2");
+ setSelectCriteria(0, true, 4, 0, 1, 0x203, "1", true);
+ setSelectCriteria(1, true, 4, 2, 2, 0, "E2806894", false);
+ } else if (mDid.matches("E2806894C") || mDid.matches("E2806894d")) {
+ appendToLog("RfidReader.setSelectData 3 found " + mDid);
+ setSelectCriteria(0, true, 4, 0, 1, 0x204, "1", true);
+ setSelectCriteria(1, true, 4, 2, 2, 0, "E2806894", false);
+ }
+ mDid = "E2806894";
+ }
+
+ if (bNeedSelectedTagByTID) {
+ String strMdid = mDid;
+ if (strMdid.indexOf("E28011") == 0) {
+ int iValue1 = Integer.valueOf(strMdid.substring(6, 8), 16);
+ iValue1 &= 0x0F;
+ appendToLog(String.format("iValue1 = 0x%X", iValue1));
+ if (iValue1 == 1) strMdid = "E2C011A2";
+ else if (iValue1 == 2) strMdid = "E28011C";
+ else if (iValue1 == 3) strMdid = "E28011B";
+ else if (iValue1 == 4) strMdid = "E28011A";
+ else if (iValue1 == 5) strMdid = "E280119";
+ else if (iValue1 == 6) strMdid = "E2801171";
+ else if (iValue1 == 7) strMdid = "E2801170";
+ else if (iValue1 == 8) strMdid = "E2801150";
+ else
+ strMdid = "E2001"; //strMdid.substring(0, 5); even E2801 or E2C01 will return
+ }
+ if (stringProtectPassword != null) {
+ if (stringProtectPassword.trim().length() == 0)
+ stringProtectPassword = "00000000";
+ if (utility.DEBUG_SELECT) appendToLog("Debug_Select: RfidReader.setSelectCriteria: Going to setSelectCriteria");
+ setSelectCriteria(-1, true, 4, 0, 3, 0, stringProtectPassword, false);
+ }
+ if (utility.DEBUG_SELECT) appendToLog("Debug_Select: RfidReader.setSelectCriteria: Going to setSelectedByTID");
+ setSelectedTagByTID(strMdid, -1);
+ }
+ }
+ return iValue;
+ }
+
+ //============ utility ============
+ private void appendToLog(String s) { utility.appendToLog(s); }
+
+ //============ Rfid ============
+ //============ Rfid ============
+ //============ Rfid ============
+ //============ Rfid ============
+ //============ Rfid ============
+
+ public boolean setInvAlgoNoSave(boolean dynamicAlgo) {
+ appendToLog("writeBleStreamOut: going to setInvAlgo with dynamicAlgo = " + dynamicAlgo);
+ return setInvAlgo1(dynamicAlgo);
+ }
+ public boolean setInvAlgo1(boolean dynamicAlgo) {
+ boolean bValue = true, DEBUG = false;
+ if (DEBUG) appendToLog("2 setInvAlgo1");
+ int iAlgo = getInvAlgoInChip();
+ int iRetry = getRetryCount();
+ int iAbFlip = (bis108 ? rfidReaderChipR2000.rx000Setting.getAlgoAbFlip() : rfidReaderChipE710.rx000Setting.getAlgoAbFlip());
+ if (DEBUG) appendToLog("2 setInvAlgo1: going to setInvAlgo with dynamicAlgo = " + dynamicAlgo + ", iAlgo = " + iAlgo + ", iRetry = " + iRetry + ", iabFlip = " + iAbFlip);
+ if ( (dynamicAlgo && iAlgo == 0) || (dynamicAlgo == false && iAlgo == 3)) {
+ bValue = (bis108 ? rfidReaderChipR2000.rx000Setting.setInvAlgo(dynamicAlgo ? 3 : 0) : rfidReaderChipE710.rx000Setting.setInvAlgo(dynamicAlgo ? 3 : 0));
+ if (DEBUG) appendToLog("After setInvAlgo, bValue = " + bValue);
+ if (DEBUG) appendToLog("Before setPopulation, population = " + getPopulation());
+ if (bValue) bValue = setPopulation(getPopulation());
+ if (DEBUG) appendToLog("After setPopulation, bValue = " + bValue);
+ if (bValue) bValue = setRetryCount(iRetry);
+ if (DEBUG) appendToLog("After setRetryCount, bValue = " + bValue);
+ if (bValue) bValue = (bis108 ? rfidReaderChipR2000.rx000Setting.setAlgoAbFlip(iAbFlip) : rfidReaderChipE710.rx000Setting.setAlgoAbFlip(iAbFlip));
+ if (DEBUG) appendToLog("After setAlgoAbFlip, bValue = " + bValue);
+ }
+ return bValue;
+ }
+
+ private int[] freqTable = null;
+ private int[] freqSortedIdx = null;
+ static class CountryChannelData {
+ final int FCC_CHN_CNT = 50;
+ private final double[] FCCTableOfFreq = new double[]{
+ 902.75, 903.25, 903.75, 904.25, 904.75, 905.25, 905.75, 906.25, 906.75, 907.25,//10
+ 907.75, 908.25, 908.75, 909.25, 909.75, 910.25, 910.75, 911.25, 911.75, 912.25,//20
+ 912.75, 913.25, 913.75, 914.25, 914.75, 915.25, 915.75, 916.25, 916.75, 917.25,
+ 917.75, 918.25, 918.75, 919.25, 919.75, 920.25, 920.75, 921.25, 921.75, 922.25,
+ 922.75, 923.25, 923.75, 924.25, 924.75, 925.25, 925.75, 926.25, 926.75, 927.25};
+ private final double[] FCCTableOfFreq0 = new double[]{
+ 903.75, 912.25, 907.75, 910.25, 922.75, 923.25, 923.75, 915.25, 909.25, 912.75,
+ 910.75, 913.75, 909.75, 905.25, 911.75, 902.75, 914.25, 918.25, 926.25, 925.75,
+ 920.75, 920.25, 907.25, 914.75, 919.75, 922.25, 903.25, 906.25, 905.75, 926.75,
+ 924.25, 904.75, 925.25, 924.75, 919.25, 916.75, 911.25, 921.25, 908.25, 908.75,
+ 913.25, 916.25, 904.25, 906.75, 917.75, 921.75, 917.25, 927.25, 918.75, 915.75};
+ private int[] fccFreqSortedIdx0;
+ private final double[] FCCTableOfFreq1 = new double[]{
+ 915.25, 920.75, 909.25, 912.25, 918.25, 920.25, 909.75, 910.25, 919.75, 922.75,
+ 908.75, 913.75, 903.75, 919.25, 922.25, 907.75, 911.75, 923.75, 916.75, 926.25,
+ 908.25, 912.75, 924.25, 916.25, 927.25, 907.25, 910.75, 903.25, 917.75, 926.75,
+ 905.25, 911.25, 924.75, 917.25, 925.75, 906.75, 914.25, 904.75, 918.75, 923.25,
+ 902.75, 914.75, 905.75, 915.75, 925.25, 906.25, 921.25, 913.25, 921.75, 904.25};
+ private int[] fccFreqSortedIdx1;
+ private int[] fccFreqTable = new int[]{
+ 0x00180E4F, //915.75 MHz
+ 0x00180E4D, //915.25 MHz
+ 0x00180E1D, //903.25 MHz
+ 0x00180E7B, //926.75 MHz
+ 0x00180E79, //926.25 MHz
+ 0x00180E21, //904.25 MHz
+ 0x00180E7D, //927.25 MHz
+ 0x00180E61, //920.25 MHz
+ 0x00180E5D, //919.25 MHz
+ 0x00180E35, //909.25 MHz
+ 0x00180E5B, //918.75 MHz
+ 0x00180E57, //917.75 MHz
+ 0x00180E25, //905.25 MHz
+ 0x00180E23, //904.75 MHz
+ 0x00180E75, //925.25 MHz
+ 0x00180E67, //921.75 MHz
+ 0x00180E4B, //914.75 MHz
+ 0x00180E2B, //906.75 MHz
+ 0x00180E47, //913.75 MHz
+ 0x00180E69, //922.25 MHz
+ 0x00180E3D, //911.25 MHz
+ 0x00180E3F, //911.75 MHz
+ 0x00180E1F, //903.75 MHz
+ 0x00180E33, //908.75 MHz
+ 0x00180E27, //905.75 MHz
+ 0x00180E41, //912.25 MHz
+ 0x00180E29, //906.25 MHz
+ 0x00180E55, //917.25 MHz
+ 0x00180E49, //914.25 MHz
+ 0x00180E2D, //907.25 MHz
+ 0x00180E59, //918.25 MHz
+ 0x00180E51, //916.25 MHz
+ 0x00180E39, //910.25 MHz
+ 0x00180E3B, //910.75 MHz
+ 0x00180E2F, //907.75 MHz
+ 0x00180E73, //924.75 MHz
+ 0x00180E37, //909.75 MHz
+ 0x00180E5F, //919.75 MHz
+ 0x00180E53, //916.75 MHz
+ 0x00180E45, //913.25 MHz
+ 0x00180E6F, //923.75 MHz
+ 0x00180E31, //908.25 MHz
+ 0x00180E77, //925.75 MHz
+ 0x00180E43, //912.75 MHz
+ 0x00180E71, //924.25 MHz
+ 0x00180E65, //921.25 MHz
+ 0x00180E63, //920.75 MHz
+ 0x00180E6B, //922.75 MHz
+ 0x00180E1B, //902.75 MHz
+ 0x00180E6D, //923.25 MHz
+ };
+ private int[] fccFreqTableIdx;
+ private final int[] fccFreqSortedIdx = new int[]{
+ 26, 25, 1, 48, 47,
+ 3, 49, 35, 33, 13,
+ 32, 30, 5, 4, 45,
+ 38, 24, 8, 22, 39,
+ 17, 18, 2, 12, 6,
+ 19, 7, 29, 23, 9,
+ 31, 27, 15, 16, 10,
+ 44, 14, 34, 28, 21,
+ 42, 11, 46, 20, 43,
+ 37, 36, 40, 0, 41};
+
+ private final int AUS_CHN_CNT = 10;
+ private final double[] AUSTableOfFreq = new double[]{
+ 920.75, 921.25, 921.75, 922.25, 922.75,
+ 923.25, 923.75, 924.25, 924.75, 925.25};
+ private final int[] AusFreqTable = new int[]{
+ 0x00180E63, // 920.75MHz
+ 0x00180E69, // 922.25MHz
+ 0x00180E6F, // 923.75MHz
+ 0x00180E73, // 924.75MHz
+ 0x00180E65, // 921.25MHz
+ 0x00180E6B, // 922.75MHz
+ 0x00180E71, // 924.25MHz
+ 0x00180E75, // 925.25MHz
+ 0x00180E67, // 921.75MHz
+ 0x00180E6D, // 923.25MHz
+ };
+ private final int[] ausFreqSortedIdx = new int[]{
+ 0, 3, 6, 8, 1,
+ 4, 7, 9, 2, 5};
+
+ private double[] PRTableOfFreq = new double[]{
+ 915.25, 915.75, 916.25, 916.75, 917.25,
+ 917.75, 918.25, 918.75, 919.25, 919.75, 920.25, 920.75, 921.25, 921.75, 922.25,
+ 922.75, 923.25, 923.75, 924.25, 924.75, 925.25, 925.75, 926.25, 926.75, 927.25};
+
+ private final int VZ_CHN_CNT = 10;
+ private final double[] VZTableOfFreq = new double[]{
+ 922.75, 923.25, 923.75, 924.25, 924.75,
+ 925.25, 925.75, 926.25, 926.75, 927.25};
+ private final int[] vzFreqTable = new int[]{
+ 0x00180E77, // 925.75 MHz
+ 0x00180E6B, // 922.75MHz
+ 0x00180E7D, // 927.25 MHz
+ 0x00180E75, // 925.25MHz
+ 0x00180E6D, // 923.25MHz
+ 0x00180E7B, // 926.75 MHz
+ 0x00180E73, // 924.75MHz
+ 0x00180E6F, // 923.75MHz
+ 0x00180E79, // 926.25 MHz
+ 0x00180E71, // 924.25MHz
+ };
+ private final int[] vzFreqSortedIdx = new int[]{
+ 6, 0, 9, 5, 1,
+ 8, 4, 2, 7, 3};
+
+ private final int BR1_CHN_CNT = 24;
+ private final double[] BR1TableOfFreq = new double[]{
+ //902.75, 903.25, 903.75, 904.25, 904.75,
+ //905.25, 905.75, 906.25, 906.75, 907.25,
+ //907.75, 908.25, 908.75, 909.25, 909.75,
+ //910.25, 910.75, 911.25, 911.75, 912.25,
+ //912.75, 913.25, 913.75, 914.25, 914.75,
+ //915.25,
+ 915.75, 916.25, 916.75, 917.25, 917.75,
+ 918.25, 918.75, 919.25, 919.75, 920.25,
+ 920.75, 921.25, 921.75, 922.25, 922.75,
+ 923.25, 923.75, 924.25, 924.75, 925.25,
+ 925.75, 926.25, 926.75, 927.25};
+ private final int[] br1FreqTable = new int[]{
+ 0x00180E4F, //915.75 MHz
+ //0x00180E4D, //915.25 MHz
+ //0x00180E1D, //903.25 MHz
+ 0x00180E7B, //926.75 MHz
+ 0x00180E79, //926.25 MHz
+ //0x00180E21, //904.25 MHz
+ 0x00180E7D, //927.25 MHz
+ 0x00180E61, //920.25 MHz
+ 0x00180E5D, //919.25 MHz
+ //0x00180E35, //909.25 MHz
+ 0x00180E5B, //918.75 MHz
+ 0x00180E57, //917.75 MHz
+ //0x00180E25, //905.25 MHz
+ //0x00180E23, //904.75 MHz
+ 0x00180E75, //925.25 MHz
+ 0x00180E67, //921.75 MHz
+ //0x00180E4B, //914.75 MHz
+ //0x00180E2B, //906.75 MHz
+ //0x00180E47, //913.75 MHz
+ 0x00180E69, //922.25 MHz
+ //0x00180E3D, //911.25 MHz
+ //0x00180E3F, //911.75 MHz
+ //0x00180E1F, //903.75 MHz
+ //0x00180E33, //908.75 MHz
+ //0x00180E27, //905.75 MHz
+ //0x00180E41, //912.25 MHz
+ //0x00180E29, //906.25 MHz
+ 0x00180E55, //917.25 MHz
+ //0x00180E49, //914.25 MHz
+ //0x00180E2D, //907.25 MHz
+ 0x00180E59, //918.25 MHz
+ 0x00180E51, //916.25 MHz
+ //0x00180E39, //910.25 MHz
+ //0x00180E3B, //910.75 MHz
+ //0x00180E2F, //907.75 MHz
+ 0x00180E73, //924.75 MHz
+ //0x00180E37, //909.75 MHz
+ 0x00180E5F, //919.75 MHz
+ 0x00180E53, //916.75 MHz
+ //0x00180E45, //913.25 MHz
+ 0x00180E6F, //923.75 MHz
+ //0x00180E31, //908.25 MHz
+ 0x00180E77, //925.75 MHz
+ //0x00180E43, //912.75 MHz
+ 0x00180E71, //924.25 MHz
+ 0x00180E65, //921.25 MHz
+ 0x00180E63, //920.75 MHz
+ 0x00180E6B, //922.75 MHz
+ //0x00180E1B, //902.75 MHz
+ 0x00180E6D, //923.25 MHz
+ };
+ private final int[] br1FreqSortedIdx = new int[]{
+ 0, 22, 21, 23, 9,
+ 7, 6, 4, 19, 12,
+ 13, 3, 5, 1, 18,
+ 8, 2, 16, 20, 17,
+ 11, 10, 14, 15};
+
+ private final int BR2_CHN_CNT = 33;
+ private double[] BR2TableOfFreq = new double[]{
+ 902.75, 903.25, 903.75, 904.25, 904.75,
+ 905.25, 905.75, 906.25, 906.75,
+ //907.25, 907.75, 908.25, 908.75, 909.25,
+ //909.75, 910.25, 910.75, 911.25, 911.75,
+ //912.25, 912.75, 913.25, 913.75, 914.25,
+ //914.75, 915.25,
+ 915.75, 916.25, 916.75, 917.25, 917.75,
+ 918.25, 918.75, 919.25, 919.75, 920.25,
+ 920.75, 921.25, 921.75, 922.25, 922.75,
+ 923.25, 923.75, 924.25, 924.75, 925.25,
+ 925.75, 926.25, 926.75, 927.25};
+ private final int[] br2FreqTable = new int[]{
+ 0x00180E4F, //915.75 MHz
+ //0x00180E4D, //915.25 MHz
+ 0x00180E1D, //903.25 MHz
+ 0x00180E7B, //926.75 MHz
+ 0x00180E79, //926.25 MHz
+ 0x00180E21, //904.25 MHz
+ 0x00180E7D, //927.25 MHz
+ 0x00180E61, //920.25 MHz
+ 0x00180E5D, //919.25 MHz
+ //0x00180E35, //909.25 MHz
+ 0x00180E5B, //918.75 MHz
+ 0x00180E57, //917.75 MHz
+ 0x00180E25, //905.25 MHz
+ 0x00180E23, //904.75 MHz
+ 0x00180E75, //925.25 MHz
+ 0x00180E67, //921.75 MHz
+ //0x00180E4B, //914.75 MHz
+ 0x00180E2B, //906.75 MHz
+ //0x00180E47, //913.75 MHz
+ 0x00180E69, //922.25 MHz
+ //0x00180E3D, //911.25 MHz
+ //0x00180E3F, //911.75 MHz
+ 0x00180E1F, //903.75 MHz
+ //0x00180E33, //908.75 MHz
+ 0x00180E27, //905.75 MHz
+ //0x00180E41, //912.25 MHz
+ 0x00180E29, //906.25 MHz
+ 0x00180E55, //917.25 MHz
+ //0x00180E49, //914.25 MHz
+ //0x00180E2D, //907.25 MHz
+ 0x00180E59, //918.25 MHz
+ 0x00180E51, //916.25 MHz
+ //0x00180E39, //910.25 MHz
+ //0x00180E3B, //910.75 MHz
+ //0x00180E2F, //907.75 MHz
+ 0x00180E73, //924.75 MHz
+ //0x00180E37, //909.75 MHz
+ 0x00180E5F, //919.75 MHz
+ 0x00180E53, //916.75 MHz
+ //0x00180E45, //913.25 MHz
+ 0x00180E6F, //923.75 MHz
+ //0x00180E31, //908.25 MHz
+ 0x00180E77, //925.75 MHz
+ //0x00180E43, //912.75 MHz
+ 0x00180E71, //924.25 MHz
+ 0x00180E65, //921.25 MHz
+ 0x00180E63, //920.75 MHz
+ 0x00180E6B, //922.75 MHz
+ 0x00180E1B, //902.75 MHz
+ 0x00180E6D, //923.25 MHz
+ };
+ private final int[] br2FreqSortedIdx = new int[]{
+ 9, 1, 31, 30, 3,
+ 32, 18, 16, 15, 13,
+ 5, 4, 28, 21, 8,
+ 22, 2, 6, 7, 12,
+ 14, 10, 27, 17, 11,
+ 25, 29, 26, 20, 19,
+ 23, 0, 24,
+ };
+
+ private final int BR3_CHN_CNT = 9;
+ private final double[] BR3TableOfFreq = new double[]{
+ 902.75, 903.25, 903.75, 904.25, 904.75, // 4
+ 905.25, 905.75, 906.25, 906.75};
+ private final int[] br3FreqTable = new int[]{
+ 0x00180E1D, //903.25 MHz
+ 0x00180E21, //904.25 MHz
+ 0x00180E25, //905.25 MHz
+ 0x00180E23, //904.75 MHz
+ 0x00180E2B, //906.75 MHz
+ 0x00180E1F, //903.75 MHz
+ 0x00180E27, //905.75 MHz
+ 0x00180E29, //906.25 MHz
+ 0x00180E1B, //902.75 MHz
+ };
+ private final int[] br3FreqSortedIdx = new int[]{
+ 1, 3, 5, 4, 8,
+ 2, 6, 7, 0};
+
+ private final int BR4_CHN_CNT = 4;
+ private final double[] BR4TableOfFreq = new double[]{
+ 902.75, 903.25, 903.75, 904.25};
+ private final int[] br4FreqTable = new int[]{
+ 0x00180E1D, //903.25 MHz
+ 0x00180E21, //904.25 MHz
+ 0x00180E1F, //903.75 MHz
+ 0x00180E1B, //902.75 MHz
+ };
+ private final int[] br4FreqSortedIdx = new int[]{
+ 1, 3, 2, 0};
+
+ private final int BR5_CHN_CNT = 14;
+ private final double[] BR5TableOfFreq = new double[]{
+ 917.75, 918.25, 918.75, 919.25, 919.75, // 4
+ 920.25, 920.75, 921.25, 921.75, 922.25, // 9
+ 922.75, 923.25, 923.75, 924.25};
+ private final int[] br5FreqTable = new int[]{
+ 0x00180E61, //920.25 MHz
+ 0x00180E5D, //919.25 MHz
+ 0x00180E5B, //918.75 MHz
+ 0x00180E57, //917.75 MHz
+ 0x00180E67, //921.75 MHz
+ 0x00180E69, //922.25 MHz
+ 0x00180E59, //918.25 MHz
+ 0x00180E5F, //919.75 MHz
+ 0x00180E6F, //923.75 MHz
+ 0x00180E71, //924.25 MHz
+ 0x00180E65, //921.25 MHz
+ 0x00180E63, //920.75 MHz
+ 0x00180E6B, //922.75 MHz
+ 0x00180E6D, //923.25 MHz
+ };
+ private final int[] br5FreqSortedIdx = new int[]{
+ 5, 3, 2, 0, 8,
+ 9, 1, 4, 12, 13,
+ 7, 6, 10, 11};
+
+ private final int HK_CHN_CNT = 8;
+ private final double[] HKTableOfFreq = new double[]{
+ 920.75, 921.25, 921.75, 922.25, 922.75,
+ 923.25, 923.75, 924.25};
+ private final int[] hkFreqTable = new int[]{
+ 0x00180E63, //920.75MHz
+ 0x00180E69, //922.25MHz
+ 0x00180E71, //924.25MHz
+ 0x00180E65, //921.25MHz
+ 0x00180E6B, //922.75MHz
+ 0x00180E6D, //923.25MHz
+ 0x00180E6F, //923.75MHz
+ 0x00180E67, //921.75MHz
+ };
+ private final int[] hkFreqSortedIdx = new int[]{
+ 0, 3, 7, 1, 4,
+ 5, 6, 2};
+
+ private final int BD_CHN_CNT = 4;
+ private final double[] BDTableOfFreq = new double[]{
+ 925.25, 925.75, 926.25, 926.75};
+ private final int[] bdFreqTable = new int[]{
+ 0x00180E75, //925.25MHz
+ 0x00180E77, //925.75MHz
+ 0x00180E79, //926.25MHz
+ 0x00180E7B, //926.75MHz
+ };
+ private final int[] bdFreqSortedIdx = new int[]{
+ 0, 3, 1, 2};
+
+ private final int TW_CHN_CNT = 12;
+ private final double[] TWTableOfFreq = new double[]{
+ 922.25, 922.75, 923.25, 923.75, 924.25,
+ 924.75, 925.25, 925.75, 926.25, 926.75,
+ 927.25, 927.75};
+ private int[] twFreqTable = new int[]{
+ 0x00180E7D, //927.25MHz 10
+ 0x00180E73, //924.75MHz 5
+ 0x00180E6B, //922.75MHz 1
+ 0x00180E75, //925.25MHz 6
+ 0x00180E7F, //927.75MHz 11
+ 0x00180E71, //924.25MHz 4
+ 0x00180E79, //926.25MHz 8
+ 0x00180E6D, //923.25MHz 2
+ 0x00180E7B, //926.75MHz 9
+ 0x00180E69, //922.25MHz 0
+ 0x00180E77, //925.75MHz 7
+ 0x00180E6F, //923.75MHz 3
+ };
+ private final int[] twFreqSortedIdx = new int[]{
+ 10, 5, 1, 6, 11,
+ 4, 8, 2, 9, 0,
+ 7, 3};
+
+ private final int MYS_CHN_CNT = 8;
+ private final double[] MYSTableOfFreq = new double[]{
+ 919.75, 920.25, 920.75, 921.25, 921.75,
+ 922.25, 922.75, 923.25};
+ private final int[] mysFreqTable = new int[]{
+ 0x00180E5F, //919.75MHz
+ 0x00180E65, //921.25MHz
+ 0x00180E6B, //922.75MHz
+ 0x00180E61, //920.25MHz
+ 0x00180E67, //921.75MHz
+ 0x00180E6D, //923.25MHz
+ 0x00180E63, //920.75MHz
+ 0x00180E69, //922.25MHz
+ };
+ private final int[] mysFreqSortedIdx = new int[]{
+ 0, 3, 6, 1, 4,
+ 7, 2, 5};
+
+ private final int ZA_CHN_CNT = 16;
+ private final double[] ZATableOfFreq = new double[]{
+ 915.7, 915.9, 916.1, 916.3, 916.5,
+ 916.7, 916.9, 917.1, 917.3, 917.5,
+ 917.7, 917.9, 918.1, 918.3, 918.5,
+ 918.7};
+ private final int[] zaFreqTable = new int[]{
+ 0x003C23C5, //915.7 MHz
+ 0x003C23C7, //915.9 MHz
+ 0x003C23C9, //916.1 MHz
+ 0x003C23CB, //916.3 MHz
+ 0x003C23CD, //916.5 MHz
+ 0x003C23CF, //916.7 MHz
+ 0x003C23D1, //916.9 MHz
+ 0x003C23D3, //917.1 MHz
+ 0x003C23D5, //917.3 MHz
+ 0x003C23D7, //917.5 MHz
+ 0x003C23D9, //917.7 MHz
+ 0x003C23DB, //917.9 MHz
+ 0x003C23DD, //918.1 MHz
+ 0x003C23DF, //918.3 MHz
+ 0x003C23E1, //918.5 MHz
+ 0x003C23E3, //918.7 MHz
+ };
+ private final int[] zaFreqSortedIdx = new int[]{
+ 0, 1, 2, 3, 4,
+ 5, 6, 7, 8, 9,
+ 10, 11, 12, 13, 14,
+ 15};
+
+ final int ID_CHN_CNT = 4;
+ private final double[] IDTableOfFreq = new double[]{
+ 923.25, 923.75, 924.25, 924.75};
+ private final int[] indonesiaFreqTable = new int[]{
+ 0x00180E6D, //923.25 MHz
+ 0x00180E6F,//923.75 MHz
+ 0x00180E71,//924.25 MHz
+ 0x00180E73,//924.75 MHz
+ };
+ private final int[] indonesiaFreqSortedIdx = new int[]{
+ 0, 1, 2, 3};
+
+ private final int IL_CHN_CNT = 7;
+ private final double[] ILTableOfFreq = new double[]{
+ 915.25, 915.5, 915.75, 916.0, 916.25, // 4
+ 916.5, 916.75};
+ private final int[] ilFreqTable = new int[]{
+ 0x00180E4D, //915.25 MHz
+ 0x00180E51, //916.25 MHz
+ 0x00180E4E, //915.5 MHz
+ 0x00180E52, //916.5 MHz
+ 0x00180E4F, //915.75 MHz
+ 0x00180E53, //916.75 MHz
+ 0x00180E50, //916.0 MHz
+ };
+ private final int[] ilFreqSortedIdx = new int[]{
+ 0, 4, 1, 5, 2, 6, 3};
+
+ private final int IL2019RW_CHN_CNT = 5;
+ private final double[] IL2019RWTableOfFreq = new double[]{
+ 915.9, 916.025, 916.15, 916.275, 916.4};
+ private final int[] il2019RwFreqTable = new int[]{
+ 0x003C23C7, //915.9 MHz
+ 0x003C23C8, //916.025 MHz
+ 0x003C23C9, //916.15 MHz
+ 0x003C23CA, //916.275 MHz
+ 0x003C23CB, //916.4 MHz
+ };
+ private final int[] il2019RwFreqSortedIdx = new int[]{
+ 0, 4, 1, 2, 3};
+
+ private final int PH_CHN_CNT = 8;
+ private final double[] PHTableOfFreq = new double[]{
+ 918.125, 918.375, 918.625, 918.875, 919.125, // 5
+ 919.375, 919.625, 919.875};
+ private final int[] phFreqTable = new int[]{
+ 0x00301CB1, //918.125MHz Channel 0
+ 0x00301CBB, //919.375MHz Channel 5
+ 0x00301CB7, //918.875MHz Channel 3
+ 0x00301CBF, //919.875MHz Channel 7
+ 0x00301CB3, //918.375MHz Channel 1
+ 0x00301CBD, //919.625MHz Channel 6
+ 0x00301CB5, //918.625MHz Channel 2
+ 0x00301CB9, //919.125MHz Channel 4
+ };
+ private final int[] phFreqSortedIdx = new int[]{
+ 0, 5, 3, 7, 1, 6, 2, 4};
+
+ private int NZ_CHN_CNT = 11;
+ private final double[] NZTableOfFreq = new double[]{
+ 922.25, 922.75, 923.25, 923.75, 924.25,// 4
+ 924.75, 925.25, 925.75, 926.25, 926.75,// 9
+ 927.25};
+ private final int[] nzFreqTable = new int[]{
+ 0x00180E71, //924.25 MHz
+ 0x00180E77, //925.75 MHz
+ 0x00180E69, //922.25 MHz
+ 0x00180E7B, //926.75 MHz
+ 0x00180E6D, //923.25 MHz
+ 0x00180E7D, //927.25 MHz
+ 0x00180E75, //925.25 MHz
+ 0x00180E6B, //922.75 MHz
+ 0x00180E79, //926.25 MHz
+ 0x00180E6F, //923.75 MHz
+ 0x00180E73, //924.75 MHz
+ };
+ private final int[] nzFreqSortedIdx = new int[]{
+ 4, 7, 0, 9, 2, 10, 6, 1, 8, 3, 5};
+
+ private final int CN_CHN_CNT = 16;
+ private final double[] CHNTableOfFreq = new double[]{
+ 920.625, 920.875, 921.125, 921.375, 921.625, 921.875, 922.125, 922.375, 922.625, 922.875,
+ 923.125, 923.375, 923.625, 923.875, 924.125, 924.375};
+ private final int[] cnFreqTable = new int[]{
+ 0x00301CD3, //922.375MHz
+ 0x00301CD1, //922.125MHz
+ 0x00301CCD, //921.625MHz
+ 0x00301CC5, //920.625MHz
+ 0x00301CD9, //923.125MHz
+ 0x00301CE1, //924.125MHz
+ 0x00301CCB, //921.375MHz
+ 0x00301CC7, //920.875MHz
+ 0x00301CD7, //922.875MHz
+ 0x00301CD5, //922.625MHz
+ 0x00301CC9, //921.125MHz
+ 0x00301CDF, //923.875MHz
+ 0x00301CDD, //923.625MHz
+ 0x00301CDB, //923.375MHz
+ 0x00301CCF, //921.875MHz
+ 0x00301CE3, //924.375MHz
+ };
+ private final int[] cnFreqSortedIdx = new int[]{
+ 7, 6, 4, 0, 10,
+ 14, 3, 1, 9, 8,
+ 2, 13, 12, 11, 5,
+ 15};
+
+ private final int UH1_CHN_CNT = 10;
+ private final double[] UH1TableOfFreq = new double[]{
+ 915.25, 915.75, 916.25, 916.75, 917.25,
+ 917.75, 918.25, 918.75, 919.25, 919.75};
+ private final int[] uh1FreqTable = new int[]{
+ 0x00180E4F, //915.75 MHz
+ 0x00180E4D, //915.25 MHz
+ 0x00180E5D, //919.25 MHz
+ 0x00180E5B, //918.75 MHz
+ 0x00180E57, //917.75 MHz
+ 0x00180E55, //917.25 MHz
+ 0x00180E59, //918.25 MHz
+ 0x00180E51, //916.25 MHz
+ 0x00180E5F, //919.75 MHz
+ 0x00180E53, //916.75 MHz
+ };
+ private final int[] uh1FreqSortedIdx = new int[]{
+ 1, 0, 8, 7, 5,
+ 4, 6, 2, 9, 3};
+
+ private final int UH2_CHN_CNT = 15;
+ private final double[] UH2TableOfFreq = new double[]{
+ 920.25, 920.75, 921.25, 921.75, 922.25, // 4
+ 922.75, 923.25, 923.75, 924.25, 924.75, // 9
+ 925.25, 925.75, 926.25, 926.75, 927.25};
+ private final int[] uh2FreqTable = new int[]{
+ 0x00180E7B, //926.75 MHz
+ 0x00180E79, //926.25 MHz
+ 0x00180E7D, //927.25 MHz
+ 0x00180E61, //920.25 MHz
+ 0x00180E75, //925.25 MHz
+ 0x00180E67, //921.75 MHz
+ 0x00180E69, //922.25 MHz
+ 0x00180E73, //924.75 MHz
+ 0x00180E6F, //923.75 MHz
+ 0x00180E77, //925.75 MHz
+ 0x00180E71, //924.25 MHz
+ 0x00180E65, //921.25 MHz
+ 0x00180E63, //920.75 MHz
+ 0x00180E6B, //922.75 MHz
+ 0x00180E6D, //923.25 MHz
+ };
+ private final int[] uh2FreqSortedIdx = new int[]{
+ 13, 12, 14, 0, 10,
+ 3, 4, 9, 7, 11,
+ 8, 2, 1, 5, 6,};
+
+ private final int LH_CHN_CNT = 26;
+ private double[] LHTableOfFreq = new double[]{
+ 902.75, 903.25, 903.75, 904.25, 904.75, // 4
+ 905.25, 905.75, 906.25, 906.75, 907.25, // 9
+ 907.75, 908.25, 908.75, 909.25, 909.75, // 14
+ 910.25, 910.75, 911.25, 911.75, 912.25, // 19
+ 912.75, 913.25, 913.75, 914.25, 914.75, // 24
+ 915.25, // 25
+ //915.75, 916.25, 916.75, 917.25, 917.75,
+ //918.25, 918.75, 919.25, 919.75, 920.25,
+ //920.75, 921.25, 921.75, 922.25, 922.75,
+ //923.25, 923.75, 924.25, 924.75, 925.25,
+ //925.75, 926.25, 926.75, 927.25,
+ };
+ private final int[] lhFreqTable = new int[]{
+ 0x00180E1B, //902.75 MHz
+ 0x00180E35, //909.25 MHz
+ 0x00180E1D, //903.25 MHz
+ 0x00180E37, //909.75 MHz
+ 0x00180E1F, //903.75 MHz
+ 0x00180E39, //910.25 MHz
+ 0x00180E21, //904.25 MHz
+ 0x00180E3B, //910.75 MHz
+ 0x00180E23, //904.75 MHz
+ 0x00180E3D, //911.25 MHz
+ 0x00180E25, //905.25 MHz
+ 0x00180E3F, //911.75 MHz
+ 0x00180E27, //905.75 MHz
+ 0x00180E41, //912.25 MHz
+ 0x00180E29, //906.25 MHz
+ 0x00180E43, //912.75 MHz
+ 0x00180E2B, //906.75 MHz
+ 0x00180E45, //913.25 MHz
+ 0x00180E2D, //907.25 MHz
+ 0x00180E47, //913.75 MHz
+ 0x00180E2F, //907.75 MHz
+ 0x00180E49, //914.25 MHz
+ 0x00180E31, //908.25 MHz
+ 0x00180E4B, //914.75 MHz
+ 0x00180E33, //908.75 MHz
+ 0x00180E4D, //915.25 MHz
+
+
+ //0x00180E4F, //915.75 MHz
+ //0x00180E7B, //926.75 MHz
+ //0x00180E79, //926.25 MHz
+ //0x00180E7D, //927.25 MHz
+ //0x00180E61, //920.25 MHz
+ //0x00180E5D, //919.25 MHz
+ //0x00180E5B, //918.75 MHz
+ //0x00180E57, //917.75 MHz
+ //0x00180E75, //925.25 MHz
+ //0x00180E67, //921.75 MHz
+ //0x00180E69, //922.25 MHz
+ //0x00180E55, //917.25 MHz
+ //0x00180E59, //918.25 MHz
+ //0x00180E51, //916.25 MHz
+ //0x00180E73, //924.75 MHz
+ //0x00180E5F, //919.75 MHz
+ //0x00180E53, //916.75 MHz
+ //0x00180E6F, //923.75 MHz
+ //0x00180E77, //925.75 MHz
+ //0x00180E71, //924.25 MHz
+ //0x00180E65, //921.25 MHz
+ //0x00180E63, //920.75 MHz
+ //0x00180E6B, //922.75 MHz
+ //0x00180E6D, //923.25 MHz
+ };
+ private final int[] lhFreqSortedIdx = new int[]{
+ 0, 13, 1, 14, 2,
+ 15, 3, 16, 4, 17,
+ 5, 18, 6, 19, 7,
+ 20, 8, 21, 9, 22,
+ 10, 23, 11, 24, 12,
+ 25};
+
+ private final int LH1_CHN_CNT = 14;
+ private double[] LH1TableOfFreq = new double[]{
+ 902.75, 903.25, 903.75, 904.25, 904.75, // 4
+ 905.25, 905.75, 906.25, 906.75, 907.25, // 9
+ 907.75, 908.25, 908.75, 909.25, // 13
+ };
+ private final int[] lh1FreqTable = new int[]{
+ 0x00180E1B, //902.75 MHz
+ 0x00180E35, //909.25 MHz
+ 0x00180E1D, //903.25 MHz
+ 0x00180E1F, //903.75 MHz
+ 0x00180E21, //904.25 MHz
+ 0x00180E23, //904.75 MHz
+ 0x00180E25, //905.25 MHz
+ 0x00180E27, //905.75 MHz
+ 0x00180E29, //906.25 MHz
+ 0x00180E2B, //906.75 MHz
+ 0x00180E2D, //907.25 MHz
+ 0x00180E2F, //907.75 MHz
+ 0x00180E31, //908.25 MHz
+ 0x00180E33, //908.75 MHz
+ };
+ private final int[] lh1FreqSortedIdx = new int[]{
+ 0, 13, 1, 2, 3,
+ 4, 5, 6, 7, 8,
+ 9, 10, 11, 12};
+
+ private final int LH2_CHN_CNT = 11;
+ private double[] LH2TableOfFreq = new double[]{
+ 909.75, 910.25, 910.75, 911.25, 911.75, // 4
+ 912.25, 912.75, 913.25, 913.75, 914.25, // 9
+ 914.75};
+ private final int[] lh2FreqTable = new int[]{
+ 0x00180E37, //909.75 MHz
+ 0x00180E39, //910.25 MHz
+ 0x00180E3B, //910.75 MHz
+ 0x00180E3D, //911.25 MHz
+ 0x00180E3F, //911.75 MHz
+ 0x00180E41, //912.25 MHz
+ 0x00180E43, //912.75 MHz
+ 0x00180E45, //913.25 MHz
+ 0x00180E47, //913.75 MHz
+ 0x00180E49, //914.25 MHz
+ 0x00180E4B, //914.75 MHz
+ };
+ private final int[] lh2FreqSortedIdx = new int[]{
+ 0, 1, 2, 3, 4,
+ 5, 6, 7, 8, 9,
+ 10};
+
+ private final int ETSI_CHN_CNT = 4;
+ private final double[] ETSITableOfFreq = new double[]{
+ 865.70, 866.30, 866.90, 867.50};
+ private final int[] etsiFreqTable = new int[]{
+ 0x003C21D1, //865.700MHz
+ 0x003C21D7, //866.300MHz
+ 0x003C21DD, //866.900MHz
+ 0x003C21E3, //867.500MHz
+ };
+ private final int[] etsiFreqSortedIdx = new int[]{
+ 0, 1, 2, 3};
+
+ private final int IDA_CHN_CNT = 3;
+ private final double[] IDATableOfFreq = new double[]{
+ 865.70, 866.30, 866.90};
+ private final int[] indiaFreqTable = new int[]{
+ 0x003C21D1, //865.700MHz
+ 0x003C21D7, //866.300MHz
+ 0x003C21DD, //866.900MHz
+ };
+ private final int[] indiaFreqSortedIdx = new int[]{
+ 0, 1, 2};
+
+ private final int KR_CHN_CNT = 19;
+ private final double[] KRTableOfFreq = new double[]{
+ 910.20, 910.40, 910.60, 910.80, 911.00, 911.20, 911.40, 911.60, 911.80, 912.00,
+ 912.20, 912.40, 912.60, 912.80, 913.00, 913.20, 913.40, 913.60, 913.80};
+ private int[] krFreqTable = new int[]{
+ 0x003C23A8, //912.8MHz 13
+ 0x003C23A0, //912.0MHz 9
+ 0x003C23AC, //913.2MHz 15
+ 0x003C239E, //911.8MHz 8
+ 0x003C23A4, //912.4MHz 11
+ 0x003C23B2, //913.8MHz 18
+ 0x003C2392, //910.6MHz 2
+ 0x003C23B0, //913.6MHz 17
+ 0x003C2390, //910.4MHz 1
+ 0x003C239C, //911.6MHz 7
+ 0x003C2396, //911.0MHz 4
+ 0x003C23A2, //912.2MHz 10
+ 0x003C238E, //910.2MHz 0
+ 0x003C23A6, //912.6MHz 12
+ 0x003C2398, //911.2MHz 5
+ 0x003C2394, //910.8MHz 3
+ 0x003C23AE, //913.4MHz 16
+ 0x003C239A, //911.4MHz 6
+ 0x003C23AA, //913.0MHz 14
+ };
+ private final int[] krFreqSortedIdx = new int[]{
+ 13, 9, 15, 8, 11,
+ 18, 2, 17, 1, 7,
+ 4, 10, 0, 12, 5,
+ 3, 16, 6, 14};
+
+ private final int KR2017RW_CHN_CNT = 6;
+ private final double[] KR2017RwTableOfFreq = new double[]{
+ 917.30, 917.90, 918.50, 919.10, 919.70, 920.30};
+ private int[] kr2017RwFreqTable = new int[]{
+ 0x003C23D5, // 917.3 -> 917.25 MHz Channel 1
+ 0x003C23DB, //917.9 -> 918 MHz Channel 2
+ 0x003C23E1, //918.5 MHz Channel 3
+ 0x003C23E7, //919.1 -> 919 MHz Channel 4
+ 0x003C23ED, //919.7 -> 919.75 MHz Channel 5
+ 0x003C23F3 // 920.3 -> 920.25 MHz Channel 6
+ };
+ private final int[] kr2017RwFreqSortedIdx = new int[]{
+ 3, 0, 5, 1, 4, 2};
+
+ private final int JPN2012_CHN_CNT = 4;
+ private final double[] JPN2012TableOfFreq = new double[]{
+ 916.80, 918.00, 919.20, 920.40};
+ private final int[] jpn2012FreqTable = new int[]{
+ 0x003C23D0, //916.800MHz Channel 1
+ 0x003C23DC, //918.000MHz Channel 2
+ 0x003C23E8, //919.200MHz Channel 3
+ 0x003C23F4, //920.400MHz Channel 4
+ //0x003C23F6, //920.600MHz Channel 5
+ //0x003C23F8, //920.800MHz Channel 6
+ };
+ private final int[] jpn2012FreqSortedIdx = new int[]{
+ 0, 1, 2, 3};
+
+ private final int JPN2012A_CHN_CNT = 6;
+ private final double[] JPN2012ATableOfFreq = new double[]{
+ 916.80, 918.00, 919.20, 920.40, 920.60, 920.80};
+ private final int[] jpn2012AFreqTable = new int[]{
+ 0x003C23D0, //916.800MHz Channel 1
+ 0x003C23DC, //918.000MHz Channel 2
+ 0x003C23E8, //919.200MHz Channel 3
+ 0x003C23F4, //920.400MHz Channel 4
+ 0x003C23F6, //920.600MHz Channel 5
+ 0x003C23F8, //920.800MHz Channel 6
+ };
+ private final int[] jpn2012AFreqSortedIdx = new int[]{
+ 0, 1, 2, 3, 4, 5};
+
+ private final int ETSIUPPERBAND_CHN_CNT = 4;
+ private final double[] ETSIUPPERBANDTableOfFreq = new double[]{
+ 916.3, 917.5, 918.7, 919.9};
+ private final int[] etsiupperbandFreqTable = new int[]{
+ 0x003C23CB, //916.3 MHz
+ 0x003C23D7, //917.5 MHz
+ 0x003C23E3, //918.7 MHz
+ 0x003C23EF, //919.9 MHz
+ };
+ private final int[] etsiupperbandFreqSortedIdx = new int[]{
+ 0, 1, 2, 3};
+
+ private final int VN1_CHN_CNT = 3;
+ private final double[] VN1TableOfFreq = new double[]{
+ 866.30, 866.90, 867.50};
+ private final int[] vietnam1FreqTable = new int[]{
+ 0x003C21D7, //866.300MHz
+ 0x003C21DD, //866.900MHz
+ 0x003C21E3, //867.500MHz
+ };
+ private final int[] vietnam1FreqSortedIdx = new int[]{
+ 0, 1, 2};
+
+ private final int VN2_CHN_CNT = 8;
+ private final double[] VN2TableOfFreq = new double[]{
+ 918.75, 919.25, 919.75, 920.25, 920.75, 921.25, 921.75, 922.25};
+ private final int[] vietnam2FreqTable = new int[]{
+ 0x00180E61, //920.25 MHz
+ 0x00180E5D, //919.25 MHz
+ 0x00180E5B, //918.75 MHz
+ 0x00180E67, //921.75 MHz
+ 0x00180E69, //922.25 MHz
+ 0x00180E5F, //919.75 MHz
+ 0x00180E65, //921.25 MHz
+ 0x00180E63, //920.75 MHz
+ };
+ private final int[] vietnam2FreqSortedIdx = new int[]{
+ 3, 1, 0, 6, 7, 2, 5, 4};
+
+ private final int VN3_CHN_CNT = 4;
+ private final double[] VN3TableOfFreq = new double[]{
+ 920.75, 921.25, 921.75, 922.25};
+ private final int[] vietnam3FreqTable = new int[]{
+ 0x00180E67, //921.75 MHz
+ 0x00180E69, //922.25 MHz
+ 0x00180E65, //921.25 MHz
+ 0x00180E63, //920.75 MHz
+ };
+ private final int[] vietnam3FreqSortedIdx = new int[]{
+ 2, 3, 1, 0};
+
+ public final int iCountryEnumInfoColumn = 7;
+ public String[] strCountryEnumInfo = {
+ "1", "Albania1", "-1", "4", "Fixed", "600", "865.7",
+ "2", "Albania2", "-2 RW", "23", "Hop", "250", "915.25",
+ "3", "Algeria1", "-1", "4", "Fixed", "600", "871.6",
+ "4", "Algeria2", "-1", "4", "Fixed", "600", "881.6",
+ "5", "Algeria3", "-9", "3", "Fixed", "1200", "916.3",
+ "6", "Algeria4", "-7", "2", "Fixed", "500", "925.25",
+ "7", "Argentina", "-2 RW", "50", "Hop", "500", "902.75",
+ "8", "Armenia", "-1", "4", "Fixed", "600", "865.7",
+ "9", "Australia1", "-2 AS", "10", "Hop", "500", "920.75",
+ "10", "Australia2", "-2 AS", "14", "Hop", "500", "918.75",
+ "11", "Austria1", "-1", "4", "Fixed", "600", "865.7",
+ "12", "Austria2", "-9", "3", "Fixed", "1200", "916.3",
+ "13", "Azerbaijan", "-1", "4", "Fixed", "600", "865.7",
+ "14", "Bahrain", "-1", "4", "Fixed", "600", "865.7",
+ "15", "Bangladesh", "-1", "4", "Fixed", "600", "865.7",
+ "16", "Belarus", "-1", "4", "Fixed", "600", "865.7",
+ "17", "Belgium1", "-1", "4", "Fixed", "600", "865.7",
+ "18", "Belgium2", "-9", "3", "Fixed", "1200", "916.3",
+ "19", "Bolivia", "-2", "50", "Hop", "500", "902.75",
+ "20", "Bosnia", "-1", "4", "Fixed", "600", "865.7",
+ "21", "Botswana", "-1", "4", "Fixed", "600", "865.7",
+ "22", "Brazil1", "-2 RW", "9", "Fixed", "500", "902.75",
+ "23", "Brazil2", "-2 RW", "24", "Fixed", "500", "915.75",
+ "24", "Brunei1", "-1", "4", "Fixed", "600", "865.7",
+ "25", "Brunei2", "-7", "7", "Fixed", "250", "923.25",
+ "26", "Blgaria1", "-1", "4", "Fixed", "600", "865.7",
+ "27", "Bulgaria2", "-9", "3", "Fixed", "1200", "916.3",
+ "28", "Cambodia", "-7", "16", "Hop", "250", "920.625",
+ "29", "Cameroon", "-1", "4", "Fixed", "600", "865.7",
+ "30", "Canada", "-2", "50", "Hop", "500", "902.75",
+ "31", "Chile1", "-2 RW", "3", "Fixed", "1200", "916.3",
+ "32", "Chile2", "-2 RW", "24", "Hop", "500", "915.75",
+ "33", "Chile3", "-2 RW", "4", "Hop", "500", "925.75",
+ "34", "China", "-7", "16", "Hop", "250", "920.625",
+ "35", "Colombia", "-2 RW", "50", "Hop", "500", "902.75",
+ "36", "Congo", "-1", "4", "Fixed", "600", "865.7",
+ "37", "CostaRica", "-2 RW", "50", "Hop", "500", "902.75",
+ "38", "Cotedlvoire", "-1", "4", "Fixed", "600", "865.7",
+ "39", "Croatia", "-1", "4", "Fixed", "600", "865.7",
+ "40", "Cuba", "-2 RW", "50", "Hop", "500", "902.75",
+ "41", "Cyprus1", "-1", "4", "Fixed", "600", "865.7",
+ "42", "Cyprus2", "-9", "3", "Fixed", "1200", "916.3",
+ "43", "Czech1", "-1", "4", "Fixed", "600", "865.7",
+ "44", "Czech2", "-9", "3", "Fixed", "1200", "916.3",
+ "45", "Denmark1", "-1", "4", "Fixed", "600", "865.7",
+ "46", "Denmark2", "-9", "3", "Fixed", "1200", "916.3",
+ "47", "Dominican", "-2 RW", "50", "Hop", "500", "902.75",
+ "48", "Ecuador", "-2 RW", "50", "Hop", "500", "902.75",
+ "49", "Egypt", "-1", "4", "Fixed", "600", "865.7",
+ "50", "ElSalvador", "-2 RW", "50", "Hop", "500", "902.75",
+ "51", "Estonia", "-1", "4", "Fixed", "600", "865.7",
+ "52", "Finland1", "-1", "4", "Fixed", "600", "865.7",
+ "53", "Finland2", "-9", "3", "Fixed", "1200", "916.3",
+ "54", "France", "-1", "4", "Fixed", "600", "865.7",
+ "55", "Georgia", "-1", "4", "Fixed", "600", "865.7",
+ "56", "Germany", "-1", "4", "Fixed", "600", "865.7",
+ "57", "Ghana", "-1", "4", "Fixed", "600", "865.7",
+ "58", "Greece", "-1", "4", "Fixed", "600", "865.7",
+ "59", " Guatemala", "-2 RW", "50", "Hop", "500", "902.75",
+ "60", "HongKong1", "-1", "4", "Fixed", "600", "865.7",
+ "61", "HongKong2", "-2 OFCA", "50", "Hop", "50", "921.25",
+ "62", "Hungary1", "-1", "4", "Fixed", "600", "865.7",
+ "63", "Hungary2", "-9", "3", "Fixed", "1200", "916.3",
+ "64", "Iceland", "-1", "4", "Fixed", "600", "865.7",
+ "65", "India", "-1", "3", "Fixed", "600", "865.7",
+ "66", "Indonesia", "-7", "4", "Hop", "500", "923.75",
+ "67", "Iran", "-1", "4", "Fixed", "600", "865.7",
+ "68", "Ireland1", "-1", "4", "Fixed", "600", "865.7",
+ "69", "Ireland2", "-9", "3", "Fixed", "1200", "916.3",
+ "70", "Israel", "-9", "3", "Fixed", "500", "915.5",
+ "71", "Italy", "-1", "4", "Fixed", "600", "865.7",
+ "72", "Jamaica", "-2 RW", "50", "Hop", "500", "902.75",
+ "73", "Japan4", "-8", "4", "Fixed", "1200", "916.8",
+ "74", "Japan6", "-8", "6", "Fixed", "1200", "916.8",
+ "75", "Jordan", "-1", "4", "Fixed", "600", "865.7",
+ "76", "Kazakhstan", "-1", "4", "Fixed", "600", "865.7",
+ "77", "Kenya", "-1", "4", "Fixed", "600", "865.7",
+ "78", "Korea", "-6", "6", "Hop", "600", "917.3",
+ "79", "KoreaDPR", "-7", "16", "Hop", "250", "920.625",
+ "80", "Kuwait", "-1", "4", "Fixed", "600", "865.7",
+ "81", "Kyrgyz", "-1", "4", "Fixed", "600", "865.7",
+ "82", "Latvia", "-1", "4", "Fixed", "600", "865.7",
+ "83", "Lebanon", "-1", "4", "Fixed", "600", "865.7",
+ "84", "Libya", "-1", "4", "Fixed", "600", "865.7",
+ "85", "Liechtenstein1", "-1", "4", "Fixed", "600", "865.7",
+ "86", "Liechtenstein2", "-9", "3", "Fixed", "1200", "916.3",
+ "87", "Lithuania1", "-1", "4", "Fixed", "600", "865.7",
+ "88", "Lithuania2", "-9", "3", "Fixed", "1200", "916.3",
+ "89", "Luxembourg1", "-1", "4", "Fixed", "600", "865.7",
+ "90", "Luxembourg2", "-9", "3", "Fixed", "1200", "916.3",
+ "91", "Macao", "-7", "16", "Hop", "250", "920.625",
+ "92", "Macedonia", "-1", "4", "Fixed", "600", "865.7",
+ "93", "Malaysia", "-7", "6", "Hop", "500", "919.75",
+ "94", "Malta1", "-1", "4", "Fixed", "600", "865.7",
+ "95", "Malta2", "-9", "3", "Fixed", "1200", "916.3",
+ "96", "Mauritius", "-1", "4", "Fixed", "600", "865.7",
+ "97", "Mexico", "-2", "50", "Hop", "500", "902.75",
+ "98", "Moldova1", "-1", "4", "Fixed", "600", "865.7",
+ "99", "Moldova2", "-9", "3", "Fixed", "1200", "916.3",
+ "100", "Mongolia", "-7", "16", "Hop", "250", "920.625",
+ "101", "Montenegro", "-1", "4", "Fixed", "600", "865.7",
+ "102", "Morocco", "-1", "4", "Fixed", "600", "865.7",
+ "103", "Netherlands", "-1", "4", "Fixed", "600", "865.7",
+ "104", "NewZealand1", "-1", "4", "Hop", "500", "864.75",
+ "105", "NewZealand2", "-2 NZ", "14", "Hop", "500", "920.75",
+ "106", "Nicaragua", "-2 RW", "50", "Hop", "500", "902.75",
+ "107", "Nigeria", "-1", "4", "Fixed", "600", "865.7",
+ "108", "Norway1", "-1", "4", "Fixed", "600", "865.7",
+ "109", "Norway2", "-9", "3", "Fixed", "1200", "916.3",
+ "110", "Oman", "-1", "4", "Fixed", "600", "865.7",
+ "111", "Pakistan", "-1", "4", "Fixed", "600", "865.7",
+ "112", "Panama", "-2 RW", "50", "Hop", "500", "902.75",
+ "113", "Paraguay", "-2 RW", "50", "Hop", "500", "902.75",
+ "114", "Peru", "-2 RW", "24", "Hop", "500", "915.75",
+ "115", "Philippines", "-2 RW", "50", "Hop", "250", "918.125",
+ "116", "Poland", "-1", "4", "Fixed", "600", "865.7",
+ "117", "Portugal", "-1", "4", "Fixed", "600", "865.7",
+ "118", "Romania", "-1", "4", "Fixed", "600", "865.7",
+ "119", "Russia1", "-1", "4", "Fixed", "600", "866.3",
+ "120", "Russia3", "-9", "4", "Fixed", "1200", "915.6",
+ "121", "Senegal", "-1", "4", "Fixed", "600", "865.7",
+ "122", "Serbia", "-1", "4", "Fixed", "600", "865.7",
+ "123", "Singapore1", "-1", "4", "Fixed", "600", "865.7",
+ "124", "Singapore2", "-2 RW", "8", "Hop", "500", "920.75",
+ "125", "Slovak1", "-1", "4", "Fixed", "600", "865.7",
+ "126", "Slovak2", "-9", "3", "Fixed", "1200", "916.3",
+ "127", "Slovenia1", "-1", "4", "Fixed", "600", "865.7",
+ "128", "Solvenia2", "-9", "3", "Fixed", "1200", "916.3",
+ "129", "SAfrica1", "-1", "4", "Fixed", "600", "865.7",
+ "130", "SAfrica2", "-9", "7", "Fixed", "500", "915.7",
+ "131", "Spain", "-1", "4", "Fixed", "600", "865.7",
+ "132", "SriLanka", "-1", "4", "Fixed", "600", "865.7",
+ "133", "Sudan", "-1", "4", "Fixed", "600", "865.7",
+ "134", "Sweden1", "-1", "4", "Fixed", "600", "865.7",
+ "135", "Sweden2", "-9", "3", "Fixed", "1200", "916.3",
+ "136", "Switzerland1", "-1", "4", "Fixed", "600", "865.7",
+ "137", "Switzerland2", "-9", "3", "Fixed", "1200", "916.3",
+ "138", "Syria", "-1", "4", "Fixed", "600", "865.7",
+ "139", "Taiwan1", "-4", "12", "Hop", "375", "922.875",
+ "140", "Taiwan2", "-4", "12", "Hop", "375", "922.875",
+ "141", "Tajikistan", "-1", "4", "Fixed", "600", "865.7",
+ "142", "Tanzania", "-1", "4", "Fixed", "600", "865.7",
+ "143", "Thailand", "-2 RW", "8", "Hop", "500", "920.75",
+ "144", "Trinidad", "-2 RW", "50", "Hop", "500", "902.75",
+ "145", "Tunisia", "-1", "4", "Fixed", "600", "865.7",
+ "146", "Turkey", "-1", "4", "Fixed", "600", "865.7",
+ "147", "Turkmenistan", "-1", "4", "Fixed", "600", "865.7",
+ "148", "Uganda", "-1", "4", "Fixed", "600", "865.7",
+ "149", "Ukraine", "-1", "4", "Fixed", "600", "865.7",
+ "150", "UAE", "-1", "4", "Fixed", "600", "865.7",
+ "151", "UK1", "-1", "4", "Fixed", "600", "865.7",
+ "152", "UK2", "-9", "3", "Fixed", "1200", "916.3",
+ "153", "USA", "-2", "50", "Hop", "500", "902.75",
+ "154", "Uruguay", "-2 RW", "50", "Hop", "500", "902.75",
+ "155", "Venezuela", "-2 RW", "50", "Hop", "500", "902.75",
+ "156", "Vietnam1", "-1", "4", "Fixed", "600", "866.3",
+ "157", "Vietnam2", "-7", "16", "Hop", "500", "918.75",
+ "158", "Yemen", "-1", "4", "Fixed", "600", "865.7",
+ "159", "Zimbabwe", "-1", "4", "Fixed", "600", "865.7",
+ "160", "Vietnam3", "-7", "4", "Hop", "500", "920.75"
+ };
+ }
+/*
+ boolean setChannelData(RegionCodes regionCode) {
+ return true;
+ }
+ private void SetFrequencyBand (UInt32 frequencySelector, BandState config, UInt32 multdiv, UInt32 pllcc)
+ {
+ MacWriteRegister(MACREGISTER.HST_RFTC_FRQCH_SEL, frequencySelector);
+
+ MacWriteRegister(MACREGISTER.HST_RFTC_FRQCH_CFG, (uint)config);
+
+ if (config == BandState.ENABLE)
+ {
+ MacWriteRegister(MACREGISTER.HST_RFTC_FRQCH_DESC_PLLDIVMULT, multdiv);
+
+ MacWriteRegister(MACREGISTER.HST_RFTC_FRQCH_DESC_PLLDACCTL, pllcc);
+ }
+ }
+*/
+ public double[] GetAvailableFrequencyTable(RegionCodes regionCode) {
+ double[] freqText = null;
+ if (bis108) {
+ switch (regionCode) {
+ case FCC:
+ case AG:
+ case CL:
+ case CO:
+ case CR:
+ case DR:
+ case MX:
+ case PM:
+ case UG:
+// switch (mRfidDevice.mRx000Device.mRx000OemSetting.getVersionCode()) {
+// case 0:
+// return FCCTableOfFreq0;
+// case 1:
+// return FCCTableOfFreq1;
+// default:
+// return FCCTableOfFreq;
+// }
+ return countryChannelData.FCCTableOfFreq;
+ case PR:
+ return countryChannelData.PRTableOfFreq;
+ case VZ:
+ return countryChannelData.VZTableOfFreq;
+ case AU:
+ return countryChannelData.AUSTableOfFreq;
+ case BR1:
+ return countryChannelData.BR1TableOfFreq;
+ case BR2:
+ return countryChannelData.BR2TableOfFreq;
+ case BR3:
+ return countryChannelData.BR3TableOfFreq;
+ case BR4:
+ return countryChannelData.BR4TableOfFreq;
+ case BR5:
+ return countryChannelData.BR5TableOfFreq;
+ case HK:
+ case SG:
+ case TH:
+ case VN:
+ return countryChannelData.HKTableOfFreq;
+ case VN1:
+ return countryChannelData.VN1TableOfFreq;
+ case VN2:
+ return countryChannelData.VN2TableOfFreq;
+ case VN3:
+ return countryChannelData.VN3TableOfFreq;
+ case BD:
+ return countryChannelData.BDTableOfFreq;
+ case TW:
+ return countryChannelData.TWTableOfFreq;
+ case MY:
+ return countryChannelData.MYSTableOfFreq;
+ case ZA:
+ return countryChannelData.ZATableOfFreq;
+ case ID:
+ return countryChannelData.IDTableOfFreq;
+ case IL:
+ return countryChannelData.ILTableOfFreq;
+ case IL2019RW:
+ return countryChannelData.IL2019RWTableOfFreq;
+ case PH:
+ return countryChannelData.PHTableOfFreq;
+ case NZ:
+ return countryChannelData.NZTableOfFreq;
+ case CN:
+ return countryChannelData.CHNTableOfFreq;
+
+ case UH1:
+ return countryChannelData.UH1TableOfFreq;
+ case UH2:
+ return countryChannelData.UH2TableOfFreq;
+ case LH:
+ return countryChannelData.LHTableOfFreq;
+ case LH1:
+ return countryChannelData.LH1TableOfFreq;
+ case LH2:
+ return countryChannelData.LH2TableOfFreq;
+
+ case ETSI:
+ appendToLog("Got ETSI Table of Frequencies");
+ return countryChannelData.ETSITableOfFreq;
+ case IN:
+ return countryChannelData.IDATableOfFreq;
+ case KR:
+ return countryChannelData.KRTableOfFreq;
+ case KR2017RW:
+ return countryChannelData.KR2017RwTableOfFreq;
+ case JP:
+ return countryChannelData.JPN2012TableOfFreq;
+ case JP6:
+ return countryChannelData.JPN2012ATableOfFreq;
+ case ETSIUPPERBAND:
+ return countryChannelData.ETSIUPPERBANDTableOfFreq;
+
+ default:
+ return new double[0];
+ }
+ } else {
+ int iRegionEnum = regionCode.ordinal() - RegionCodes.Albania1.ordinal() + 1;
+ if (DEBUG) appendToLog("regionCode = " + regionCode.toString() + ", iRegionEnum = " + iRegionEnum);
+
+ String strChannelCount = countryChannelData.strCountryEnumInfo[(iRegionEnum - 1) * countryChannelData.iCountryEnumInfoColumn + 3];
+ int iChannelCount = -1;
+ try {
+ iChannelCount = Integer.parseInt(strChannelCount);
+ } catch (Exception ex) { }
+ if (DEBUG) appendToLog("strChannelCount = " + strChannelCount + ", iChannelCount = " + iChannelCount);
+
+ String strChannelSeparation = countryChannelData.strCountryEnumInfo[(iRegionEnum - 1) * countryChannelData.iCountryEnumInfoColumn + 5];
+ int iChannelSeparation = -1;
+ try {
+ iChannelSeparation = Integer.parseInt(strChannelSeparation);
+ } catch (Exception ex) { }
+ if (DEBUG) appendToLog("strChannelSeparation = " + strChannelSeparation + ",iChannelSeparation = " + iChannelSeparation);
+
+ String strChannelFirst = countryChannelData.strCountryEnumInfo[(iRegionEnum - 1) * countryChannelData.iCountryEnumInfoColumn + 6];
+ double dChannelFirst = -1;
+ try {
+ dChannelFirst = Double.parseDouble(strChannelFirst);
+ } catch (Exception ex) { }
+ if (DEBUG) appendToLog("strChannelFirst = " + strChannelFirst + ", dChannelFirst = " + dChannelFirst);
+
+ if (iChannelCount > 0) {
+ freqText = new double[iChannelCount];
+ for (int i = 0; i < iChannelCount; i++) {
+ freqText[i] = dChannelFirst + ((double) iChannelSeparation) / 1000 * i;
+ if (DEBUG) appendToLog("Frequency freqTable[" + i + "] = " + freqText[i]);
+ }
+ }
+ return freqText;
+ }
+ }
+ public int[] FreqIndex(RegionCodes regionCode) {
+ if (bis108) {
+ switch (regionCode) {
+ case FCC:
+ case AG:
+ case CL:
+ case CO:
+ case CR:
+ case DR:
+ case MX:
+ case PM:
+ case UG:
+// switch (mRfidDevice.mRx000Device.mRx000OemSetting.getVersionCode()) {
+// case 0:
+// return fccFreqSortedIdx0;
+// case 1:
+// return fccFreqSortedIdx1;
+// default:
+// return fccFreqSortedIdx;
+// }
+ return countryChannelData.fccFreqSortedIdx;
+ case PR:
+ if (freqSortedIdx == null) {
+ freqSortedIdx = new int[countryChannelData.PRTableOfFreq.length];
+ if (DEBUG) appendToLog("PR: freqSortedIdx size = " + freqSortedIdx.length);
+ ArrayList list = new ArrayList();
+ for (int i = 0; i < freqSortedIdx.length; i++) list.add(new Integer(i));
+ Collections.shuffle(list);
+ for (int i = 0; i < freqSortedIdx.length; i++) {
+ freqSortedIdx[i] = list.get(i);
+ if (DEBUG) appendToLog("PR: Random Value = " + freqSortedIdx[i]);
+ }
+ }
+ return freqSortedIdx;
+ case VZ:
+ return countryChannelData.vzFreqSortedIdx;
+ case AU:
+ return countryChannelData.ausFreqSortedIdx;
+ case BR1:
+ return countryChannelData.br1FreqSortedIdx;
+ case BR2:
+ return countryChannelData.br2FreqSortedIdx;
+ case BR3:
+ return countryChannelData.br3FreqSortedIdx;
+ case BR4:
+ return countryChannelData.br4FreqSortedIdx;
+ case BR5:
+ return countryChannelData.br5FreqSortedIdx;
+ case HK:
+ case SG:
+ case TH:
+ case VN:
+ return countryChannelData.hkFreqSortedIdx;
+ case VN1:
+ return countryChannelData.vietnam1FreqSortedIdx;
+ case VN2:
+ return countryChannelData.vietnam2FreqSortedIdx;
+ case VN3:
+ return countryChannelData.vietnam3FreqSortedIdx;
+ case BD:
+ return countryChannelData.bdFreqSortedIdx;
+ case TW:
+ return countryChannelData.twFreqSortedIdx;
+ case MY:
+ return countryChannelData.mysFreqSortedIdx;
+ case ZA:
+ return countryChannelData.zaFreqSortedIdx;
+ case ID:
+ return countryChannelData.indonesiaFreqSortedIdx;
+ case IL:
+ return countryChannelData.ilFreqSortedIdx;
+ case IL2019RW:
+ return countryChannelData.il2019RwFreqSortedIdx;
+ case PH:
+ return countryChannelData.phFreqSortedIdx;
+ case NZ:
+ return countryChannelData.nzFreqSortedIdx;
+ case CN:
+ return countryChannelData.cnFreqSortedIdx;
+
+ case UH1:
+ return countryChannelData.uh1FreqSortedIdx;
+ case UH2:
+ return countryChannelData.uh2FreqSortedIdx;
+ case LH:
+ return countryChannelData.lhFreqSortedIdx;
+ case LH1:
+ return countryChannelData.lh1FreqSortedIdx;
+ case LH2:
+ return countryChannelData.lh2FreqSortedIdx;
+
+ case ETSI:
+ return countryChannelData.etsiFreqSortedIdx;
+ case IN:
+ return countryChannelData.indiaFreqSortedIdx;
+ case KR:
+ return countryChannelData.krFreqSortedIdx;
+ case KR2017RW:
+ return countryChannelData.kr2017RwFreqSortedIdx;
+ case JP:
+ return countryChannelData.jpn2012FreqSortedIdx;
+ case JP6:
+ return countryChannelData.jpn2012AFreqSortedIdx;
+ case ETSIUPPERBAND:
+ return countryChannelData.etsiupperbandFreqSortedIdx;
+
+ default:
+ return null;
+ }
+ } else {
+ int[] iFreqSortedIdx = null;
+ int iFreqChnCnt = FreqChnCnt(regionCode);
+ if (iFreqChnCnt > 0) {
+ iFreqSortedIdx = new int[iFreqChnCnt];
+ for (int i = 0; i < iFreqChnCnt; i++) {
+ iFreqSortedIdx[i] = (byte)i;
+ if (false) appendToLog("Frequency index[" + i + "] = " + iFreqSortedIdx[i]);
+ }
+ }
+ return iFreqSortedIdx;
+ }
+ }
+ public int[] FreqTable(RegionCodes regionCode) {
+ switch (regionCode) {
+ case FCC:
+ case AG:
+ case CL:
+ case CO:
+ case CR:
+ case DR:
+ case MX:
+ case PM:
+ case UG:
+// int[] freqTableIdx = fccFreqTableIdx;
+// int[] freqSortedIdx;
+// int[] freqTable = new int[50];
+// if (DEBUG) appendToLog("gerVersionCode = " + mRfidDevice.mRx000Device.mRx000OemSetting.getVersionCode());
+// switch (mRfidDevice.mRx000Device.mRx000OemSetting.getVersionCode()) {
+// case 0:
+// freqSortedIdx = fccFreqSortedIdx0;
+// break;
+// case 1:
+// freqSortedIdx = fccFreqSortedIdx1;
+// break;
+// default:
+// freqSortedIdx = fccFreqSortedIdx;
+// break;
+// }
+// for (int i = 0; i < 50; i++) {
+// freqTable[i] = fccFreqTable[fccFreqTableIdx[freqSortedIdx[i]]];
+// if (DEBUG) appendToLog("i = " + i + ", freqSortedIdx = " + freqSortedIdx[i] + ", fccFreqTableIdx = " + fccFreqTableIdx[freqSortedIdx[i]] + ", freqTable[" + i + "] = " + freqTable[i]);
+// }
+// return freqTable;
+ return countryChannelData.fccFreqTable;
+ case PR:
+ int[] freqSortedIndex = FreqIndex(regionCode);
+ int[] freqTable = null;
+ if (freqSortedIndex != null) {
+ freqTable = new int[freqSortedIndex.length];
+ for (int i = 0; i < freqSortedIndex.length; i++) {
+ int j = 0;
+ for (; j < countryChannelData.FCCTableOfFreq.length; j++) {
+ if (countryChannelData.FCCTableOfFreq[j] == countryChannelData.PRTableOfFreq[freqSortedIndex[i]]) break;
+ }
+ freqTable[i] = countryChannelData.fccFreqTable[countryChannelData.fccFreqTableIdx[j]];
+ }
+ } else
+ if (DEBUG) appendToLog("NULL freqSortedIndex");
+ return freqTable; // return prFreqTable;
+ case VZ:
+ return countryChannelData.vzFreqTable;
+ case AU:
+ return countryChannelData.AusFreqTable;
+
+ case BR1:
+ return countryChannelData.br1FreqTable;
+ case BR2:
+ return countryChannelData.br2FreqTable;
+ case BR3:
+ return countryChannelData.br3FreqTable;
+ case BR4:
+ return countryChannelData.br4FreqTable;
+ case BR5:
+ return countryChannelData.br5FreqTable;
+
+ case HK:
+ case SG:
+ case TH:
+ case VN:
+ return countryChannelData.hkFreqTable;
+ case VN1:
+ return countryChannelData.vietnam1FreqTable;
+ case VN2:
+ return countryChannelData.vietnam2FreqTable;
+ case VN3:
+ return countryChannelData.vietnam3FreqTable;
+ case BD:
+ return countryChannelData.bdFreqTable;
+ case TW:
+ return countryChannelData.twFreqTable;
+ case MY:
+ return countryChannelData.mysFreqTable;
+ case ZA:
+ return countryChannelData.zaFreqTable;
+
+ case ID:
+ return countryChannelData.indonesiaFreqTable;
+ case IL:
+ return countryChannelData.ilFreqTable;
+ case IL2019RW:
+ return countryChannelData.il2019RwFreqTable;
+ case PH:
+ return countryChannelData.phFreqTable;
+ case NZ:
+ return countryChannelData.nzFreqTable;
+ case CN:
+ return countryChannelData.cnFreqTable;
+
+ case UH1:
+ return countryChannelData.uh1FreqTable;
+ case UH2:
+ return countryChannelData.uh2FreqTable;
+ case LH:
+ return countryChannelData.lhFreqTable;
+ case LH1:
+ return countryChannelData.lh1FreqTable;
+ case LH2:
+ return countryChannelData.lh2FreqTable;
+
+ case ETSI:
+ return countryChannelData.etsiFreqTable;
+ case IN:
+ return countryChannelData.indiaFreqTable;
+ case KR:
+ return countryChannelData.krFreqTable;
+ case KR2017RW:
+ return countryChannelData.kr2017RwFreqTable;
+ case JP:
+ return countryChannelData.jpn2012FreqTable;
+ case JP6:
+ return countryChannelData.jpn2012AFreqTable;
+ case ETSIUPPERBAND:
+ return countryChannelData.etsiupperbandFreqTable;
+
+ default:
+ return null;
+ }
+ }
+ private long GetPllcc(RegionCodes regionCode) {
+ switch (regionCode) {
+ case ETSI:
+ case IN:
+ return 0x14070400; //Notice: the read value is 0x14040400
+ }
+ return 0x14070200; //Notice: the read value is 0x14020200
+ }
+ private boolean FreqChnWithinRange(int Channel, RegionCodes regionCode) {
+ int TotalCnt = FreqChnCnt(regionCode);
+ if (TotalCnt <= 0) return false;
+ if (Channel >= 0 && Channel < TotalCnt) return true;
+ return false;
+ }
+ private int FreqSortedIdxTbls(RegionCodes regionCode, int Channel) {
+ int TotalCnt = FreqChnCnt(regionCode);
+ int[] freqIndex = FreqIndex(regionCode);
+ if (!FreqChnWithinRange(Channel, regionCode) || freqIndex == null)
+ return -1;
+ for (int i = 0; i < TotalCnt; i++) {
+ if (freqIndex[i] == Channel) return i;
+ }
+ return -1;
+ }
+ byte tagDelayDefaultCompactSetting = 0;
+ public byte tagDelayDefaultNormalSetting = 30;
+ public byte tagDelaySettingDefault = tagDelayDefaultCompactSetting, tagDelaySetting = tagDelaySettingDefault;
+ public long cycleDelaySettingDefault = 0, cycleDelaySetting = cycleDelaySettingDefault;
+ /*
+ byte[] string2ByteArray(String string) {
+ byte[] bytes = null;
+ if (string == null) return null;
+ if ((string.length()/2)*2 != string.length()) string += "0";
+ for (int i = 0; i < string.length(); i+=2) {
+ try {
+ Short sValue = Short.parseShort(string.substring(i, i + 2), 16);
+ byte[] bytesNew = new byte[1];
+ if (bytes != null) {
+ bytesNew = new byte[bytes.length + 1];
+ System.arraycopy(bytes, 0, bytesNew, 0, bytes.length);
+ }
+ bytesNew[bytesNew.length - 1] = (byte) (sValue & 0xFF);
+ bytes = bytesNew;
+ } catch (Exception ex) {
+ appendToLog("Exception in i = " + i + ", substring = " + string.substring(i, i+2));
+ break;
+ }
+ }
+ return bytes;
+ }
+*/
+ public boolean starAuthOperation() {
+ if (bis108) {
+ rfidReaderChipR2000.setPwrManagementMode(false);
+ return rfidReaderChipR2000.sendHostRegRequestHST_CMD(RfidReaderChipData.HostCommands.CMD_18K6CAUTHENTICATE);
+ }
+ rfidReaderChipE710.setPwrManagementMode(false);
+ return rfidReaderChipE710.sendHostRegRequestHST_CMD(RfidReaderChipData.HostCommands.CMD_18K6CAUTHENTICATE);
+ }
+
+ //============ Rfid ============
+ //============ Rfid ============
+
+ public String getAuthMatchData() {
+ int iValue1 = 96;
+ String strValue;
+ if (bis108) strValue = rfidReaderChipR2000.rx000Setting.getAuthMatchData();
+ else strValue = rfidReaderChipE710.rx000Setting.getAuthMatchData();
+ if (strValue == null) return null;
+ int strLength = iValue1 / 4;
+ if (strLength * 4 != iValue1) strLength++;
+ return strValue.substring(0, strLength);
+ }
+ public boolean setAuthMatchData(String mask) {
+ boolean result = false;
+ if (mask != null) {
+ if (bis108) result = rfidReaderChipR2000.rx000Setting.setAuthMatchData(mask);
+ else result = rfidReaderChipE710.rx000Setting.setAuthenticateMessage(mask.getBytes());
+ }
+ return result;
+ }
+ public int getStartQValue() {
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.getAlgoStartQ(3) : rfidReaderChipE710.rx000Setting.getAlgoStartQ(3));
+ }
+ public int getMaxQValue() {
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.getAlgoMaxQ(3) : rfidReaderChipE710.rx000Setting.getAlgoMaxQ(3));
+ }
+ public int getMinQValue() {
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.getAlgoMinQ(3) : rfidReaderChipE710.rx000Setting.getAlgoMinQ(3));
+ }
+ public boolean setDynamicQParms(int startQValue, int minQValue, int maxQValue, int retryCount) {
+ appendToLog("setTagGroup: going to setAlgoSelect with input as 3");
+ boolean result;
+ result = (bis108 ? rfidReaderChipR2000.rx000Setting.setAlgoSelect(3) : rfidReaderChipE710.rx000Setting.setAlgoSelect(3));
+ if (result) {
+ result = (bis108 ? rfidReaderChipR2000.rx000Setting.setAlgoStartQ(startQValue, maxQValue, minQValue, -1, -1, -1) : rfidReaderChipE710.rx000Setting.setAlgoStartQ(startQValue, maxQValue, minQValue, -1, -1, -1));
+ }
+ if (result) result = setRetryCount(retryCount);
+ return result;
+ }
+ public int getFixedQValue() {
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.getAlgoStartQ(0) : rfidReaderChipE710.rx000Setting.getAlgoStartQ(0));
+ }
+ public int getFixedRetryCount() {
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.getAlgoRetry(0) : rfidReaderChipE710.rx000Setting.getAlgoMinQCycles());
+ }
+ public boolean getRepeatUnitNoTags() {
+ if (bis108) return rfidReaderChipR2000.rx000Setting.getAlgoRunTilZero(0) == 1 ? true : false;
+ return rfidReaderChipE710.rx000Setting.getAlgoRunTilZero(0) == 1 ? true : false;
+ }
+ public boolean setFixedQParms(int qValue, int retryCount, boolean repeatUnitNoTags) {
+ boolean result, DEBUG = false;
+ if (DEBUG) appendToLog("qValue=" + qValue + ", retryCount = " + retryCount + ", repeatUntilNoTags = " + repeatUnitNoTags);
+ result = (bis108 ? rfidReaderChipR2000.rx000Setting.setAlgoSelect(0) : rfidReaderChipE710.rx000Setting.setAlgoSelect(0));
+ if (DEBUG) appendToLog("after setAlgoSelect, result = " + result);
+ if (qValue == getFixedQValue() && retryCount == getFixedRetryCount() && repeatUnitNoTags == getRepeatUnitNoTags()) {
+ appendToLog("!!! Skip repeated repeated data with qValue=" + qValue + ", retryCount = " + retryCount + ", repeatUntilNoTags = " + repeatUnitNoTags);
+ return true;
+ }
+
+ if (result) {
+ result = (bis108 ? rfidReaderChipR2000.rx000Setting.setAlgoStartQ(qValue, -1, -1, -1, -1, -1) : rfidReaderChipE710.rx000Setting.setAlgoStartQ(qValue));
+ }
+ if (result) result = setRetryCount(retryCount);
+ if (result) {
+ result = (bis108 ? rfidReaderChipR2000.rx000Setting.setAlgoRunTilZero(repeatUnitNoTags ? 1 : 0) : rfidReaderChipE710.rx000Setting.setAlgoRunTilZero(repeatUnitNoTags ? 1 : 0));
+ }
+ return result;
+ }
+
+ public static class PreMatchData {
+ public boolean enable; public int target;
+ public int action; public int bank;
+ public int offset; public String mask; public int maskblen; public int querySelect; public long pwrlevel; public boolean invAlgo; public int qValue;
+ public PreMatchData(boolean enable, int target, int action, int bank, int offset, String mask, int maskblen, int querySelect, long pwrlevel, boolean invAlgo, int qValue) {
+ this.enable = enable;
+ this.target = target;
+ this.action = action;
+ this.bank = bank;
+ this.offset = offset;
+ this.mask = mask;
+ this.maskblen = maskblen;
+ this.querySelect = querySelect;
+ this.pwrlevel = pwrlevel;
+ this.invAlgo = invAlgo;
+ this.qValue = qValue;
+ }
+ }
+ public PreMatchData preMatchData;
+ public boolean setOnlyPowerLevel(long pwrlevel) {
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.setAntennaPower(pwrlevel) : rfidReaderChipE710.rx000Setting.setAntennaPower(pwrlevel));
+ }
+
+ boolean[] bSelectEnabled = { false, false, false };
+ boolean setSelectCriteria3(int index, boolean enable, int target, int action, int delay, int bank, int offset, String mask, int maskblen) {
+ boolean DEBUG = false;
+ if (utility.DEBUG_SELECT) appendToLog("Debug_Select: RfidReader.setSelectCriteria3 with index = " + index + ", enable = " + enable + ", bSelectEnable = " + bSelectEnabled[index]
+ + ", target = " + target + ", action = " + action + ", delay = " + delay
+ + ", bank = " + bank + ", offset = " + offset + ", mask = " + mask + ", maskbitlen = " + maskblen);
+ if (!enable) {
+ if (bSelectEnabled[index] = false) return true;
+ }
+ int maskbytelen = maskblen / 4; if ((maskblen % 4) != 0) maskbytelen++; if (maskbytelen > 64) maskbytelen = 64;
+ if (mask == null) mask = "";
+ if (mask.length() > maskbytelen ) mask = mask.substring(0, maskbytelen);
+ if (index == 0) preMatchData = new RfidReader.PreMatchData(enable, target, action, bank, offset, mask, maskblen,
+ (bis108 ? rfidReaderChipR2000.rx000Setting.getQuerySelect() : rfidReaderChipE710.rx000Setting.getQuerySelect()), getPwrlevel(), getInvAlgo(), getQValue());
+ boolean result = true;
+ if (index != (bis108 ? rfidReaderChipR2000.rx000Setting.getInvSelectIndex() : rfidReaderChipE710.rx000Setting.getInvSelectIndex())) {
+ if (utility.DEBUG_SELECT) appendToLog("Debug_Select: RfidReader.setSelectCriteria3 goes to setInvSelectIndex");
+ result = (bis108 ? rfidReaderChipR2000.rx000Setting.setInvSelectIndex(index) : rfidReaderChipE710.rx000Setting.setInvSelectIndex(index));
+ if (DEBUG) appendToLog("After setInvSelectIndex, result = " + result);
+ }
+ if (utility.DEBUG_SELECT) appendToLog("Debug_Select: RfidReader.setSelectCriteria3 goes to setSelectEnable");
+ if (result) result = (bis108 ? rfidReaderChipR2000.rx000Setting.setSelectEnable(enable ? 1 : 0, target, action, delay) : rfidReaderChipE710.rx000Setting.setSelectEnable(enable ? 1 : 0, target, action, delay));
+ if (DEBUG) appendToLog("After setSelectEnable, result = " + result);
+ if (result) result = (bis108 ? rfidReaderChipR2000.rx000Setting.setSelectMaskBank(bank) : rfidReaderChipE710.rx000Setting.setSelectMaskBank(bank));
+ if (DEBUG) appendToLog("After setSelectMaskBank, result = " + result);
+ if (result) result = (bis108 ? rfidReaderChipR2000.rx000Setting.setSelectMaskOffset(offset) : rfidReaderChipE710.rx000Setting.setSelectMaskOffset(offset));
+ if (DEBUG) appendToLog("After setSelectMaskOffset, result = " + result + " and mask = " + mask);
+ if (mask == null) return false;
+ if (result) result = (bis108 ? rfidReaderChipR2000.rx000Setting.setSelectMaskLength(maskblen) : rfidReaderChipE710.rx000Setting.setSelectMaskLength(maskblen));
+ if (DEBUG) appendToLog("After setSelectMaskLength, result = " + result);
+ if (result) result = (bis108 ? rfidReaderChipR2000.rx000Setting.setSelectMaskData(mask) : rfidReaderChipE710.rx000Setting.setSelectMaskData(mask));
+ if (DEBUG) appendToLog("After setSelectMaskData, result = " + result);
+ if (result) {
+ //appendToLog("BtDataOut: RfidReader.setSelectCriteria3 with enable = " + enable);
+ if (enable) {
+ result = (bis108 ? rfidReaderChipR2000.rx000Setting.setTagSelect(1) : rfidReaderChipE710.rx000Setting.setTagSelect(1));
+ if (DEBUG) appendToLog("After setTagSelect[1], result = " + result);
+ if (result) result = (bis108 ? rfidReaderChipR2000.rx000Setting.setQuerySelect(3) : rfidReaderChipE710.rx000Setting.setQuerySelect(3));
+ if (DEBUG) appendToLog("After setQuerySelect[3], result = " + result);
+ } else {
+ result = (bis108 ? rfidReaderChipR2000.rx000Setting.setTagSelect(0) : rfidReaderChipE710.rx000Setting.setTagSelect(0));
+ if (DEBUG) appendToLog("After setTagSelect[0], result = " + result);
+ if (result) result = (bis108 ? rfidReaderChipR2000.rx000Setting.setQuerySelect(0) : rfidReaderChipE710.rx000Setting.setQuerySelect(0));
+ if (DEBUG) appendToLog("After setQuerySelect[0], result = " + result);
+ }
+ }
+ if (result) {
+ bSelectEnabled[index] = enable;
+ }
+ return result;
+ }
+ public PostMatchData postMatchDataOld; public boolean postMatchDataChanged = false;
+ public RfidReader.PreMatchData preMatchDataOld; public boolean preMatchDataChanged = false;
+ public boolean setSelectedTag1(boolean selectOne, String selectMask, int selectBank, int selectOffset, int delay, long pwrlevel, int qValue, int matchRep) {
+ if (utility.DEBUG_SELECT) appendToLog("Debug_Select: RfidReader.setSelectedTag1[selectOne = " + selectOne + ", selectMask = "
+ + selectMask + ", selectBank = " + selectBank + ", selectOffset = " + selectOffset + ", delay = "
+ + delay + ", pwrlevel = " + pwrlevel + ", qValue = " + qValue + ", matchRep = " + matchRep);
+ boolean setSuccess = true, DEBUG = false;
+ if (selectMask == null) selectMask = "";
+
+ if (preMatchDataChanged == false) {
+ preMatchDataChanged = true; if (DEBUG) appendToLog("setSelectCriteria preMatchDataChanged is SET with preMatchData = " + (preMatchData != null ? "valid" : "null"));
+ if (preMatchData == null) {
+ preMatchData = new RfidReader.PreMatchData(false,
+ (bis108 ? rfidReaderChipR2000.rx000Setting.getQueryTarget() : rfidReaderChipE710.rx000Setting.getQueryTarget()), 0, 0, 0, "", 0,
+ (bis108 ? rfidReaderChipR2000.rx000Setting.getQuerySelect() : rfidReaderChipE710.rx000Setting.getQuerySelect()), getPwrlevel(), getInvAlgo(), getQValue());
+ }
+ preMatchDataOld = preMatchData;
+ }
+ int indexCurrent = (bis108 ? rfidReaderChipR2000.rx000Setting.invSelectIndex : rfidReaderChipE710.rx000Setting.invSelectIndex);
+ for (int i = 0; i < 7; i++) {
+ if (utility.DEBUG_SELECT) appendToLog("Debug_Select: RfidReader.setSelectedTag1 1 goes to setInvSelectIndex with i = " + i);
+ if (bis108) rfidReaderChipR2000.rx000Setting.setInvSelectIndex(i); else rfidReaderChipE710.rx000Setting.setInvSelectIndex(i);
+ int isEnabled = (bis108 ? rfidReaderChipR2000.rx000Setting.getSelectEnable() : rfidReaderChipE710.rx000Setting.getSelectEnable());
+ if (isEnabled == 0 || selectOne) {
+ if (utility.DEBUG_SELECT) appendToLog("Debug_Select: RfidReader.setSelectedTag1. goes to setSelectCriteria3");
+ setSuccess = setSelectCriteria3(i, true, 4, 0, delay, selectBank, selectOffset, selectMask, selectMask.length() * 4);
+ if (DEBUG) appendToLog("setSelectCriteria after setSelectCriteria, setSuccess = " + setSuccess);
+ break;
+ }
+ }
+ if (utility.DEBUG_SELECT) appendToLog("Debug_Select: RfidReader.setSelectedTag1 2 goes to setInvSelectIndex with indexCurrent = " + indexCurrent);
+ if (bis108) rfidReaderChipR2000.rx000Setting.setInvSelectIndex(indexCurrent); else rfidReaderChipE710.rx000Setting.setInvSelectIndex(indexCurrent);
+
+ if (setSuccess) setSuccess = setOnlyPowerLevel(pwrlevel);
+ if (DEBUG) appendToLog("setSelectCriteria after setOnlyPowerLevel, setSuccess = " + setSuccess);
+ if (false) {
+ if (setSuccess) setSuccess = setFixedQParms(qValue, 5, false);
+ if (DEBUG) appendToLog("setSelectCriteria after setFixedQParms, setSuccess = " + setSuccess);
+ if (setSuccess) setSuccess = (bis108 ? rfidReaderChipR2000.rx000Setting.setAlgoAbFlip(1) : rfidReaderChipE710.rx000Setting.setAlgoAbFlip(1));
+ if (DEBUG) appendToLog("setSelectCriteria after setAlgoAbFlip, setSuccess = " + setSuccess);
+ if (setSuccess) setSuccess = setInvAlgo1(false);
+ if (DEBUG) appendToLog("setSelectCriteria after setInvAlgo1, setSuccess = " + setSuccess);
+ }
+
+ if (utility.DEBUG_INVCFG) appendToLog("Debug_InvCfg: RfidReader.setSelectTag1 goes to setMatchRep with matchRep = " + matchRep);
+ if (setSuccess) setSuccess = setMatchRep(matchRep);
+ if (DEBUG) appendToLog("setSelectCriteria after setMatchRep, setSuccess = " + setSuccess);
+ if (setSuccess) setSuccess = setTagDelay2RfidReader(tagDelayDefaultNormalSetting);
+ if (DEBUG) appendToLog("setSelectCriteria after setTagDelay, setSuccess = " + setSuccess);
+ if (setSuccess) setSuccess = (bis108 ? rfidReaderChipR2000.rx000Setting.setCycleDelay(cycleDelaySetting) : rfidReaderChipE710.rx000Setting.setCycleDelay(cycleDelaySetting));
+ if (DEBUG) appendToLog("setSelectCriteria after setCycleDelay, setSuccess = " + setSuccess);
+ if (utility.DEBUG_COMPACT) appendToLog("Debug_Compact 3: RfidReadder.setSelectedTag1 goes to setInvModeCompact");
+ if (setSuccess) setSuccess = setInvModeCompact(false);
+ if (DEBUG) appendToLog("setSelectCriteria after setInvModeCompact, setSuccess = " + setSuccess);
+ return setSuccess;
+ }
+ public boolean setSelectedTag4Access(boolean selectOne, String selectMask, int selectBank, int selectOffset, long pwrlevel, int qValue, int matchRep) {
+ if (utility.DEBUG_SELECT) appendToLog("Debug_Select: RfidReader.setSelectedTag long goes to setSelectedTag1");
+ return setSelectedTag1(selectOne, selectMask, selectBank, selectOffset, 0, pwrlevel, qValue, matchRep);
+ }
+ public boolean setSelectedTag(String selectMask, int selectBank, long pwrlevel) {
+ boolean isValid = false;
+ if (selectBank < 0 || selectBank > 3) return false;
+ int selectOffset = (selectBank == 1 ? 32 : 0);
+ //appendToLog("BtDataOut: RfidReader.setSelectTag");
+ //isValid = setSelectCriteriaDisable(-1);
+ appendToLog("BtDataOut: RfidReader.setSelectedTag short goes to setSelectedTag1");
+ isValid = setSelectedTag1(true, selectMask, selectBank, selectOffset, 0, pwrlevel, 0, 0);
+ return isValid;
+ }
+ public boolean setSelectedTagByTID(String selectMask, long pwrlevel) {
+ if (pwrlevel < 0) pwrlevel = pwrlevelSetting;
+ if (utility.DEBUG_SELECT) appendToLog("Debug_Select: RfidReader.setSelectedTagByTID goes to setSelectedTag1");
+ return setSelectedTag1(false, selectMask, 2, 0, 0, pwrlevel, 0, 0);
+ }
+
+ public final int modifyCodeAA = 0xAA;
+ public enum RegionCodes {
+ NULL,
+ AG, BD, CL, CO, CR, DR, MX, PM, UG,
+ BR1, BR2, BR3, BR4, BR5,
+ IL, IL2019RW, PR, PH, SG, ZA, VZ,
+ AU, NZ, HK, MY, VN, VN1, VN2, VN3,
+ CN, TW, KR, KR2017RW, JP, JP6, TH, IN, FCC,
+ UH1, UH2, LH, LH1, LH2,
+ ETSI, ID, ETSIUPPERBAND,
+
+ Albania1, Albania2, Algeria1, Algeria2, Algeria3, Algeria4, Argentina, Armenia, Australia1, Australia2,
+ Austria1, Austria2, Azerbaijan, Bahrain, Bangladesh, Belarus, Belgium1, Belgium2, Bolivia, Bosnia,
+ Botswana, Brazil1, Brazil2, Brunei1, Brunei2, Bulgaria1, Bulgaria2, Cambodia, Cameroon, Canada,
+ Chile1, Chile2, Chile3, China, Colombia, Congo, CostaRica, Cotedlvoire, Croatia, Cuba,
+ Cyprus1, Cyprus2, Czech1, Czech2, Denmark1, Denmark2, Dominican, Ecuador, Egypt, ElSalvador,
+ Estonia, Finland1, Finland2, France, Georgia, Germany, Ghana, Greece, Guatemala, HongKong1,
+ HongKong2, Hungary1, Hungary2, Iceland, India, Indonesia, Iran, Ireland1, Ireland2, Israel,
+ Italy, Jamaica, Japan4, Japan6, Jordan, Kazakhstan, Kenya, Korea, KoreaDPR, Kuwait,
+ Kyrgyz, Latvia, Lebanon, Libya, Liechtenstein1, Liechtenstein2, Lithuania1, Lithuania2, Luxembourg1, Luxembourg2,
+ Macao, Macedonia, Malaysia, Malta1, Malta2, Mauritius, Mexico, Moldova1, Moldova2, Mongolia,
+ Montenegro, Morocco, Netherlands, NewZealand1, NewZealand2, Nicaragua, Nigeria, Norway1, Norway2, Oman,
+ Pakistan, Panama, Paraguay, Peru, Philippines, Poland, Portugal, Romania, Russia1, Russia3,
+ Senegal, Serbia, Singapore1, Singapore2, Slovak1, Slovak2, Slovenia1, Solvenia2, SAfrica1, SAfrica2,
+ Spain, SriLanka, Sudan, Sweden1, Sweden2, Switzerland1, Switzerland2, Syria, Taiwan1, Taiwan2,
+ Tajikistan, Tanzania, Thailand, Trinidad, Tunisia, Turkey, Turkmenistan, Uganda, Ukraine, UAE,
+ UK1, UK2, USA, Uruguay, Venezuela, Vietnam1, Vietnam2, Yemen, Zimbabwe, Vietnam3
+ }
+ public String regionCode2StringArray(@NonNull RegionCodes region) {
+ switch (region) {
+ case AG:
+ return "Argentina";
+ case CL:
+ return "Chile";
+ case CO:
+ return "Columbia";
+ case CR:
+ return "Costa Rica";
+ case DR:
+ return "Dominican Republic";
+ case MX:
+ return "Mexico";
+ case PM:
+ return "Panama";
+ case UG:
+ return "Uruguay";
+ case BR1:
+ return "Brazil 915-927";
+ case BR2:
+ return "Brazil 902-906, 915-927";
+ case BR3:
+ return "Brazil 902-906";
+ case BR4:
+ return "Brazil 902-904";
+ case BR5:
+ return "Brazil 917-924";
+ case IL:
+ case IL2019RW:
+ return "Israel";
+ case PR:
+ return "Peru";
+ case PH:
+ return "Philippines";
+ case SG:
+ return "Singapore";
+ case ZA:
+ return "South Africa";
+ case VZ:
+ return "Venezuela";
+ case AU:
+ return "Australia";
+ case NZ:
+ return "New Zealand";
+ case HK:
+ return "Hong Kong";
+ case MY:
+ return "Malaysia";
+ case VN:
+ return "Vietnam";
+ case VN1:
+ return "Vietnam1";
+ case VN2:
+ return "Vietnam2";
+ case VN3:
+ return "Vietnam3";
+ case BD:
+ return "Bangladesh";
+ case CN:
+ return "China";
+ case TW:
+ return "Taiwan";
+ case KR:
+ case KR2017RW:
+ return "Korea";
+ case JP:
+ return "Japan";
+ case JP6:
+ return "Japan";
+ case TH:
+ return "Thailand";
+ case ID:
+ return "Indonesia";
+ case FCC:
+ if (getFreqModifyCode() == modifyCodeAA) return "FCC";
+ return "USA/Canada";
+ case UH1:
+ return "UH1";
+ case UH2:
+ return "UH2";
+ case LH:
+ return "LH";
+ case LH1:
+ return "LH1";
+ case LH2:
+ return "LH2";
+ case ETSI:
+ return "Europe";
+ case IN:
+ return "India";
+ case ETSIUPPERBAND:
+ return "ETSI Upper Band";
+ default:
+ return region.toString();
+ }
+ }
+ public RegionCodes regionCode = null;
+ RegionCodes[] getRegionList1() {
+ boolean DEBUG = false;
+ RegionCodes[] regionList = null;
+ regionCode = null;
+ if (DEBUG) appendToLog("3 getCountryList: getCountryCode is " + getCountryCode());
+ switch (getCountryCode()) {
+ case 1:
+ RegionCodes RegionCodes;
+ regionList = new RfidReader.RegionCodes[]{
+ RfidReader.RegionCodes.Albania1, RfidReader.RegionCodes.Algeria1, RfidReader.RegionCodes.Algeria2, RfidReader.RegionCodes.Armenia, RfidReader.RegionCodes.Austria1,
+ RfidReader.RegionCodes.Azerbaijan, RfidReader.RegionCodes.Bahrain, RfidReader.RegionCodes.Bangladesh, RfidReader.RegionCodes.Belarus, RfidReader.RegionCodes.Belgium1,
+ RfidReader.RegionCodes.Bosnia, RfidReader.RegionCodes.Botswana, RfidReader.RegionCodes.Brunei1, RfidReader.RegionCodes.Bulgaria1, RfidReader.RegionCodes.Cameroon,
+ RfidReader.RegionCodes.Congo, RfidReader.RegionCodes.Cotedlvoire, RfidReader.RegionCodes.Croatia, RfidReader.RegionCodes.Cyprus1, RfidReader.RegionCodes.Czech1,
+ RfidReader.RegionCodes.Denmark1, RfidReader.RegionCodes.Egypt, RfidReader.RegionCodes.Estonia, RfidReader.RegionCodes.Finland1, RfidReader.RegionCodes.France,
+ RfidReader.RegionCodes.Georgia, RfidReader.RegionCodes.Germany, RfidReader.RegionCodes.Ghana, RfidReader.RegionCodes.Greece, RfidReader.RegionCodes.HongKong1,
+ RfidReader.RegionCodes.Hungary1, RfidReader.RegionCodes.Iceland, RfidReader.RegionCodes.India, RfidReader.RegionCodes.Iran, RfidReader.RegionCodes.Ireland1,
+ RfidReader.RegionCodes.Italy, RfidReader.RegionCodes.Jordan, RfidReader.RegionCodes.Kazakhstan, RfidReader.RegionCodes.Kenya, RfidReader.RegionCodes.Kuwait,
+ RfidReader.RegionCodes.Kyrgyz, RfidReader.RegionCodes.Latvia, RfidReader.RegionCodes.Lebanon, RfidReader.RegionCodes.Libya, RfidReader.RegionCodes.Liechtenstein1,
+ RfidReader.RegionCodes.Lithuania1, RfidReader.RegionCodes.Luxembourg1, RfidReader.RegionCodes.Macedonia, RfidReader.RegionCodes.Malta1, RfidReader.RegionCodes.Mauritius,
+ RfidReader.RegionCodes.Moldova1, RfidReader.RegionCodes.Montenegro, RfidReader.RegionCodes.Morocco, RfidReader.RegionCodes.Netherlands, RfidReader.RegionCodes.NewZealand1,
+ RfidReader.RegionCodes.Nigeria, RfidReader.RegionCodes.Norway1, RfidReader.RegionCodes.Oman, RfidReader.RegionCodes.Pakistan, RfidReader.RegionCodes.Poland,
+ RfidReader.RegionCodes.Portugal, RfidReader.RegionCodes.Romania, RfidReader.RegionCodes.Russia1, RfidReader.RegionCodes.SAfrica1, RfidReader.RegionCodes.Senegal,
+ RfidReader.RegionCodes.Serbia, RfidReader.RegionCodes.Singapore1, RfidReader.RegionCodes.Slovak1, RfidReader.RegionCodes.Slovenia1, RfidReader.RegionCodes.Spain,
+ RfidReader.RegionCodes.SriLanka, RfidReader.RegionCodes.Sudan, RfidReader.RegionCodes.Sweden1, RfidReader.RegionCodes.Switzerland1, RfidReader.RegionCodes.Syria,
+ RfidReader.RegionCodes.Tajikistan, RfidReader.RegionCodes.Tanzania, RfidReader.RegionCodes.Tunisia, RfidReader.RegionCodes.Turkey, RfidReader.RegionCodes.Turkmenistan,
+ RfidReader.RegionCodes.UAE, RfidReader.RegionCodes.Uganda, RfidReader.RegionCodes.UK1, RfidReader.RegionCodes.Ukraine, RfidReader.RegionCodes.Vietnam1,
+ RfidReader.RegionCodes.Yemen, RfidReader.RegionCodes.Zimbabwe, RfidReader.RegionCodes.Vietnam3
+ };
+ break;
+ case 2:
+ String strSpecialCountryVersion = getSpecialCountryVersion();
+ if (DEBUG) appendToLog("3A getCountryList: getSpecialCountryVersion is [" + strSpecialCountryVersion + "]");
+ if (strSpecialCountryVersion == null || (strSpecialCountryVersion != null && strSpecialCountryVersion.length() == 0)) {
+ regionList = new RegionCodes[]{
+ RfidReader.RegionCodes.Bolivia, RfidReader.RegionCodes.Canada, RfidReader.RegionCodes.Mexico, RfidReader.RegionCodes.USA
+ };
+ } else if (strSpecialCountryVersion.contains("AS")) {
+ regionList = new RegionCodes[]{
+ RfidReader.RegionCodes.Australia1, RfidReader.RegionCodes.Australia2
+ };
+ } else if (strSpecialCountryVersion.contains("NZ")) {
+ regionList = new RegionCodes[]{
+ RfidReader.RegionCodes.NewZealand2
+ };
+ } else if (strSpecialCountryVersion.contains("OFCA")) {
+ regionList = new RegionCodes[]{
+ RfidReader.RegionCodes.HongKong2
+ };
+ } else if (strSpecialCountryVersion.contains("SG")) {
+ regionList = new RegionCodes[]{
+ RfidReader.RegionCodes.Singapore2
+ };
+ } else if (strSpecialCountryVersion.contains("RW")) {
+ regionList = new RegionCodes[]{
+ RfidReader.RegionCodes.Albania2, RfidReader.RegionCodes.Argentina, RfidReader.RegionCodes.Brazil1, RfidReader.RegionCodes.Brazil2, RfidReader.RegionCodes.Chile1,
+ RfidReader.RegionCodes.Chile2, RfidReader.RegionCodes.Chile3, RfidReader.RegionCodes.Colombia, RfidReader.RegionCodes.CostaRica, RfidReader.RegionCodes.Cuba,
+ RfidReader.RegionCodes.Dominican, RfidReader.RegionCodes.Ecuador, RfidReader.RegionCodes.ElSalvador, RfidReader.RegionCodes.Guatemala, RfidReader.RegionCodes.Jamaica,
+ RfidReader.RegionCodes.Nicaragua, RfidReader.RegionCodes.Panama, RfidReader.RegionCodes.Paraguay, RfidReader.RegionCodes.Peru, RfidReader.RegionCodes.Philippines,
+ RfidReader.RegionCodes.Singapore2, RfidReader.RegionCodes.Thailand, RfidReader.RegionCodes.Trinidad, RfidReader.RegionCodes.Uruguay, RfidReader.RegionCodes.Venezuela
+ };
+ }
+ break;
+ case 4:
+ regionList = new RfidReader.RegionCodes[]{
+ RfidReader.RegionCodes.Taiwan1, RfidReader.RegionCodes.Taiwan2
+ };
+ break;
+ case 6:
+ regionList = new RfidReader.RegionCodes[]{
+ RfidReader.RegionCodes.Korea
+ };
+ break;
+ case 7:
+ regionList = new RfidReader.RegionCodes[]{
+ RfidReader.RegionCodes.Algeria4, RfidReader.RegionCodes.Brunei2, RfidReader.RegionCodes.Cambodia, RfidReader.RegionCodes.China, RfidReader.RegionCodes.Indonesia,
+ RfidReader.RegionCodes.KoreaDPR, RfidReader.RegionCodes.Macao, RfidReader.RegionCodes.Malaysia, RfidReader.RegionCodes.Mongolia, RfidReader.RegionCodes.Vietnam2
+ };
+ break;
+ case 8:
+ regionList = new RfidReader.RegionCodes[]{
+ RfidReader.RegionCodes.Japan4, RfidReader.RegionCodes.Japan6
+ };
+ break;
+ case 9:
+ regionList = new RfidReader.RegionCodes[]{
+ RfidReader.RegionCodes.Algeria3, RfidReader.RegionCodes.Austria2, RfidReader.RegionCodes.Belgium2, RfidReader.RegionCodes.Bulgaria2, RfidReader.RegionCodes.Cyprus2,
+ RfidReader.RegionCodes.Czech2, RfidReader.RegionCodes.Denmark2, RfidReader.RegionCodes.Finland2, RfidReader.RegionCodes.Hungary2, RfidReader.RegionCodes.Ireland2,
+ RfidReader.RegionCodes.Israel, RfidReader.RegionCodes.Liechtenstein2, RfidReader.RegionCodes.Lithuania2, RfidReader.RegionCodes.Luxembourg2, RfidReader.RegionCodes.Malta2,
+ RfidReader.RegionCodes.Moldova2, RfidReader.RegionCodes.Norway2, RfidReader.RegionCodes.Russia3, RfidReader.RegionCodes.SAfrica2, RfidReader.RegionCodes.Slovak2,
+ RfidReader.RegionCodes.Solvenia2, RfidReader.RegionCodes.Sweden2, RfidReader.RegionCodes.Switzerland2, RfidReader.RegionCodes.UK2
+ };
+ break;
+ default:
+ int indexBegin = RfidReader.RegionCodes.Albania1.ordinal();
+ int indexEnd = RfidReader.RegionCodes.Vietnam3.ordinal();
+ regionList = new RegionCodes[indexEnd - indexBegin + 1];
+ for (int i = 0; i < regionList.length; i++)
+ regionList[i] = RfidReader.RegionCodes.values()[indexBegin + i];
+ break;
+ }
+ int iValue = rfidReaderChipE710.rx000Setting.getCountryEnum();
+ if (DEBUG) appendToLog("3b getCountryList: getCountryEnum is " + iValue);
+ if (iValue < 0) return null;
+
+ iValue += RfidReader.RegionCodes.Albania1.ordinal() - 1;
+ regionCode = RfidReader.RegionCodes.values()[iValue];
+ if (DEBUG) appendToLog("3C getCountryList: regionCode is " + regionCode.toString());
+ return regionList;
+ }
+ public final RegionCodes regionCodeDefault4Country2 = RegionCodes.FCC;
+ public RegionCodes[] getRegionList() {
+ if (bis108) {
+ boolean DEBUG = false;
+ RegionCodes[] regionList = null;
+ {
+ switch (getCountryCode()) {
+ case 1:
+ if (regionCode == null) regionCode = RegionCodes.ETSI;
+ regionList = new RegionCodes[]{RegionCodes.ETSI, RegionCodes.IN, RegionCodes.VN1};
+ break;
+ default:
+ case 2:
+ int modifyCode = getFreqModifyCode();
+ if (modifyCode != modifyCodeAA) {
+ if (regionCode == null) regionCode = regionCodeDefault4Country2;
+ regionList = new RegionCodes[]{
+ RegionCodes.AG,
+ RegionCodes.AU,
+ RegionCodes.BD,
+ RegionCodes.BR1, RegionCodes.BR2, RegionCodes.BR3, RegionCodes.BR4, RegionCodes.BR5,
+ RegionCodes.CL, RegionCodes.CO, RegionCodes.CR, RegionCodes.DR,
+ RegionCodes.HK,
+ RegionCodes.ID,
+ RegionCodes.IL2019RW,
+ RegionCodes.KR2017RW,
+ RegionCodes.LH1, RegionCodes.LH2,
+ RegionCodes.MY,
+ RegionCodes.MX, RegionCodes.PM,
+ RegionCodes.PR,
+ RegionCodes.PH, RegionCodes.SG,
+ RegionCodes.ZA,
+ RegionCodes.TH,
+ RegionCodes.UH1, RegionCodes.UH2,
+ RegionCodes.UG,
+ RegionCodes.FCC,
+ RegionCodes.VZ,
+ RegionCodes.VN};
+ } else {
+ String strSpecialCountryVersion = rfidReaderChipR2000.rx000OemSetting.getSpecialCountryVersion();
+ if (strSpecialCountryVersion.contains("OFCA")) {
+ regionCode = RegionCodes.HK;
+ regionList = new RegionCodes[]{RegionCodes.HK};
+ } else if (strSpecialCountryVersion.contains("SG")) {
+ regionCode = RegionCodes.SG;
+ regionList = new RegionCodes[]{RegionCodes.SG};
+ } else if (strSpecialCountryVersion.contains("AS")) {
+ regionCode = RegionCodes.AU;
+ regionList = new RegionCodes[]{RegionCodes.AU};
+ } else if (strSpecialCountryVersion.contains("NZ")) {
+ regionCode = RegionCodes.NZ;
+ regionList = new RegionCodes[]{RegionCodes.NZ};
+ } else if (strSpecialCountryVersion.contains("ZA")) {
+ regionCode = RegionCodes.ZA;
+ regionList = new RegionCodes[]{RegionCodes.ZA};
+ } else if (strSpecialCountryVersion.contains("TH")) {
+ regionCode = RegionCodes.TH;
+ regionList = new RegionCodes[]{RegionCodes.TH};
+ } else { //if (strSpecialCountryVersion.contains("*USA")) {
+ regionCode = regionCodeDefault4Country2;
+ regionList = new RegionCodes[]{RegionCodes.FCC};
+ }
+ }
+ break;
+ case 3:
+// break;
+ case 4:
+ if (regionCode == null) regionCode = RegionCodes.TW;
+ regionList = new RegionCodes[]{RegionCodes.TW, RegionCodes.AU, RegionCodes.MY,
+ RegionCodes.HK, RegionCodes.SG, RegionCodes.ID, RegionCodes.CN};
+ break;
+ case 5:
+ regionCode = RegionCodes.KR;
+ regionList = new RegionCodes[]{RegionCodes.KR};
+ break;
+ case 6:
+ regionCode = RegionCodes.KR2017RW;
+ regionList = new RegionCodes[]{RegionCodes.KR2017RW};
+ break;
+ case 7:
+ if (regionCode == null) regionCode = RegionCodes.CN;
+ regionList = new RegionCodes[]{RegionCodes.CN, RegionCodes.AU, RegionCodes.HK, RegionCodes.TH,
+ RegionCodes.SG, RegionCodes.MY, RegionCodes.ID, RegionCodes.VN2, RegionCodes.VN3};
+ break;
+ case 8:
+ String strSpecialCountryVersion = rfidReaderChipR2000.rx000OemSetting.getSpecialCountryVersion();
+ if (strSpecialCountryVersion.contains("6")) {
+ regionCode = RegionCodes.JP6;
+ regionList = new RegionCodes[]{RegionCodes.JP6};
+ } else {
+ regionCode = RegionCodes.JP;
+ regionList = new RegionCodes[]{RegionCodes.JP};
+ }
+ break;
+ case 9:
+ regionCode = RegionCodes.ETSIUPPERBAND;
+ regionList = new RegionCodes[]{RegionCodes.ETSIUPPERBAND};
+ break;
+ }
+ }
+ countryInList = 0; if (DEBUG) appendToLog("saveSetting2File testpoint 1");
+ for (int i = 0; i < regionList.length; i++) {
+ if (regionCode == regionList[i]) {
+ countryInList = i; if (DEBUG) appendToLog("saveSetting2File testpoint 2"); break;
+ }
+ }
+ if (countryInListDefault < 0) countryInListDefault = countryInList;
+ appendToLog("countryInListDefault = " + countryInListDefault);
+ return regionList;
+ } else {
+ boolean DEBUG = false;
+ RegionCodes[] regionList;
+ regionCode = null;
+ if (DEBUG) appendToLog("2 getCountryList");
+ regionList = getRegionList1();
+ if (DEBUG) appendToLog("2A getCountryList: regionList is " + (regionList != null ? "Valid" : "null"));
+ if (regionList != null) {
+ if (DEBUG) appendToLog(String.format("2b getCountryList: countryInList = %d, regionCode = %s", countryInList, (regionCode != null ? regionCode.toString() : "")));
+ if (countryInList < 0) {
+ if (regionCode == null) regionCode = regionList[0];
+ countryInList = 0;
+ for (int i = 0; i < regionList.length; i++) {
+ if (regionCode == regionList[i]) {
+ countryInList = i;
+ break;
+ }
+ }
+ if (countryInListDefault < 0) countryInListDefault = countryInList;
+ regionCode = regionList[countryInList];
+ if (DEBUG) appendToLog(String.format("2C getCountryList: countryInList = %d, regionCode = %s", countryInList, regionCode.toString()));
+ }
+ } else regionCode = null;
+ return regionList;
+ }
+ }
+ public boolean getChannelHoppingDefault() {
+ int countryCode = getCountryCode();
+ appendToLog("getChannelHoppingDefault: countryCode (for channelOrderType) = " + countryCode);
+ {
+ if (countryCode == 1 || countryCode == 8 || countryCode == 9) return false;
+ return true;
+ }
+ }
+ public int getCountryCode() {
+ if (bis108) return rfidReaderChipR2000.rx000OemSetting.getCountryCode();
+ final boolean DEBUG = false;
+ int iCountrycode = -1;
+ int iValue = rfidReaderChipE710.rx000Setting.getCountryEnum();
+ if (DEBUG) appendToLog("getCountryEnum 0x3014 = " + iValue);
+ if (iValue > 0 && iValue < countryChannelData.strCountryEnumInfo.length/countryChannelData.iCountryEnumInfoColumn) {
+ if (DEBUG) {
+ for (int i = 1; i <= 160; i++) {
+ appendToLog("i = " + i + ", " + countryChannelData.strCountryEnumInfo[(i - 1) * countryChannelData.iCountryEnumInfoColumn + 0]
+ + ", " + countryChannelData.strCountryEnumInfo[(i - 1) * countryChannelData.iCountryEnumInfoColumn + 1]
+ + ", " + countryChannelData.strCountryEnumInfo[(i - 1) * countryChannelData.iCountryEnumInfoColumn + 2]
+ + ", " + countryChannelData.strCountryEnumInfo[(i - 1) * countryChannelData.iCountryEnumInfoColumn + 3]
+ + ", " + countryChannelData.strCountryEnumInfo[(i - 1) * countryChannelData.iCountryEnumInfoColumn + 4]
+ + ", " + countryChannelData.strCountryEnumInfo[(i - 1) * countryChannelData.iCountryEnumInfoColumn + 5]
+ + ", " + countryChannelData.strCountryEnumInfo[(i - 1) * countryChannelData.iCountryEnumInfoColumn + 6]
+ );
+ }
+ }
+ String strCountryCode = countryChannelData.strCountryEnumInfo[(iValue - 1) * countryChannelData.iCountryEnumInfoColumn + 2];
+ if (DEBUG) appendToLog("strCountryCode 0 = " + strCountryCode);
+ String[] countryCodePart = strCountryCode.split(" ");
+ strCountryCode = countryCodePart[0].substring(1);
+ if (DEBUG) appendToLog("strCountryCode 1 = " + strCountryCode);
+ try {
+ iCountrycode = Integer.decode(strCountryCode);
+ if (DEBUG) appendToLog("iCountrycode = " + iCountrycode);
+ } catch (Exception ex) {
+ }
+ }
+ if (true) {
+ int iCountrycode1 = rfidReaderChipE710.rx000Setting.getCountryEnumOem();
+ if (DEBUG) appendToLog("getCountryEnumOem 0x5040 = " + iCountrycode1);
+ int iCountrycode2 = rfidReaderChipE710.rx000Setting.getCountryCodeOem();
+ if (DEBUG) appendToLog("getCountryCodeOem 0xef98 = " + iCountrycode2);
+ if (iCountrycode < 0 && iCountrycode1 > 0 && iCountrycode1 < 10) iCountrycode = iCountrycode1;
+ if (iCountrycode < 0 && iCountrycode2 > 0 && iCountrycode2 < 10) iCountrycode = iCountrycode2;
+ }
+ return iCountrycode;
+ }
+ public int getFreqModifyCode() {
+ if (bis108) return rfidReaderChipR2000.rx000OemSetting.getFreqModifyCode();
+ boolean DEBUG = false;
+ int iFreqModifyCode = rfidReaderChipE710.rx000Setting.getFreqModifyCode();
+ if (DEBUG) appendToLog("getFreqModifyCode 0xefb0 = " + iFreqModifyCode);
+ return iFreqModifyCode;
+ }
+ public boolean getRfidOnStatus() {
+ return rfidConnector.getOnStatus();
+ }
+ public boolean isRfidFailure() {
+ return rfidConnector.rfidFailure;
+ }
+ public void setReaderDefault() {
+ setPowerLevel(300);
+ setTagGroup(0, 0, 2);
+ setPopulation(60);
+ setInvAlgoNoSave(true);
+ setBasicCurrentLinkProfile();
+
+ setCountryInList(countryInListDefault);
+ setChannel(0);
+
+ //getAntennaPower(0)
+ //getPopulation()
+ //getQuerySession()
+ //getQueryTarget()
+ setTagFocus(false);
+ setFastId(false);
+ //getInvAlgo()
+ //\\getRetryCount()
+ //getCurrentProfile() + "\n"));
+ //\\getRxGain() + "\n"));
+ }
+ public void getReaderDefault() {
+ if (bis108 == false) {
+ rfidReaderChipE710.rx000Setting.getAntennaPortConfig(0);
+ rfidReaderChipE710.rx000Setting.getAntennaPortConfig(1);
+ rfidReaderChipE710.rx000Setting.getSelectConfiguration(0);
+ rfidReaderChipE710.rx000Setting.getSelectConfiguration(1);
+ rfidReaderChipE710.rx000Setting.getSelectConfiguration(2);
+ rfidReaderChipE710.rx000Setting.getMultibankReadConfig(0);
+ rfidReaderChipE710.rx000Setting.getMultibankReadConfig(1);
+ rfidReaderChipE710.rx000Setting.getRx000AccessPassword();
+ rfidReaderChipE710.rx000Setting.getRx000KillPassword();
+ rfidReaderChipE710.rx000Setting.getDupElimRollWindow();
+ //rfidReaderChip.rx000Setting.getEventPacketUplinkEnable();
+ rfidReaderChipE710.rx000Setting.setEventPacketUplinkEnable((byte) 0x09);
+ rfidReaderChipE710.rx000Setting.getIntraPacketDelay();
+ rfidReaderChipE710.rx000Setting.getFrequencyChannelIndex();
+ rfidReaderChipE710.rx000Setting.getCurrentPort();
+ }
+ }
+ public String getMacVer() {
+ appendToLog("RfidReader.getMacVersion: bis108 is " + bis108);
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.getMacVer() : rfidReaderChipE710.rx000Setting.getMacVer());
+ }
+ public String getRadioSerial() {
+ boolean DEBUG = true;
+ String strValue, strValue1;
+ strValue = getSerialNumber();
+ if (bis108 == false) {
+ if (DEBUG) appendToLog("getSerialNumber 0xEF9C = " + strValue);
+ strValue1 = getProductSerialNumber();
+ if (DEBUG) appendToLog("getProductSerialNumber 0x5020 = " + strValue1);
+ if (strValue1 != null && false) strValue = strValue1;
+ }
+ if (strValue != null) {
+ appendToLog("strValue length = " + strValue.length());
+ if (strValue.length() >= 13) strValue = strValue.substring(0, 13);
+ } else appendToLog("BBB");
+ if (DEBUG) appendToLog("strValue = " + strValue);
+ return strValue;
+ }
+ public String getRadioBoardVersion() {
+ String str = getSerialNumber();
+ if (str == null) return null;
+ if (str.length() != 16) return null;
+ if (bis108) {
+ String strOut;
+ if (str.substring(13, 14).matches("0")) strOut = str.substring(14, 15);
+ else strOut = str.substring(13, 15);
+ strOut += "." + str.substring(15);
+ str = strOut;
+ } else {
+ str = str.substring(13);
+ String string = "";
+ if (str.length() >= 2) string = str.substring(0, 2);
+ if (str.length() >= 3) string += ("." + str.substring(2, 3));
+ str = string;
+ }
+ return str;
+ }
+ public int getAntennaSelect() {
+ int iValue = 0;
+ iValue = (bis108 ? rfidReaderChipR2000.rx000Setting.getAntennaSelect() : rfidReaderChipE710.rx000Setting.getAntennaPort());
+ appendToLog("AntennaSelect = " + iValue);
+ return iValue;
+ }
+ public boolean setAntennaSelect(int number) {
+ boolean bValue = false;
+ bValue = (bis108 ? rfidReaderChipR2000.rx000Setting.setAntennaSelect(number) : rfidReaderChipE710.rx000Setting.setAntennaSelect(number));
+ appendToLog("AntennaSelect = " + number + " returning " + bValue);
+ return bValue;
+ }
+ public boolean getAntennaEnable() {
+ int iValue; boolean DEBUG = false;
+ if (DEBUG) appendToLog("1 getAntennaEnable");
+ iValue = (bis108 ? rfidReaderChipR2000.rx000Setting.getAntennaEnable() : rfidReaderChipE710.rx000Setting.getAntennaEnable());
+ if (DEBUG) appendToLog("1A getAntennaEnable: AntennaEnable = " + iValue);
+ if (iValue > 0) return true;
+ else return false;
+ }
+ public boolean setAntennaEnable(boolean enable) {
+ int iEnable = 0;
+ if (enable) iEnable = 1;
+ boolean bValue = false;
+ appendToLog("1A setAntennaEnable: iEnable = " + iEnable);
+ bValue = (bis108 ? rfidReaderChipR2000.rx000Setting.setAntennaEnable(iEnable) : rfidReaderChipE710.rx000Setting.setAntennaEnable(iEnable));
+ appendToLog("AntennaEnable = " + iEnable + " returning " + bValue);
+ if (bValue && bis108 == false) bValue = rfidReaderChipE710.rx000Setting.updateCurrentPort();
+ return bValue;
+ }
+ public long getAntennaDwell() {
+ long lValue = 0; boolean DEBUG = false;
+ if (DEBUG) appendToLog("1 getAntennaDwell");
+ lValue = (bis108 ? rfidReaderChipR2000.rx000Setting.getAntennaDwell() : rfidReaderChipE710.rx000Setting.getAntennaDwell());
+ if (DEBUG) appendToLog("1A getAntennaDwell: lValue = " + lValue);
+ //appendToLog("BtDataOut: getAntennaDwell as " + lValue);
+ return lValue;
+ }
+ public boolean setAntennaDwell(long antennaDwell) {
+ boolean bValue = false, DEBUG = false;
+ //appendToLog("BtDataOut: setAntennaDwell as " + antennaDwell);
+ if (DEBUG) appendToLog("1 AntennaDwell = " + antennaDwell + " returning " + bValue);
+ if (getAntennaDwell() == antennaDwell) return true;
+ bValue = (bis108 ? rfidReaderChipR2000.rx000Setting.setAntennaDwell(antennaDwell) : rfidReaderChipE710.rx000Setting.setAntennaDwell(antennaDwell));
+ if (DEBUG) appendToLog("1A AntennaDwell = " + antennaDwell + " returning " + bValue);
+ return bValue;
+ }
+ public long getPwrlevel() {
+ long lValue = 0;
+ lValue = (bis108 ? rfidReaderChipR2000.rx000Setting.getAntennaPower(-1) : rfidReaderChipE710.rx000Setting.getAntennaPower(-1));
+ return lValue;
+ }
+ public long pwrlevelSetting;
+ public boolean setPowerLevel(long pwrlevel) {
+ pwrlevelSetting = pwrlevel;
+ boolean bValue = false;
+ bValue = (bis108 ? rfidReaderChipR2000.rx000Setting.setAntennaPower(pwrlevel) : rfidReaderChipE710.rx000Setting.setAntennaPower(pwrlevel));
+ if (false) appendToLog("PowerLevel = " + pwrlevel + " returning " + bValue);
+ return bValue;
+ }
+ public int getQueryTarget() {
+ int iValue; boolean DEBUG = false;
+ iValue = (bis108 ? rfidReaderChipR2000.rx000Setting.getAlgoAbFlip() : rfidReaderChipE710.rx000Setting.getQueryTarget());
+ if (DEBUG) appendToLog("getQueryTarget with bis108 = " + bis108 + ", iValue = " + iValue);
+ if (bis108) {
+ if (iValue > 0) {
+ rfidReaderChipR2000.rx000Setting.getQueryTarget();
+ return 2;
+ }
+ else {
+ if (DEBUG) appendToLog("getQueryTarget");
+ iValue = rfidReaderChipR2000.rx000Setting.getQueryTarget();
+ if (iValue > 0) return 1;
+ return 0;
+ }
+ } else {
+ if (DEBUG) appendToLog("1A getQueryTarget: iValue = " + iValue);
+ if (iValue < 0) iValue = 0;
+ return iValue;
+ }
+ }
+ public int getQuerySession() {
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.getQuerySession() : rfidReaderChipE710.rx000Setting.getQuerySession());
+ }
+ public int getQuerySelect() {
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.getQuerySelect() : rfidReaderChipE710.rx000Setting.getQuerySelect());
+ }
+ public boolean setTagGroup(int sL, int session, int target1) {
+ if (bis108) {
+ rfidReaderChipR2000.rx000Setting.setAlgoSelect(getInvAlgoInChip()); //Must not delete this line
+ if (false) appendToLog("RfidReader.setTagGroup[" + target1 + ", " + session + ", " + sL);
+ return rfidReaderChipR2000.rx000Setting.setQueryTarget(target1, session, sL);
+ } else {
+ //appendToLog("1d");
+ int iAlgoAbFlip = rfidReaderChipE710.rx000Setting.getAlgoAbFlip();
+ appendToLog("sL = " + sL + ", session = " + session + ", target = " + target1 + ", getAlgoAbFlip = " + iAlgoAbFlip);
+ boolean bValue = false;
+ bValue = rfidReaderChipE710.rx000Setting.setQueryTarget(target1, session, sL);
+ if (bValue) {
+ if (iAlgoAbFlip != 0 && target1 < 2)
+ bValue = rfidReaderChipE710.rx000Setting.setAlgoAbFlip(0);
+ else if (iAlgoAbFlip == 0 && target1 >= 2)
+ bValue = rfidReaderChipE710.rx000Setting.setAlgoAbFlip(1);
+ }
+ return bValue;
+ }
+ }
+ public int tagFocus = -1;
+ public int getTagFocus() {
+ if (bis108) {
+ tagFocus = rfidReaderChipR2000.rx000Setting.getImpinjExtension();
+ if (tagFocus > 0) tagFocus = ((tagFocus & 0x10) >> 4);
+ } else {
+ tagFocus = rfidReaderChipE710.rx000Setting.getImpinjExtension() & 0x04;
+ }
+ return tagFocus;
+ }
+ public boolean setTagFocus(boolean tagFocusNew) {
+ boolean bRetValue;
+ if (bis108) {
+ bRetValue = rfidReaderChipR2000.rx000Setting.setImpinjExtension(tagFocusNew, (fastId > 0 ? true : false));
+ } else {
+ bRetValue = rfidReaderChipE710.rx000Setting.setImpinjExtension(tagFocusNew, (fastId > 0 ? true : false));
+ }
+ if (bRetValue) tagFocus = (tagFocusNew ? 1 : 0);
+ return bRetValue;
+ }
+ public int fastId = -1;
+ public int getFastId() {
+ if (rfidReaderChipR2000 != null) {
+ fastId = rfidReaderChipR2000.rx000Setting.getImpinjExtension();
+ if (fastId > 0) fastId = ((fastId & 0x20) >> 5);
+ } else {
+ fastId = rfidReaderChipE710.rx000Setting.getImpinjExtension() & 0x02;
+ }
+ return fastId;
+ }
+ public boolean setFastId(boolean fastIdNew) {
+ boolean bRetValue;
+ if (bis108) {
+ bRetValue = rfidReaderChipR2000.rx000Setting.setImpinjExtension((tagFocus > 0 ? true : false), fastIdNew);
+ } else {
+ bRetValue = rfidReaderChipE710.rx000Setting.setImpinjExtension((tagFocus > 0 ? true : false), fastIdNew);
+ }
+ if (bRetValue) fastId = (fastIdNew ? 1 : 0);
+ return bRetValue;
+ }
+ public boolean invAlgoSetting = true;
+ public boolean getInvAlgo() {
+ return invAlgoSetting;
+ }
+ public int getInvAlgoInChip() {
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.getInvAlgo() : rfidReaderChipE710.rx000Setting.getInvAlgo());
+ }
+ public boolean setInvAlgo(boolean dynamicAlgo) {
+ boolean DEBUG = false;
+ if (DEBUG) appendToLog("1 setInvAlgo with dynamicAlgo = " + dynamicAlgo);
+ boolean bValue = setInvAlgo1(dynamicAlgo);
+ if (bValue) invAlgoSetting = dynamicAlgo;
+ if (DEBUG) appendToLog("1A setInvAlgo with bValue = " + bValue);
+ return bValue;
+ }
+ public List getProfileList() {
+ if (bis108) return Arrays.asList(context.getResources().getStringArray(R.array.profile1_options));
+ appendToLog("getMacVer = " + rfidReaderChipE710.rx000Setting.getMacVer());
+ if (bluetoothGatt.isVersionGreaterEqual(rfidReaderChipE710.rx000Setting.getMacVer(), 2, 1, 1)) {
+ appendToLog("equal or greater than 2.1.1");
+ return Arrays.asList(context.getResources().getStringArray(R.array.profile4_options));
+ } else if (bluetoothGatt.isVersionGreaterEqual(rfidReaderChipE710.rx000Setting.getMacVer(), 1, 0, 250)) {
+ appendToLog("equal or greater than 1.0.250");
+ return Arrays.asList(context.getResources().getStringArray(R.array.profile3A_options));
+ } else {
+ appendToLog("matching less than 1.0.250");
+ return Arrays.asList(context.getResources().getStringArray(R.array.profile2_options)); //for 1.0.12
+ }
+ }
+ public int getCurrentProfile() {
+ if (bis108) return rfidReaderChipR2000.rx000Setting.getCurrentProfile();
+ boolean DEBUG = false;
+ if (DEBUG) appendToLog("1 getCurrentProfile");
+ int iValue;
+ if (true) {
+ iValue = rfidReaderChipE710.rx000Setting.getCurrentProfile();
+ if (DEBUG) appendToLog("1A getCurrentProfile: getCurrentProfile = " + iValue);
+ if (iValue > 0) {
+ List profileList = getProfileList();
+ if (DEBUG) appendToLog("1b getCurrentProfile: getProfileList = " + (profileList != null ? "valid" : ""));
+ int index = 0;
+ for (; index < profileList.size(); index++) {
+ if (Integer.valueOf(profileList.get(index).substring(0, profileList.get(index).indexOf(":"))) == iValue)
+ break;
+ }
+ if (index >= profileList.size()) {
+ index = profileList.size()-1;
+ setCurrentLinkProfile(index);
+ }
+ if (DEBUG) appendToLog("1C getCurrentProfile: index in the profileList = " + index);
+ iValue = index;
+ }
+ }
+ return iValue;
+ }
+ public boolean setBasicCurrentLinkProfile() {
+ if (bis108) return setCurrentLinkProfile(1);
+ boolean b211 = bluetoothGatt.isVersionGreaterEqual(rfidReaderChipE710.rx000Setting.getMacVer(), 2, 1, 1);
+ int profile = (b211 ? 343 : 244);
+ if (getCountryCode() == 1) profile = (b211 ? 342 : 241);
+ appendToLog("profile is " + profile);
+ return rfidReaderChipE710.rx000Setting.setCurrentProfile(profile);
+ }
+ public boolean setCurrentLinkProfile(int profile) {
+ if (bis108) {
+ if (profile == getCurrentProfile()) return true;
+ boolean result;
+ result = rfidReaderChipR2000.rx000Setting.setCurrentProfile(profile);
+ if (result) {
+ rfidReaderChipR2000.setPwrManagementMode(false);
+ result = rfidReaderChipR2000.sendHostRegRequestHST_CMD(RfidReaderChipData.HostCommands.CMD_UPDATELINKPROFILE);
+ }
+ if (result && profile == 3) {
+ appendToLog("It is profile3");
+ if (getTagDelay() < 2) result = setTagDelay((byte) 2);
+ }
+ return result;
+ }
+ boolean DEBUG = true;
+ if (DEBUG) appendToLog("1 setCurrentLinkProfile: input profile = " + profile);
+ if (true && profile < 50) {
+ List profileList = getProfileList();
+ if (profile < 0 || profile >= profileList.size()) return false;
+ int profile1 = Integer.valueOf(profileList.get(profile).substring(0, profileList.get(profile).indexOf(":")));
+ profile = profile1;
+ }
+ if (DEBUG) appendToLog("1A setCurrentLinkProfile: adjusted profile = " + profile);
+ boolean result = rfidReaderChipE710.rx000Setting.setCurrentProfile(profile);
+ if (DEBUG) appendToLog("1b setCurrentLinkProfile: after setCurrentProfile, result = " + result);
+ if (result) {
+ setPwrManagementMode(false);
+ }
+ if (DEBUG) appendToLog("1C setCurrentLinkProfile: after setPwrManagementMode, result = " + result + ", profile = " + profile);
+ if (result && profile == 3) {
+ if (getTagDelay() < 2) result = setTagDelay((byte)2);
+ }
+ if (DEBUG) appendToLog("1d setCurrentLinkProfile: after setTagDelay, result = " + result);
+ getCurrentProfile();
+ return result;
+ }
+ public void resetEnvironmentalRSSI() {
+ if (bis108) rfidReaderChipR2000.rx000EngSetting.resetRSSI();
+ else rfidReaderChipE710.rx000EngSetting.resetRSSI();
+ }
+ public String getEnvironmentalRSSI() {
+ int iValue;
+ if (bis108) {
+ rfidReaderChipR2000.setPwrManagementMode(false);
+ iValue = rfidReaderChipR2000.rx000EngSetting.getwideRSSI();
+ }
+ else {
+ rfidReaderChipE710.setPwrManagementMode(false);
+ iValue = rfidReaderChipE710.getwideRSSI();
+ }
+
+ if (iValue < 0) return null;
+ if (iValue > 255) return "Invalid data";
+ double dValue = (bis108 ? rfidReaderChipR2000.decodeNarrowBandRSSI((byte)iValue) : rfidReaderChipE710.decodeNarrowBandRSSI((byte)iValue));
+ return String.format("%.2f dB", dValue);
+ }
+ public int getHighCompression() {
+ return (bis108 ? rfidReaderChipR2000.rx000MbpSetting.getHighCompression() : rfidReaderChipE710.getHighCompression());
+ }
+ public int getRflnaGain() {
+ return (bis108 ? rfidReaderChipR2000.rx000MbpSetting.getRflnaGain() : rfidReaderChipE710.getRflnaGain());
+ }
+ public int getIflnaGain() {
+ return (bis108 ? rfidReaderChipR2000.rx000MbpSetting.getIflnaGain() : rfidReaderChipE710.getIflnaGain());
+ }
+ public int getAgcGain() {
+ return (bis108 ? rfidReaderChipR2000.rx000MbpSetting.getAgcGain() : rfidReaderChipE710.getAgcGain());
+ }
+ public int getRxGain() {
+ return (bis108 ? rfidReaderChipR2000.rx000MbpSetting.getRxGain() : rfidReaderChipE710.getRxGain());
+ }
+ public boolean setRxGain(int highCompression, int rflnagain, int iflnagain, int agcgain) {
+ return (bis108 ? rfidReaderChipR2000.rx000MbpSetting.setRxGain(highCompression, rflnagain, iflnagain, agcgain) : rfidReaderChipE710.setRxGain(highCompression, rflnagain, iflnagain, agcgain));
+ }
+ public boolean setRxGain(int rxGain) {
+ return (bis108 ? rfidReaderChipR2000.rx000MbpSetting.setRxGain(rxGain) : rfidReaderChipE710.setRxGain(rxGain));
+ }
+ public int FreqChnCnt() {
+ return FreqChnCnt(regionCode);
+ }
+ public int FreqChnCnt(RegionCodes regionCode) {
+ if (bis108) {
+ switch (regionCode) {
+ case FCC:
+ case AG:
+ case CL:
+ case CO:
+ case CR:
+ case DR:
+ case MX:
+ case PM:
+ case UG:
+ return countryChannelData.FCC_CHN_CNT;
+ case PR:
+ return countryChannelData.PRTableOfFreq.length;
+ case VZ:
+ return countryChannelData.VZ_CHN_CNT;
+ case AU:
+ return countryChannelData.AUS_CHN_CNT;
+ case BR1:
+ return countryChannelData.BR1_CHN_CNT;
+ case BR2:
+ return countryChannelData.BR2_CHN_CNT;
+ case BR3:
+ return countryChannelData.BR3_CHN_CNT;
+ case BR4:
+ return countryChannelData.BR4_CHN_CNT;
+ case BR5:
+ return countryChannelData.BR5_CHN_CNT;
+ case HK:
+ case SG:
+ case TH:
+ case VN:
+ return countryChannelData.HK_CHN_CNT;
+ case VN1:
+ return countryChannelData.VN1_CHN_CNT;
+ case VN2:
+ return countryChannelData.VN2_CHN_CNT;
+ case VN3:
+ return countryChannelData.VN3_CHN_CNT;
+ case BD:
+ return countryChannelData.BD_CHN_CNT;
+ case TW:
+ return countryChannelData.TW_CHN_CNT;
+ case MY:
+ return countryChannelData.MYS_CHN_CNT;
+ case ZA:
+ return countryChannelData.ZA_CHN_CNT;
+ case ID:
+ return countryChannelData.ID_CHN_CNT;
+ case IL:
+ return countryChannelData.IL_CHN_CNT;
+ case IL2019RW:
+ return countryChannelData.IL2019RW_CHN_CNT;
+ case PH:
+ return countryChannelData.PH_CHN_CNT;
+ case NZ:
+ return countryChannelData.NZ_CHN_CNT;
+ case CN:
+ return countryChannelData.CN_CHN_CNT;
+
+ case UH1:
+ return countryChannelData.UH1_CHN_CNT;
+ case UH2:
+ return countryChannelData.UH2_CHN_CNT;
+ case LH:
+ return countryChannelData.LH_CHN_CNT;
+ case LH1:
+ return countryChannelData.LH1_CHN_CNT;
+ case LH2:
+ return countryChannelData.LH2_CHN_CNT;
+
+ case ETSI:
+ return countryChannelData.ETSI_CHN_CNT;
+ case IN:
+ return countryChannelData.IDA_CHN_CNT;
+ case KR:
+ return countryChannelData.KR_CHN_CNT;
+ case KR2017RW:
+ return countryChannelData.KR2017RW_CHN_CNT;
+ case JP:
+ return countryChannelData.JPN2012_CHN_CNT;
+ case JP6:
+ return countryChannelData.JPN2012A_CHN_CNT;
+ case ETSIUPPERBAND:
+ return countryChannelData.ETSIUPPERBAND_CHN_CNT;
+
+ default:
+ return 0;
+ }
+ } else {
+ boolean DEBUG = true;
+ int iFreqChnCnt = -1, iValue = -1; //mRfidDevice.mRfidReaderChip.mRfidReaderChip.mRx000Setting.getCountryEnum(); //iValue--;
+ iValue = regionCode.ordinal() - RegionCodes.Albania1.ordinal() + 1;
+ if (DEBUG) appendToLog("regionCode = " + regionCode.toString() + ", regionCodeEnum = " + iValue);
+ if (iValue > 0) {
+ String strFreqChnCnt = countryChannelData.strCountryEnumInfo[(iValue - 1) * countryChannelData.iCountryEnumInfoColumn + 3];
+ if (DEBUG) appendToLog("strFreqChnCnt = " + strFreqChnCnt);
+ try {
+ iFreqChnCnt = Integer.parseInt(strFreqChnCnt);
+ } catch (Exception ex) {
+ appendToLog("!!! CANNOT parse strFreqChnCnt = " + strFreqChnCnt);
+ }
+ }
+ if (DEBUG) appendToLog("iFreqChnCnt = " + iFreqChnCnt);
+ return iFreqChnCnt; //1 for hopping, 0 for fixed
+ }
+ }
+ public double getLogicalChannel2PhysicalFreq(int channel) {
+ if (bis108) {
+ getCountryList(); // used to set up possibly regionCode
+ int TotalCnt = FreqChnCnt(regionCode);
+ int[] freqIndex = FreqIndex(regionCode);
+ double[] freqTable = GetAvailableFrequencyTable(regionCode);
+ if (freqIndex.length != TotalCnt || freqTable.length != TotalCnt || channel >= TotalCnt)
+ return -1;
+ return freqTable[freqIndex[channel]];
+ }
+ boolean DEBUG = false;
+ if (DEBUG) appendToLog("regionCode = " + regionCode.toString());
+ int TotalCnt = FreqChnCnt(regionCode);
+ if (DEBUG) appendToLog("TotalCnt = " + TotalCnt);
+ int[] freqIndex = FreqIndex(regionCode);
+ if (DEBUG) appendToLog("Frequency index " + (freqIndex != null ? ("length = " + freqIndex.length) : "null"));
+ double[] freqTable = GetAvailableFrequencyTable(regionCode);
+ if (DEBUG) appendToLog("Frequency freqTable " + (freqTable != null ? ("length = " + freqTable.length) : "null"));
+ if (DEBUG) appendToLog("Check TotalCnt = " + TotalCnt + ", freqIndex.length = " + freqIndex.length + ", freqTable.length = " + freqTable.length + ", channel = " + channel);
+ if (freqIndex.length != TotalCnt || freqTable.length != TotalCnt || channel >= TotalCnt) return -1;
+ double dRetvalue = freqTable[freqIndex[channel]];
+ if (DEBUG) appendToLog("channel = " + channel + ", dRetvalue = " + dRetvalue);
+ return dRetvalue;
+ }
+ public byte getTagDelay() {
+ return tagDelaySetting;
+ }
+ public boolean setTagDelay(byte tagDelay) {
+ tagDelaySetting = tagDelay;
+ return true;
+ }
+ boolean setTagDelay2RfidReader(int tagDelay) {
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.setTagDelay2RfidReader(tagDelay) : rfidReaderChipE710.rx000Setting.setTagDelay(tagDelay));
+ }
+ public byte getIntraPkDelay() {
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.getIntraPacketDelay() : rfidReaderChipE710.rx000Setting.getIntraPacketDelay());
+ }
+ public boolean setIntraPkDelay(byte intraPkDelay) {
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.setIntraPacketDelay(intraPkDelay) : rfidReaderChipE710.rx000Setting.setIntraPacketDelay(intraPkDelay));
+ }
+ public byte getDupDelay() {
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.getDupElimRollWindow() : rfidReaderChipE710.rx000Setting.getDupElimRollWindow());
+ }
+ public boolean setDupDelay(byte dupElim) {
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.setDupElimRollWindow(dupElim) : rfidReaderChipE710.rx000Setting.setDupElimRollWindow(dupElim));
+ }
+ public long getCycleDelay() {
+ cycleDelaySetting = (bis108 ? rfidReaderChipR2000.rx000Setting.getCycleDelay() : rfidReaderChipE710.rx000Setting.getCycleDelay());
+ return cycleDelaySetting;
+ }
+ public boolean setCycleDelay(long cycleDelay) {
+ cycleDelaySetting = cycleDelay;
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.setCycleDelay(cycleDelay) : rfidReaderChipE710.rx000Setting.setCycleDelay(cycleDelay));
+ }
+ public void getAuthenticateReplyLength() {
+ if (bis108) rfidReaderChipR2000.rx000Setting.getAuthenticateReplyLength();
+ else rfidReaderChipE710.rx000Setting.getAuthenticateReplyLength();
+ }
+ public boolean setTamConfiguration(boolean header, String matchData) {
+ appendToLog("header = " + header + ", matchData.length = " + matchData.length() + ", matchData = " + matchData);
+ if (matchData == null) matchData = "";
+ if (matchData.length() != 12) return false;
+ boolean retValue = false; String preChallenge = matchData.substring(0, 2);
+ int iValue = Integer.parseInt(preChallenge, 16);
+ iValue &= 0x07;
+ if (header) iValue |= 0x04;
+ else iValue &= ~0x04;
+ preChallenge = String.format("%02X", iValue);
+ matchData = preChallenge + matchData.substring(2);
+ appendToLog("new matchData = " + matchData);
+ if (bis108) {
+ retValue = setAuthMatchData(matchData);
+ appendToLog("setAuthMatchData returns " + retValue);
+ if (retValue) {
+ retValue = rfidReaderChipR2000.rx000Setting.setHST_AUTHENTICATE_CFG(true, true, 1, matchData.length() * 4);
+ appendToLog("setHST_AUTHENTICATE_CFG returns " + retValue);
+ }
+ return retValue;
+ } else {
+ boolean bValue = rfidReaderChipE710.rx000Setting.setAuthenticateConfig(((matchData.length() * 4) << 10) | (1 << 2) | 0x03);
+ appendToLog("setAuthenticateConfiguration 1 revised matchData = " + matchData + " with bValue = " + (bValue ? "true" : "false"));
+ appendToLog("revised bytes = " + utility.byteArrayToString(utility.string2ByteArray(matchData)));
+ if (bValue) {
+ bValue = rfidReaderChipE710.rx000Setting.setAuthenticateMessage(utility.string2ByteArray(matchData));
+ appendToLog("setAuthenticateConfiguration 2: bValue = " + (bValue ? "true" : "false"));
+ }
+ if (bValue) {
+ int iLength = 8 * 8;
+ if (header) iLength = 16 * 8;
+ bValue = rfidReaderChipE710.rx000Setting.setAuthenticateResponseLen(iLength);
+ appendToLog("setAuthenticateConfiguration 3: bValue = " + (bValue ? "true" : "false"));
+ }
+ return bValue;
+ }
+ }
+ public boolean setTam1Configuration(int keyId, String matchData) {
+ appendToLog("keyId = " + keyId + ", matchData = " + matchData);
+ if (keyId > 255) return false;
+ if (matchData == null) matchData = "";
+ if (matchData.length() != 20) return false;
+
+ boolean retValue = false; String preChallenge = "00";
+ preChallenge += String.format("%02X", keyId);
+ matchData = preChallenge + matchData;
+ if (bis108) {
+ retValue = setAuthMatchData(matchData);
+ appendToLog("setAuthMatchData returns " + retValue);
+ if (retValue) {
+ retValue = rfidReaderChipR2000.rx000Setting.setHST_AUTHENTICATE_CFG(true, true, 0, matchData.length() * 4);
+ appendToLog("setHST_AUTHENTICATE_CFG returns " + retValue);
+ }
+ return retValue;
+ } else {
+ boolean bValue = rfidReaderChipE710.rx000Setting.setAuthenticateConfig(((matchData.length() * 4) << 10) | (0 << 2) | 0x03);
+ appendToLog("setAuthenticateConfiguration 1 revised matchData = " + matchData + " with bValue = " + (bValue ? "true" : "false"));
+ appendToLog("revised bytes = " + utility.byteArrayToString(utility.string2ByteArray(matchData)));
+ if (bValue) {
+ if (true)
+ bValue = rfidReaderChipE710.rx000Setting.setAuthenticateMessage(utility.string2ByteArray(matchData));
+ else
+ bValue = rfidReaderChipE710.rx000Setting.setAuthenticateMessage(new byte[]{
+ 0, 0, (byte) 0xFD, (byte) 0x5D,
+ (byte) 0x80, 0x48, (byte) 0xF4, (byte) 0x8D,
+ (byte) 0xD0, (byte) 0x9A, (byte) 0xAD, 0x22});
+ appendToLog("setAuthenticateConfiguration 2: bValue = " + (bValue ? "true" : "false"));
+ }
+ if (bValue) {
+ bValue = rfidReaderChipE710.rx000Setting.setAuthenticateResponseLen(16 * 8);
+ appendToLog("setAuthenticateConfiguration 3: bValue = " + (bValue ? "true" : "false"));
+ }
+ return bValue;
+ }
+ }
+ public boolean setTam2Configuration(int keyId, String matchData, int profile, int offset, int blockId, int protMode) {
+ if (keyId > 255) return false;
+ if (matchData == null) matchData = "";
+ if (matchData.length() != 20) return false;
+ if (profile > 15) return false;
+ if (offset > 0xFFF) return false;
+ if (blockId > 15) return false;
+ if (protMode > 15) return false;
+
+ boolean retValue = false;
+ String preChallenge = "20";
+ String postChallenge;
+ preChallenge += String.format("%02X", keyId);
+ postChallenge = String.valueOf(profile);
+ postChallenge += String.format("%03X", offset);
+ postChallenge += String.valueOf(blockId);
+ postChallenge += String.valueOf(protMode);
+ matchData = preChallenge + matchData + postChallenge;
+ if (bis108) {
+ retValue = setAuthMatchData(matchData);
+ if (retValue) {
+ retValue = rfidReaderChipR2000.rx000Setting.setHST_AUTHENTICATE_CFG(true, true, 0, matchData.length() * 4);
+ }
+ return retValue;
+ } else {
+ boolean bValue = rfidReaderChipE710.rx000Setting.setAuthenticateConfig(((matchData.length() * 4) << 10) | (0 << 2) | 0x03);
+ appendToLog("setAuthenticateConfiguration 1 revised matchData = " + matchData + " with bValue = " + (bValue ? "true" : "false"));
+ appendToLog("revised bytes = " + utility.byteArrayToString(utility.string2ByteArray(matchData)));
+ if (bValue) {
+ if (true)
+ bValue = rfidReaderChipE710.rx000Setting.setAuthenticateMessage(utility.string2ByteArray(matchData));
+ else
+ bValue = rfidReaderChipE710.rx000Setting.setAuthenticateMessage(new byte[]{
+ 0, 0, (byte) 0xFD, (byte) 0x5D,
+ (byte) 0x80, 0x48, (byte) 0xF4, (byte) 0x8D,
+ (byte) 0xD0, (byte) 0x9A, (byte) 0xAD, 0x22});
+ appendToLog("setAuthenticateConfiguration 2: bValue = " + (bValue ? "true" : "false"));
+ }
+ if (bValue) {
+ int iSize = 32;
+ if (protMode > 2) iSize = 44;
+ bValue = rfidReaderChipE710.rx000Setting.setAuthenticateResponseLen(iSize * 8);
+ appendToLog("setAuthenticateConfiguration 3: protMode = " + protMode + ", bValue = " + (bValue ? "true" : "false"));
+ }
+ return bValue;
+ }
+ }
+ public int getUntraceableEpcLength() {
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.getUntraceableEpcLength() : rfidReaderChipE710.rx000Setting.getUntraceableEpcLength());
+ }
+ public boolean setUntraceable(boolean bHideEpc, int ishowEpcSize, int iHideTid, boolean bHideUser, boolean bHideRange) {
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.setHST_UNTRACEABLE_CFG(bHideRange ? 2 : 0, bHideUser, iHideTid, ishowEpcSize, bHideEpc, false) : rfidReaderChipE710.rx000Setting.setHST_UNTRACEABLE_CFG(bHideRange ? 2 : 0, bHideUser, iHideTid, ishowEpcSize, bHideEpc, false));
+ }
+ public boolean setUntraceable(int range, boolean user, int tid, int epcLength, boolean epc, boolean uxpc) {
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.setHST_UNTRACEABLE_CFG(range, user, tid, epcLength, epc, uxpc) : rfidReaderChipE710.rx000Setting.setHST_UNTRACEABLE_CFG(range, user, tid, epcLength, epc, uxpc));
+ }
+ public boolean setAuthenticateConfiguration() {
+ boolean bValue = (bis108 ?
+ rfidReaderChipR2000.rx000Setting.setHST_AUTHENTICATE_CFG(true, true, 1, 48)
+ : rfidReaderChipE710.rx000Setting.setAuthenticateConfig((48 << 10) | (1 << 2) | 0x03));
+ if (bis108) {
+ if (bValue) {
+ bValue = rfidReaderChipR2000.rx000Setting.setAuthMatchData("049CA53E55EA"); //setAuthenticateMessage(new byte[] { 0x04, (byte)0x9C, (byte)0xA5, 0x3E, 0x55, (byte)0xEA } );
+ appendToLog("setAuthenuateConfiguration 2: bValue = " + (bValue ? "true" : "false"));
+ }
+ /*if (bValue) {
+ bValue = mRfidDevice.mRfidReaderChip.mRfidReaderChip.mRx000Setting.setAuthenticateResponseLen(16 * 8);
+ appendToLog("setAuthenuateConfiguration 3: bValue = " + (bValue ? "true" : "false"));
+ }*/
+ return false; //bValue;
+ } else {
+ if (bValue) {
+ bValue = rfidReaderChipE710.rx000Setting.setAuthenticateMessage(new byte[]{0x04, (byte) 0x9C, (byte) 0xA5, 0x3E, 0x55, (byte) 0xEA});
+ appendToLog("setAuthenticateConfiguration 2: bValue = " + (bValue ? "true" : "false"));
+ }
+ if (bValue) {
+ bValue = rfidReaderChipE710.rx000Setting.setAuthenticateResponseLen(16 * 8);
+ appendToLog("setAuthenticateConfiguration 3: bValue = " + (bValue ? "true" : "false"));
+ }
+ return bValue;
+ }
+ }
+ public int getRetryCount() {
+ if (bis108) {
+ int algoSelect;
+ algoSelect = rfidReaderChipR2000.rx000Setting.getAlgoSelect();
+ if (algoSelect == 0 || algoSelect == 3) {
+ return rfidReaderChipR2000.rx000Setting.getAlgoRetry(algoSelect);
+ } else return -1;
+ } else {
+ return rfidReaderChipE710.rx000Setting.getAlgoMinQCycles();
+ }
+ }
+ public boolean setRetryCount(int retryCount) {
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.setAlgoRetry(retryCount) : rfidReaderChipE710.rx000Setting.setAlgoMinQCycles(retryCount));
+ }
+ public int getInvSelectIndex() {
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.getInvSelectIndex(): rfidReaderChipE710.rx000Setting.getInvSelectIndex());
+ }
+ public boolean getSelectEnable() {
+ int iValue = (bis108 ?
+ rfidReaderChipR2000.rx000Setting.getSelectEnable() :
+ rfidReaderChipE710.rx000Setting.getSelectEnable());
+ return iValue > 0 ? true : false;
+ }
+ public int getSelectTarget() {
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.getSelectTarget() : rfidReaderChipE710.rx000Setting.getSelectTarget());
+ }
+ public int getSelectAction() {
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.getSelectAction() : rfidReaderChipE710.rx000Setting.getSelectAction());
+ }
+ public int getSelectMaskBank() {
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.getSelectMaskBank() : rfidReaderChipE710.rx000Setting.getSelectMaskBank());
+ }
+ public int getSelectMaskOffset() {
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.getSelectMaskOffset() : rfidReaderChipE710.rx000Setting.getSelectMaskOffset());
+ }
+ public String getSelectMaskData() {
+ int iValue1;
+ iValue1 = (bis108 ? rfidReaderChipR2000.rx000Setting.getSelectMaskLength() : rfidReaderChipE710.rx000Setting.getSelectMaskLength());
+ if (iValue1 < 0) return null;
+ String strValue = (bis108 ? rfidReaderChipR2000.rx000Setting.getSelectMaskData() : rfidReaderChipE710.rx000Setting.getSelectMaskData());
+ if (strValue == null) return null;
+ int strLength = iValue1 / 4;
+ if (strLength * 4 != iValue1) strLength++;
+ if (false) appendToLog("Mask data = iValue1 = " + iValue1 + ", strValue = " + strValue + ", strLength = " + strLength);
+ if (strValue.length() < strLength) strLength = strValue.length();
+ return strValue.substring(0, strLength);
+ }
+ public boolean setInvSelectIndex(int invSelect) {
+ if (false) appendToLog("BtDataOut: RfidReader.setSelectIndex goes to setInvSelectIndex");
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.setInvSelectIndex(invSelect) : rfidReaderChipE710.rx000Setting.setInvSelectIndex(invSelect));
+ }
+ public int findFirstEmptySelect() {
+ int iValue = -1, iSelectEnable;
+ for (int i = 0; i < 3; i++) {
+ if (false) appendToLog("RfidReader.findFirstEmptySelect goes to setInvSelectIndex with i = " + i);
+ if (bis108) rfidReaderChipR2000.rx000Setting.setInvSelectIndex(i);
+ iSelectEnable = (bis108 ? rfidReaderChipR2000.rx000Setting.getSelectEnable() : rfidReaderChipE710.rx000Setting.selectConfiguration[i][0]);
+ if (iSelectEnable == 0) {
+ iValue = i;
+ appendToLog("cs710Library4A: setSelectCriteria 1 with New index = " + iValue);
+ break;
+ }
+ }
+ return iValue;
+ }
+ public boolean setSelectCriteriaDisable(int index) {
+ if (bis108) rfidReaderChipR2000.rx000Setting.setQuerySelect(0);
+ else rfidReaderChipE710.rx000Setting.setQuerySelect(0);
+ if (utility.DEBUG_SELECT) appendToLog("Debug_Select: RfidReader.setSelectCriteriaDisable[" + index + "] goes to setSelectCriteria");
+ boolean bValue = false;
+ if (index < 0) {
+ for (int i = 0; i < 3; i++) {
+ bValue = setSelectCriteria(i, false, 0, 0, 0, 0, 0, "");
+ if (bValue == false) {
+ break;
+ }
+ }
+ } else {
+ bValue = setSelectCriteria(index, false, 0, 0, 0, 0, 0, "");
+ }
+ return bValue;
+ }
+ public boolean setSelectCriteria(int index, boolean enable, int target, int action, int bank, int offset, String mask, boolean maskbit) {
+ if (index == 0) settingData.preFilterData = new SettingData.PreFilterData(enable, target, action, bank, offset, mask, maskbit);
+ if (index < 0) index = findFirstEmptySelect();
+ if (index < 0) {
+ appendToLog("cs710Library4A: no index is available !!!"); return false;
+ }
+
+ appendToLog("mask = " + mask + ", maskbit = " + maskbit);
+ if (mask == null) mask = "";
+ int maskblen = mask.length() * 4;
+ String maskHex = ""; int iHex = 0;
+ if (maskbit) {
+ for (int i = 0; i < mask.length(); i++) {
+ iHex <<= 1;
+ if (mask.substring(i, i+1).matches("0")) iHex &= 0xFE;
+ else if (mask.substring(i, i+1).matches("1")) iHex |= 0x01;
+ else return false;
+ if ((i+1) % 4 == 0) maskHex += String.format("%1X", iHex & 0x0F);
+ }
+ int iBitRemain = mask.length() % 4;
+ if (iBitRemain != 0) {
+ iHex <<= (4 - iBitRemain);
+ maskHex += String.format("%1X", iHex & 0x0F);
+ }
+ maskblen = mask.length();
+ mask = maskHex;
+ }
+ if (false) appendToLog("RfidReader.setSelectCriteria goes to setSelectCriteria3");
+ return setSelectCriteria3(index, enable, target, action, 0, bank, offset, mask, maskblen);
+ }
+ public boolean setSelectCriteria(int index, boolean enable, int target, int action, int delay, int bank, int offset, String mask) {
+ if (utility.DEBUG_SELECT) appendToLog("Debug_Select: RfidReader.setSelectCriteria with index = " + index + ", enable = " + enable + ", bSelectedEnable[" + index + "] = " + bSelectEnabled[index]);
+ if (bis108) {
+ if (!enable) {
+ if (bSelectEnabled[index] == enable) return true;
+ }
+ if (false) appendToLog("cs108Library4A: setSelectCriteria 2 with index = " + index + ", enable = " + enable + ", target = " + target + ", action = " + action + ", delay = " + delay + ", bank = " + bank + ", offset = " + offset + ", mask = " + mask);
+ if (index < 0) index = findFirstEmptySelect();
+ if (index < 0) {
+ appendToLog("cs710Library4A: no index is available !!!");
+ return false;
+ }
+
+ if (index == 0)
+ settingData.preFilterData = new SettingData.PreFilterData(enable, target, action, bank, offset, mask, false);
+ if (mask == null) mask = "";
+ if (mask.length() > 64) mask = mask.substring(0, 64);
+ if (index == 0)
+ preMatchData = new RfidReader.PreMatchData(enable, target, action, bank, offset, mask, mask.length() * 4, rfidReaderChipR2000.rx000Setting.getQuerySelect(), getPwrlevel(), getInvAlgo(), getQValue());
+ boolean result = true;
+ if (index != rfidReaderChipR2000.rx000Setting.getInvSelectIndex()) {
+ if (false) appendToLog("RfidReader.setSelectCriteria goes to setInvSelectIndex");
+ result = rfidReaderChipR2000.rx000Setting.setInvSelectIndex(index);
+ }
+ if (rfidReaderChipR2000.rx000Setting.getSelectEnable() == 0 && enable == false) {
+ appendToLog("cs108Library4A: setSelectCriteria 2: no need to set as when index = " + index + ", getSelectEnable() = " + rfidReaderChipR2000.rx000Setting.getSelectEnable() + ", new enable = " + enable);
+ result = true;
+ } else {
+ if (utility.DEBUG_SELECT) appendToLog("Debug_Select: RfidReader.setSelectCriteria goes to setSelectEnable with result = " + result);
+ if (result)
+ result = rfidReaderChipR2000.rx000Setting.setSelectEnable(enable ? 1 : 0, target, action, delay);
+ if (result) result = rfidReaderChipR2000.rx000Setting.setSelectMaskBank(bank);
+ if (result) result = rfidReaderChipR2000.rx000Setting.setSelectMaskOffset(offset);
+ if (mask == null) return false;
+ if (result)
+ result = rfidReaderChipR2000.rx000Setting.setSelectMaskLength(mask.length() * 4);
+ if (result) result = rfidReaderChipR2000.rx000Setting.setSelectMaskData(mask);
+ if (false) appendToLog("RfidReader.setSelectCriteria with result = " + result + ", enable = " + enable);
+ if (result) {
+ if (enable) {
+ rfidReaderChipR2000.rx000Setting.setTagSelect(1);
+ rfidReaderChipR2000.rx000Setting.setQuerySelect(3);
+ } else {
+ rfidReaderChipR2000.rx000Setting.setTagSelect(0);
+ rfidReaderChipR2000.rx000Setting.setQuerySelect(0);
+ }
+ }
+ }
+ if (result) {
+ bSelectEnabled[index] = enable;
+ }
+ return result;
+ } else {
+ boolean bValue = false, DEBUG = false;
+ appendToLog("cs710Library4A: setSelectCriteria 2 with index = " + index + ", enable = " + enable + ", target = " + target + ", action = " + action + ", delay = " + delay + ", bank = " + bank + ", offset = " + offset + ", mask = " + mask);
+ if (index < 0) index = findFirstEmptySelect();
+ if (index < 0) {
+ appendToLog("cs710Library4A: no index is available !!!"); return false;
+ }
+
+ if (rfidReaderChipE710.rx000Setting.selectConfiguration[index] == null) appendToLog("CANNOT continue as selectConfiguration[" + index + "] is null !!!");
+ else if (rfidReaderChipE710.rx000Setting.selectConfiguration[index][0] != 0 || enable != false) {
+ if (DEBUG) appendToLog("0 selectConfiguration[" + index + "] = " + utility.byteArrayToString(rfidReaderChipE710.rx000Setting.selectConfiguration[index]));
+ byte[] byteArrayMask = null;
+ if (mask != null) byteArrayMask = utility.string2ByteArray(mask);
+ bValue = rfidReaderChipE710.rx000Setting.setSelectConfiguration(index, enable, bank, offset, byteArrayMask, target, action, delay);
+ if (DEBUG) appendToLog("0 selectConfiguration[" + index + "] = " + utility.byteArrayToString(rfidReaderChipE710.rx000Setting.selectConfiguration[index]));
+ } else {
+ appendToLog("cs710Library4A: setSelectCriteria 2: no need to set as old selectConfiguration[" + index + "][0] = " + rfidReaderChipE710.rx000Setting.selectConfiguration[index][0] + ", new enable = " + enable);
+ bValue = true;
+ }
+ return bValue;
+ }
+ }
+ public boolean getRssiFilterEnable() {
+ int iValue = (bis108 ? rfidReaderChipR2000.rx000Setting.getRssiFilterType() : rfidReaderChipE710.rx000Setting.getRssiFilterType());
+ if (iValue < 0) return false;
+ iValue &= 0xF;
+ return (iValue > 0 ? true : false);
+ }
+ public int getRssiFilterType() {
+ int iValue = (bis108 ? rfidReaderChipR2000.rx000Setting.getRssiFilterType() : rfidReaderChipE710.rx000Setting.getRssiFilterType());
+ if (iValue < 0) return 0;
+ iValue &= 0xF;
+ if (iValue < 2) return 0;
+ return iValue - 1;
+ }
+ public int getRssiFilterOption() {
+ int iValue = (bis108 ? rfidReaderChipR2000.rx000Setting.getRssiFilterOption() : rfidReaderChipE710.rx000Setting.getRssiFilterOption());
+ if (iValue < 0) return 0;
+ iValue &= 0xF;
+ return iValue;
+ }
+ public boolean setRssiFilterConfig(boolean enable, int rssiFilterType, int rssiFilterOption) {
+ int iValue = 0;
+ if (enable == false) iValue = 0;
+ else iValue = rssiFilterType + 1;
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.setHST_INV_RSSI_FILTERING_CONFIG(iValue, rssiFilterOption) : rfidReaderChipE710.rx000Setting.setHST_INV_RSSI_FILTERING_CONFIG(iValue, rssiFilterOption));
+ }
+ public double getRssiFilterThreshold1() {
+ double dValue;
+ if (bis108) {
+ int iValue = rfidReaderChipR2000.rx000Setting.getRssiFilterThreshold1();
+ byte byteValue = (byte) (iValue & 0xFF);
+ dValue = rfidReaderChipR2000.decodeNarrowBandRSSI(byteValue);
+ } else {
+ int iValue = rfidReaderChipE710.rx000Setting.getRssiFilterThreshold1();
+ dValue = (double) iValue;
+ dValue /= 100;
+ dValue += dBuV_dBm_constant;
+ }
+ return dValue;
+ }
+ public double getRssiFilterThreshold2() {
+ int iValue = (bis108 ? rfidReaderChipR2000.rx000Setting.getRssiFilterThreshold2() : rfidReaderChipE710.rx000Setting.getRssiFilterThreshold2());
+ appendToLog("iValue = " + iValue);
+ byte byteValue = (byte)(iValue & 0xFF);
+ double dValue = (bis108 ? rfidReaderChipR2000.decodeNarrowBandRSSI(byteValue) : rfidReaderChipE710.decodeNarrowBandRSSI(byteValue));
+ return dValue;
+ }
+ public boolean setRssiFilterThreshold(double rssiFilterThreshold1, double rssiFilterThreshold2) {
+ if (bis108) {
+ appendToLog("rssiFilterThreshold = " + rssiFilterThreshold1 + ", " + rssiFilterThreshold2);
+ return rfidReaderChipR2000.rx000Setting.setHST_INV_RSSI_FILTERING_THRESHOLD(rfidReaderChipR2000.encodeNarrowBandRSSI(rssiFilterThreshold1), rfidReaderChipR2000.encodeNarrowBandRSSI(rssiFilterThreshold2));
+ } else {
+ appendToLog("rssiFilterThreshold = " + rssiFilterThreshold1 + ", rssiFilterThreshold2 = " + rssiFilterThreshold2);
+ rssiFilterThreshold1 -= dBuV_dBm_constant;
+ rssiFilterThreshold2 -= dBuV_dBm_constant;
+ appendToLog("After adjustment, rssiFilterThreshold = " + rssiFilterThreshold1 + ", rssiFilterThreshold2 = " + rssiFilterThreshold2);
+ rssiFilterThreshold1 *= 100;
+ rssiFilterThreshold2 *= 100;
+ appendToLog("After multiplication, rssiFilterThreshold = " + rssiFilterThreshold1 + ", rssiFilterThreshold2 = " + rssiFilterThreshold2);
+ return rfidReaderChipE710.rx000Setting.setHST_INV_RSSI_FILTERING_THRESHOLD((int) rssiFilterThreshold1, (int) rssiFilterThreshold2);
+ }
+ }
+ public long getRssiFilterCount() {
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.getRssiFilterCount() : rfidReaderChipE710.rx000Setting.getRssiFilterCount());
+ }
+ public boolean setRssiFilterCount(long rssiFilterCount) {
+ appendToLog("rssiFilterCount = " + rssiFilterCount);
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.setHST_INV_RSSI_FILTERING_COUNT(rssiFilterCount) : rfidReaderChipE710.rx000Setting.setHST_INV_RSSI_FILTERING_COUNT(rssiFilterCount));
+ }
+ public boolean getInvMatchEnable() {
+ int iValue = (bis108 ? rfidReaderChipR2000.rx000Setting.getInvMatchEnable() : rfidReaderChipE710.rx000Setting.getInvMatchEnable());
+ return iValue > 0 ? true : false;
+ }
+ public boolean getInvMatchType() {
+ int iValue = (bis108 ? rfidReaderChipR2000.rx000Setting.getInvMatchType() : rfidReaderChipE710.rx000Setting.getInvMatchType());
+ return iValue > 0 ? true : false;
+ }
+ public int getInvMatchOffset() {
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.getInvMatchOffset() : rfidReaderChipE710.rx000Setting.getInvMatchOffset());
+ }
+ public String getInvMatchData() {
+ int iValue1 = (bis108 ? rfidReaderChipR2000.rx000Setting.getInvMatchLength() : rfidReaderChipE710.rx000Setting.getInvMatchLength());
+ if (iValue1 < 0) return null;
+ String strValue = (bis108 ? rfidReaderChipR2000.rx000Setting.getInvMatchData() : rfidReaderChipE710.rx000Setting.getInvMatchData());
+ int strLength = iValue1 / 4;
+ if (strLength * 4 != iValue1) strLength++;
+ return strValue.substring(0, strLength);
+ }
+ String getSpecialCountryVersion() {
+ boolean DEBUG = false;
+ if (bis108) return rfidReaderChipR2000.rx000OemSetting.getSpecialCountryVersion();
+ String strSpecialCountryCode = null;
+ int iValue = rfidReaderChipE710.rx000Setting.getCountryEnum();
+ if (DEBUG) appendToLog("getCountryEnum 0x3014 = " + iValue);
+ if (iValue > 0 && iValue < countryChannelData.strCountryEnumInfo.length/countryChannelData.iCountryEnumInfoColumn) {
+ String strCountryCode = countryChannelData.strCountryEnumInfo[(iValue - 1) * countryChannelData.iCountryEnumInfoColumn + 2];
+ if (DEBUG) appendToLog("strCountryCode 0 = " + strCountryCode);
+ String[] countryCodePart = strCountryCode.split(" ");
+ if (DEBUG) appendToLog("countryCodePart.length = " + countryCodePart.length);
+ if (countryCodePart.length >= 2) strSpecialCountryCode = countryCodePart[1];
+ else strSpecialCountryCode = "";
+ if (DEBUG) appendToLog("strSpecialCountryCode = " + strSpecialCountryCode);
+ }
+ if (true) {
+ String strValue = rfidReaderChipE710.rx000Setting.getSpecialCountryCodeOem();
+ if (DEBUG) appendToLog("getCountryCodeOem 0xefac = " + strValue);
+ if (strSpecialCountryCode == null && strValue != null) {
+ if (DEBUG) appendToLog("strSpecialCountryCode is replaced with countryCodeOem");
+ strSpecialCountryCode = strValue;
+ }
+ }
+ return strSpecialCountryCode;
+ }
+ public static class PostMatchData {
+ public boolean enable; public boolean target; public int offset; public String mask; public long pwrlevel; public boolean invAlgo; public int qValue;
+ public PostMatchData(boolean enable, boolean target, int offset, String mask, int antennaCycle, long pwrlevel, boolean invAlgo, int qValue) {
+ this.enable = enable;
+ this.target = target;
+ this.offset = offset;
+ this.mask = mask;
+ this.pwrlevel = pwrlevel;
+ this.invAlgo = invAlgo;
+ this.qValue = qValue;
+ }
+ }
+ public PostMatchData postMatchData;
+ public boolean setPostMatchCriteria(boolean enable, boolean target, int offset, String mask) {
+ postMatchData = new RfidReader.PostMatchData(enable, target, offset, mask, getAntennaCycle(), getPwrlevel(), getInvAlgo(), getQValue());
+ boolean result = (bis108 ? rfidReaderChipR2000.rx000Setting.setInvMatchEnable(enable ? 1 : 0, target ? 1 : 0, mask == null ? -1 : mask.length() * 4, offset)
+ : rfidReaderChipE710.rx000Setting.setInvMatchEnable(enable ? 1 : 0, target ? 1 : 0, mask == null ? -1 : mask.length() * 4, offset));
+ if (result && mask != null) result = (bis108 ? rfidReaderChipR2000.rx000Setting.setInvMatchData(mask) : rfidReaderChipE710.rx000Setting.setInvMatchData(mask));
+ return result;
+ }
+ public int rfidToWriteSize() {
+ return mRfidToWrite.size();
+ }
+ public void mrfidToWritePrint() {
+ for (int i = 0; i < mRfidToWrite.size(); i++) {
+ appendToLog(utility.byteArrayToString(mRfidToWrite.get(i).dataValues));
+ }
+ }
+ public long getTagRate() {
+ return (bis108 ? -1 : rfidReaderChipE710.rx000Setting.getTagRate());
+ }
+ public boolean startOperation(RfidReaderChipData.OperationTypes operationTypes) {
+ boolean retValue = false;
+ switch (operationTypes) {
+ case TAG_INVENTORY_COMPACT:
+ case TAG_INVENTORY:
+ case TAG_SEARCHING:
+ //setInventoring(true);
+ if (false && operationTypes == RfidReaderChipData.OperationTypes.TAG_INVENTORY) {
+ //setTam1Configuration(0, "FD5D8048F48DD09AAD22");
+ setTam2Configuration(1, "FD5D8048F48DD09AAD22", 0, 0, 1, 1);
+ setInvAuthenticate(true);
+ }
+ if (utility.DEBUG_COMPACT) appendToLog("Debug_Compact 0: RfidReadder.startOperation operationTypes is " + operationTypes.toString());
+ if (operationTypes == RfidReaderChipData.OperationTypes.TAG_INVENTORY_COMPACT) {
+ setTagDelay2RfidReader(0); setMatchRep(0);
+ if (false && tagFocus >= 1) {
+ setTagGroup(-1, 1, 0); //Set Session S1, Target A
+ setTagDelay2RfidReader(0);
+ setAntennaDwell(2000);
+ }
+ if (utility.DEBUG_COMPACT) appendToLog("Debug_Compact 4: RfidReadder.startOperation goes to setInvModeCompact");
+ setInvModeCompact(true);
+ } else {
+ setTagDelay2RfidReader(tagDelayDefaultNormalSetting);
+ if (bis108) {
+ rfidReaderChipR2000.rx000Setting.setCycleDelay(cycleDelaySetting);
+ } else {
+ rfidReaderChipE710.rx000Setting.setCycleDelay(cycleDelaySetting);
+ }
+ setInvModeCompact(false);
+ if (utility.DEBUG_COMPACT) appendToLog("Debug_Compact 5: RfidReadder.startOperation goes to setInvModeCompact");
+ if (operationTypes == RfidReaderChipData.OperationTypes.TAG_SEARCHING && bis108 == false) rfidReaderChipE710.rx000Setting.setDupElimRollWindow((byte)0);
+ }
+ if (bis108) {
+ notificationConnector.getAutoRFIDAbort();
+ notificationConnector.setAutoRFIDAbort(true);
+ notificationConnector.getAutoRFIDAbort();
+ rfidReaderChipR2000.setPwrManagementMode(false);
+ appendToLog("going to sendHostRegRequestHST_CMD(Cs108Library4A.HostCommands.CMD_18K6CINV)");
+
+ retValue = true;
+ RfidReaderChipData.HostCommands hostCommand = RfidReaderChipData.HostCommands.CMD_18K6CINV;
+ retValue = rfidReaderChipR2000.sendHostRegRequestHST_CMD(hostCommand);
+ break;
+ } else {
+ rfidReaderChipE710.rx000Setting.setEventPacketUplinkEnable((byte)0x09);
+ rfidReaderChipE710.setPwrManagementMode(false);
+ RfidReaderChipData.HostCommands hostCommands = RfidReaderChipData.HostCommands.CMD_18K6CINV;
+ appendToLog("BtData: tagFocus = " + rfidReaderChipE710.rx000Setting.getImpinjExtension());
+ boolean bTagFocus = ((rfidReaderChipE710.rx000Setting.getImpinjExtension() & 0x04) != 0);
+ appendToLog("0 OperationTypes = " + operationTypes.toString() + ", hostCommands = " + hostCommands.toString() + ", bTagFocus = " + bTagFocus);
+ if (operationTypes == RfidReaderChipData.OperationTypes.TAG_INVENTORY_COMPACT) hostCommands = RfidReaderChipData.HostCommands.CMD_18K6CINV_COMPACT;
+ else if (rfidReaderChipE710.rx000Setting.getTagRead() != 0 && bTagFocus == false) hostCommands = RfidReaderChipData.HostCommands.CMD_18K6CINV_MB;
+ appendToLog("1 OperationTypes = " + operationTypes.toString() + ", hostCommands = " + hostCommands.toString());
+ if (true) {
+ appendToLog("BtDataOut: 3030: " + utility.byteArrayToString(rfidReaderChipE710.rx000Setting.antennaPortConfig[0]));
+ appendToLog("BtDataOut: 3140: " + utility.byteArrayToString(rfidReaderChipE710.rx000Setting.selectConfiguration[0]));
+ appendToLog("BtDataOut: 3270: " + utility.byteArrayToString(rfidReaderChipE710.rx000Setting.multibankReadConfig[0]));
+ appendToLog("BtDataOut: 3277: " + utility.byteArrayToString(rfidReaderChipE710.rx000Setting.multibankReadConfig[1]));
+ appendToLog("BtDataOut: 3908: " + utility.byteArrayToString(rfidReaderChipE710.rx000Setting.intraPacketDelay));
+ }
+ retValue = rfidReaderChipE710.sendHostRegRequestHST_CMD(hostCommands);
+ break;
+ }
+ }
+ return retValue;
+ }
+ public boolean abortOperation() {
+ boolean bRetValue = (bis108 ? rfidReaderChipR2000.sendControlCommand(RfidReaderChipR2000.ControlCommands.ABORT) : rfidReaderChipE710.sendHostRegRequestHST_CMD(RfidReaderChipData.HostCommands.NULL));
+ setInventoring(false);
+ return bRetValue;
+ }
+ public boolean setMatchRep(int matchRep) {
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.setMatchRep(matchRep) : rfidReaderChipE710.rx000Setting.setMatchRep(matchRep));
+ }
+ public String[] getCountryList() {
+ String[] strCountryList = null;
+ RegionCodes[] regionList = getRegionList();
+ if (regionList != null) {
+ strCountryList = new String[regionList.length];
+ for (int i = 0; i < regionList.length; i++) {
+ strCountryList[i] = regionCode2StringArray(regionList[i]);
+ }
+ }
+ return strCountryList;
+ }
+ public int countryInList = -1, countryInListDefault = -1;
+ public int getCountryNumberInList() {
+ return countryInList;
+ }
+ public boolean setCountryInList(int countryInList) {
+ if (bis108) {
+ boolean DEBUG = true;
+ if (DEBUG)
+ appendToLog("this.countryInList =" + this.countryInList + ", countryInList = " + countryInList);
+ if (this.countryInList == countryInList) return true;
+
+ RegionCodes[] regionList = getRegionList();
+ if (DEBUG)
+ appendToLog("regionList length =" + (regionList == null ? "NULL" : regionList.length));
+ if (regionList == null) return false;
+ if (countryInList < 0 || countryInList >= regionList.length) return false;
+
+ int[] freqDataTableOld = FreqTable(regionCode);
+ if (DEBUG)
+ appendToLog("regionCode =" + regionCode + ", freqDataTableOld length = " + (freqDataTableOld == null ? "NULL" : freqDataTableOld.length));
+ if (freqDataTableOld == null) return false;
+
+ RegionCodes regionCodeNew = regionList[countryInList];
+ final int[] freqDataTable = FreqTable(regionCodeNew);
+ if (DEBUG)
+ appendToLog("regionCodeNew =" + regionCodeNew + ", freqDataTable length = " + (freqDataTable == null ? "NULL" : freqDataTable.length));
+ if (freqDataTable == null) return false;
+
+ this.countryInList = countryInList;
+ appendToLog("saveSetting2File testpoint 4");
+ regionCode = regionCodeNew;
+ if (DEBUG)
+ appendToLog("getChannel =" + getChannel() + ", FreqChnCnt = " + FreqChnCnt());
+ appendToLog("X channel = ");
+ if (getChannel() >= FreqChnCnt()) setChannel(0);
+ switch (getCountryCode()) {
+ case 1:
+ case 5:
+ case 8:
+ case 9:
+ break;
+ case 2:
+ if (false && regionCode == regionCodeDefault4Country2) {
+ if (DEBUG) appendToLog("FCC Region is set");
+// toggledConnection = false;
+// mHandler.removeCallbacks(runnableToggleConnection);
+// mHandler.postDelayed(runnableToggleConnection, 500);
+ return true;
+ }
+ default: // 2, 4, 7
+ if (freqDataTable.length == freqDataTableOld.length) {
+ int i = 0;
+ for (; i < freqDataTable.length; i++) {
+ if (freqDataTable[i] != freqDataTableOld[i]) break;
+ }
+ if (i == freqDataTable.length) {
+ if (DEBUG) appendToLog("Break as same freqDataTable");
+ break;
+ }
+ }
+ if (DEBUG) appendToLog("Finish as different freqDataTable");
+ int k = 0;
+ for (; k < freqDataTable.length; k++) {
+ if (DEBUG) appendToLog("Setting channel = " + k);
+ rfidReaderChipR2000.rx000Setting.setFreqChannelSelect(k);
+ rfidReaderChipR2000.rx000Setting.setFreqChannelConfig(true);
+ rfidReaderChipR2000.rx000Setting.setFreqPllMultiplier(freqDataTable[k]);
+ }
+ for (; k < 50; k++) {
+ if (DEBUG) appendToLog("Resetting channel = " + k);
+ rfidReaderChipR2000.rx000Setting.setFreqChannelSelect(k);
+ rfidReaderChipR2000.rx000Setting.setFreqChannelConfig(false);
+ }
+ break;
+ }
+ if (DEBUG)
+ appendToLog("New regionCode = " + regionCode.toString() + ", channel = " + getChannel() + ", FreqChnCnt = " + FreqChnCnt());
+ return true;
+ } else {
+ boolean DEBUG = true;
+ if (this.countryInList == countryInList) return true;
+
+ if (DEBUG) appendToLog("1 setCountryInList with countryInList = " + countryInList);
+ RegionCodes[] regionList = getRegionList();
+ if (regionList == null) return false;
+
+ RegionCodes regionCodeNew = regionList[countryInList];
+ regionCode = regionCodeNew;
+
+ int indexBegin = RegionCodes.Albania1.ordinal();
+ int indexEnd = RegionCodes.Vietnam3.ordinal();
+ int i = indexBegin;
+ for (; i < indexEnd + 1; i++) {
+ if (regionCode == RegionCodes.values()[i]) {
+ break;
+ }
+ }
+
+ boolean bValue = false;
+ if (i < indexEnd + 1) {
+ appendToLog("countryEnum: i = " + i + ", indexEnd = " + indexEnd);
+ bValue = rfidReaderChipE710.rx000Setting.setCountryEnum((short)(i - indexBegin + 1));
+ if (bValue) {
+ this.countryInList = countryInList;
+ channelOrderType = -1;
+ }
+ }
+ if (DEBUG) appendToLog("1A setCountryInList with bValue = " + bValue);
+ return bValue;
+ }
+ }
+ public int channelOrderType; // 0 for frequency hopping / agile, 1 for fixed frequencey
+ public boolean getChannelHoppingStatus() {
+ if (bis108) {
+ appendToLog("countryCode with channelOrderType = " + channelOrderType);
+ if (channelOrderType < 0) {
+ if (getChannelHoppingDefault()) channelOrderType = 0;
+ else channelOrderType = 1;
+ }
+ return (channelOrderType == 0 ? true : false);
+ } else {
+ boolean bValue = false, DEBUG = false;
+ int iValue = rfidReaderChipE710.rx000Setting.getCountryEnum(); //iValue--;
+ if (DEBUG) appendToLog("getChannelHoppingStatus: countryEnum = " + iValue);
+ if (iValue > 0) {
+ String strFixedHop = countryChannelData.strCountryEnumInfo[(iValue - 1) * countryChannelData.iCountryEnumInfoColumn + 4];
+ if (DEBUG) appendToLog("getChannelHoppingStatus: FixedHop = " + strFixedHop);
+ if (strFixedHop.matches("Hop")) {
+ if (DEBUG) appendToLog("getChannelHoppingStatus: matched");
+ bValue = true;
+ }
+ }
+ if (DEBUG) appendToLog("getChannelHoppingStatus: bValue = " + bValue);
+ return bValue; //1 for hopping, 0 for fixed
+ }
+ }
+ public boolean setChannelHoppingStatus(boolean channelOrderHopping) {
+ if (this.channelOrderType != (channelOrderHopping ? 0 : 1)) {
+ if (bis108) {
+ boolean result = true;
+ if (getChannelHoppingDefault() == false) {
+ result = rfidReaderChipR2000.rx000Setting.setAntennaFreqAgile(channelOrderHopping ? 1 : 0);
+ }
+ int freqcnt = FreqChnCnt();
+ appendToLog("FrequencyA Count = " + freqcnt);
+ int channel = getChannel();
+ appendToLog(" FrequencyA Channel = " + channel);
+ for (int i = 0; i < freqcnt; i++) {
+ if (result == true) rfidReaderChipR2000.rx000Setting.setFreqChannelSelect(i);
+ if (result == true) rfidReaderChipR2000.rx000Setting.setFreqChannelConfig(channelOrderHopping);
+ }
+ if (result == true) rfidReaderChipR2000.rx000Setting.setFreqChannelSelect(channel);
+ if (result == true) rfidReaderChipR2000.rx000Setting.setFreqChannelConfig(true);
+ } else {
+ boolean result = true;
+ if (getChannelHoppingDefault() == false) {
+ result = rfidReaderChipE710.rx000Setting.setAntennaFreqAgile(channelOrderHopping ? 1 : 0);
+ }
+ int freqcnt = FreqChnCnt(); appendToLog("FrequencyA Count = " + freqcnt);
+ int channel = getChannel(); appendToLog(" FrequencyA Channel = " + channel);
+ }
+ appendToLog(" FrequencyA: end of setting");
+
+ this.channelOrderType = (channelOrderHopping ? 0 : 1);
+ appendToLog("setChannelHoppingStatus: channelOrderType = " + channelOrderType);
+ }
+ return true;
+ }
+ public String[] getChannelFrequencyList() {
+ if (bis108) {
+ boolean DEBUG = true;
+ appendToLog("regionCode is " + regionCode.toString());
+ double[] table = GetAvailableFrequencyTable(regionCode);
+ appendToLog("table length = " + table.length);
+ for (int i = 0; i < table.length; i++) appendToLog("table[" + i + "] = " + table[i]);
+ String[] strChannnelFrequencyList = new String[table.length];
+ for (int i = 0; i < table.length; i++) {
+ strChannnelFrequencyList[i] = String.format("%.2f MHz", table[i]);
+ appendToLog("strChannnelFrequencyList[" + i + "] = " + strChannnelFrequencyList[i]);
+ }
+ return strChannnelFrequencyList;
+ } else {
+ boolean DEBUG = true;
+ int iCountryEnum = rfidReaderChipE710.rx000Setting.getCountryEnum();
+ appendToLog("countryEnum = " + iCountryEnum);
+ appendToLog("i = " + iCountryEnum + ", " + countryChannelData.strCountryEnumInfo[(iCountryEnum - 1) * countryChannelData.iCountryEnumInfoColumn + 0]
+ + ", " + countryChannelData.strCountryEnumInfo[(iCountryEnum - 1) * countryChannelData.iCountryEnumInfoColumn + 1]
+ + ", " + countryChannelData.strCountryEnumInfo[(iCountryEnum - 1) * countryChannelData.iCountryEnumInfoColumn + 2]
+ + ", " + countryChannelData.strCountryEnumInfo[(iCountryEnum - 1) * countryChannelData.iCountryEnumInfoColumn + 3]
+ + ", " + countryChannelData.strCountryEnumInfo[(iCountryEnum - 1) * countryChannelData.iCountryEnumInfoColumn + 4]
+ + ", " + countryChannelData.strCountryEnumInfo[(iCountryEnum - 1) * countryChannelData.iCountryEnumInfoColumn + 5]
+ + ", " + countryChannelData.strCountryEnumInfo[(iCountryEnum - 1) * countryChannelData.iCountryEnumInfoColumn + 6]
+ );
+ int iFrequencyCount = Integer.valueOf(countryChannelData.strCountryEnumInfo[(iCountryEnum - 1) * countryChannelData.iCountryEnumInfoColumn + 3]);
+ int iFrequencyInterval = Integer.valueOf(countryChannelData.strCountryEnumInfo[(iCountryEnum - 1) * countryChannelData.iCountryEnumInfoColumn + 5]);
+ float iFrequencyStart = Float.valueOf(countryChannelData.strCountryEnumInfo[(iCountryEnum - 1) * countryChannelData.iCountryEnumInfoColumn + 6]);
+ appendToLog("iFrequencyCount = " + iFrequencyCount + ", interval = " + iFrequencyInterval + ", start = " + iFrequencyStart);
+
+ String[] strChannnelFrequencyList = new String[iFrequencyCount];
+ for (int i = 0; i < iFrequencyCount ; i++) {
+ strChannnelFrequencyList[i] = String.format("%.2f MHz", (iFrequencyStart * 1000 + iFrequencyInterval * i) / 1000);
+ appendToLog("strChannnelFrequencyList[" + i + "] = " + strChannnelFrequencyList[i]);
+ }
+ return strChannnelFrequencyList;
+ }
+ }
+ public int getChannel() {
+ if (true) return settingData.channel;
+ if (bis108) {
+ int channel = -1;
+ if (rfidReaderChipR2000.rx000Setting.getFreqChannelConfig() != 0) {
+ channel = rfidReaderChipR2000.rx000Setting.getFreqChannelSelect();
+ }
+ if (getChannelHoppingStatus()) {
+ channel = 0;
+ }
+ return channel;
+ } else {
+ int channel = -1;
+ channel = rfidReaderChipE710.rx000Setting.getFrequencyChannelIndex();
+ if (getChannelHoppingStatus()) channel = 0;
+ else if (channel > 0) channel--;
+ return channel;
+ }
+ }
+ public boolean setChannel(int channelSelect) {
+ if (bis108) {
+ boolean result = true;
+ if (result == true) result = rfidReaderChipR2000.rx000Setting.setFreqChannelConfig(false);
+ if (result == true)
+ result = rfidReaderChipR2000.rx000Setting.setFreqChannelSelect(channelSelect);
+ if (result == true) result = rfidReaderChipR2000.rx000Setting.setFreqChannelConfig(true);
+ if (result) settingData.channel = channelSelect;
+ return result;
+ } else {
+ boolean result = true; int channel = channelSelect;
+ if (getChannelHoppingStatus()) channelSelect = 0;
+ else channelSelect++;
+ if (result == true) result = rfidReaderChipE710.rx000Setting.setFrequencyChannelIndex((byte)(channelSelect & 0xFF));
+ if (result) settingData.channel = channel;
+ return result;
+ }
+ }
+ public byte getPopulation2Q(int population) {
+ double dValue = 1 + log10(population * 2) / log10(2);
+ if (dValue < 0) dValue = 0;
+ if(dValue > 15) dValue = 15;
+ byte iValue = (byte) dValue;
+ if (DEBUG || true) appendToLog("getPopulation2Q(" + population + "): log dValue = " + dValue + ", iValue = " + iValue);
+ return iValue;
+ }
+ public int population = 30;
+ public int getPopulation() {
+ return population;
+ }
+ public boolean setPopulation(int population) {
+ if (true) appendToLog("setPopulation " + population);
+ byte iValue = getPopulation2Q(population);
+ if (true) appendToLog("getPopulation2Q = " + iValue);
+ this.population = population;
+ return setQValue(iValue);
+ }
+ public byte qValueSetting = -1;
+ public byte getQValue() {
+ return qValueSetting;
+ }
+ public boolean setQValue(byte byteValue) {
+ qValueSetting = byteValue;
+ if (false) appendToLog("Stream population qValue = " + qValueSetting);
+ return setQValue1(byteValue);
+ }
+ int getQValue1() {
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.getAlgoStartQ() : rfidReaderChipE710.rx000Setting.getAlgoStartQ());
+ }
+ public boolean setQValue1(int iValue) {
+ if (bis108) {
+ boolean result = true;
+ {
+ int invAlgo = getInvAlgoInChip();
+ if (iValue != rfidReaderChipR2000.rx000Setting.getAlgoStartQ(invAlgo)) {
+ if (false)
+ appendToLog("setTagGroup: going to setAlgoSelect with invAlgo = " + invAlgo);
+ result = rfidReaderChipR2000.rx000Setting.setAlgoSelect(invAlgo);
+ }
+ }
+ if (result) {
+ result = rfidReaderChipR2000.rx000Setting.setAlgoStartQ(iValue);
+ }
+ return result;
+ } else {
+ boolean result = true;
+ if (false) appendToLog("3 setAlgoStartQ with iValue = " + iValue);
+ result = rfidReaderChipE710.rx000Setting.setAlgoStartQ(iValue);
+ return result;
+ }
+ }
+ public static final double dBuV_dBm_constant = 106.98;
+ public RfidReaderChipData.Rx000pkgData onRFIDEvent() {
+ if (bis108) {
+ RfidReaderChipData.Rx000pkgData rx000pkgData = null;
+ //if (mrfidToWriteSize() != 0) mRfidReaderChip.mRx000ToRead.clear();
+ if (rfidReaderChipR2000.bRx000ToReading == false && rfidReaderChipR2000.mRx000ToRead.size() != 0) {
+ rfidReaderChipR2000.bRx000ToReading = true;
+ int index = 0;
+ try {
+ rx000pkgData = rfidReaderChipR2000.mRx000ToRead.get(index);
+ if (false)
+ appendToLog("rx000pkgData.type = " + rx000pkgData.responseType.toString());
+ rfidReaderChipR2000.mRx000ToRead.remove(index); //appendToLog("mRx000ToRead.remove");
+ } catch (Exception ex) {
+ rx000pkgData = null;
+ }
+ rfidReaderChipR2000.bRx000ToReading = false;
+ }
+ return rx000pkgData;
+ } else {
+ boolean DEBUG = false;
+ RfidReaderChipData.Rx000pkgData rx000pkgData = null;
+ //if (mrfidToWriteSize() != 0) mRfidDevice.mRfidReaderChip.mRfidReaderChip.mRx000ToRead.clear()
+ if (rfidReaderChipE710.bRx000ToReading == false && rfidReaderChipE710.mRx000ToRead.size() != 0) {
+ rfidReaderChipE710.bRx000ToReading = true;
+ int index = 0;
+ try {
+ rx000pkgData = rfidReaderChipE710.mRx000ToRead.get(index);
+ if (false && rx000pkgData.responseType == RfidReaderChipData.HostCmdResponseTypes.TYPE_COMMAND_END)
+ if (DEBUG) appendToLog("get mRx000ToRead with COMMAND_END");
+ rfidReaderChipE710.mRx000ToRead.remove(index);
+ if (DEBUG) appendToLog("got one mRx000ToRead with responseType = " + rx000pkgData.responseType.toString() + ", and remained size = " + rfidReaderChipE710.mRx000ToRead.size());
+ } catch (Exception ex) {
+ rx000pkgData = null;
+ }
+ rfidReaderChipE710.bRx000ToReading = false;
+ }
+
+ if (rx000pkgData != null && rx000pkgData.responseType != null) {
+ if (rx000pkgData.responseType == RfidReaderChipData.HostCmdResponseTypes.TYPE_18K6C_INVENTORY || rx000pkgData.responseType == RfidReaderChipData.HostCmdResponseTypes.TYPE_18K6C_INVENTORY_COMPACT) {
+ if (DEBUG) appendToLog("Before adjustment, decodedRssi = " + rx000pkgData.decodedRssi);
+ rx000pkgData.decodedRssi += dBuV_dBm_constant;
+ if (DEBUG) appendToLog("After adjustment, decodedRssi = " + rx000pkgData.decodedRssi);
+ if (rfidReaderChipE710.rx000Setting.getInvMatchEnable() > 0) {
+ byte[] bytesCompared = new byte[rx000pkgData.decodedEpc.length];
+ System.arraycopy(rx000pkgData.decodedEpc, 0, bytesCompared, 0, rx000pkgData.decodedEpc.length);
+ //bytesCompared = new byte[] { (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0x2F };
+ //bytesCompared = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, (byte) 0xFF, (byte) 0xFF, (byte) 0x2F };
+ appendToLog("decodedEpc = " + utility.byteArrayToString(rx000pkgData.decodedEpc));
+ if (rfidReaderChipE710.rx000Setting.getInvMatchOffset() > 0) {
+ appendToLog("getInvMatchOffset = " + rfidReaderChipE710.rx000Setting.getInvMatchOffset());
+ BigInteger bigInt = new BigInteger(bytesCompared);
+ BigInteger shiftInt = bigInt.shiftLeft(rfidReaderChipE710.rx000Setting.getInvMatchOffset());
+ byte [] shifted = shiftInt.toByteArray();
+ appendToLog("shifted = " + utility.byteArrayToString(shifted));
+ if (shifted.length > bytesCompared.length) System.arraycopy(shifted, shifted.length - bytesCompared.length, bytesCompared, 0, bytesCompared.length);
+ else if (shifted.length < bytesCompared.length) {
+ System.arraycopy(shifted, 0, bytesCompared, bytesCompared.length - shifted.length, shifted.length);
+ for (int i = 0; i < bytesCompared.length - shifted.length; i++) {
+ if ((shifted[0] & 0x80) == 0) bytesCompared[i] = 0;
+ else bytesCompared[i] = (byte)0xFF;
+ }
+ }
+ appendToLog("new bytesCompared 1 = " + utility.byteArrayToString(bytesCompared));
+ }
+
+ if (rfidReaderChipE710.rx000Setting.getInvMatchType() > 0) {
+ appendToLog("getInvMatchType = " + rfidReaderChipE710.rx000Setting.getInvMatchType());
+ for (int i = 0; i < bytesCompared.length; i++) {
+ bytesCompared[i] ^= (byte) 0xFF;
+ }
+ }
+ appendToLog("new bytesCompared 2 = " + utility.byteArrayToString(bytesCompared));
+ appendToLog("getInvMatchData = " + rfidReaderChipE710.rx000Setting.getInvMatchData());
+ if (utility.byteArrayToString(bytesCompared).indexOf(rfidReaderChipE710.rx000Setting.getInvMatchData()) != 0) {
+ appendToLog("Post Mis-Matched !!!");
+ rx000pkgData = null;
+ }
+ }
+ }
+ }
+ if (rx000pkgData != null && DEBUG) appendToLog("response = " + rx000pkgData.responseType.toString() + ", " + utility.byteArrayToString(rx000pkgData.dataValues));
+ return rx000pkgData;
+ }
+ }
+ public String getModelNumber(String strModelName) {
+ if (bis108) {
+ int iCountryCode = getCountryCode();
+ String strCountryCode = "";
+ appendToLog("iCountryCode = " + iCountryCode + ", strModelNumber = " + strModelName);
+ if (strModelName != null && strModelName.length() != 0) {
+ if (iCountryCode > 0)
+ strCountryCode = strModelName + "-" + String.valueOf(iCountryCode) + " " + rfidReaderChipR2000.rx000OemSetting.getSpecialCountryVersion();
+ else strCountryCode = strModelName;
+ }
+ return strCountryCode;
+ } else {
+ boolean DEBUG = false;
+ if (DEBUG) appendToLog("getModelName = " + strModelName);
+ int iCountryCode = getCountryCode();
+ if (DEBUG) appendToLog("getCountryCode = " + iCountryCode);
+ String strSpecialCountryVersion = getSpecialCountryVersion();
+ if (DEBUG) appendToLog("getSpecialCountryVersion = " + strSpecialCountryVersion);
+ int iFreqModifyCode = getFreqModifyCode();
+ if (DEBUG) appendToLog("getFreqModifyCode = " + iFreqModifyCode);
+
+ String strModelNumber = (strModelName == null ? "" : strModelName);
+ if (iCountryCode > 0) strModelNumber += ("-" + String.valueOf(iCountryCode) + (strSpecialCountryVersion == null ? "" : (" " + strSpecialCountryVersion)));
+ if (DEBUG) appendToLog("strModelNumber = " + strModelNumber);
+ return strModelNumber;
+ }
+ }
+ public boolean setRx000KillPassword(String password) {
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.setRx000KillPassword(password) : rfidReaderChipE710.rx000Setting.setRx000KillPassword(password));
+ }
+ public boolean setRx000AccessPassword(String password) {
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.setRx000AccessPassword(password) : rfidReaderChipE710.rx000Setting.setRx000AccessPassword(password));
+ }
+ public boolean setAccessRetry(boolean accessVerfiy, int accessRetry) {
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.setAccessRetry(accessVerfiy, accessRetry) : rfidReaderChipE710.rx000Setting.setAccessRetry(accessVerfiy, accessRetry));
+ }
+ public boolean setInvModeCompact(boolean invModeCompact) {
+ if (utility.DEBUG_COMPACT) appendToLog("Debug_Compact: RfidReader.setInvModeCompact as " + invModeCompact);
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.setInvModeCompact(invModeCompact) : rfidReaderChipE710.rx000Setting.setInvModeCompact(invModeCompact));
+ }
+ public boolean setAccessLockAction(int accessLockAction, int accessLockMask) {
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.setAccessLockAction(accessLockAction, accessLockMask)
+ : rfidReaderChipE710.rx000Setting.setAccessLockAction(accessLockAction, accessLockMask));
+ }
+ public boolean setAccessBank(int accessBank) {
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.setAccessBank(accessBank) : rfidReaderChipE710.rx000Setting.setAccessBank(accessBank));
+ }
+ public boolean setAccessBank(int accessBank, int accessBank2) {
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.setAccessBank(accessBank, accessBank2) : rfidReaderChipE710.rx000Setting.setAccessBank(accessBank, accessBank2));
+ }
+ public boolean setAccessOffset(int accessOffset) {
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.setAccessOffset(accessOffset) : rfidReaderChipE710.rx000Setting.setAccessOffset(accessOffset));
+ }
+ public boolean setAccessOffset(int accessOffset, int accessOffset2) {
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.setAccessOffset(accessOffset, accessOffset2) : rfidReaderChipE710.rx000Setting.setAccessOffset(accessOffset, accessOffset2));
+ }
+ public boolean setAccessCount(int accessCount) {
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.setAccessCount(accessCount) : rfidReaderChipE710.rx000Setting.setAccessCount(accessCount));
+ }
+ public boolean setAccessCount(int accessCount, int accessCount2) {
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.setAccessCount(accessCount, accessCount2) : rfidReaderChipE710.rx000Setting.setAccessCount(accessCount, accessCount2));
+ }
+ public boolean setAccessWriteData(String dataInput) {
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.setAccessWriteData(dataInput) : rfidReaderChipE710.rx000Setting.setAccessWriteData(dataInput));
+ }
+ public boolean setResReadNoReply(boolean resReadNoReply) {
+ return (bis108 ? false : rfidReaderChipE710.rx000Setting.setResReadNoReply(resReadNoReply));
+ }
+ public boolean setTagRead(int tagRead) {
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.setTagRead(tagRead) : rfidReaderChipE710.rx000Setting.setTagRead(tagRead));
+ }
+ public boolean setInvBrandId(boolean invBrandId) {
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.setInvBrandId(invBrandId) : rfidReaderChipE710.rx000Setting.setInvBrandId(invBrandId));
+ }
+ public boolean setInvAuthenticate(boolean invAuthenticate) {
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.setInvAuthenticate(invAuthenticate) : false);
+ }
+ public boolean sendHostRegRequestHST_CMD(RfidReaderChipData.HostCommands hostCommand) {
+ if (bis108) {
+ rfidReaderChipR2000.setPwrManagementMode(false);
+ rfidReaderChipR2000.rx000Setting.setAlgoRetry(5);
+ }
+ else rfidReaderChipE710.setPwrManagementMode(false);
+ return (bis108 ? rfidReaderChipR2000.sendHostRegRequestHST_CMD(hostCommand) : rfidReaderChipE710.sendHostRegRequestHST_CMD(hostCommand));
+ }
+ public boolean setPwrManagementMode(boolean bLowPowerStandby) {
+ return (bis108 ? rfidReaderChipR2000.setPwrManagementMode(bLowPowerStandby) : rfidReaderChipE710.setPwrManagementMode(bLowPowerStandby));
+ }
+ void macRead(int address) {
+ if (bis108) rfidReaderChipR2000.rx000Setting.readMAC(address);
+ else rfidReaderChipE710.rx000Setting.readMAC(address);
+ }
+ public boolean macWrite(int address, long value) {
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.writeMAC(address, value) : rfidReaderChipE710.rx000Setting.writeMAC(address, value));
+ }
+ public void set_fdCmdCfg(int value) {
+ macWrite(0x117, value);
+ }
+ public void set_fdRegAddr(int addr) {
+ macWrite(0x118, addr);
+ }
+ public void set_fdWrite(int addr, long value) {
+ macWrite(0x118, addr);
+ macWrite(0x119, value);
+ }
+ public void set_fdPwd(int value) {
+ macWrite(0x11A, value);
+ }
+ public void set_fdBlockAddr4GetTemperature(int addr) {
+ macWrite(0x11b, addr);
+ }
+ public void set_fdReadMem(int addr, long len) {
+ macWrite(0x11c, addr);
+ macWrite(0x11d, len);
+ }
+ public void set_fdWriteMem(int addr, int len, long value) {
+ set_fdReadMem(addr, len);
+ macWrite(0x11e, value);
+ }
+ public void setImpinJExtension(boolean tagFocus, boolean fastId) {
+ if (rfidReaderChipR2000 != null) {
+ int iValue = 0;
+ if (tagFocus) iValue |= 0x10;
+ if (fastId) iValue |= 0x20;
+ if (false) appendToLog("ivalue = " + iValue + ", impinjExtensionValue = " + rfidReaderChipR2000.rx000Setting.impinjExtensionValue);
+ boolean bRetValue;
+ bRetValue = macWrite(0x203, iValue);
+ } else {
+ boolean bRetValue;
+ bRetValue = rfidReaderChipE710.rx000Setting.setImpinjExtension(tagFocus, fastId);
+ if (bRetValue) this.tagFocus = (tagFocus ? 1 : 0);
+ }
+ }
+ public String getSerialNumber() {
+ return (bis108 ? rfidReaderChipR2000.rx000OemSetting.getSerialNumber() : rfidReaderChipE710.rx000Setting.getBoardSerialNumber());
+ }
+ public boolean isInventoring() {
+ boolean bValue;
+ if (bis108) bValue = rfidReaderChipR2000.isInventoring();
+ else bValue = rfidReaderChipE710.isInventoring();
+ //appendToLog("isInventoring " + bValue + " with bis108 " + bis108);
+ return bValue;
+ }
+ public void setInventoring(boolean enable) {
+ appendToLog("setInventoring " + enable + " with bis108 " + bis108);
+ if (bis108) rfidReaderChipR2000.setInventoring(enable);
+ else rfidReaderChipE710.setInventoring(enable);
+ }
+ void addRfidToWrite(RfidConnector.CsReaderRfidData csReaderRfidData) {
+ if (bis108) rfidReaderChipR2000.addRfidToWrite(csReaderRfidData);
+ else rfidReaderChipE710.addRfidToWrite(csReaderRfidData);
+ }
+ void uplinkHandler() {
+ if (bis108) rfidReaderChipR2000.uplinkHandler();
+ else rfidReaderChipE710.uplinkHandler();
+ }
+ public int getAntennaCycle() {
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.getAntennaCycle() : rfidReaderChipE710.rx000Setting.getAntennaCycle());
+ }
+ public boolean setAntennaCycle(int antennaCycle) {
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.setAntennaCycle(antennaCycle) : rfidReaderChipE710.rx000Setting.setAntennaCycle(antennaCycle));
+ }
+ public boolean setAntennaInvCount(long antennaInvCount) {
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.setAntennaInvCount(antennaInvCount) : rfidReaderChipE710.rx000Setting.setAntennaInvCount(antennaInvCount));
+ }
+ public int getFreqChannelConfig() {
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.getFreqChannelConfig(): -1);
+ }
+ public int getDiagnosticConfiguration() {
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.getDiagnosticConfiguration(): -1);
+ }
+ public boolean setDiagnosticConfiguration(boolean bCommmandActive) {
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.setDiagnosticConfiguration(bCommmandActive): false);
+ }
+ public int getImpinjExtension() {
+ return (bis108 ? rfidReaderChipR2000.rx000Setting.getImpinjExtension(): rfidReaderChipE710.rx000Setting.getImpinjExtension());
+ }
+ public String getProductSerialNumber() {
+ return (bis108 ? rfidReaderChipR2000.rx000OemSetting.getProductSerialNumber(): rfidReaderChipE710.rx000Setting.getProductSerialNumber());
+ }
+ public boolean turnOn(boolean onStatus) {
+ return (bis108 ? rfidReaderChipR2000.turnOn(onStatus): rfidReaderChipE710.turnOn(onStatus));
+ }
+}
+
+
+
+package com.csl.cslibrary4a;
+
+import androidx.annotation.Keep;
+
+public class RfidReaderChipData {
+ public enum OperationTypes {
+ TAG_RDOEM,
+ TAG_INVENTORY_COMPACT, TAG_INVENTORY, TAG_SEARCHING
+ }
+
+ public enum HostCommands {
+ NULL, CMD_WROEM, CMD_RDOEM, CMD_ENGTEST, CMD_MBPRDREG, CMD_MBPWRREG,
+ CMD_18K6CINV, CMD_18K6CREAD, CMD_18K6CWRITE, CMD_18K6CLOCK, CMD_18K6CKILL, CMD_SETPWRMGMTCFG, CMD_18K6CAUTHENTICATE, CMD_UNTRACEABLE,
+ CMD_UPDATELINKPROFILE,
+ CMD_18K6CBLOCKWRITE,
+ CMD_CHANGEEAS, CMD_GETSENSORDATA,
+ CMD_READBUFFER,
+ CMD_FDM_RDMEM, CMD_FDM_WRMEM, CMD_FDM_AUTH, CMD_FDM_GET_TEMPERATURE, CMD_FDM_START_LOGGING, CMD_FDM_STOP_LOGGING,
+ CMD_FDM_WRREG, CMD_FDM_RDREG, CMD_FDM_DEEP_SLEEP, CMD_FDM_OPMODE_CHECK, CMD_FDM_INIT_REGFILE, CMD_FDM_LED_CTRL,
+ CMD_18K6CINV_SELECT,
+ CMD_18K6CINV_COMPACT, CMD_18K6CINV_COMPACT_SELECT,
+ CMD_18K6CINV_MB, CMD_18K6CINV_MB_SELECT
+ }
+
+ public enum HostCmdResponseTypes {
+ NULL,
+ TYPE_COMMAND_BEGIN,
+ TYPE_COMMAND_END,
+ TYPE_18K6C_INVENTORY, TYPE_18K6C_INVENTORY_COMPACT,
+ TYPE_18K6C_TAG_ACCESS,
+ TYPE_ANTENNA_CYCLE_END,
+ TYPE_COMMAND_ACTIVE,
+ TYPE_COMMAND_ABORT_RETURN
+ }
+
+ public static class Rx000pkgData {
+ public RfidReaderChipData.HostCmdResponseTypes responseType;
+ public int flags;
+ public byte[] dataValues;
+ public long decodedTime;
+ public double decodedRssi;
+ public int decodedPhase, decodedChidx, decodedPort;
+ public byte[] decodedPc, decodedEpc, decodedCrc, decodedData1, decodedData2;
+ public String decodedResult;
+ public String decodedError;
+ }
+
+ public enum CsvColumn {
+ RESERVE_BANK,
+ EPC_BANK,
+ TID_BANK,
+ USER_BANK,
+ PHASE,
+ CHANNEL,
+ TIME, TIMEZONE,
+ LOCATION, DIRECTION,
+ OTHERS
+ }
+}
+
+
+
+package com.csl.cslibrary4a;
+
+import static java.lang.Math.log10;
+import static java.lang.Math.pow;
+
+import android.content.Context;
+
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Date;
+
+public class RfidReaderChipE710 {
+ boolean DEBUG_PKDATA;
+ boolean sameCheck = true;
+ //RfidReaderChip mRfidReaderChip;
+ boolean DEBUGTHREAD = false, DEBUG_APDATA = false;
+ int intervalRx000UplinkHandler;
+ boolean aborting = false;
+ Context context; Utility utility; CsReaderConnector csReaderConnector;
+ public RfidReaderChipE710(Context context, Utility utility, CsReaderConnector csReaderConnector) {
+ this.context = context;
+ this.utility = utility; DEBUG_PKDATA = utility.DEBUG_PKDATA;
+ //mRfidReaderChip = new RfidReaderChip();
+ this.csReaderConnector = csReaderConnector;
+ this.DEBUGTHREAD = csReaderConnector.DEBUGTHREAD;
+ this.DEBUG_APDATA = csReaderConnector.DEBUG_APDATA;
+ this.intervalRx000UplinkHandler = csReaderConnector.intervalRx000UplinkHandler;
+ }
+ private String byteArrayToString(byte[] packet) { return utility.byteArrayToString(packet); }
+ private boolean compareArray(byte[] array1, byte[] array2, int length) { return utility.compareByteArray(array1, array2, length); }
+ private void appendToLog(String s) { utility.appendToLog(s); }
+ private void appendToLogView(String s) { utility.appendToLogView(s); }
+ void writeDebug2File(String stringDebug) { utility.writeDebug2File(stringDebug); }
+ private String byteArray2DisplayString(byte[] byteData) { return utility.byteArray2DisplayString(byteData); }
+ private int byteArrayToInt(byte[] bytes) { return utility.byteArrayToInt(bytes); }
+ private double get2BytesOfRssi(byte[] bytes, int index) { return utility.get2BytesOfRssi(bytes, index); }
+ enum ControlCommands {
+ NULL,
+ CANCEL, SOFTRESET, ABORT, PAUSE, RESUME, GETSERIALNUMBER, RESETTOBOOTLOADER
+ }
+ enum HostRegRequests {
+ MAC_OPERATION,
+ //MAC_VER, MAC_LAST_COMMAND_DURATION,
+ //HST_CMNDIAGS,
+ //HST_MBP_ADDR, HST_MBP_DATA,
+ //HST_OEM_ADDR, HST_OEM_DATA,
+ HST_ANT_CYCLES, HST_ANT_DESC_SEL, HST_ANT_DESC_CFG, MAC_ANT_DESC_STAT, HST_ANT_DESC_PORTDEF, HST_ANT_DESC_DWELL, HST_ANT_DESC_RFPOWER, HST_ANT_DESC_INV_CNT,
+ HST_TAGMSK_DESC_SEL, HST_TAGMSK_DESC_CFG, HST_TAGMSK_BANK, HST_TAGMSK_PTR, HST_TAGMSK_LEN, HST_TAGMSK_0_3,
+ HST_QUERY_CFG, HST_INV_CFG, HST_INV_SEL, HST_INV_ALG_PARM_0, HST_INV_ALG_PARM_1, HST_INV_ALG_PARM_2, HST_INV_ALG_PARM_3, HST_INV_RSSI_FILTERING_CONFIG, HST_INV_RSSI_FILTERING_THRESHOLD, HST_INV_RSSI_FILTERING_COUNT, HST_INV_EPC_MATCH_CFG, HST_INV_EPCDAT_0_3,
+ HST_TAGACC_DESC_CFG, HST_TAGACC_BANK, HST_TAGACC_PTR, HST_TAGACC_CNT, HST_TAGACC_LOCKCFG, HST_TAGACC_ACCPWD, HST_TAGACC_KILLPWD, HST_TAGWRDAT_SEL, HST_TAGWRDAT_0,
+ HST_RFTC_CURRENT_PROFILE,
+ HST_RFTC_FRQCH_SEL, HST_RFTC_FRQCH_CFG, HST_RFTC_FRQCH_DESC_PLLDIVMULT, HST_RFTC_FRQCH_DESC_PLLDACCTL, HST_RFTC_FRQCH_CMDSTART,
+ HST_AUTHENTICATE_CFG, HST_AUTHENTICATE_MSG, HST_READBUFFER_LEN, HST_UNTRACEABLE_CFG,
+ HST_CMD
+ }
+ public class Rx000Setting {
+ Rx000Setting(boolean set_default_setting) {
+ if (set_default_setting) {
+ macVer = mDefault.macVer;
+ diagnosticCfg = mDefault.diagnosticCfg;
+ oemAddress = mDefault.oemAddress;
+
+ //RFTC block paramters
+ currentProfile = mDefault.currentProfile;
+
+ // Antenna block parameters
+ antennaCycle = mDefault.antennaCycle;
+ antennaFreqAgile = mDefault.antennaFreqAgile;
+ antennaSelect = mDefault.antennaSelect;
+ }
+ antennaSelectedData = new AntennaSelectedData[ANTSELECT_MAX + 1];
+ for (int i = 0; i < antennaSelectedData.length; i++) {
+ int default_setting_type = 0;
+ if (set_default_setting) {
+ if (i == 0) default_setting_type = 1;
+ else if (i >= 1 && i <= 3) default_setting_type = 2;
+ else if (i >= 4 && i <= 7) default_setting_type = 3;
+ else if (i >= 8 && i <= 11) default_setting_type = 4;
+ else default_setting_type = 5;
+ }
+ antennaSelectedData[i] = new AntennaSelectedData(set_default_setting, default_setting_type);
+ }
+
+ //Tag select block parameters
+ if (set_default_setting) invSelectIndex = 0;
+ invSelectData = new InvSelectData[INVSELECT_MAX + 1];
+ for (int i = 0; i < invSelectData.length; i++) {
+ invSelectData[i] = new InvSelectData(set_default_setting);
+ }
+
+ if (set_default_setting) {
+ //Inventtory block paraameters
+ //queryTarget = mDefault.queryTarget;
+ //querySession = mDefault.querySession;
+ //querySelect = mDefault.querySelect;
+ invAlgo = mDefault.invAlgo;
+ matchRep = mDefault.matchRep;
+ tagSelect = mDefault.tagSelect;
+ noInventory = mDefault.noInventory;
+ tagDelay = mDefault.tagDelay;
+ invModeCompact = mDefault.tagJoin;
+ invBrandId = mDefault.brandid;
+ }
+
+ if (set_default_setting) algoSelect = 3;
+ algoSelectedData = new AlgoSelectedData[ALGOSELECT_MAX + 1];
+ for (int i = 0; i < algoSelectedData.length; i++) {//0 for invalid default, 1 for 0, 2 for 1, 3 for 2, 4 for 3
+ int default_setting_type = 0;
+ if (set_default_setting) {
+ default_setting_type = i + 1;
+ }
+ algoSelectedData[i] = new AlgoSelectedData(set_default_setting, default_setting_type);
+ }
+
+ if (set_default_setting) {
+ rssiFilterType = mDefault.rssiFilterType;
+ rssiFilterOption = mDefault.rssiFilterOption;
+ rssiFilterThreshold1 = mDefault.rssiFilterThreshold;
+ rssiFilterThreshold2 = mDefault.rssiFilterThreshold;
+ rssiFilterCount = mDefault.rssiFilterCount;
+
+ matchEnable = mDefault.matchEnable;
+ matchType = mDefault.matchType;
+ matchLength = mDefault.matchLength;
+ matchOffset = mDefault.matchOffset;
+ invMatchDataReady = mDefault.invMatchDataReady;
+
+ //Tag access block parameters
+ //accessRetry = mDefault.accessRetry;
+ //accessBank = mDefault.accessBank; accessBank2 = mDefault.accessBank2;
+ //accessOffset = mDefault.accessOffset; accessOffset2 = mDefault.accessOffset2;
+ //accessCount = mDefault.accessCount; accessCount2 = mDefault.accessCount2;
+ //accessLockAction = mDefault.accessLockAction;
+ //accessLockMask = mDefault.accessLockMask;
+ //long accessPassword = 0;
+ //long killPassword = 0;
+ //accessWriteDataSelect = mDefault.accessWriteDataSelect;
+ //accWriteDataReady = mDefault.accWriteDataReady;
+
+ authMatchDataReady = mDefault.authMatchDataReady;
+ }
+
+ invMatchData0_63 = new byte[4 * 16];
+ accWriteData0_63 = new byte[4 * 16 * 2];
+ authMatchData0_63 = new byte[4 * 4];
+ }
+
+ class Rx000Setting_default {
+ String macVer;
+ int diagnosticCfg = 0x210;
+ int mbpAddress = 0; // ?
+ int mbpData = 0; // ?
+ int oemAddress = 4; // ?
+ int oemData = 0; // ?
+
+ //RFTC block paramters
+ int currentProfile = 1;
+ int freqChannelSelect = 0;
+
+ // Antenna block parameters
+ int antennaCycle = 1;
+ int antennaFreqAgile = 0;
+ int antennaSelect = 0;
+
+ //Tag select block parameters
+ int invSelectIndex = 0;
+
+ //Inventtory block paraameters
+ int queryTarget = 0;
+ int querySession = 2;
+ int querySelect = 1;
+ int invAlgo = 3;
+ int matchRep = 0;
+ int tagSelect = 0;
+ int noInventory = 0;
+ int tagRead = 0;
+ int tagDelay = 0;
+ int tagJoin = 0;
+ int brandid = 0;
+ int algoSelect = 3;
+
+ int rssiFilterType = 0;
+ int rssiFilterOption = 0;
+ int rssiFilterThreshold = 0;
+ long rssiFilterCount = 0;
+
+ int matchEnable = 0;
+ int matchType = 0;
+ int matchLength = 0;
+ int matchOffset = 0;
+ byte[] invMatchData0_63; int invMatchDataReady = 0;
+
+ //Tag access block parameters
+ int accessRetry = 3;
+ int accessBank = 1; int accessBank2 = 0;
+ int accessOffset = 2; int accessOffset2 = 0;
+ int accessCount = 1; int accessCount2 = 0;
+ int accessLockAction = 0;
+ int accessLockMask = 0;
+ //long accessPassword = 0;
+ // long killPassword = 0;
+ int accessWriteDataSelect = 0;
+ byte[] accWriteData0_63; int accWriteDataReady = 0;
+
+ byte[] authMatchData; int authMatchDataReady = 0;
+ }
+ Rx000Setting_default mDefault = new Rx000Setting_default();
+
+ boolean readMAC(int address, int length) {
+ boolean DEBUG = false;
+ byte[] msgBuffer = new byte[]{(byte) 0x80, (byte)0xb3, 0x14, 0x71, 0, 0, 4, 1, 0, 8, 0};
+ msgBuffer[8] = (byte) ((address >> 8) % 256);
+ msgBuffer[9] = (byte) (address % 256);
+ msgBuffer[10] = (byte) (length & 0xFF);
+ if (DEBUG) appendToLog("RfidReaderChipE710.readMAC mRfidToWrite.size = " + csReaderConnector.rfidConnector.mRfidToWrite.size() + ", msgBufferIn = " + byteArrayToString(msgBuffer));
+ if (csReaderConnector.rfidConnector.mRfidToWrite.size() != 0) {
+ for (int i = 1; i < csReaderConnector.rfidConnector.mRfidToWrite.size(); i++) {
+ byte[] msgBufferOld = csReaderConnector.rfidConnector.mRfidToWrite.get(i).dataValues;
+ if (DEBUG) appendToLog("mRfidToWrite[" + i + "].dataValues = " + byteArrayToString(msgBufferOld));
+ int k = 0, m = 4;
+ for (; k < m; k++) {
+ if ((byte)msgBufferOld[k] != (byte)msgBuffer[k]) break;
+ }
+ int iMultipleNumber = 25; //25 for normal, 3 for Usb, 16 or above will have multiple uplinks
+ if (utility.ENABLE_USBDATA) iMultipleNumber = 3;
+ if (k == m && msgBufferOld[7] < iMultipleNumber) {
+ for (int x = 8; x < msgBufferOld.length; x+=3) {
+ if (msgBufferOld[x] == msgBuffer[8]
+ && msgBufferOld[x+1] == msgBuffer[9]
+ && msgBufferOld[x+2] == msgBuffer[10]
+ ) {
+ if (DEBUG) appendToLog("RfidReaderChipE710.readMAC matched payload read at x = " + x + ", and no adding");
+ return true;
+ }
+ }
+ byte[] msgBufferProposed = new byte[msgBufferOld.length + 3];
+ System.arraycopy(msgBufferOld, 0, msgBufferProposed, 0, msgBufferOld.length);
+ byte payloadLen = msgBufferProposed[6];
+ msgBufferProposed[6] += 3; //(byte)(payloadLen + 3);
+ if (msgBufferProposed[6] < payloadLen) break;
+
+ msgBufferProposed[7]++;
+ System.arraycopy(msgBuffer, 8, msgBufferProposed, msgBufferOld.length, 3);
+ if (DEBUG) appendToLog("RfidReaderChipE710.readMAC msgBufferProposed = " + byteArrayToString(msgBufferProposed));
+
+ csReaderConnector.rfidConnector.mRfidToWrite.remove(i);
+ msgBuffer = msgBufferProposed;
+ }
+ }
+ }
+ if (DEBUG) appendToLog("RfidReaderChipE710.readMAC msgBufferOut = " + byteArrayToString(msgBuffer));
+ return sendHostRegRequest(HostRegRequests.MAC_OPERATION, false, msgBuffer);
+ }
+ boolean writeMAC(int address, byte[] bytes, boolean bReady) {
+ byte[] header = new byte[] {(byte) 0x80, (byte)0xb3, (byte)0x9A, 6, 0, 0, 4, 1, 0, 8, 0 };
+ byte[] msgBuffer = new byte[header.length + bytes.length];
+ int iPayloadLength = 4 + bytes.length;
+ System.arraycopy(header, 0, msgBuffer, 0, header.length);
+ msgBuffer[5] = (byte)((iPayloadLength / 256) & 0xFF);
+ msgBuffer[6] = (byte)((iPayloadLength % 256) & 0xFF);
+ msgBuffer[8] = (byte) ((address >> 8) & 0xFF);
+ msgBuffer[9] = (byte) (address & 0xFF);
+ msgBuffer[10] = (byte) (bytes.length & 0XFF);
+ System.arraycopy(bytes, 0, msgBuffer, 11, bytes.length);
+ if (false) appendToLog(String.format("3 writeMAC with address = 0x%X, msgBuffer = ", address) + byteArrayToString(msgBuffer));
+ return sendHostRegRequest(HostRegRequests.MAC_OPERATION, true, msgBuffer);
+ }
+ public boolean readMAC(int address) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 0, 0, 0, 0, 0, 0};
+ msgBuffer[2] = (byte) (address % 256);
+ msgBuffer[3] = (byte) ((address >> 8) % 256);
+ return sendHostRegRequest(HostRegRequests.MAC_OPERATION, false, msgBuffer);
+ }
+ public boolean writeMAC(int address, long value) {
+ byte[] msgBuffer = null;
+ appendToLog(String.format("3A setTagFocus with address = 0x%X, value = 0x%X ", address, value));
+ return sendHostRegRequest(HostRegRequests.MAC_OPERATION, true, msgBuffer);
+ }
+
+ String macVer = null; int macVerBuild = -1;
+ public String getMacVer() {
+ appendToLog("macVerBuild = " + macVerBuild + ", macVer = " + (macVer == null ? "null" : macVer));
+ if (macVerBuild < 0) readMAC(0x28, 4);
+ if (macVer == null) readMAC(8, 0x20);
+ if (macVerBuild < 0 || macVer == null) return null;
+ String strValue = macVer + " b" + macVerBuild;
+ if (false) appendToLog("2 getMacVer = " + strValue);
+ return strValue;
+ }
+
+ int authenticateConfig = -1;
+ public boolean setAuthenticateConfig(int authenticateConfig) {
+ byte[] data = new byte[3];
+ data[0] = (byte) ((authenticateConfig >> 16) & 0xFF);
+ data[1] = (byte) ((authenticateConfig >> 8) & 0xFF);
+ data[2] = (byte) (authenticateConfig & 0xFF);
+ appendToLog("AAA: writing 390E with data " + byteArrayToString(data));
+ boolean bValue = writeMAC(0x390E, data, true);
+ if (bValue) this.authenticateConfig = authenticateConfig;
+ //readMAC3(0x390E, 3);
+ return bValue;
+ }
+ public boolean setAuthenticateMessage(byte[] authenticateMessage) {
+ int length = authenticateMessage.length;
+ if (length > 32) length = 32;
+ byte[] data = new byte[length];
+ System.arraycopy(authenticateMessage, 0, data, 0, length);
+ appendToLog("AAA: writing 3912 with data " + byteArrayToString(data));
+ boolean bValue = writeMAC(0x3912, data, true);
+ //readMAC3(0x3912, 32);
+ return bValue;
+ }
+ public boolean setAuthenticateResponseLen(int authenticateResponseLen) {
+ byte[] data = new byte[2];
+ data[0] = (byte) ((authenticateResponseLen >> 8) & 0xFF);
+ data[1] = (byte) (authenticateResponseLen & 0xFF);
+ appendToLog("AAA: writing 3944 with data " + byteArrayToString(data));
+ boolean bValue = writeMAC(0x3944, data, true);
+ //readMAC3(0x3944, 2);
+ return bValue;
+ }
+
+ byte[] currentPort = null;
+ public byte getCurrentPort() {
+ byte byValue = (byte)-1;
+ if (currentPort != null && currentPort.length == 1) byValue = currentPort[0];
+ else readMAC(0x3948, 1);
+ appendToLog("byValue = " + byValue);
+ return byValue;
+ }
+ boolean setCurrentPort(byte currentPortNew) {
+ if (currentPortNew >= 0 && currentPort.length == 1 && currentPort[0] == currentPortNew && sameCheck) {
+ appendToLog("!!! Skip sending repeated data with currentPortNew = " + currentPortNew);
+ return true;
+ }
+ byte[] bytes = new byte[1];
+ bytes[0] = currentPortNew;
+ boolean bValue;
+ bValue = rx000Setting.writeMAC(0x3948, bytes, true);
+ appendToLog("new currentPort = " + byteArrayToString(bytes) + ", old currentPort = " + byteArrayToString(currentPort));
+ if (bValue) currentPort = bytes;
+ return true;
+ }
+ public boolean updateCurrentPort() {
+ byte currentPortOld = getCurrentPort();
+ byte currentPortNew = 0;
+ for (int i = 0; i < 16; i++) {
+ if (rx000Setting.antennaPortConfig[i] != null) {
+ if (rx000Setting.antennaPortConfig[i][0] != 0) {
+ currentPortNew = (byte)(i & 0xFF);
+ }
+ }
+ }
+ appendToLog("currentPortOld = " + currentPortOld + ", currentPortNew = " + currentPortNew);
+ boolean bValue = false;
+ if (currentPortOld != currentPortNew) bValue = setCurrentPort(currentPortNew);
+ return bValue;
+ }
+
+ byte[] modelCode;
+ public String getModelCode() {
+ String strValue = null;
+ if (modelCode == null) readMAC(0x5000, 32);
+ else {
+ strValue = byteArray2DisplayString(modelCode);
+ if (strValue == null || strValue.length() == 0) strValue = byteArrayToString(modelCode).substring(0, 5);
+ }
+ return strValue;
+ }
+
+ byte[] productSerialNumber;
+ public String getProductSerialNumber() {
+ String strValue = null;
+ if (productSerialNumber == null) {
+ readMAC(0x5020, 32);
+ } else {
+ strValue = byteArray2DisplayString(productSerialNumber);
+ if (strValue == null || strValue.length() == 0) strValue = byteArrayToString(productSerialNumber).substring(0, 5);
+ //string.substring(string.length() - 8, string.length());
+ }
+ return strValue;
+ }
+
+ byte[] countryEnum;
+ public int getCountryEnum() {
+ int iValue = -1;
+ if (countryEnum == null) readMAC(0x3014, 2);
+ else iValue = byteArrayToInt(countryEnum);
+ appendToLog("countryEnum = " + iValue);
+ return iValue;
+ }
+ public boolean setCountryEnum(short countryEnum) {
+ byte[] data = new byte[2];
+ data[0] = 0;
+ data[1] = (byte) ((countryEnum) & 0xFF);
+ if (this.countryEnum != null && compareArray(this.countryEnum, data, data.length) && sameCheck) return true;
+ boolean bValue = writeMAC(0x3014, data, true);
+ appendToLog("new countryEnum = " + byteArrayToString(data) + ", with bValue = " + bValue);
+ if (bValue) this.countryEnum = data;
+ return bValue;
+ }
+
+ byte[] frequencyChannelIndex;
+ public int getFrequencyChannelIndex() {
+ int iValue = -1;
+ if (frequencyChannelIndex == null) readMAC(0x3018, 1);
+ else iValue = byteArrayToInt(frequencyChannelIndex);
+ appendToLog("frequencyChannelIndex = " + iValue);
+ return iValue;
+ }
+ public boolean setFrequencyChannelIndex(byte frequencyChannelIndex) {
+ byte[] data = new byte[1];
+ data[0] = frequencyChannelIndex;
+ if (this.frequencyChannelIndex != null && compareArray(this.frequencyChannelIndex, data, data.length) && sameCheck) return true;
+ boolean bValue = writeMAC(0x3018, data, true);
+ appendToLog("new frequencyChannelIndex = " + byteArrayToString(data) + ", old frequencyChannelIndex = " + byteArrayToString(this.frequencyChannelIndex) + ", with bValue = " + bValue + ", sameCheck = " + sameCheck);
+ if (bValue) this.frequencyChannelIndex = data;
+ return bValue;
+ }
+
+ byte[] countryEnumOem;
+ public int getCountryEnumOem() {
+ int iValue = -1;
+ if (countryEnumOem == null) readMAC(0x5040, 2);
+ else iValue = byteArrayToInt(countryEnumOem);
+ appendToLog("countryEnumOem = " + iValue);
+ return iValue;
+ }
+
+ byte[] countryCodeOem;
+ public int getCountryCodeOem() {
+ int iValue = -1;
+ if (countryCodeOem == null) readMAC(0xef98, 4);
+ else iValue = byteArrayToInt(countryCodeOem);
+ return iValue;
+ }
+ byte[] boardSerialNumber;
+ public String getBoardSerialNumber() {
+ if (boardSerialNumber == null) {
+ readMAC(0xef9c, 16);
+ return null;
+ } else if (boardSerialNumber.length < 13) return null;
+ else {
+ byte[] retValue = new byte[boardSerialNumber.length];
+ System.arraycopy(boardSerialNumber, 0, retValue, 0, boardSerialNumber.length);
+ String string = new String(retValue).trim().replaceAll("[^\\x00-\\x7F]", "");
+ if (string == null || string.length() == 0) return byteArrayToString(retValue).substring(0, 13);
+ if (false) appendToLog("String = " + string + ", length = " + string.length());
+ if (retValue.length > 13) {
+ for (int i = 13; i < retValue.length; i++) {
+ if (retValue[i] < 0x30) retValue[i] += 0x30;
+ }
+ }
+ return (retValue == null ? null : new String(retValue).trim().replaceAll("[^\\x00-\\x7F]", ""));
+ }
+ }
+
+ byte[] specialcountryCodeOem;
+ public String getSpecialCountryCodeOem() {
+ String strValue = null;
+ if (specialcountryCodeOem == null) readMAC(0xefac, 4);
+ else {
+ strValue = byteArray2DisplayString(specialcountryCodeOem);
+ //if (strValue == null || strValue.length() == 0) strValue = byteArrayToString(modelCode).substring(0, 5);
+ }
+ return strValue;
+ }
+
+ byte[] freqModifyCode;
+ public int getFreqModifyCode() {
+ int iValue = -1;
+ if (freqModifyCode == null) readMAC(0xefb0, 4);
+ else iValue = byteArrayToInt(freqModifyCode);
+ return iValue;
+ }
+ long mac_last_command_duration;
+ final int DIAGCFG_INVALID = -1; final int DIAGCFG_MIN = 0; final int DIAGCFG_MAX = 0x3FF;
+ int diagnosticCfg = DIAGCFG_INVALID;
+ public int getAntennaPort() {
+ if (false) appendToLog("2 iAntennaPort = " + antennaSelect);
+ return antennaSelect;
+ }
+ byte[][] antennaPortConfig = new byte[16][];
+ public byte[] getAntennaPortConfig(int iAntennaPort) {
+ byte[] bytes = null;
+ if (antennaPortConfig[iAntennaPort] == null) {
+ if (false) appendToLog("getAntennaPortConfig starts readMAC");
+ readMAC(0x3030 + iAntennaPort * 16, 16);
+ }
+ else {
+ bytes = new byte[antennaPortConfig[iAntennaPort].length];
+ System.arraycopy(antennaPortConfig[iAntennaPort], 0, bytes, 0, bytes.length);
+ }
+ if (false) appendToLog("getAntennaPortConfig[" + iAntennaPort + "] = " + byteArrayToString(antennaPortConfig[iAntennaPort]));
+ return bytes;
+ }
+
+ int impinjExtensionValue = -1;
+ public int getImpinjExtension() {
+ int iValue = -1; boolean DEBUG = false;
+ if (DEBUG) appendToLog("2 getImpinjExtension: iAntennaPort = " + antennaSelect);
+ if (antennaPortConfig[antennaSelect] == null) appendToLog("CANNOT continue as antennaPortConfig[" + antennaSelect + "] is null !!!");
+ else {
+ if (DEBUG) appendToLog("2A getImpinjExtension: getAntennaPortConfig[" + antennaSelect + "] = " + byteArrayToString(antennaPortConfig[antennaSelect]));
+ iValue = (antennaPortConfig[antennaSelect][5] & 0x06);
+ if (DEBUG) appendToLog(String.format("2b getImpinjExtension: iValue = 0x%X", iValue));
+ }
+ return iValue;
+ }
+
+ public boolean setImpinjExtension(boolean tagFocus, boolean fastId) {
+ boolean bValue = false, DEBUG = false;
+ if (antennaPortConfig[antennaSelect] == null) appendToLog("CANNOT continue as antennaPortConfig[" + antennaSelect + "] is null !!!");
+ else {
+ if (DEBUG) appendToLog("2 setImpinjExtension: tagFocus = " + tagFocus);
+ if (DEBUG) appendToLog("2A setImpinjExtension: getAntennaPortConfig[" + antennaSelect + "] = " + byteArrayToString(antennaPortConfig[antennaSelect]));
+ byte[] bytes = new byte[1];
+ bytes[0] = antennaPortConfig[antennaSelect][5];
+
+ if (tagFocus) bytes[0] |= 0x04;
+ else bytes[0] &= ~0x04;
+ if (fastId) bytes[0] |= 0x02;
+ else bytes[0] &= ~0x02;
+ if (DEBUG) appendToLog(String.format("2A1 setImpinjExtension: bytes = 0x%X", bytes[0]));
+ boolean bSame = false;
+ if (sameCheck | true) {
+ if (antennaPortConfig[antennaSelect][5] == bytes[0]) bSame = true;
+ if (DEBUG) appendToLog("2ab setImpinjExtension: the array is the same = " + bSame);
+ }
+ //bSame = false; appendToLog("!!! assme bSame is false before 1A writeMAC 0x3035");
+ if (bSame) {
+ if (DEBUG_PKDATA) appendToLog(String.format("!!! Skip sending repeated data %s in address 0x%X", byteArrayToString(bytes), 0x3030 + antennaSelect * 16 + 5));
+ bValue = true;
+ } else {
+ appendToLog("test 1");
+ bValue = writeMAC(0x3030 + antennaSelect * 16 + 5, bytes, true);
+ if (bValue) antennaPortConfig[antennaSelect][5] = bytes[0];
+ }
+ if (DEBUG) appendToLog("2b setImpinjExtension: with updated " + byteArrayToString(antennaPortConfig[antennaSelect]));
+ }
+ return bValue;
+ }
+
+ int iSelectPort = 0;
+ public byte[][] selectConfiguration = new byte[7][];
+
+ public byte[] getSelectConfiguration(int iSelectPort) {
+ byte[] bytes = null;
+ if (selectConfiguration[iSelectPort] == null) {
+ if (false) appendToLog("getSelectConfiguration starts readMAC");
+ readMAC(0x3140 + iSelectPort * 42, 42);
+ }
+ else {
+ bytes = new byte[selectConfiguration[iSelectPort].length];
+ System.arraycopy(selectConfiguration[iSelectPort], 0, bytes, 0, bytes.length);
+ }
+ if (false) appendToLog("getSelectConfiguration[" + iSelectPort + "] = " + byteArrayToString(selectConfiguration[iSelectPort]));
+ return bytes;
+ }
+ public boolean setSelectConfiguration(int index, boolean enable, int bank, int offset, byte[] mask, int target, int action, int delay) {
+ boolean bValue = false;
+ byte[] bytes = new byte[42];
+ if (selectConfiguration[index] != null) System.arraycopy(selectConfiguration[index], 0, bytes, 0, bytes.length);
+ bytes[0] = (byte) (enable ? 1 : 0);
+ bytes[1] = (byte) (bank & 0xFF);
+ bytes[2] = (byte) ((offset >> 24) & 0xFF);
+ bytes[3] = (byte) ((offset >> 16) & 0xFF);
+ bytes[4] = (byte) ((offset >> 8) & 0xFF);
+ bytes[5] = (byte) (offset & 0xFF);
+ if (mask != null) {
+ int iWdith = mask.length;
+ if (iWdith > 32) iWdith = 32;
+ System.arraycopy(mask, 0, bytes, 7, iWdith);
+ bytes[6] = (byte) ((iWdith * 8) & 0xFF);
+ } else bytes[6] = 0;
+ bytes[39] = (byte) (target & 0xFF);
+ bytes[40] = (byte) (action & 0xFF);
+ bytes[41] = (byte) (delay & 0xFF);
+ if (false) appendToLog("1A writeMAC 0x3140");
+ if (compareArray(selectConfiguration[index], bytes, bytes.length) && sameCheck) {
+ appendToLog("!!! Skip sending repeated data " + byteArrayToString(bytes) + " to address 0x3140");
+ return true;
+ }
+ bValue = writeMAC(0x3140 + index * 42, bytes, true);
+ if (bValue) selectConfiguration[index] = bytes;
+ else appendToLog("!!! Failed to send data " + byteArrayToString(bytes) + " to address 0x3140");
+ return bValue;
+ }
+
+ byte[][] multibankReadConfig = new byte[3][];
+ int getMultibankEnable(int iSelectPort) {
+ int iValue = 0;
+ if (multibankReadConfig[iSelectPort] != null) {
+ if (multibankReadConfig[iSelectPort][0] != 0) iValue = multibankReadConfig[iSelectPort][0];
+ }
+ return iValue;
+ }
+ int getMultibankReadLength(int iSelectPort) {
+ int iValue = 0;
+ if (multibankReadConfig[iSelectPort] != null) {
+ if (multibankReadConfig[iSelectPort][0] != 0) iValue = multibankReadConfig[iSelectPort][6];
+ }
+ return iValue;
+ }
+ public byte[] getMultibankReadConfig(int iSelectPort) {
+ boolean DEBUG = false; int iPortSize = 7;
+ byte[] bytes = null;
+ if (multibankReadConfig[iSelectPort] == null) {
+ if (DEBUG) appendToLog("getMultibankReadConfig starts readMAC");
+ readMAC(0x3270 + iSelectPort * iPortSize, iPortSize);
+ }
+ else {
+ bytes = new byte[multibankReadConfig[iSelectPort].length];
+ System.arraycopy(multibankReadConfig[iSelectPort], 0, bytes, 0, bytes.length);
+ }
+ if (DEBUG) appendToLog("getMultibankReadConfig[" + iSelectPort + "] = " + byteArrayToString(multibankReadConfig[iSelectPort]));
+ return bytes;
+ }
+ byte[][] multibankWriteConfig = new byte[3][];
+ boolean setMultibankReadConfig(int index, boolean enable, int bank, int offset, int length) {
+ boolean bValue = false;
+ byte[] bytes = new byte[7];
+ bytes[0] = (byte) (enable ? 1 : 0);
+ bytes[1] = (byte) (bank & 0xFF);
+ bytes[2] = (byte) ((offset >> 24) & 0xFF);
+ bytes[3] = (byte) ((offset >> 16) & 0xFF);
+ bytes[4] = (byte) ((offset >> 8) & 0xFF);
+ bytes[5] = (byte) (offset & 0xFF);
+ bytes[6] = (byte) (length & 0xFF);
+ bValue = writeMAC(0x3270 + index * 7, bytes, true);
+ if (bValue) multibankReadConfig[index] = bytes;
+ return bValue;
+ }
+
+ boolean setMultibankWriteConfig(int index, boolean enable, int bank, int offset, int length, byte[] data) {
+ boolean bValue = false, DEBUG = false;
+ if (DEBUG) appendToLog("Start with index = " + index + ", enable = " + enable + ", bank = " + bank + ", offset = " + offset + ", length = " + length + ", data = " + byteArrayToString(data));
+ byte[] bytes = new byte[7+data.length];
+ bytes[0] = (byte) (enable ? 1 : 0);
+ bytes[1] = (byte) (bank & 0xFF);
+ bytes[2] = (byte) ((offset >> 24) & 0xFF);
+ bytes[3] = (byte) ((offset >> 16) & 0xFF);
+ bytes[4] = (byte) ((offset >> 8) & 0xFF);
+ bytes[5] = (byte) (offset & 0xFF);
+ bytes[6] = (byte) (length & 0xFF);
+ System.arraycopy(data, 0, bytes, 7, data.length);
+ if (DEBUG) appendToLog("bytes = " + byteArrayToString(bytes));
+ bValue = writeMAC(0x3290 + index * 519, bytes, true);
+ if (DEBUG) appendToLog("After writeMAC, bValue = " + bValue);
+ if (bValue) multibankWriteConfig[index] = bytes;
+ return bValue;
+ }
+ int pwrMgmtStatus = -1;
+ void getPwrMgmtStatus() {
+ appendToLog("pwrMgmtStatus: getPwrMgmtStatus ");
+ pwrMgmtStatus = -1; readMAC(0x204);
+ }
+
+ final int MBPADDR_INVALID = -1; final int MBPADDR_MIN = 0; final int MBPADDR_MAX = 0x1FFF;
+ long mbpAddress = MBPADDR_INVALID;
+ final int MBPDATA_INVALID = -1; final int MBPDATA_MIN = 0; final int MBPDATA_MAX = 0x1FFF;
+ long mbpData = MBPDATA_INVALID;
+ final int OEMADDR_INVALID = -1; final int OEMADDR_MIN = 0; final int OEMADDR_MAX = 0x1FFF;
+ long oemAddress = OEMADDR_INVALID;
+ final int OEMDATA_INVALID = -1; final int OEMDATA_MIN = 0; final int OEMDATA_MAX = 0x1FFF;
+ long oemData = OEMDATA_INVALID;
+
+ // Antenna block parameters
+ final int ANTCYCLE_INVALID = -1; final int ANTCYCLE_MIN = 0; final int ANTCYCLE_MAX = 0xFFFF;
+ int antennaCycle = ANTCYCLE_INVALID;
+ public int getAntennaCycle() {
+ if (antennaCycle < ANTCYCLE_MIN || antennaCycle > ANTCYCLE_MAX) getHST_ANT_CYCLES();
+ return antennaCycle;
+ }
+ public boolean setAntennaCycle(int antennaCycle) {
+ if (antennaCycle == this.antennaCycle) return true;
+ this.antennaCycle = antennaCycle; appendToLog(String.format("!!! Skip setAntennaCycle[0x%X]", antennaCycle));
+ return true;
+ }
+ boolean setAntennaCycle(int antennaCycle, int antennaFreqAgile) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 0, 7, 0, 0, 0, 0};
+ if (antennaCycle < ANTCYCLE_MIN || antennaCycle > ANTCYCLE_MAX) antennaCycle = mDefault.antennaCycle;
+ if (antennaFreqAgile < FREQAGILE_MIN || antennaFreqAgile > FREQAGILE_MAX) antennaFreqAgile = mDefault.antennaFreqAgile;
+ if (this.antennaCycle == antennaCycle && this.antennaFreqAgile == antennaFreqAgile && sameCheck) return true;
+ msgBuffer[4] = (byte) (antennaCycle % 256);
+ msgBuffer[5] = (byte) ((antennaCycle >> 8) % 256);
+ if (antennaFreqAgile != 0) {
+ msgBuffer[7] |= 0x01;
+ }
+ this.antennaCycle = antennaCycle;
+ this.antennaFreqAgile = antennaFreqAgile;
+ appendToLog("3 Set HST_ANT_CYCLES");
+ return sendHostRegRequest(HostRegRequests.HST_ANT_CYCLES, true, msgBuffer);
+ }
+
+ final int FREQAGILE_INVALID = -1; final int FREQAGILE_MIN = 0; final int FREQAGILE_MAX = 1;
+ int antennaFreqAgile = FREQAGILE_INVALID;
+ int getAntennaFreqAgile() {
+ if (antennaFreqAgile < FREQAGILE_MIN || antennaFreqAgile > FREQAGILE_MAX)
+ getHST_ANT_CYCLES();
+ return antennaFreqAgile;
+ }
+ public boolean setAntennaFreqAgile(int freqAgile) {
+ appendToLog("Set HST_ANT_CYCLES");
+ return setAntennaCycle(antennaCycle, freqAgile);
+ }
+
+ private boolean getHST_ANT_CYCLES() {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 0, 7, 0, 0, 0, 0};
+ return sendHostRegRequest(HostRegRequests.HST_ANT_CYCLES, false, msgBuffer);
+ }
+
+ final int ANTSELECT_INVALID = -1; final int ANTSLECT_MIN = 0; final int ANTSELECT_MAX = 15;
+ int antennaSelect = ANTSELECT_INVALID; //default value = 0
+ public boolean setAntennaSelect(int antennaSelect) {
+ if (antennaSelect < ANTSLECT_MIN || antennaSelect > ANTSELECT_MAX) antennaSelect = mDefault.antennaSelect;
+ if (this.antennaSelect == antennaSelect && sameCheck) return true;
+ this.antennaSelect = antennaSelect; appendToLog("antennaSelect is set to " + antennaSelect);
+ return true;
+ }
+
+ AntennaSelectedData[] antennaSelectedData;
+ public int getAntennaEnable() {
+ boolean DEBUG = false;
+ int iValue = -1;
+ if (antennaPortConfig[antennaSelect] == null) {
+ rx000Setting.getAntennaPortConfig(antennaSelect);
+ readMAC(0x3030 + antennaSelect * 16, 16);
+ appendToLog("CANNOT continue as antennaPortConfig[" + antennaSelect + "] is null !!!");
+ } else {
+ if (DEBUG) appendToLog("2 getAntennaEnable");
+ if (DEBUG) appendToLog("2A getAntennaEnable: getAntennaPortConfig[" + antennaSelect + "] = " + byteArrayToString(antennaPortConfig[antennaSelect]));
+ iValue = antennaPortConfig[antennaSelect][0] & 0xFF;
+ }
+ if (DEBUG) appendToLog("2 getAntennaEnable: iValue = " + iValue);
+ return iValue;
+ }
+ public boolean setAntennaEnable(int antennaEnable) {
+ boolean bValue = false, DEBUG = false;
+
+ appendToLog("antennaEnable is " + antennaEnable);
+ if (antennaEnable == 0) {
+ boolean disableInvalid = true;
+ for (int i = 0; i < 16; i++) {
+ appendToLog("i = " + i + ", antennaSelect = " + antennaSelect);
+ if (i != antennaSelect && antennaPortConfig[i] != null) {
+ if (antennaPortConfig[i][0] != 0) disableInvalid = false;
+ appendToLog("i = " + i + ", disableInvalid = " + disableInvalid);
+ }
+ }
+ appendToLog("disableInvalid is " + disableInvalid);
+ if (disableInvalid) return false;
+ }
+
+ if (antennaPortConfig[antennaSelect] == null) appendToLog("CANNOT continue as antennaPortConfig[" + antennaSelect + "] is null !!!");
+ else {
+ if (DEBUG) appendToLog("2 setAntennaEnable with antennaEnable = " + antennaEnable);
+ if (DEBUG) appendToLog("2A setAntennaEnable: getAntennaPortConfig[" + antennaSelect + "] = " + byteArrayToString(antennaPortConfig[antennaSelect]));
+ byte[] bytes = new byte[1];
+ if (antennaEnable > 0) bytes[0] = 1;
+ else bytes[0] = 0;
+ if (DEBUG) appendToLog("2b setAntennaEnable: bytes = " + byteArrayToString(bytes));
+ bValue = writeMAC(0x3030 + antennaSelect * 16, bytes, true);
+ if (bValue) antennaPortConfig[antennaSelect][0] = bytes[0];
+ if (DEBUG) appendToLog("2C setAntennaEnable: getAntennaPortConfig[" + antennaSelect + "] = " + byteArrayToString(antennaPortConfig[antennaSelect]));
+ }
+ if (DEBUG) appendToLog("2d getAntennaEnable: bValue = " + bValue);
+ return bValue;
+ }
+
+ public long getAntennaDwell() {
+ boolean DEBUG = false;
+ long lValue = -1;
+ if (antennaPortConfig[antennaSelect] == null) appendToLog("CANNOT continue as antennaPortConfig[" + antennaSelect + "] is null !!!");
+ else {
+ if (DEBUG) appendToLog("2 getAntennaDwell");
+ if (DEBUG) appendToLog("2A getAntennaDwell: getAntennaPortConfig[" + antennaSelect + "] = " + byteArrayToString(antennaPortConfig[antennaSelect]));
+ lValue = (antennaPortConfig[antennaSelect][1] & 0xFF) << 8;
+ lValue += (antennaPortConfig[antennaSelect][2] & 0xFF);
+ }
+ if (DEBUG) appendToLog("2C getAntennaDwell: iValue = " + lValue);
+ return lValue;
+ }
+
+ public boolean setAntennaDwell(long antennaDwell) {
+ boolean bValue = false, DEBUG = false;
+ if (antennaPortConfig[antennaSelect] == null) appendToLog("CANNOT continue as antennaPortConfig[" + antennaSelect + "] is null !!!");
+ else {
+ if (DEBUG) appendToLog("2 setAntennaDwell: antennaDwell = " + antennaDwell);
+ if (DEBUG) appendToLog("2A setAntennaDwell: getAntennaPortConfig[" + antennaSelect + "] = " + byteArrayToString(antennaPortConfig[antennaSelect]));
+ byte[] bytes = new byte[2];
+ bytes[0] = (byte)((antennaDwell/256) & 0xFF);
+ bytes[1] = (byte)((antennaDwell%256) & 0xFF);
+ if (sameCheck || true) {
+ byte[] bytesOld = new byte[2];
+ System.arraycopy(antennaPortConfig[antennaSelect], 1, bytesOld, 0, bytesOld.length);
+ if (DEBUG) appendToLog("2A2 setAntennaDwell: bytesOld = " + byteArrayToString(bytesOld));
+ boolean bValue1 = compareArray(bytes, bytesOld, bytes.length);
+ if (DEBUG) appendToLog("2ab setAntennaDwell: the array is the same = " + bValue1);
+ }
+ bValue = writeMAC(0x3030 + antennaSelect * 16 + 1, bytes, true);
+ if (bValue) {
+ System.arraycopy(bytes, 0, antennaPortConfig[antennaSelect], 1, bytes.length);
+ //appendToLog("RfidReaderChipE710.setAntennaDwell, antennaPortConfig[" + antennaSelect + "] = " + byteArrayToString(bytes));
+ }
+ if (DEBUG) appendToLog("2b setAntennaDwell: getAntennaPortConfig[" + antennaSelect + "] = " + byteArrayToString(antennaPortConfig[antennaSelect]));
+ }
+ return bValue;
+ }
+
+ public long getAntennaPower(int portNumber) {
+ long lValue = -1; boolean DEBUG = false;
+ if (DEBUG) appendToLog("2 getAntennaPower: portNumber = " + portNumber);
+ if (portNumber < 0) portNumber = antennaSelect;
+ if (antennaPortConfig[portNumber] == null) appendToLog("CANNOT continue as antennaPortConfig[" + portNumber + "] is null !!!");
+ else {
+ if (DEBUG) appendToLog("2A getAntennaPower: getAntennaPortConfig[" + portNumber + "] = " + byteArrayToString(antennaPortConfig[portNumber]));
+ lValue = (antennaPortConfig[portNumber][3] & 0xFF) * 256;
+ lValue += (antennaPortConfig[portNumber][4] & 0xFF);
+ if (DEBUG) appendToLog(String.format("2b getAntennaPower: lValue = 0x%X", lValue));
+ lValue /= 10;
+ }
+ return lValue;
+ }
+ public boolean setAntennaPower(long antennaPower) {
+ boolean bValue = false, DEBUG = false;
+ if (antennaPortConfig[antennaSelect] == null) {
+ if (DEBUG) appendToLog("4 bValue = " + bValue);
+ appendToLog("!!! CANNOT continue as antennaPortConfig[" + antennaSelect + "] is null");
+ }
+ else if (getAntennaPower(antennaSelect) == antennaPower && sameCheck) {
+ if (DEBUG) appendToLog("3 bValue = " + bValue);
+ return true;
+ }
+ else {
+ if (DEBUG) appendToLog("2 setAntennaPower: antennaPower = " + antennaPower);
+ if (DEBUG) appendToLog("2A setAntennaPower: getAntennaPortConfig[" + antennaSelect + "] = " + byteArrayToString(antennaPortConfig[antennaSelect]));
+ antennaPower *= 10;
+ byte[] bytes = new byte[2];
+ bytes[0] = (byte)((antennaPower/256) & 0xFF);
+ bytes[1] = (byte)((antennaPower%256) & 0xFF);
+ if (sameCheck | true) {
+ byte[] bytesOld = new byte[2];
+ System.arraycopy(antennaPortConfig[antennaSelect], 3, bytesOld, 0, bytesOld.length);
+ if (DEBUG) appendToLog("2A2 setAntennaPower: bytesOld = " + byteArrayToString(bytesOld));
+ boolean bValue1 = compareArray(bytes, bytesOld, bytes.length);
+ if (DEBUG) appendToLog("2ab setAntennaPower: the array is the same = " + bValue1);
+ }
+
+ bValue = writeMAC(0x3030 + antennaSelect * 16 + 3, bytes, true);
+ if (DEBUG) appendToLog("2 bValue = " + bValue);
+ if (bValue) System.arraycopy(bytes, 0, antennaPortConfig[antennaSelect], 3, bytes.length);
+ if (DEBUG) appendToLog("2b setAntennaPower: with updated " + byteArrayToString(antennaPortConfig[antennaSelect]));
+ }
+ if (DEBUG) appendToLog("1 bValue = " + bValue);
+ return bValue;
+ }
+
+ long antennaInvCount = -1;
+ public boolean setAntennaInvCount(long antennaInvCount) {
+ if (antennaInvCount == this.antennaInvCount) return true;
+ this.antennaInvCount = antennaInvCount; appendToLog(String.format("!!! Skip setAntennaInvCount[0x%X]", antennaInvCount));
+ return true;
+ }
+
+ //Tag select block parameters
+ final int INVSELECT_INVALID = -1; final int INVSELECT_MIN = 0; final int INVSELECT_MAX = 7;
+ public int invSelectIndex = INVSELECT_INVALID;
+ public int getInvSelectIndex() {
+ if (invSelectIndex < INVSELECT_MIN || invSelectIndex > INVSELECT_MAX) {
+ invSelectIndex = 0; appendToLog("!!! Skip getInvSelectIndex with assumed value = 0");
+ }
+ return invSelectIndex;
+ }
+ public boolean setInvSelectIndex(int invSelect) {
+ if (invSelect < INVSELECT_MIN || invSelect > INVSELECT_MAX) invSelect = mDefault.invSelectIndex;
+ if (this.invSelectIndex == invSelect && sameCheck) {
+ appendToLog("!!! Skip sending repeated data with invSelect = " + invSelect);
+ return true;
+ }
+ this.invSelectIndex = invSelect;
+ appendToLog(String.format("!!! Skip setInvSelectIndex[%d]", invSelect));
+ return true;
+ }
+
+ InvSelectData[] invSelectData;
+ public int getSelectEnable() {
+ int iValue = -1;
+ if (invSelectIndex < INVSELECT_MIN || invSelectIndex > INVSELECT_MAX) invSelectIndex = mDefault.invSelectIndex;
+ if (selectConfiguration[invSelectIndex] == null) appendToLog("!!! CANNOT getSelectEnable as selectConfiguration[" + invSelectIndex + "] is null");
+ else iValue = (byte)(selectConfiguration[invSelectIndex][0] & 0xFF);
+ return iValue;
+ }
+ public boolean setSelectEnable(int enable, int selectTarget, int selectAction, int selectDelay) {
+ boolean bValue = false, DEBUG = false;
+ if (DEBUG) appendToLog("Start with enable = " + enable + ", selectTarget = " + selectTarget + ", selectAction = " + selectAction + ", selectDelay = " + selectDelay);
+ if (invSelectIndex < INVSELECT_MIN || invSelectIndex > INVSELECT_MAX) invSelectIndex = mDefault.invSelectIndex;
+ if (selectConfiguration[invSelectIndex] == null) appendToLog("!!! CANNOT setSelectEnable as selectConfiguration[" + invSelectIndex + "] is null");
+ else {
+ if (DEBUG) appendToLog("Old selectConfiguration " + invSelectIndex + " = " + byteArrayToString(selectConfiguration[invSelectIndex]));
+ byte[] bytes = new byte[42];
+ if (selectConfiguration[invSelectIndex] != null) System.arraycopy(selectConfiguration[invSelectIndex], 0, bytes, 0, bytes.length);
+ bytes[0] = (byte)(enable & 0xFF);
+ bytes[39] = (byte)(selectTarget & 0xFF);
+ bytes[40] = (byte)(selectAction & 0xFF);
+ bytes[41] = (byte)(selectDelay & 0xFF);;
+ if (compareArray(selectConfiguration[invSelectIndex], bytes, bytes.length) && sameCheck) {
+ appendToLog("!!! Skip sending repeated data " + byteArrayToString(bytes) + " to address 0x3140");
+ return true;
+ }
+ bValue = writeMAC(0x3140 + invSelectIndex * 42, bytes, true);
+ if (DEBUG) appendToLog("after writeMAC 0x3140, bValue = " + bValue);
+ if (bValue) selectConfiguration[invSelectIndex] = bytes;
+ else appendToLog("!!! Failed to send data " + byteArrayToString(bytes) + " to address 0x3140");
+ if (DEBUG) appendToLog("bytes = " + byteArrayToString(bytes) + ", new selectConfiguration " + invSelectIndex + " = " + byteArrayToString(selectConfiguration[invSelectIndex]));
+ }
+ if (DEBUG) appendToLog("End with bValue = " + bValue);
+ return bValue;
+ }
+
+ public int getSelectTarget() {
+ int iValue = -1;
+ if (invSelectIndex < INVSELECT_MIN || invSelectIndex > INVSELECT_MAX) invSelectIndex = mDefault.invSelectIndex;
+ if (selectConfiguration[invSelectIndex] == null) appendToLog("!!! CANNOT getSelectTarget as selectConfiguration[" + invSelectIndex + "] is null");
+ else iValue = (selectConfiguration[invSelectIndex][39] & 0xFF);
+ return iValue;
+ }
+
+ public int getSelectAction() {
+ int iValue = -1;
+ if (invSelectIndex < INVSELECT_MIN || invSelectIndex > INVSELECT_MAX) invSelectIndex = mDefault.invSelectIndex;
+ if (selectConfiguration[invSelectIndex] == null) appendToLog("!!! CANNOT getSelectTarget as selectConfiguration[" + invSelectIndex + "] is null");
+ else iValue = (selectConfiguration[invSelectIndex][40] & 0xFF);
+ return iValue;
+ }
+
+ public int getSelectMaskBank() {
+ int iValue = -1;
+ if (invSelectIndex < INVSELECT_MIN || invSelectIndex > INVSELECT_MAX) invSelectIndex = mDefault.invSelectIndex;
+ if (selectConfiguration[invSelectIndex] == null) appendToLog("!!! CANNOT getSelectMaskBank as selectConfiguration[" + invSelectIndex + "] is null");
+ else iValue = (byte)(selectConfiguration[invSelectIndex][1] & 0xFF);
+ return iValue;
+ }
+ public boolean setSelectMaskBank(int selectMaskBank) {
+ boolean bValue = false, DEBUG = false;
+ if (invSelectIndex < INVSELECT_MIN || invSelectIndex > INVSELECT_MAX) invSelectIndex = mDefault.invSelectIndex;
+ if (selectConfiguration[invSelectIndex] == null) appendToLog("!!! CANNOT setSelectMaskBank[" + selectMaskBank + "] as selectConfiguration[" + invSelectIndex + "] is null");
+ else {
+ if (DEBUG) appendToLog("Old selectConfiguration " + invSelectIndex + " = " + byteArrayToString(selectConfiguration[invSelectIndex]));
+ byte[] bytes = new byte[1];
+ bytes[0] = (byte)(selectMaskBank & 0xFF);
+ if (true) {
+ byte[] bytes1 = new byte[selectConfiguration[invSelectIndex].length];
+ System.arraycopy(selectConfiguration[invSelectIndex], 0, bytes1, 0, bytes1.length);
+ System.arraycopy(bytes, 0, bytes1, 1, bytes.length);
+ bValue = writeMAC(0x3140 + invSelectIndex * 42, bytes1, true);
+ } else {
+ bValue = writeMAC(0x3140 + invSelectIndex * 42 + 1, bytes, true);
+ }
+ if (bValue) selectConfiguration[invSelectIndex][1] = bytes[0];
+ if (DEBUG) appendToLog("bytes = " + byteArrayToString(bytes) + ", new selectConfiguration " + invSelectIndex + " = " + byteArrayToString(selectConfiguration[invSelectIndex]));
+ }
+ if (DEBUG) appendToLog("1 setSelectMaskBank with selectMaskBank = " + selectMaskBank + " and bValue = " + bValue);
+ return bValue;
+ }
+
+ public int getSelectMaskOffset() {
+ int iValue = -1;
+ if (invSelectIndex < INVSELECT_MIN || invSelectIndex > INVSELECT_MAX) invSelectIndex = mDefault.invSelectIndex;
+ if (selectConfiguration[invSelectIndex] == null) appendToLog("!!! CANNOT getSelectMaskBank as selectConfiguration[" + invSelectIndex + "] is null");
+ else {
+ iValue = ((selectConfiguration[invSelectIndex][2] & 0xFF) << 24);
+ iValue += ((selectConfiguration[invSelectIndex][3] & 0xFF) << 16);
+ iValue += ((selectConfiguration[invSelectIndex][4] & 0xFF) << 8);
+ iValue += (selectConfiguration[invSelectIndex][5] & 0xFF);
+ }
+ return iValue;
+ }
+ public boolean setSelectMaskOffset(int selectMaskOffset) {
+ boolean bValue = false, DEBUG = false;
+ if (invSelectIndex < INVSELECT_MIN || invSelectIndex > INVSELECT_MAX) invSelectIndex = mDefault.invSelectIndex;
+ if (selectConfiguration[invSelectIndex] == null) appendToLog("!!! CANNOT setSelectMaskBank[" + selectMaskOffset + "] as selectConfiguration[" + invSelectIndex + "] is null");
+ else {
+ if (DEBUG) appendToLog("Old selectConfiguration " + invSelectIndex + " = " + byteArrayToString(selectConfiguration[invSelectIndex]));
+ byte[] bytes = new byte[4];
+ bytes[0] = (byte)((selectMaskOffset >> 24) & 0xFF);
+ bytes[1] = (byte)((selectMaskOffset >> 16) & 0xFF);
+ bytes[2] = (byte)((selectMaskOffset >> 8) & 0xFF);
+ bytes[3] = (byte)(selectMaskOffset & 0xFF);
+ if (true) {
+ byte[] bytes1 = new byte[selectConfiguration[invSelectIndex].length];
+ System.arraycopy(selectConfiguration[invSelectIndex], 0, bytes1, 0, bytes1.length);
+ System.arraycopy(bytes, 0, bytes1, 2, bytes.length);
+ bValue = writeMAC(0x3140 + invSelectIndex * 42, bytes1, true);
+ } else {
+ bValue = writeMAC(0x3140 + invSelectIndex * 42 + 2, bytes, true);
+ }
+ if (bValue) System.arraycopy(bytes, 0, selectConfiguration[invSelectIndex], 2, bytes.length);
+ if (DEBUG) appendToLog("bytes = " + byteArrayToString(bytes) + ", new selectConfiguration " + invSelectIndex + " = " + byteArrayToString(selectConfiguration[invSelectIndex]));
+ }
+ if (DEBUG) appendToLog("1 setSelectMaskOffset with selectMaskOffset = " + selectMaskOffset + " and bValue = " + bValue);
+ return bValue;
+ }
+
+ public int getSelectMaskLength() {
+ int dataIndex = invSelectIndex, iValue = INVSELECT_INVALID; boolean DEBUG = false;
+ if (dataIndex >= INVSELECT_MIN && dataIndex <= INVSELECT_MAX) {
+ if (DEBUG) appendToLog("selectConfiguration " + dataIndex + " = " + byteArrayToString(selectConfiguration[dataIndex]));
+ if (selectConfiguration[dataIndex] != null) {
+ iValue = selectConfiguration[dataIndex][6];
+ }
+ }
+ if (DEBUG) appendToLog("iValue = " + iValue);
+ return iValue;
+ }
+ public boolean setSelectMaskLength(int selectMaskLength) {
+ boolean bValue = false, DEBUG = false;
+ if (invSelectIndex < INVSELECT_MIN || invSelectIndex > INVSELECT_MAX) invSelectIndex = mDefault.invSelectIndex;
+ if (selectConfiguration[invSelectIndex] == null) appendToLog("!!! CANNOT setSelectMaskLength[" + selectMaskLength + "] as selectConfiguration[" + invSelectIndex + "] is null");
+ else {
+ if (DEBUG) appendToLog("Old selectConfiguration " + invSelectIndex + " = " + byteArrayToString(selectConfiguration[invSelectIndex]));
+ byte[] bytes = new byte[1];
+ bytes[0] = (byte)(selectMaskLength & 0xFF);
+ if (true) {
+ byte[] bytes1 = new byte[selectConfiguration[invSelectIndex].length];
+ System.arraycopy(selectConfiguration[invSelectIndex], 0, bytes1, 0, bytes1.length);
+ System.arraycopy(bytes, 0, bytes1, 6, bytes.length);
+ bValue = writeMAC(0x3140 + invSelectIndex * 42, bytes1, true);
+ } else {
+ bValue = writeMAC(0x3140 + invSelectIndex * 42 + 6, bytes, true);
+ }
+ if (bValue) selectConfiguration[invSelectIndex][6] = bytes[0];
+ if (DEBUG) appendToLog("bytes = " + byteArrayToString(bytes) + ", new selectConfiguration " + invSelectIndex + " = " + byteArrayToString(selectConfiguration[invSelectIndex]));
+ }
+ if (DEBUG) appendToLog("1 setSelectMaskOffset with setSelectMaskLength = " + selectMaskLength + " and bValue = " + bValue);
+ return bValue;
+ }
+
+ public String getSelectMaskData() {
+ String strValue = null; boolean DEBUG = false;
+ if (invSelectIndex < INVSELECT_MIN || invSelectIndex > INVSELECT_MAX) invSelectIndex = mDefault.invSelectIndex;
+ if (selectConfiguration[invSelectIndex] == null) appendToLog("!!! CANNOT getSelectMaskBank as selectConfiguration[" + invSelectIndex + "] is null");
+ else {
+ if (selectConfiguration[invSelectIndex] != null && selectConfiguration[invSelectIndex].length > 39) {
+ if (DEBUG || true) appendToLog("selectConfiguration " + invSelectIndex + " = " + byteArrayToString(selectConfiguration[invSelectIndex]));
+ byte[] bytes = new byte[32];
+ System.arraycopy(selectConfiguration[invSelectIndex], 7, bytes, 0, bytes.length);
+ if (DEBUG || true) appendToLog("bytes = " + byteArrayToString(bytes));
+ for (int i = 0; i < bytes.length; i++) {
+ String string = String.format("%02X", bytes[i]);
+ if (strValue == null) strValue = string;
+ else strValue += string;
+ if (DEBUG) appendToLog("i = " + i + ", strValue = " + strValue);
+ }
+ if (strValue == null) strValue = "";
+ }
+ }
+ return strValue;
+ }
+ public boolean setSelectMaskData(String maskData) {
+ boolean bValue = false, DEBUG = false;
+ if (invSelectIndex < INVSELECT_MIN || invSelectIndex > INVSELECT_MAX) invSelectIndex = mDefault.invSelectIndex;
+ if (selectConfiguration[invSelectIndex] == null) appendToLog("!!! CANNOT setSelectMaskData[" + maskData + "] as selectConfiguration[" + invSelectIndex + "] is null");
+ else {
+ if (DEBUG) appendToLog("Old selectConfiguration " + invSelectIndex + " = " + byteArrayToString(selectConfiguration[invSelectIndex]));
+ byte[] bytes = new byte[maskData.length() / 2 + maskData.length() % 2];
+ for (int i = 0; i < bytes.length; i++) {
+ boolean bSingle = false;
+ if (i * 2 + 2 > maskData.length()) bSingle = true;
+ if (DEBUG) appendToLog("substring i = " + i + " " + maskData.substring(i * 2, (bSingle ? i * 2 +1 : i * 2 + 2)));
+ try {
+ String stringSub = null;
+ if (bSingle) {
+ stringSub = maskData.substring(i * 2, i * 2 + 1) + "0";
+ } else stringSub = maskData.substring(i * 2, i * 2 + 2);
+ int iValue = Integer.parseInt(stringSub, 16);
+ bytes[i] = (byte) (iValue & 0xFF);
+ } catch (Exception ex) {
+ appendToLog("!!! Error in parsing maskdata " + maskData + " when i = " + i);
+ }
+ }
+ if (true) {
+ byte[] bytes1 = new byte[selectConfiguration[invSelectIndex].length];
+ System.arraycopy(selectConfiguration[invSelectIndex], 0, bytes1, 0, bytes1.length);
+ System.arraycopy(bytes, 0, bytes1, 7, bytes.length);
+ bValue = writeMAC(0x3140 + invSelectIndex * 42, bytes1, true);
+ } else {
+ bValue = writeMAC(0x3140 + invSelectIndex * 42 + 7, bytes, true);
+ }
+ if (bValue) System.arraycopy(bytes, 0, selectConfiguration[invSelectIndex], 7, bytes.length);
+ if (DEBUG) appendToLog("bytes = " + byteArrayToString(bytes) + ", new selectConfiguration " + invSelectIndex + " = " + byteArrayToString(selectConfiguration[invSelectIndex]));
+ }
+ if (DEBUG) appendToLog("1 setSelectMaskData with maskData = " + maskData + " and bValue = " + bValue);
+ return bValue;
+
+ }
+
+ public int getQueryTarget() {
+ int iValue = -1; boolean DEBUG = false;
+ if (DEBUG) appendToLog("2 getQueryTarget: iAntennaPort = " + antennaSelect);
+ if (antennaPortConfig[antennaSelect] == null)
+ appendToLog("CANNOT continue as antennaPortConfig[" + antennaSelect + "] is null !!!");
+ else {
+ if (DEBUG)
+ appendToLog("2A getQueryTarget: getAntennaPortConfig[" + antennaSelect + "] = " + byteArrayToString(antennaPortConfig[antennaSelect]));
+ if (antennaPortConfig[antennaSelect][13] != 0) iValue = 2;
+ else if ((antennaPortConfig[antennaSelect][6] & 0x80) != 0) iValue = 1;
+ else iValue = 0;
+ if (DEBUG) appendToLog(String.format("2b getQueryTarget: iValue = 0x%X", iValue));
+ }
+ return iValue;
+ }
+ public boolean setQueryTarget(int queryTarget, int querySession, int querySelect) {
+ boolean bValue = false, DEBUG = false;
+ if (antennaPortConfig[antennaSelect] == null) appendToLog("CANNOT continue as antennaPortConfig[" + antennaSelect + "] is null !!!");
+ else { // queryTarget = 0;
+ if (DEBUG) appendToLog("2 setQueryConfig: queryTarget = " + queryTarget + ", querySession = " + querySession + ", querySelect = " + querySelect);
+ if (DEBUG) appendToLog("2A setQueryConfig: getAntennaPortConfig[" + antennaSelect + "] = " + byteArrayToString(antennaPortConfig[antennaSelect]));
+ byte[] bytes = new byte[9];
+ System.arraycopy(antennaPortConfig[antennaSelect], 5, bytes, 0, bytes.length);
+
+ int iValue;
+ if (querySession >= 0) {
+ iValue = querySession & 0x03;
+ bytes[1] &= ~0x18; bytes[1] |= (iValue << 3);
+ }
+ if (querySelect >= 0) {
+ iValue = querySelect & 0x03;
+ bytes[1] &= ~0x60; bytes[1] |= (iValue << 5);
+ }
+ if (DEBUG) appendToLog("2b setQueryConfig: queryTarget = " + queryTarget);
+ if (queryTarget >= 0) {
+ iValue = queryTarget & 0x01;
+ bytes[1] &= ~0x80; bytes[1] |= (iValue << 7);
+ if (queryTarget >= 2) bytes[8] = 1;
+ else bytes[8] = 0;
+ }
+ if (DEBUG) appendToLog("2C setQueryConfig: bytes = " + byteArrayToString(bytes));
+ boolean bSame = false;
+ if (sameCheck | true) {
+ byte[] bytesOld = new byte[9];
+ System.arraycopy(antennaPortConfig[antennaSelect], 5, bytesOld, 0, bytes.length);
+ if (DEBUG) appendToLog("2d setQueryConfig: bytesOld = " + byteArrayToString(bytesOld));
+ bSame = compareArray(bytes, bytesOld, bytes.length);
+ if (DEBUG) appendToLog("2E setQueryConfig: the array is the same = " + bSame);
+ }
+ //bSame = false; appendToLog("!!! assme bSame is false before 1b writeMAC 0x3035");
+ if (bSame) {
+ if (DEBUG_PKDATA) appendToLog(String.format("!!! Skip sending repeated data %s in address 0x%X", byteArrayToString(bytes), 0x3030 + antennaSelect * 16 + 5));
+ bValue = true;
+ } else {
+ appendToLog("test 2");
+ bValue = rx000Setting.writeMAC(0x3030 + antennaSelect * 16 + 5, bytes, true);
+ if (bValue)
+ System.arraycopy(bytes, 0, antennaPortConfig[antennaSelect], 5, bytes.length);
+ }
+ if (DEBUG) appendToLog("2F setQueryConfig: with updated " + byteArrayToString(antennaPortConfig[antennaSelect]));
+ }
+ return bValue;
+ }
+ public int getQuerySession() {
+ int iValue = -1; boolean DEBUG = false;
+ if (DEBUG) appendToLog("2 getQuerySession: iAntennaPort = " + antennaSelect);
+ if (antennaPortConfig[antennaSelect] == null) appendToLog("CANNOT continue as antennaPortConfig[" + antennaSelect + "] is null !!!");
+ else {
+ if (DEBUG) appendToLog("2A getQuerySession: getAntennaPortConfig[" + antennaSelect + "] = " + byteArrayToString(antennaPortConfig[antennaSelect]));
+ iValue = (antennaPortConfig[antennaSelect][6] & 0x18) >> 3;
+ if (DEBUG) appendToLog(String.format("2b getQuerySession: iValue = 0x%X", iValue));
+ }
+ return iValue;
+ }
+
+ public int getQuerySelect() {
+ int iValue = -1; boolean DEBUG = false;
+ if (DEBUG) appendToLog("2 getQuerySession: iAntennaPort = " + antennaSelect);
+ if (antennaPortConfig[antennaSelect] == null) appendToLog("CANNOT continue as antennaPortConfig[" + antennaSelect + "] is null !!!");
+ else {
+ if (DEBUG) appendToLog("2A getQuerySession: getAntennaPortConfig[" + antennaSelect + "] = " + byteArrayToString(antennaPortConfig[antennaSelect]));
+ iValue = (antennaPortConfig[antennaSelect][6] & 0x60) >> 5;
+ if (DEBUG) appendToLog(String.format("2b getQuerySession: iValue = 0x%X", iValue));
+ }
+ return iValue;
+
+ }
+ public boolean setQuerySelect(int querySelect) {
+ boolean bValue = false, DEBUG = false;
+ for (int antennaSelect = 0; antennaSelect < 16; antennaSelect++) {
+ if (antennaPortConfig[antennaSelect] == null)
+ appendToLog("CANNOT continue as antennaPortConfig[" + antennaSelect + "] is null !!!");
+ else if (antennaPortConfig[antennaSelect][0] == 0) { }
+ else { // queryTarget = 0;
+ if (DEBUG) appendToLog("2 setQuerySelect: querySelect = " + querySelect);
+ if (DEBUG)
+ appendToLog("2A setQuerySelect: getAntennaPortConfig[" + antennaSelect + "] = " + byteArrayToString(antennaPortConfig[antennaSelect]));
+ byte[] bytes = new byte[1];
+ bytes[0] = antennaPortConfig[antennaSelect][6];
+
+ int iValue;
+ if (querySelect >= 0) {
+ iValue = querySelect & 0x03;
+ bytes[0] &= ~0x60;
+ bytes[0] |= (iValue << 5);
+ }
+ if (DEBUG)
+ appendToLog("2C setQueryConfig: bytes = " + byteArrayToString(bytes));
+ boolean bSame = false;
+ if (sameCheck) {
+ if (bytes[0] == antennaPortConfig[antennaSelect][6]) bSame = true;
+ if (DEBUG)
+ appendToLog("2E setQueryConfig: the array is the same = " + bSame);
+ }
+ if (bSame) {
+ if (DEBUG_PKDATA)
+ appendToLog(String.format("!!! Skip sending repeated data %s in address 0x%X", byteArrayToString(bytes), 0x3030 + antennaSelect * 16 + 5));
+ bValue = true;
+ } else {
+ bValue = rx000Setting.writeMAC(0x3030 + antennaSelect * 16 + 6, bytes, true);
+ if (bValue) antennaPortConfig[antennaSelect][6] = bytes[0];
+ }
+ if (DEBUG)
+ appendToLog("2F setQueryConfig: with updated " + byteArrayToString(antennaPortConfig[antennaSelect]));
+ if (bValue == false) break;
+ }
+ }
+ return bValue;
+ }
+
+ final int INVALGO_INVALID = -1; final int INVALGO_MIN = 0; final int INVALGO_MAX = 3;
+ int invAlgo = INVALGO_INVALID;
+ public int getInvAlgo() {
+ int iValue = -1; boolean DEBUG = false;
+ if (DEBUG) appendToLog("3 getInvAlgo: iAntennaPort = " + antennaSelect);
+ if (antennaPortConfig[antennaSelect] == null) appendToLog("CANNOT continue as antennaPortConfig[" + antennaSelect + "] is null !!!");
+ else {
+ if (DEBUG) appendToLog("3A getInvAlgo: getAntennaPortConfig[" + antennaSelect + "] = " + byteArrayToString(antennaPortConfig[antennaSelect]));
+ iValue = antennaPortConfig[antennaSelect][6];
+ if (DEBUG) appendToLog(String.format("3b getInvAlgo: iValue = 0x%X", iValue));
+ iValue &= 0x01; //iValue |= 0x01;
+ if (DEBUG) appendToLog(String.format("3c getInvAlgo: changed iValue = 0x%X", iValue));
+ if (iValue == 0) iValue = 3;
+ else iValue = 0;
+ if (DEBUG) appendToLog(String.format("3d getInvAlgo: after adjustement, iValue = 0x%X", iValue));
+ }
+ return iValue;
+ }
+ public boolean setInvAlgo(int invAlgo) {
+ boolean bValue = false, DEBUG = false;
+ if (DEBUG) appendToLog("3 setInvAlgo[" + invAlgo + "]");
+ if (antennaPortConfig[antennaSelect] == null) appendToLog("CANNOT continue as antennaPortConfig[" + antennaSelect + "] is null !!!");
+ else {
+ byte[] bytes = new byte[1];
+ bytes[0] = (byte)(antennaPortConfig[antennaSelect][6] & ~0x01);
+ if (invAlgo == 0) bytes[0] |= 0x01;
+ if (DEBUG) appendToLog("3 setInvAlgo: bytes = " + byteArrayToString(bytes));
+ bValue = writeMAC(0x3036 + this.antennaSelect * 16, bytes, true);
+ if (bValue) antennaPortConfig[antennaSelect][6] = bytes[0];
+ }
+ if (DEBUG) appendToLog("3A setInvAlgo with bValue = " + bValue);
+ return bValue;
+ }
+
+ final int MATCHREP_INVALID = -1; final int MATCHREP_MIN = 0; final int MATCHREP_MAX = 255;
+ int matchRep = MATCHREP_INVALID;
+ public boolean setMatchRep(int matchRep) {
+ if (matchRep == this.matchRep) return true;
+ if (this.matchRep == matchRep && sameCheck) {
+ appendToLog("Skip sending repeated data with matchRep = " + matchRep);
+ return true;
+ }
+ this.matchRep = matchRep; appendToLog(String.format("!!! Skip setMatchRep[0x%X]", matchRep));
+ return true;
+ }
+
+ final int TAGSELECT_INVALID = -1; final int TAGSELECT_MIN = 0; final int TAGSELECT_MAX = 1;
+ int tagSelect = TAGSELECT_INVALID;
+ public boolean setTagSelect(int tagSelect) {
+ if (tagSelect == this.tagSelect) return true;
+ this.tagSelect = tagSelect; appendToLog(String.format("!!! Skip setTagSelect[%d]", tagSelect));
+ return true;
+ }
+
+ final int NOINVENTORY_INVALID = -1; final int NOINVENTORY_MIN = 0; final int NOINVENTORY_MAX = 1;
+ int noInventory = NOINVENTORY_INVALID;
+
+ final int TAGREAD_INVALID = -1; final int TAGREAD_MIN = 0; final int TAGREAD_MAX = 2;
+ int tagRead = TAGREAD_INVALID;
+ public int getTagRead() {
+ int iValue = 0;
+ if (rx000Setting.multibankReadConfig[0] == null)
+ appendToLog("!!! CANNOT continue as multibankReadConfig[0] is null !!!");
+ else if (rx000Setting.multibankReadConfig[1] == null)
+ appendToLog("!!! CANNOT continue as multibankReadConfig[1] is null !!!");
+ else if (rx000Setting.multibankReadConfig[0][0] != 0) {
+ iValue++;
+ if (rx000Setting.multibankReadConfig[1][0] != 0)
+ iValue++;
+ appendToLog("getTagRead = " + iValue);
+ } else appendToLog("getTagRead = 0 as multibankReadConfig[0] = " + byteArrayToString(multibankReadConfig[0]) + ", [1] = " + byteArrayToString(multibankReadConfig[1]));
+ return iValue;
+ }
+ boolean isMultibankReplyNeed(int index) {
+ boolean bValue = false;
+ if (resReadNoReply) bValue = true;
+ appendToLog("multibankReadConfig[" + index + "] = " + byteArrayToString(rx000Setting.multibankReadConfig[index]) + ", bValue = " + bValue);
+ return bValue;
+ }
+ boolean resReadNoReply = false;
+ public boolean setResReadNoReply(boolean resReadNoReply) {
+ appendToLog("setResReadNoReply[" + resReadNoReply + "]");
+ this.resReadNoReply = resReadNoReply;
+ return true;
+ }
+ public boolean setTagRead(int tagRead) {
+ boolean bValue = false, DEBUG = false;
+ if (DEBUG) appendToLog("0 setTagRead with tagRead = " + tagRead);
+ if (rx000Setting.multibankReadConfig[0] == null)
+ appendToLog("!!! CANNOT continue as multibankReadConfig[0] is null !!!");
+ else if (rx000Setting.multibankReadConfig[1] == null)
+ appendToLog("!!! CANNOT continue as multibankReadConfig[1] is null !!!");
+ else {
+ if (DEBUG) {
+ appendToLog("0 multibankReadConfig[0] = " + byteArrayToString(rx000Setting.multibankReadConfig[0]));
+ appendToLog("0 multibankReadConfig[1] = " + byteArrayToString(rx000Setting.multibankReadConfig[1]));
+ }
+ if ((tagRead == 0 && rx000Setting.multibankReadConfig[0][0] != 0)
+ || (tagRead != 0 && rx000Setting.multibankReadConfig[0][0] == 0)) {
+ byte[] bytes = new byte[1];
+ if (tagRead == 2 && isMultibankReplyNeed(0)) bytes[0] = 2;
+ else if (tagRead != 0) bytes[0] = 1;
+ else bytes[0] = 0;
+ if (true) {
+ byte[] bytes1 = new byte[7];
+ System.arraycopy(rx000Setting.multibankReadConfig[0], 0, bytes1, 0, bytes1.length);
+ System.arraycopy(bytes, 0, bytes1, 0, bytes.length);
+ bValue = writeMAC(0x3270 + 7 * 0, bytes1, true);
+ } else {
+ bValue = writeMAC(0x3270 + 7 * 0, bytes, true);
+ }
+ if (bValue)
+ rx000Setting.multibankReadConfig[0][0] = bytes[0];
+ if (DEBUG)
+ appendToLog("0A multibankReadConfig[0] = " + byteArrayToString(rx000Setting.multibankReadConfig[0]) + ", with bValue = " + bValue);
+ } else bValue = true;
+ if (DEBUG)
+ appendToLog("0 multibankReadConfig[1] = " + byteArrayToString(rx000Setting.multibankReadConfig[1]));
+ if (bValue && ((tagRead < 2 && rx000Setting.multibankReadConfig[1][0] != 0)
+ || (tagRead >= 2 && rx000Setting.multibankReadConfig[1][0] == 0))) {
+ byte[] bytes = new byte[1], bytes1 = null;
+ if (tagRead >= 2) bytes[0] = 1;
+ else bytes[0] = 0;
+ if (true) {
+ bytes1 = new byte[7];
+ System.arraycopy(rx000Setting.multibankReadConfig[1], 0, bytes1, 0, bytes1.length);
+ System.arraycopy(bytes, 0, bytes1, 0, bytes.length);
+ bValue = writeMAC(0x3270 + 7 * 1, bytes1, true);
+ } else {
+ bValue = writeMAC(0x3270 + 7 * 1, bytes, true);
+ }
+ if (bValue)
+ rx000Setting.multibankReadConfig[1][0] = bytes[0];
+ if (DEBUG)
+ appendToLog("0A multibankReadConfig[1] = " + byteArrayToString(rx000Setting.multibankReadConfig[1]));
+ }
+ }
+ return bValue;
+ }
+
+ final int TAGDELAY_INVALID = -1; final int TAGDELAY_MIN = 0; final int TAGDELAY_MAX = 63;
+ int tagDelay = TAGDELAY_INVALID;
+ public boolean setTagDelay(int tagDelay) {
+ if (tagDelay == this.tagDelay) return true;
+ if (this.tagDelay == tagDelay && sameCheck) {
+ appendToLog("!!! Skip sending repeated data with tagDelay = " + tagDelay);
+ return true;
+ }
+ this.tagDelay = tagDelay; appendToLog(String.format("!!! Skip setTagDelay[%d]", tagDelay));
+ return true;
+ }
+
+ byte[] dupElimRollWindow = null;
+ public byte getDupElimRollWindow() {
+ if (dupElimRollWindow != null && dupElimRollWindow.length == 1) return dupElimRollWindow[0];
+ readMAC(0x3900, 1);
+ return ((byte)-1);
+ }
+ public boolean setDupElimRollWindow(byte dupElimDelay) {
+ if (dupElimRollWindow != null && dupElimRollWindow.length == 1 && dupElimRollWindow[0] == dupElimDelay && sameCheck) {
+ appendToLog("!!! Skip sending repeated data with dupElimDelay = " + dupElimDelay);
+ return true;
+ }
+ byte[] bytes = new byte[1];
+ bytes[0] = dupElimDelay;
+ boolean bValue;
+ bValue = rx000Setting.writeMAC(0x3900, bytes, true);
+ if (bValue) dupElimRollWindow = bytes;
+ return true;
+ }
+ Date keepAliveTime;
+ Date inventoryRoundEndTime;
+ int crcErrorRate;
+ int tagRate = -1;
+ public int getTagRate() {
+ int iValue = tagRate;
+ tagRate = -1;
+ return iValue;
+ }
+ byte[] eventPacketUplnkEnable = null;
+ public int getEventPacketUplinkEnable() {
+ if (eventPacketUplnkEnable != null && eventPacketUplnkEnable.length == 2) {
+ int iValue = ((eventPacketUplnkEnable[0] & 0xFF) << 8) + (eventPacketUplnkEnable[1] & 0xFF);
+ appendToLog("eventPacketUplnkEnable iValue = " + iValue);
+ return iValue;
+ }
+ readMAC(0x3906, 2);
+ return -1;
+ }
+
+ public boolean setEventPacketUplinkEnable(byte byteEventPacketUplinkEnable) {
+ if (eventPacketUplnkEnable != null && eventPacketUplnkEnable.length == 2 && eventPacketUplnkEnable[1] == byteEventPacketUplinkEnable && sameCheck) {
+ appendToLog("!!! Skip sending repeated data with byteEventPacketUplinkEnable = " + byteEventPacketUplinkEnable);
+ return true;
+ }
+ byte[] bytes = new byte[2];
+ bytes[1] = byteEventPacketUplinkEnable;
+ boolean bValue;
+ bValue = rx000Setting.writeMAC(0x3906, bytes, true);
+ if (bValue) eventPacketUplnkEnable = bytes;
+ return true;
+ }
+
+ byte[] intraPacketDelay = null;
+ public byte getIntraPacketDelay() {
+ if (intraPacketDelay != null && intraPacketDelay.length == 1) return intraPacketDelay[0];
+ readMAC(0x3908, 1);
+ return ((byte)-1);
+ }
+ public boolean setIntraPacketDelay(byte intraPkDelay) {
+ if (intraPkDelay >= 0 && intraPacketDelay != null && sameCheck) {
+ if (intraPacketDelay.length == 1 && intraPacketDelay[0] == intraPkDelay) {
+ appendToLog("!!! Skip sending repeated data with intraPkDelay = " + intraPkDelay);
+ return true;
+ }
+ }
+ byte[] bytes = new byte[1];
+ bytes[0] = intraPkDelay;
+ boolean bValue;
+ bValue = rx000Setting.writeMAC(0x3908, bytes, true);
+ if (bValue) intraPacketDelay = bytes;
+ return true;
+ }
+ long cycleDelay = -1;
+ public long getCycleDelay() {
+ return cycleDelay;
+ }
+ public boolean setCycleDelay(long cycleDelay) {
+ if (cycleDelay == this.cycleDelay) return true;
+ if (this.cycleDelay == cycleDelay && sameCheck) {
+ appendToLog("!!! Skip sending repeated data with cycleDelay = " + cycleDelay);
+ return true;
+ }
+ this.cycleDelay = cycleDelay; appendToLog(String.format("!!! Skip setCycleDelay[%d]", cycleDelay));
+ return true;
+ }
+
+ final int AUTHENTICATE_CFG_INVALID = -1; final int AUTHENTICATE_CFG_MIN = 0; final int AUTHENTICATE_CFG_MAX = 4095;
+ boolean authenticateSendReply;
+ boolean authenticateIncReplyLength;
+ int authenticateLength = AUTHENTICATE_CFG_INVALID;
+ public int getAuthenticateReplyLength() {
+ if (authenticateLength < AUTHENTICATE_CFG_MIN || authenticateLength > AUTHENTICATE_CFG_MAX) getHST_AUTHENTICATE_CFG();
+ return authenticateLength;
+ }
+ private boolean getHST_AUTHENTICATE_CFG() {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 0, (byte) 0x0F, 0, 0, 0, 0};
+ return sendHostRegRequest(HostRegRequests.HST_AUTHENTICATE_CFG, false, msgBuffer);
+ }
+ boolean setHST_AUTHENTICATE_CFG(boolean sendReply, boolean incReplyLenth, int csi, int length) {
+ appendToLog("sendReply = " + sendReply + ", incReplyLenth = " + incReplyLenth + ", length = " + length);
+ if (length < 0 || length > 0x3FF) return false;
+
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 0, (byte) 0x0F, 0, 0, 0, 0};
+ if (sendReply) msgBuffer[4] |= 0x01; authenticateSendReply = sendReply;
+ if (incReplyLenth) msgBuffer[4] |= 0x02; authenticateIncReplyLength = incReplyLenth;
+ msgBuffer[4] |= ((csi & 0x3F) << 2);
+ msgBuffer[5] |= ((csi >> 6) & 0x03);
+ msgBuffer[5] |= ((length & 0x3F) << 2);
+ msgBuffer[6] |= ((length & 0xFC0) >> 6); authenticateLength = length;
+ return sendHostRegRequest(HostRegRequests.HST_AUTHENTICATE_CFG, true, msgBuffer);
+ }
+
+ byte[] authMatchData0_63; int authMatchDataReady = 0;
+ public String getAuthMatchData() {
+ int length = 96;
+ String strValue = "";
+ for (int i = 0; i < 3; i++) {
+ if (length > 0) {
+ appendToLog("i = " + i + ", authMatchDataReady = " + authMatchDataReady);
+ if ((authMatchDataReady & (0x01 << i)) == 0) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 1, (byte)0x0F, 0, 0, 0, 0};
+ msgBuffer[2] += i;
+ sendHostRegRequest(HostRegRequests.HST_AUTHENTICATE_MSG, false, msgBuffer);
+ } else {
+ for (int j = 0; j < 4; j++) {
+ strValue += String.format("%02X", authMatchData0_63[i * 4 + j]);
+ }
+ }
+ length -= 32;
+ }
+ }
+ if (strValue.length() < 16) strValue = null;
+ return strValue;
+ }
+
+ final int UNTRACEABLE_CFG_INVALID = -1; final int UNTRACEABLE_CFG_MIN = 0; final int UNTRACEABLE_CFG_MAX = 3;
+ int untraceableRange = UNTRACEABLE_CFG_INVALID;
+ boolean untraceableUser;
+ int untraceableTid = UNTRACEABLE_CFG_INVALID;
+ int untraceableEpcLength = UNTRACEABLE_CFG_INVALID;
+ boolean untraceableEpc;
+ boolean untraceableUXpc;
+ public int getUntraceableEpcLength() {
+ if (untraceableRange < UNTRACEABLE_CFG_MIN || untraceableRange > UNTRACEABLE_CFG_MAX) getHST_UNTRACEABLE_CFG();
+ return untraceableEpcLength;
+ }
+ private boolean getHST_UNTRACEABLE_CFG() {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 5, (byte) 0x0F, 0, 0, 0, 0};
+ return sendHostRegRequest(HostRegRequests.HST_UNTRACEABLE_CFG, false, msgBuffer);
+ }
+ public boolean setHST_UNTRACEABLE_CFG(int range, boolean user, int tid, int epcLength, boolean epc, boolean uxpc) {
+ appendToLog("range = " + range + ", user = " + user + ", tid = " + tid + ", epc = " + epc + ", epcLength = " + epcLength + ", xcpc = " + uxpc);
+ if (range < 0 || range > 3) return false;
+ if (tid < 0 || tid > 2) return false;
+ if (epcLength < 0 || epcLength > 31) return false;
+
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 5, (byte) 0x0F, 0, 0, 0, 0};
+ msgBuffer[4] |= (range); untraceableRange = range;
+ if (user) msgBuffer[4] |= 0x04; untraceableUser = user;
+ msgBuffer[4] |= (tid << 3); untraceableTid = tid;
+ msgBuffer[4] |= ((epcLength & 0x7) << 5);
+ msgBuffer[5] |= ((epcLength & 0x18) >> 3); untraceableEpcLength = epcLength;
+ if (epc) msgBuffer[5] |= 0x04; untraceableEpc = epc;
+ if (uxpc) msgBuffer[5] |= 0x08; untraceableUXpc = uxpc;
+ appendToLog("going to do sendHostRegRequest(HostRegRequests.HST_UNTRACEABLE_CFG,");
+ return sendHostRegRequest(HostRegRequests.HST_UNTRACEABLE_CFG, true, msgBuffer);
+ }
+
+ final int TAGJOIN_INVALID = -1; final int TAGJOIN_MIN = 0; final int TAGJOIN_MAX = 1;
+ int invModeCompact = TAGJOIN_INVALID;
+ public boolean setInvModeCompact(boolean bInvModeCompact) {
+ int invModeCompact = (bInvModeCompact ? 1 : 0);
+ if (invModeCompact == this.invModeCompact && sameCheck) {
+ appendToLog("!!! Skip sending repeated data with bInvModeCompact = " + bInvModeCompact);
+ return true;
+ }
+ this.invModeCompact = invModeCompact; appendToLog(String.format("!!! Skip setInvModeCompact[%s]", (bInvModeCompact ? "true" : "false")));
+ return true;
+ }
+
+ final int BRAND_INVALID = -1; final int BRANDID_MIN = 0; final int BRANDID_MAX = 1;
+ int invBrandId = BRAND_INVALID;
+ boolean getInvBrandId() {
+ if (invBrandId < BRANDID_MIN || invBrandId > BRANDID_MAX) { getHST_INV_CFG(); return false; }
+ return (invModeCompact == 1);
+ }
+ public boolean setInvBrandId(boolean invBrandId) {
+ if (invBrandId == getInvBrandId()) return true;
+ this.invBrandId = (invBrandId ? 1 : 0); appendToLog("!!! Skip setInvBrandId[" + invBrandId + "]");
+ return true;
+ }
+ private boolean getHST_INV_CFG() {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 1, 9, 0, 0, 0, 0};
+ return sendHostRegRequest(HostRegRequests.HST_INV_CFG, false, msgBuffer);
+ }
+
+ final int ALGOSELECT_INVALID = -1; final int ALGOSELECT_MIN = 0; final int ALGOSELECT_MAX = 3; //DataSheet says Max=1
+ int algoSelect = ALGOSELECT_INVALID;
+ public boolean setAlgoSelect(int algoSelect) {
+ boolean bValue = false, DEBUG = false;
+ if (antennaPortConfig[antennaSelect] == null) appendToLog("CANNOT continue as antennaPortConfig[" + antennaSelect + "] is null !!!");
+ else { //algoSelect = 0;
+ if (DEBUG) appendToLog("2 setAlgoSelect: algoSelect = " + algoSelect);
+ if (DEBUG) appendToLog("2A setAlgoSelect: getAntennaPortConfig[" + antennaSelect + "] = " + byteArrayToString(antennaPortConfig[antennaSelect]));
+ byte[] bytes = new byte[1];
+ bytes[0] = antennaPortConfig[antennaSelect][6];
+ if (algoSelect >= 3) bytes[0] &= ~0x01;
+ else bytes[0] |= 0x01;
+ if (DEBUG) appendToLog(String.format("2A1 setAlgoSelect: bytes = 0x%X with sameCheck = ", bytes[0]) + sameCheck);
+ boolean bSame = false;
+ if (sameCheck) {
+ if (DEBUG) appendToLog(String.format("2A2 setAlgoSelect: bytesOld = 0x%X", antennaPortConfig[antennaSelect][6]));
+ if (antennaPortConfig[antennaSelect][6] == bytes[0]) bSame = true;
+ if (DEBUG) appendToLog("2ab setAlgoSelect: the array is the same = " + bSame);
+ }
+ if (bSame) {
+ if (DEBUG_PKDATA) appendToLog(String.format("!!! Skip sending repeated data %s in address 0x%X", byteArrayToString(bytes), 0x3030 + antennaSelect * 16 + 6));
+ bValue = true;
+ } else {
+ bValue = rx000Setting.writeMAC(0x3030 + antennaSelect * 16 + 6, bytes, true);
+ if (bValue) antennaPortConfig[antennaSelect][6] = bytes[0];
+ }
+ if (DEBUG) appendToLog("2b setAlgoSelect: with updated array " + byteArrayToString(antennaPortConfig[antennaSelect]));
+ }
+ return bValue;
+ }
+ AlgoSelectedData[] algoSelectedData;
+ public int getAlgoStartQ(int algoSelect) {
+ if (algoSelect < ALGOSELECT_MIN || algoSelect > ALGOSELECT_MAX) {
+ return ALGOSELECT_INVALID;
+ } else {
+ return algoSelectedData[algoSelect].getAlgoStartQ(false);
+ }
+ }
+ public int getAlgoStartQ() {
+ if (algoSelect < ALGOSELECT_MIN || algoSelect > ALGOSELECT_MAX) {
+ return ALGOSELECT_INVALID;
+ } else {
+ return algoSelectedData[algoSelect].getAlgoStartQ(true);
+ }
+ }
+ public boolean setAlgoStartQ(int algoStartQ) {
+ boolean bValue = false, DEBUG = false;
+ if (antennaPortConfig[antennaSelect] == null) appendToLog("CANNOT continue as antennaPortConfig[" + antennaSelect + "] is null !!!");
+ else { //algoStartQ = 6;
+ if (DEBUG) appendToLog("2 setAlgoStartQ: algoStartQ = " + algoStartQ);
+ if (DEBUG) appendToLog("2A setAlgoStartQ: getAntennaPortConfig[" + antennaSelect + "] = " + byteArrayToString(antennaPortConfig[antennaSelect]));
+ byte[] bytes = new byte[1];
+ bytes[0] = antennaPortConfig[antennaSelect][8];
+
+ bytes[0] &= ~0x0F; bytes[0] |= (algoStartQ & 0x0F);
+ if (DEBUG) appendToLog(String.format("2A1 setAlgoStartQ: bytes = 0x%X with sameCheck = ", bytes[0]) + sameCheck);
+ boolean bSame = false;
+ if (sameCheck) {
+ if (antennaPortConfig[antennaSelect][8] == bytes[0]) bSame = true;
+ if (DEBUG) appendToLog("2ab setAlgoStartQ: the array is the same = " + bSame);
+ }
+ if (bSame) {
+ if (DEBUG_PKDATA) appendToLog(String.format("!!! Skip sending repeated data %s in address 0x%X", byteArrayToString(bytes), 0x3030 + antennaSelect * 16 + 8));
+ bValue = true;
+ } else {
+ bValue = writeMAC(0x3030 + antennaSelect * 16 + 8, bytes, true);
+ if (bValue) antennaPortConfig[antennaSelect][8] = bytes[0];
+ }
+ if (DEBUG) appendToLog("2b setAlgoStartQ: with updated " + byteArrayToString(antennaPortConfig[antennaSelect]));
+ }
+ return bValue;
+ }
+ public boolean setAlgoStartQ(int startQ, int algoMaxQ, int algoMinQ, int algoMaxRep, int algoHighThres, int algoLowThres) {
+ if (algoSelect < ALGOSELECT_MIN || algoSelect > ALGOSELECT_MAX) return false;
+ return algoSelectedData[algoSelect].setAlgoStartQ(startQ, algoMaxQ, algoMinQ, algoMaxRep, algoHighThres, algoLowThres);
+ }
+
+ public int getAlgoMaxQ(int algoSelect) {
+ if (algoSelect < ALGOSELECT_MIN || algoSelect > ALGOSELECT_MAX) {
+ return ALGOSELECT_INVALID;
+ } else {
+ return algoSelectedData[algoSelect].getAlgoMaxQ();
+ }
+ }
+
+ public int getAlgoMinQ(int algoSelect) {
+ if (algoSelect < ALGOSELECT_MIN || algoSelect > ALGOSELECT_MAX) {
+ return ALGOSELECT_INVALID;
+ } else {
+ return algoSelectedData[algoSelect].getAlgoMinQ();
+ }
+ }
+
+ final int ALGORETRY_INVALID = -1, ALGORETRY_MIN = 0, ALGORETRY_MAX = 255, ALGORETRY_DEFAULT = 1;
+ int algoRetry = ALGORETRY_INVALID;
+ public int getAlgoMinQCycles() {
+ int iValue = -1; boolean DEBUG = false;
+ if (antennaPortConfig[antennaSelect] == null) appendToLog("CANNOT continue as antennaPortConfig[" + antennaSelect + "] is null !!!");
+ else {
+ if (DEBUG) appendToLog("3A getAlgoMinQCycles: getAntennaPortConfig[" + antennaSelect + "] = " + byteArrayToString(antennaPortConfig[antennaSelect]));
+ iValue = ((antennaPortConfig[antennaSelect][7] >> 4) & 0x0F);
+ if (DEBUG) appendToLog(String.format("3b getAlgoMinQCycles: iValue = 0x%X", iValue));
+ }
+ return iValue;
+ }
+ public boolean setAlgoMinQCycles(int minQCycles) {
+ boolean bValue = false, DEBUG = false;
+ if (antennaPortConfig[antennaSelect] == null) appendToLog("CANNOT continue as antennaPortConfig[" + antennaSelect + "] is null !!!");
+ else if (getAlgoMinQCycles() == minQCycles && sameCheck) {
+ appendToLog("!!! Skip sending repeated data with algoRetry = " + algoRetry);
+ return true;
+ } else {
+ if (DEBUG) appendToLog("3A setAlgoMinQCycles: minQCycles = " + minQCycles + ", getAntennaPortConfig[" + antennaSelect + "] = " + byteArrayToString(antennaPortConfig[antennaSelect]));
+ byte[] data = new byte[1];
+ data[0] = (byte) (antennaPortConfig[antennaSelect][7] & 0x0F);
+ data[0] |= (byte)(minQCycles << 4);
+ bValue = writeMAC(0x3037 + this.antennaSelect * 16, data, true);
+ if (bValue) antennaPortConfig[antennaSelect][7] = data[0];
+ if (DEBUG) appendToLog("3C setAlgoMinQCycles: getAntennaPortConfig[" + antennaSelect + "] = " + byteArrayToString(antennaPortConfig[antennaSelect]));
+ }
+ return bValue;
+ }
+
+ int getAlgoAbFlip(int algoSelect) {
+ if (algoSelect < ALGOSELECT_MIN || algoSelect > ALGOSELECT_MAX) {
+ return ALGOSELECT_INVALID;
+ } else {
+ return algoSelectedData[algoSelect].getAlgoAbFlip();
+ }
+ }
+ public int getAlgoAbFlip() {
+ int iValue = -1; boolean DEBUG = false;
+ if (DEBUG) appendToLog("3 getAlgoAbFlip: iAntennaPort = " + antennaSelect);
+ if (antennaPortConfig[antennaSelect] == null) appendToLog("CANNOT continue as antennaPortConfig[" + antennaSelect + "] is null !!!");
+ else {
+ if (DEBUG) appendToLog("3A getAlgoAbFlip: getAntennaPortConfig[" + antennaSelect + "] = " + byteArrayToString(antennaPortConfig[antennaSelect]));
+ iValue = antennaPortConfig[antennaSelect][13];
+ if (DEBUG) appendToLog(String.format("3b getAlgoAbFlip: iValue = 0x%X", iValue));
+ }
+ return iValue;
+ }
+ public boolean setAlgoAbFlip(int algoAbFlip) {
+ boolean bValue = false, DEBUG = false;
+ if (DEBUG) appendToLog("3 setAlgoAbFlip: iAntennaPort = " + antennaSelect);
+ if (antennaPortConfig[antennaSelect] == null) appendToLog("CANNOT continue as antennaPortConfig[" + antennaSelect + "] is null !!!");
+ else {
+ if (DEBUG) appendToLog("3A setAlgoAbFlip: getAntennaPortConfig[" + antennaSelect + "] = " + byteArrayToString(antennaPortConfig[antennaSelect]));
+ byte[] data = new byte[1];
+ data[0] = (byte)(algoAbFlip & 0xFF);
+ bValue = writeMAC(0x303d + this.antennaSelect * 16, data, true);
+ if (bValue) antennaPortConfig[antennaSelect][13] = data[0];
+ if (DEBUG) appendToLog("3b setAlgoAbFlip: bValue = " + bValue);
+ if (DEBUG) appendToLog("3C setAlgoAbFlip: getAntennaPortConfig[" + antennaSelect + "] = " + byteArrayToString(antennaPortConfig[antennaSelect]));
+ }
+ return bValue;
+ }
+ boolean setAlgoAbFlip(int algoAbFlip, int algoRunTilZero) {
+ if (algoSelect < ALGOSELECT_MIN || algoSelect > ALGOSELECT_MAX) return false;
+ appendToLog("algoSelect = " + algoSelect + ", algoAbFlip = " + algoAbFlip + ", algoRunTilZero = " + algoRunTilZero);
+ return algoSelectedData[algoSelect].setAlgoAbFlip(algoAbFlip, algoRunTilZero);
+ }
+
+ public int getAlgoRunTilZero(int algoSelect) {
+ if (algoSelect < ALGOSELECT_MIN || algoSelect > ALGOSELECT_MAX) {
+ return ALGOSELECT_INVALID;
+ } else {
+ return algoSelectedData[algoSelect].getAlgoRunTilZero();
+ }
+ }
+ int getAlgoRunTilZero() {
+ if (algoSelect < ALGOSELECT_MIN || algoSelect > ALGOSELECT_MAX) {
+ return ALGOSELECT_INVALID;
+ } else {
+ return algoSelectedData[algoSelect].getAlgoRunTilZero();
+ }
+ }
+ int algoRunTilZero = -1, ALGORUNTILZERO_MIN = 0, ALGORUNTILZERO_MAX = 1, ALGORUNTILZERO_DEFAULT = 0;
+ public boolean setAlgoRunTilZero(int algoRunTilZero) {
+ if (algoSelect < ALGOSELECT_MIN || algoSelect > ALGOSELECT_MAX) return false;
+ else if (algoRunTilZero < ALGORUNTILZERO_MIN || algoRunTilZero > ALGORUNTILZERO_MAX) algoRunTilZero = ALGORUNTILZERO_DEFAULT;
+ if (this.algoRunTilZero == algoRunTilZero && sameCheck) {
+ appendToLog("!!! Skip sending repeated data with algoRunTilZero = " + algoRunTilZero);
+ return true;
+ }
+ this.algoRunTilZero = algoRunTilZero; appendToLog(String.format("!!! Skip setAlgoRunTilZero[%d]", algoRunTilZero));
+ return true;
+ }
+
+ int rssiFilterConfig = -1;
+ final int RSSIFILTERTYPE_INVALID = -1, RSSIFILTERTYPE_MIN = 0, RSSIFILTERTYPE_MAX = 2;
+ int rssiFilterType = RSSIFILTERTYPE_INVALID;
+ final int RSSIFILTEROPTION_INVALID = -1, RSSIFILTEROPTION_MIN = 0, RSSIFILTEROPTION_MAX = 4;
+ int rssiFilterOption = RSSIFILTEROPTION_INVALID;
+ public int getRssiFilterType() {
+ if (rssiFilterType < 0) getHST_INV_RSSI_FILTERING_CONFIG();
+ return rssiFilterType;
+ }
+ public int getRssiFilterOption() {
+ if (rssiFilterOption < 0) getHST_INV_RSSI_FILTERING_CONFIG();
+ return rssiFilterOption;
+ }
+ private boolean getHST_INV_RSSI_FILTERING_CONFIG() {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 7, 9, 0, 0, 0, 0};
+ return sendHostRegRequest(HostRegRequests.HST_INV_RSSI_FILTERING_CONFIG, false, msgBuffer);
+ }
+ public boolean setHST_INV_RSSI_FILTERING_CONFIG(int rssiFilterType, int rssiFilterOption) {
+ appendToLog("rssiFilterType = " + rssiFilterType + ", rssiFilterOption = " + rssiFilterOption);
+ byte[] bytes = new byte[] { 0 };
+ if (rssiFilterType > 0) {
+ if (rssiFilterOption > 0) bytes[0] = 2;
+ else bytes[0] = 1;
+ } else bytes[0] = 0;
+ boolean bValue = writeMAC(0x390A, bytes, true);
+ if (bValue) {
+ this.rssiFilterType = rssiFilterType;
+ this.rssiFilterOption = rssiFilterOption;
+ }
+ return bValue;
+ }
+
+ final int RSSIFILTERTHRESHOLD_INVALID = -1, RSSIFILTERTHRESHOLD_MIN = 0, RSSIFILTERTHRESHOLD_MAX = 0xFFFF;
+ int rssiFilterThreshold1 = RSSIFILTERTHRESHOLD_INVALID;
+ public int getRssiFilterThreshold1() {
+ if (rssiFilterThreshold1 < 0) getHST_INV_RSSI_FILTERING_THRESHOLD();
+ return rssiFilterThreshold1;
+ }
+ int rssiFilterThreshold2 = RSSIFILTERTHRESHOLD_INVALID;
+ public int getRssiFilterThreshold2() {
+ if (rssiFilterThreshold2 < 0) getHST_INV_RSSI_FILTERING_THRESHOLD();
+ return rssiFilterThreshold2;
+ }
+ private boolean getHST_INV_RSSI_FILTERING_THRESHOLD() {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 8, 9, 0, 0, 0, 0};
+ return sendHostRegRequest(HostRegRequests.HST_INV_RSSI_FILTERING_THRESHOLD, false, msgBuffer);
+ }
+ public boolean setHST_INV_RSSI_FILTERING_THRESHOLD(int rssiFilterThreshold1, int rssiFilterThreshold2) {
+ byte[] bytes = new byte[2];
+ bytes[0] = (byte)(((short)rssiFilterThreshold1 >> 8) & 0xFF);
+ bytes[1] = (byte)((short)rssiFilterThreshold1 & 0xFF);
+ boolean bValue = writeMAC(0x390C, bytes, true);
+ if (bValue) {
+ this.rssiFilterThreshold1 = rssiFilterThreshold1;
+ this.rssiFilterThreshold2 = rssiFilterThreshold2;
+ }
+ return bValue;
+ }
+
+ final long RSSIFILTERCOUNT_INVALID = -1, RSSIFILTERCOUNT_MIN = 0, RSSIFILTERCOUNT_MAX = 1000000;
+ long rssiFilterCount = RSSIFILTERCOUNT_INVALID;
+ public long getRssiFilterCount() {
+ if (rssiFilterCount < 0) getHST_INV_RSSI_FILTERING_COUNT();
+ return rssiFilterCount;
+ }
+ private boolean getHST_INV_RSSI_FILTERING_COUNT() {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 9, 9, 0, 0, 0, 0};
+ return sendHostRegRequest(HostRegRequests.HST_INV_RSSI_FILTERING_THRESHOLD, false, msgBuffer);
+ }
+ public boolean setHST_INV_RSSI_FILTERING_COUNT(long rssiFilterCount) {
+ appendToLog("entry: rssiFilterCount = " + rssiFilterCount + ", this.rssiFilterCount = " + this.rssiFilterCount);
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 9, 9, 0, 0, 0, 0};
+ if (rssiFilterCount < RSSIFILTERCOUNT_MIN || rssiFilterCount > RSSIFILTERCOUNT_MAX)
+ rssiFilterCount = mDefault.rssiFilterCount;
+ appendToLog("rssiFilterCount 1 = " + rssiFilterCount + ", this.rssiFilterCount = " + this.rssiFilterCount);
+ if (this.rssiFilterCount == rssiFilterCount && sameCheck) return true;
+ appendToLog("rssiFilterCount 2 = " + rssiFilterCount + ", this.rssiFilterCount = " + this.rssiFilterCount);
+ msgBuffer[4] |= (byte) (rssiFilterCount & 0xFF);
+ msgBuffer[5] |= (byte) ((rssiFilterCount >> 8) & 0xFF);
+ msgBuffer[6] |= (byte) ((rssiFilterCount >> 16) & 0xFF);
+ msgBuffer[7] |= (byte) ((rssiFilterCount >> 24) & 0xFF);
+ this.rssiFilterCount = rssiFilterCount;
+ appendToLog("entering to sendHostRegRequest: rssiFilterCount = " + rssiFilterCount);
+ boolean bValue = sendHostRegRequest(HostRegRequests.HST_INV_RSSI_FILTERING_COUNT, true, msgBuffer);
+ appendToLog("after sendHostRegRequest: rssiFilterCount = " + rssiFilterCount);
+ return bValue;
+ }
+
+ final int MATCHENABLE_INVALID = -1; final int MATCHENABLE_MIN = 0; final int MATCHENABLE_MAX = 1;
+ int matchEnable = MATCHENABLE_INVALID;
+ public int getInvMatchEnable() {
+ getHST_INV_EPC_MATCH_CFG();
+ return matchEnable;
+ }
+ public boolean setInvMatchEnable(int matchEnable, int matchType, int matchLength, int matchOffset) {
+ return setHST_INV_EPC_MATCH_CFG(matchEnable, matchType, matchLength, matchOffset);
+ }
+
+ final int MATCHTYPE_INVALID = -1; final int MATCHTYPE_MIN = 0; final int MATCHTYPE_MAX = 1;
+ int matchType = MATCHTYPE_INVALID;
+ public int getInvMatchType() {
+ getHST_INV_EPC_MATCH_CFG();
+ return matchType;
+ }
+
+ final int MATCHLENGTH_INVALID = 0; final int MATCHLENGTH_MIN = 0; final int MATCHLENGTH_MAX = 496;
+ int matchLength = MATCHLENGTH_INVALID;
+ public int getInvMatchLength() {
+ getHST_INV_EPC_MATCH_CFG();
+ return matchLength;
+ }
+
+ final int MATCHOFFSET_INVALID = -1; final int MATCHOFFSET_MIN = 0; final int MATCHOFFSET_MAX = 496;
+ int matchOffset = MATCHOFFSET_INVALID;
+ public int getInvMatchOffset() {
+ getHST_INV_EPC_MATCH_CFG();
+ return matchOffset;
+ }
+
+ private boolean getHST_INV_EPC_MATCH_CFG() { return true; }
+ private boolean setHST_INV_EPC_MATCH_CFG(int matchEnable, int matchType, int matchLength, int matchOffset) {
+ this.matchEnable = matchEnable;
+ this.matchType = matchType;
+ this.matchLength = matchLength;
+ this.matchOffset = matchOffset;
+ return true;
+ }
+
+ byte[] invMatchData0_63; int invMatchDataReady = 0;
+ public String getInvMatchData() {
+ String strValue = "";
+ if (invMatchData0_63 != null) strValue = byteArrayToString(invMatchData0_63);
+ return strValue;
+ }
+ public boolean setInvMatchData(String matchData) {
+ invMatchData0_63 = utility.stringToByteArray(matchData);
+ return true;
+ }
+
+ //Tag access block parameters
+ boolean accessVerfiy;
+ final int ACCRETRY_INVALID = -1; final int ACCRETRY_MIN = 0; final int ACCRETRY_MAX = 7;
+ int accessRetry = ACCRETRY_INVALID;
+ public boolean setAccessRetry(boolean accessVerfiy, int accessRetry) {
+ if (accessVerfiy == this.accessVerfiy && accessRetry == this.accessRetry) return true;
+ this.accessVerfiy = accessVerfiy; this.accessRetry = accessRetry; appendToLog("!!! Skip setAccessRetry[" + accessVerfiy + ", " + accessRetry + "]");
+ return true;
+ }
+
+ boolean setAccessEnable(int accessEnable, int accessEnable2) {
+ boolean bValue = false, DEBUG = false;
+ if (DEBUG) appendToLog("0 setAccessEnable with accessEnable = " + accessEnable + ", accessEnable2 = " + accessEnable2);
+ if (rx000Setting.multibankReadConfig[0] == null) appendToLog("!!! CANNOT continue as multibankReadConfig[0] is null !!!");
+ else if (rx000Setting.multibankReadConfig[1] == null) appendToLog("!!! CANNOT continue as multibankReadConfig[1] is null !!!");
+ else {
+ if (DEBUG) appendToLog("0 multibankReadConfig[0] = " + byteArrayToString(rx000Setting.multibankReadConfig[0]));
+ if (accessEnable == rx000Setting.multibankReadConfig[0][0] && sameCheck) bValue = true;
+ else {
+ byte[] bytes = new byte[1];
+ bytes[0] = (byte) (accessEnable & 0xFF);
+ if (true) {
+ byte[] bytes1 = new byte[7];
+ System.arraycopy(rx000Setting.multibankReadConfig[0], 0, bytes1, 0, bytes1.length);
+ System.arraycopy(bytes, 0, bytes1, 0, bytes.length);
+ bValue = writeMAC(0x3270 + 7 * 0, bytes1, true);
+ } else {
+ bValue = writeMAC(0x3270 + 7 * 0, bytes, true);
+ }
+ if (bValue) rx000Setting.multibankReadConfig[0][0] = bytes[0];
+ if (DEBUG) appendToLog("0A multibankReadConfig[0] = " + byteArrayToString(rx000Setting.multibankReadConfig[0]));
+ }
+ if (DEBUG) appendToLog("0 multibankReadConfig[1] = " + byteArrayToString(rx000Setting.multibankReadConfig[1]));
+ if (accessEnable2 == rx000Setting.multibankReadConfig[1][0] && sameCheck) { }
+ else if (bValue) {
+ byte[] bytes = new byte[1];
+ bytes[0] = (byte) (accessEnable2 & 0xFF);
+ if (true) {
+ byte[] bytes1 = new byte[7];
+ System.arraycopy(rx000Setting.multibankReadConfig[1], 0, bytes1, 0, bytes1.length);
+ System.arraycopy(bytes, 0, bytes1, 0, bytes.length);
+ bValue = writeMAC(0x3270 + 7 * 1, bytes1, true);
+ } else {
+ bValue = writeMAC(0x3270 + 7 * 1, bytes, true);
+ }
+ if (bValue) rx000Setting.multibankReadConfig[1][0] = bytes[0];
+ if (DEBUG) appendToLog("0A multibankReadConfig[1] = " + byteArrayToString(rx000Setting.multibankReadConfig[1]));
+ }
+ }
+ return bValue;
+ }
+ final int ACCBANK_INVALID = -1; final int ACCBANK_MIN = 0; final int ACCBANK_MAX = 3;
+ int accessBank = ACCBANK_INVALID; int accessBank2 = ACCBANK_INVALID;
+ int getAccessBank() {
+ boolean DEBUG = false; int iValue = -1;
+ if (accessBank >= 0 && accessBank <= 3 && rx000Setting.multibankReadConfig[0] == null) appendToLog("!!! CANNOT continue as multibankReadConfig[0] is null !!!");
+ else iValue = rx000Setting.multibankReadConfig[0][1];
+ return iValue;
+ }
+ public boolean setAccessBank(int accessBank) { return setAccessBank(accessBank, 0); }
+ public boolean setAccessBank(int accessBank, int accessBank2) {
+ boolean bValue = false, DEBUG = false;
+ if (DEBUG) appendToLog("0 setAccessBank with accessBank = " + accessBank + ", accessBank2 = " + accessBank2);
+ if (accessBank >= 0 && accessBank <= 3 && rx000Setting.multibankReadConfig[0] == null) appendToLog("!!! CANNOT continue as multibankReadConfig[0] is null !!!");
+ else if (accessBank2 >= 0 && accessBank2 <= 3 && rx000Setting.multibankReadConfig[1] == null) appendToLog("!!! CANNOT continue as multibankReadConfig[1] is null !!!");
+ else {
+ if (DEBUG) appendToLog("0 multibankReadConfig[0] = " + byteArrayToString(rx000Setting.multibankReadConfig[0]));
+ if (accessBank == rx000Setting.multibankReadConfig[0][1] && sameCheck) bValue = true;
+ else if (accessBank >= 0 && accessBank <= 3) {
+ byte[] bytes = new byte[1];
+ bytes[0] = (byte)(accessBank & 0xFF);
+ if (true) {
+ byte[] bytes1 = new byte[7];
+ System.arraycopy(rx000Setting.multibankReadConfig[0], 0, bytes1, 0, bytes1.length);
+ System.arraycopy(bytes, 0, bytes1, 1, bytes.length);
+ bValue = writeMAC(0x3270 + 7 * 0, bytes1, true);
+ } else {
+ bValue = writeMAC(0x3270 + 7 * 0 + 1, bytes, true);
+ }
+ if (bValue) rx000Setting.multibankReadConfig[0][1] = bytes[0];
+ if (DEBUG) appendToLog("0A multibankReadConfig[0] = " + byteArrayToString(rx000Setting.multibankReadConfig[0]));
+ }
+ if (DEBUG) appendToLog("0 multibankReadConfig[1] = " + byteArrayToString(rx000Setting.multibankReadConfig[1]));
+ if (accessBank2 == rx000Setting.multibankReadConfig[1][1] && sameCheck) { }
+ else if (bValue && accessBank2 >= 0 && accessBank2 <= 3) {
+ byte[] bytes = new byte[1];
+ bytes[0] = (byte)(accessBank2 & 0xFF);
+ if (true) {
+ byte[] bytes1 = new byte[7];
+ System.arraycopy(rx000Setting.multibankReadConfig[1], 0, bytes1, 0, bytes1.length);
+ System.arraycopy(bytes, 0, bytes1, 1, bytes.length);
+ bValue = writeMAC(0x3270 + 7 * 1, bytes1, true);
+ } else {
+ bValue = writeMAC(0x3270 + 7 * 1 + 1, bytes, true);
+ }
+ if (bValue) rx000Setting.multibankReadConfig[1][1] = bytes[0];
+ if (DEBUG) appendToLog("0A multibankReadConfig[1] = " + byteArrayToString(rx000Setting.multibankReadConfig[1]));
+ }
+ }
+ return bValue;
+ }
+
+ final int ACCOFFSET_INVALID = -1;
+ int getAccessOffset() {
+ boolean DEBUG = false; int iValue = -1;
+ if (accessBank >= 0 && accessBank <= 3 && rx000Setting.multibankReadConfig[0] == null) appendToLog("!!! CANNOT continue as multibankReadConfig[0] is null !!!");
+ else {
+ iValue = (rx000Setting.multibankReadConfig[0][2] & 0xFF) << 24;
+ iValue |= (rx000Setting.multibankReadConfig[0][3] & 0xFF) << 16;
+ iValue |= (rx000Setting.multibankReadConfig[0][4] & 0xFF) << 8;
+ iValue |= (rx000Setting.multibankReadConfig[0][5] & 0xFF);
+ }
+ return iValue;
+ }
+ public boolean setAccessOffset(int accessOffset) {
+ //appendToLog("10 setAccessOffset with accessOffset = " + accessOffset);
+ return setAccessOffset(accessOffset, 0); }
+ public boolean setAccessOffset(int accessOffset, int accessOffset2) {
+ boolean bValue = false, DEBUG = false;
+ if (DEBUG) appendToLog("0 setAccessOffset with accessOffset = " + accessOffset + ", accessOffset2 = " + accessOffset2);
+ if (accessOffset >= 0 && rx000Setting.multibankReadConfig[0] == null) appendToLog("!!! CANNOT continue as multibankReadConfig[0] is null !!!");
+ else if (accessOffset2 >= 0 && rx000Setting.multibankReadConfig[1] == null) appendToLog("!!! CANNOT continue as multibankReadConfig[1] is null !!!");
+ else {
+ if (DEBUG) appendToLog("0 multibankReadConfig[0] = " + byteArrayToString(rx000Setting.multibankReadConfig[0]));
+ if (accessOffset >= 0) {
+ byte[] bytes = new byte[4];
+ bytes[0] = (byte)((accessOffset >> 24) & 0xFF);
+ bytes[1] = (byte)((accessOffset >> 16) & 0xFF);
+ bytes[2] = (byte)((accessOffset >> 8) & 0xFF);
+ bytes[3] = (byte)(accessOffset & 0xFF);
+ byte[] bytesOld = new byte[4]; System.arraycopy(rx000Setting.multibankReadConfig[0], 2, bytesOld, 0, bytesOld.length);
+ if (compareArray(bytes, bytesOld, bytesOld.length) && sameCheck) bValue = true;
+ else {
+ if (true) {
+ byte[] bytes1 = new byte[7];
+ System.arraycopy(rx000Setting.multibankReadConfig[0], 0, bytes1, 0, bytes1.length);
+ System.arraycopy(bytes, 0, bytes1, 2, bytes.length);
+ bValue = writeMAC(0x3270 + 7 * 0, bytes1, true);
+ } else {
+ bValue = writeMAC(0x3270 + 7 * 0 + 2, bytes, true);
+ }
+ if (bValue) System.arraycopy(bytes, 0, rx000Setting.multibankReadConfig[0], 2, bytes.length);
+ if (DEBUG) appendToLog("0A multibankReadConfig[0] = " + byteArrayToString(rx000Setting.multibankReadConfig[0]));
+ }
+ }
+ if (DEBUG) appendToLog("0 multibankReadConfig[1] = " + byteArrayToString(rx000Setting.multibankReadConfig[1]));
+ if (bValue && accessOffset2 >= 0) {
+ byte[] bytes = new byte[4];
+ bytes[0] = (byte)((accessOffset2 >> 24) & 0xFF);
+ bytes[1] = (byte)((accessOffset2 >> 16) & 0xFF);
+ bytes[2] = (byte)((accessOffset2 >> 8) & 0xFF);
+ bytes[3] = (byte)(accessOffset2 & 0xFF);
+ byte[] bytesOld = new byte[4]; System.arraycopy(rx000Setting.multibankReadConfig[1], 2, bytesOld, 0, bytesOld.length);
+ if (compareArray(bytes, bytesOld, bytesOld.length) && sameCheck) { }
+ else {
+ if (true) {
+ byte[] bytes1 = new byte[7];
+ System.arraycopy(rx000Setting.multibankReadConfig[1], 0, bytes1, 0, bytes1.length);
+ System.arraycopy(bytes, 0, bytes1, 2, bytes.length);
+ bValue = writeMAC(0x3270 + 7 * 1, bytes1, true);
+ } else {
+ bValue = writeMAC(0x3270 + 7 * 1 + 2, bytes, true);
+ }
+ if (bValue) System.arraycopy(bytes, 0, rx000Setting.multibankReadConfig[1], 2, bytes.length);
+ if (DEBUG) appendToLog("0A multibankReadConfig[1] = " + byteArrayToString(rx000Setting.multibankReadConfig[1]));
+ }
+ }
+ }
+ return bValue;
+ }
+
+ final int ACCCOUNT_INVALID = -1; final int ACCCOUNT_MIN = 0; final int ACCCOUNT_MAX = 255;
+ int accessCount = ACCCOUNT_INVALID; int accessCount2 = ACCCOUNT_INVALID;
+ public boolean setAccessCount(int accessCount) {
+ setAccessEnable(((accessCount != 0) ? 1 : 0), 0);
+ return setAccessCount(accessCount, 0); }
+ public boolean setAccessCount(int accessCount, int accessCount2) {
+ boolean bValue = false, DEBUG = false;
+ if (DEBUG) appendToLog("0 setAccessCount with accessCount = " + accessCount + ", accessCount2 = " + accessCount2);
+ if (rx000Setting.multibankReadConfig[0] == null) appendToLog("!!! CANNOT continue as multibankReadConfig[0] is null !!!");
+ else if (rx000Setting.multibankReadConfig[1] == null) appendToLog("!!! CANNOT continue as multibankReadConfig[1] is null !!!");
+ else {
+ if (DEBUG) appendToLog("0 multibankReadConfig[0] = " + byteArrayToString(rx000Setting.multibankReadConfig[0]));
+ if (accessCount == rx000Setting.multibankReadConfig[0][6] && sameCheck) bValue = true;
+ else if (rx000Setting.multibankReadConfig[0][0] == 0) {
+ bValue = true;
+ } else {
+ byte[] bytes = new byte[1], bytes1 = null;
+ bytes[0] = (byte)(accessCount & 0xFF);
+ if (true) {
+ bytes1 = new byte[7];
+ System.arraycopy(rx000Setting.multibankReadConfig[0], 0, bytes1, 0, bytes1.length);
+ System.arraycopy(bytes, 0, bytes1, 6, bytes.length);
+ bValue = writeMAC(0x3270 + 7 * 0, bytes1, true);
+ } else {
+ bValue = writeMAC(0x3270 + 7 * 0 + 6, bytes, true);
+ }
+ if (bValue) rx000Setting.multibankReadConfig[0][6] = bytes[0];
+ if (DEBUG) appendToLog("0A multibankReadConfig[0] = " + byteArrayToString(rx000Setting.multibankReadConfig[0]));
+ }
+ if (DEBUG) appendToLog("0 multibankReadConfig[1] = " + byteArrayToString(rx000Setting.multibankReadConfig[1]));
+ if (accessCount2 == rx000Setting.multibankReadConfig[1][6] && sameCheck) { }
+ else if (rx000Setting.multibankReadConfig[1][0] == 0) {
+ bValue = true;
+ } else if (bValue) {
+ byte[] bytes = new byte[1], bytes1 = null;
+ bytes[0] = (byte)(accessCount2 & 0xFF);
+ if (true) {
+ bytes1 = new byte[7];
+ System.arraycopy(rx000Setting.multibankReadConfig[1], 0, bytes1, 0, bytes1.length);
+ System.arraycopy(bytes, 0, bytes1, 6, bytes.length);
+ bValue = writeMAC(0x3270 + 7 * 1, bytes1, true);
+ } else {
+ bValue = writeMAC(0x3270 + 7 * 1 + 6, bytes, true);
+ }
+ if (bValue) rx000Setting.multibankReadConfig[1][6] = bytes[0];
+ if (DEBUG) appendToLog("0A multibankReadConfig[1] = " + byteArrayToString(rx000Setting.multibankReadConfig[1]));
+ }
+ }
+ return bValue;
+ }
+
+ final int ACCLOCKACTION_INVALID = -1; final int ACCLOCKACTION_MIN = 0; final int ACCLOCKACTION_MAX = 0x3FF;
+ int accessLockAction = ACCLOCKACTION_INVALID;
+ final int ACCLOCKMASK_INVALID = -1; final int ACCLOCKMASK_MIN = 0; final int ACCLOCKMASK_MAX = 0x3FF;
+ int accessLockMask = ACCLOCKMASK_INVALID;
+
+ boolean getHST_TAGACC_LOCKCFG() {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 5, (byte) 0x0A, 0, 0, 0, 0};
+ return sendHostRegRequest(HostRegRequests.HST_TAGACC_LOCKCFG, false, msgBuffer);
+ }
+
+ byte[] lockMask, lockAction;
+ public boolean setAccessLockAction(int accessLockAction, int accessLockMask) {
+ appendToLog("accessLockAction = " + accessLockAction + ", accessLockMask = " + accessLockMask);
+ boolean bValue = false;
+ byte[] bytes = new byte[2];
+ bytes[0] = (byte) (accessLockMask / 256);
+ bytes[1] = (byte) (accessLockMask % 256);
+ bValue = writeMAC(0x38AE, bytes, true);
+ if (bValue) {
+ lockMask = bytes;
+ byte[] bytes1 = new byte[2];
+ bytes1[0] = (byte) (accessLockAction / 256);
+ bytes1[1] = (byte) (accessLockAction % 256);
+ bValue = writeMAC(0x38B0, bytes1, true);
+ if (bValue) lockAction = bytes;
+ }
+ return bValue;
+ }
+
+ byte[] accessPassword = null;
+ public boolean getRx000AccessPassword() {
+ return readMAC(0x38A6, 4);
+ }
+ public boolean setRx000AccessPassword(String password) {
+ boolean bValue = false, DEBUG = false;
+ if (DEBUG) appendToLog("0 setRx000AccessPassword with password = " + password);
+ if (accessPassword == null) appendToLog("!!! CANNOT continue as accessPassword is null !!!");
+ else {
+ if (DEBUG) appendToLog("0 accessPassword = " + byteArrayToString(accessPassword));
+ byte[] bytes = new byte[4];
+ if (password == null) password = "";
+ String hexString = "0123456789ABCDEF";
+ for (int j = 0; j < 16; j++) {
+ if (j + 1 <= password.length()) {
+ String subString = password.substring(j, j + 1).toUpperCase();
+ int k = 0;
+ for (k = 0; k < 16; k++) {
+ if (subString.matches(hexString.substring(k, k + 1))) {
+ break;
+ }
+ }
+ if (k == 16) return false;
+ if ((j / 2) * 2 == j) {
+ bytes[j / 2] |= (byte) (k << 4);
+ } else {
+ bytes[j / 2] |= (byte) (k);
+ }
+ }
+ }
+ byte[] bytesOld = new byte[4];
+ System.arraycopy(accessPassword, 0, bytesOld, 0, bytesOld.length);
+ if (DEBUG) appendToLog("0 bytes = " + byteArrayToString(bytes));
+ if (compareArray(bytes, bytesOld, bytesOld.length) && sameCheck) bValue = true;
+ else {
+ bValue = writeMAC(0x38A6, bytes, true);
+ if (bValue) accessPassword = bytes;
+ if (DEBUG)
+ appendToLog("0A accessPassword = " + byteArrayToString(accessPassword));
+ }
+ }
+ return bValue;
+ }
+
+ final int KILLPWD_INVALID = 0; final long KILLPWD_MIN = 0; final long KILLPWD_MAX = 0x0FFFFFFFF;
+ byte[] killPassword = null;
+ public boolean getRx000KillPassword() {
+ return readMAC(0x38AA, 4);
+ }
+ public boolean setRx000KillPassword(String password) {
+ boolean bValue = false, DEBUG = false;
+ if (DEBUG) appendToLog("0 setRx000KillPassword with password = " + password);
+ if (killPassword == null) appendToLog("!!! CANNOT continue as killPassword is null !!!");
+ else {
+ if (DEBUG) appendToLog("0 killPassword = " + byteArrayToString(killPassword));
+ byte[] bytes = utility.stringToByteArray(password);
+ byte[] bytesOld = new byte[4];
+ System.arraycopy(accessPassword, 0, bytesOld, 0, bytesOld.length);
+ if (DEBUG) appendToLog("0 bytes = " + byteArrayToString(bytes));
+ if (compareArray(bytes, bytesOld, bytesOld.length) && sameCheck) bValue = true;
+ else {
+ bValue = writeMAC(0x38AA, bytes, true);
+ if (bValue) killPassword = bytes;
+ if (DEBUG)
+ appendToLog("0A killPassword = " + byteArrayToString(killPassword));
+ }
+ }
+ return bValue;
+ }
+
+ final int ACCWRITEDATSEL_INVALID = -1; final int ACCWRITEDATSEL_MIN = 0; final int ACCWRITEDATSEL_MAX = 7;
+ int accessWriteDataSelect = ACCWRITEDATSEL_INVALID;
+
+ byte[] accWriteData0_63; int accWriteDataReady = 0;
+ public boolean setAccessWriteData(String dataInput) {
+ boolean bVAlue = false, DEBUG = false;
+ if (DEBUG) appendToLog("Start with dataInput = " + dataInput);
+ dataInput = dataInput.trim();
+ int writeBufLength = 16 * 2; //16
+ int wrieByteSize = 4; //8
+ int length = dataInput.length();
+ if (DEBUG) appendToLog("Check dataInput length = " + length + " with maximum length = " + wrieByteSize * writeBufLength);
+ if (length > wrieByteSize * writeBufLength) return false;
+ byte[] msgBuffer = new byte[length/2 + (length%2 != 0 ? 1 : 0)];
+ for (int i = 0; i < writeBufLength; i++) {
+ if (DEBUG) appendToLog("Before processing 4 nibbles, check length = " + length);
+ if (length > 0) {
+ length -= wrieByteSize;
+ String hexString = "0123456789ABCDEF";
+ for (int j = 0; j < wrieByteSize; j++) {
+ if (DEBUG) appendToLog("Check dataInput = " + dataInput + ", i = " + i + ", wrieByteSize = " + wrieByteSize + ", j = " + j);
+ if (i * wrieByteSize + j >= dataInput.length()) break;
+ String subString = dataInput.substring(i * wrieByteSize + j, i * wrieByteSize + j + 1).toUpperCase();
+ if (DEBUG) appendToLog("subString = " + subString);
+ int k = 0;
+ for (k = 0; k < 16; k++) {
+ if (DEBUG && false) appendToLog("k = " + k + ", with hexString = " + hexString);
+ if (subString.matches(hexString.substring(k, k + 1))) {
+ break;
+ }
+ }
+ if (k == 16) { appendToLog("!!! Cannot decode the data, with with i= " + i + ", j=" + j + ", subString = " + subString); return false; }
+ if ((j / 2) * 2 == j) {
+ msgBuffer[i * 2 + j / 2] |= (byte) (k << 4);
+ } else {
+ msgBuffer[i * 2 + j / 2] |= (byte) (k);
+ }
+ if (DEBUG) appendToLog("j = " + j + " with updated data : " + byteArrayToString(msgBuffer));
+ }
+ if (DEBUG) appendToLog("complete 4 bytes: " + byteArrayToString(msgBuffer));
+ } else break;
+ }
+
+ bVAlue = setMultibankWriteConfig(0,true, getAccessBank(), getAccessOffset(), (msgBuffer.length/2 + (msgBuffer.length%2 != 0 ? 1 : 0)), msgBuffer);
+ if (DEBUG) appendToLog("after setMultibankWriteConfig, bvalue = " + bVAlue);
+ if (bVAlue) {
+ //mRfidReaderChip.mRx000Setting.accWriteDataReady |= (0x01 << i);
+ if (DEBUG) appendToLog("accWriteReady=" + accWriteDataReady);
+ for (int k = 0; k < 4; k++) {
+ //accWriteData0_63[i * 4 + k] = msgBuffer[7 - k];
+ }
+ if (DEBUG) appendToLog("Data=" + byteArrayToString(accWriteData0_63));
+ }
+ return bVAlue;
+ }
+
+ //RFTC block paramters
+ final int PROFILE_INVALID = -1; final int PROFILE_MIN = 0; final int PROFILE_MAX = 5; //profile 4 and 5 are custom profiles.
+ int currentProfile = PROFILE_INVALID;
+ int iRfidModeSingleByte = -1;
+ public int getCurrentProfile() {
+ int iValue = -1; boolean DEBUG = false;
+ if (DEBUG) appendToLog("2 getCurrentProfile: antennaSelect = " + antennaSelect);
+ if (antennaPortConfig[antennaSelect] == null) appendToLog("CANNOT continue as antennaPortConfig[" + antennaSelect + "] is null !!!");
+ else {
+ if (DEBUG) appendToLog("2A getCurrentProfile: getAntennaPortConfig[" + antennaSelect + "] = " + byteArrayToString(antennaPortConfig[antennaSelect]));
+ if (antennaPortConfig[antennaSelect][14] != 0 && antennaPortConfig[antennaSelect][15] == 0) {
+ iRfidModeSingleByte = 1;
+ iValue = antennaPortConfig[antennaSelect][14];
+ } else {
+ iRfidModeSingleByte = 0;
+ iValue = (antennaPortConfig[antennaSelect][14] & 0xFF) << 8;
+ iValue += (antennaPortConfig[antennaSelect][15] & 0xFF);
+ }
+ if (DEBUG) appendToLog(String.format("2b getCurrentProfile: iValue = 0x%X", iValue));
+ }
+ return iValue;
+ }
+ public boolean setCurrentProfile(int currentProfile) {
+ byte[] data; boolean DEBUG = false, bValue = false;
+ if (DEBUG) appendToLog("2 setCurrentProfile: currentProfile = " + currentProfile + ", iRfidModeSingleByte = " + iRfidModeSingleByte);
+ if (antennaPortConfig[antennaSelect] == null) appendToLog("CANNOT continue as antennaPortConfig[" + antennaSelect + "] is null !!!");
+ else if (getCurrentProfile() == currentProfile && sameCheck) bValue = true;
+ else {
+ if (iRfidModeSingleByte < 0) getCurrentProfile();
+ else {
+ if (iRfidModeSingleByte != 0) {
+ data = new byte[1];
+ data[0] = (byte) currentProfile;
+ } else {
+ data = new byte[2];
+ data[0] = (byte) (currentProfile / 256);
+ data[1] = (byte) (currentProfile & 0xFF);
+ }
+ if (DEBUG)
+ appendToLog("2A setCurrentProfile: data = " + byteArrayToString(data));
+ bValue = writeMAC(0x3030 + this.antennaSelect * 16 + 14, data, true);
+ if (DEBUG)
+ appendToLog("2b setCurrentProfile: after writeMAC, bValue = " + bValue);
+ if (bValue && antennaPortConfig[antennaSelect] != null)
+ System.arraycopy(data, 0, antennaPortConfig[antennaSelect], 14, data.length);
+ }
+ }
+ return bValue;
+ }
+
+ final int COUNTRYCODE_INVALID = -1;
+ final int FREQCHANSEL_INVALID = -1;
+
+ final int FREQCHANCONFIG_INVALID = -1; final int FREQCHANCONFIG_MIN = 0; final int FREQCHANCONFIG_MAX = 1;
+ int freqChannelConfig = FREQCHANCONFIG_INVALID;
+
+ final int FREQPLLMULTIPLIER_INVALID = -1;
+
+ final int FREQPLLDAC_INVALID = -1;
+ }
+ class AntennaSelectedData {
+ AntennaSelectedData(boolean set_default_setting, int default_setting_type) {
+ if (default_setting_type < 0) default_setting_type = 0;
+ if (default_setting_type > 5) default_setting_type = 5;
+ mDefault = new AntennaSelectedData.AntennaSelectedData_default(default_setting_type);
+ if (false && set_default_setting) {
+ antennaEnable = mDefault.antennaEnable;
+ antennaInventoryMode = mDefault.antennaInventoryMode;
+ antennaLocalAlgo = mDefault.antennaLocalAlgo;
+ antennaLocalStartQ = mDefault.antennaLocalStartQ;
+ antennaProfileMode = mDefault.antennaProfileMode;
+ antennaLocalProfile = mDefault.antennaLocalProfile;
+ antennaFrequencyMode = mDefault.antennaFrequencyMode;
+ antennaLocalFrequency = mDefault.antennaLocalFrequency;
+ antennaStatus = mDefault.antennaStatus;
+ antennaDefine = mDefault.antennaDefine;
+ antennaDwell = mDefault.antennaDwell;
+ antennaPower = mDefault.antennaPower; appendToLog("antennaPower is set to default " + antennaPower);
+ antennaInvCount = mDefault.antennaInvCount;
+ }
+ }
+
+ class AntennaSelectedData_default {
+ AntennaSelectedData_default(int set_default_setting) {
+ antennaEnable = mDefaultArray.antennaEnable[set_default_setting];
+ antennaInventoryMode = mDefaultArray.antennaInventoryMode[set_default_setting];
+ antennaLocalAlgo = mDefaultArray.antennaLocalAlgo[set_default_setting];
+ antennaLocalStartQ = mDefaultArray.antennaLocalStartQ[set_default_setting];
+ antennaProfileMode = mDefaultArray.antennaProfileMode[set_default_setting];
+ antennaLocalProfile = mDefaultArray.antennaLocalProfile[set_default_setting];
+ antennaFrequencyMode = mDefaultArray.antennaFrequencyMode[set_default_setting];
+ antennaLocalFrequency = mDefaultArray.antennaLocalFrequency[set_default_setting];
+ antennaStatus = mDefaultArray.antennaStatus[set_default_setting];
+ antennaDefine = mDefaultArray.antennaDefine[set_default_setting];
+ antennaDwell = mDefaultArray.antennaDwell[set_default_setting];
+ antennaPower = mDefaultArray.antennaPower[set_default_setting];
+ antennaInvCount = mDefaultArray.antennaInvCount[set_default_setting];
+ }
+
+ int antennaEnable;
+ int antennaInventoryMode;
+ int antennaLocalAlgo;
+ int antennaLocalStartQ;
+ int antennaProfileMode;
+ int antennaLocalProfile;
+ int antennaFrequencyMode;
+ int antennaLocalFrequency;
+ int antennaStatus;
+ int antennaDefine;
+ long antennaDwell;
+ long antennaPower;
+ long antennaInvCount;
+ }
+ AntennaSelectedData.AntennaSelectedData_default mDefault;
+
+ private class AntennaSelectedData_defaultArray { //0 for invalid default, 1 for 0, 2 for 1 to 3, 3 for 4 to 7, 4 for 8 to 11, 5 for 12 to 15
+ int[] antennaEnable = { -1, 1, 0, 0, 0, 0 };
+ int[] antennaInventoryMode = { -1, 0, 0, 0, 0, 0 };
+ int[] antennaLocalAlgo = { -1, 0, 0, 0, 0, 0 };
+ int[] antennaLocalStartQ = { -1, 0, 0, 0, 0, 0 };
+ int[] antennaProfileMode = { -1, 0, 0, 0, 0, 0 };
+ int[] antennaLocalProfile = { -1, 0, 0, 0, 0, 0 };
+ int[] antennaFrequencyMode = { -1, 0, 0, 0, 0, 0 };
+ int[] antennaLocalFrequency = { -1, 0, 0, 0, 0, 0 };
+ int[] antennaStatus = { -1, 0, 0, 0, 0, 0 };
+ int[] antennaDefine = { -1, 0, 0, 1, 2, 3 };
+ long[] antennaDwell = { -1, 2000, 2000, 2000, 2000, 2000 };
+ long[] antennaPower = { -1, 300, 0, 0, 0, 0 };
+ long[] antennaInvCount = { -1, 8192, 8192, 8192, 8192, 8192 };
+ }
+ AntennaSelectedData.AntennaSelectedData_defaultArray mDefaultArray = new AntennaSelectedData.AntennaSelectedData_defaultArray();
+
+ final int ANTENABLE_INVALID = -1; final int ANTENABLE_MIN = 0; final int ANTENABLE_MAX = 1;
+ int antennaEnable = ANTENABLE_INVALID;
+
+ final int ANTINVMODE_INVALID = 0; final int ANTINVMODE_MIN = 0; final int ANTINVMODE_MAX = 1;
+ int antennaInventoryMode = ANTINVMODE_INVALID;
+ int getAntennaInventoryMode() {
+ if (antennaInventoryMode < ANTPROFILEMODE_MIN || antennaInventoryMode > ANTPROFILEMODE_MAX)
+ getHST_ANT_DESC_CFG();
+ return antennaInventoryMode;
+ }
+ boolean setAntennaInventoryMode(int antennaInventoryMode) {
+ return setAntennaEnable(antennaEnable, antennaInventoryMode, antennaLocalAlgo, antennaLocalStartQ, antennaProfileMode,
+ antennaLocalProfile, antennaFrequencyMode, antennaLocalFrequency);
+ }
+
+ final int ANTLOCALALGO_INVALID = 0; final int ANTLOCALALGO_MIN = 0; final int ANTLOCALALGO_MAX = 5;
+ int antennaLocalAlgo = ANTLOCALALGO_INVALID;
+ int getAntennaLocalAlgo() {
+ if (antennaLocalAlgo < ANTLOCALALGO_MIN || antennaLocalAlgo > ANTLOCALALGO_MAX)
+ getHST_ANT_DESC_CFG();
+ return antennaLocalAlgo;
+ }
+ boolean setAntennaLocalAlgo(int antennaLocalAlgo) {
+ return setAntennaEnable(antennaEnable, antennaInventoryMode, antennaLocalAlgo, antennaLocalStartQ,
+ antennaProfileMode, antennaLocalProfile, antennaFrequencyMode, antennaLocalFrequency);
+ }
+
+ final int ANTLOCALSTARTQ_INVALID = 0; final int ANTLOCALSTARTQ_MIN = 0; final int ANTLOCALSTARTQ_MAX = 15;
+ int antennaLocalStartQ = ANTLOCALSTARTQ_INVALID;
+ int getAntennaLocalStartQ() {
+ if (antennaLocalStartQ < ANTLOCALSTARTQ_MIN || antennaLocalStartQ > ANTLOCALSTARTQ_MAX)
+ getHST_ANT_DESC_CFG();
+ return antennaLocalStartQ;
+ }
+ boolean setAntennaLocalStartQ(int antennaLocalStartQ) {
+ return setAntennaEnable(antennaEnable, antennaInventoryMode, antennaLocalAlgo, antennaLocalStartQ,
+ antennaProfileMode, antennaLocalProfile, antennaFrequencyMode, antennaLocalFrequency);
+ }
+
+ final int ANTPROFILEMODE_INVALID = 0; final int ANTPROFILEMODE_MIN = 0; final int ANTPROFILEMODE_MAX = 1;
+ int antennaProfileMode = ANTPROFILEMODE_INVALID;
+ int getAntennaProfileMode() {
+ if (antennaProfileMode < ANTPROFILEMODE_MIN || antennaProfileMode > ANTPROFILEMODE_MAX)
+ getHST_ANT_DESC_CFG();
+ return antennaProfileMode;
+ }
+ boolean setAntennaProfileMode(int antennaProfileMode) {
+ return setAntennaEnable(antennaEnable, antennaInventoryMode, antennaLocalAlgo, antennaLocalStartQ,
+ antennaProfileMode, antennaLocalProfile, antennaFrequencyMode, antennaLocalFrequency);
+ }
+
+ final int ANTLOCALPROFILE_INVALID = 0; final int ANTLOCALPROFILE_MIN = 0; final int ANTLOCALPROFILE_MAX = 5;
+ int antennaLocalProfile = ANTLOCALPROFILE_INVALID;
+ int getAntennaLocalProfile() {
+ if (antennaLocalProfile < ANTLOCALPROFILE_MIN || antennaLocalProfile > ANTLOCALPROFILE_MIN)
+ getHST_ANT_DESC_CFG();
+ return antennaLocalProfile;
+ }
+ boolean setAntennaLocalProfile(int antennaLocalProfile) {
+ return setAntennaEnable(antennaEnable, antennaInventoryMode, antennaLocalAlgo, antennaLocalStartQ,
+ antennaProfileMode, antennaLocalProfile, antennaFrequencyMode, antennaLocalFrequency);
+ }
+
+ final int ANTFREQMODE_INVALID = 0; final int ANTFREQMODE_MIN = 0; final int ANTFREQMODE_MAX = 1;
+ int antennaFrequencyMode = ANTFREQMODE_INVALID;
+ int getAntennaFrequencyMode() {
+ if (antennaFrequencyMode < ANTFREQMODE_MIN || antennaFrequencyMode > ANTFREQMODE_MAX)
+ getHST_ANT_DESC_CFG();
+ return antennaFrequencyMode;
+ }
+ boolean setAntennaFrequencyMode(int antennaFrequencyMode) {
+ return setAntennaEnable(antennaEnable, antennaInventoryMode, antennaLocalAlgo, antennaLocalStartQ,
+ antennaProfileMode, antennaLocalProfile, antennaFrequencyMode, antennaLocalFrequency);
+ }
+
+ final int ANTLOCALFREQ_INVALID = 0; final int ANTLOCALFREQ_MIN = 0; final int ANTLOCALFREQ_MAX = 49;
+ int antennaLocalFrequency = ANTLOCALFREQ_INVALID;
+ int getAntennaLocalFrequency() {
+ if (antennaLocalFrequency < ANTLOCALFREQ_MIN || antennaLocalFrequency > ANTLOCALFREQ_MAX)
+ getHST_ANT_DESC_CFG();
+ return antennaLocalFrequency;
+ }
+ boolean setAntennaLocalFrequency(int antennaLocalFrequency) {
+ return setAntennaEnable(antennaEnable, antennaInventoryMode, antennaLocalAlgo, antennaLocalStartQ,
+ antennaProfileMode, antennaLocalProfile, antennaFrequencyMode, antennaLocalFrequency);
+ }
+
+ private boolean getHST_ANT_DESC_CFG() {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 2, 7, 0, 0, 0, 0};
+ return sendHostRegRequest(HostRegRequests.HST_ANT_DESC_CFG, false, msgBuffer);
+ }
+ boolean setAntennaEnable(int antennaEnable, int antennaInventoryMode, int antennaLocalAlgo, int antennaLocalStartQ,
+ int antennaProfileMode, int antennaLocalProfile,
+ int antennaFrequencyMode, int antennaLocalFrequency) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 2, 7, 0, 0, 0, 0};
+ if (antennaEnable < ANTENABLE_MIN || antennaEnable > ANTENABLE_MAX)
+ antennaEnable = mDefault.antennaEnable;
+ if (antennaInventoryMode < ANTINVMODE_MIN || antennaInventoryMode > ANTINVMODE_MAX)
+ antennaInventoryMode = mDefault.antennaInventoryMode;
+ if (antennaLocalAlgo < ANTLOCALALGO_MIN || antennaLocalAlgo > ANTLOCALALGO_MAX)
+ antennaLocalAlgo = mDefault.antennaLocalAlgo;
+ if (antennaLocalStartQ < ANTLOCALSTARTQ_MIN || antennaLocalStartQ > ANTLOCALSTARTQ_MAX)
+ antennaLocalStartQ = mDefault.antennaLocalStartQ;
+ if (antennaProfileMode < ANTPROFILEMODE_MIN || antennaProfileMode > ANTPROFILEMODE_MAX)
+ antennaProfileMode = mDefault.antennaProfileMode;
+ if (antennaLocalProfile < ANTLOCALPROFILE_MIN || antennaLocalProfile > ANTLOCALPROFILE_MAX)
+ antennaLocalProfile = mDefault.antennaLocalProfile;
+ if (antennaFrequencyMode < ANTFREQMODE_MIN || antennaFrequencyMode > ANTFREQMODE_MAX)
+ antennaFrequencyMode = mDefault.antennaFrequencyMode;
+ if (antennaLocalFrequency < ANTLOCALFREQ_MIN || antennaLocalFrequency > ANTLOCALFREQ_MAX)
+ antennaLocalFrequency = mDefault.antennaLocalFrequency;
+ if (this.antennaEnable == antennaEnable && this.antennaInventoryMode == antennaInventoryMode && this.antennaLocalAlgo == antennaLocalAlgo
+ && this.antennaLocalStartQ == antennaLocalStartQ && this.antennaProfileMode == antennaProfileMode && this.antennaLocalProfile == antennaLocalProfile
+ && this.antennaFrequencyMode == antennaFrequencyMode && this.antennaLocalFrequency == antennaLocalFrequency
+ && sameCheck)
+ return true;
+ msgBuffer[4] |= antennaEnable;
+ msgBuffer[4] |= (antennaInventoryMode << 1);
+ msgBuffer[4] |= (antennaLocalAlgo << 2);
+ msgBuffer[4] |= (antennaLocalStartQ << 4);
+ msgBuffer[5] |= antennaProfileMode;
+ msgBuffer[5] |= (antennaLocalProfile << 1);
+ msgBuffer[5] |= (antennaFrequencyMode << 5);
+ msgBuffer[5] |= ((antennaLocalFrequency & 0x03) << 6);
+ msgBuffer[6] |= (antennaLocalFrequency >> 2);
+ this.antennaEnable = antennaEnable;
+ this.antennaInventoryMode = antennaInventoryMode;
+ this.antennaLocalAlgo = antennaLocalAlgo;
+ this.antennaLocalStartQ = antennaLocalStartQ;
+ this.antennaProfileMode = antennaProfileMode;
+ this.antennaLocalProfile = antennaLocalProfile;
+ this.antennaFrequencyMode = antennaFrequencyMode;
+ this.antennaLocalFrequency = antennaLocalFrequency;
+ return sendHostRegRequest(HostRegRequests.HST_ANT_DESC_CFG, true, msgBuffer);
+ }
+
+ final int ANTSTATUS_INVALID = -1; final int ANTSTATUS_MIN = 0; final int ANTSTATUS_MAX = 0xFFFFF;
+ int antennaStatus = ANTSTATUS_INVALID;
+
+ final int ANTDEFINE_INVALID = -1; final int ANTDEFINE_MIN = 0; final int ANTDEFINE_MAX = 3;
+ int antennaDefine = ANTDEFINE_INVALID;
+
+ final long ANTDWELL_INVALID = -1;
+ long antennaDwell = ANTDWELL_INVALID;
+
+ final long ANTPOWER_INVALID = -1; final long ANTPOWER_MIN = 0; final long ANTPOWER_MAX = 330; //Maximum 330\
+ long antennaPower = ANTPOWER_INVALID; //default value = 300
+
+ final long ANTINVCOUNT_INVALID = -1; final long ANTINVCOUNT_MIN = 0; final long ANTINVCOUNT_MAX = 0xFFFFFFFFL;
+ long antennaInvCount = ANTINVCOUNT_INVALID;
+ long getAntennaInvCount() {
+ if (antennaInvCount < ANTINVCOUNT_MIN || antennaInvCount > ANTINVCOUNT_MAX) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 7, 7, 0, 0, 0, 0};
+ sendHostRegRequest(HostRegRequests.HST_ANT_DESC_INV_CNT, false, msgBuffer);
+ }
+ return antennaInvCount;
+ }
+ }
+ class InvSelectData {
+ InvSelectData(boolean set_default_setting) {
+ if (set_default_setting) {
+ selectEnable = mDefault.selectEnable;
+ selectTarget = mDefault.selectTarget;
+ selectAction = mDefault.selectAction;
+ selectDelay = mDefault.selectDelay;
+ selectMaskBank = mDefault.selectMaskBank;
+ selectMaskOffset = mDefault.selectMaskOffset;
+ selectMaskLength = mDefault.selectMaskLength;
+ }
+ }
+
+ private class InvSelectData_default {
+ int selectEnable = 0;
+ int selectTarget = 0;
+ int selectAction = 0;
+ int selectDelay = 0;
+ int selectMaskBank = 0;
+ int selectMaskOffset = 0;
+ int selectMaskLength = 0;
+ }
+ InvSelectData.InvSelectData_default mDefault = new InvSelectData.InvSelectData_default();
+
+ final int INVSELENABLE_INVALID = 0; final int INVSELENABLE_MIN = 0; final int INVSELENABLE_MAX = 1;
+ int selectEnable = INVSELENABLE_INVALID;
+
+ final int INVSELTARGET_INVALID = -1; final int INVSELTARGET_MIN = 0; final int INVSELTARGET_MAX = 7;
+ int selectTarget = INVSELTARGET_INVALID;
+
+ final int INVSELACTION_INVALID = -1; final int INVSELACTION_MIN = 0; final int INVSELACTION_MAX = 7;
+ int selectAction = INVSELACTION_INVALID;
+
+ final int INVSELDELAY_INVALID = -1; final int INVSELDELAY_MIN = 0; final int INVSELDELAY_MAX = 255;
+ int selectDelay = INVSELDELAY_INVALID;
+
+ final int INVSELMBANK_INVALID = -1; final int INVSELMBANK_MIN = 0; final int INVSELMBANK_MAX = 3;
+ int selectMaskBank = INVSELMBANK_INVALID;
+
+ final int INVSELMOFFSET_INVALID = -1; final int INVSELMOFFSET_MIN = 0; final int INVSELMOFFSET_MAX = 0xFFFF;
+ int selectMaskOffset = INVSELMOFFSET_INVALID;
+
+ final int INVSELMLENGTH_INVALID = -1; final int INVSELMLENGTH_MIN = 0; final int INVSELMLENGTH_MAX = 255;
+ int selectMaskLength = INVSELMLENGTH_INVALID;
+ }
+ class AlgoSelectedData {
+ AlgoSelectedData(boolean set_default_setting, int default_setting_type) {
+ if (default_setting_type < 0) default_setting_type = 0;
+ if (default_setting_type > 4) default_setting_type = 4;
+ mDefault = new AlgoSelectedData.AlgoSelectedData_default(default_setting_type);
+ if (set_default_setting) {
+ algoStartQ = mDefault.algoStartQ;
+ algoMaxQ = mDefault.algoMaxQ;
+ algoMinQ = mDefault.algoMinQ;
+ algoMaxRep = mDefault.algoMaxRep;
+ algoHighThres = mDefault.algoHighThres;
+ algoLowThres = mDefault.algoLowThres;
+ algoRetry = mDefault.algoRetry;
+ algoAbFlip = mDefault.algoAbFlip;
+ algoRunTilZero = mDefault.algoRunTilZero;
+ }
+ }
+
+ class AlgoSelectedData_default {
+ AlgoSelectedData_default(int set_default_setting) {
+ algoStartQ = mDefaultArray.algoStartQ[set_default_setting];
+ algoMaxQ = mDefaultArray.algoMaxQ[set_default_setting];
+ algoMinQ = mDefaultArray.algoMinQ[set_default_setting];
+ algoMaxRep = mDefaultArray.algoMaxRep[set_default_setting];
+ algoHighThres = mDefaultArray.algoHighThres[set_default_setting];
+ algoLowThres = mDefaultArray.algoLowThres[set_default_setting];
+ algoRetry = mDefaultArray.algoRetry[set_default_setting];
+ algoAbFlip = mDefaultArray.algoAbFlip[set_default_setting];
+ algoRunTilZero = mDefaultArray.algoRunTilZero[set_default_setting];
+ }
+
+ int algoStartQ = -1;
+ int algoMaxQ = -1;
+ int algoMinQ = -1;
+ int algoMaxRep = -1;
+ int algoHighThres = -1;
+ int algoLowThres = -1;
+ int algoRetry = -1;
+ int algoAbFlip = -1;
+ int algoRunTilZero = -1;
+ }
+ AlgoSelectedData.AlgoSelectedData_default mDefault;
+
+ class AlgoSelectedData_defaultArray { //0 for invalid default, 1 for 0, 2 for 1, 3 for 2, 4 for 3
+ int[] algoStartQ = { -1, 0, 0, 0, 4 };
+ int[] algoMaxQ = { -1, 0, 0, 0, 15 };
+ int[] algoMinQ = { -1, 0, 0, 0, 0 };
+ int[] algoMaxRep = { -1, 0, 0, 0, 4 };
+ int[] algoHighThres = { -1, 0, 5, 5, 5 };
+ int[] algoLowThres = { -1, 0, 3, 3, 3 };
+ int[] algoRetry = { -1, 0, 0, 0, 0 };
+ int[] algoAbFlip = { -1, 0, 1, 1, 1 };
+ int[] algoRunTilZero = { -1, 0, 0, 0, 0 };
+ }
+ AlgoSelectedData.AlgoSelectedData_defaultArray mDefaultArray = new AlgoSelectedData.AlgoSelectedData_defaultArray();
+
+ final int ALGOSTARTQ_INVALID = -1; final int ALGOSTARTQ_MIN = 0; final int ALGOSTARTQ_MAX = 15;
+ int algoStartQ = ALGOSTARTQ_INVALID;
+ int getAlgoStartQ(boolean getInvalid) {
+ if (getInvalid && (algoStartQ < ALGOSTARTQ_MIN || algoStartQ > ALGOSTARTQ_MAX)) getHST_INV_ALG_PARM_0();
+ return algoStartQ;
+ }
+ boolean setAlgoStartQ(int algoStartQ) {
+ appendToLog("1A setAlgoStartQ with algoStartQ = " + algoStartQ);
+ return setAlgoStartQ(algoStartQ, algoMaxQ, algoMinQ, algoMaxRep, algoHighThres, algoLowThres);
+ }
+
+ final int ALGOMAXQ_INVALID = -1; final int ALGOMAXQ_MIN = 0; final int ALGOMAXQ_MAX = 15;
+ int algoMaxQ = ALGOMAXQ_INVALID;
+ int getAlgoMaxQ() {
+ if (algoMaxQ < ALGOMAXQ_MIN || algoMaxQ > ALGOMAXQ_MAX) getHST_INV_ALG_PARM_0();
+ return algoMaxQ;
+ }
+ boolean setAlgoMaxQ(int algoMaxQ) {
+ appendToLog("1b setAlgoStartQ");
+ return setAlgoStartQ(algoStartQ, algoMaxQ, algoMinQ, algoMaxRep, algoHighThres, algoLowThres);
+ }
+
+ final int ALGOMINQ_INVALID = -1; final int ALGOMINQ_MIN = 0; final int ALGOMINQ_MAX = 15;
+ int algoMinQ = ALGOMINQ_INVALID;
+ int getAlgoMinQ() {
+ if (algoMinQ < ALGOMINQ_MIN || algoMinQ > ALGOMINQ_MAX) getHST_INV_ALG_PARM_0();
+ return algoMinQ;
+ }
+
+ final int ALGOMAXREP_INVALID = -1; final int ALGOMAXREP_MIN = 0; final int ALGOMAXREP_MAX = 255;
+ int algoMaxRep = ALGOMAXREP_INVALID;
+
+ final int ALGOHIGHTHRES_INVALID = -1; final int ALGOHIGHTHRES_MIN = 0; final int ALGOHIGHTHRES_MAX = 15;
+ int algoHighThres = ALGOHIGHTHRES_INVALID;
+
+ final int ALGOLOWTHRES_INVALID = -1; final int ALGOLOWTHRES_MIN = 0; final int ALGOLOWTHRES_MAX = 15;
+ int algoLowThres = ALGOLOWTHRES_INVALID;
+
+ private boolean getHST_INV_ALG_PARM_0() {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 3, 9, 0, 0, 0, 0};
+ return sendHostRegRequest(HostRegRequests.HST_INV_ALG_PARM_0, false, msgBuffer);
+ }
+ boolean setAlgoStartQ(int startQ, int algoMaxQ, int algoMinQ, int algoMaxRep, int algoHighThres, int algoLowThres) {
+ appendToLog("0 setAlgoStartQ with startQ = " + startQ);
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 3, 9, 0, 0, 0, 0};
+ if (startQ < ALGOSTARTQ_MIN || startQ > ALGOSTARTQ_MAX) startQ = mDefault.algoStartQ;
+ if (algoMaxQ < ALGOMAXQ_MIN || algoMaxQ > ALGOMAXQ_MAX) algoMaxQ = mDefault.algoMaxQ;
+ if (algoMinQ < ALGOMINQ_MIN || algoMinQ > ALGOMINQ_MAX) algoMinQ = mDefault.algoMinQ;
+ if (algoMaxRep < ALGOMAXREP_MIN || algoMaxRep > ALGOMAXREP_MAX)
+ algoMaxRep = mDefault.algoMaxRep;
+ if (algoHighThres < ALGOHIGHTHRES_MIN || algoHighThres > ALGOHIGHTHRES_MAX)
+ algoHighThres = mDefault.algoHighThres;
+ if (algoLowThres < ALGOLOWTHRES_MIN || algoLowThres > ALGOLOWTHRES_MAX)
+ algoLowThres = mDefault.algoLowThres;
+ if (false && this.algoStartQ == startQ && this.algoMaxQ == algoMaxQ && this.algoMinQ == algoMinQ
+ && this.algoMaxRep == algoMaxRep && this.algoHighThres == algoHighThres && this.algoLowThres == algoLowThres
+ && sameCheck)
+ return true;
+ msgBuffer[4] |= (byte) (startQ & 0x0F);
+ msgBuffer[4] |= (byte) ((algoMaxQ & 0x0F) << 4);
+ msgBuffer[5] |= (byte) (algoMinQ & 0x0F);
+ msgBuffer[5] |= (byte) ((algoMaxRep & 0xF) << 4);
+ msgBuffer[6] |= (byte) ((algoMaxRep & 0xF0) >> 4);
+ msgBuffer[6] |= (byte) ((algoHighThres & 0x0F) << 4);
+ msgBuffer[7] |= (byte) (algoLowThres & 0x0F);
+ this.algoStartQ = startQ;
+ this.algoMaxQ = algoMaxQ;
+ this.algoMinQ = algoMinQ;
+ this.algoMaxRep = algoMaxRep;
+ this.algoHighThres = algoHighThres;
+ this.algoLowThres = algoLowThres;
+ return sendHostRegRequest(HostRegRequests.HST_INV_ALG_PARM_0, true, msgBuffer);
+ }
+
+ final int ALGORETRY_INVALID = -1; final int ALGORETRY_MIN = 0; final int ALGORETRY_MAX = 255;
+ int algoRetry = ALGORETRY_INVALID;
+
+ final int ALGOABFLIP_INVALID = -1; final int ALGOABFLIP_MIN = 0; final int ALGOABFLIP_MAX = 1;
+ int algoAbFlip = ALGOABFLIP_INVALID;
+ int getAlgoAbFlip() {
+ if (algoAbFlip < ALGOABFLIP_MIN || algoAbFlip > ALGOABFLIP_MAX) getHST_INV_ALG_PARM_2();
+ return algoAbFlip;
+ }
+
+ final int ALGORUNTILZERO_INVALID = -1; final int ALGORUNTILZERO_MIN = 0; final int ALGORUNTILZERO_MAX = 1;
+ int algoRunTilZero = ALGORUNTILZERO_INVALID;
+ int getAlgoRunTilZero() {
+ if (algoRunTilZero < ALGORUNTILZERO_MIN || algoRunTilZero > ALGORUNTILZERO_MAX) getHST_INV_ALG_PARM_2();
+ return algoRunTilZero;
+ }
+ boolean setAlgoRunTilZero(int algoRunTilZero) {
+ return setAlgoAbFlip(algoAbFlip, algoRunTilZero);
+ }
+
+ private boolean getHST_INV_ALG_PARM_2() {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 5, 9, 0, 0, 0, 0};
+ return sendHostRegRequest(HostRegRequests.HST_INV_ALG_PARM_2, false, msgBuffer);
+ }
+ boolean setAlgoAbFlip(int algoAbFlip, int algoRunTilZero) {
+ if (algoAbFlip < ALGOABFLIP_MIN || algoAbFlip > ALGOABFLIP_MAX)
+ algoAbFlip = mDefault.algoAbFlip;
+ if (algoRunTilZero < ALGORUNTILZERO_MIN || algoRunTilZero > ALGORUNTILZERO_MAX)
+ algoRunTilZero = mDefault.algoRunTilZero;
+ if (false) appendToLog("this.algoAbFlip = " + this.algoAbFlip + ", algoAbFlip = " + algoAbFlip + ", this.algoRunTilZero = " + this.algoRunTilZero + ", algoRunTilZero = " + algoRunTilZero);
+ if (false && this.algoAbFlip == algoAbFlip && this.algoRunTilZero == algoRunTilZero && sameCheck) return true;
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 5, 9, 0, 0, 0, 0};
+ if (algoAbFlip != 0) {
+ msgBuffer[4] |= 0x01;
+ }
+ if (algoRunTilZero != 0) {
+ msgBuffer[4] |= 0x02;
+ }
+ this.algoAbFlip = algoAbFlip;
+ this.algoRunTilZero = algoRunTilZero;
+ return sendHostRegRequest(HostRegRequests.HST_INV_ALG_PARM_2, true, msgBuffer);
+ }
+ }
+ public class Rx000EngSetting {
+ int narrowRSSI = -1, wideRSSI = -1;
+ public void resetRSSI() {
+ narrowRSSI = -1; wideRSSI = -1;
+ }
+ }
+
+ //public boolean bFirmware_reset_before = false;
+ final int RFID_READING_BUFFERSIZE = 600; //1024;
+
+ byte[] mRfidToReading = new byte[RFID_READING_BUFFERSIZE];
+ int mRfidToReadingOffset = 0;
+ ArrayList mRx000ToWrite = new ArrayList<>();
+
+ public Rx000Setting rx000Setting = new Rx000Setting(true);
+ public Rx000EngSetting rx000EngSetting = new Rx000EngSetting();
+
+ public ArrayList mRx000ToRead = new ArrayList<>();
+ boolean commandOperating;
+
+ public double decodeNarrowBandRSSI(byte byteRSSI) {
+ byte mantissa = byteRSSI;
+ mantissa &= 0x07;
+ byte exponent = byteRSSI;
+ exponent >>= 3;
+ double dValue = 20 * log10(pow(2, exponent) * (1 + (mantissa / pow(2, 3))));
+ if (false) appendToLog("byteRSSI = " + String.format("%X", byteRSSI) + ", mantissa = " + mantissa + ", exponent = " + exponent + "dValue = " + dValue);
+ return dValue;
+ }
+
+ public boolean bRx000ToReading = false;
+ int getBytes2EpcLength(byte[] bytes) {
+ int iValue = ((bytes[0] & 0xFF) >> 3) * 2;
+ if (false) appendToLog("bytes = " + byteArrayToString(bytes) + ", iValue = " + iValue);
+ return iValue;
+ }
+ void uplinkHandler() {
+ boolean DEBUG = false;
+ if (bRx000ToReading) return;
+ bRx000ToReading = true;
+ int startIndex = 0, startIndexOld = 0, startIndexNew = 0;
+ boolean packageFound = false;
+ int packageType = 0;
+ long lTime = System.currentTimeMillis();
+ if (csReaderConnector.rfidConnector.mRfidToRead.size() != 0) { if (DEBUGTHREAD) appendToLog("mRx000UplinkHandler(): START with mRfidToRead size = " + csReaderConnector.rfidConnector.mRfidToRead.size() + ", mRx000ToRead size = " + mRx000ToRead.size()); }
+ else if (DEBUGTHREAD) appendToLog("START AAA with mRx000ToRead size = " + mRx000ToRead.size());
+ if (false && mRx000ToRead.size() != 0) appendToLog("START AAA with mRx000ToRead size = " + mRx000ToRead.size());
+ boolean bFirst = true;
+ while (csReaderConnector.rfidConnector.mRfidToRead.size() != 0) {
+ if (DEBUG) appendToLog("Looping with mRfidToRead.size = " + csReaderConnector.rfidConnector.mRfidToRead.size() + " with bleConnected = " + csReaderConnector.isConnected());
+ if (csReaderConnector.isConnected() == false) {
+ csReaderConnector.rfidConnector.mRfidToRead.clear();
+ appendToLog("BLE DISCONNECTED !!! mRfidToRead.size() = " + csReaderConnector.rfidConnector.mRfidToRead.size());
+ } else if (System.currentTimeMillis() - lTime > (intervalRx000UplinkHandler/2)) {
+ writeDebug2File("D" + String.valueOf(intervalRx000UplinkHandler) + ", " + System.currentTimeMillis() + ", Timeout");
+ appendToLogView("TIMEOUT !!! mRfidToRead.size() = " + csReaderConnector.rfidConnector.mRfidToRead.size());
+ break;
+ } else {
+ if (DEBUG) appendToLog("Check bFirst = " + bFirst);
+ if (bFirst) { bFirst = false; writeDebug2File("D" + String.valueOf(intervalRx000UplinkHandler) + ", " + System.currentTimeMillis()); }
+ byte[] dataIn = csReaderConnector.rfidConnector.mRfidToRead.get(0).dataValues;
+ long tagMilliSeconds = csReaderConnector.rfidConnector.mRfidToRead.get(0).milliseconds;
+ boolean invalidSequence = csReaderConnector.rfidConnector.mRfidToRead.get(0).invalidSequence;
+ if (DEBUG_APDATA) appendToLog("ApData: found mRfidToRead data with invalidSequence= " + invalidSequence + ", bytes= " + byteArrayToString(dataIn));
+ csReaderConnector.rfidConnector.mRfidToRead.remove(0);
+
+ if (DEBUG) appendToLog("Check buffer size: data.length = " + dataIn.length+ ", mRfidToReading.length = " + mRfidToReading.length + ", mRfidToReadingOffset = " + mRfidToReadingOffset);
+ if (dataIn.length >= mRfidToReading.length - mRfidToReadingOffset) {
+ if (mRfidToReadingOffset != 0) {
+ byte[] unhandledBytes = new byte[mRfidToReadingOffset];
+ System.arraycopy(mRfidToReading, 0, unhandledBytes, 0, unhandledBytes.length);
+ appendToLogView("!!! ERROR insufficient buffer, mRfidToReadingOffset=" + mRfidToReadingOffset + ", dataIn.length=" + dataIn.length + ", clear mRfidToReading: " + byteArrayToString(unhandledBytes));
+ byte[] mRfidToReadingNew = new byte[RFID_READING_BUFFERSIZE];
+ mRfidToReading = mRfidToReadingNew;
+ mRfidToReadingOffset = 0;
+ csReaderConnector.invalidUpdata++;
+ }
+ if (dataIn.length >= mRfidToReading.length - mRfidToReadingOffset) {
+ appendToLogView("!!! ERROR insufficient buffer, mRfidToReading.length=" + mRfidToReading.length + ", dataIn.length=" + dataIn.length + ", clear mRfidToReading: " + byteArrayToString(dataIn));
+ csReaderConnector.invalidata++;
+ break;
+ }
+ }
+
+ if (DEBUG) appendToLog("Check invalidSequence = " + invalidSequence + " with mRfidToReadingOffset = " + mRfidToReadingOffset);
+ if (mRfidToReadingOffset != 0 && invalidSequence) {
+ byte[] unhandledBytes = new byte[mRfidToReadingOffset];
+ System.arraycopy(mRfidToReading, 0, unhandledBytes, 0, unhandledBytes.length);
+ if (true) appendToLog("!!! ERROR invalidSequence with nonzero mRfidToReadingOffset=" + mRfidToReadingOffset + ", throw invalid unused data=" + unhandledBytes.length + ", " + byteArrayToString(unhandledBytes));
+ mRfidToReadingOffset = 0;
+ startIndex = 0;
+ startIndexNew = 0;
+ }
+
+ appendToLog("BtData: DataIn = " + byteArrayToString(dataIn));
+ System.arraycopy(dataIn, 0, mRfidToReading, mRfidToReadingOffset, dataIn.length);
+ mRfidToReadingOffset += dataIn.length;
+
+ int iPayloadSizeMin = 7; //boolean bprinted = false;
+ while (mRfidToReadingOffset - startIndex >= iPayloadSizeMin) {
+ //if (bprinted == false) { bprinted = true; appendToLog(byteArrayToString(mRfidToReading)); }
+ int packageLengthRead = (mRfidToReading[startIndex + 5] & 0xFF) * 256 + (mRfidToReading[startIndex + 6] & 0xFF);
+ int expectedLength = 7 + (mRfidToReading[startIndex + 5] & 0xFF) * 256 + (mRfidToReading[startIndex + 6] & 0xFF);
+ if (DEBUG) appendToLog("Looping with startIndex = " + startIndex + ", mRfidToReadingOffset = " + mRfidToReadingOffset + ", iPayloadSizeMin = " + iPayloadSizeMin + ", expectedLength = " + expectedLength);
+ if (true) {
+ if (mRfidToReading[startIndex + 0] == 0x49
+ && mRfidToReading[startIndex + 1] == (byte) 0xdc
+ && (mRfidToReadingOffset - startIndex >= expectedLength) && (expectedLength > 7)
+ ) {
+ byte[] header = new byte[7], payload = new byte[expectedLength - 7];
+ System.arraycopy(mRfidToReading, startIndex, header, 0, header.length);
+ System.arraycopy(mRfidToReading, startIndex + 7, payload, 0, payload.length);
+ int iUplinkPackageType = (mRfidToReading[startIndex + 2] & 0xFF) * 256 + (mRfidToReading[startIndex + 3] & 0xFF);
+ if (DEBUG_APDATA) appendToLog(String.format("ApData: found Rfid.Uplink.DataRead.UplinkPackage_%04X with payload = ", iUplinkPackageType) + byteArrayToString(payload));
+ RfidReaderChipData.Rx000pkgData dataA = new RfidReaderChipData.Rx000pkgData();
+ dataA.dataValues = new byte[expectedLength - 7];
+ System.arraycopy(mRfidToReading, startIndex + 7, dataA.dataValues, 0, dataA.dataValues.length);
+ if (iUplinkPackageType == 0x3001 || iUplinkPackageType == 0x3003) {
+ dataA.responseType = RfidReaderChipData.HostCmdResponseTypes.TYPE_18K6C_INVENTORY;
+ //mRfidDevice.setInventoring(true);
+ if (DEBUG) appendToLog("Check UplinkPackage_Event_csl_tag_read_epc_only_new data length = " + dataA.dataValues.length);
+ if ((iUplinkPackageType == 0x3001 && dataA.dataValues.length < 17)
+ || (iUplinkPackageType == 0x3003 && dataA.dataValues.length < 18)) {
+ appendToLog("!!! UplinkPackage_Event_csl_tag_read_epc_only_new data length has length equal or less than 15");
+ dataA.decodedError = "Received UplinkPackage_Event_csl_tag_read_epc_only_new with length = " + String.valueOf(dataA.dataValues.length) + ", data = " + byteArrayToString(dataA.dataValues);
+ } else {
+ dataA.decodedTime = System.currentTimeMillis();
+ dataA.decodedRssi = get2BytesOfRssi(dataA.dataValues, 4);
+ if (DEBUG) appendToLog("decoded decodedRssi = " + dataA.decodedRssi);
+ dataA.decodedPhase = (dataA.dataValues[6] & 0xFF) * 256 + (dataA.dataValues[7] & 0xFF);
+ if (DEBUG) appendToLog("decoded decodedPhase = " + dataA.decodedPhase);
+ dataA.decodedPort = (dataA.dataValues[10] & 0xFF);
+ if (DEBUG) appendToLog("decoded decodedPort = " + dataA.decodedPort);
+ dataA.decodedChidx = 1; //(dataA.dataValues[13] & 0xFF) * 256 + (dataA.dataValues[14] & 0xFF);
+ if (DEBUG) appendToLog("decoded decodedChidx = " + dataA.decodedChidx);
+ dataA.decodedPc = new byte[2]; System.arraycopy(dataA.dataValues, 15, dataA.decodedPc, 0, dataA.decodedPc.length);
+ if (DEBUG) appendToLog("decoded decodedPc = " + byteArrayToString(dataA.decodedPc));
+ if (iUplinkPackageType == 0x3001) {
+ dataA.decodedEpc = new byte[dataA.dataValues.length - 17];
+ System.arraycopy(dataA.dataValues, 17, dataA.decodedEpc, 0, dataA.decodedEpc.length);
+ } else {
+ int iEpcLength = getBytes2EpcLength(dataA.decodedPc);
+ if (DEBUG) appendToLog("dataA.dataValues.length = " + dataA.dataValues.length + ", iEpcLength = " + iEpcLength + " for data " + byteArrayToString(dataA.dataValues));
+ if (dataA.dataValues.length - 18 >= iEpcLength) {
+ dataA.decodedEpc = new byte[dataA.dataValues.length - 18];
+ System.arraycopy(dataA.dataValues, 17, dataA.decodedEpc, 0, iEpcLength);
+ System.arraycopy(dataA.dataValues, iEpcLength + 18, dataA.decodedEpc, iEpcLength, dataA.dataValues.length - iEpcLength - 18);
+ if (DEBUG) appendToLog("decodedEpc = " + byteArrayToString(dataA.decodedEpc));
+
+ int iMbDataLength = dataA.dataValues.length - 18 - iEpcLength;
+ int iDataIndex = 0, iDataOffset = 0;
+ for (int i = 0; i < 3; i++) {
+ int iValue = rx000Setting.getMultibankReadLength(i);
+ if (DEBUG) appendToLog("i = " + i + ", getMultibankReadLength = " + iValue);
+ if (iValue != 0) {
+ int iBankLength = iValue * 2;
+ if (DEBUG) appendToLog("Check iDataIndex = " + iDataIndex + ", iDataOffset = " + iDataOffset + ", iBankLength = " + iBankLength + ", iMbDataLength = " + iMbDataLength);
+ if (iDataOffset + iBankLength > iMbDataLength) appendToLog("!!! iBankLength " + iBankLength + " is too long for iDataOffset " + iDataOffset + ", iMbDataLength = " + iMbDataLength);
+ else {
+ if (rx000Setting.getMultibankEnable(i) == 2) iDataIndex++;
+ else if (iDataIndex == 0) {
+ dataA.decodedData1 = new byte[iBankLength];
+ System.arraycopy(dataA.dataValues, iEpcLength + 18 + iDataOffset, dataA.decodedData1, 0, dataA.decodedData1.length);
+ if (DEBUG) appendToLog("decodedData1 = " + byteArrayToString(dataA.decodedData1));
+ iDataIndex++; iDataOffset += iBankLength;
+ } else if (iDataIndex == 1) {
+ dataA.decodedData2 = new byte[iBankLength];
+ System.arraycopy(dataA.dataValues, iEpcLength + 18 + iDataOffset, dataA.decodedData2, 0, dataA.decodedData2.length);
+ if (DEBUG) appendToLog("decodedData2 = " + byteArrayToString(dataA.decodedData2));
+ iDataIndex++; iDataOffset += iBankLength;
+ } else appendToLog("!!! CANNOT handle the third multibank data");
+ }
+ }
+ }
+ int extraLength = 0;
+ if (dataA.decodedData1 != null) extraLength += dataA.decodedData1.length;
+ if (dataA.decodedData2 != null) extraLength += dataA.decodedData2.length;
+ if (extraLength != 0) {
+ byte[] decodedEpcNew = new byte[dataA.decodedEpc.length - extraLength];
+ System.arraycopy(dataA.decodedEpc, 0, decodedEpcNew, 0, decodedEpcNew.length);
+ dataA.decodedEpc = decodedEpcNew;
+ }
+ appendToLog("dataA.decodedPc,Epc = " + byteArrayToString(dataA.decodedPc) + "," + byteArrayToString(dataA.decodedEpc)
+ + ", decodedData1,2 = " + (dataA.decodedData1 == null ? "null" : byteArrayToString(dataA.decodedData1))
+ + ", " + (dataA.decodedData2 == null ? "null" : byteArrayToString(dataA.decodedData2)));
+ if (iDataOffset != iMbDataLength) appendToLog("!!! Some unhandled data as iDataOffset = " + iDataOffset + " for iMbDataLength = " + iMbDataLength);
+ else if (DEBUG) appendToLog("iDataOffset = iMbDataLength = " + iMbDataLength);
+ } else appendToLog("!!! iEpcLength " + iEpcLength + " is too long for the data " + byteArrayToString(dataA.dataValues));
+ }
+ mRx000ToRead.add(dataA);
+ if (DEBUG) appendToLog("3001/3003 dataA.responseType = " + dataA.responseType.toString());
+ if (DEBUG) appendToLog("decoded decodedEpc = " + byteArrayToString(dataA.decodedEpc) + " with mRx000ToRead.size = " + mRx000ToRead.size());
+ if (DEBUG_APDATA) appendToLog("ApData: uplink data UplinkPackage_Event_csl_tag_read_epc_only_new tag with Epc = " + byteArrayToString(dataA.decodedEpc) + " is uploaded to mRx000ToRead with mRx000ToRead.size = " + mRx000ToRead.size());
+ if (DEBUG_APDATA) appendToLog("ApData: Rfid.Uplink.DataRead.UplinkPackage_Event_csl_tag_read_epc_only_new has been processed");
+ }
+ } else if (iUplinkPackageType == 0x3006) {
+ dataA.responseType = RfidReaderChipData.HostCmdResponseTypes.TYPE_18K6C_INVENTORY_COMPACT;
+ //mRfidDevice.setInventoring(true);
+ if (DEBUG) appendToLog("Check UplinkPackage_Event_csl_tag_read_compact data length = " + dataA.dataValues.length);
+ if (dataA.dataValues.length < 10) {
+ appendToLog("!!! UplinkPackage_Event_csl_tag_read_compact data length has length equal or less than 6");
+ dataA.decodedError = "Received Event_csl_tag_read_compact with length = " + String.valueOf(dataA.dataValues.length) + ", data = " + byteArrayToString(dataA.dataValues);
+ } else {
+ int index = 0;
+ byte[] dataHeader = new byte[6]; System.arraycopy(dataA.dataValues, 0, dataHeader, 0, dataHeader.length);
+ byte[] dataValuesFull = new byte[dataA.dataValues.length - 6]; System.arraycopy(dataA.dataValues, 6, dataValuesFull, 0, dataValuesFull.length);
+ if (DEBUG_APDATA) appendToLog("ApData: found Rfid.Uplink.DataRead.UplinkPackage_Event_csl_tag_read_compact with payload header = " + byteArrayToString(dataHeader) + ", dataValuesFull = " + byteArrayToString(dataValuesFull));
+ while (index < dataValuesFull.length) { //change from while
+ if (DEBUG) appendToLog("Looping with index = " + index + ", dataValuesFull.length = " + dataValuesFull.length);
+ dataA.decodedTime = System.currentTimeMillis();
+ if (dataValuesFull.length >= index + 2) {
+ dataA.decodedPc = new byte[2];
+ System.arraycopy(dataValuesFull, index, dataA.decodedPc, 0, dataA.decodedPc.length);
+ index += 2;
+ } else break;
+
+ int epcLength = getBytes2EpcLength(dataA.decodedPc); //((dataA.decodedPc[0] & 0xFF) >> 3) * 2;
+ if (DEBUG) appendToLog("decoded decodedPc = " + byteArrayToString(dataA.decodedPc) + " with epclength = " + epcLength);
+ if (dataValuesFull.length >= index + epcLength) {
+ dataA.decodedEpc = new byte[epcLength];
+ System.arraycopy(dataValuesFull, index, dataA.decodedEpc, 0, epcLength);
+ index += epcLength;
+ } else break;
+
+ if (DEBUG) appendToLog("decoded decodedEpc = " + byteArrayToString(dataA.decodedEpc));
+ if (dataValuesFull.length >= index + 2) {
+ dataA.decodedRssi = get2BytesOfRssi(dataValuesFull, index);
+ if (DEBUG) appendToLog("decoded decodedRssi = " + dataA.decodedRssi);
+ index += 2;
+ } else break;
+
+ mRx000ToRead.add(dataA);
+ if (DEBUG) appendToLog("3006 dataA.responseType = " + dataA.responseType.toString());
+ if (DEBUG_APDATA) appendToLog("ApData: uplink data UplinkPackage_Event_csl_tag_read_compact tag with Epc = " + byteArrayToString(dataA.decodedEpc) + " is uploaded to mRx000ToRead with mRx000ToRead.size = " + mRx000ToRead.size());
+
+ dataA = new RfidReaderChipData.Rx000pkgData();
+ dataA.responseType = RfidReaderChipData.HostCmdResponseTypes.TYPE_18K6C_INVENTORY_COMPACT;
+ }
+ if (DEBUG) appendToLog("Exit while loop with index = " + index + ", dataValuesFull.length = " + dataValuesFull.length);
+ if (index != dataValuesFull.length) {
+ byte[] bytesUnhandled = new byte[dataValuesFull.length - index];
+ System.arraycopy(dataValuesFull, index, bytesUnhandled, 0, bytesUnhandled.length);
+ appendToLog("!!! unhandled data 0: " + byteArrayToString(bytesUnhandled));
+ }
+ if (DEBUG_APDATA) appendToLog("ApData: Rfid.Uplink.DataRead.UplinkPackage_Event_csl_tag_read_compact has been processed");
+ }
+ } else if (iUplinkPackageType == 0x3007) {
+ DEBUG = false;
+ if (DEBUG) appendToLog("Check UplinkPackage_Event_csl_miscellaneous_event data length = " + dataA.dataValues.length);
+ int iCommand = (dataA.dataValues[4] & 0xFF) * 256 + (dataA.dataValues[5] & 0xFF);
+ if (dataA.dataValues.length < 6 || (iCommand >= 3 && dataA.dataValues.length < 8)) {
+ appendToLog("!!! UplinkPackage_Event_csl_miscellaneous_event data length has length equal or less than 8");
+ } else {
+ switch (iCommand) {
+ case 1:
+ rx000Setting.keepAliveTime = new Date();
+ break;
+ case 2:
+ rx000Setting.inventoryRoundEndTime = new Date();
+ break;
+ case 3:
+ rx000Setting.crcErrorRate = ((dataA.dataValues[6] & 0xFF) << 8) + (dataA.dataValues[7] & 0xFF);
+ break;
+ case 4:
+ rx000Setting.tagRate = ((dataA.dataValues[6] & 0xFF) << 8) + (dataA.dataValues[7] & 0xFF);
+ break;
+ default:
+ appendToLog("!!! iCommand cannot be recognised for the uplink data " + byteArrayToString(dataA.dataValues));
+ break;
+ }
+ if (DEBUG_PKDATA) appendToLog("PkData: Rfid.Uplink.DataRead.UplinkPackage_Event_csl_miscellaneous_event has been processed");
+ }
+ } else if (iUplinkPackageType == 0x3008) {
+ dataA.responseType = RfidReaderChipData.HostCmdResponseTypes.TYPE_COMMAND_END;
+ setInventoring(false);
+ appendToLogView("mRx000UplinkHandler_3008: " + byteArrayToString(dataA.dataValues));
+ if (DEBUG) appendToLog("Check UplinkPackage_Event_csl_operation_complete data length = " + dataA.dataValues.length);
+ if (dataA.dataValues.length < 8) {
+ appendToLog("!!! UplinkPackage_Event_csl_operation_complete data length has length equal or less than 8");
+ dataA.decodedError = "Received Event_csl_operation_complete with length = " + String.valueOf(dataA.dataValues.length) + ", data = " + byteArrayToString(dataA.dataValues);
+ } else {
+ int iCommand = (dataA.dataValues[4] & 0xFF) * 256 + (dataA.dataValues[5] & 0xFF);
+ int iStatus = (dataA.dataValues[6] & 0xFF) * 256 + (dataA.dataValues[7] & 0xFF);
+ if (DEBUG_APDATA) appendToLog("ApData: found Rfid.Uplink.DataRead.UplinkPackage_Event_csl_operation_complete");
+ if (DEBUG) appendToLog("Check iStatus = " + iStatus);
+ switch (iStatus) {
+ case 0:
+ dataA.decodedError = null;
+ break;
+ case 1:
+ dataA.decodedError = "0x0001 Tag cache table buffer is overflowed";
+ break;
+ case 2:
+ dataA.decodedError = "0x0002 Wrong register address";
+ break;
+ case 3:
+ dataA.decodedError = "0x0003 Register length too large";
+ break;
+ case 4:
+ dataA.decodedError = "0x0004 E710 not powered up";
+ break;
+ case 5:
+ dataA.decodedError = "0x0005 Invalid parameter";
+ break;
+ case 6:
+ dataA.decodedError = "0x0006 Event fifo full";
+ break;
+ case 7:
+ dataA.decodedError = "0x0007 TX not ramped up";
+ break;
+ case 8:
+ dataA.decodedError = "0x0008 Register read only";
+ break;
+ case 9:
+ dataA.decodedError = "0x0009 Failed to halt";
+ break;
+ case 10:
+ dataA.decodedError = "0x000A PLL not locked";
+ break;
+ case 11:
+ dataA.decodedError = "0x000B Power control target failed";
+ break;
+ case 12:
+ dataA.decodedError = "0x000C Radio power not enabled";
+ break;
+ case 13:
+ dataA.decodedError = "0x000D E710 command error (e.g. battery low)";
+ break;
+ case 14:
+ dataA.decodedError = "0x000E E710 Op timeout";
+ break;
+ case 15:
+ dataA.decodedError = "0x000F E710 Aggregate error (e.g. battery low, metal reflection)";
+ break;
+ case 0x10:
+ dataA.decodedError = "0x0010 E710 hardware link error";
+ break;
+ case 0x11:
+ dataA.decodedError = "0x0011 E710 event fail to send error";
+ break;
+ case 0x12:
+ dataA.decodedError = "0x0012 E710 antenna error (e.g. metal reflection)";
+ break;
+ case 0x00FF:
+ dataA.decodedError = "0x00FF Other error (e.g. battery low)";
+ break;
+ default:
+ dataA.decodedError = "Unknown error";
+ appendToLog("!!! CANNOT handle status type with " + byteArrayToString(header) + "." + byteArrayToString(payload));
+ break;
+ }
+ mRx000ToRead.add(dataA);
+ if (DEBUG) appendToLog("3008 dataA.responseType = " + dataA.responseType.toString());
+ if (DEBUG_APDATA) appendToLog("ApData: uplink data UplinkPackage_Event_csl_operation_complete with decodedError = " + dataA.decodedError + " is uploaded to mRx000ToRead with mRx000ToRead.size = " + mRx000ToRead.size());
+ if (DEBUG_APDATA) appendToLog("ApData: Rfid.Uplink.DataRead.UplinkPackage_Event_csl_operation_complete has been processed");
+ }
+ } else if (iUplinkPackageType == 0x3009) {
+ dataA.responseType = RfidReaderChipData.HostCmdResponseTypes.TYPE_18K6C_TAG_ACCESS;
+ if (DEBUG) appendToLog("Check UplinkPackage_Event_csl_access_complete data length = " + dataA.dataValues.length);
+ if (dataA.dataValues.length < 12) {
+ appendToLog("!!! UplinkPackage_Event_csl_access_complete data length has length equal or less than 12");
+ dataA.decodedError = "Received Event_csl_access_complete with length = " + String.valueOf(dataA.dataValues.length) + ", data = " + byteArrayToString(dataA.dataValues);
+ } else {
+ int iCommand = (dataA.dataValues[4] & 0xFF) * 256 + (dataA.dataValues[5] & 0xFF);
+ int iTagError = dataA.dataValues[6];
+ int iMacError = dataA.dataValues[7];
+ int iWriteCount = dataA.dataValues[8] * 256 + dataA.dataValues[9];
+ byte[] bytesResponse = null, bytesHeader = new byte[12];
+ System.arraycopy(dataA.dataValues, 0, bytesHeader, 0, bytesHeader.length);
+ if (dataA.dataValues.length > 12) {
+ bytesResponse = new byte[dataA.dataValues.length - 12];
+ System.arraycopy(dataA.dataValues, 12, bytesResponse, 0, bytesResponse.length);
+ if (DEBUG)
+ appendToLog("bytesResponse = " + byteArrayToString(bytesResponse));
+ }
+ String string = null;
+ switch (iTagError) {
+ case 0x00:
+ string = "Other error";
+ break;
+ case 0x01:
+ string = "Not supported";
+ break;
+ case 0x02:
+ string = "Insufficient privileges";
+ break;
+ case 0x03:
+ string = "Memory overrun";
+ break;
+ case 0x04:
+ string = "Memory locked";
+ break;
+ case 0x05:
+ string = "Crypto suite error";
+ break;
+ case 0x06:
+ string = "Command not encapsulated";
+ break;
+ case 0x07:
+ string = "ResponseBuffer overflow";
+ break;
+ case 0x08:
+ string = "Security timeout";
+ break;
+ case 0x0B:
+ string = "Insufficient power";
+ break;
+ case 0x0F:
+ string = "Non-specific error";
+ break;
+ case 0x10:
+ //string = "No error";
+ break;
+ default:
+ string = "OTHER errors";
+ break;
+ }
+ if (string != null)
+ dataA.decodedError = "Tag Error: " + string;
+ string = null;
+ switch (iMacError) {
+ case 0x00:
+ //string = "No error";
+ break;
+ case 0x01:
+ string = "No tag reply";
+ break;
+ case 0x02:
+ string = "Invalid password";
+ break;
+ case 0x03:
+ string = "Failed to send command";
+ break;
+ case 0x04:
+ string = "No access reply";
+ break;
+ default:
+ string = "OTHER errors";
+ break;
+ }
+ if (string != null) {
+ if (dataA.decodedError == null)
+ dataA.decodedError = "Mac Error: " + string;
+ else dataA.decodedError += (", Mac Error: " + string);
+ }
+ if (iCommand == 0xC3 && iWriteCount == 0) {
+ string = "Write Error: nothing is written";
+ if (dataA.decodedError == null)
+ dataA.decodedError = string;
+ else dataA.decodedError += (", " + string);
+ appendToLog(String.format("rx000pkgData: Command 0x%X with mRfidToWrite.size = %s", iCommand, csReaderConnector.rfidConnector.mRfidToWrite.size()));
+ }
+ if (DEBUG)
+ appendToLog("decodedError2 = " + dataA.decodedError);
+ appendToLog("bytesResponse is " + (bytesResponse == null ? "null" : byteArrayToString(bytesResponse)));
+ if (bytesResponse != null && bytesResponse.length != 0) {
+ for (int i = 0; i < bytesResponse.length; i++) {
+ string = String.format("%02X", (byte) ((bytesResponse[i] & 0xFF)));
+ if (dataA.decodedResult == null)
+ dataA.decodedResult = string;
+ else dataA.decodedResult += string;
+ }
+ } else dataA.decodedResult = "";
+ if (DEBUG || true)
+ appendToLog("decodedResult = " + dataA.decodedResult);
+ }
+ mRx000ToRead.add(dataA);
+ if (DEBUG) appendToLog("3009 dataA.responseType = " + dataA.responseType.toString());
+ if (DEBUG_APDATA) appendToLog("ApData: uplink data UplinkPackage_Event_csl_access_complete tag with data = " + byteArrayToString(dataA.dataValues) + " is uploaded to mRx000ToRead with mRx000ToRead.size = " + mRx000ToRead.size());
+ if (DEBUG_APDATA) appendToLog("ApData: Rfid.Uplink.DataRead.UplinkPackage_Event_csl_access_complete has been processed");
+ }
+ else appendToLog(String.format("!!! CANNOT handle UplinkPackageType 0x%X", iUplinkPackageType) + " with uplink data " + byteArrayToString(header) + "." + byteArrayToString(payload));
+ packageFound = true;
+ packageType = 4;
+ startIndexNew = startIndex + expectedLength;
+ }
+ }
+
+ if (packageFound) {
+ packageFound = false;
+ if (DEBUG) appendToLog("Found package with packageType = " + packageType + ", Check startIndex = " + startIndex + " with startIndexNew = " + startIndexNew + ", mRfidToReadingOffset = " + mRfidToReadingOffset);
+ if (DEBUG && startIndex != 0) {
+ byte[] unhandledBytes = new byte[startIndex];
+ System.arraycopy(mRfidToReading, 0, unhandledBytes, 0, unhandledBytes.length);
+ appendToLog("!!! packageFound with invalid unused data: " + unhandledBytes.length + ", " + byteArrayToString(unhandledBytes));
+ csReaderConnector.invalidUpdata++;
+ }
+ if (DEBUG) {
+ byte[] usedBytes = new byte[startIndexNew - startIndex];
+ System.arraycopy(mRfidToReading, startIndex, usedBytes, 0, usedBytes.length);
+ if (DEBUG) appendToLog("used data = " + usedBytes.length + ", " + byteArrayToString(usedBytes));
+ }
+ byte[] mRfidToReadingNew = new byte[RFID_READING_BUFFERSIZE];
+ System.arraycopy(mRfidToReading, startIndexNew, mRfidToReadingNew, 0, mRfidToReadingOffset - startIndexNew);
+ mRfidToReading = mRfidToReadingNew;
+ mRfidToReadingOffset -= startIndexNew;
+ startIndex = 0;
+ startIndexNew = 0;
+ startIndexOld = 0;
+ if (DEBUG) appendToLog("Check new mRfidToReadingOffset = " + mRfidToReadingOffset + " with startIndex and startIndexNew = 0");
+ if (DEBUG && mRfidToReadingOffset != 0) {
+ byte[] remainedBytes = new byte[mRfidToReadingOffset];
+ System.arraycopy(mRfidToReading, 0, remainedBytes, 0, remainedBytes.length);
+ appendToLog("!!! moved with remained bytes=" + byteArrayToString(remainedBytes));
+ }
+ } else {
+ startIndex++;
+ }
+ }
+ if (DEBUG) appendToLog("Exit while loop with startIndex = " + startIndex + ", mRfidToReadingOffset = " + mRfidToReadingOffset + ", iPayloadSizeMin = " + iPayloadSizeMin);
+ if (startIndex != 0 && mRfidToReadingOffset != 0) {
+ //appendToLog("exit while(-8) loop with startIndex = " + startIndex + ( startIndex == 0 ? "" : "(NON-ZERO)" ) + ", mRfidToReadingOffset=" + mRfidToReadingOffset);
+ if (startIndex > mRfidToReadingOffset) appendToLog("!!! ERROR. startIndex = " + startIndex + " is greater than mRfidToReadingOffset = " + mRfidToReadingOffset);
+ else {
+ byte[] unhandled = new byte[startIndex];
+ System.arraycopy(mRfidToReading, 0, unhandled, 0, unhandled.length);
+ appendToLog("!!! Unhandled data 1: " + byteArrayToString(unhandled));
+ byte[] mRfidToReadingNew = new byte[RFID_READING_BUFFERSIZE];
+ System.arraycopy(mRfidToReading, startIndex, mRfidToReadingNew, 0, mRfidToReadingOffset - startIndex);
+ mRfidToReading = mRfidToReadingNew;
+ mRfidToReadingOffset = mRfidToReadingOffset - startIndex;
+ startIndex = 0;
+ startIndexNew = 0;
+ csReaderConnector.invalidUpdata++;
+ }
+ }
+ }
+ }
+ if (DEBUG & bFirst == false) appendToLog("Exit while loop with mRfidToRead.size = " + csReaderConnector.rfidConnector.mRfidToRead.size());
+ //if (DEBUG) appendToLog("mRfidToReadingOffset = " + mRfidToReadingOffset + ", startIndexNew = " + startIndexNew);
+ //if (mRfidToReadingOffset == startIndexNew && mRfidToReadingOffset != 0) {
+ // byte[] unusedData = new byte[mRfidToReadingOffset];
+ // System.arraycopy(mRfidToReading, 0, unusedData, 0, unusedData.length);
+ // appendToLog("Ending with invaid unused data: " + mRfidToReadingOffset + ", " + byteArrayToString(unusedData));
+ // mRfidToReading = new byte[RFID_READING_BUFFERSIZE];
+ // mRfidToReadingOffset = 0;
+ //}
+ bRx000ToReading = false;
+ if (DEBUGTHREAD) {
+ if (mRx000ToRead.size() != 0) appendToLog("mRx000UplinkHandler(): END with mRx000ToRead size = " + mRx000ToRead.size());
+ }
+ }
+ public boolean turnOn(boolean onStatus) {
+ appendToLog("aabb 1");
+ RfidConnector.CsReaderRfidData csReaderRfidData = new RfidConnector.CsReaderRfidData();
+ if (onStatus) {
+ csReaderRfidData.rfidPayloadEvent = RfidConnector.RfidPayloadEvents.RFID_POWER_ON;
+ csReaderRfidData.waitUplinkResponse = false;
+ appendToLog("aabb 2");
+ addRfidToWrite(csReaderRfidData);
+ return true;
+ } else if (onStatus == false) {
+ csReaderRfidData.rfidPayloadEvent = RfidConnector.RfidPayloadEvents.RFID_POWER_OFF;
+ csReaderRfidData.waitUplinkResponse = false;
+ addRfidToWrite(csReaderRfidData);
+ return true;
+ } else {
+ return false;
+ }
+ }
+
+ boolean bLowPowerStandby = false;
+ public boolean setPwrManagementMode(boolean bLowPowerStandby) {
+ if (csReaderConnector.isConnected() == false) return false;
+ if (this.bLowPowerStandby == bLowPowerStandby) return true;
+ this.bLowPowerStandby = bLowPowerStandby; appendToLog("!!! Skip setPwrManagementMode[" + bLowPowerStandby + "] with this.blowPowerStandby = " + this.bLowPowerStandby);
+ return true;
+ }
+
+ int wideRSSI = -1;
+ public int getwideRSSI() {
+ if (wideRSSI < 0) {
+ setPwrManagementMode(false);
+ wideRSSI = 0; appendToLog("!!! Skip getwideRSSI with assumed value = 0");
+ }
+ return wideRSSI;
+ }
+
+ final int RXGAIN_INVALID = -1, RXGAIN_MIN = 0, RXGAIN_MAX = 0x1FF, RXGAIN_DEFAULT = 0x104;
+ int rxGain = RXGAIN_INVALID;
+ public int getHighCompression() {
+ int iRetValue = -1;
+ if (rxGain < RXGAIN_MIN || rxGain > RXGAIN_MAX) {
+ setPwrManagementMode(false);
+ rxGain = RXGAIN_DEFAULT; appendToLog(String.format("!!! Skip getHighCompression with assumed rxGain = 0x%X", RXGAIN_DEFAULT));
+ } else iRetValue = (rxGain >> 8);
+ return iRetValue;
+ }
+ public int getRflnaGain() {
+ int iRetValue = -1;
+ if (rxGain < RXGAIN_MIN || rxGain > RXGAIN_MAX) {
+ setPwrManagementMode(false);
+ rxGain = RXGAIN_DEFAULT; appendToLog(String.format("!!! Skip getRflnaGain with assumed rxGain = 0x%X", RXGAIN_DEFAULT));
+ } else iRetValue = ((rxGain & 0xC0) >> 6);
+ return iRetValue;
+ }
+ public int getIflnaGain() {
+ int iRetValue = -1;
+ if (rxGain < RXGAIN_MIN || rxGain > RXGAIN_MAX) {
+ setPwrManagementMode(false);
+ rxGain = RXGAIN_DEFAULT; appendToLog(String.format("!!! Skip getIflnaGain with assumed rxGain = 0x%X", RXGAIN_DEFAULT));
+ } else iRetValue = ((rxGain & 0x38) >> 3);
+ return iRetValue;
+ }
+ public int getAgcGain() {
+ int iRetValue = -1;
+ if (rxGain < RXGAIN_MIN || rxGain > RXGAIN_MAX) {
+ setPwrManagementMode(false);
+ rxGain = RXGAIN_DEFAULT; appendToLog(String.format("!!! Skip getAgcGain with assumed rxGain = 0x%X", RXGAIN_DEFAULT));
+ } else iRetValue = (rxGain & 0x07);
+ return iRetValue;
+ }
+ public int getRxGain() {
+ int iRetValue = -1;
+ if (rxGain < RXGAIN_MIN || rxGain > RXGAIN_MAX) {
+ setPwrManagementMode(false);
+ rxGain = RXGAIN_DEFAULT; appendToLog(String.format("!!! Skip getRxGain with assumed rxGain = 0x%X", RXGAIN_DEFAULT));
+ } else iRetValue = rxGain;
+ return iRetValue;
+ }
+ public boolean setRxGain(int highCompression, int rflnagain, int iflnagain, int agcgain) {
+ int rxGain_new = ((highCompression & 0x01) << 8) | ((rflnagain & 0x3) << 6) | ((iflnagain & 0x7) << 3) | (agcgain & 0x7);
+ return setRxGain(rxGain_new);
+ }
+ public boolean setRxGain(int rxGain_new) {
+ boolean bRetValue = true;
+ if ((rxGain_new != rxGain) || (sameCheck == false)) {
+ setPwrManagementMode(false);
+ rxGain = rxGain_new; appendToLog(String.format("!!! Skip setRxGain[0x%X]", rxGain_new));
+ }
+ return bRetValue;
+ }
+
+ public boolean sendHostRegRequestHST_CMD(RfidReaderChipData.HostCommands hostCommand) {
+ appendToLog("!!! hostCommand = " + hostCommand.toString());
+ long hostCommandData = -1;
+ switch (hostCommand) {
+ case CMD_18K6CINV:
+ hostCommandData = 0xA1;
+ if (rx000Setting.getQuerySelect() > 1 /*&& mRfidReaderChip.mRx000Setting.getImpinjExtension() == 0*/) hostCommandData = 0xA3;
+ break;
+ case CMD_18K6CINV_COMPACT:
+ hostCommandData = 0xA2;
+ if (rx000Setting.getQuerySelect() > 1 /*&& mRfidReaderChip.mRx000Setting.getImpinjExtension() == 0*/) hostCommandData = 0xA6;
+ break;
+ case CMD_18K6CINV_MB:
+ hostCommandData = 0xA4;
+ appendToLog("getQuerySelect = " + rx000Setting.getQuerySelect() + ", getImpinjExtension = " + rx000Setting.getImpinjExtension());
+ if (rx000Setting.getQuerySelect() > 1 /*&& mRfidReaderChip.mRx000Setting.getImpinjExtension() == 0*/) hostCommandData = 0xA5;
+ break;
+ case NULL:
+ hostCommandData = 0xAE;
+ break;
+ case CMD_18K6CREAD:
+ hostCommandData = 0xB1;
+ break;
+ case CMD_18K6CWRITE:
+ hostCommandData = 0xB2;
+ break;
+ case CMD_18K6CLOCK:
+ hostCommandData = 0xB7;
+ break;
+ case CMD_18K6CKILL:
+ hostCommandData = 0xB8;
+ break;
+ case CMD_18K6CAUTHENTICATE:
+ hostCommandData = 0xB9;
+ break;
+
+ case CMD_WROEM:
+ hostCommandData = 0x02;
+ break;
+ case CMD_RDOEM:
+ hostCommandData = 0x03;
+ break;
+ case CMD_ENGTEST:
+ hostCommandData = 0x04;
+ break;
+ case CMD_MBPRDREG:
+ hostCommandData = 0x05;
+ break;
+ case CMD_MBPWRREG:
+ hostCommandData = 0x06;
+ break;
+ case CMD_SETPWRMGMTCFG:
+ hostCommandData = 0x14;
+ break;
+ case CMD_UPDATELINKPROFILE:
+ hostCommandData = 0x19;
+ break;
+ case CMD_18K6CBLOCKWRITE:
+ hostCommandData = 0x1F;
+ break;
+ case CMD_CHANGEEAS:
+ hostCommandData = 0x26;
+ break;
+ case CMD_GETSENSORDATA:
+ hostCommandData = 0x3b;
+ break;
+ case CMD_READBUFFER:
+ hostCommandData = 0x51;
+ break;
+ case CMD_UNTRACEABLE:
+ hostCommandData = 0x52;
+ break;
+ case CMD_FDM_RDMEM:
+ hostCommandData = 0x53; break;
+ case CMD_FDM_WRMEM:
+ hostCommandData = 0x54; break;
+ case CMD_FDM_AUTH:
+ hostCommandData = 0x55; break;
+ case CMD_FDM_GET_TEMPERATURE:
+ hostCommandData = 0x56; break;
+ case CMD_FDM_START_LOGGING:
+ hostCommandData = 0x57; break;
+ case CMD_FDM_STOP_LOGGING:
+ hostCommandData = 0x58; break;
+ case CMD_FDM_WRREG:
+ hostCommandData = 0x59; break;
+ case CMD_FDM_RDREG:
+ hostCommandData = 0x5A; break;
+ case CMD_FDM_DEEP_SLEEP:
+ hostCommandData = 0x5B; break;
+ case CMD_FDM_OPMODE_CHECK:
+ hostCommandData = 0x5C; break;
+ case CMD_FDM_INIT_REGFILE:
+ hostCommandData = 0x5d; break;
+ case CMD_FDM_LED_CTRL:
+ hostCommandData = 0x5e; break;
+ default:
+ appendToLog("!!! CANNOT handle with hostCommand = " + hostCommand.toString());
+ }
+ if (hostCommandData == -1) {
+ return false;
+ } else {
+ commandOperating = true;
+ byte[] msgBuffer = new byte[]{(byte)0x80, (byte)0xb3, (byte)0x10, (byte)0xA1, 0, 0, 0};
+ msgBuffer[3] = (byte) (hostCommandData % 256);
+ if (true) appendToLog("3030 data = " + byteArrayToString(rx000Setting.antennaPortConfig[0]));
+ return sendHostRegRequest(HostRegRequests.HST_CMD, true, msgBuffer);
+ }
+ }
+
+ ArrayList macAccessHistory = new ArrayList<>();
+ void addMacAccessHistory(byte[] msgBuffer) {
+ byte[] msgBuffer4 = Arrays.copyOf(msgBuffer, 4);
+ for (int i = 0; i < macAccessHistory.size(); i++) {
+ byte[] macAccessHistory4 = Arrays.copyOf(macAccessHistory.get(i), 4);
+ if (Arrays.equals(msgBuffer4, macAccessHistory4)) {
+ appendToLog("macAccessHistory: deleted old record=" + byteArrayToString(macAccessHistory4));
+ macAccessHistory.remove(i);
+ break;
+ }
+ }
+ appendToLog("macAccessHistory: added msgbuffer=" + byteArrayToString(msgBuffer));
+ macAccessHistory.add(msgBuffer);
+ }
+
+ byte downlinkSequenceNumber = 0;
+ boolean sendHostRegRequest(HostRegRequests hostRegRequests, boolean writeOperation, byte[] msgBuffer) {
+ boolean needResponse = false;
+ boolean validRequest = false;
+
+ if (hostRegRequests == HostRegRequests.HST_ANT_DESC_DWELL) appendToLog("setAntennaDwell 4");
+ boolean bSkip = false;
+ if ( (hostRegRequests != HostRegRequests.HST_CMD && hostRegRequests != HostRegRequests.MAC_OPERATION)
+ || (hostRegRequests == HostRegRequests.HST_CMD
+ && msgBuffer[3] != (byte)0xA1
+ && msgBuffer[3] != (byte)0xA2
+ && msgBuffer[3] != (byte)0xA3
+ && msgBuffer[3] != (byte)0xA4
+ && msgBuffer[3] != (byte)0xA5
+ && msgBuffer[3] != (byte)0xA6
+ && msgBuffer[3] != (byte)0xAE
+ && msgBuffer[3] != (byte)0xB1
+ && msgBuffer[3] != (byte)0xB2
+ && msgBuffer[3] != (byte)0xB7
+ && msgBuffer[3] != (byte)0xB8
+ && msgBuffer[3] != (byte)0xB9
+ ) || (hostRegRequests == HostRegRequests.MAC_OPERATION && writeOperation && msgBuffer[0] != (byte)0x80)
+ ) bSkip = true;
+ if (bSkip) {
+ appendToLog("!!! Skip sendingRegRequest with " + hostRegRequests.toString() + ", writeOperation = " + writeOperation + "." + byteArrayToString(msgBuffer));
+ return true;
+ }
+ if (csReaderConnector.isConnected() == false) {
+ appendToLog("!!! Skip sending as bleConnected is false");
+ return false;
+ }
+ if (false) addMacAccessHistory(msgBuffer);
+ switch (hostRegRequests) {
+ case MAC_OPERATION:
+ case HST_ANT_CYCLES:
+ case HST_ANT_DESC_SEL:
+ case HST_ANT_DESC_CFG:
+ case MAC_ANT_DESC_STAT:
+ case HST_ANT_DESC_PORTDEF:
+ case HST_ANT_DESC_DWELL:
+ case HST_ANT_DESC_RFPOWER:
+ case HST_ANT_DESC_INV_CNT:
+ validRequest = true;
+ break;
+ case HST_TAGMSK_DESC_SEL:
+ case HST_TAGMSK_DESC_CFG:
+ case HST_TAGMSK_BANK:
+ case HST_TAGMSK_PTR:
+ case HST_TAGMSK_LEN:
+ case HST_TAGMSK_0_3:
+ validRequest = true;
+ break;
+ case HST_QUERY_CFG:
+ case HST_INV_CFG:
+ case HST_INV_SEL:
+ case HST_INV_ALG_PARM_0:
+ case HST_INV_ALG_PARM_1:
+ case HST_INV_ALG_PARM_2:
+ case HST_INV_ALG_PARM_3:
+ case HST_INV_RSSI_FILTERING_CONFIG:
+ case HST_INV_RSSI_FILTERING_THRESHOLD:
+ case HST_INV_RSSI_FILTERING_COUNT:
+ case HST_INV_EPC_MATCH_CFG:
+ case HST_INV_EPCDAT_0_3:
+ validRequest = true;
+ break;
+ case HST_TAGACC_DESC_CFG:
+ case HST_TAGACC_BANK:
+ case HST_TAGACC_PTR:
+ case HST_TAGACC_CNT:
+ case HST_TAGACC_LOCKCFG:
+ case HST_TAGACC_ACCPWD:
+ case HST_TAGACC_KILLPWD:
+ case HST_TAGWRDAT_SEL:
+ case HST_TAGWRDAT_0:
+ validRequest = true;
+ break;
+ case HST_RFTC_CURRENT_PROFILE:
+ case HST_RFTC_FRQCH_SEL:
+ case HST_RFTC_FRQCH_CFG:
+ case HST_RFTC_FRQCH_DESC_PLLDIVMULT:
+ case HST_RFTC_FRQCH_DESC_PLLDACCTL:
+ case HST_RFTC_FRQCH_CMDSTART:
+ validRequest = true;
+ break;
+ case HST_AUTHENTICATE_CFG:
+ case HST_AUTHENTICATE_MSG:
+ case HST_READBUFFER_LEN:
+ case HST_UNTRACEABLE_CFG:
+ validRequest = true;
+ break;
+ case HST_CMD:
+ validRequest = true;
+ needResponse = true;
+ break;
+ }
+
+ if (msgBuffer == null || validRequest == false) {
+ appendToLog("invalid request for msgbuffer = " + (msgBuffer == null ? "NULL" : "Valid") + ", validRequst = " + validRequest);
+ return false;
+ } else {
+ RfidConnector.CsReaderRfidData csReaderRfidData = new RfidConnector.CsReaderRfidData();
+ csReaderRfidData.rfidPayloadEvent = RfidConnector.RfidPayloadEvents.RFID_COMMAND;
+ csReaderRfidData.dataValues = msgBuffer;
+ csReaderRfidData.waitUplinkResponse = true; //(needResponse || writeOperation == false);
+ if (msgBuffer[0] == (byte)0x80
+ && msgBuffer[1] == (byte)0xB3
+ ) {
+ csReaderRfidData.dataValues[4] = downlinkSequenceNumber++;
+ if (msgBuffer[2] == 0x10
+ && msgBuffer[3] != (byte)0xA1
+ && msgBuffer[3] != (byte)0xA2
+ && msgBuffer[3] != (byte)0xA3
+ && msgBuffer[3] != (byte)0xA4
+ && msgBuffer[3] != (byte)0xA5
+ && msgBuffer[3] != (byte)0xA6
+ && msgBuffer[3] != (byte)0xB1
+ && msgBuffer[3] != (byte)0xB2
+ && msgBuffer[3] != (byte)0xB7
+ && msgBuffer[3] != (byte)0xB8
+ && msgBuffer[3] != (byte)0xB9
+ ) csReaderRfidData.waitUplink1Response = true;
+ }
+ addRfidToWrite(csReaderRfidData);
+ return true;
+ }
+ }
+
+ void addRfidToWrite(RfidConnector.CsReaderRfidData csReaderRfidData) {
+ boolean repeatRequest = false, DEBUG = false;
+ if (false && csReaderRfidData.rfidPayloadEvent == RfidConnector.RfidPayloadEvents.RFID_COMMAND) {
+ appendToLog("!!! Skip " + csReaderRfidData.rfidPayloadEvent.toString() + "." + byteArrayToString(csReaderRfidData.dataValues));
+ return;
+ }
+ if (DEBUG) appendToLog("0 with mRfidToWrite.size() = " + csReaderConnector.rfidConnector.mRfidToWrite.size());
+ if (csReaderConnector.rfidConnector.mRfidToWrite.size() != 0 && sameCheck) {
+ for (int i = 1; i < csReaderConnector.rfidConnector.mRfidToWrite.size(); i++) {
+ RfidConnector.CsReaderRfidData csReaderRfidData1 = csReaderConnector.rfidConnector.mRfidToWrite.get(i);
+ //appendToLog("BtDataOut " + i + " : 1 with rfidPayloadEvent0,1 = " + csReaderRfidData.rfidPayloadEvent.toString() + ", " + csReaderRfidData1.rfidPayloadEvent.toString());
+ if (csReaderRfidData.rfidPayloadEvent == csReaderRfidData1.rfidPayloadEvent) {
+ //appendToLog("BtDataOut " + i + " : 2 with dataValues = " + byteArrayToString(csReaderRfidData.dataValues));
+ //appendToLog("BtDataOut " + i + " : 2A with dataValues1 = " + byteArrayToString(csReaderRfidData1.dataValues));
+ if (csReaderRfidData.dataValues == null && csReaderRfidData1.dataValues == null) {
+ repeatRequest = true;
+ } else if (csReaderRfidData.dataValues != null && csReaderRfidData1.dataValues != null) {
+ if (csReaderRfidData.dataValues.length == csReaderRfidData1.dataValues.length) {
+ if (compareArray(csReaderRfidData.dataValues, csReaderRfidData1.dataValues, csReaderRfidData.dataValues.length)) {
+ repeatRequest = true;
+ } else if (csReaderRfidData.dataValues.length >= 8) {
+ int iCommand = (csReaderRfidData.dataValues[2] & 0xFF) * 256 + (csReaderRfidData.dataValues[3] & 0xFF);
+ int iVariableCount = csReaderRfidData.dataValues[7] & 0xFF;
+ int iLengthIndex = 10;
+ if (DEBUG) appendToLog("BtDataOut 70: iCommand = " + String.format("0x%04X", iCommand) + ", iVariableCount = " + iVariableCount);
+ if (iCommand == 0x9A06) {
+ int k = 0;
+ for (; k < csReaderRfidData.dataValues.length; k++) {
+ if (k == 4) { //skip
+ } else if ((byte) csReaderRfidData.dataValues[k] != (byte) csReaderRfidData1.dataValues[k]) {
+ if (DEBUG) appendToLog("7 mis-matched at position " + k);
+ break;
+ } else if (k == iLengthIndex) {
+ k += (csReaderRfidData.dataValues[k] & 0xFF);
+ iLengthIndex += 3;
+ if (DEBUG) appendToLog("7A k is updated to " + k);
+ }
+ }
+ if (k == csReaderRfidData.dataValues.length) {
+ if (DEBUG) appendToLog(" " + i + " : 8 with dataValues = " + byteArrayToString(csReaderRfidData.dataValues));
+ if (DEBUG) appendToLog(" " + i + " : 8A with dataValues1 = " + byteArrayToString(csReaderRfidData1.dataValues));
+ if (DEBUG) appendToLog("8 with matched data and remove the previous one");
+ csReaderConnector.rfidConnector.mRfidToWrite.remove(i);
+ break;
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ if (repeatRequest == false) {
+ csReaderConnector.rfidConnector.mRfidToWrite.add(csReaderRfidData);
+ if (DEBUG) appendToLog("BtDataOut: 9 added data with mRfidToWrite.size() = " + csReaderConnector.rfidConnector.mRfidToWrite.size());
+ if (DEBUG_PKDATA) appendToLog("PkData: add " + csReaderRfidData.rfidPayloadEvent + (csReaderRfidData.dataValues != null ? "." : "") + byteArrayToString(csReaderRfidData.dataValues)
+ + (csReaderRfidData.waitUplinkResponse ? " waitUplinkResponse" : "") + (csReaderRfidData.waitUplink1Response ? " waitUplink1Response" : "")
+ + " to mRfidToWrite with length = " + csReaderConnector.rfidConnector.mRfidToWrite.size());
+ } else if (DEBUG_PKDATA) appendToLog("!!! Skip repeated sending " + csReaderRfidData.rfidPayloadEvent + (csReaderRfidData.dataValues != null ? "." : "") + byteArrayToString(csReaderRfidData.dataValues));
+ }
+
+ byte[] dataValueTemp = null; int dataValueTempIndex = 0;
+ boolean inventoring = false;
+ public boolean isInventoring() { return inventoring; }
+ void setInventoring(boolean enable) { inventoring = enable; utility.debugFileEnable(false); if (true) appendToLog("setInventoring E710 is set as " + inventoring);}
+ boolean decode710Data(byte[] dataValue){
+ boolean DEBUG = false;
+ if (DEBUG) appendToLog("mRfidToWrite.size = " + csReaderConnector.rfidConnector.mRfidToWrite.size());
+ if (csReaderConnector.rfidConnector.mRfidToWrite.size() > 0) {
+ RfidConnector.CsReaderRfidData csReaderRfidData = csReaderConnector.rfidConnector.mRfidToWrite.get(0);
+ if (DEBUG) appendToLog("downlinkResponsed = " + csReaderRfidData.downlinkResponded + ", uplinkResponsed = " + csReaderRfidData.uplinkResponded);
+ if (csReaderRfidData.downlinkResponded || csReaderRfidData.uplinkResponded) {
+ boolean matched = false, updatedUplinkResponse = false;
+ if (DEBUG) appendToLog("mRfidToWrite.dataValue = " + byteArrayToString(csReaderRfidData.dataValues));
+ if (DEBUG) appendToLog("dataValue = " + byteArrayToString(dataValue));
+ if (DEBUG) appendToLog("MatchCheck, commandValueIndex = " + dataValueTempIndex);
+
+ if (dataValue.length < 7) {
+ appendToLog("!!! number of data received is less than 7"); //not debugged
+ return false;
+ }
+ if (dataValueTempIndex != 0) {
+ appendToLog("commandValueTempIndex = " + dataValueTempIndex + ", dataValue.length = " + dataValue.length + ", commandValueTemp.length = " + dataValueTemp.length);
+ if (dataValueTemp.length < dataValueTempIndex + dataValue.length) { //not debugged
+ appendToLog("!!! Data received is greater than expected in dataValueTemp");
+ return false;
+ } else {
+ System.arraycopy(dataValue, 0, dataValueTemp, dataValueTempIndex, dataValue.length);
+ dataValueTempIndex += dataValue.length;
+ if (dataValueTemp.length != dataValueTempIndex) {
+ appendToLog(" Data received is still not sufficient in dataValueTemp");
+ return false;
+ } else {
+ dataValue = dataValueTemp;
+ appendToLog("dataValueTemp is filled up as " + byteArrayToString(dataValue));
+ dataValueTempIndex = 0;
+ }
+ }
+ }
+
+ byte[] payloadValue = null;
+ int iCommandCode = (dataValue[2] & 0xFF) * 256 + (dataValue[3] & 0xFF);
+ int iLength = (dataValue[5] & 0xFF) * 256 + (dataValue[6] & 0xFF);
+ appendToLog("iCommandCode = " + String.format("0x%4X", iCommandCode) + ", iLength = " + iLength + ", LengthPayload = " + (dataValue.length - 7));
+
+ if (iLength < dataValue.length - 7) { //not debugged
+ appendToLog("!!! Data received is greater than expected in dataValue");
+ return false;
+ } else if (iLength != dataValue.length - 7) {
+ dataValueTemp = new byte[iLength + 7];
+ System.arraycopy(dataValue, 0, dataValueTemp, 0, dataValue.length);
+ dataValueTempIndex = dataValue.length;
+ appendToLog("stored dataValueTemp as " + byteArrayToString(dataValueTemp)); //not debugged
+ return false;
+ }
+
+ payloadValue = new byte[iLength];
+ appendToLog("Matched 2 with dataValue.length = " + dataValue.length + ", payloadValue.length = " + payloadValue.length);
+ System.arraycopy(dataValue, 7, payloadValue, 0, dataValue.length - 7);
+
+ if (csReaderRfidData.dataValues[0] == (byte)0x80
+ && csReaderRfidData.dataValues[1] == (byte)0xB3
+ && dataValue[0] == 0x51
+ && dataValue[1] == (byte)0xE2
+ && csReaderRfidData.dataValues[2] == dataValue[2]
+ && csReaderRfidData.dataValues[3] == dataValue[3]
+ && csReaderRfidData.dataValues[4] == dataValue[4]
+ ) {
+ appendToLog("Matched 0x51E2 with 0x80B3");
+ boolean valid = false;
+ if (DEBUG_PKDATA || true) appendToLog("PkData: found Rfid.Uplink.DataRead.CommandResponse" + (iLength != 0 ? " with payload = " + byteArrayToString(payloadValue) : ""));
+ if (DEBUG || true) appendToLog("found iCommandCode = " + String.format("0x%4X", iCommandCode) + ", iLength = " + iLength + ", payloadValue = " + byteArrayToString(payloadValue));
+ if ((iCommandCode == 0x10A1 && iLength == 0)
+ || (iCommandCode == 0x10A2 && iLength == 0)
+ || (iCommandCode == 0x10A3 && iLength == 0)
+ || (iCommandCode == 0x10A4 && iLength == 0)
+ || (iCommandCode == 0x10A5 && iLength == 0)
+ || (iCommandCode == 0x10A6 && iLength == 0)
+ || (iCommandCode == 0x10AE && iLength == 0)
+ || (iCommandCode == 0x10B1 && iLength == 0)
+ || (iCommandCode == 0x10B2 && iLength == 0)
+ || (iCommandCode == 0x10B7 && iLength == 0)
+ || (iCommandCode == 0x10B8 && iLength == 0)
+ || (iCommandCode == 0x10B9 && iLength == 0)
+ || (iCommandCode == 0x1471)
+ || (iCommandCode == 0x9A06)
+ ) valid = true;
+ String strCommandResponseType = null;
+ if (iCommandCode == 0x10A1) strCommandResponseType = "RfidStartSimpleInventory";
+ else if (iCommandCode == 0x10A2) strCommandResponseType = "RfidStartCompactInventory";
+ else if (iCommandCode == 0x10A3) strCommandResponseType = "RfidStartSelectInventory";
+ else if (iCommandCode == 0x10A4) strCommandResponseType = "RfidStartMBInventory";
+ else if (iCommandCode == 0x10A5) strCommandResponseType = "RfidStartSelectMBInventory";
+ else if (iCommandCode == 0x10A6) strCommandResponseType = "RfidStartSelectCompactInventory";
+ else if (iCommandCode == 0x10AE) strCommandResponseType = "RfidStopOperation";
+ else if (iCommandCode == 0x10B1) strCommandResponseType = "RfidReadMB";
+ else if (iCommandCode == 0x10B2) strCommandResponseType = "RfidWriteMB";
+ else if (iCommandCode == 0x10B7) strCommandResponseType = "RfidLock";
+ else if (iCommandCode == 0x10B8) strCommandResponseType = "RfidKill";
+ else if (iCommandCode == 0x10B9) strCommandResponseType = "RfidAuthenticate";
+ if (valid) {
+ appendToLog("waitUplink1Response is " + csReaderRfidData.waitUplink1Response);
+ if (csReaderRfidData.waitUplink1Response) {
+ csReaderConnector.rfidConnector.found = true;
+ csReaderRfidData.uplinkResponded = true; updatedUplinkResponse = true;
+ csReaderConnector.rfidConnector.mRfidToWrite.set(0, csReaderRfidData);
+ if (DEBUG_PKDATA) appendToLog("PkData: Rfid.Uplink.DataRead.CommandResponse_" + strCommandResponseType + " is processed to set mRfidToWrite.uplinkResponded and wait uplink data 1");
+ } else {
+ matched = true;
+ if (iCommandCode == 0x10A1) { if (DEBUG_PKDATA) appendToLog("PkData: uplink data is processed as CommandResponse.RfidStartSimpleInventory"); }
+ else if (iCommandCode == 0x10A2) { setInventoring(true); if (DEBUG_PKDATA) appendToLog("PkData: uplink data is processed as CommandResponse.RfidStartCompactInventory"); }
+ else if (iCommandCode == 0x10A3) { setInventoring(true); if (DEBUG_PKDATA) appendToLog("PkData: uplink data is processed as CommandResponse.RfidStartSelectInventory"); }
+ else if (iCommandCode == 0x10A4) { setInventoring(true); if (DEBUG_PKDATA) appendToLog("PkData: uplink data is processed as CommandResponse.RfidStartMBInventory"); }
+ else if (iCommandCode == 0x10A5) { setInventoring(true); if (DEBUG_PKDATA) appendToLog("PkData: uplink data is processed as CommandResponse.RfidStartSelectMBInventory"); }
+ else if (iCommandCode == 0x10A6) { setInventoring(true); if (DEBUG_PKDATA) appendToLog("PkData: uplink data is processed as CommandResponse.RfidStartSelectCompactInventory"); }
+ else if (iCommandCode == 0x10AE) { if (DEBUG_PKDATA) appendToLog("PkData: uplink data is processed as CommandResponse.RfidStopOperation"); }
+ else if (iCommandCode == 0x10B1) { if (DEBUG_PKDATA) appendToLog("PkData: uplink data is processed as CommandResponse.RfidReadMB"); }
+ else if (iCommandCode == 0x10B2) { if (DEBUG_PKDATA) appendToLog("PkData: uplink data is processed as CommandResponse.RfidWriteMB"); }
+ else if (iCommandCode == 0x10B7) { if (DEBUG_PKDATA) appendToLog("PkData: uplink data is processed as CommandResponse.RfidLock"); }
+ else if (iCommandCode == 0x10B8) { if (DEBUG_PKDATA) appendToLog("PkData: uplink data is processed as CommandResponse.RfidKill"); }
+ else if (iCommandCode == 0x10B9) { if (DEBUG_PKDATA) appendToLog("PkData: uplink data is processed as CommandResponse.RfidAuthenticate"); }
+ //else if ((iCommandCode & 0x7F00) == 0x1000) { if (DEBUG_PKDATA) appendToLog("PkData: uplink data is processed as CommandResponse.RFID??? !!!"); }
+ else if (iCommandCode == 0x1471 || iCommandCode == 0x9A06) {
+ int iRegAddr = (csReaderRfidData.dataValues[8] & 0xFF) * 256 + (csReaderRfidData.dataValues[9] & 0xFF);
+ boolean bprocessed = false;
+ if (DEBUG) appendToLog(String.format("1 iCommandCode = 0x%X with iRegAddr = 0x%X", iCommandCode, iRegAddr));
+ if (iCommandCode == 0x9A06) {
+ if (DEBUG) appendToLog(String.format("2 CommandCode = 0x%X is processed here", iCommandCode));
+ bprocessed = true;
+ } else { //not debugged
+ int iNumberExpected = csReaderRfidData.dataValues[7];
+ int iLengthExpected = 0;
+ for (int i = 0; i < iNumberExpected; i++) {
+ iLengthExpected += csReaderRfidData.dataValues[10 + i * 3];
+ }
+ appendToLog("ReaderChipE710.decode710Data, iNumberExpected = " + iNumberExpected + ", iLengthExpected = " + iLengthExpected);
+ if (iLengthExpected == iLength) {
+ appendToLog("Matched iLengthExpected");
+ byte[] commandValue0 = new byte[payloadValue.length]; int indexCommandValue0 = 0;
+ System.arraycopy(payloadValue, 0, commandValue0, 0, commandValue0.length);
+ for (int k = 0; k < iNumberExpected; k++) {
+ iRegAddr = (csReaderRfidData.dataValues[8 + k * 3] & 0xFF) * 256 + (csReaderRfidData.dataValues[9 + k * 3] & 0xFF);
+ payloadValue = new byte[csReaderRfidData.dataValues[10 + k * 3]];
+ System.arraycopy(commandValue0, indexCommandValue0, payloadValue, 0, payloadValue.length); indexCommandValue0 += payloadValue.length;
+ if (DEBUG) appendToLog("k = " + k + ", " + String.format("2 iRegAddr = 0x%X", iRegAddr) + ", data = " + byteArrayToString(payloadValue));
+ if (iRegAddr == 8) {
+ if (DEBUG) appendToLog("2 iCommandCode");
+ try {
+ rx000Setting.macVer = new String(payloadValue, StandardCharsets.UTF_8).trim();
+ bprocessed = true;
+ if (false)
+ appendToLog("macVer = " + rx000Setting.macVer);
+ } catch (Exception e) {
+ //throw new RuntimeException(e);
+ }
+ } else if (iRegAddr == 0x28 && payloadValue.length >= 3) {
+ int iValue = 0;
+ for (int i = 0, increment = 1; i < payloadValue.length; i++, increment *= 10) {
+ iValue = payloadValue[payloadValue.length - 1 - i] * increment;
+ }
+ rx000Setting.macVerBuild = iValue;
+ bprocessed = true;
+ if (true)
+ appendToLog("macVerBuild = " + rx000Setting.macVerBuild);
+ } else if (iRegAddr == 0x3014) {
+ rx000Setting.countryEnum = payloadValue;
+ bprocessed = true;
+ if (true)
+ appendToLog("countryEnum = " + byteArrayToString(rx000Setting.countryEnum));
+ } else if (iRegAddr == 0x3018) {
+ rx000Setting.frequencyChannelIndex = payloadValue;
+ bprocessed = true;
+ if (true)
+ appendToLog("frequencyChannelIndex = " + byteArrayToString(rx000Setting.frequencyChannelIndex));
+ } else if (iRegAddr >= 0x3030 && iRegAddr < 0x3030 + 16 * 16) {
+ int iPort = 0, iOffset = 0, iWidth = 0;
+ for (iPort = 0; iPort < 16; iPort++) {
+ if (DEBUG)
+ appendToLog("antennaPortConfig: iPort = " + iPort + String.format(", iRegAddr = 0x%04X", iRegAddr));
+ if (iRegAddr < 0x3030 + (iPort + 1) * 16) break;
+ }
+ iOffset = iRegAddr - 0x3030 - iPort * 16;
+ if (DEBUG)
+ appendToLog("antennaPortConfig: iOffset = " + iOffset);
+ iWidth = payloadValue.length;
+ if (DEBUG)
+ appendToLog("antennaPortConfig: iWidth = " + iWidth);
+ if (iOffset == 0 && iWidth == 16) {
+ rx000Setting.antennaPortConfig[iPort] = payloadValue;
+ bprocessed = true;
+ if (false)
+ appendToLog("antennaPortConfig[" + iPort + "] = " + byteArrayToString(rx000Setting.antennaPortConfig[iPort]));
+ } else
+ appendToLog("!!! CANNOT handle with iPort = " + iPort + ", iOffset = " + iOffset + ", iWidth = " + iWidth);
+ } else if (iRegAddr >= 0x3140 && iRegAddr < 0x3140 + 42 * 7) {
+ int index = 0, iOffset = 0, iWidth = 0;
+ for (index = 0; index < 7; index++) {
+ if (DEBUG)
+ appendToLog("selectConfiguration: index = " + index + String.format(", iRegAddr = 0x%04X", iRegAddr));
+ if (iRegAddr < 0x3140 + (index + 1) * 42) break;
+ }
+ iOffset = iRegAddr - 0x3140 - index * 42;
+ if (DEBUG)
+ appendToLog("selectConfiguration: iOffset = " + iOffset);
+ iWidth = payloadValue.length;
+ if (DEBUG)
+ appendToLog("selectConfiguration: iWidth = " + iWidth);
+ if (iOffset == 0 && iWidth == 42) {
+ rx000Setting.selectConfiguration[index] = payloadValue;
+ bprocessed = true;
+ if (false)
+ appendToLog("selectConfiguration[" + index + "] = " + byteArrayToString(rx000Setting.selectConfiguration[index]));
+ } else
+ appendToLog("!!! CANNOT handle with index = " + index + ", iOffset = " + iOffset + ", iWidth = " + iWidth);
+ } else if (iRegAddr >= 0x3270 && iRegAddr < 0x3270 + 7 * 3) {
+ int index = 0, iOffset = 0, iWidth = 0, iPortStartAddr = 0x3270, iPortSize = 7;
+ for (index = 0; index < 3; index++) {
+ if (DEBUG)
+ appendToLog("multibankReadConfig: index = " + index + String.format(", iRegAddr = 0x%04X", iRegAddr));
+ if (iRegAddr < iPortStartAddr + (index + 1) * iPortSize) break;
+ }
+ iOffset = iRegAddr - iPortStartAddr - index * iPortSize;
+ if (DEBUG)
+ appendToLog("multibankReadConfig: iOffset = " + iOffset);
+ iWidth = payloadValue.length;
+ if (DEBUG)
+ appendToLog("multibankReadConfig: iWidth = " + iWidth);
+ if (iOffset == 0 && iWidth == iPortSize) {
+ rx000Setting.multibankReadConfig[index] = payloadValue;
+ bprocessed = true;
+ if (false)
+ appendToLog("multibankReadConfig[" + index + "] = " + byteArrayToString(rx000Setting.multibankReadConfig[index]));
+ } else
+ appendToLog("!!! CANNOT handle with index = " + index + ", iOffset = " + iOffset + ", iWidth = " + iWidth);
+ } else if (iRegAddr == 0x38A6) {
+ rx000Setting.accessPassword = payloadValue;
+ bprocessed = true;
+ if (false) appendToLog("accessPassword = " + byteArrayToString(rx000Setting.accessPassword));
+ } else if (iRegAddr == 0x38AA) {
+ rx000Setting.killPassword = payloadValue;
+ bprocessed = true;
+ if (false) appendToLog("killPassword = " + byteArrayToString(rx000Setting.killPassword));
+ } else if (iRegAddr == 0x3900) {
+ rx000Setting.dupElimRollWindow = payloadValue;
+ bprocessed = true;
+ if (false) appendToLog("dupElimDelay = " + byteArrayToString(rx000Setting.dupElimRollWindow));
+ } else if (iRegAddr == 0x3906) {
+ rx000Setting.eventPacketUplnkEnable = payloadValue;
+ bprocessed = true;
+ if (false) appendToLog("eventPacketUplnkEnable = " + byteArrayToString(rx000Setting.eventPacketUplnkEnable));
+ } else if (iRegAddr == 0x3908) {
+ rx000Setting.intraPacketDelay = payloadValue;
+ bprocessed = true;
+ if (false) appendToLog("intraPacketDelay = " + byteArrayToString(rx000Setting.intraPacketDelay));
+ } else if (iRegAddr == 0x3948) {
+ rx000Setting.currentPort = payloadValue;
+ bprocessed = true;
+ if (true) appendToLog("currentPort = " + byteArrayToString(rx000Setting.currentPort));
+ } else if (iRegAddr == 0x5000) {
+ rx000Setting.modelCode = payloadValue;
+ bprocessed = true;
+ if (false)
+ appendToLog("modelCode = " + byteArrayToString(rx000Setting.modelCode));
+ } else if (iRegAddr == 0x5020) {
+ rx000Setting.productSerialNumber = payloadValue;
+ bprocessed = true;
+ if (false)
+ appendToLog("productSerialNumber = " + byteArrayToString(rx000Setting.productSerialNumber));
+ } else if (iRegAddr == 0x5040) {
+ rx000Setting.countryEnumOem = payloadValue;
+ bprocessed = true;
+ if (true)
+ appendToLog("countryEnumOem = " + byteArrayToString(rx000Setting.countryEnumOem));
+ } else if (iRegAddr == 0xEF98) {
+ rx000Setting.countryCodeOem = payloadValue;
+ bprocessed = true;
+ if (false)
+ appendToLog("countryCodeOem = " + byteArrayToString(rx000Setting.countryCodeOem));
+ } else if (iRegAddr == 0xEF9C) {
+ rx000Setting.boardSerialNumber = payloadValue;
+ bprocessed = true;
+ if (true)
+ appendToLog("boardSerialNumber = " + byteArrayToString(rx000Setting.boardSerialNumber));
+ } else if (iRegAddr == 0xEFAC) {
+ rx000Setting.specialcountryCodeOem = payloadValue;
+ bprocessed = true;
+ if (false)
+ appendToLog("specialcountryCodeOem = " + byteArrayToString(rx000Setting.specialcountryCodeOem));
+ } else if (iRegAddr == 0xEFB0) {
+ rx000Setting.freqModifyCode = payloadValue;
+ bprocessed = true;
+ if (false)
+ appendToLog("freqModifyCode = " + byteArrayToString(rx000Setting.freqModifyCode));
+ }
+ }
+ }
+ }
+
+ if (bprocessed) {
+ if (DEBUG_PKDATA) {
+ if (iCommandCode == 0x9A06)
+ appendToLog("PkData: Rfid.Uplink.DataRead.CommandResponse_WriteRegister with result " + byteArrayToString(payloadValue) + " is processed for register address = " + String.format("0x%X", iRegAddr));
+ else if (iCommandCode == 0x1471)
+ appendToLog("PkData: Rfid.Uplink.DataRead.CommandResponse_ReadRegister with result " + byteArrayToString(payloadValue) + " is processed for register address = " + String.format("0x%X", iRegAddr));
+ else { //not debugged
+ appendToLog("PkData: Rfid.Uplink.DataRead.CommandResponse_xxx with result " + byteArrayToString(payloadValue) + " is processed");
+ }
+ }
+ } else {//not debugged
+ appendToLog("!!! Rfid.Uplink.DataRead.CommandResponse_ReadRegister CANNOT be processed for register address = " + String.format("0x%X", iRegAddr));
+ }
+ } else { //not debuggged
+ appendToLog(String.format("!!! Rfid.Uplink.DataRead.CommandResponse_%X CANNOT be processed", iCommandCode));
+ }
+ }
+ } else appendToLog("!!! Rfid.Uplink.DataRead.CommandResponse CANNOT be processed"); //not debugged
+ } else if (csReaderRfidData.dataValues[0] == (byte)0x80
+ && csReaderRfidData.dataValues[1] == (byte)0xB3
+ && dataValue[0] == 0x49
+ && dataValue[1] == (byte)0xDC
+ //&& csReaderRfidData.dataValues[4] == dataValue[4] //dataValue[4] == 0
+ ) {
+ if (DEBUG) appendToLog("Ready 0 with iCommandCode = " + String.format("0x%04X", iCommandCode));
+ if (true || dataValue.length == 7 + iLength) {
+ byte[] dataValues1 = new byte[iLength];
+ System.arraycopy(dataValue, 7, dataValues1, 0, dataValues1.length);
+ if (iCommandCode == 0x3008) {
+ setInventoring(false);
+ appendToLogView("isRfidToRead_3008: " + byteArrayToString(dataValue));
+ if (DEBUG) appendToLog("Ready 2");
+ if (DEBUG_PKDATA)
+ appendToLog("PkData: found Rfid.Uplink.DataRead.UplinkPackage_Event_csl_operation_complete with payload = " + byteArrayToString(dataValues1));
+ if (csReaderRfidData.dataValues[2] == dataValues1[4]
+ && csReaderRfidData.dataValues[3] == dataValues1[5]) {
+ if (DEBUG) appendToLog("Ready 3");
+
+ int iStatus = dataValues1[6] * 256 + dataValues1[7];
+ if (csReaderRfidData.uplinkResponded) {
+ matched = true;
+ if (DEBUG_PKDATA)
+ appendToLog("PkData: Rfid.Uplink.DataRead.UplinkPackage_Event_csl_operation_complete is processed with status = " + String.format("%04X", iStatus));
+ }
+ } else appendToLog("!!! mismatched command code"); //not debugged
+ }
+ }
+ } //not debugged
+
+ appendToLog("Ending matched = " + matched + ", updatedUplinkResponse = " + updatedUplinkResponse);
+ if (matched) {
+ csReaderConnector.rfidConnector.found = true;
+ csReaderConnector.rfidConnector.mRfidToWrite.remove(0); csReaderConnector.rfidConnector.sendRfidToWriteSent = 0; csReaderConnector.rfidConnector.mRfidToWriteRemoved = true;
+ if (DEBUG_PKDATA) appendToLog("PkData: new mRfidToWrite size = " + csReaderConnector.rfidConnector.mRfidToWrite.size());
+ appendToLog("RfidReaderChipE710.decode710Data, UsbData: remove one");
+ }
+ if (matched || updatedUplinkResponse) return true;
+ }
+ }
+ return false;
+ }
+}
+
+
+
+package com.csl.cslibrary4a;
+
+import static java.lang.Math.log10;
+import static java.lang.Math.pow;
+
+import android.content.Context;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Date;
+
+public class RfidReaderChipR2000 {
+ boolean DEBUG_PKDATA, DEBUG;
+ boolean sameCheck = true;
+ //RfidReaderChip mRfidReaderChip;
+ boolean DEBUGTHREAD = false;
+ int intervalRx000UplinkHandler;
+ public int invalidUpdata; //invalidata, invalidUpdata, validata;
+ boolean aborting = false;
+ Context context; Utility utility; CsReaderConnector csReaderConnector;
+ public RfidReaderChipR2000(Context context, Utility utility, CsReaderConnector csReaderConnector) {
+ this.context = context;
+ this.utility = utility;
+ appendToLog("csReaderConnector 1 is " + (csReaderConnector == null ? "null" : "valid"));
+ this.csReaderConnector = csReaderConnector;
+ this.DEBUGTHREAD = csReaderConnector.DEBUGTHREAD;
+ this.intervalRx000UplinkHandler = csReaderConnector.intervalRx000UplinkHandler;
+ }
+ private String byteArrayToString(byte[] packet) { return utility.byteArrayToString(packet); }
+ private boolean compareArray(byte[] array1, byte[] array2, int length) { return utility.compareByteArray(array1, array2, length); }
+ private void appendToLog(String s) { utility.appendToLog(s); }
+ private void appendToLogView(String s) { utility.appendToLogView(s); }
+ void writeDebug2File(String stringDebug) { utility.writeDebug2File(stringDebug); }
+ public enum ControlCommands {
+ NULL,
+ CANCEL, SOFTRESET, ABORT, PAUSE, RESUME, GETSERIALNUMBER, RESETTOBOOTLOADER
+ }
+ enum HostRegRequests {
+ MAC_OPERATION,
+ //MAC_VER, MAC_LAST_COMMAND_DURATION,
+ //HST_CMNDIAGS,
+ //HST_MBP_ADDR, HST_MBP_DATA,
+ //HST_OEM_ADDR, HST_OEM_DATA,
+ HST_ANT_CYCLES, HST_ANT_DESC_SEL, HST_ANT_DESC_CFG, MAC_ANT_DESC_STAT, HST_ANT_DESC_PORTDEF, HST_ANT_DESC_DWELL, HST_ANT_DESC_RFPOWER, HST_ANT_DESC_INV_CNT,
+ HST_TAGMSK_DESC_SEL, HST_TAGMSK_DESC_CFG, HST_TAGMSK_BANK, HST_TAGMSK_PTR, HST_TAGMSK_LEN, HST_TAGMSK_0_3,
+ HST_QUERY_CFG, HST_INV_CFG, HST_INV_SEL, HST_INV_ALG_PARM_0, HST_INV_ALG_PARM_1, HST_INV_ALG_PARM_2, HST_INV_ALG_PARM_3, HST_INV_RSSI_FILTERING_CONFIG, HST_INV_RSSI_FILTERING_THRESHOLD, HST_INV_RSSI_FILTERING_COUNT, HST_INV_EPC_MATCH_CFG, HST_INV_EPCDAT_0_3,
+ HST_TAGACC_DESC_CFG, HST_TAGACC_BANK, HST_TAGACC_PTR, HST_TAGACC_CNT, HST_TAGACC_LOCKCFG, HST_TAGACC_ACCPWD, HST_TAGACC_KILLPWD, HST_TAGWRDAT_SEL, HST_TAGWRDAT_0,
+ HST_RFTC_CURRENT_PROFILE,
+ HST_RFTC_FRQCH_SEL, HST_RFTC_FRQCH_CFG, HST_RFTC_FRQCH_DESC_PLLDIVMULT, HST_RFTC_FRQCH_DESC_PLLDACCTL, HST_RFTC_FRQCH_CMDSTART,
+ HST_AUTHENTICATE_CFG, HST_AUTHENTICATE_MSG, HST_READBUFFER_LEN, HST_UNTRACEABLE_CFG,
+ HST_CMD
+ }
+ public class Rx000Setting {
+ Rx000Setting(boolean set_default_setting) {
+ if (set_default_setting) {
+ macVer = mDefault.macVer;
+ //diagnosticCfg = mDefault.diagnosticCfg;
+ oemAddress = mDefault.oemAddress;
+
+ //RFTC block paramters
+ currentProfile = mDefault.currentProfile;
+
+ // Antenna block parameters
+ antennaCycle = mDefault.antennaCycle;
+ antennaFreqAgile = mDefault.antennaFreqAgile;
+ antennaSelect = mDefault.antennaSelect;
+ }
+ antennaSelectedData = new AntennaSelectedData[ANTSELECT_MAX + 1];
+ for (int i = 0; i < antennaSelectedData.length; i++) {
+ int default_setting_type = 0;
+ if (set_default_setting) {
+ if (i == 0) default_setting_type = 1;
+ else if (i >= 1 && i <= 3) default_setting_type = 2;
+ else if (i >= 4 && i <= 7) default_setting_type = 3;
+ else if (i >= 8 && i <= 11) default_setting_type = 4;
+ else default_setting_type = 5;
+ }
+ antennaSelectedData[i] = new AntennaSelectedData(set_default_setting, default_setting_type);
+ }
+
+ //Tag select block parameters
+ if (set_default_setting) invSelectIndex = 0;
+ invSelectData = new InvSelectData[INVSELECT_MAX + 1];
+ for (int i = 0; i < invSelectData.length; i++) {
+ invSelectData[i] = new InvSelectData(set_default_setting);
+ }
+
+ if (set_default_setting) {
+ //Inventtory block paraameters
+ //queryTarget = mDefault.queryTarget;
+ //querySession = mDefault.querySession;
+ //querySelect = mDefault.querySelect;
+ //appendToLog("BtDataOut: RfidReaderChipR2000.Rx000Setting new querySelect = " + querySelect);
+ //invAlgo = mDefault.invAlgo;
+ matchRep = mDefault.matchRep;
+ tagSelect = mDefault.tagSelect;
+ noInventory = mDefault.noInventory;
+ tagDelay = mDefault.tagDelay;
+ invModeCompact = mDefault.tagJoin;
+ invBrandId = mDefault.brandid;
+ invAuthenticate = mDefault.invAuthenticate;
+ }
+
+ if (set_default_setting) algoSelect = 3;
+ algoSelectedData = new AlgoSelectedData[ALGOSELECT_MAX + 1];
+ for (int i = 0; i < algoSelectedData.length; i++) {//0 for invalid default, 1 for 0, 2 for 1, 3 for 2, 4 for 3
+ int default_setting_type = 0;
+ if (set_default_setting) {
+ default_setting_type = i + 1;
+ }
+ algoSelectedData[i] = new AlgoSelectedData(set_default_setting, default_setting_type);
+ }
+
+ if (set_default_setting) {
+ rssiFilterType = mDefault.rssiFilterType;
+ rssiFilterOption = mDefault.rssiFilterOption;
+ rssiFilterThreshold1 = mDefault.rssiFilterThreshold;
+ rssiFilterThreshold2 = mDefault.rssiFilterThreshold;
+ rssiFilterCount = mDefault.rssiFilterCount;
+
+ matchEnable = mDefault.matchEnable;
+ matchType = mDefault.matchType;
+ matchLength = mDefault.matchLength;
+ matchOffset = mDefault.matchOffset;
+ invMatchDataReady = mDefault.invMatchDataReady;
+
+ //Tag access block parameters
+ accessRetry = mDefault.accessRetry;
+ accessBank = mDefault.accessBank; accessBank2 = mDefault.accessBank2;
+ accessOffset = mDefault.accessOffset; accessOffset2 = mDefault.accessOffset2;
+ //accessCount = mDefault.accessCount; accessCount2 = mDefault.accessCount2;
+ accessLockAction = mDefault.accessLockAction;
+ accessLockMask = mDefault.accessLockMask;
+ //long accessPassword = 0;
+ //long killPassword = 0;
+ accessWriteDataSelect = mDefault.accessWriteDataSelect;
+ accWriteDataReady = mDefault.accWriteDataReady;
+
+ authMatchDataReady = mDefault.authMatchDataReady;
+ }
+
+ invMatchData0_63 = new byte[4 * 16];
+ accWriteData0_63 = new byte[4 * 16 * 2];
+ authMatchData0_63 = new byte[4 * 4];
+ }
+
+ class Rx000Setting_default {
+ String macVer;
+ int diagnosticCfg = 0x210;
+ int mbpAddress = 0; // ?
+ int mbpData = 0; // ?
+ int oemAddress = 4; // ?
+ int oemData = 0; // ?
+
+ //RFTC block paramters
+ int currentProfile = 1;
+ int freqChannelSelect = 0;
+
+ // Antenna block parameters
+ int antennaCycle = 1;
+ int antennaFreqAgile = 0;
+ int antennaSelect = 0;
+
+ //Tag select block parameters
+ int invSelectIndex = 0;
+
+ //Inventtory block paraameters
+ int queryTarget = 0;
+ int querySession = 2;
+ int querySelect = 1;
+ int invAlgo = 3;
+ int matchRep = 0;
+ int tagSelect = 0;
+ int noInventory = 0;
+ int tagRead = 0;
+ int tagDelay = 0;
+ int tagJoin = 0;
+ int brandid = 0;
+ int invAuthenticate = 0;
+ int algoSelect = 3;
+
+ int rssiFilterType = 0;
+ int rssiFilterOption = 0;
+ int rssiFilterThreshold = 0;
+ long rssiFilterCount = 0;
+
+ int matchEnable = 0;
+ int matchType = 0;
+ int matchLength = 0;
+ int matchOffset = 0;
+ byte[] invMatchData0_63; int invMatchDataReady = 0;
+
+ //Tag access block parameters
+ int accessRetry = 3;
+ int accessBank = 1; int accessBank2 = 0;
+ int accessOffset = 2; int accessOffset2 = 0;
+ int accessCount = 1; int accessCount2 = 0;
+ int accessLockAction = 0;
+ int accessLockMask = 0;
+ //long accessPassword = 0;
+ // long killPassword = 0;
+ int accessWriteDataSelect = 0;
+ byte[] accWriteData0_63; int accWriteDataReady = 0;
+
+ byte[] authMatchData; int authMatchDataReady = 0;
+ }
+ Rx000Setting_default mDefault = new Rx000Setting_default();
+
+ public boolean readMAC(int address) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 0, 0, 0, 0, 0, 0};
+ msgBuffer[2] = (byte) (address % 256);
+ msgBuffer[3] = (byte) ((address >> 8) % 256);
+ if (false) appendToLog("readMac buffer = " + byteArrayToString(msgBuffer));
+ return sendHostRegRequest(HostRegRequests.MAC_OPERATION, false, msgBuffer);
+ }
+ public boolean writeMAC(int address, long value) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 0, 0, 0, 0, 0, 0};
+ msgBuffer[2] = (byte) (address % 256);
+ msgBuffer[3] = (byte) ((address >> 8) % 256);
+ msgBuffer[4] = (byte) (value % 256);
+ msgBuffer[5] = (byte) ((value >> 8) % 256);
+ msgBuffer[6] = (byte) ((value >> 16) % 256);
+ msgBuffer[7] = (byte) ((value >> 24) % 256);
+ if (false) appendToLog("writeMac buffer = " + byteArrayToString(msgBuffer));
+ return sendHostRegRequest(HostRegRequests.MAC_OPERATION, true, msgBuffer);
+ }
+
+ String macVer = null; int macVerBuild = 0;
+ public String getMacVer() {
+ if (macVer == null) {
+ readMAC(0);
+ return "";
+ } else {
+ return macVer;
+ }
+ }
+
+ long mac_last_command_duration;
+ long getMacLastCommandDuration(boolean request) {
+ if (request) {
+ if (true) readMAC(9);
+ //byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 9, 0, 0, 0, 0, 0};
+ //mRfidDevice.mRx000Device.sendHostRegRequest(HostRegRequests.MAC_LAST_COMMAND_DURATION, false, msgBuffer);
+ }
+ return mac_last_command_duration;
+ }
+
+ final int DIAGCFG_INVALID = -1; final int DIAGCFG_MIN = 0; final int DIAGCFG_MAX = 0x3FF;
+ int diagnosticCfg = DIAGCFG_INVALID;
+ public int getDiagnosticConfiguration() {
+ if (diagnosticCfg < DIAGCFG_MIN || diagnosticCfg > DIAGCFG_MAX) {
+ if (true) readMAC(0x201);
+ //byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 1, 2, 0, 0, 0, 0};
+ //mRfidDevice.mRx000Device.sendHostRegRequest(HostRegRequests.HST_CMNDIAGS, false, msgBuffer);
+ }
+ return diagnosticCfg;
+ }
+ public boolean setDiagnosticConfiguration(boolean bCommmandActive) {
+ int diagnosticCfgNew = diagnosticCfg;
+ diagnosticCfgNew &= ~0x0200; if (bCommmandActive) diagnosticCfgNew |= 0x200;
+ if (diagnosticCfg == diagnosticCfgNew && sameCheck) return true;
+ diagnosticCfg = diagnosticCfgNew;
+ return writeMAC(0x201, diagnosticCfgNew); //mRfidDevice.mRx000Device.sendHostRegRequest(HostRegRequests.HST_CMNDIAGS, true, msgBuffer);
+ }
+
+ int impinjExtensionValue = -1;
+ public int getImpinjExtension() {
+ if (antennaSelect < ANTSLECT_MIN || antennaSelect > ANTSELECT_MAX) {
+ return ANTSELECT_INVALID;
+ } else {
+ {
+ if (impinjExtensionValue < 0) readMAC(0x203);
+ return impinjExtensionValue;
+ }
+ }
+ }
+ public boolean setImpinjExtension(boolean tagFocus, boolean fastId) {
+ int iValue = (tagFocus ? 0x10 : 0) | (fastId ? 0x20 : 0);
+ if (impinjExtensionValue == iValue && sameCheck) return true;
+ appendToLog("BtDataOut 11: ivalue = " + iValue + ", impinjExtensionValue = " + rx000Setting.impinjExtensionValue);
+ boolean bRetValue = writeMAC(0x203, iValue);
+ if (bRetValue) impinjExtensionValue = iValue;
+ return bRetValue;
+ }
+
+ int pwrMgmtStatus = -1;
+ void getPwrMgmtStatus() {
+ if (false) appendToLog("pwrMgmtStatus: getPwrMgmtStatus ");
+ pwrMgmtStatus = -1; readMAC(0x204);
+ }
+
+ final int MBPADDR_INVALID = -1; final int MBPADDR_MIN = 0; final int MBPADDR_MAX = 0x1FFF;
+ long mbpAddress = MBPADDR_INVALID;
+ boolean setMBPAddress(long mbpAddress) {
+ //byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 0, 4, 0, 0, 0, 0};
+ if (mbpAddress < MBPADDR_MIN || mbpAddress > MBPADDR_MAX) return false;
+ //mbpAddress = mDefault.mbpAddress;
+ if (this.mbpAddress == mbpAddress && sameCheck) return true;
+ //msgBuffer[4] = (byte) (mbpAddress % 256);
+ //msgBuffer[5] = (byte) ((mbpAddress >> 8) % 256);
+ this.mbpAddress = mbpAddress;
+ if (false) appendToLog("Going to writeMAC");
+ return writeMAC(0x400, (int) mbpAddress); //mRfidDevice.mRx000Device.sendHostRegRequest(HostRegRequests.HST_MBP_ADDR, true, msgBuffer);
+ }
+
+ final int MBPDATA_INVALID = -1; final int MBPDATA_MIN = 0; final int MBPDATA_MAX = 0x1FFF;
+ long mbpData = MBPDATA_INVALID;
+ boolean setMBPData(long mbpData) {
+ //byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 1, 4, 0, 0, 0, 0};
+ if (mbpData < MBPADDR_MIN || mbpData > MBPADDR_MAX) return false;
+ //mbpData = mDefault.mbpData;
+ if (this.mbpData == mbpData && sameCheck) return true;
+ //msgBuffer[4] = (byte) (mbpData % 256);
+ //msgBuffer[5] = (byte) ((mbpData >> 8) % 256);
+ this.mbpData = mbpData;
+ return writeMAC(0x401, (int) mbpData); //mRfidDevice.mRx000Device.sendHostRegRequest(HostRegRequests.HST_MBP_DATA, true, msgBuffer);
+ }
+
+ final int OEMADDR_INVALID = -1; final int OEMADDR_MIN = 0; final int OEMADDR_MAX = 0x1FFF;
+ long oemAddress = OEMADDR_INVALID;
+ boolean setOEMAddress(long oemAddress) {
+ //byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 0, 5, 0, 0, 0, 0};
+ if (oemAddress < OEMADDR_MIN || oemAddress > OEMADDR_MAX) return false;
+ //oemAddress = mDefault.oemAddress;
+ if (this.oemAddress == oemAddress && sameCheck) return true;
+ //msgBuffer[4] = (byte) (oemAddress % 256);
+ //msgBuffer[5] = (byte) ((oemAddress >> 8) % 256);
+ this.oemAddress = oemAddress;
+ return writeMAC(0x500, (int) oemAddress); //mRfidDevice.mRx000Device.sendHostRegRequest(HostRegRequests.HST_OEM_ADDR, true, msgBuffer);
+ }
+
+ final int OEMDATA_INVALID = -1; final int OEMDATA_MIN = 0; final int OEMDATA_MAX = 0x1FFF;
+ long oemData = OEMDATA_INVALID;
+ boolean setOEMData(long oemData) {
+ //byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 1, 5, 0, 0, 0, 0};
+ if (oemData < OEMADDR_MIN || oemData > OEMADDR_MAX) return false;
+ //oemData = mDefault.oemData;
+ if (this.oemData == oemData && sameCheck) return true;
+ //msgBuffer[4] = (byte) (oemData % 256);
+ //msgBuffer[5] = (byte) ((oemData >> 8) % 256);
+ this.oemData = oemData;
+ return writeMAC(0x501, (int) oemData); //mRfidDevice.mRx000Device.sendHostRegRequest(HostRegRequests.HST_OEM_DATA, true, msgBuffer);
+ }
+
+ // Antenna block parameters
+ final int ANTCYCLE_INVALID = -1; final int ANTCYCLE_MIN = 0; final int ANTCYCLE_MAX = 0xFFFF;
+ int antennaCycle = ANTCYCLE_INVALID;
+ public int getAntennaCycle() {
+ if (antennaCycle < ANTCYCLE_MIN || antennaCycle > ANTCYCLE_MAX) getHST_ANT_CYCLES();
+ return antennaCycle;
+ }
+ public boolean setAntennaCycle(int antennaCycle) {
+ return setAntennaCycle(antennaCycle, antennaFreqAgile);
+ }
+ boolean setAntennaCycle(int antennaCycle, int antennaFreqAgile) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 0, 7, 0, 0, 0, 0};
+ if (antennaCycle < ANTCYCLE_MIN || antennaCycle > ANTCYCLE_MAX) antennaCycle = mDefault.antennaCycle;
+ if (antennaFreqAgile < FREQAGILE_MIN || antennaFreqAgile > FREQAGILE_MAX) antennaFreqAgile = mDefault.antennaFreqAgile;
+ if (this.antennaCycle == antennaCycle && this.antennaFreqAgile == antennaFreqAgile && sameCheck) return true;
+ msgBuffer[4] = (byte) (antennaCycle % 256);
+ msgBuffer[5] = (byte) ((antennaCycle >> 8) % 256);
+ if (antennaFreqAgile != 0) {
+ msgBuffer[7] |= 0x01;
+ }
+ this.antennaCycle = antennaCycle;
+ this.antennaFreqAgile = antennaFreqAgile;
+ return sendHostRegRequest(HostRegRequests.HST_ANT_CYCLES, true, msgBuffer);
+ }
+
+ final int FREQAGILE_INVALID = -1; final int FREQAGILE_MIN = 0; final int FREQAGILE_MAX = 1;
+ int antennaFreqAgile = FREQAGILE_INVALID;
+ int getAntennaFreqAgile() {
+ if (antennaFreqAgile < FREQAGILE_MIN || antennaFreqAgile > FREQAGILE_MAX)
+ getHST_ANT_CYCLES();
+ return antennaFreqAgile;
+ }
+ public boolean setAntennaFreqAgile(int freqAgile) {
+ return setAntennaCycle(antennaCycle, freqAgile);
+ }
+
+ private boolean getHST_ANT_CYCLES() {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 0, 7, 0, 0, 0, 0};
+ return sendHostRegRequest(HostRegRequests.HST_ANT_CYCLES, false, msgBuffer);
+ }
+
+ final int ANTSELECT_INVALID = -1; final int ANTSLECT_MIN = 0; final int ANTSELECT_MAX = 15;
+ int antennaSelect = ANTSELECT_INVALID; //default value = 0
+ public int getAntennaSelect() {
+ appendToLog("AntennaSelect = " + antennaSelect);
+ if (antennaSelect < ANTSLECT_MIN || antennaSelect > ANTSELECT_MAX) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 1, 7, 0, 0, 0, 0};
+ sendHostRegRequest(HostRegRequests.HST_ANT_DESC_SEL, false, msgBuffer);
+ }
+ return antennaSelect;
+ }
+ public boolean setAntennaSelect(int antennaSelect) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 1, 7, 0, 0, 0, 0};
+ if (antennaSelect < ANTSLECT_MIN || antennaSelect > ANTSELECT_MAX) antennaSelect = mDefault.antennaSelect;
+ if (this.antennaSelect == antennaSelect && sameCheck) return true;
+ this.antennaSelect = antennaSelect; appendToLog("antennaSelect is set to " + antennaSelect);
+ msgBuffer[4] = (byte) (antennaSelect);
+ return sendHostRegRequest(HostRegRequests.HST_ANT_DESC_SEL, true, msgBuffer);
+ }
+
+ AntennaSelectedData[] antennaSelectedData;
+ public int getAntennaEnable() {
+ if (antennaSelect < ANTSLECT_MIN || antennaSelect > ANTSELECT_MAX) {
+ return ANTSELECT_INVALID;
+ } else {
+ return antennaSelectedData[antennaSelect].getAntennaEnable();
+ }
+ }
+ public boolean setAntennaEnable(int antennaEnable) {
+ if (antennaSelect < ANTSLECT_MIN || antennaSelect > ANTSELECT_MAX) { antennaSelect = mDefault.antennaSelect; appendToLog("antennaSelect is set to " + antennaSelect); }
+ return antennaSelectedData[antennaSelect].setAntennaEnable(antennaEnable);
+ }
+ boolean setAntennaEnable(int antennaEnable, int antennaInventoryMode, int antennaLocalAlgo, int antennaLocalStartQ,
+ int antennaProfileMode, int antennaLocalProfile, int antennaFrequencyMode, int antennaLocalFrequency) {
+ if (antennaSelect < ANTSLECT_MIN || antennaSelect > ANTSELECT_MAX) { antennaSelect = mDefault.antennaSelect; appendToLog("antennaSelect is set to " + antennaSelect); }
+ return antennaSelectedData[antennaSelect].setAntennaEnable(antennaEnable, antennaInventoryMode, antennaLocalAlgo, antennaLocalStartQ,
+ antennaProfileMode, antennaLocalProfile, antennaFrequencyMode, antennaLocalFrequency);
+ }
+
+ int getAntennaInventoryMode() {
+ if (antennaSelect < ANTSLECT_MIN || antennaSelect > ANTSELECT_MAX) {
+ return ANTSELECT_INVALID;
+ } else {
+ return antennaSelectedData[antennaSelect].getAntennaInventoryMode();
+ }
+ }
+ boolean setAntennaInventoryMode(int antennaInventoryMode) {
+ if (antennaSelect < ANTSLECT_MIN || antennaSelect > ANTSELECT_MAX) { antennaSelect = mDefault.antennaSelect; appendToLog("antennaSelect is set to " + antennaSelect); }
+ return antennaSelectedData[antennaSelect].setAntennaInventoryMode(antennaInventoryMode);
+ }
+
+ int getAntennaLocalAlgo() {
+ if (antennaSelect < ANTSLECT_MIN || antennaSelect > ANTSELECT_MAX) {
+ return ANTSELECT_INVALID;
+ } else {
+ return antennaSelectedData[antennaSelect].getAntennaLocalAlgo();
+ }
+ }
+ boolean setAntennaLocalAlgo(int antennaLocalAlgo) {
+ if (antennaSelect < ANTSLECT_MIN || antennaSelect > ANTSELECT_MAX) { antennaSelect = mDefault.antennaSelect; appendToLog("antennaSelect is set to " + antennaSelect); }
+ return antennaSelectedData[antennaSelect].setAntennaLocalAlgo(antennaLocalAlgo);
+ }
+
+ int getAntennaLocalStartQ() {
+ if (antennaSelect < ANTSLECT_MIN || antennaSelect > ANTSELECT_MAX) {
+ return ANTSELECT_INVALID;
+ } else {
+ return antennaSelectedData[antennaSelect].getAntennaLocalStartQ();
+ }
+ }
+ boolean setAntennaLocalStartQ(int antennaLocalStartQ) {
+ if (antennaSelect < ANTSLECT_MIN || antennaSelect > ANTSELECT_MAX) { antennaSelect = mDefault.antennaSelect; appendToLog("antennaSelect is set to " + antennaSelect); }
+ return antennaSelectedData[antennaSelect].setAntennaLocalStartQ(antennaLocalStartQ);
+ }
+
+ int getAntennaProfileMode() {
+ if (antennaSelect < ANTSLECT_MIN || antennaSelect > ANTSELECT_MAX) {
+ return ANTSELECT_INVALID;
+ } else {
+ return antennaSelectedData[antennaSelect].getAntennaProfileMode();
+ }
+ }
+ boolean setAntennaProfileMode(int antennaProfileMode) {
+ if (antennaSelect < ANTSLECT_MIN || antennaSelect > ANTSELECT_MAX) { antennaSelect = mDefault.antennaSelect; appendToLog("antennaSelect is set to " + antennaSelect); }
+ return antennaSelectedData[antennaSelect].setAntennaProfileMode(antennaProfileMode);
+ }
+
+ int getAntennaLocalProfile() {
+ if (antennaSelect < ANTSLECT_MIN || antennaSelect > ANTSELECT_MAX) {
+ return ANTSELECT_INVALID;
+ } else {
+ return antennaSelectedData[antennaSelect].getAntennaLocalProfile();
+ }
+ }
+ boolean setAntennaLocalProfile(int antennaLocalProfile) {
+ if (antennaSelect < ANTSLECT_MIN || antennaSelect > ANTSELECT_MAX) { antennaSelect = mDefault.antennaSelect; appendToLog("antennaSelect is set to " + antennaSelect); }
+ return antennaSelectedData[antennaSelect].setAntennaLocalProfile(antennaLocalProfile);
+ }
+
+ int getAntennaFrequencyMode() {
+ if (antennaSelect < ANTSLECT_MIN || antennaSelect > ANTSELECT_MAX) {
+ return ANTSELECT_INVALID;
+ } else {
+ return antennaSelectedData[antennaSelect].getAntennaFrequencyMode();
+ }
+ }
+ boolean setAntennaFrequencyMode(int antennaFrequencyMode) {
+ if (antennaSelect < ANTSLECT_MIN || antennaSelect > ANTSELECT_MAX) { antennaSelect = mDefault.antennaSelect; appendToLog("antennaSelect is set to " + antennaSelect); }
+ return antennaSelectedData[antennaSelect].setAntennaFrequencyMode(antennaFrequencyMode);
+ }
+
+ int getAntennaLocalFrequency() {
+ if (antennaSelect < ANTSLECT_MIN || antennaSelect > ANTSELECT_MAX) {
+ return ANTSELECT_INVALID;
+ } else {
+ return antennaSelectedData[antennaSelect].getAntennaLocalFrequency();
+ }
+ }
+ boolean setAntennaLocalFrequency(int antennaLocalFrequency) {
+ if (antennaSelect < ANTSLECT_MIN || antennaSelect > ANTSELECT_MAX) { antennaSelect = mDefault.antennaSelect; appendToLog("antennaSelect is set to " + antennaSelect); }
+ return antennaSelectedData[antennaSelect].setAntennaLocalFrequency(antennaLocalFrequency);
+ }
+
+ int getAntennaStatus() {
+ if (antennaSelect < ANTSLECT_MIN || antennaSelect > ANTSELECT_MAX) {
+ return ANTSELECT_INVALID;
+ } else {
+ return antennaSelectedData[antennaSelect].getAntennaStatus();
+ }
+ }
+
+ int getAntennaDefine() {
+ if (antennaSelect < ANTSLECT_MIN || antennaSelect > ANTSELECT_MAX) {
+ return ANTSELECT_INVALID;
+ } else {
+ return antennaSelectedData[antennaSelect].getAntennaDefine();
+ }
+ }
+
+ public long getAntennaDwell() {
+ if (antennaSelect < ANTSLECT_MIN || antennaSelect > ANTSELECT_MAX) {
+ return ANTSELECT_INVALID;
+ } else {
+ return antennaSelectedData[antennaSelect].getAntennaDwell();
+ }
+ }
+ public boolean setAntennaDwell(long antennaDwell) {
+ if (antennaSelect < ANTSLECT_MIN || antennaSelect > ANTSELECT_MAX) { antennaSelect = mDefault.antennaSelect; appendToLog("antennaSelect is set to " + antennaSelect); }
+ return antennaSelectedData[antennaSelect].setAntennaDwell(antennaDwell);
+ }
+
+ public long getAntennaPower(int portNumber) {
+ if (antennaSelect < ANTSLECT_MIN || antennaSelect > ANTSELECT_MAX) {
+ return ANTSELECT_INVALID;
+ } else {
+ if (portNumber < 0 || portNumber > 15) portNumber = antennaSelect;
+ long lValue;
+ lValue = antennaSelectedData[portNumber].getAntennaPower();
+ return lValue;
+ }
+ }
+ public boolean setAntennaPower(long antennaPower) {
+ if (antennaSelect < ANTSLECT_MIN || antennaSelect > ANTSELECT_MAX) { antennaSelect = mDefault.antennaSelect; appendToLog("antennaSelect is set to " + antennaSelect); }
+ return antennaSelectedData[antennaSelect].setAntennaPower(antennaPower);
+ }
+
+ long getAntennaInvCount() {
+ if (antennaSelect < ANTSLECT_MIN || antennaSelect > ANTSELECT_MAX) {
+ return ANTSELECT_INVALID;
+ } else {
+ return antennaSelectedData[antennaSelect].getAntennaInvCount();
+ }
+ }
+ public boolean setAntennaInvCount(long antennaInvCount) {
+ if (antennaSelect < ANTSLECT_MIN || antennaSelect > ANTSELECT_MAX) { antennaSelect = mDefault.antennaSelect; appendToLog("antennaSelect is set to " + antennaSelect); }
+ return antennaSelectedData[antennaSelect].setAntennaInvCount(antennaInvCount);
+ }
+
+ //Tag select block parameters
+ final int INVSELECT_INVALID = -1; final int INVSELECT_MIN = 0; final int INVSELECT_MAX = 7;
+ public int invSelectIndex = INVSELECT_INVALID;
+ public int getInvSelectIndex() {
+ if (invSelectIndex < INVSELECT_MIN || invSelectIndex > INVSELECT_MAX) {
+ {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 0, 8, 0, 0, 0, 0};
+ sendHostRegRequest(HostRegRequests.HST_TAGMSK_DESC_SEL, false, msgBuffer);
+ }
+ }
+ return invSelectIndex;
+ }
+ public boolean setInvSelectIndex(int invSelect) {
+ if (utility.DEBUG_SELECT) appendToLog("Debug_Select: RfidReaderChipR2000.setInvSelectIndex[" + invSelect);
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 0, 8, 0, 0, 0, 0};
+ if (invSelect < INVSELECT_MIN || invSelect > INVSELECT_MAX) invSelect = mDefault.invSelectIndex;
+ if (this.invSelectIndex == invSelect && sameCheck) return true;
+ msgBuffer[4] = (byte) (invSelect & 0x07);
+ this.invSelectIndex = invSelect;
+ return sendHostRegRequest(HostRegRequests.HST_TAGMSK_DESC_SEL, true, msgBuffer);
+ }
+
+ InvSelectData[] invSelectData;
+ public int getSelectEnable() {
+ if (invSelectIndex < INVSELECT_MIN || invSelectIndex > INVSELECT_MAX) invSelectIndex = mDefault.invSelectIndex;
+ return invSelectData[invSelectIndex].getSelectEnable();
+ }
+ public boolean setSelectEnable(int enable, int selectTarget, int selectAction, int selectDelay) {
+ if (utility.DEBUG_SELECT) appendToLog("Debug_Select: RfidReaderChipR2000.Rx000Setting.setSelectEnable[" + enable);
+ if (invSelectIndex < INVSELECT_MIN || invSelectIndex > INVSELECT_MAX) invSelectIndex = mDefault.invSelectIndex;
+ if (false) appendToLog("BtDataOut: RfidReaderChipR200.setSelectEnable goes to setRx000HostReg_HST_TAGMSK_DESC_CFG with index = " + invSelectIndex);
+ return invSelectData[invSelectIndex].setRx000HostReg_HST_TAGMSK_DESC_CFG(enable, selectTarget, selectAction, selectDelay);
+ }
+
+ public int getSelectTarget() {
+ if (invSelectIndex < INVSELECT_MIN || invSelectIndex > INVSELECT_MAX) invSelectIndex = mDefault.invSelectIndex;
+ return invSelectData[invSelectIndex].getSelectTarget();
+ }
+
+ public int getSelectAction() {
+ if (invSelectIndex < INVSELECT_MIN || invSelectIndex > INVSELECT_MAX) invSelectIndex = mDefault.invSelectIndex;
+ return invSelectData[invSelectIndex].getSelectAction();
+ }
+
+ public int getSelectMaskBank() {
+ if (invSelectIndex < INVSELECT_MIN || invSelectIndex > INVSELECT_MAX) invSelectIndex = mDefault.invSelectIndex;
+ return invSelectData[invSelectIndex].getSelectMaskBank();
+ }
+ public boolean setSelectMaskBank(int selectMaskBank) {
+ if (invSelectIndex < INVSELECT_MIN || invSelectIndex > INVSELECT_MAX) invSelectIndex = mDefault.invSelectIndex;
+ return invSelectData[invSelectIndex].setSelectMaskBank(selectMaskBank);
+ }
+
+ public int getSelectMaskOffset() {
+ int dataIndex = invSelectIndex;
+ if (dataIndex < INVSELECT_MIN || dataIndex > INVSELECT_MAX) {
+ return INVSELECT_INVALID;
+ } else {
+ return invSelectData[dataIndex].getSelectMaskOffset();
+ }
+ }
+ public boolean setSelectMaskOffset(int selectMaskOffset) {
+ if (invSelectIndex < INVSELECT_MIN || invSelectIndex > INVSELECT_MAX) invSelectIndex = mDefault.invSelectIndex;
+ return invSelectData[invSelectIndex].setSelectMaskOffset(selectMaskOffset);
+ }
+
+ public int getSelectMaskLength() {
+ int dataIndex = invSelectIndex;
+ if (dataIndex < INVSELECT_MIN || dataIndex > INVSELECT_MAX) {
+ return INVSELECT_INVALID;
+ } else {
+ return invSelectData[dataIndex].getSelectMaskLength();
+ }
+ }
+ public boolean setSelectMaskLength(int selectMaskLength) {
+ if (false) appendToLog("btDataOut: setSelectMaskLength with selectMaskLength = " + selectMaskLength);
+ if (invSelectIndex < INVSELECT_MIN || invSelectIndex > INVSELECT_MAX) invSelectIndex = mDefault.invSelectIndex;
+ return invSelectData[invSelectIndex].setSelectMaskLength(selectMaskLength);
+ }
+
+ public String getSelectMaskData() {
+ int dataIndex = invSelectIndex;
+ if (dataIndex < INVSELECT_MIN || dataIndex > INVSELECT_MAX) {
+ return null;
+ } else {
+ return invSelectData[dataIndex].getRx000SelectMaskData();
+ }
+ }
+ public boolean setSelectMaskData(String maskData) {
+ if (maskData == null) return false;
+ if (invSelectIndex < INVSELECT_MIN || invSelectIndex > INVSELECT_MAX) invSelectIndex = mDefault.invSelectIndex;
+ if (invSelectData[invSelectIndex].selectMaskDataReady != 0) {
+ String maskDataOld = getSelectMaskData();
+ if (maskData != null && maskDataOld != null) {
+ if (maskData.matches(maskDataOld) && sameCheck) return true;
+ }
+ }
+ return invSelectData[invSelectIndex].setRx000SelectMaskData(maskData);
+ }
+
+ //Inventtory block paraameters
+ final int QUERYTARGET_INVALID = -1; final int QUERYTARGET_MIN = 0; final int QUERYTARGET_MAX = 1;
+ int queryTarget = QUERYTARGET_INVALID;
+ public int getQueryTarget() {
+ if (DEBUG) appendToLog("RfidReaderChipR2000.getQueryTarget with queryTarget = " + queryTarget);
+ if (queryTarget == QUERYTARGET_INVALID) getHST_QUERY_CFG();
+ return queryTarget;
+ }
+ boolean setQueryTarget(int queryTarget) {
+ if (DEBUG || true) appendToLog("3 setQueryTarget is callled from RfidReaderChipR2000.setQueryTarget[" + queryTarget);
+ return setQueryTarget(queryTarget, querySession, querySelect);
+ }
+ public boolean setQueryTarget(int queryTarget, int querySession, int querySelect) {
+ if (false) appendToLog("setQueryTarget[" + queryTarget + ", " + querySession + ", " + querySelect + "] with sameCheck = " + sameCheck + ", old queryTarget/Session/Select = " + this.queryTarget + ", " + this.querySession + ", " + this.querySelect);
+ if (queryTarget >= 2) { rx000Setting.setAlgoAbFlip(1); }
+ else if (queryTarget >= 0) { rx000Setting.setAlgoAbFlip(0); }
+
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 0, 9, 0, 0, 0, 0};
+
+ if ((this.queryTarget == queryTarget || queryTarget == 2 || queryTarget == -1)
+ && (this.querySession == querySession || querySession == -1)
+ && (this.querySelect == querySelect || querySelect == -1) && sameCheck) return true;
+ msgBuffer[4] |= ((queryTarget == 2 ? 0 : queryTarget) << 4);
+ msgBuffer[4] |= (byte) (querySession << 5);
+ if ((querySelect & 0x01) != 0) {
+ msgBuffer[4] |= (byte) 0x80;
+ }
+ if ((querySelect & 0x02) != 0) {
+ msgBuffer[5] |= (byte) 0x01;
+ }
+ this.queryTarget = queryTarget;
+ this.querySession = querySession;
+ this.querySelect = querySelect;
+ return sendHostRegRequest(HostRegRequests.HST_QUERY_CFG, true, msgBuffer);
+ }
+
+ final int QUERYSESSION_INVALID = -1; final int QUERYSESSION_MIN = 0; final int QUERYSESSION_MAX = 3;
+ int querySession = QUERYSESSION_INVALID;
+ public int getQuerySession() {
+ if (antennaSelect < ANTSLECT_MIN || antennaSelect > ANTSELECT_MAX) {
+ return ANTSELECT_INVALID;
+ } else {
+ {
+ //appendToLog("BtDataOut: RfidReaderChipR2000.getQuerySession with querySession = " + querySession);
+ if (querySession < QUERYSESSION_MIN || querySession > QUERYSESSION_MAX)
+ getHST_QUERY_CFG();
+ return querySession;
+ }
+ }
+
+ }
+ boolean setQuerySession(int querySession) {
+ if (true) appendToLog("4 setQueryTargetis callled from BtDataOut: RfidReaderChipR2000.setQuerySession[" + querySession);
+ return setQueryTarget((getAlgoAbFlip() > 0 ? 2 : queryTarget), querySession, querySelect);
+ }
+
+ final int QUERYSELECT_INVALID = -1; final int QUERYSELECT_MIN = 0; final int QUERYSELECT_MAX = 3;
+ int querySelect = QUERYSELECT_INVALID;
+ public int getQuerySelect() {
+ if (false) appendToLog("BtDataOut: RfidReaderChipR2000.getQuerySelect with querySelect = " + querySelect);
+ if (querySelect < QUERYSELECT_MIN || querySelect > QUERYSELECT_MAX) getHST_QUERY_CFG();
+ if (false) appendToLog("Stream querySelect = " + querySelect);
+ return querySelect;
+ }
+ public boolean setQuerySelect(int querySelect) {
+ if (false) appendToLog("5 setQueryTarget is callled from RfidReaderChipR2000.setQuerySelect[" + querySelect);
+ if (querySelect == this.querySelect) return true;
+ return setQueryTarget((getAlgoAbFlip() > 0 ? 2 : queryTarget), querySession, querySelect);
+ }
+
+ private boolean getHST_QUERY_CFG() {
+ //appendToLog("BtDataOut: RfidReaderChipR2000.getHST_QUERY_CFG");
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 0, 9, 0, 0, 0, 0};
+ return sendHostRegRequest(HostRegRequests.HST_QUERY_CFG, false, msgBuffer);
+ }
+
+ final int INVALGO_INVALID = -1; final int INVALGO_MIN = 0; final int INVALGO_MAX = 3;
+ int invAlgo = INVALGO_INVALID;
+ public int getInvAlgo() {
+ if (invAlgo < INVALGO_MIN || invAlgo > INVALGO_MAX) getHST_INV_CFG();
+ return invAlgo;
+ }
+ public boolean setInvAlgo(int invAlgo) {
+ if (utility.DEBUG_INVCFG) appendToLog("Debug_InvCfg: RfidReaderChipR2000.Rx000setting.setInvAlog goes to setInvAlgo with invAlgo = " + invAlgo);
+ return setInvAlgo(invAlgo, matchRep, tagSelect, noInventory, tagRead, tagDelay, invModeCompact, invBrandId, invAuthenticate);
+ }
+
+ final int MATCHREP_INVALID = -1; final int MATCHREP_MIN = 0; final int MATCHREP_MAX = 255;
+ int matchRep = MATCHREP_INVALID;
+ int getMatchRep() {
+ if (matchRep < MATCHREP_MIN || matchRep > MATCHREP_MAX) getHST_INV_CFG();
+ return matchRep;
+ }
+ public boolean setMatchRep(int matchRep) {
+ if (utility.DEBUG_INVCFG) appendToLog("Debug_InvCfg: RfidReaderChipR2000.Rx000setting.setMatchRep goes to setInvAlgo with matchRep = " + matchRep);
+ return setInvAlgo(invAlgo, matchRep, tagSelect, noInventory, tagRead, tagDelay, invModeCompact, invBrandId, invAuthenticate);
+ }
+
+ final int TAGSELECT_INVALID = -1; final int TAGSELECT_MIN = 0; final int TAGSELECT_MAX = 1;
+ int tagSelect = TAGSELECT_INVALID;
+ int getTagSelect() {
+ if (tagSelect < TAGSELECT_MIN || tagSelect > TAGSELECT_MAX) getHST_INV_CFG();
+ return tagSelect;
+ }
+ public boolean setTagSelect(int tagSelect) {
+ if (utility.DEBUG_INVCFG) appendToLog("Debug_InvCfg: RfidReaderChipR2000.Rx000setting.setTagSelect goes to setInvAlgo with tagSelect = " + tagSelect);
+ return setInvAlgo(invAlgo, matchRep, tagSelect, noInventory, tagRead, tagDelay, invModeCompact, invBrandId, invAuthenticate);
+ }
+
+ final int NOINVENTORY_INVALID = -1; final int NOINVENTORY_MIN = 0; final int NOINVENTORY_MAX = 1;
+ int noInventory = NOINVENTORY_INVALID;
+ int getNoInventory() {
+ if (noInventory < NOINVENTORY_MIN || noInventory > NOINVENTORY_MAX) getHST_INV_CFG();
+ return noInventory;
+ }
+ boolean setNoInventory(int noInventory) {
+ if (utility.DEBUG_INVCFG) appendToLog("Debug_InvCfg: RfidReaderChipR2000.Rx000setting.setNoInventory goes to setInvAlgo with noInventory = " + noInventory);
+ return setInvAlgo(invAlgo, matchRep, tagSelect, noInventory, tagRead, tagDelay, invModeCompact, invBrandId, invAuthenticate);
+ }
+
+ final int TAGREAD_INVALID = -1; final int TAGREAD_MIN = 0; final int TAGREAD_MAX = 2;
+ int tagRead = TAGREAD_INVALID;
+ int getTagRead() {
+ if (tagRead < TAGREAD_MIN || tagRead > TAGREAD_MAX) getHST_INV_CFG();
+ return tagRead;
+ }
+ public boolean setTagRead(int tagRead) {
+ if (utility.DEBUG_INVCFG) appendToLog("Debug_InvCfg: RfidReaderChipR2000.Rx000setting.setTagRead goes to setInvAlgo with tagRead = " + tagRead);
+ return setInvAlgo(invAlgo, matchRep, tagSelect, noInventory, tagRead, tagDelay, invModeCompact, invBrandId, invAuthenticate);
+ }
+
+ final int TAGDELAY_INVALID = -1; final int TAGDELAY_MIN = 0; final int TAGDELAY_MAX = 63;
+ int tagDelay = TAGDELAY_INVALID;
+ int getTagDelay() {
+ if (tagDelay < TAGDELAY_MIN || tagDelay > TAGDELAY_MAX) getHST_INV_CFG();
+ return tagDelay;
+ }
+ public boolean setTagDelay2RfidReader(int tagDelay) {
+ if (utility.DEBUG_INVCFG) appendToLog("Debug_InvCfg: RfidReaderChipR2000.Rx000setting.setTagDelay goes to setInvAlgo with tagDelay = " + tagDelay);
+ return setInvAlgo(invAlgo, matchRep, tagSelect, noInventory, tagRead, tagDelay, invModeCompact, invBrandId, invAuthenticate);
+ }
+
+ byte intraPacketDelay = 4;
+ public byte getIntraPacketDelay() {
+ appendToLog("intraPacketDelay = " + intraPacketDelay);
+ return intraPacketDelay;
+ }
+ public boolean setIntraPacketDelay(byte intraPkDelay) {
+ if (intraPacketDelay == intraPkDelay && sameCheck) {
+ appendToLog("!!! Skip sending repeated data with intraPkDelay = " + intraPkDelay);
+ return true;
+ }
+ appendToLog("Skip setDupElim with intraPkDelay = " + intraPkDelay);
+ intraPacketDelay = intraPkDelay;
+ return true;
+ }
+
+ byte dupElimRollWindow = 0;
+ public byte getDupElimRollWindow() {
+ appendToLog("dupElim = " + dupElimRollWindow);
+ return dupElimRollWindow;
+ }
+ public boolean setDupElimRollWindow(byte dupElimDelay) {
+ if (dupElimRollWindow == dupElimDelay && sameCheck) {
+ appendToLog("!!! Skip sending repeated data with dupElimDelay = " + dupElimDelay);
+ return true;
+ }
+ appendToLog("Skip setDupElim with dupElimDelay = " + dupElimDelay);
+ dupElimRollWindow = dupElimDelay;
+ return true;
+ }
+
+ long cycleDelay = 0;
+ public long getCycleDelay() {
+ return cycleDelay;
+ }
+ public boolean setCycleDelay(long cycleDelay) {
+ if (this.cycleDelay == cycleDelay && sameCheck) return true;
+
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, (byte)0x0F, (byte)0x0F, 0, 0, 0, 0};
+ msgBuffer[4] |= (cycleDelay & 0xFF);
+ msgBuffer[5] |= (byte) ((cycleDelay & 0xFF00) >> 8);
+ msgBuffer[6] |= (byte) ((cycleDelay & 0xFF0000) >> 16);
+ msgBuffer[7] |= (byte) ((cycleDelay & 0xFF000000) >> 24);
+ this.cycleDelay = cycleDelay;
+ boolean bResult = sendHostRegRequest(HostRegRequests.HST_INV_CFG, true, msgBuffer);
+ //msgBuffer = new byte[]{(byte) 0x70, 0, (byte)0x0F, (byte)0x0F, 0, 0, 0, 0};
+ //sendHostRegRequest(HostRegRequests.HST_INV_CFG, false, msgBuffer);
+ return bResult;
+ }
+
+ final int AUTHENTICATE_CFG_INVALID = -1; final int AUTHENTICATE_CFG_MIN = 0; final int AUTHENTICATE_CFG_MAX = 4095;
+ boolean authenticateSendReply;
+ boolean authenticateIncReplyLength;
+ int authenticateLength = AUTHENTICATE_CFG_INVALID;
+ public int getAuthenticateReplyLength() {
+ if (authenticateLength < AUTHENTICATE_CFG_MIN || authenticateLength > AUTHENTICATE_CFG_MAX) getHST_AUTHENTICATE_CFG();
+ return authenticateLength;
+ }
+ private boolean getHST_AUTHENTICATE_CFG() {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 0, (byte) 0x0F, 0, 0, 0, 0};
+ return sendHostRegRequest(HostRegRequests.HST_AUTHENTICATE_CFG, false, msgBuffer);
+ }
+ public boolean setHST_AUTHENTICATE_CFG(boolean sendReply, boolean incReplyLenth, int csi, int length) {
+ appendToLog("sendReply = " + sendReply + ", incReplyLenth = " + incReplyLenth + ", length = " + length);
+ if (length < 0 || length > 0x3FF) return false;
+
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 0, (byte) 0x0F, 0, 0, 0, 0};
+ if (sendReply) msgBuffer[4] |= 0x01; authenticateSendReply = sendReply;
+ if (incReplyLenth) msgBuffer[4] |= 0x02; authenticateIncReplyLength = incReplyLenth;
+ msgBuffer[4] |= ((csi & 0x3F) << 2);
+ msgBuffer[5] |= ((csi >> 6) & 0x03);
+ msgBuffer[5] |= ((length & 0x3F) << 2);
+ msgBuffer[6] |= ((length & 0xFC0) >> 6); authenticateLength = length;
+ return sendHostRegRequest(HostRegRequests.HST_AUTHENTICATE_CFG, true, msgBuffer);
+ }
+
+ byte[] authMatchData0_63; int authMatchDataReady = 0;
+ public String getAuthMatchData() {
+ int length = 96;
+ String strValue = "";
+ for (int i = 0; i < 3; i++) {
+ if (length > 0) {
+ appendToLog("i = " + i + ", authMatchDataReady = " + authMatchDataReady);
+ if ((authMatchDataReady & (0x01 << i)) == 0) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 1, (byte)0x0F, 0, 0, 0, 0};
+ msgBuffer[2] += i;
+ sendHostRegRequest(HostRegRequests.HST_AUTHENTICATE_MSG, false, msgBuffer);
+ } else {
+ for (int j = 0; j < 4; j++) {
+ strValue += String.format("%02X", authMatchData0_63[i * 4 + j]);
+ }
+ }
+ length -= 32;
+ }
+ }
+ if (strValue.length() < 16) strValue = null;
+ return strValue;
+ }
+ public boolean setAuthMatchData(String matchData) {
+ int length = matchData.length();
+ appendToLog("matchData is " + length + ", " + matchData);
+ for (int i = 0; i < 6; i++) {
+ if (length > 0) {
+ length -= 8;
+
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 1, (byte)0x0F, 0, 0, 0, 0};
+ String hexString = "0123456789ABCDEF";
+ for (int j = 0; j < 8; j++) {
+ if (i * 8 + j + 1 <= matchData.length()) {
+ String subString = matchData.substring(i * 8 + j, i * 8 + j + 1).toUpperCase();
+ int k = 0;
+ for (k = 0; k < 16; k++) {
+ if (subString.matches(hexString.substring(k, k + 1))) {
+ break;
+ }
+ }
+ if (k == 16) return false;
+ if ((j / 2) * 2 == j) {
+ msgBuffer[7 - j / 2] |= (byte) (k << 4);
+ } else {
+ msgBuffer[7 - j / 2] |= (byte) (k);
+ }
+ }
+ }
+ msgBuffer[2] = (byte) ((msgBuffer[2] & 0xFF) + i);
+ if (sendHostRegRequest(HostRegRequests.HST_AUTHENTICATE_MSG, true, msgBuffer) == false)
+ return false;
+ else {
+ //authMatchDataReady |= (0x01 << i);
+ System.arraycopy(msgBuffer, 4, authMatchData0_63, i * 4, 4); //appendToLog("Data=" + byteArrayToString(mRx000Setting.invMatchData0_63));
+// appendToLog("invMatchDataReady=" + Integer.toString(mRx000Setting.invMatchDataReady, 16) + ", message=" + byteArrayToString(msgBuffer));
+ }
+ }
+ }
+ return true;
+ }
+
+ final int UNTRACEABLE_CFG_INVALID = -1; final int UNTRACEABLE_CFG_MIN = 0; final int UNTRACEABLE_CFG_MAX = 3;
+ int untraceableRange = UNTRACEABLE_CFG_INVALID;
+ boolean untraceableUser;
+ int untraceableTid = UNTRACEABLE_CFG_INVALID;
+ int untraceableEpcLength = UNTRACEABLE_CFG_INVALID;
+ boolean untraceableEpc;
+ boolean untraceableUXpc;
+ public int getUntraceableEpcLength() {
+ if (untraceableRange < UNTRACEABLE_CFG_MIN || untraceableRange > UNTRACEABLE_CFG_MAX) getHST_UNTRACEABLE_CFG();
+ return untraceableEpcLength;
+ }
+ private boolean getHST_UNTRACEABLE_CFG() {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 5, (byte) 0x0F, 0, 0, 0, 0};
+ return sendHostRegRequest(HostRegRequests.HST_UNTRACEABLE_CFG, false, msgBuffer);
+ }
+ public boolean setHST_UNTRACEABLE_CFG(int range, boolean user, int tid, int epcLength, boolean epc, boolean uxpc) {
+ appendToLog("range1 = " + range + ", user = " + user + ", tid = " + tid + ", epc = " + epc + ", epcLength = " + epcLength + ", xcpc = " + uxpc);
+ if (range < 0 || range > 3) return false;
+ if (tid < 0 || tid > 2) return false;
+ if (epcLength < 0 || epcLength > 31) return false;
+
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 5, (byte) 0x0F, 0, 0, 0, 0};
+ msgBuffer[4] |= (range); untraceableRange = range;
+ if (user) msgBuffer[4] |= 0x04; untraceableUser = user;
+ msgBuffer[4] |= (tid << 3); untraceableTid = tid;
+ msgBuffer[4] |= ((epcLength & 0x7) << 5);
+ msgBuffer[5] |= ((epcLength & 0x18) >> 3); untraceableEpcLength = epcLength;
+ if (epc) msgBuffer[5] |= 0x04; untraceableEpc = epc;
+ if (uxpc) msgBuffer[5] |= 0x08; untraceableUXpc = uxpc;
+ appendToLog("msgbuffer = " + byteArrayToString(msgBuffer));
+ return sendHostRegRequest(HostRegRequests.HST_UNTRACEABLE_CFG, true, msgBuffer);
+ }
+
+ final int TAGJOIN_INVALID = -1; final int TAGJOIN_MIN = 0; final int TAGJOIN_MAX = 1;
+ int invModeCompact = TAGJOIN_INVALID;
+ boolean getInvModeCompact() {
+ if (invModeCompact < TAGDELAY_MIN || invModeCompact > TAGDELAY_MAX) { getHST_INV_CFG(); return false; }
+ return (invModeCompact == 1);
+ }
+ public boolean setInvModeCompact(boolean invModeCompact) {
+ if (utility.DEBUG_INVCFG) appendToLog("Debug_InvCfg: RfidReaderChipR2000.Rx000setting.setInvModeCompact goes to setInvAlgo with invModeCompact = " + invModeCompact);
+ return setInvAlgo(invAlgo, matchRep, tagSelect, noInventory, tagRead, tagDelay, (invModeCompact ? 1 : 0), invBrandId, invAuthenticate);
+ }
+
+ final int BRAND_INVALID = -1; final int BRANDID_MIN = 0; final int BRANDID_MAX = 1;
+ int invBrandId = BRAND_INVALID;
+ boolean getInvBrandId() {
+ if (invBrandId < BRANDID_MIN || invBrandId > BRANDID_MAX) { getHST_INV_CFG(); return false; }
+ return (invModeCompact == 1);
+ }
+ public boolean setInvBrandId(boolean invBrandId) {
+ if (utility.DEBUG_INVCFG) appendToLog("Debug_InvCfg: RfidReaderChipR2000.Rx000setting.setInvBrandId goes to setInvAlgo with invBrandId = " + invBrandId);
+ return setInvAlgo(invAlgo, matchRep, tagSelect, noInventory, tagRead, tagDelay, invModeCompact, (invBrandId ? 1 : 0), invAuthenticate);
+ }
+
+ final int INVAUTHENTICATE_INVALID = -1; final int INVAUTHENTICATE_MIN = 0; final int INVAUTHENTICATE_MAX = 1;
+ int invAuthenticate = INVAUTHENTICATE_INVALID;
+ boolean getInvAuthenticate() {
+ if (invAuthenticate < INVAUTHENTICATE_MIN || invAuthenticate > INVAUTHENTICATE_MAX) { getHST_INV_CFG(); return false; }
+ return (invAuthenticate == 1);
+ }
+ public boolean setInvAuthenticate(boolean invAuthenticate) {
+ if (utility.DEBUG_INVCFG) appendToLog("Debug_InvCfg: RfidReaderChipR2000.Rx000setting.setInvBrandId goes to setInvAlgo with invBrandId = " + invBrandId);
+ return setInvAlgo(invAlgo, matchRep, tagSelect, noInventory, tagRead, tagDelay, invModeCompact, invBrandId, (invAuthenticate ? 1: 0));
+ }
+
+ private boolean getHST_INV_CFG() {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 1, 9, 0, 0, 0, 0};
+ return sendHostRegRequest(HostRegRequests.HST_INV_CFG, false, msgBuffer);
+ }
+ boolean setInvAlgo(int invAlgo, int matchRep, int tagSelect, int noInventory, int tagRead, int tagDelay, int invModeCompact, int invBrandId, int invAuthenticate) {
+ boolean DEBUG = utility.DEBUG_INVCFG;
+ if (DEBUG) appendToLog("Debug_InvCfg: 0 tagRead is " + tagRead);
+ if (invAlgo < INVALGO_MIN || invAlgo > INVALGO_MAX) invAlgo = mDefault.invAlgo;
+ if (matchRep < MATCHREP_MIN || matchRep > MATCHREP_MAX) matchRep = mDefault.matchRep;
+ if (tagSelect < TAGSELECT_MIN || tagSelect > TAGSELECT_MAX) tagSelect = mDefault.tagSelect;
+ if (noInventory < NOINVENTORY_MIN || noInventory > NOINVENTORY_MAX) noInventory = mDefault.noInventory;
+ if (tagDelay < TAGDELAY_MIN || tagDelay > TAGDELAY_MAX) tagDelay = mDefault.tagDelay;
+ if (invModeCompact < TAGJOIN_MIN || invModeCompact > TAGJOIN_MAX) invModeCompact = mDefault.tagJoin;
+ if (invBrandId < BRANDID_MIN || invBrandId > BRANDID_MAX) invBrandId = mDefault.brandid;
+ if (invAuthenticate < INVAUTHENTICATE_MIN || invAuthenticate > INVAUTHENTICATE_MAX) invAuthenticate = mDefault.invAuthenticate;
+ if (tagRead < TAGREAD_MIN || tagRead > TAGREAD_MAX) tagRead = mDefault.tagRead;
+ if (DEBUG) appendToLog("Debug_InvCfg: Old invAlgo = " + this.invAlgo + ", matchRep = " + this.matchRep + ", tagSelect = " + this.tagSelect + ", noInventory = " + this.noInventory + ", tagRead = " + this.tagRead + ", tagDelay = " + this.tagDelay + ", invModeCompact = " + this.invModeCompact + ", invBrandId = " + this.invBrandId + ", invAuthenticate = " + this.invAuthenticate);
+ if (DEBUG) appendToLog("Debug_InvCfg: New invAlgo = " + invAlgo + ", matchRep = " + matchRep + ", tagSelect = " + tagSelect + ", noInventory = " + noInventory + ", tagRead = " + tagRead + ", tagDelay = " + tagDelay + ", invModeCompact = " + invModeCompact + ", invBrandId = " + invBrandId + ", invAuthenticate = " + invAuthenticate + ", sameCheck = " + sameCheck);
+ boolean bool1 = this.invAlgo == invAlgo;
+ boolean bool2 = this.matchRep == matchRep;
+ boolean bool3 = this.tagSelect == tagSelect;
+ boolean bool4 = this.noInventory == noInventory;
+ if (DEBUG) appendToLog("Debug_InvCfg: tagRead = " + tagRead + ", this.tagRead = " + this.tagRead);
+ boolean bool5 = (this.tagRead == tagRead) || (tagRead == -1);
+ boolean bool6 = this.tagDelay == tagDelay;
+ boolean bool7 = this.invModeCompact == invModeCompact;
+ boolean bool8 = this.invBrandId == invBrandId;
+ boolean bool9 = this.invAuthenticate == invAuthenticate;
+ if (bool1 && bool2 && bool3 && bool4 && bool5 && bool6 && bool7 && bool8 && bool9 && sameCheck) return true;
+ if (DEBUG) appendToLog("Debug_InvCfg: There is difference with " + bool1 + "," + bool2 + "," + bool3 + "," + bool4 + "," + bool5 + "," + bool6 + "," + bool7 + "," + bool8 + "," + bool9);
+ this.invAlgo = invAlgo; if (DEBUG) appendToLog("Hello6: invAlgo = " + invAlgo + ", queryTarget = " + queryTarget);
+ this.matchRep = matchRep;
+ this.tagSelect = tagSelect;
+ this.noInventory = noInventory;
+ this.tagRead = tagRead;
+ this.tagDelay = tagDelay;
+ this.invModeCompact = invModeCompact;
+ this.invBrandId = invBrandId;
+ this.invAuthenticate = invAuthenticate;
+ appendToLog("BtDataOut: 1, invAuthenticate = " + rx000Setting.invAuthenticate);
+ if (DEBUG) appendToLog("Debug_InvCfg: Stored tagDelay = " + this.tagDelay);
+
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 1, 9, 0, 0, 0, 0};
+ msgBuffer[4] |= invAlgo;
+ msgBuffer[4] |= (byte) ((matchRep & 0x03) << 6);
+ msgBuffer[5] |= (byte) (matchRep >> 2);
+ if (tagSelect != 0) {
+ msgBuffer[5] |= 0x40;
+ }
+ if (noInventory != 0) {
+ msgBuffer[5] |= 0x80;
+ }
+ if ((tagRead & 0x03) != 0) {
+ msgBuffer[6] |= (tagRead & 0x03);
+ }
+ if ((tagDelay & 0x0F) != 0) {
+ msgBuffer[6] |= ((tagDelay & 0x0F) << 4);
+ }
+ if ((tagDelay & 0x30) != 0) {
+ msgBuffer[7] |= ((tagDelay & 0x30) >> 4);
+ }
+ if (invModeCompact == 1) {
+ msgBuffer[7] |= 0x04;
+ }
+ if (invBrandId == 1) {
+ msgBuffer[7] |= 0x08;
+ }
+ if (invAuthenticate == 1) {
+ msgBuffer[7] |= 0x10;
+ }
+ return sendHostRegRequest(HostRegRequests.HST_INV_CFG, true, msgBuffer);
+ }
+
+ final int ALGOSELECT_INVALID = -1; final int ALGOSELECT_MIN = 0; final int ALGOSELECT_MAX = 3; //DataSheet says Max=1
+ int algoSelect = ALGOSELECT_INVALID;
+ public int getAlgoSelect() {
+ if (algoSelect < ALGOSELECT_MIN || algoSelect > ALGOSELECT_MAX) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 2, 9, 0, 0, 0, 0};
+ sendHostRegRequest(HostRegRequests.HST_INV_SEL, false, msgBuffer);
+ }
+ return algoSelect;
+ }
+ boolean dummyAlgoSelected = false;
+ public boolean setAlgoSelect(int algoSelect) {
+ if (false) appendToLog("setTagGroup: algoSelect = " + algoSelect + ", this.algoSelct = " + this.algoSelect + ", dummyAlgoSelected = " + dummyAlgoSelected);
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 2, 9, 0, 0, 0, 0};
+ if (algoSelect < ALGOSELECT_MIN || algoSelect > ALGOSELECT_MAX)
+ algoSelect = mDefault.algoSelect;
+ if (algoSelect == this.algoSelect && dummyAlgoSelected == false) return true;
+ msgBuffer[4] = (byte) (algoSelect & 0xFF);
+ msgBuffer[5] = (byte) ((algoSelect & 0xFF00) >> 8);
+ msgBuffer[6] = (byte) ((algoSelect & 0xFF0000) >> 16);
+ msgBuffer[7] = (byte) ((algoSelect & 0xFF000000) >> 24);
+ this.algoSelect = algoSelect;
+ return sendHostRegRequest(HostRegRequests.HST_INV_SEL, true, msgBuffer);
+ }
+
+ AlgoSelectedData[] algoSelectedData;
+ public int getAlgoStartQ(int algoSelect) {
+ if (algoSelect < ALGOSELECT_MIN || algoSelect > ALGOSELECT_MAX) {
+ return ALGOSELECT_INVALID;
+ } else {
+ return algoSelectedData[algoSelect].getAlgoStartQ(false);
+ }
+ }
+ public int getAlgoStartQ() {
+ if (algoSelect < ALGOSELECT_MIN || algoSelect > ALGOSELECT_MAX) {
+ return ALGOSELECT_INVALID;
+ } else {
+ return algoSelectedData[algoSelect].getAlgoStartQ(true);
+ }
+ }
+ public boolean setAlgoStartQ(int algoStartQ) {
+ if (algoSelect < ALGOSELECT_MIN || algoSelect > ALGOSELECT_MAX) return false;
+ return algoSelectedData[algoSelect].setAlgoStartQ(algoStartQ);
+ }
+ public boolean setAlgoStartQ(int startQ, int algoMaxQ, int algoMinQ, int algoMaxRep, int algoHighThres, int algoLowThres) {
+ if (algoSelect < ALGOSELECT_MIN || algoSelect > ALGOSELECT_MAX) return false;
+ return algoSelectedData[algoSelect].setAlgoStartQ(startQ, algoMaxQ, algoMinQ, algoMaxRep, algoHighThres, algoLowThres);
+ }
+
+ public int getAlgoMaxQ(int algoSelect) {
+ if (algoSelect < ALGOSELECT_MIN || algoSelect > ALGOSELECT_MAX) {
+ return ALGOSELECT_INVALID;
+ } else {
+ return algoSelectedData[algoSelect].getAlgoMaxQ();
+ }
+ }
+ int getAlgoMaxQ() {
+ if (algoSelect < ALGOSELECT_MIN || algoSelect > ALGOSELECT_MAX) {
+ return ALGOSELECT_INVALID;
+ } else {
+ return algoSelectedData[algoSelect].getAlgoMaxQ();
+ }
+ }
+ boolean setAlgoMaxQ(int algoMaxQ) {
+ if (algoSelect < ALGOSELECT_MIN || algoSelect > ALGOSELECT_MAX) return false;
+ return algoSelectedData[algoSelect].setAlgoMaxQ(algoMaxQ);
+ }
+
+ public int getAlgoMinQ(int algoSelect) {
+ if (algoSelect < ALGOSELECT_MIN || algoSelect > ALGOSELECT_MAX) {
+ return ALGOSELECT_INVALID;
+ } else {
+ return algoSelectedData[algoSelect].getAlgoMinQ();
+ }
+ }
+ int getAlgoMinQ() {
+ if (algoSelect < ALGOSELECT_MIN || algoSelect > ALGOSELECT_MAX) {
+ return ALGOSELECT_INVALID;
+ } else {
+ return algoSelectedData[algoSelect].getAlgoMinQ();
+ }
+ }
+ boolean setAlgoMinQ(int algoMinQ) {
+ if (algoSelect < ALGOSELECT_MIN || algoSelect > ALGOSELECT_MAX) return false;
+ return algoSelectedData[algoSelect].setAlgoMinQ(algoMinQ);
+ }
+
+ int getAlgoMaxRep() {
+ if (algoSelect < ALGOSELECT_MIN || algoSelect > ALGOSELECT_MAX) {
+ return ALGOSELECT_INVALID;
+ } else {
+ return algoSelectedData[algoSelect].getAlgoMaxRep();
+ }
+ }
+ boolean setAlgoMaxRep(int algoMaxRep) {
+ if (algoSelect < ALGOSELECT_MIN || algoSelect > ALGOSELECT_MAX) return false;
+ return algoSelectedData[algoSelect].setAlgoMaxRep(algoMaxRep);
+ }
+
+ int getAlgoHighThres() {
+ if (algoSelect < ALGOSELECT_MIN || algoSelect > ALGOSELECT_MAX) {
+ return ALGOSELECT_INVALID;
+ } else {
+ return algoSelectedData[algoSelect].getAlgoHighThres();
+ }
+ }
+ boolean setAlgoHighThres(int algoHighThre) {
+ if (algoSelect < ALGOSELECT_MIN || algoSelect > ALGOSELECT_MAX) return false;
+ return algoSelectedData[algoSelect].setAlgoHighThres(algoHighThre);
+ }
+
+ int getAlgoLowThres() {
+ if (algoSelect < ALGOSELECT_MIN || algoSelect > ALGOSELECT_MAX) {
+ return ALGOSELECT_INVALID;
+ } else {
+ return algoSelectedData[algoSelect].getAlgoLowThres();
+ }
+ }
+ boolean setAlgoLowThres(int algoLowThre) {
+ if (algoSelect < ALGOSELECT_MIN || algoSelect > ALGOSELECT_MAX) return false;
+ return algoSelectedData[algoSelect].setAlgoLowThres(algoLowThre);
+ }
+
+ public int getAlgoRetry(int algoSelect) {
+ if (algoSelect < ALGOSELECT_MIN || algoSelect > ALGOSELECT_MAX) {
+ return ALGOSELECT_INVALID;
+ } else {
+ return algoSelectedData[algoSelect].getAlgoRetry();
+ }
+ }
+ public boolean setAlgoRetry(int algoRetry) {
+ if (algoSelect < ALGOSELECT_MIN || algoSelect > ALGOSELECT_MAX) return false;
+ return algoSelectedData[algoSelect].setAlgoRetry(algoRetry);
+ }
+
+ int getAlgoAbFlip(int algoSelect) {
+ if (algoSelect < ALGOSELECT_MIN || algoSelect > ALGOSELECT_MAX) {
+ return ALGOSELECT_INVALID;
+ } else {
+ return algoSelectedData[algoSelect].getAlgoAbFlip();
+ }
+ }
+ public int getAlgoAbFlip() {
+ if (algoSelect < ALGOSELECT_MIN || algoSelect > ALGOSELECT_MAX) {
+ return ALGOSELECT_INVALID;
+ } else {
+ return algoSelectedData[algoSelect].getAlgoAbFlip();
+ }
+ }
+ public boolean setAlgoAbFlip(int algoAbFlip) {
+ if (algoSelect < ALGOSELECT_MIN || algoSelect > ALGOSELECT_MAX) return false;
+ return algoSelectedData[algoSelect].setAlgoAbFlip(algoAbFlip);
+ }
+ boolean setAlgoAbFlip(int algoAbFlip, int algoRunTilZero) {
+ if (algoSelect < ALGOSELECT_MIN || algoSelect > ALGOSELECT_MAX) return false;
+ appendToLog("algoSelect = " + algoSelect + ", algoAbFlip = " + algoAbFlip + ", algoRunTilZero = " + algoRunTilZero);
+ return algoSelectedData[algoSelect].setAlgoAbFlip(algoAbFlip, algoRunTilZero);
+ }
+
+ public int getAlgoRunTilZero(int algoSelect) {
+ if (algoSelect < ALGOSELECT_MIN || algoSelect > ALGOSELECT_MAX) {
+ return ALGOSELECT_INVALID;
+ } else {
+ return algoSelectedData[algoSelect].getAlgoRunTilZero();
+ }
+ }
+ int getAlgoRunTilZero() {
+ if (algoSelect < ALGOSELECT_MIN || algoSelect > ALGOSELECT_MAX) {
+ return ALGOSELECT_INVALID;
+ } else {
+ return algoSelectedData[algoSelect].getAlgoRunTilZero();
+ }
+ }
+ public boolean setAlgoRunTilZero(int algoRunTilZero) {
+ if (algoSelect < ALGOSELECT_MIN || algoSelect > ALGOSELECT_MAX) return false;
+ return algoSelectedData[algoSelect].setAlgoRunTilZero(algoRunTilZero);
+ }
+
+ int rssiFilterConfig = -1;
+ final int RSSIFILTERTYPE_INVALID = -1, RSSIFILTERTYPE_MIN = 0, RSSIFILTERTYPE_MAX = 2;
+ int rssiFilterType = RSSIFILTERTYPE_INVALID;
+ final int RSSIFILTEROPTION_INVALID = -1, RSSIFILTEROPTION_MIN = 0, RSSIFILTEROPTION_MAX = 4;
+ int rssiFilterOption = RSSIFILTEROPTION_INVALID;
+ public int getRssiFilterType() {
+ if (rssiFilterType < 0) getHST_INV_RSSI_FILTERING_CONFIG();
+ return rssiFilterType;
+ }
+ public int getRssiFilterOption() {
+ if (rssiFilterOption < 0) getHST_INV_RSSI_FILTERING_CONFIG();
+ return rssiFilterOption;
+ }
+ private boolean getHST_INV_RSSI_FILTERING_CONFIG() {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 7, 9, 0, 0, 0, 0};
+ return sendHostRegRequest(HostRegRequests.HST_INV_RSSI_FILTERING_CONFIG, false, msgBuffer);
+ }
+ public boolean setHST_INV_RSSI_FILTERING_CONFIG(int rssiFilterType, int rssiFilterOption) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 7, 9, 0, 0, 0, 0};
+ if (rssiFilterType < RSSIFILTERTYPE_MIN || rssiFilterType > RSSIFILTERTYPE_MAX)
+ rssiFilterType = mDefault.rssiFilterType;
+ if (rssiFilterOption < RSSIFILTEROPTION_MIN || matchType > RSSIFILTEROPTION_MAX)
+ rssiFilterOption = mDefault.rssiFilterOption;
+ if (this.rssiFilterType == rssiFilterType && this.rssiFilterOption == rssiFilterOption && sameCheck) return true;
+ msgBuffer[4] |= (byte) (rssiFilterType & 0xF);
+ msgBuffer[4] |= (byte) ((rssiFilterOption & 0xF) << 4);
+ this.rssiFilterType = rssiFilterType;
+ this.rssiFilterOption = rssiFilterOption;
+ boolean bValue = sendHostRegRequest(HostRegRequests.HST_INV_RSSI_FILTERING_CONFIG, true, msgBuffer);
+ if (false) getHST_INV_RSSI_FILTERING_CONFIG();
+ return bValue;
+ }
+
+ final int RSSIFILTERTHRESHOLD_INVALID = -1, RSSIFILTERTHRESHOLD_MIN = 0, RSSIFILTERTHRESHOLD_MAX = 0xFFFF;
+ int rssiFilterThreshold1 = RSSIFILTERTHRESHOLD_INVALID;
+ public int getRssiFilterThreshold1() {
+ if (rssiFilterThreshold1 < 0) getHST_INV_RSSI_FILTERING_THRESHOLD();
+ return rssiFilterThreshold1;
+ }
+ int rssiFilterThreshold2 = RSSIFILTERTHRESHOLD_INVALID;
+ public int getRssiFilterThreshold2() {
+ if (rssiFilterThreshold2 < 0) getHST_INV_RSSI_FILTERING_THRESHOLD();
+ return rssiFilterThreshold2;
+ }
+ private boolean getHST_INV_RSSI_FILTERING_THRESHOLD() {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 8, 9, 0, 0, 0, 0};
+ return sendHostRegRequest(HostRegRequests.HST_INV_RSSI_FILTERING_THRESHOLD, false, msgBuffer);
+ }
+ public boolean setHST_INV_RSSI_FILTERING_THRESHOLD(int rssiFilterThreshold1, int rssiFilterThreshold2) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 8, 9, 0, 0, 0, 0};
+ if (rssiFilterThreshold1 < RSSIFILTERTHRESHOLD_MIN || rssiFilterThreshold1 > RSSIFILTERTHRESHOLD_MAX)
+ rssiFilterThreshold1 = mDefault.rssiFilterThreshold;
+ if (rssiFilterThreshold2 < RSSIFILTERTHRESHOLD_MIN || rssiFilterThreshold2 > RSSIFILTERTHRESHOLD_MAX)
+ rssiFilterThreshold2 = mDefault.rssiFilterThreshold;
+ if (this.rssiFilterThreshold1 == rssiFilterThreshold1 && this.rssiFilterThreshold2 == rssiFilterThreshold2 && sameCheck) return true;
+ msgBuffer[4] |= (byte) (rssiFilterThreshold1 & 0xFF);
+ msgBuffer[5] |= (byte) ((rssiFilterThreshold1 >> 8) & 0xFF);
+ msgBuffer[6] |= (byte) (rssiFilterThreshold2 & 0xFF);
+ msgBuffer[7] |= (byte) ((rssiFilterThreshold2 >> 8) & 0xFF);
+ this.rssiFilterThreshold1 = rssiFilterThreshold1;
+ this.rssiFilterThreshold2 = rssiFilterThreshold2;
+ boolean bValue = sendHostRegRequest(HostRegRequests.HST_INV_RSSI_FILTERING_THRESHOLD, true, msgBuffer);
+ if (false) getHST_INV_RSSI_FILTERING_THRESHOLD();
+ return bValue;
+ }
+
+ final long RSSIFILTERCOUNT_INVALID = -1, RSSIFILTERCOUNT_MIN = 0, RSSIFILTERCOUNT_MAX = 1000000;
+ long rssiFilterCount = RSSIFILTERCOUNT_INVALID;
+ public long getRssiFilterCount() {
+ if (rssiFilterCount < 0) getHST_INV_RSSI_FILTERING_COUNT();
+ return rssiFilterCount;
+ }
+ private boolean getHST_INV_RSSI_FILTERING_COUNT() {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 9, 9, 0, 0, 0, 0};
+ return sendHostRegRequest(HostRegRequests.HST_INV_RSSI_FILTERING_THRESHOLD, false, msgBuffer);
+ }
+ public boolean setHST_INV_RSSI_FILTERING_COUNT(long rssiFilterCount) {
+ appendToLog("entry: rssiFilterCount = " + rssiFilterCount + ", this.rssiFilterCount = " + this.rssiFilterCount);
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 9, 9, 0, 0, 0, 0};
+ if (rssiFilterCount < RSSIFILTERCOUNT_MIN || rssiFilterCount > RSSIFILTERCOUNT_MAX)
+ rssiFilterCount = mDefault.rssiFilterCount;
+ appendToLog("rssiFilterCount 1 = " + rssiFilterCount + ", this.rssiFilterCount = " + this.rssiFilterCount);
+ if (this.rssiFilterCount == rssiFilterCount && sameCheck) return true;
+ appendToLog("rssiFilterCount 2 = " + rssiFilterCount + ", this.rssiFilterCount = " + this.rssiFilterCount);
+ msgBuffer[4] |= (byte) (rssiFilterCount & 0xFF);
+ msgBuffer[5] |= (byte) ((rssiFilterCount >> 8) & 0xFF);
+ msgBuffer[6] |= (byte) ((rssiFilterCount >> 16) & 0xFF);
+ msgBuffer[7] |= (byte) ((rssiFilterCount >> 24) & 0xFF);
+ this.rssiFilterCount = rssiFilterCount;
+ appendToLog("entering to sendHostRegRequest: rssiFilterCount = " + rssiFilterCount);
+ boolean bValue = sendHostRegRequest(HostRegRequests.HST_INV_RSSI_FILTERING_COUNT, true, msgBuffer);
+ appendToLog("after sendHostRegRequest: rssiFilterCount = " + rssiFilterCount);
+ return bValue;
+ }
+
+ final int MATCHENABLE_INVALID = -1; final int MATCHENABLE_MIN = 0; final int MATCHENABLE_MAX = 1;
+ int matchEnable = MATCHENABLE_INVALID;
+ public int getInvMatchEnable() {
+ getHST_INV_EPC_MATCH_CFG();
+ return matchEnable;
+ }
+ boolean setInvMatchEnable(int matchEnable) {
+ return setHST_INV_EPC_MATCH_CFG(matchEnable, this.matchType, this.matchLength, this.matchOffset);
+ }
+ public boolean setInvMatchEnable(int matchEnable, int matchType, int matchLength, int matchOffset) {
+ return setHST_INV_EPC_MATCH_CFG(matchEnable, matchType, matchLength, matchOffset);
+ }
+
+ final int MATCHTYPE_INVALID = -1; final int MATCHTYPE_MIN = 0; final int MATCHTYPE_MAX = 1;
+ int matchType = MATCHTYPE_INVALID;
+ public int getInvMatchType() {
+ getHST_INV_EPC_MATCH_CFG();
+ return matchType;
+ }
+
+ final int MATCHLENGTH_INVALID = 0; final int MATCHLENGTH_MIN = 0; final int MATCHLENGTH_MAX = 496;
+ int matchLength = MATCHLENGTH_INVALID;
+ public int getInvMatchLength() {
+ getHST_INV_EPC_MATCH_CFG();
+ return matchLength;
+ }
+
+ final int MATCHOFFSET_INVALID = -1; final int MATCHOFFSET_MIN = 0; final int MATCHOFFSET_MAX = 496;
+ int matchOffset = MATCHOFFSET_INVALID;
+ public int getInvMatchOffset() {
+ getHST_INV_EPC_MATCH_CFG();
+ return matchOffset;
+ }
+
+ private boolean getHST_INV_EPC_MATCH_CFG() {
+ if (matchEnable < MATCHENABLE_MIN || matchEnable > MATCHENABLE_MAX
+ || matchType < MATCHTYPE_MIN || matchType > MATCHTYPE_MAX
+ || matchLength < MATCHLENGTH_MIN || matchLength > MATCHLENGTH_MAX
+ || matchOffset < MATCHOFFSET_MIN || matchOffset > MATCHOFFSET_MAX
+ ) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 0x11, 9, 0, 0, 0, 0};
+ return sendHostRegRequest(HostRegRequests.HST_INV_EPC_MATCH_CFG, false, msgBuffer);
+ } else {
+ return false;
+ }
+ }
+ private boolean setHST_INV_EPC_MATCH_CFG(int matchEnable, int matchType, int matchLength, int matchOffset) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 0x11, 9, 0, 0, 0, 0};
+ if (matchEnable < MATCHENABLE_MIN || matchEnable > MATCHENABLE_MAX)
+ matchEnable = mDefault.matchEnable;
+ if (matchType < MATCHTYPE_MIN || matchType > MATCHTYPE_MAX)
+ matchType = mDefault.matchType;
+ if (matchLength < MATCHLENGTH_MIN || matchLength > MATCHLENGTH_MAX)
+ matchLength = mDefault.matchLength;
+ if (matchOffset < MATCHOFFSET_MIN || matchOffset > MATCHOFFSET_MAX)
+ matchOffset = mDefault.matchOffset;
+ if (this.matchEnable == matchEnable && this.matchType == matchType && this.matchLength == matchLength && this.matchOffset == matchOffset && sameCheck) return true;
+ if (matchEnable != 0) {
+ msgBuffer[4] |= 0x01;
+ }
+ if (matchType != 0) {
+ msgBuffer[4] |= 0x02;
+ }
+ msgBuffer[4] |= (byte) ((matchLength % 64) << 2);
+ msgBuffer[5] |= (byte) ((matchLength / 64));
+ msgBuffer[5] |= (byte) ((matchOffset % 32) << 3);
+ msgBuffer[6] |= (byte) (matchOffset / 32);
+ this.matchEnable = matchEnable;
+ this.matchType = matchType;
+ this.matchLength = matchLength;
+ this.matchOffset = matchOffset;
+ return sendHostRegRequest(HostRegRequests.HST_INV_EPC_MATCH_CFG, true, msgBuffer);
+ }
+
+ byte[] invMatchData0_63; int invMatchDataReady = 0;
+ public String getInvMatchData() {
+ int length = matchLength;
+ String strValue = "";
+ for (int i = 0; i < 16; i++) {
+ if (length > 0) {
+ if ((invMatchDataReady & (0x01 << i)) == 0) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 0x12, 9, 0, 0, 0, 0};
+ msgBuffer[2] += i;
+ sendHostRegRequest(HostRegRequests.HST_INV_EPCDAT_0_3, false, msgBuffer);
+
+ strValue = null;
+ break;
+ } else {
+ for (int j = 0; j < 4; j++) {
+ strValue += String.format("%02X", invMatchData0_63[i * 4 + j]);
+ }
+ }
+ length -= 32;
+ }
+ }
+ return strValue;
+ }
+ public boolean setInvMatchData(String matchData) {
+ int length = matchData.length();
+ for (int i = 0; i < 16; i++) {
+ if (length > 0) {
+ length -= 8;
+
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 0x12, 9, 0, 0, 0, 0};
+ String hexString = "0123456789ABCDEF";
+ for (int j = 0; j < 8; j++) {
+ if (i * 8 + j + 1 <= matchData.length()) {
+ String subString = matchData.substring(i * 8 + j, i * 8 + j + 1).toUpperCase();
+ int k = 0;
+ for (k = 0; k < 16; k++) {
+ if (subString.matches(hexString.substring(k, k + 1))) {
+ break;
+ }
+ }
+ if (k == 16) return false;
+ if ((j / 2) * 2 == j) {
+ msgBuffer[4 + j / 2] |= (byte) (k << 4);
+ } else {
+ msgBuffer[4 + j / 2] |= (byte) (k);
+ }
+ }
+ }
+ msgBuffer[2] = (byte) ((msgBuffer[2] & 0xFF) + i);
+ if (sendHostRegRequest(HostRegRequests.HST_INV_EPCDAT_0_3, true, msgBuffer) == false)
+ return false;
+ else {
+ invMatchDataReady |= (0x01 << i);
+ System.arraycopy(msgBuffer, 4, invMatchData0_63, i * 4, 4); //appendToLog("Data=" + byteArrayToString(mRx000Setting.invMatchData0_63));
+// appendToLog("invMatchDataReady=" + Integer.toString(mRx000Setting.invMatchDataReady, 16) + ", message=" + byteArrayToString(msgBuffer));
+ }
+ }
+ }
+ return true;
+ }
+
+ //Tag access block parameters
+ boolean accessVerfiy;
+ final int ACCRETRY_INVALID = -1; final int ACCRETRY_MIN = 0; final int ACCRETRY_MAX = 7;
+ int accessRetry = ACCRETRY_INVALID;
+ int getAccessRetry() {
+ if (accessRetry < ACCRETRY_MIN || accessRetry > ACCRETRY_MAX) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 1, (byte) 0x0A, 0, 0, 0, 0};
+ sendHostRegRequest(HostRegRequests.HST_TAGACC_DESC_CFG, false, msgBuffer);
+ }
+ return accessRetry;
+ }
+ public boolean setAccessRetry(boolean accessVerfiy, int accessRetry) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 1, 0x0A, 0, 0, 0, 0};
+ if (DEBUG) appendToLog("setAccessRetry[" + accessVerfiy + ", " + accessRetry + "] with tagRead = " + tagRead + ", sameCheck = " + sameCheck + ", old accessVerfiy = " + this.accessVerfiy + ", accessRetry = " + this.accessRetry);
+ if (accessRetry < ACCRETRY_MIN || accessRetry > ACCRETRY_MAX)
+ accessRetry = mDefault.accessRetry;
+ if (this.accessVerfiy == accessVerfiy && this.accessRetry == accessRetry && sameCheck) return true;
+ msgBuffer[4] |= (byte) (accessRetry << 1);
+ if (accessVerfiy) msgBuffer[4] |= 0x01;
+ this.accessVerfiy = accessVerfiy;
+ this.accessRetry = accessRetry;
+ return sendHostRegRequest(HostRegRequests.HST_TAGACC_DESC_CFG, true, msgBuffer);
+ }
+
+ final int ACCBANK_INVALID = -1; final int ACCBANK_MIN = 0; final int ACCBANK_MAX = 3;
+ int accessBank = ACCBANK_INVALID; int accessBank2 = ACCBANK_INVALID;
+ int getAccessBank() {
+ if (accessBank < ACCBANK_MIN || accessBank > ACCBANK_MAX) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 2, (byte) 0x0A, 0, 0, 0, 0};
+ sendHostRegRequest(HostRegRequests.HST_TAGACC_BANK, false, msgBuffer);
+ }
+ return accessBank;
+ }
+ public boolean setAccessBank(int accessBank) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 2, 0x0A, 0, 0, 0, 0};
+ if (DEBUG) appendToLog("setAccessBank[" + accessBank + "] with tagRead = " + tagRead + ", sameCheck = " + sameCheck + ", old accessBank = " + this.accessBank);
+ if (accessBank < ACCBANK_MIN || accessBank > ACCBANK_MAX)
+ accessBank = mDefault.accessBank;
+ if (this.accessBank == accessBank && this.accessBank2 == 0 && sameCheck) return true;
+ msgBuffer[4] = (byte) (accessBank & 0x03);
+ this.accessBank = accessBank; this.accessBank2 = 0;
+ return sendHostRegRequest(HostRegRequests.HST_TAGACC_BANK, true, msgBuffer);
+ }
+ public boolean setAccessBank(int accessBank, int accessBank2) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 2, 0x0A, 0, 0, 0, 0};
+ if (DEBUG) appendToLog("setAccessBank[" + accessBank + ", " + accessBank2 + "] with tagRead = " + tagRead + ", sameCheck = " + sameCheck + ", old accessBank = " + this.accessBank + ", " + this.accessBank2);
+ if (tagRead != 2) accessBank2 = 0;
+ if (accessBank < ACCBANK_MIN || accessBank > ACCBANK_MAX)
+ accessBank = mDefault.accessBank;
+ if (accessBank2 < ACCBANK_MIN || accessBank2 > ACCBANK_MAX)
+ accessBank2 = mDefault.accessBank2;
+ if (this.accessBank == accessBank && this.accessBank2 == accessBank2 && sameCheck) return true;
+ msgBuffer[4] = (byte) (accessBank & 0x03);
+ msgBuffer[4] |= (byte) ((accessBank2 & 0x03) << 2);
+ this.accessBank = accessBank; this.accessBank2 = accessBank2;
+ return sendHostRegRequest(HostRegRequests.HST_TAGACC_BANK, true, msgBuffer);
+ }
+
+ final int ACCOFFSET_INVALID = -1; final int ACCOFFSET_MIN = 0; final int ACCOFFSET_MAX = 0xFFFF;
+ int accessOffset = ACCOFFSET_INVALID; int accessOffset2 = ACCOFFSET_INVALID;
+ int getAccessOffset() {
+ if (accessOffset < ACCOFFSET_MIN || accessOffset > ACCOFFSET_MAX) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 3, (byte) 0x0A, 0, 0, 0, 0};
+ sendHostRegRequest(HostRegRequests.HST_TAGACC_PTR, false, msgBuffer);
+ }
+ return accessOffset;
+ }
+ public boolean setAccessOffset(int accessOffset) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 3, 0x0A, 0, 0, 0, 0};
+ if (false) appendToLog("setAccessOffset[" + accessOffset + "] with tagRead = " + tagRead + ", sameCheck = " + sameCheck + ", old accessOffset = " + this.accessOffset);
+ if (accessOffset < ACCOFFSET_MIN || accessOffset > ACCOFFSET_MAX)
+ accessOffset = mDefault.accessOffset;
+ if (this.accessOffset == accessOffset && this.accessOffset2 == 0 && sameCheck) return true;
+ msgBuffer[4] = (byte) (accessOffset & 0xFF);
+ msgBuffer[5] = (byte) ((accessOffset >> 8) & 0xFF);
+ msgBuffer[6] = (byte) ((accessOffset >> 16) & 0xFF);
+ msgBuffer[7] = (byte) ((accessOffset >> 24) & 0xFF);
+ this.accessOffset = accessOffset; this.accessOffset2 = 0;
+ return sendHostRegRequest(HostRegRequests.HST_TAGACC_PTR, true, msgBuffer);
+ }
+ public boolean setAccessOffset(int accessOffset, int accessOffset2) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 3, 0x0A, 0, 0, 0, 0};
+ if (false) appendToLog("setAccessOffset[" + accessOffset + ", " + accessOffset2 + "] with tagRead = " + tagRead + ", sameCheck = " + sameCheck + ", old accessOffset = " + this.accessOffset + ", " + this.accessOffset2);
+ if (tagRead != 2) accessOffset2 = 0;
+ if (accessOffset < ACCOFFSET_MIN || accessOffset > ACCOFFSET_MAX)
+ accessOffset = mDefault.accessOffset;
+ if (accessOffset2 < ACCOFFSET_MIN || accessOffset2 > ACCOFFSET_MAX)
+ accessOffset2 = mDefault.accessOffset2;
+ if (this.accessOffset == accessOffset && this.accessOffset2 == accessOffset2 && sameCheck) return true;
+ msgBuffer[4] = (byte) (accessOffset & 0xFF);
+ msgBuffer[5] = (byte) ((accessOffset >> 8) & 0xFF);
+ msgBuffer[6] = (byte) (accessOffset2 & 0xFF);
+ msgBuffer[7] = (byte) ((accessOffset2 >> 8) & 0xFF);
+ this.accessOffset = accessOffset; this.accessOffset2 = accessOffset2;
+ return sendHostRegRequest(HostRegRequests.HST_TAGACC_PTR, true, msgBuffer);
+ }
+
+ final int ACCCOUNT_INVALID = -1; final int ACCCOUNT_MIN = 0; final int ACCCOUNT_MAX = 255;
+ int accessCount = ACCCOUNT_INVALID; int accessCount2 = ACCCOUNT_INVALID;
+ public int getAccessCount() {
+ if (accessCount < ACCCOUNT_MIN || accessCount > ACCCOUNT_MAX) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 4, (byte) 0x0A, 0, 0, 0, 0};
+ sendHostRegRequest(HostRegRequests.HST_TAGACC_CNT, false, msgBuffer);
+ }
+ return accessCount;
+ }
+ public boolean setAccessCount(int accessCount) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 4, 0x0A, 0, 0, 0, 0};
+ if (DEBUG) appendToLog("BtDataOut: SetAccessCount[" + accessCount + "] with tagRead = " + tagRead + ", sameCheck = " + sameCheck + ", old accessCount = " + this.accessCount);
+ if (accessCount < ACCCOUNT_MIN || accessCount > ACCCOUNT_MAX)
+ accessCount = mDefault.accessCount;
+ if ((this.accessCount == accessCount || accessCount == -1) && this.accessCount2 == 0 && sameCheck) return true;
+ msgBuffer[4] = (byte) (accessCount & 0xFF);
+ this.accessCount = accessCount; this.accessCount2 = 0;
+ return sendHostRegRequest(HostRegRequests.HST_TAGACC_CNT, true, msgBuffer);
+ }
+ public boolean setAccessCount(int accessCount, int accessCount2) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 4, 0x0A, 0, 0, 0, 0};
+ if (DEBUG) appendToLog("setAccessCount[" + accessCount + ", " + accessCount2 + "] with tagRead = " + tagRead + ", sameCheck = " + sameCheck + ", old accessCount = " + this.accessCount + ", " + this.accessCount2);
+ if (tagRead != 2) accessCount2 = 0;
+ if (accessCount < ACCCOUNT_MIN || accessCount > ACCCOUNT_MAX)
+ accessCount = mDefault.accessCount;
+ if (accessCount2 < ACCCOUNT_MIN || accessCount2 > ACCCOUNT_MAX)
+ accessCount2 = mDefault.accessCount2;
+ if (this.accessCount == accessCount && this.accessCount2 == accessCount2 && sameCheck) return true;
+ msgBuffer[4] = (byte) (accessCount & 0xFF);
+ msgBuffer[5] = (byte) (accessCount2 & 0xFF);
+ this.accessCount = accessCount; this.accessCount2 = accessCount2;
+ return sendHostRegRequest(HostRegRequests.HST_TAGACC_CNT, true, msgBuffer);
+ }
+
+ final int ACCLOCKACTION_INVALID = -1; final int ACCLOCKACTION_MIN = 0; final int ACCLOCKACTION_MAX = 0x3FF;
+ int accessLockAction = ACCLOCKACTION_INVALID;
+ int getAccessLockAction() {
+ if (accessLockAction < ACCLOCKACTION_MIN || accessLockAction > ACCLOCKACTION_MAX)
+ getHST_TAGACC_LOCKCFG();
+ return accessLockAction;
+ }
+ boolean setAccessLockAction(int accessLockAction) {
+ return setAccessLockAction(accessLockAction, accessLockMask);
+ }
+
+ final int ACCLOCKMASK_INVALID = -1; final int ACCLOCKMASK_MIN = 0; final int ACCLOCKMASK_MAX = 0x3FF;
+ int accessLockMask = ACCLOCKMASK_INVALID;
+ int getAccessLockMask() {
+ if (accessLockMask < ACCLOCKMASK_MIN || accessLockMask > ACCLOCKMASK_MAX)
+ getHST_TAGACC_LOCKCFG();
+ return accessLockMask;
+ }
+ boolean setAccessLockMask(int accessLockMask) {
+ return setAccessLockAction(accessLockAction, accessLockMask);
+ }
+
+ boolean getHST_TAGACC_LOCKCFG() {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 5, (byte) 0x0A, 0, 0, 0, 0};
+ return sendHostRegRequest(HostRegRequests.HST_TAGACC_LOCKCFG, false, msgBuffer);
+ }
+ public boolean setAccessLockAction(int accessLockAction, int accessLockMask) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 5, 0x0A, 0, 0, 0, 0};
+ if (accessLockAction < ACCLOCKACTION_MIN || accessLockAction > ACCLOCKACTION_MAX)
+ accessLockAction = mDefault.accessLockAction;
+ if (accessLockMask < ACCLOCKMASK_MIN || accessLockMask > ACCLOCKMASK_MAX)
+ accessLockMask = mDefault.accessLockMask;
+ if (this.accessLockAction == accessLockAction && this.accessLockMask == accessLockMask && sameCheck) return true;
+ msgBuffer[4] = (byte) (accessLockAction & 0xFF);
+ msgBuffer[5] |= (byte) ((accessLockAction & 0x3FF) >> 8);
+
+ msgBuffer[5] |= (byte) ((accessLockMask & 0x3F) << 2);
+ msgBuffer[6] |= (byte) ((accessLockMask & 0x3FF) >> 6);
+ this.accessLockAction = accessLockAction;
+ this.accessLockMask = accessLockMask;
+ return sendHostRegRequest(HostRegRequests.HST_TAGACC_LOCKCFG, true, msgBuffer);
+ }
+
+ final int ACCPWD_INVALID = 0; final long ACCPWD_MIN = 0; final long ACCPWD_MAX = 0x0FFFFFFFF;
+ String stringAccessPasword = "00000000";
+ public boolean setRx000AccessPassword(String password) {
+ //appendToLog("BtDataOut: setRx000AccessPassword with password = " + password + ", stringAccessPasword = " + stringAccessPasword);
+ if (stringAccessPasword.matches(password) && sameCheck) return true;
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 6, (byte) 0x0A, 0, 0, 0, 0};
+ if (password == null) password = "";
+ String hexString = "0123456789ABCDEF";
+ for (int j = 0; j < 16; j++) {
+ if (j + 1 <= password.length()) {
+ String subString = password.substring(j, j + 1).toUpperCase();
+ int k = 0;
+ for (k = 0; k < 16; k++) {
+ if (subString.matches(hexString.substring(k, k + 1))) {
+ break;
+ }
+ }
+ if (k == 16) return false;
+ if ((j / 2) * 2 == j) {
+ msgBuffer[7 - j / 2] |= (byte) (k << 4);
+ } else {
+ msgBuffer[7 - j / 2] |= (byte) (k);
+ }
+ }
+ }
+ boolean retValue = sendHostRegRequest(HostRegRequests.HST_TAGACC_ACCPWD, true, msgBuffer);
+ if (DEBUG) appendToLog("sendHostRegRequest(): retValue = " + retValue);
+ if (retValue) stringAccessPasword = password;
+ return retValue;
+ }
+
+ public boolean setRx000KillPassword(String password) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 7, (byte) 0x0A, 0, 0, 0, 0};
+ String hexString = "0123456789ABCDEF";
+ for (int j = 0; j < 16; j++) {
+ if (j + 1 <= password.length()) {
+ String subString = password.substring(j, j + 1).toUpperCase();
+ int k = 0;
+ for (k = 0; k < 16; k++) {
+ if (subString.matches(hexString.substring(k, k + 1))) {
+ break;
+ }
+ }
+ if (k == 16) return false;
+ if ((j / 2) * 2 == j) {
+ msgBuffer[7 - j / 2] |= (byte) (k << 4);
+ } else {
+ msgBuffer[7 - j / 2] |= (byte) (k);
+ }
+ }
+ }
+ boolean retValue = sendHostRegRequest(HostRegRequests.HST_TAGACC_KILLPWD, true, msgBuffer);
+ if (DEBUG) appendToLog("sendHostRegRequest(): retValue = " + retValue);
+ return retValue;
+ }
+
+ final int ACCWRITEDATSEL_INVALID = -1; final int ACCWRITEDATSEL_MIN = 0; final int ACCWRITEDATSEL_MAX = 7;
+ int accessWriteDataSelect = ACCWRITEDATSEL_INVALID;
+ int getAccessWriteDataSelect() {
+ if (accessWriteDataSelect < ACCWRITEDATSEL_MIN || accessWriteDataSelect > ACCWRITEDATSEL_MAX) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 8, (byte) 0x0A, 0, 0, 0, 0};
+ sendHostRegRequest(HostRegRequests.HST_TAGWRDAT_SEL, false, msgBuffer);
+ }
+ return accessWriteDataSelect;
+ }
+ boolean setAccessWriteDataSelect(int accessWriteDataSelect) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 8, 0x0A, 0, 0, 0, 0};
+ if (accessWriteDataSelect < ACCWRITEDATSEL_MIN || accessWriteDataSelect > ACCWRITEDATSEL_MAX)
+ accessWriteDataSelect = mDefault.accessWriteDataSelect;
+ if (this.accessWriteDataSelect == accessWriteDataSelect && sameCheck) return true;
+ accWriteDataReady = 0;
+ msgBuffer[4] = (byte) (accessWriteDataSelect & 0x07);
+ this.accessWriteDataSelect = accessWriteDataSelect;
+ return sendHostRegRequest(HostRegRequests.HST_TAGWRDAT_SEL, true, msgBuffer);
+ }
+
+ byte[] accWriteData0_63; int accWriteDataReady = 0;
+ String getAccessWriteData() {
+ int length = accessCount;
+ if (length > 32) {
+ length = 32;
+ }
+ String strValue = "";
+ for (int i = 0; i < 32; i++) {
+ if (length > 0) {
+ if ((accWriteDataReady & (0x01 << i)) == 0) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 9, (byte) 0x0A, 0, 0, 0, 0};
+ msgBuffer[2] += i;
+ sendHostRegRequest(HostRegRequests.HST_TAGWRDAT_0, false, msgBuffer);
+
+ strValue = null;
+ break;
+ } else {
+ for (int j = 0; j < 4; j++) {
+ strValue += String.format("%02X", accWriteData0_63[i * 4 + j]);
+ }
+ }
+ length -= 2;
+ }
+ }
+ return strValue;
+ }
+
+ public boolean setAccessWriteData(String dataInput) {
+ dataInput = dataInput.trim();
+ int writeBufLength = 16 * 2; //16
+ int wrieByteSize = 4; //8
+ int length = dataInput.length(); appendToLog("length = " + length);
+ if (length > wrieByteSize * writeBufLength) { appendToLog("1"); return false; }
+ for (int i = 0; i < writeBufLength; i++) {
+ if (length > 0) {
+ length -= wrieByteSize;
+ if ((i / 16) * 16 == i) {
+ if (true) {
+ if (setAccessWriteDataSelect(i/16) == false) return false;
+ }
+ else {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 8, (byte) 0x0A, 0, 0, 0, 0};
+ msgBuffer[4] = (byte) (i / 16);
+ if (sendHostRegRequest(HostRegRequests.HST_TAGWRDAT_SEL, true, msgBuffer) == false) {
+ appendToLog("23");
+ return false;
+ }
+ }
+ }
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 9, (byte) 0x0A, 0, 0, 0, 0};
+ String hexString = "0123456789ABCDEF";
+ for (int j = 0; j < wrieByteSize; j++) {
+// if (i * wrieByteSize + j + 1 <= dataInput.length()) {
+ appendToLog("dataInput = " + dataInput + ", i = " + i + ", wrieByteSize = " + wrieByteSize + ", j = " + j);
+ if (i * wrieByteSize + j >= dataInput.length()) break;
+ String subString = dataInput.substring(i * wrieByteSize + j, i * wrieByteSize + j + 1).toUpperCase();
+ appendToLog("subString = " + subString);
+ if (DEBUG) appendToLog(subString);
+ int k = 0;
+ for (k = 0; k < 16; k++) {
+ if (subString.matches(hexString.substring(k, k + 1))) {
+ break;
+ }
+ }
+ if (k == 16) { appendToLog("2: i= " + i + ", j=" + j + ", subString = " + subString); return false; }
+ if ((j / 2) * 2 == j) {
+ msgBuffer[5- j / 2] |= (byte) (k << 4);
+ } else {
+ msgBuffer[5 - j / 2] |= (byte) (k);
+ }
+// }
+ }
+ appendToLog("complete 4 bytes: " + byteArrayToString(msgBuffer));
+ msgBuffer[2] = (byte) ((msgBuffer[2] & 0xFF) + (i % 16));
+ if (wrieByteSize == 4) {
+ msgBuffer[6] = (byte)(i);
+ }
+ byte[] debugBuffer = new byte[4];
+ int k = 0;
+ for (; k < 4; k++) {
+ debugBuffer[k] = accWriteData0_63[i * 4 + k];
+ if (accWriteData0_63[i * 4 + k] != msgBuffer[7 - k]) break;
+ }
+ if (k != 4) {
+ appendToLog("BtDataOut: RfidReaderChipR2000.setAccessWriteData msgBuffer = " + byteArrayToString(msgBuffer) + ", debugBuffer = " + byteArrayToString(debugBuffer));
+ if (sendHostRegRequest(HostRegRequests.HST_TAGWRDAT_0, true, msgBuffer) == false) {
+ appendToLog("3");
+ return false;
+ } else {
+ rx000Setting.accWriteDataReady |= (0x01 << i);
+ if (DEBUG) appendToLog("accWriteReady=" + accWriteDataReady);
+ for (int k1 = 0; k1 < 4; k1++) {
+ accWriteData0_63[i * 4 + k1] = msgBuffer[7 - k1];
+ }
+ if (DEBUG) appendToLog("Data=" + byteArrayToString(accWriteData0_63));
+ }
+ }
+ } else break;
+ }
+ return true;
+ }
+
+ //RFTC block paramters
+ final int PROFILE_INVALID = -1; final int PROFILE_MIN = 0; final int PROFILE_MAX = 5; //profile 4 and 5 are custom profiles.
+ int currentProfile = PROFILE_INVALID;
+ public int getCurrentProfile() {
+ if (antennaSelect < ANTSLECT_MIN || antennaSelect > ANTSELECT_MAX) {
+ return ANTSELECT_INVALID;
+ } else {
+ if (currentProfile < PROFILE_MIN || currentProfile > PROFILE_MAX) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 0x60, 0x0B, 0, 0, 0, 0};
+ sendHostRegRequest(HostRegRequests.HST_RFTC_CURRENT_PROFILE, false, msgBuffer);
+ }
+ return currentProfile;
+ }
+ }
+
+ public boolean setCurrentProfile(int currentProfile) {
+ if (antennaSelect < ANTSLECT_MIN || antennaSelect > ANTSELECT_MAX) return false;
+ else {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 0x60, 0x0B, 0, 0, 0, 0};
+ if (currentProfile < PROFILE_MIN || currentProfile > PROFILE_MAX)
+ currentProfile = mDefault.currentProfile;
+ if (this.currentProfile == currentProfile && sameCheck) return true;
+ msgBuffer[4] = (byte) (currentProfile);
+ this.currentProfile = currentProfile;
+ return sendHostRegRequest(HostRegRequests.HST_RFTC_CURRENT_PROFILE, true, msgBuffer);
+ }
+ }
+
+ final int COUNTRYENUM_INVALID = -1; final int COUNTRYENUM_MIN = 1; final int COUNTRYENUM_MAX = 109;
+ final int COUNTRYCODE_INVALID = -1; final int COUNTRYCODE_MIN = 1; final int COUNTRYCODE_MAX = 9;
+ int countryEnumOem = COUNTRYENUM_INVALID; int countryEnum = COUNTRYENUM_INVALID; int countryCode = COUNTRYCODE_INVALID; // OemAddress = 0x02
+ String modelCode = null;
+
+ final int FREQCHANSEL_INVALID = -1; final int FREQCHANSEL_MIN = 0; final int FREQCHANSEL_MAX = 49;
+ int freqChannelSelect = FREQCHANSEL_INVALID;
+ public int getFreqChannelSelect() {
+ appendToLog("freqChannelSelect = " + freqChannelSelect);
+ if (freqChannelSelect < FREQCHANSEL_MIN || freqChannelSelect > FREQCHANSEL_MAX) {
+ {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 1, 0x0C, 0, 0, 0, 0};
+ sendHostRegRequest(HostRegRequests.HST_RFTC_FRQCH_SEL, false, msgBuffer);
+ }
+ }
+ return freqChannelSelect;
+ }
+ public boolean setFreqChannelSelect(int freqChannelSelect) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 1, 0x0C, 0, 0, 0, 0};
+ if (freqChannelSelect < FREQCHANSEL_MIN || freqChannelSelect > FREQCHANSEL_MAX) freqChannelSelect = mDefault.freqChannelSelect;
+ //if (this.freqChannelSelect == freqChannelSelect && sameCheck) return true;
+ appendToLog("freqChannelSelect = " + freqChannelSelect);
+ msgBuffer[4] = (byte) (freqChannelSelect);
+ this.freqChannelSelect = freqChannelSelect;
+ freqChannelSelect = FREQCHANCONFIG_INVALID; freqPllMultiplier = FREQPLLMULTIPLIER_INVALID;
+ return sendHostRegRequest(HostRegRequests.HST_RFTC_FRQCH_SEL, true, msgBuffer);
+ }
+
+ final int FREQCHANCONFIG_INVALID = -1; final int FREQCHANCONFIG_MIN = 0; final int FREQCHANCONFIG_MAX = 1;
+ int freqChannelConfig = FREQCHANCONFIG_INVALID;
+ public int getFreqChannelConfig() {
+ if (freqChannelConfig < FREQCHANCONFIG_MIN || freqChannelConfig > FREQCHANCONFIG_MAX) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 2, 0x0C, 0, 0, 0, 0};
+ sendHostRegRequest(HostRegRequests.HST_RFTC_FRQCH_CFG, false, msgBuffer);
+ }
+ return freqChannelConfig;
+ }
+ public boolean setFreqChannelConfig(boolean on) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 2, 0x0C, 0, 0, 0, 0};
+ boolean onCurrent = false;
+ if (freqChannelConfig != 0) onCurrent = true;
+// if (onCurrent == on && sameCheck) return true;
+ if (on) {
+ msgBuffer[4] = 1;
+ freqChannelConfig = 1;
+ } else {
+ freqChannelConfig = 0;
+ }
+ return sendHostRegRequest(HostRegRequests.HST_RFTC_FRQCH_CFG, true, msgBuffer);
+ }
+
+ final int FREQPLLMULTIPLIER_INVALID = -1;
+ int freqPllMultiplier = FREQPLLMULTIPLIER_INVALID;
+ int getFreqPllMultiplier() {
+ if (freqPllMultiplier == FREQPLLMULTIPLIER_INVALID) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 3, 0x0C, 0, 0, 0, 0};
+ sendHostRegRequest(HostRegRequests.HST_RFTC_FRQCH_DESC_PLLDIVMULT, false, msgBuffer);
+ }
+ return freqPllMultiplier;
+ }
+ public boolean setFreqPllMultiplier(int freqPllMultiplier) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 3, 0x0C, 0, 0, 0, 0};
+ msgBuffer[4] = (byte)(freqPllMultiplier & 0xFF);
+ msgBuffer[5] = (byte)((freqPllMultiplier >> 8) & 0xFF);
+ msgBuffer[6] = (byte)((freqPllMultiplier >> 16) & 0xFF);
+ msgBuffer[7] = (byte)((freqPllMultiplier >> 24) & 0xFF);
+ this.freqPllMultiplier = freqPllMultiplier;
+ return sendHostRegRequest(HostRegRequests.HST_RFTC_FRQCH_DESC_PLLDIVMULT, true, msgBuffer);
+ }
+
+ final int FREQPLLDAC_INVALID = -1;
+ int freqPllDac = FREQPLLDAC_INVALID;
+ int getFreqPllDac() {
+ if (freqPllDac == FREQPLLDAC_INVALID) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 4, 0x0C, 0, 0, 0, 0};
+ sendHostRegRequest(HostRegRequests.HST_RFTC_FRQCH_DESC_PLLDACCTL, false, msgBuffer);
+ }
+ return freqPllDac;
+ }
+
+ boolean setFreqChannelOverride(int freqStart) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 8, 0x0C, 0, 0, 0, 0};
+ msgBuffer[4] = (byte)(freqStart & 0xFF);
+ msgBuffer[5] = (byte)((freqStart >> 8) & 0xFF);
+ msgBuffer[6] = (byte)((freqStart >> 16) & 0xFF);
+ msgBuffer[7] = (byte)((freqStart >> 24) & 0xFF);
+ return sendHostRegRequest(HostRegRequests.HST_RFTC_FRQCH_CMDSTART, true, msgBuffer);
+ }
+ }
+ class AntennaSelectedData {
+ AntennaSelectedData(boolean set_default_setting, int default_setting_type) {
+ if (default_setting_type < 0) default_setting_type = 0;
+ if (default_setting_type > 5) default_setting_type = 5;
+ mDefault = new AntennaSelectedData_default(default_setting_type);
+ if (false && set_default_setting) {
+ antennaEnable = mDefault.antennaEnable;
+ antennaInventoryMode = mDefault.antennaInventoryMode;
+ antennaLocalAlgo = mDefault.antennaLocalAlgo;
+ antennaLocalStartQ = mDefault.antennaLocalStartQ;
+ antennaProfileMode = mDefault.antennaProfileMode;
+ antennaLocalProfile = mDefault.antennaLocalProfile;
+ antennaFrequencyMode = mDefault.antennaFrequencyMode;
+ antennaLocalFrequency = mDefault.antennaLocalFrequency;
+ antennaStatus = mDefault.antennaStatus;
+ antennaDefine = mDefault.antennaDefine;
+ antennaDwell = mDefault.antennaDwell;
+ antennaPower = mDefault.antennaPower; appendToLog("antennaPower is set to default " + antennaPower);
+ antennaInvCount = mDefault.antennaInvCount;
+ }
+ }
+
+ class AntennaSelectedData_default {
+ AntennaSelectedData_default(int set_default_setting) {
+ antennaEnable = mDefaultArray.antennaEnable[set_default_setting];
+ antennaInventoryMode = mDefaultArray.antennaInventoryMode[set_default_setting];
+ antennaLocalAlgo = mDefaultArray.antennaLocalAlgo[set_default_setting];
+ antennaLocalStartQ = mDefaultArray.antennaLocalStartQ[set_default_setting];
+ antennaProfileMode = mDefaultArray.antennaProfileMode[set_default_setting];
+ antennaLocalProfile = mDefaultArray.antennaLocalProfile[set_default_setting];
+ antennaFrequencyMode = mDefaultArray.antennaFrequencyMode[set_default_setting];
+ antennaLocalFrequency = mDefaultArray.antennaLocalFrequency[set_default_setting];
+ antennaStatus = mDefaultArray.antennaStatus[set_default_setting];
+ antennaDefine = mDefaultArray.antennaDefine[set_default_setting];
+ antennaDwell = mDefaultArray.antennaDwell[set_default_setting];
+ antennaPower = mDefaultArray.antennaPower[set_default_setting];
+ antennaInvCount = mDefaultArray.antennaInvCount[set_default_setting];
+ }
+
+ int antennaEnable;
+ int antennaInventoryMode;
+ int antennaLocalAlgo;
+ int antennaLocalStartQ;
+ int antennaProfileMode;
+ int antennaLocalProfile;
+ int antennaFrequencyMode;
+ int antennaLocalFrequency;
+ int antennaStatus;
+ int antennaDefine;
+ long antennaDwell;
+ long antennaPower;
+ long antennaInvCount;
+ }
+ AntennaSelectedData_default mDefault;
+
+ private class AntennaSelectedData_defaultArray { //0 for invalid default, 1 for 0, 2 for 1 to 3, 3 for 4 to 7, 4 for 8 to 11, 5 for 12 to 15
+ int[] antennaEnable = { -1, 1, 0, 0, 0, 0 };
+ int[] antennaInventoryMode = { -1, 0, 0, 0, 0, 0 };
+ int[] antennaLocalAlgo = { -1, 0, 0, 0, 0, 0 };
+ int[] antennaLocalStartQ = { -1, 0, 0, 0, 0, 0 };
+ int[] antennaProfileMode = { -1, 0, 0, 0, 0, 0 };
+ int[] antennaLocalProfile = { -1, 0, 0, 0, 0, 0 };
+ int[] antennaFrequencyMode = { -1, 0, 0, 0, 0, 0 };
+ int[] antennaLocalFrequency = { -1, 0, 0, 0, 0, 0 };
+ int[] antennaStatus = { -1, 0, 0, 0, 0, 0 };
+ int[] antennaDefine = { -1, 0, 0, 1, 2, 3 };
+ long[] antennaDwell = { -1, 2000, 2000, 2000, 2000, 2000 };
+ long[] antennaPower = { -1, 300, 0, 0, 0, 0 };
+ long[] antennaInvCount = { -1, 8192, 8192, 8192, 8192, 8192 };
+ }
+ AntennaSelectedData_defaultArray mDefaultArray = new AntennaSelectedData_defaultArray();
+
+ final int ANTENABLE_INVALID = -1; final int ANTENABLE_MIN = 0; final int ANTENABLE_MAX = 1;
+ int antennaEnable = ANTENABLE_INVALID;
+ int getAntennaEnable() {
+ if (antennaEnable < ANTENABLE_MIN || antennaEnable > ANTENABLE_MAX)
+ getHST_ANT_DESC_CFG();
+ return antennaEnable;
+ }
+ boolean setAntennaEnable(int antennaEnable) {
+ return setAntennaEnable(antennaEnable, antennaInventoryMode, antennaLocalAlgo, antennaLocalStartQ,
+ antennaProfileMode, antennaLocalProfile, antennaFrequencyMode, antennaLocalFrequency);
+ }
+
+ final int ANTINVMODE_INVALID = 0; final int ANTINVMODE_MIN = 0; final int ANTINVMODE_MAX = 1;
+ int antennaInventoryMode = ANTINVMODE_INVALID;
+ int getAntennaInventoryMode() {
+ if (antennaInventoryMode < ANTPROFILEMODE_MIN || antennaInventoryMode > ANTPROFILEMODE_MAX)
+ getHST_ANT_DESC_CFG();
+ return antennaInventoryMode;
+ }
+ boolean setAntennaInventoryMode(int antennaInventoryMode) {
+ return setAntennaEnable(antennaEnable, antennaInventoryMode, antennaLocalAlgo, antennaLocalStartQ, antennaProfileMode,
+ antennaLocalProfile, antennaFrequencyMode, antennaLocalFrequency);
+ }
+
+ final int ANTLOCALALGO_INVALID = 0; final int ANTLOCALALGO_MIN = 0; final int ANTLOCALALGO_MAX = 5;
+ int antennaLocalAlgo = ANTLOCALALGO_INVALID;
+ int getAntennaLocalAlgo() {
+ if (antennaLocalAlgo < ANTLOCALALGO_MIN || antennaLocalAlgo > ANTLOCALALGO_MAX)
+ getHST_ANT_DESC_CFG();
+ return antennaLocalAlgo;
+ }
+ boolean setAntennaLocalAlgo(int antennaLocalAlgo) {
+ return setAntennaEnable(antennaEnable, antennaInventoryMode, antennaLocalAlgo, antennaLocalStartQ,
+ antennaProfileMode, antennaLocalProfile, antennaFrequencyMode, antennaLocalFrequency);
+ }
+
+ final int ANTLOCALSTARTQ_INVALID = 0; final int ANTLOCALSTARTQ_MIN = 0; final int ANTLOCALSTARTQ_MAX = 15;
+ int antennaLocalStartQ = ANTLOCALSTARTQ_INVALID;
+ int getAntennaLocalStartQ() {
+ if (antennaLocalStartQ < ANTLOCALSTARTQ_MIN || antennaLocalStartQ > ANTLOCALSTARTQ_MAX)
+ getHST_ANT_DESC_CFG();
+ return antennaLocalStartQ;
+ }
+ boolean setAntennaLocalStartQ(int antennaLocalStartQ) {
+ return setAntennaEnable(antennaEnable, antennaInventoryMode, antennaLocalAlgo, antennaLocalStartQ,
+ antennaProfileMode, antennaLocalProfile, antennaFrequencyMode, antennaLocalFrequency);
+ }
+
+ final int ANTPROFILEMODE_INVALID = 0; final int ANTPROFILEMODE_MIN = 0; final int ANTPROFILEMODE_MAX = 1;
+ int antennaProfileMode = ANTPROFILEMODE_INVALID;
+ int getAntennaProfileMode() {
+ if (antennaProfileMode < ANTPROFILEMODE_MIN || antennaProfileMode > ANTPROFILEMODE_MAX)
+ getHST_ANT_DESC_CFG();
+ return antennaProfileMode;
+ }
+ boolean setAntennaProfileMode(int antennaProfileMode) {
+ return setAntennaEnable(antennaEnable, antennaInventoryMode, antennaLocalAlgo, antennaLocalStartQ,
+ antennaProfileMode, antennaLocalProfile, antennaFrequencyMode, antennaLocalFrequency);
+ }
+
+ final int ANTLOCALPROFILE_INVALID = 0; final int ANTLOCALPROFILE_MIN = 0; final int ANTLOCALPROFILE_MAX = 5;
+ int antennaLocalProfile = ANTLOCALPROFILE_INVALID;
+ int getAntennaLocalProfile() {
+ if (antennaLocalProfile < ANTLOCALPROFILE_MIN || antennaLocalProfile > ANTLOCALPROFILE_MIN)
+ getHST_ANT_DESC_CFG();
+ return antennaLocalProfile;
+ }
+ boolean setAntennaLocalProfile(int antennaLocalProfile) {
+ return setAntennaEnable(antennaEnable, antennaInventoryMode, antennaLocalAlgo, antennaLocalStartQ,
+ antennaProfileMode, antennaLocalProfile, antennaFrequencyMode, antennaLocalFrequency);
+ }
+
+ final int ANTFREQMODE_INVALID = 0; final int ANTFREQMODE_MIN = 0; final int ANTFREQMODE_MAX = 1;
+ int antennaFrequencyMode = ANTFREQMODE_INVALID;
+ int getAntennaFrequencyMode() {
+ if (antennaFrequencyMode < ANTFREQMODE_MIN || antennaFrequencyMode > ANTFREQMODE_MAX)
+ getHST_ANT_DESC_CFG();
+ return antennaFrequencyMode;
+ }
+ boolean setAntennaFrequencyMode(int antennaFrequencyMode) {
+ return setAntennaEnable(antennaEnable, antennaInventoryMode, antennaLocalAlgo, antennaLocalStartQ,
+ antennaProfileMode, antennaLocalProfile, antennaFrequencyMode, antennaLocalFrequency);
+ }
+
+ final int ANTLOCALFREQ_INVALID = 0; final int ANTLOCALFREQ_MIN = 0; final int ANTLOCALFREQ_MAX = 49;
+ int antennaLocalFrequency = ANTLOCALFREQ_INVALID;
+ int getAntennaLocalFrequency() {
+ if (antennaLocalFrequency < ANTLOCALFREQ_MIN || antennaLocalFrequency > ANTLOCALFREQ_MAX)
+ getHST_ANT_DESC_CFG();
+ return antennaLocalFrequency;
+ }
+ boolean setAntennaLocalFrequency(int antennaLocalFrequency) {
+ return setAntennaEnable(antennaEnable, antennaInventoryMode, antennaLocalAlgo, antennaLocalStartQ,
+ antennaProfileMode, antennaLocalProfile, antennaFrequencyMode, antennaLocalFrequency);
+ }
+
+ private boolean getHST_ANT_DESC_CFG() {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 2, 7, 0, 0, 0, 0};
+ return sendHostRegRequest(HostRegRequests.HST_ANT_DESC_CFG, false, msgBuffer);
+ }
+ boolean setAntennaEnable(int antennaEnable, int antennaInventoryMode, int antennaLocalAlgo, int antennaLocalStartQ,
+ int antennaProfileMode, int antennaLocalProfile,
+ int antennaFrequencyMode, int antennaLocalFrequency) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 2, 7, 0, 0, 0, 0};
+ if (antennaEnable < ANTENABLE_MIN || antennaEnable > ANTENABLE_MAX)
+ antennaEnable = mDefault.antennaEnable;
+ if (antennaInventoryMode < ANTINVMODE_MIN || antennaInventoryMode > ANTINVMODE_MAX)
+ antennaInventoryMode = mDefault.antennaInventoryMode;
+ if (antennaLocalAlgo < ANTLOCALALGO_MIN || antennaLocalAlgo > ANTLOCALALGO_MAX)
+ antennaLocalAlgo = mDefault.antennaLocalAlgo;
+ if (antennaLocalStartQ < ANTLOCALSTARTQ_MIN || antennaLocalStartQ > ANTLOCALSTARTQ_MAX)
+ antennaLocalStartQ = mDefault.antennaLocalStartQ;
+ if (antennaProfileMode < ANTPROFILEMODE_MIN || antennaProfileMode > ANTPROFILEMODE_MAX)
+ antennaProfileMode = mDefault.antennaProfileMode;
+ if (antennaLocalProfile < ANTLOCALPROFILE_MIN || antennaLocalProfile > ANTLOCALPROFILE_MAX)
+ antennaLocalProfile = mDefault.antennaLocalProfile;
+ if (antennaFrequencyMode < ANTFREQMODE_MIN || antennaFrequencyMode > ANTFREQMODE_MAX)
+ antennaFrequencyMode = mDefault.antennaFrequencyMode;
+ if (antennaLocalFrequency < ANTLOCALFREQ_MIN || antennaLocalFrequency > ANTLOCALFREQ_MAX)
+ antennaLocalFrequency = mDefault.antennaLocalFrequency;
+ if (this.antennaEnable == antennaEnable && this.antennaInventoryMode == antennaInventoryMode && this.antennaLocalAlgo == antennaLocalAlgo
+ && this.antennaLocalStartQ == antennaLocalStartQ && this.antennaProfileMode == antennaProfileMode && this.antennaLocalProfile == antennaLocalProfile
+ && this.antennaFrequencyMode == antennaFrequencyMode && this.antennaLocalFrequency == antennaLocalFrequency
+ && sameCheck)
+ return true;
+ msgBuffer[4] |= antennaEnable;
+ msgBuffer[4] |= (antennaInventoryMode << 1);
+ msgBuffer[4] |= (antennaLocalAlgo << 2);
+ msgBuffer[4] |= (antennaLocalStartQ << 4);
+ msgBuffer[5] |= antennaProfileMode;
+ msgBuffer[5] |= (antennaLocalProfile << 1);
+ msgBuffer[5] |= (antennaFrequencyMode << 5);
+ msgBuffer[5] |= ((antennaLocalFrequency & 0x03) << 6);
+ msgBuffer[6] |= (antennaLocalFrequency >> 2);
+ this.antennaEnable = antennaEnable;
+ this.antennaInventoryMode = antennaInventoryMode;
+ this.antennaLocalAlgo = antennaLocalAlgo;
+ this.antennaLocalStartQ = antennaLocalStartQ;
+ this.antennaProfileMode = antennaProfileMode;
+ this.antennaLocalProfile = antennaLocalProfile;
+ this.antennaFrequencyMode = antennaFrequencyMode;
+ this.antennaLocalFrequency = antennaLocalFrequency;
+ return sendHostRegRequest(HostRegRequests.HST_ANT_DESC_CFG, true, msgBuffer);
+ }
+
+ final int ANTSTATUS_INVALID = -1; final int ANTSTATUS_MIN = 0; final int ANTSTATUS_MAX = 0xFFFFF;
+ int antennaStatus = ANTSTATUS_INVALID;
+ int getAntennaStatus() {
+ if (antennaStatus < ANTSTATUS_MIN || antennaStatus > ANTSTATUS_MAX) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 3, 7, 0, 0, 0, 0};
+ sendHostRegRequest(HostRegRequests.MAC_ANT_DESC_STAT, false, msgBuffer);
+ }
+ return antennaStatus;
+ }
+
+ final int ANTDEFINE_INVALID = -1; final int ANTDEFINE_MIN = 0; final int ANTDEFINE_MAX = 3;
+ int antennaDefine = ANTDEFINE_INVALID;
+ int getAntennaDefine() {
+ if (antennaDefine < ANTDEFINE_MIN || antennaDefine > ANTDEFINE_MAX) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 4, 7, 0, 0, 0, 0};
+ sendHostRegRequest(HostRegRequests.HST_ANT_DESC_PORTDEF, false, msgBuffer);
+ }
+ return antennaDefine;
+ }
+
+ final long ANTDWELL_INVALID = -1; final long ANTDWELL_MIN = 0; final long ANTDWELL_MAX = 0xFFFF;
+ long antennaDwell = ANTDWELL_INVALID;
+ long getAntennaDwell() {
+ if (antennaDwell < ANTDWELL_MIN || antennaDwell > ANTDWELL_MAX) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 5, 7, 0, 0, 0, 0};
+ sendHostRegRequest(HostRegRequests.HST_ANT_DESC_DWELL, false, msgBuffer);
+ }
+ return antennaDwell;
+ }
+ boolean setAntennaDwell(long antennaDwell) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 5, 7, 0, 0, 0, 0};
+ if (antennaDwell < ANTDWELL_MIN || antennaDwell > ANTDWELL_MAX)
+ antennaDwell = mDefault.antennaDwell;
+ if (this.antennaDwell == antennaDwell && sameCheck) return true;
+ msgBuffer[4] = (byte) (antennaDwell % 256);
+ msgBuffer[5] = (byte) ((antennaDwell >> 8) % 256);
+ msgBuffer[6] = (byte) ((antennaDwell >> 16) % 256);
+ msgBuffer[7] = (byte) ((antennaDwell >> 24) % 256);
+ this.antennaDwell = antennaDwell;
+ return sendHostRegRequest(HostRegRequests.HST_ANT_DESC_DWELL, true, msgBuffer);
+ }
+
+ final int ANTARGET_INVALID = -1; final int ANTARGET_MIN = 0; final int ANTARGET_MAX = 1;
+ int antennaTarget = ANTARGET_INVALID;
+ byte[] antennaInventoryRoundControl = null;
+ final int ANTOGGLE_INVALID = -1; final int ANTOGGLE_MIN = 0; final int ANTOGGLE_MAX = 100;
+ int antennaToggle = ANTOGGLE_INVALID;
+ final int ANTRFMODE_INVALID = -1; final int ANTRFMODE_MIN = 1; final int ANTRFMODE_MAX = 15;
+ int antennaRfMode = ANTRFMODE_INVALID;
+
+ final long ANTPOWER_INVALID = -1; final long ANTPOWER_MIN = 0; final long ANTPOWER_MAX = 330; //Maximum 330\
+ long antennaPower = ANTPOWER_INVALID; //default value = 300
+ long getAntennaPower() {
+ if (antennaPower < ANTPOWER_MIN || antennaPower > ANTPOWER_MAX) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 6, 7, 0, 0, 0, 0};
+ sendHostRegRequest(HostRegRequests.HST_ANT_DESC_RFPOWER, false, msgBuffer);
+ }
+ return antennaPower;
+ }
+ boolean antennaPowerSet = false;
+ boolean setAntennaPower(long antennaPower) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 6, 7, 0, 0, 0, 0};
+ if (antennaPower < ANTPOWER_MIN || antennaPower > ANTPOWER_MAX)
+ antennaPower = mDefault.antennaPower;
+ if (this.antennaPower == antennaPower && sameCheck) return true;
+ msgBuffer[4] = (byte) (antennaPower % 256);
+ msgBuffer[5] = (byte) ((antennaPower >> 8) % 256);
+ this.antennaPower = antennaPower;
+ antennaPowerSet = true;
+ return sendHostRegRequest(HostRegRequests.HST_ANT_DESC_RFPOWER, true, msgBuffer);
+ }
+
+ final long ANTINVCOUNT_INVALID = -1; final long ANTINVCOUNT_MIN = 0; final long ANTINVCOUNT_MAX = 0xFFFFFFFFL;
+ long antennaInvCount = ANTINVCOUNT_INVALID;
+ long getAntennaInvCount() {
+ if (antennaInvCount < ANTINVCOUNT_MIN || antennaInvCount > ANTINVCOUNT_MAX) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 7, 7, 0, 0, 0, 0};
+ sendHostRegRequest(HostRegRequests.HST_ANT_DESC_INV_CNT, false, msgBuffer);
+ }
+ return antennaInvCount;
+ }
+ boolean setAntennaInvCount(long antennaInvCount) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 7, 7, 0, 0, 0, 0};
+ if (antennaInvCount < ANTINVCOUNT_MIN || antennaInvCount > ANTINVCOUNT_MAX)
+ antennaInvCount = mDefault.antennaInvCount;
+ if (this.antennaInvCount == antennaInvCount && sameCheck) return true;
+ msgBuffer[4] = (byte) (antennaInvCount % 256);
+ msgBuffer[5] = (byte) ((antennaInvCount >> 8) % 256);
+ msgBuffer[6] = (byte) ((antennaInvCount >> 16) % 256);
+ msgBuffer[7] = (byte) ((antennaInvCount >> 24) % 256);
+ this.antennaInvCount = antennaInvCount;
+ return sendHostRegRequest(HostRegRequests.HST_ANT_DESC_INV_CNT, true, msgBuffer);
+ }
+ }
+ class InvSelectData {
+ InvSelectData(boolean set_default_setting) {
+ if (set_default_setting) {
+ selectEnable = mDefault.selectEnable;
+ selectTarget = mDefault.selectTarget;
+ selectAction = mDefault.selectAction;
+ selectDelay = mDefault.selectDelay;
+ selectMaskBank = mDefault.selectMaskBank;
+ selectMaskOffset = mDefault.selectMaskOffset;
+ selectMaskLength = mDefault.selectMaskLength;
+ selectMaskDataReady = mDefault.selectMaskDataReady;
+ //Log.i("Hello", "BtDataOut 123b");
+ }
+ }
+
+ private class InvSelectData_default {
+ int selectEnable = 0;
+ int selectTarget = 0;
+ int selectAction = 0;
+ int selectDelay = 0;
+ int selectMaskBank = 0;
+ int selectMaskOffset = 0;
+ int selectMaskLength = 0;
+ byte[] selectMaskData0_31 = new byte[4 * 8]; byte selectMaskDataReady = 0;
+ }
+ InvSelectData_default mDefault = new InvSelectData_default();
+
+ final int INVSELENABLE_INVALID = 0; final int INVSELENABLE_MIN = 0; final int INVSELENABLE_MAX = 1;
+ int selectEnable = INVSELENABLE_INVALID;
+ int getSelectEnable() {
+ getRx000HostReg_HST_TAGMSK_DESC_CFG();
+ return selectEnable;
+ }
+ boolean setSelectEnable(int selectEnable) {
+ appendToLog("BtDataOut: RfidReaderChipR200.setSelectEnable");
+ return setRx000HostReg_HST_TAGMSK_DESC_CFG(selectEnable, this.selectTarget, this.selectAction, this.selectDelay);
+ }
+
+ final int INVSELTARGET_INVALID = -1; final int INVSELTARGET_MIN = 0; final int INVSELTARGET_MAX = 7;
+ int selectTarget = INVSELTARGET_INVALID;
+ int getSelectTarget() {
+ getRx000HostReg_HST_TAGMSK_DESC_CFG();
+ return selectTarget;
+ }
+
+ final int INVSELACTION_INVALID = -1; final int INVSELACTION_MIN = 0; final int INVSELACTION_MAX = 7;
+ int selectAction = INVSELACTION_INVALID;
+ int getSelectAction() {
+ getRx000HostReg_HST_TAGMSK_DESC_CFG();
+ return selectAction;
+ }
+
+ final int INVSELDELAY_INVALID = -1; final int INVSELDELAY_MIN = 0; final int INVSELDELAY_MAX = 255;
+ int selectDelay = INVSELDELAY_INVALID;
+ int getSelectDelay() {
+ getRx000HostReg_HST_TAGMSK_DESC_CFG();
+ return selectDelay;
+ }
+
+ boolean getRx000HostReg_HST_TAGMSK_DESC_CFG() {
+ if (selectEnable < INVSELENABLE_MIN || selectEnable > INVSELENABLE_MAX
+ || selectTarget < INVSELTARGET_MIN || selectTarget > INVSELTARGET_MAX
+ || selectAction < INVSELACTION_MIN || selectAction > INVSELACTION_MAX
+ || selectDelay < INVSELDELAY_MIN || selectDelay > INVSELDELAY_MAX
+ ) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 1, 8, 0, 0, 0, 0};
+ return sendHostRegRequest(HostRegRequests.HST_TAGMSK_DESC_CFG, false, msgBuffer);
+ } else {
+ return false;
+ }
+ }
+ boolean setRx000HostReg_HST_TAGMSK_DESC_CFG(int selectEnable, int selectTarget, int selectAction, int selectDelay) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 1, 8, 0, 0, 0, 0};
+ if (utility.DEBUG_SELECT) appendToLog("Debug_Select: RfidReaderR2000.setRx000HostReg_HST_TAGMSK_DESC_CFG[" +
+ selectEnable + "," + selectTarget + "," + selectAction + "," + selectDelay + "] with old SelectEnable/Target/Action/Delay =" +
+ this.selectEnable + "," + this.selectTarget + "," + this.selectAction + "," + this.selectDelay);
+ if (selectEnable < INVSELENABLE_MIN || selectEnable > INVSELENABLE_MAX)
+ selectEnable = mDefault.selectEnable;
+ if (selectTarget < INVSELTARGET_MIN || selectTarget > INVSELTARGET_MAX)
+ selectTarget = mDefault.selectTarget;
+ if (selectAction < INVSELACTION_MIN || selectAction > INVSELACTION_MAX)
+ selectAction = mDefault.selectAction;
+ int selectDalay0 = selectDelay;
+ if (selectDelay < INVSELDELAY_MIN || selectDelay > INVSELDELAY_MAX)
+ selectDelay = mDefault.selectDelay;
+ if (this.selectEnable == selectEnable && this.selectTarget == selectTarget && this.selectAction == selectAction && this.selectDelay == selectDelay && sameCheck) return true;
+ msgBuffer[4] |= (byte) (selectEnable & 0x1);
+ msgBuffer[4] |= (byte) ((selectTarget & 0x07) << 1);
+ msgBuffer[4] |= (byte) ((selectAction & 0x07) << 4);
+ msgBuffer[5] |= (byte) (selectDelay & 0xFF);
+ this.selectEnable = selectEnable;
+ this.selectTarget = selectTarget;
+ this.selectAction = selectAction;
+ this.selectDelay = selectDelay;
+ return sendHostRegRequest(HostRegRequests.HST_TAGMSK_DESC_CFG, true, msgBuffer);
+ }
+
+ final int INVSELMBANK_INVALID = -1; final int INVSELMBANK_MIN = 0; final int INVSELMBANK_MAX = 3;
+ int selectMaskBank = INVSELMBANK_INVALID;
+ int getSelectMaskBank() {
+ if (selectMaskBank < INVSELMBANK_MIN || selectMaskBank > INVSELMBANK_MAX) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 2, 8, 0, 0, 0, 0};
+ sendHostRegRequest(HostRegRequests.HST_TAGMSK_BANK, false, msgBuffer);
+ }
+ return selectMaskBank;
+ }
+ boolean setSelectMaskBank(int selectMaskBank) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 2, 8, 0, 0, 0, 0};
+ if (selectMaskBank < INVSELMBANK_MIN || selectMaskBank > INVSELMBANK_MAX)
+ selectMaskBank = mDefault.selectMaskBank;
+ if (this.selectMaskBank == selectMaskBank && sameCheck) return true;
+ msgBuffer[4] |= (byte) (selectMaskBank & 0x3);
+ this.selectMaskBank = selectMaskBank;
+ return sendHostRegRequest(HostRegRequests.HST_TAGMSK_BANK, true, msgBuffer);
+ }
+
+ final int INVSELMOFFSET_INVALID = -1; final int INVSELMOFFSET_MIN = 0; final int INVSELMOFFSET_MAX = 0xFFFF;
+ int selectMaskOffset = INVSELMOFFSET_INVALID;
+ int getSelectMaskOffset() {
+ if (selectMaskOffset < INVSELMOFFSET_MIN || selectMaskOffset > INVSELMOFFSET_MAX) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 3, 8, 0, 0, 0, 0};
+ sendHostRegRequest(HostRegRequests.HST_TAGMSK_PTR, false, msgBuffer);
+ }
+ return selectMaskOffset;
+ }
+ boolean setSelectMaskOffset(int selectMaskOffset) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 3, 8, 0, 0, 0, 0};
+ if (selectMaskOffset < INVSELMOFFSET_MIN || selectMaskOffset > INVSELMOFFSET_MAX)
+ selectMaskOffset = mDefault.selectMaskOffset;
+ if (this.selectMaskOffset == selectMaskOffset && sameCheck) return true;
+ msgBuffer[4] |= (byte) (selectMaskOffset & 0xFF);
+ msgBuffer[5] |= (byte) ((selectMaskOffset >> 8) & 0xFF);
+ this.selectMaskOffset = selectMaskOffset;
+ return sendHostRegRequest(HostRegRequests.HST_TAGMSK_PTR, true, msgBuffer);
+ }
+
+ final int INVSELMLENGTH_INVALID = -1; final int INVSELMLENGTH_MIN = 0; final int INVSELMLENGTH_MAX = 255;
+ int selectMaskLength = INVSELMLENGTH_INVALID;
+ int getSelectMaskLength() {
+ appendToLog("getSelectMaskData with selectMaskLength = " + selectMaskLength);
+ if (selectMaskLength < INVSELMLENGTH_MIN || selectMaskOffset > INVSELMLENGTH_MAX) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 4, 8, 0, 0, 0, 0};
+ sendHostRegRequest(HostRegRequests.HST_TAGMSK_LEN, false, msgBuffer);
+ }
+ return selectMaskLength;
+ }
+ boolean setSelectMaskLength(int selectMaskLength) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 4, 8, 0, 0, 0, 0};
+ if (selectMaskLength < INVSELMLENGTH_MIN) selectMaskLength = INVSELMLENGTH_MIN;
+ else if (selectMaskLength > INVSELMLENGTH_MAX) selectMaskLength = INVSELMLENGTH_MAX;
+ if (this.selectMaskLength == selectMaskLength && sameCheck) return true;
+ msgBuffer[4] |= (byte) (selectMaskLength & 0xFF);
+ if (selectMaskLength == INVSELMLENGTH_MAX) msgBuffer[5] = 1;
+ this.selectMaskLength = selectMaskLength;
+ return sendHostRegRequest(HostRegRequests.HST_TAGMSK_PTR, true, msgBuffer);
+ }
+
+ byte[] selectMaskData0_31 = new byte[4 * 8]; byte selectMaskDataReady = 0;
+ String getRx000SelectMaskData() {
+ if (false) appendToLog("getSelectMaskData with selectMaskData0_31 = " + byteArrayToString(selectMaskData0_31));
+ int length = selectMaskLength;
+ String strValue = "";
+ if (length < 0) {
+ getSelectMaskLength();
+ } else {
+ for (int i = 0; i < 8; i++) {
+ if (length > 0) {
+ if ((selectMaskDataReady & (0x01 << i)) == 0) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 5, 8, 0, 0, 0, 0};
+ msgBuffer[2] += i;
+ sendHostRegRequest(HostRegRequests.HST_TAGMSK_0_3, false, msgBuffer);
+
+ strValue = null;
+ break;
+ } else {
+ for (int j = 0; j < 4; j++) {
+ if (DEBUG) appendToLog("i = " + i + ", j = " + j + ", selectMaskData0_31 = " + selectMaskData0_31[i * 4 + j]);
+ strValue += String.format("%02X", selectMaskData0_31[i * 4 + j]);
+ }
+ }
+ length -= 32;
+ }
+ }
+ }
+ return strValue;
+ }
+ boolean setRx000SelectMaskData(String maskData) {
+ int length = maskData.length();
+ for (int i = 0; i < 8; i++) {
+ if (length > 0) {
+ length -= 8;
+
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 5, 8, 0, 0, 0, 0};
+ String hexString = "0123456789ABCDEF";
+ for (int j = 0; j < 8; j++) {
+ if (i * 8 + j + 1 <= maskData.length()) {
+ String subString = maskData.substring(i * 8 + j, i * 8 + j + 1).toUpperCase();
+ int k = 0;
+ for (k = 0; k < 16; k++) {
+ if (subString.matches(hexString.substring(k, k + 1))) {
+ break;
+ }
+ }
+ if (k == 16) return false;
+// appendToLog("setSelectMaskData(" + maskData +"): i=" + i + ", j=" + j + ", k=" + k);
+ if ((j / 2) * 2 == j) {
+ msgBuffer[4 + j / 2] |= (byte) (k << 4);
+ } else {
+ msgBuffer[4 + j / 2] |= (byte) (k);
+ }
+ }
+ }
+ msgBuffer[2] = (byte) ((msgBuffer[2] & 0xFF) + i);
+ if (sendHostRegRequest(HostRegRequests.HST_TAGMSK_0_3, true, msgBuffer) == false)
+ return false;
+ else {
+ selectMaskDataReady |= (0x01 << i);
+ if (DEBUG) appendToLog("Old selectMaskData0_31 = " + byteArrayToString(selectMaskData0_31));
+ System.arraycopy(msgBuffer, 4, selectMaskData0_31, i * 4, 4);
+ if (DEBUG) appendToLog("New selectMaskData0_31 = " + byteArrayToString(selectMaskData0_31));
+ }
+ }
+ }
+ return true;
+ }
+ }
+ class AlgoSelectedData {
+ AlgoSelectedData(boolean set_default_setting, int default_setting_type) {
+ if (default_setting_type < 0) default_setting_type = 0;
+ if (default_setting_type > 4) default_setting_type = 4;
+ mDefault = new AlgoSelectedData_default(default_setting_type);
+ if (set_default_setting) {
+ algoStartQ = mDefault.algoStartQ;
+ //Log.i("Hello", "BtDataOut: algoStartQ is set to default " + algoStartQ);
+ algoMaxQ = mDefault.algoMaxQ;
+ algoMinQ = mDefault.algoMinQ;
+ algoMaxRep = mDefault.algoMaxRep;
+ algoHighThres = mDefault.algoHighThres;
+ algoLowThres = mDefault.algoLowThres;
+ algoRetry = mDefault.algoRetry;
+ algoAbFlip = mDefault.algoAbFlip;
+ algoRunTilZero = mDefault.algoRunTilZero;
+ }
+ }
+
+ class AlgoSelectedData_default {
+ AlgoSelectedData_default(int set_default_setting) {
+ algoStartQ = mDefaultArray.algoStartQ[set_default_setting];
+ algoMaxQ = mDefaultArray.algoMaxQ[set_default_setting];
+ algoMinQ = mDefaultArray.algoMinQ[set_default_setting];
+ algoMaxRep = mDefaultArray.algoMaxRep[set_default_setting];
+ algoHighThres = mDefaultArray.algoHighThres[set_default_setting];
+ algoLowThres = mDefaultArray.algoLowThres[set_default_setting];
+ algoRetry = mDefaultArray.algoRetry[set_default_setting];
+ algoAbFlip = mDefaultArray.algoAbFlip[set_default_setting];
+ algoRunTilZero = mDefaultArray.algoRunTilZero[set_default_setting];
+ }
+
+ int algoStartQ = -1;
+ int algoMaxQ = -1;
+ int algoMinQ = -1;
+ int algoMaxRep = -1;
+ int algoHighThres = -1;
+ int algoLowThres = -1;
+ int algoRetry = -1;
+ int algoAbFlip = -1;
+ int algoRunTilZero = -1;
+ }
+ AlgoSelectedData_default mDefault;
+
+ class AlgoSelectedData_defaultArray { //0 for invalid default, 1 for 0, 2 for 1, 3 for 2, 4 for 3
+ int[] algoStartQ = { -1, 0, 0, 0, 7 };
+ int[] algoMaxQ = { -1, 0, 0, 0, 15 };
+ int[] algoMinQ = { -1, 0, 0, 0, 0 };
+ int[] algoMaxRep = { -1, 0, 0, 0, 4 };
+ int[] algoHighThres = { -1, 0, 5, 5, 5 };
+ int[] algoLowThres = { -1, 0, 3, 3, 3 };
+ int[] algoRetry = { -1, 0, 0, 0, 0 };
+ int[] algoAbFlip = { -1, 0, 1, 1, 1 };
+ int[] algoRunTilZero = { -1, 0, 0, 0, 0 };
+ }
+ AlgoSelectedData_defaultArray mDefaultArray = new AlgoSelectedData_defaultArray();
+
+ final int ALGOSTARTQ_INVALID = -1; final int ALGOSTARTQ_MIN = 0; final int ALGOSTARTQ_MAX = 15;
+ int algoStartQ = ALGOSTARTQ_INVALID;
+ int getAlgoStartQ(boolean getInvalid) {
+ if (getInvalid && (algoStartQ < ALGOSTARTQ_MIN || algoStartQ > ALGOSTARTQ_MAX)) getHST_INV_ALG_PARM_0();
+ return algoStartQ;
+ }
+ boolean setAlgoStartQ(int algoStartQ) {
+ return setAlgoStartQ(algoStartQ, algoMaxQ, algoMinQ, algoMaxRep, algoHighThres, algoLowThres);
+ }
+
+ final int ALGOMAXQ_INVALID = -1; final int ALGOMAXQ_MIN = 0; final int ALGOMAXQ_MAX = 15;
+ int algoMaxQ = ALGOMAXQ_INVALID;
+ int getAlgoMaxQ() {
+ if (algoMaxQ < ALGOMAXQ_MIN || algoMaxQ > ALGOMAXQ_MAX) getHST_INV_ALG_PARM_0();
+ return algoMaxQ;
+ }
+ boolean setAlgoMaxQ(int algoMaxQ) {
+ return setAlgoStartQ(algoStartQ, algoMaxQ, algoMinQ, algoMaxRep, algoHighThres, algoLowThres);
+ }
+
+ final int ALGOMINQ_INVALID = -1; final int ALGOMINQ_MIN = 0; final int ALGOMINQ_MAX = 15;
+ int algoMinQ = ALGOMINQ_INVALID;
+ int getAlgoMinQ() {
+ if (algoMinQ < ALGOMINQ_MIN || algoMinQ > ALGOMINQ_MAX) getHST_INV_ALG_PARM_0();
+ return algoMinQ;
+ }
+ boolean setAlgoMinQ(int algoMinQ) {
+ return setAlgoStartQ(algoStartQ, algoMaxQ, algoMinQ, algoMaxRep, algoHighThres, algoLowThres);
+ }
+
+ final int ALGOMAXREP_INVALID = -1; final int ALGOMAXREP_MIN = 0; final int ALGOMAXREP_MAX = 255;
+ int algoMaxRep = ALGOMAXREP_INVALID;
+ int getAlgoMaxRep() {
+ if (algoMaxRep < ALGOMAXREP_MIN || algoMaxRep > ALGOMAXREP_MAX) getHST_INV_ALG_PARM_0();
+ return algoMaxRep;
+ }
+ boolean setAlgoMaxRep(int algoMaxRep) {
+ return setAlgoStartQ(algoStartQ, algoMaxQ, algoMinQ, algoMaxRep, algoHighThres, algoLowThres);
+ }
+
+ final int ALGOHIGHTHRES_INVALID = -1; final int ALGOHIGHTHRES_MIN = 0; final int ALGOHIGHTHRES_MAX = 15;
+ int algoHighThres = ALGOHIGHTHRES_INVALID;
+ int getAlgoHighThres() {
+ if (algoHighThres < ALGOHIGHTHRES_MIN || algoHighThres > ALGOHIGHTHRES_MAX)
+ getHST_INV_ALG_PARM_0();
+ return algoHighThres;
+ }
+ boolean setAlgoHighThres(int algoHighThres) {
+ return setAlgoStartQ(algoStartQ, algoMaxQ, algoMinQ, algoMaxRep, algoHighThres, algoLowThres);
+ }
+
+ final int ALGOLOWTHRES_INVALID = -1; final int ALGOLOWTHRES_MIN = 0; final int ALGOLOWTHRES_MAX = 15;
+ int algoLowThres = ALGOLOWTHRES_INVALID;
+ int getAlgoLowThres() {
+ if (algoLowThres < ALGOLOWTHRES_MIN || algoLowThres > ALGOLOWTHRES_MAX)
+ getHST_INV_ALG_PARM_0();
+ return algoLowThres;
+ }
+ boolean setAlgoLowThres(int algoLowThres) {
+ return setAlgoStartQ(algoStartQ, algoMaxQ, algoMinQ, algoMaxRep, algoHighThres, algoLowThres);
+ }
+
+ private boolean getHST_INV_ALG_PARM_0() {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 3, 9, 0, 0, 0, 0};
+ return sendHostRegRequest(HostRegRequests.HST_INV_ALG_PARM_0, false, msgBuffer);
+ }
+ boolean setAlgoStartQ(int startQ, int algoMaxQ, int algoMinQ, int algoMaxRep, int algoHighThres, int algoLowThres) {
+ boolean DEBUG = false;
+ if (DEBUG) appendToLog("BtDataOut: startQ = " + startQ + ", algoMaxQ = " + algoMaxQ + ", algoMinQ = " + algoMinQ + ", algoMaxRep = " + algoMaxRep +
+ ", algoHighThres = " + algoHighThres + ", algoLowThres = " + algoLowThres +
+ ", Old = " + this.algoStartQ + ", " + this.algoMaxQ + ", " + this.algoMinQ + ", " + this.algoMaxRep +
+ ", " + this.algoHighThres + ", " + this.algoLowThres);
+
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 3, 9, 0, 0, 0, 0};
+ if (startQ < ALGOSTARTQ_MIN || startQ > ALGOSTARTQ_MAX) startQ = mDefault.algoStartQ;
+ if (algoMaxQ < ALGOMAXQ_MIN || algoMaxQ > ALGOMAXQ_MAX) algoMaxQ = mDefault.algoMaxQ;
+ if (algoMinQ < ALGOMINQ_MIN || algoMinQ > ALGOMINQ_MAX) algoMinQ = mDefault.algoMinQ;
+ if (algoMaxRep < ALGOMAXREP_MIN || algoMaxRep > ALGOMAXREP_MAX)
+ algoMaxRep = mDefault.algoMaxRep;
+ if (algoHighThres < ALGOHIGHTHRES_MIN || algoHighThres > ALGOHIGHTHRES_MAX)
+ algoHighThres = mDefault.algoHighThres;
+ if (algoLowThres < ALGOLOWTHRES_MIN || algoLowThres > ALGOLOWTHRES_MAX)
+ algoLowThres = mDefault.algoLowThres;
+ if (this.algoStartQ == startQ && this.algoMaxQ == algoMaxQ && this.algoMinQ == algoMinQ
+ && this.algoMaxRep == algoMaxRep && this.algoHighThres == algoHighThres && this.algoLowThres == algoLowThres
+ && sameCheck)
+ return true;
+ if (DEBUG) appendToLog("algoMaxRep = " + algoMaxRep + ", algoMaxRep = " + algoMaxRep + ", algoLowThres = " + algoLowThres);
+ msgBuffer[4] |= (byte) (startQ & 0x0F);
+ msgBuffer[4] |= (byte) ((algoMaxQ & 0x0F) << 4);
+ msgBuffer[5] |= (byte) (algoMinQ & 0x0F);
+ msgBuffer[5] |= (byte) ((algoMaxRep & 0xF) << 4);
+ msgBuffer[6] |= (byte) ((algoMaxRep & 0xF0) >> 4);
+ msgBuffer[6] |= (byte) ((algoHighThres & 0x0F) << 4);
+ msgBuffer[7] |= (byte) (algoLowThres & 0x0F);
+ this.algoStartQ = startQ;
+ if (false) appendToLog("this.algoStartQ is updated as " + this.algoStartQ);
+ this.algoMaxQ = algoMaxQ;
+ this.algoMinQ = algoMinQ;
+ this.algoMaxRep = algoMaxRep;
+ this.algoHighThres = algoHighThres;
+ this.algoLowThres = algoLowThres;
+ return sendHostRegRequest(HostRegRequests.HST_INV_ALG_PARM_0, true, msgBuffer);
+ }
+
+ final int ALGORETRY_INVALID = -1; final int ALGORETRY_MIN = 0; final int ALGORETRY_MAX = 255;
+ int algoRetry = ALGORETRY_INVALID;
+ int getAlgoRetry() {
+ if (algoRetry < ALGORETRY_MIN || algoRetry > ALGORETRY_MAX) {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 4, 9, 0, 0, 0, 0};
+ sendHostRegRequest(HostRegRequests.HST_INV_ALG_PARM_1, false, msgBuffer);
+ }
+ return algoRetry;
+ }
+ boolean setAlgoRetry(int algoRetry) {
+ if (algoRetry < ALGORETRY_MIN || algoRetry > ALGORETRY_MAX)
+ algoRetry = mDefault.algoRetry;
+ if (this.algoRetry == algoRetry && sameCheck) return true;
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 4, 9, 0, 0, 0, 0};
+ msgBuffer[4] = (byte) algoRetry;
+ this.algoRetry = algoRetry;
+ return sendHostRegRequest(HostRegRequests.HST_INV_ALG_PARM_1, true, msgBuffer);
+ }
+
+ final int ALGOABFLIP_INVALID = -1; final int ALGOABFLIP_MIN = 0; final int ALGOABFLIP_MAX = 1;
+ int algoAbFlip = ALGOABFLIP_INVALID;
+ int getAlgoAbFlip() {
+ if (algoAbFlip < ALGOABFLIP_MIN || algoAbFlip > ALGOABFLIP_MAX) getHST_INV_ALG_PARM_2();
+ return algoAbFlip;
+ }
+ boolean setAlgoAbFlip(int algoAbFlip) {
+ return setAlgoAbFlip(algoAbFlip, algoRunTilZero);
+ }
+
+ final int ALGORUNTILZERO_INVALID = -1; final int ALGORUNTILZERO_MIN = 0; final int ALGORUNTILZERO_MAX = 1;
+ int algoRunTilZero = ALGORUNTILZERO_INVALID;
+ int getAlgoRunTilZero() {
+ if (algoRunTilZero < ALGORUNTILZERO_MIN || algoRunTilZero > ALGORUNTILZERO_MAX) getHST_INV_ALG_PARM_2();
+ return algoRunTilZero;
+ }
+ boolean setAlgoRunTilZero(int algoRunTilZero) {
+ return setAlgoAbFlip(algoAbFlip, algoRunTilZero);
+ }
+
+ private boolean getHST_INV_ALG_PARM_2() {
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 0, 5, 9, 0, 0, 0, 0};
+ return sendHostRegRequest(HostRegRequests.HST_INV_ALG_PARM_2, false, msgBuffer);
+ }
+ boolean setAlgoAbFlip(int algoAbFlip, int algoRunTilZero) {
+ if (algoAbFlip < ALGOABFLIP_MIN || algoAbFlip > ALGOABFLIP_MAX)
+ algoAbFlip = mDefault.algoAbFlip;
+ if (algoRunTilZero < ALGORUNTILZERO_MIN || algoRunTilZero > ALGORUNTILZERO_MAX)
+ algoRunTilZero = mDefault.algoRunTilZero;
+ if (true) appendToLog("this.algoAbFlip = " + this.algoAbFlip + ", algoAbFlip = " + algoAbFlip + ", this.algoRunTilZero = " + this.algoRunTilZero + ", algoRunTilZero = " + algoRunTilZero);
+ if (this.algoAbFlip == algoAbFlip && this.algoRunTilZero == algoRunTilZero && sameCheck) return true;
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 5, 9, 0, 0, 0, 0};
+ if (algoAbFlip != 0) {
+ msgBuffer[4] |= 0x01;
+ }
+ if (algoRunTilZero != 0) {
+ msgBuffer[4] |= 0x02;
+ }
+ this.algoAbFlip = algoAbFlip;
+ this.algoRunTilZero = algoRunTilZero;
+ return sendHostRegRequest(HostRegRequests.HST_INV_ALG_PARM_2, true, msgBuffer);
+ }
+ }
+ public class Rx000EngSetting {
+ int narrowRSSI = -1, wideRSSI = -1;
+ public int getwideRSSI() {
+ if (wideRSSI < 0) {
+ setPwrManagementMode(false);
+ rx000Setting.writeMAC(0x100, 0x05); //sub-command: 0x05, Arg0: reserved
+ rx000Setting.writeMAC(0x101, 3 + 0x20000); //Arg1: 15-0: number of RSSI sample
+ sendHostRegRequestHST_CMD(RfidReaderChipData.HostCommands.CMD_ENGTEST);
+ } else appendToLog("Hello123: wideRSSI = " + wideRSSI);
+ return wideRSSI;
+ }
+ int getnarrowRSSI() {
+ if (narrowRSSI < 0) {
+ setPwrManagementMode(false);
+ rx000Setting.writeMAC(0x100, 0x05); //sub-command: 0x05, Arg0: reserved
+ rx000Setting.writeMAC(0x101, 3 + 0x20000); //Arg1: 15-0: number of RSSI sample
+ sendHostRegRequestHST_CMD(RfidReaderChipData.HostCommands.CMD_ENGTEST);
+ } else appendToLog("Hello123: narrowRSSI = " + wideRSSI);
+ return wideRSSI;
+ }
+ public void resetRSSI() {
+ narrowRSSI = -1; wideRSSI = -1;
+ }
+ }
+ public class Rx000MbpSetting {
+ final int RXGAIN_INVALID = -1; final int RXGAIN_MIN = 0; final int RXGAIN_MAX = 0x1FF;
+ int rxGain = RXGAIN_INVALID;
+ public int getHighCompression() {
+ int iRetValue = -1;
+ if (rxGain < RXGAIN_MIN || rxGain > RXGAIN_MAX) {
+ setPwrManagementMode(false);
+ rx000Setting.setMBPAddress(0x450); appendToLog("70010004: getHighCompression");
+ sendHostRegRequestHST_CMD(RfidReaderChipData.HostCommands.CMD_MBPRDREG);
+ } else iRetValue = (rxGain >> 8);
+ return iRetValue;
+ }
+ public int getRflnaGain() {
+ int iRetValue = -1;
+ if (rxGain < RXGAIN_MIN || rxGain > RXGAIN_MAX) {
+ setPwrManagementMode(false);
+ rx000Setting.setMBPAddress(0x450); appendToLog("70010004: getRflnaGain");
+ sendHostRegRequestHST_CMD(RfidReaderChipData.HostCommands.CMD_MBPRDREG);
+ } else iRetValue = ((rxGain & 0xC0) >> 6);
+ return iRetValue;
+ }
+ public int getIflnaGain() {
+ int iRetValue = -1;
+ if (rxGain < RXGAIN_MIN || rxGain > RXGAIN_MAX) {
+ setPwrManagementMode(false);
+ rx000Setting.setMBPAddress(0x450); appendToLog("70010004: getIflnaGain");
+ sendHostRegRequestHST_CMD(RfidReaderChipData.HostCommands.CMD_MBPRDREG);
+ } else iRetValue = ((rxGain & 0x38) >> 3);
+ return iRetValue;
+ }
+ public int getAgcGain() {
+ int iRetValue = -1;
+ if (rxGain < RXGAIN_MIN || rxGain > RXGAIN_MAX) {
+ setPwrManagementMode(false);
+ rx000Setting.setMBPAddress(0x450); appendToLog("70010004: getAgcGain");
+ sendHostRegRequestHST_CMD(RfidReaderChipData.HostCommands.CMD_MBPRDREG);
+ } else iRetValue = (rxGain & 0x07);
+ return iRetValue;
+ }
+ public int getRxGain() {
+ int iRetValue = -1;
+ if (rxGain < RXGAIN_MIN || rxGain > RXGAIN_MAX) {
+ setPwrManagementMode(false);
+ rx000Setting.setMBPAddress(0x450);
+ sendHostRegRequestHST_CMD(RfidReaderChipData.HostCommands.CMD_MBPRDREG);
+ } else iRetValue = rxGain;
+ return iRetValue;
+ }
+ public boolean setRxGain(int highCompression, int rflnagain, int iflnagain, int agcgain) {
+ int rxGain_new = ((highCompression & 0x01) << 8) | ((rflnagain & 0x3) << 6) | ((iflnagain & 0x7) << 3) | (agcgain & 0x7);
+ return setRxGain(rxGain_new);
+ }
+ public boolean setRxGain(int rxGain_new) {
+ boolean bRetValue = true;
+ if ((rxGain_new != rxGain) || (sameCheck == false)) {
+ setPwrManagementMode(false);
+ bRetValue = rx000Setting.setMBPAddress(0x450);
+ if (bRetValue != false) bRetValue = rx000Setting.setMBPData(rxGain_new);
+ if (bRetValue != false) bRetValue = sendHostRegRequestHST_CMD(RfidReaderChipData.HostCommands.CMD_MBPWRREG);
+ if (bRetValue != false) rxGain = rxGain_new;
+ }
+ return bRetValue;
+ }
+ }
+ public class Rx000OemSetting {
+ final int COUNTRYCODE_INVALID = -1; final int COUNTRYCODE_MIN = 1; final int COUNTRYCODE_MAX = 9;
+ int countryCode = COUNTRYCODE_INVALID; // OemAddress = 0x02
+ public int getCountryCode() {
+ if (countryCode < COUNTRYCODE_MIN || countryCode > COUNTRYCODE_MAX) {
+ setPwrManagementMode(false);
+ rx000Setting.setOEMAddress(2);
+ sendHostRegRequestHST_CMD(RfidReaderChipData.HostCommands.CMD_RDOEM);
+ }
+ return countryCode;
+ }
+
+ final int SERIALCODE_INVALID = -1;
+ byte[] serialNumber = new byte[] { SERIALCODE_INVALID, 0, 0, 0, SERIALCODE_INVALID, 0, 0, 0, SERIALCODE_INVALID, 0, 0, 0, SERIALCODE_INVALID, 0, 0, 0 };
+ public String getSerialNumber() {
+ boolean invalid = false;
+ int length = serialNumber.length / 4;
+ if (serialNumber.length % 4 != 0) length++;
+ for (int i = 0; i < length; i++) {
+ if (serialNumber[4 * i] == SERIALCODE_INVALID) { // OemAddress = 0x04 - 7
+ invalid = true;
+ setPwrManagementMode(false);
+ rx000Setting.setOEMAddress(0x04 + i);
+ sendHostRegRequestHST_CMD(RfidReaderChipData.HostCommands.CMD_RDOEM);
+ }
+ }
+ if (invalid) return null;
+ appendToLog("retValue = " + byteArrayToString(serialNumber));
+ byte[] retValue = new byte[serialNumber.length];
+ for (int i = 0; i < retValue.length; i++) {
+ int j = (i/4)*4 + 3 - i%4;
+ if (j >= serialNumber.length) retValue[i] = serialNumber[i];
+ else retValue[i] = serialNumber[j];
+ if (retValue[i] == 0) retValue[i] = 0x30;
+ }
+ appendToLog("retValue = " + byteArrayToString(retValue) + ", String = " + new String(retValue));
+ return new String(retValue);
+ }
+
+ final int PRODUCT_SERIALCODE_INVALID = -1;
+ byte[] productserialNumber = new byte[] { SERIALCODE_INVALID, 0, 0, 0, SERIALCODE_INVALID, 0, 0, 0, SERIALCODE_INVALID, 0, 0, 0, SERIALCODE_INVALID, 0, 0, 0 };
+ public String getProductSerialNumber() {
+ boolean invalid = false;
+ int length = productserialNumber.length / 4;
+ if (productserialNumber.length % 4 != 0) length++;
+ for (int i = 0; i < length; i++) {
+ if (productserialNumber[4 * i] == PRODUCT_SERIALCODE_INVALID) { // OemAddress = 0x04 - 7
+ invalid = true;
+ setPwrManagementMode(false);
+ rx000Setting.setOEMAddress(0x08 + i);
+ sendHostRegRequestHST_CMD(RfidReaderChipData.HostCommands.CMD_RDOEM);
+ }
+ }
+ if (invalid) return null;
+ appendToLog("retValue = " + byteArrayToString(productserialNumber));
+ byte[] retValue = new byte[productserialNumber.length];
+ for (int i = 0; i < retValue.length; i++) {
+ int j = (i/4)*4 + 3 - i%4;
+ if (j >= productserialNumber.length) retValue[i] = productserialNumber[i];
+ else retValue[i] = productserialNumber[j];
+ if (retValue[i] == 0) retValue[i] = 0x30;
+ }
+ appendToLog("retValue = " + byteArrayToString(retValue) + ", String = " + new String(retValue));
+ return new String(retValue);
+ }
+
+ final int VERSIONCODE_INVALID = -1; final int VERSIONCODE_MIN = 1; final int VERSIONCODE_MAX = 9;
+ int versionCode = VERSIONCODE_INVALID; // OemAddress = 0x02
+ public int getVersionCode() {
+ if (versionCode < VERSIONCODE_MIN || versionCode > VERSIONCODE_MAX) {
+ setPwrManagementMode(false);
+ rx000Setting.setOEMAddress(0x0B);
+ sendHostRegRequestHST_CMD(RfidReaderChipData.HostCommands.CMD_RDOEM);
+ }
+ return versionCode;
+ }
+
+ String spcialCountryVersion = null;
+ public String getSpecialCountryVersion() {
+ if (spcialCountryVersion == null) {
+ setPwrManagementMode(false);
+ rx000Setting.setOEMAddress(0x8E);
+ sendHostRegRequestHST_CMD(RfidReaderChipData.HostCommands.CMD_RDOEM);
+ return "";
+ }
+ return spcialCountryVersion.replaceAll("[^A-Za-z0-9]", "");
+ }
+
+ final int FREQMODIFYCODE_INVALID = -1; final int FREQMODIFYCODE_MIN = 0; final int FREQMODIFYCODE_MAX = 0xAA;
+ int freqModifyCode = FREQMODIFYCODE_INVALID; // OemAddress = 0x8A
+ public int getFreqModifyCode() {
+ if (freqModifyCode < FREQMODIFYCODE_MIN || freqModifyCode > FREQMODIFYCODE_MAX) {
+ setPwrManagementMode(false);
+ rx000Setting.setOEMAddress(0x8F);
+ sendHostRegRequestHST_CMD(RfidReaderChipData.HostCommands.CMD_RDOEM);
+ }
+ return freqModifyCode;
+ }
+
+ void writeOEM(int address, int value) {
+ setPwrManagementMode(false);
+ rx000Setting.setOEMAddress(address);
+ rx000Setting.setOEMData(value);
+ sendHostRegRequestHST_CMD(RfidReaderChipData.HostCommands.CMD_WROEM);
+ }
+ }
+ //public boolean bFirmware_reset_before = false;
+ final int RFID_READING_BUFFERSIZE = 1024;
+ enum RfidDataReadTypes {
+ RFID_DATA_READ_SOFTRESET, RFID_DATA_READ_ABORT, RFID_DATA_READ_RESETTOBOOTLOADER,
+ RFID_DATA_READ_REGREAD,
+ RFID_DATA_READ_COMMAND_BEGIN, RFID_DATA_READ_COMMAND_END,
+ RFID_DATA_READ_COMMAND_INVENTORY, RFID_DATA_READ_COMMAND_COMPACT, RFID_DATA_READ_COMMAND_ACCESS,
+ RFID_DATA_READ_COMMAND_MBPREAD, RFID_DATA_READ_COMMAND_OEMREAD,
+ RFID_DATA_READ_COMMAND_RSSI, RFID_DATA_READ_COMMAND_ACTIVE
+ };
+ //class RfidReaderChip {
+ byte[] mRfidToReading = new byte[RFID_READING_BUFFERSIZE];
+ int mRfidToReadingOffset = 0;
+ ArrayList mRx000ToWrite = new ArrayList<>();
+
+ public Rx000Setting rx000Setting = new Rx000Setting(true);
+ public Rx000EngSetting rx000EngSetting = new Rx000EngSetting();
+ public Rx000MbpSetting rx000MbpSetting = new Rx000MbpSetting();
+ public Rx000OemSetting rx000OemSetting = new Rx000OemSetting();
+
+ public ArrayList mRx000ToRead = new ArrayList<>();
+ private boolean clearTempDataIn_request = false;
+ boolean commandOperating;
+
+ public double decodeNarrowBandRSSI(byte byteRSSI) {
+ byte mantissa = byteRSSI;
+ mantissa &= 0x07;
+ byte exponent = byteRSSI;
+ exponent >>= 3;
+ double dValue = 20 * log10(pow(2, exponent) * (1 + (mantissa / pow(2, 3))));
+ if (false)
+ appendToLog("byteRSSI = " + String.format("%X", byteRSSI) + ", mantissa = " + mantissa + ", exponent = " + exponent + "dValue = " + dValue);
+ return dValue;
+ }
+
+ public int encodeNarrowBandRSSI(double dRSSI) {
+ double dValue = dRSSI / 20;
+ dValue = pow(10, dValue);
+ int exponent = 0;
+ if (false) appendToLog("exponent = " + exponent + ", dValue = " + dValue);
+ while ((dValue + 0.062) >= 2) {
+ dValue /= 2;
+ exponent++;
+ if (false) appendToLog("exponent = " + exponent + ", dValue = " + dValue);
+ }
+ dValue--;
+ int mantissa = (int) ((dValue * 8) + 0.5);
+ while (mantissa >= 8) {
+ mantissa -= 8;
+ exponent++;
+ }
+ int iValue = ((exponent & 0x1F) << 3) | (mantissa & 0x7);
+ if (false)
+ appendToLog("dRssi = " + dRSSI + ", exponent = " + exponent + ", mantissa = " + mantissa + ", iValue = " + String.format("%X", iValue));
+ return iValue;
+ }
+
+ long firmware_ontime_ms = 0;
+ long date_time_ms = 0;
+ public boolean bRx000ToReading = false;
+
+ void uplinkHandler() {
+ boolean DEBUG = false;
+ if (bRx000ToReading) return;
+ bRx000ToReading = true;
+ int startIndex = 0;
+ int startIndexOld = 0;
+ int startIndexNew = 0;
+ boolean packageFound = false;
+ int packageType = 0;
+ long lTime = System.currentTimeMillis();
+ boolean bdebugging = false;
+ if (csReaderConnector.rfidConnector.mRfidToRead.size() != 0) {
+ bdebugging = true;
+ if (DEBUGTHREAD) appendToLog("mRx000UplinkHandler(): START");
+ } else if (DEBUGTHREAD) appendToLog("mRx000UplinkHandler(): START AAA");
+ boolean bFirst = true;
+ byte[] data1 = null;
+ RfidDataReadTypes rfidDataReadTypes = null;
+ boolean bLooping = false;
+ while (csReaderConnector.rfidConnector.mRfidToRead.size() != 0) {
+ if (utility.DEBUG_APDATA && bLooping == false) appendToLog("ApData: Entering loop with mRfidToRead.size as " + csReaderConnector.rfidConnector.mRfidToRead.size());
+ bLooping = true;
+
+ if (csReaderConnector.isConnected() == false) {
+ csReaderConnector.rfidConnector.mRfidToRead.clear();
+ } else if (System.currentTimeMillis() - lTime > (intervalRx000UplinkHandler / 2)) {
+ writeDebug2File("Up4 " + String.valueOf(intervalRx000UplinkHandler) + "ms Timeout");
+ if (utility.DEBUG_APDATA)
+ appendToLogView("ApData: TIMEOUT !!! mRfidToRead.size() = " + csReaderConnector.rfidConnector.mRfidToRead.size());
+ break;
+ } else {
+ if (bFirst) {
+ bFirst = false;
+ }
+ byte[] dataIn = csReaderConnector.rfidConnector.mRfidToRead.get(0).dataValues;
+ long tagMilliSeconds = csReaderConnector.rfidConnector.mRfidToRead.get(0).milliseconds;
+ boolean invalidSequence = csReaderConnector.rfidConnector.mRfidToRead.get(0).invalidSequence;
+ if (utility.DEBUG_APDATA)
+ appendToLog("ApData: mRfidToReadingOffset=" + mRfidToReadingOffset + ", mRfidToReading.length=" + mRfidToReading.length + ", dataIn.length=" + dataIn.length + ", dataIn=" + byteArrayToString(dataIn));
+ csReaderConnector.rfidConnector.mRfidToRead.remove(0);
+
+ if (dataIn.length >= mRfidToReading.length - mRfidToReadingOffset) {
+ byte[] unhandledBytes = new byte[mRfidToReadingOffset];
+ System.arraycopy(mRfidToReading, 0, unhandledBytes, 0, unhandledBytes.length);
+ if (utility.DEBUG_APDATA)
+ appendToLogView("ApData: ERROR insufficient buffer, mRfidToReadingOffset=" + mRfidToReadingOffset + ", dataIn.length=" + dataIn.length + ", clear mRfidToReading: " + byteArrayToString(unhandledBytes));
+ byte[] mRfidToReadingNew = new byte[RFID_READING_BUFFERSIZE];
+ mRfidToReading = mRfidToReadingNew;
+ mRfidToReadingOffset = 0;
+ invalidUpdata++;
+ writeDebug2File("Up4 insufficient buffer. missed " + byteArrayToString(unhandledBytes));
+ }
+ if (mRfidToReadingOffset != 0 && invalidSequence) {
+ byte[] unhandledBytes = new byte[mRfidToReadingOffset];
+ System.arraycopy(mRfidToReading, 0, unhandledBytes, 0, unhandledBytes.length);
+ if (utility.DEBUG_APDATA)
+ appendToLog("ApData: ERROR invalidSequence with nonzero mRfidToReadingOffset=" + mRfidToReadingOffset + ", throw invalid unused data=" + unhandledBytes.length + ", " + byteArrayToString(unhandledBytes));
+ mRfidToReadingOffset = 0;
+ startIndex = 0;
+ startIndexNew = 0;
+ writeDebug2File("Up4 Invalid sequence, " + byteArrayToString(unhandledBytes));
+ }
+ System.arraycopy(dataIn, 0, mRfidToReading, mRfidToReadingOffset, dataIn.length);
+ mRfidToReadingOffset += dataIn.length;
+ if (utility.DEBUG_APDATA) {
+ byte[] bufferData = new byte[mRfidToReadingOffset];
+ System.arraycopy(mRfidToReading, 0, bufferData, 0, bufferData.length);
+ appendToLog("ApData: new mRfidToReadingOffset=" + mRfidToReadingOffset + ", mRfidToReading=" + byteArrayToString(bufferData));
+ }
+
+ int iPayloadSizeMin = 8; boolean bLooping2 = false;
+ while (mRfidToReadingOffset - startIndex >= iPayloadSizeMin) {
+ if (utility.DEBUG_APDATA && bLooping2 == false) appendToLog("ApData: Entering second loop with mRfidToReadingOffset = " + mRfidToReadingOffset + ", startIndex = " + startIndex);
+ bLooping2 = true;
+
+ {
+ int packageLengthRead = (mRfidToReading[startIndex + 5] & 0xFF) * 256 + (mRfidToReading[startIndex + 4] & 0xFF);
+ int expectedLength = 8 + packageLengthRead * 4;
+ if (mRfidToReading[startIndex + 0] == 0x04)
+ expectedLength = 8 + packageLengthRead;
+ if (utility.DEBUG_APDATA)
+ appendToLog("ApData: loop: 1Byte=" + mRfidToReading[startIndex + 0] + ", mRfidToReadingOffset=" + mRfidToReadingOffset + ", expectedLength=" + expectedLength);
+ if (mRfidToReadingOffset - startIndex >= 8) {
+ if (mRfidToReading[startIndex + 0] == (byte) 0x40
+ && (mRfidToReading[startIndex + 1] == 2 || mRfidToReading[startIndex + 1] == 3 || mRfidToReading[startIndex + 1] == 7)) { //input as Control Command Response
+ dataIn = mRfidToReading;
+ if (DEBUG) appendToLog("decoding CONTROL data");
+ if (csReaderConnector.rfidConnector.mRfidToWrite.size() == 0) {
+ if (DEBUG)
+ appendToLog("Control Response is received with null mRfidToWrite");
+ } else if (csReaderConnector.rfidConnector.mRfidToWrite.get(0) == null) {
+ if (DEBUG)
+ appendToLog("Control Response is received with null mRfidToWrite.get(0)");
+ } else if (csReaderConnector.rfidConnector.mRfidToWrite.get(0).dataValues == null) {
+ csReaderConnector.rfidConnector.mRfidToWrite.remove(0);
+ if (DEBUG) appendToLog("mmRfidToWrite remove 5");
+ if (DEBUG)
+ appendToLog("Control Response is received with null mRfidToWrite.dataValues");
+ } else if (!(csReaderConnector.rfidConnector.mRfidToWrite.get(0).dataValues[0] == dataIn[startIndex + 0] && csReaderConnector.rfidConnector.mRfidToWrite.get(0).dataValues[1] == dataIn[startIndex + 1])) {
+ if (DEBUG)
+ appendToLog("Control Response is received with Mis-matched mRfidToWrite, " + startIndex + ", " + byteArrayToString(dataIn));
+ } else {
+ byte[] dataInCompare = null;
+ switch (csReaderConnector.rfidConnector.mRfidToWrite.get(0).dataValues[1]) {
+ case 2: //SOFTRESET
+ rfidDataReadTypes = RfidDataReadTypes.RFID_DATA_READ_SOFTRESET;
+ dataInCompare = new byte[]{0x40, 0x02, (byte) 0xbf, (byte) 0xfd, (byte) 0xbf, (byte) 0xfd, (byte) 0xbf, (byte) 0xfd};
+ break;
+ case 3: //ABORT
+ rfidDataReadTypes = RfidDataReadTypes.RFID_DATA_READ_ABORT;
+ dataInCompare = new byte[]{0x40, 0x03, (byte) 0xbf, (byte) 0xfc, (byte) 0xbf, (byte) 0xfc, (byte) 0xbf, (byte) 0xfc};
+ break;
+ case 7: //RESETTOBOOTLOADER
+ rfidDataReadTypes = RfidDataReadTypes.RFID_DATA_READ_RESETTOBOOTLOADER;
+ dataInCompare = new byte[]{0x40, 0x07, (byte) 0xbf, (byte) 0xf8, (byte) 0xbf, (byte) 0xf8, (byte) 0xbf, (byte) 0xf8};
+ break;
+ }
+ byte[] dataIn8 = new byte[8];
+ System.arraycopy(dataIn, startIndex, dataIn8, 0, dataIn8.length);
+ if (!(compareArray(dataInCompare, dataIn8, 8))) {
+ if (DEBUG)
+ appendToLog("Control response with invalid data: " + byteArrayToString(dataIn8));
+ } else {
+ csReaderConnector.rfidConnector.mRfidToWrite.remove(0);
+ csReaderConnector.rfidConnector.sendRfidToWriteSent = 0;
+ csReaderConnector.rfidConnector.mRfidToWriteRemoved = true;
+ if (DEBUG) appendToLog("mmRfidToWrite remove 6");
+ if (DEBUG)
+ appendToLog("matched control command with mRfidToWrite.size=" + csReaderConnector.rfidConnector.mRfidToWrite.size());
+ }
+ }
+ if (true) {
+ byte[] dataIn8 = new byte[8];
+ System.arraycopy(dataIn, startIndex, dataIn8, 0, dataIn8.length);
+ byte[] dataInCompare = new byte[]{0x40, 0x03, (byte) 0xbf, (byte) 0xfc, (byte) 0xbf, (byte) 0xfc, (byte) 0xbf, (byte) 0xfc};
+ if (compareArray(dataInCompare, dataIn8, 8)) {
+ RfidReaderChipData.Rx000pkgData dataA = new RfidReaderChipData.Rx000pkgData();
+ dataA.dataValues = dataIn8;
+ dataA.responseType = RfidReaderChipData.HostCmdResponseTypes.TYPE_COMMAND_ABORT_RETURN;
+ mRx000ToRead.add(dataA);
+ if (DEBUG)
+ appendToLog("Abort Return data is found wth type = " + dataA.responseType.toString());
+ setInventoring(false);
+ }
+ }
+ packageFound = true;
+ packageType = 1; //0x40
+ startIndexNew = startIndex + iPayloadSizeMin;
+ } else if ((mRfidToReading[startIndex + 0] == (byte) 0x00 || mRfidToReading[startIndex + 0] == (byte) 0x70)
+ && mRfidToReading[startIndex + 1] == 0
+ && csReaderConnector.rfidConnector.mRfidToWrite.size() != 0
+ && csReaderConnector.rfidConnector.mRfidToWrite.get(0).dataValues != null
+ && csReaderConnector.rfidConnector.mRfidToWrite.get(0).dataValues[0] == 0x70
+ && csReaderConnector.rfidConnector.mRfidToWrite.get(0).dataValues[1] == 0
+ ) { //if input as HOST_REG_RESP
+ if (DEBUG)
+ appendToLog("loop: decoding HOST_REG_RESP data with startIndex = " + startIndex + ", mRfidToReading=" + byteArrayToString(mRfidToReading));
+ dataIn = mRfidToReading;
+ byte[] dataInPayload = new byte[4];
+ System.arraycopy(dataIn, startIndex + 4, dataInPayload, 0, dataInPayload.length);
+ //if (mRfidDevice.mRfidToWrite.size() == 0) {
+ // if (true) appendToLog("mRx000UplinkHandler(): HOST_REG_RESP is received with null mRfidToWrite: " + byteArrayToString(dataInPayload));
+ //} else if (mRfidDevice.mRfidToWrite.get(0).dataValues == null) {
+ // if (true) appendToLog("mRx000UplinkHandler(): NULL mRfidToWrite.get(0).dataValues"); //.length = " + mRfidDevice.mRfidToWrite.get(0).dataValues.length);
+ //} else if (!(mRfidDevice.mRfidToWrite.get(0).dataValues[0] == 0x70 && mRfidDevice.mRfidToWrite.get(0).dataValues[1] == 0)) {
+ // if (true) appendToLog("mRx000UplinkHandler(): HOST_REG_RESP is received with invalid mRfidDevice.mRfidToWrite.get(0).dataValues=" + byteArrayToString(mRfidDevice.mRfidToWrite.get(0).dataValues));
+ //} else
+ {
+ int addressToWrite = csReaderConnector.rfidConnector.mRfidToWrite.get(0).dataValues[2] + csReaderConnector.rfidConnector.mRfidToWrite.get(0).dataValues[3] * 256;
+ int addressToRead = dataIn[startIndex + 2] + dataIn[startIndex + 3] * 256;
+ if (addressToRead != addressToWrite) {
+ if (DEBUG)
+ appendToLog("mRx000UplinkHandler(): HOST_REG_RESP is received with misMatch address: addressToRead=" + addressToRead + ", " + startIndex + ", " + byteArrayToString(dataInPayload) + ", addressToWrite=" + addressToWrite);
+ } else {
+ switch (addressToRead) {
+ case 0:
+ int patchVersion = dataIn[startIndex + 4] + (dataIn[startIndex + 5] & 0x0F) * 256;
+ int minorVersion = (dataIn[startIndex + 5] >> 4) + dataIn[startIndex + 6] * 256;
+ int majorVersion = dataIn[startIndex + 7];
+ rx000Setting.macVer = String.valueOf(majorVersion) + "." + String.valueOf(minorVersion) + "." + String.valueOf(patchVersion);
+ if (DEBUG)
+ appendToLog("found MacVer =" + rx000Setting.macVer);
+ break;
+ case 9:
+ rx000Setting.mac_last_command_duration = (dataIn[startIndex + 4] & 0xFF)
+ + (dataIn[startIndex + 5] & 0xFF) * 256
+ + (dataIn[startIndex + 6] & 0xFF) * 256 * 256
+ + (dataIn[startIndex + 7] & 0xFF) * 256 * 256 * 256;
+ if (DEBUG)
+ appendToLog("found mac_last_command_duration =" + rx000Setting.mac_last_command_duration);
+ break;
+ case 0x0201:
+ rx000Setting.diagnosticCfg = (dataIn[startIndex + 4] & 0x0FF) + ((dataIn[startIndex + 5] & 0x03) * 256);
+ if (DEBUG)
+ appendToLog("found diagnostic configuration: " + byteArrayToString(dataInPayload) + ", diagnosticCfg=" + rx000Setting.diagnosticCfg);
+ break;
+ case 0x0203:
+ rx000Setting.impinjExtensionValue = (dataIn[startIndex + 4] & 0x03F);
+ break;
+ case 0x204:
+ rx000Setting.pwrMgmtStatus = (dataIn[startIndex + 4] & 0x07);
+ if (DEBUG)
+ appendToLog("pwrMgmtStatus = " + rx000Setting.pwrMgmtStatus);
+ break;
+ case 0x0700:
+ rx000Setting.antennaCycle = (dataIn[startIndex + 4] & 0xFF) + (dataIn[startIndex + 5] & 0xFF) * 256;
+ rx000Setting.antennaFreqAgile = 0;
+ if ((dataIn[startIndex + 7] & 0x01) != 0)
+ rx000Setting.antennaFreqAgile = 1;
+ if (DEBUG)
+ appendToLog("found antenna cycle: " + byteArrayToString(dataInPayload) + ", cycle=" + rx000Setting.antennaCycle + ", frequencyAgile=" + rx000Setting.antennaFreqAgile);
+ break;
+ case 0x0701:
+ rx000Setting.antennaSelect = (dataIn[startIndex + 4] & 0xFF) + (dataIn[startIndex + 5] & 0xFF) * 256 + (dataIn[startIndex + 6] & 0xFF) * 256 * 256 + (dataIn[startIndex + 7] & 0xFF) * 256 * 256 * 256;
+ if (DEBUG)
+ appendToLog("found antenna select, select=" + rx000Setting.antennaSelect);
+ break;
+ case 0x0702:
+ rx000Setting.antennaSelectedData[rx000Setting.antennaSelect].antennaEnable = (dataIn[startIndex + 4] & 0x01);
+ rx000Setting.antennaSelectedData[rx000Setting.antennaSelect].antennaInventoryMode = (dataIn[startIndex + 4] & 0x02) >> 1;
+ rx000Setting.antennaSelectedData[rx000Setting.antennaSelect].antennaLocalAlgo = (dataIn[startIndex + 4] & 0x0C) >> 2;
+ rx000Setting.antennaSelectedData[rx000Setting.antennaSelect].antennaLocalStartQ = (dataIn[startIndex + 4] & 0xF0) >> 4;
+ rx000Setting.antennaSelectedData[rx000Setting.antennaSelect].antennaProfileMode = (dataIn[startIndex + 5] & 0x01);
+ rx000Setting.antennaSelectedData[rx000Setting.antennaSelect].antennaLocalProfile = ((dataIn[startIndex + 5] & 0x1E) >> 1);
+ rx000Setting.antennaSelectedData[rx000Setting.antennaSelect].antennaFrequencyMode = ((dataIn[startIndex + 5] & 0x20) >> 5);
+ rx000Setting.antennaSelectedData[rx000Setting.antennaSelect].antennaLocalFrequency = (dataIn[startIndex + 5] & 0x0F) * 4 + ((dataIn[startIndex + 5] & 0xC0) >> 6);
+ if (DEBUG)
+ appendToLog("found antenna selectEnable: " + byteArrayToString(dataInPayload)
+ + ", selectEnable=" + rx000Setting.antennaSelectedData[rx000Setting.antennaSelect].antennaEnable
+ + ", inventoryMode=" + rx000Setting.antennaSelectedData[rx000Setting.antennaSelect].antennaInventoryMode
+ + ", localAlgo=" + rx000Setting.antennaSelectedData[rx000Setting.antennaSelect].antennaLocalAlgo
+ + ", localStartQ=" + rx000Setting.antennaSelectedData[rx000Setting.antennaSelect].antennaLocalStartQ
+ + ", profileMode=" + rx000Setting.antennaSelectedData[rx000Setting.antennaSelect].antennaProfileMode
+ + ", localProfile=" + rx000Setting.antennaSelectedData[rx000Setting.antennaSelect].antennaLocalProfile
+ + ", frequencyMode=" + rx000Setting.antennaSelectedData[rx000Setting.antennaSelect].antennaFrequencyMode
+ + ", localFrequency=" + rx000Setting.antennaSelectedData[rx000Setting.antennaSelect].antennaLocalFrequency
+ );
+ break;
+ case 0x0703:
+ rx000Setting.antennaSelectedData[rx000Setting.antennaSelect].antennaStatus = (dataIn[startIndex + 4] & 0xFF) + (dataIn[startIndex + 5] & 0xFF) * 256 + (dataIn[startIndex + 6] & 0x0F) * 256 * 256;
+ if (DEBUG)
+ appendToLog("found antenna status: " + byteArrayToString(dataInPayload) + ", status=" + rx000Setting.antennaSelectedData[rx000Setting.antennaSelect].antennaStatus);
+ break;
+ case 0x0704:
+ rx000Setting.antennaSelectedData[rx000Setting.antennaSelect].antennaDefine = (dataIn[startIndex + 4] & 0x3);
+ // mRx000Setting.antennaSelectedData[mRx000Setting.antennaSelect].antennaRxDefine = (dataIn[startIndex + 6] & 0x3);
+ if (DEBUG)
+ appendToLog("found antenna define: " + byteArrayToString(dataInPayload)
+ + ", define=" + rx000Setting.antennaSelectedData[rx000Setting.antennaSelect].antennaDefine
+ // + ", RxDefine=" + mRx000Setting.antennaSelectedData[mRx000Setting.antennaSelect].antennaRxDefine
+ );
+ break;
+ case 0x0705:
+ rx000Setting.antennaSelectedData[rx000Setting.antennaSelect].antennaDwell = (dataIn[startIndex + 4] & 0xFF) + (dataIn[startIndex + 5] & 0xFF) * 256 + (dataIn[startIndex + 6] & 0xFF) * 256 * 256 + (dataIn[startIndex + 7] & 0xFF) * 256 * 256 * 256;
+ if (DEBUG)
+ appendToLog("found antenna dwell=" + rx000Setting.antennaSelectedData[rx000Setting.antennaSelect].antennaDwell);
+ break;
+ case 0x0706:
+ if (rx000Setting.antennaSelectedData[rx000Setting.antennaSelect].antennaPowerSet == false)
+ rx000Setting.antennaSelectedData[rx000Setting.antennaSelect].antennaPower = (dataIn[startIndex + 4] & 0xFF) + (dataIn[startIndex + 5] & 0xFF) * 256 + (dataIn[startIndex + 6] & 0xFF) * 256 * 256 + (dataIn[startIndex + 7] & 0xFF) * 256 * 256 * 256;
+ break;
+ case 0x0707:
+ rx000Setting.antennaSelectedData[rx000Setting.antennaSelect].antennaInvCount = (dataIn[startIndex + 4] & 0xFF) + (dataIn[startIndex + 5] & 0xFF) * 256 + (dataIn[startIndex + 6] & 0xFF) * 256 * 256 + (dataIn[startIndex + 7] & 0xFF) * 256 * 256 * 256;
+ if (DEBUG)
+ appendToLog("found antenna InvCount=" + rx000Setting.antennaSelectedData[rx000Setting.antennaSelect].antennaInvCount);
+ break;
+ case 0x0800:
+ rx000Setting.invSelectIndex = (dataIn[startIndex + 4] & 0xFF) + (dataIn[startIndex + 5] & 0xFF) * 256 + (dataIn[startIndex + 6] & 0xFF) * 256 * 256 + (dataIn[startIndex + 7] & 0xFF) * 256 * 256 * 256;
+ if (DEBUG)
+ appendToLog("found inventory select: " + byteArrayToString(dataInPayload) + ", select=" + rx000Setting.invSelectIndex);
+ break;
+ case 0x0801: {
+ int dataIndex = rx000Setting.invSelectIndex;
+ if (dataIndex < rx000Setting.INVSELECT_MIN || dataIndex > rx000Setting.INVSELECT_MAX) {
+ if (DEBUG)
+ appendToLog("found inventory select configuration: " + byteArrayToString(dataInPayload) + ", but invalid index=" + dataIndex);
+ } else {
+ appendToLog("BtDataOut 123A");
+ rx000Setting.invSelectData[dataIndex].selectEnable = (dataIn[startIndex + 4] & 0x01);
+ rx000Setting.invSelectData[dataIndex].selectTarget = ((dataIn[startIndex + 4] & 0x0E) >> 1);
+ rx000Setting.invSelectData[dataIndex].selectAction = ((dataIn[startIndex + 4] & 0x70) >> 4);
+ rx000Setting.invSelectData[dataIndex].selectDelay = dataIn[startIndex + 5];
+ if (DEBUG)
+ appendToLog("found inventory select configuration: " + byteArrayToString(dataInPayload)
+ + ", selectEnable=" + rx000Setting.invSelectData[dataIndex].selectEnable
+ + ", selectTarget=" + rx000Setting.invSelectData[dataIndex].selectTarget
+ + ", selectAction=" + rx000Setting.invSelectData[dataIndex].selectAction
+ + ", selectDelay=" + rx000Setting.invSelectData[dataIndex].selectDelay
+ );
+ }
+ break;
+ }
+ case 0x0802: {
+ int dataIndex = rx000Setting.invSelectIndex;
+ if (dataIndex < rx000Setting.INVSELECT_MIN || dataIndex > rx000Setting.INVSELECT_MAX) {
+ if (DEBUG)
+ appendToLog("found inventory select mask bank: " + byteArrayToString(dataInPayload) + ", but invalid index=" + dataIndex);
+ } else {
+ rx000Setting.invSelectData[dataIndex].selectMaskBank = (dataIn[startIndex + 4] & 0x03);
+ if (DEBUG)
+ appendToLog("found inventory select mask bank: " + byteArrayToString(dataInPayload)
+ + ", selectMaskBank=" + rx000Setting.invSelectData[dataIndex].selectMaskBank
+ );
+ }
+ break;
+ }
+ case 0x0803: {
+ int dataIndex = rx000Setting.invSelectIndex;
+ if (dataIndex < rx000Setting.INVSELECT_MIN || dataIndex > rx000Setting.INVSELECT_MAX) {
+ if (DEBUG)
+ appendToLog("found inventory select mask offset: " + byteArrayToString(dataInPayload) + ", but invalid index=" + dataIndex);
+ } else {
+ rx000Setting.invSelectData[dataIndex].selectMaskOffset = (dataIn[startIndex + 4] & 0x0FF) + (dataIn[startIndex + 5] & 0x0FF) * 256 + (dataIn[startIndex + 6] & 0x0FF) * 256 * 256 + (dataIn[startIndex + 7] & 0x0FF) * 256 * 256 * 256;
+ if (DEBUG)
+ appendToLog("found inventory select mask offset: " + byteArrayToString(dataInPayload)
+ + ", selectMaskOffset=" + rx000Setting.invSelectData[dataIndex].selectMaskOffset
+ );
+ }
+ break;
+ }
+ case 0x0804: {
+ int dataIndex = rx000Setting.invSelectIndex;
+ if (dataIndex < rx000Setting.INVSELECT_MIN || dataIndex > rx000Setting.INVSELECT_MAX) {
+ if (DEBUG)
+ appendToLog("found inventory select mask length: " + byteArrayToString(dataInPayload) + ", but invalid index=" + dataIndex);
+ } else {
+ rx000Setting.invSelectData[dataIndex].selectMaskLength = (dataIn[startIndex + 4] & 0x0FF);
+ if (DEBUG)
+ appendToLog("getSelectMaskData with read selectMaskLength = " + rx000Setting.invSelectData[dataIndex].selectMaskLength);
+ if (DEBUG)
+ appendToLog("found inventory select mask length: " + byteArrayToString(dataInPayload)
+ + ", selectMaskLength=" + rx000Setting.invSelectData[dataIndex].selectMaskLength
+ );
+ }
+ break;
+ }
+ case 0x0805:
+ case 0x0806:
+ case 0x0807:
+ case 0x0808:
+ case 0x0809:
+ case 0x080A:
+ case 0x080B:
+ case 0x080C: {
+ int dataIndex = rx000Setting.invSelectIndex;
+ if (dataIndex < rx000Setting.INVSELECT_MIN || dataIndex > rx000Setting.INVSELECT_MAX) {
+ if (DEBUG)
+ appendToLog("found inventory select mask 0-3: " + byteArrayToString(dataInPayload) + ", but invalid index=" + dataIndex);
+ } else {
+ int maskDataIndex = addressToRead - 0x0805;
+ if (DEBUG)
+ appendToLog("Old selectMaskData0_31 = " + byteArrayToString(rx000Setting.invSelectData[dataIndex].selectMaskData0_31));
+ System.arraycopy(dataIn, startIndex + 4, rx000Setting.invSelectData[dataIndex].selectMaskData0_31, maskDataIndex * 4, 4);
+ if (DEBUG)
+ appendToLog("Old selectMaskData0_31 = " + byteArrayToString(rx000Setting.invSelectData[dataIndex].selectMaskData0_31));
+ rx000Setting.invSelectData[dataIndex].selectMaskDataReady |= (0x01 << maskDataIndex);
+ if (DEBUG)
+ appendToLog("found inventory select mask 0-3: " + byteArrayToString(dataInPayload));
+ }
+ break;
+ }
+ case 0x0900:
+ if (rx000Setting.queryTarget != 2)
+ rx000Setting.queryTarget = (dataIn[startIndex + 4] >> 4) & 0x01;
+ rx000Setting.querySession = (dataIn[startIndex + 4] >> 5) & 0x03;
+ rx000Setting.querySelect = (dataIn[startIndex + 4] >> 7) & 0x01 + ((dataIn[startIndex + 5] & 0x01) * 2);
+ //appendToLog("BtDataOut: found query configuration: " + byteArrayToString(dataInPayload) + ", target=" + rx000Setting.queryTarget + ", session=" + rx000Setting.querySession + ", select=" + rx000Setting.querySelect);
+ break;
+ case 0x0901:
+ rx000Setting.invAlgo = dataIn[startIndex + 4] & 0x3F;
+ rx000Setting.matchRep = ((dataIn[startIndex + 4] & 0xC0) >> 6) + (dataIn[startIndex + 5] & 0x3F) * 4;
+ rx000Setting.tagSelect = ((dataIn[startIndex + 5] & 0x40) >> 6);
+ rx000Setting.noInventory = ((dataIn[startIndex + 5] & 0x80) >> 7);
+ rx000Setting.tagRead = dataIn[startIndex + 6] & 0x03;
+ rx000Setting.tagDelay = ((dataIn[startIndex + 7] & 0x03) * 16 + ((dataIn[startIndex + 6] & 0xF0) >> 4));
+ rx000Setting.invModeCompact = ((dataIn[startIndex + 7] & 0x04) >> 2);
+ appendToLog("BtDataOut: invAuthenticate = " + rx000Setting.invAuthenticate);
+ rx000Setting.invAuthenticate = ((dataIn[startIndex + 7] & 0x10) >> 4);
+ appendToLog("BtDataOut: invAuthenticate = " + rx000Setting.invAuthenticate);
+ if (DEBUG)
+ appendToLog("found inventory configuration: " + byteArrayToString(dataInPayload) + ", algorithm=" + rx000Setting.invAlgo + ", matchRep=" + rx000Setting.matchRep + ", tagSelect=" + rx000Setting.tagSelect + ", noInventory=" + rx000Setting.noInventory + ", tagRead=" + rx000Setting.tagRead + ", tagDelay=" + rx000Setting.tagDelay);
+ break;
+ case 0x0902:
+ if (dataIn[startIndex + 6] != 0 || dataIn[startIndex + 7] != 0) {
+ if (DEBUG)
+ appendToLog("found inventory select, but too big: " + byteArrayToString(dataInPayload));
+ } else {
+ rx000Setting.algoSelect = (dataIn[startIndex + 4] & 0xFF) + (dataIn[startIndex + 5] & 0xFF) * 256;
+ if (DEBUG)
+ appendToLog("found inventory algorithm select=" + rx000Setting.algoSelect);
+ }
+ break;
+ case 0x0903: {
+ int dataIndex = rx000Setting.algoSelect;
+ if (dataIndex < rx000Setting.ALGOSELECT_MIN || dataIndex > rx000Setting.ALGOSELECT_MAX) {
+ if (DEBUG)
+ appendToLog("found inventory algo parameter 0: " + byteArrayToString(dataInPayload) + ", but invalid index=" + dataIndex);
+ } else {
+ rx000Setting.algoSelectedData[dataIndex].algoStartQ = (dataIn[startIndex + 4] & 0x0F);
+ rx000Setting.algoSelectedData[dataIndex].algoMaxQ = ((dataIn[startIndex + 4] & 0xF0) >> 4);
+ rx000Setting.algoSelectedData[dataIndex].algoMinQ = (dataIn[startIndex + 5] & 0x0F);
+ rx000Setting.algoSelectedData[dataIndex].algoMaxRep = ((dataIn[startIndex + 5] & 0xF0) >> 4) + ((dataIn[startIndex + 6] & 0x0F) << 4);
+ rx000Setting.algoSelectedData[dataIndex].algoHighThres = ((dataIn[startIndex + 6] & 0xF0) >> 4);
+ rx000Setting.algoSelectedData[dataIndex].algoLowThres = (dataIn[startIndex + 7] & 0x0F);
+ if (DEBUG || true)
+ appendToLog("BtDataOut: found inventory algo parameter 0: " + byteArrayToString(dataInPayload)
+ + ", algoStartQ=" + rx000Setting.algoSelectedData[dataIndex].algoStartQ
+ + ", algoMaxQ=" + rx000Setting.algoSelectedData[dataIndex].algoMaxQ
+ + ", algoMinQ=" + rx000Setting.algoSelectedData[dataIndex].algoMinQ
+ + ", algoMaxRep=" + rx000Setting.algoSelectedData[dataIndex].algoMaxRep
+ + ", algoHighThres=" + rx000Setting.algoSelectedData[dataIndex].algoHighThres
+ + ", algoLowThres=" + rx000Setting.algoSelectedData[dataIndex].algoLowThres
+ );
+ }
+ break;
+ }
+ case 0x0904: {
+ int dataIndex = rx000Setting.algoSelect;
+ if (dataIndex < rx000Setting.ALGOSELECT_MIN || dataIndex > rx000Setting.ALGOSELECT_MAX) {
+ if (DEBUG)
+ appendToLog("found inventory algo parameter 1: " + byteArrayToString(dataInPayload) + ", but invalid index=" + dataIndex);
+ } else {
+ rx000Setting.algoSelectedData[dataIndex].algoRetry = dataIn[startIndex + 4] & 0x0FF;
+ if (DEBUG)
+ appendToLog("found inventory algo parameter 1: " + byteArrayToString(dataInPayload) + ", algoRetry=" + rx000Setting.algoSelectedData[dataIndex].algoRetry);
+ }
+ break;
+ }
+ case 0x0905: {
+ int dataIndex = rx000Setting.algoSelect;
+ if (dataIndex < rx000Setting.ALGOSELECT_MIN || dataIndex > rx000Setting.ALGOSELECT_MAX) {
+ if (DEBUG)
+ appendToLog("found inventory algo parameter 2: " + byteArrayToString(dataInPayload) + ", but invalid index=" + dataIndex);
+ } else {
+ if (DEBUG)
+ appendToLog("found inventory algo parameter 2: " + byteArrayToString(dataInPayload) + ", dataIndex=" + dataIndex + ", algoAbFlip=" + rx000Setting.algoSelectedData[dataIndex].algoAbFlip + ", algoRunTilZero=" + rx000Setting.algoSelectedData[dataIndex].algoRunTilZero);
+ rx000Setting.algoSelectedData[dataIndex].algoAbFlip = dataIn[startIndex + 4] & 0x01;
+ rx000Setting.algoSelectedData[dataIndex].algoRunTilZero = (dataIn[startIndex + 4] & 0x02) >> 1;
+ if (DEBUG)
+ appendToLog("found inventory algo parameter 2: " + byteArrayToString(dataInPayload) + ", algoAbFlip=" + rx000Setting.algoSelectedData[dataIndex].algoAbFlip + ", algoRunTilZero=" + rx000Setting.algoSelectedData[dataIndex].algoRunTilZero);
+ }
+ break;
+ }
+ case 0x0907:
+ rx000Setting.rssiFilterType = dataIn[startIndex + 4] & 0xF;
+ rx000Setting.rssiFilterOption = (dataIn[startIndex + 4] >> 4) & 0xF;
+ break;
+ case 0x0908:
+ rx000Setting.rssiFilterThreshold1 = dataIn[startIndex + 4];
+ rx000Setting.rssiFilterThreshold1 += (dataIn[startIndex + 5] << 8);
+ rx000Setting.rssiFilterThreshold2 = dataIn[startIndex + 6];
+ rx000Setting.rssiFilterThreshold2 += (dataIn[startIndex + 7] << 8);
+ break;
+ case 0x0909:
+ rx000Setting.rssiFilterCount = dataIn[startIndex + 4];
+ rx000Setting.rssiFilterCount += (dataIn[startIndex + 5] << 8);
+ rx000Setting.rssiFilterCount += (dataIn[startIndex + 6] << 16);
+ rx000Setting.rssiFilterCount += (dataIn[startIndex + 7] << 24);
+ break;
+ case 0x0911:
+ rx000Setting.matchEnable = dataIn[startIndex + 4] & 0x01;
+ rx000Setting.matchType = ((dataIn[startIndex + 4] & 0x02) >> 1);
+ rx000Setting.matchLength = ((dataIn[startIndex + 4] & 0x0FF) >> 2) + (dataIn[startIndex + 5] & 0x07) * 64;
+ rx000Setting.matchOffset = ((dataIn[startIndex + 5] & 0x0FF) >> 3) + (dataIn[startIndex + 6] & 0x1F) * 32;
+ if (DEBUG)
+ appendToLog("found inventory match configuration: " + byteArrayToString(dataInPayload) + ", selectEnable=" + rx000Setting.matchEnable + ", matchType=" + rx000Setting.matchType + ", matchLength=" + rx000Setting.matchLength + ", matchOffset=" + rx000Setting.matchOffset);
+ break;
+ case 0x0912:
+ case 0x0913:
+ case 0x0914:
+ case 0x0915:
+ case 0x0916:
+ case 0x0917:
+ case 0x0918:
+ case 0x0919:
+ case 0x091A:
+ case 0x091B:
+ case 0x091C:
+ case 0x091D:
+ case 0x091E:
+ case 0x091F:
+ case 0x0920:
+ case 0x0921: {
+ int maskDataIndex = addressToRead - 0x0912;
+ System.arraycopy(dataIn, startIndex + 4, rx000Setting.invMatchData0_63, maskDataIndex * 4, 4);
+ rx000Setting.invMatchDataReady |= (0x01 << maskDataIndex);
+ if (DEBUG)
+ appendToLog("found inventory match Data 0-3: " + byteArrayToString(dataInPayload));
+ break;
+ }
+ case 0x0A01:
+ rx000Setting.accessRetry = (dataIn[startIndex + 4] & 0x0E) >> 1;
+ if (DEBUG)
+ appendToLog("found access algoRetry: " + byteArrayToString(dataInPayload) + ", accessRetry=" + rx000Setting.accessRetry);
+ break;
+ case 0x0A02:
+ rx000Setting.accessBank = (dataIn[startIndex + 4] & 0x03);
+ rx000Setting.accessBank2 = ((dataIn[startIndex + 4] >> 2) & 0x03);
+ if (DEBUG)
+ appendToLog("found access bank: " + byteArrayToString(dataInPayload) + ", accessBank=" + rx000Setting.accessBank + ", accessBank2=" + rx000Setting.accessBank2);
+ break;
+ case 0x0A03:
+ if (rx000Setting.tagRead != 0) {
+ rx000Setting.accessOffset = (dataIn[startIndex + 4] & 0x0FF) + (dataIn[startIndex + 5] & 0x0FF) * 256; // + (dataIn[startIndex + 6] & 0x0FF) * 256 * 256 + (dataIn[startIndex + 7] & 0x0FF) * 256 * 256 * 256;
+ rx000Setting.accessOffset2 = (dataIn[startIndex + 6] & 0x0FF) + (dataIn[startIndex + 7] & 0x0FF) * 256; // + (dataIn[startIndex + 6] & 0x0FF) * 256 * 256 + (dataIn[startIndex + 7] & 0x0FF) * 256 * 256 * 256;
+ } else {
+ rx000Setting.accessOffset = (dataIn[startIndex + 4] & 0x0FF) + (dataIn[startIndex + 5] & 0x0FF) * 256 + (dataIn[startIndex + 6] & 0x0FF) * 256 * 256 + (dataIn[startIndex + 7] & 0x0FF) * 256 * 256 * 256;
+ }
+ if (DEBUG)
+ appendToLog("found access offset: " + byteArrayToString(dataInPayload) + ", accessOffset=" + rx000Setting.accessOffset + ", accessOffset2=" + rx000Setting.accessOffset2);
+ break;
+ case 0x0A04:
+ rx000Setting.accessCount = (dataIn[startIndex + 4] & 0x0FF);
+ rx000Setting.accessCount2 = (dataIn[startIndex + 5] & 0x0FF);
+ if (DEBUG)
+ appendToLog("found access count: " + byteArrayToString(dataInPayload) + ", accessCount=" + rx000Setting.accessCount + ", accessCount2=" + rx000Setting.accessCount2);
+ break;
+ case 0x0A05:
+ rx000Setting.accessLockAction = (dataIn[startIndex + 4] & 0x0FF) + ((dataIn[startIndex + 5] & 0x03) * 256);
+ rx000Setting.accessLockMask = ((dataIn[startIndex + 5] & 0x0FF) >> 2) + ((dataIn[startIndex + 6] & 0x0F) * 64);
+ if (DEBUG)
+ appendToLog("found access lock configuration: " + byteArrayToString(dataInPayload) + ", accessLockAction=" + rx000Setting.accessLockAction + ", accessLockMask=" + rx000Setting.accessLockMask);
+ break;
+ case 0x0A08:
+ rx000Setting.accessWriteDataSelect = (dataIn[startIndex + 4] & 0x07);
+ if (DEBUG)
+ appendToLog("found write data select: " + byteArrayToString(dataInPayload) + ", accessWriteDataSelect=" + rx000Setting.accessWriteDataSelect);
+ break;
+ case 0x0A09:
+ case 0x0A0A:
+ case 0x0A0B:
+ case 0x0A0C:
+ case 0x0A0D:
+ case 0x0A0E:
+ case 0x0A0F:
+ case 0x0A10:
+ case 0x0A11:
+ case 0x0A12:
+ case 0x0A13:
+ case 0x0A14:
+ case 0x0A15:
+ case 0x0A16:
+ case 0x0A17:
+ case 0x0A18: {
+ int maskDataIndex = addressToRead - 0x0A09;
+ int maskDataIndexH = 0;
+ if (rx000Setting.accessWriteDataSelect != 0)
+ maskDataIndexH = 16;
+ for (int k = 0; k < 4; k++) {
+ rx000Setting.accWriteData0_63[(maskDataIndexH + maskDataIndex) * 4 + k] = dataIn[startIndex + 7 - k];
+ }
+ rx000Setting.accWriteDataReady |= (0x01 << (maskDataIndexH + maskDataIndex));
+ if (DEBUG)
+ appendToLog("accessWriteData=" + rx000Setting.accWriteData0_63);
+ if (DEBUG)
+ appendToLog("found access write data 0-3: " + byteArrayToString(dataInPayload));
+ break;
+ }
+ case 0x0b60:
+ rx000Setting.currentProfile = dataIn[startIndex + 4];
+ if (DEBUG)
+ appendToLog("found current profile: " + byteArrayToString(dataInPayload) + ", profile=" + rx000Setting.currentProfile);
+ break;
+ case 0x0c01:
+ rx000Setting.freqChannelSelect = dataIn[startIndex + 4];
+ if (DEBUG)
+ appendToLog("setFreqChannelSelect: found frequency channel select: " + byteArrayToString(dataInPayload) + ", freqChannelSelect=" + rx000Setting.freqChannelSelect);
+ break;
+ case 0x0c02:
+ rx000Setting.freqChannelConfig = dataIn[startIndex + 4] & 0x01;
+ if (DEBUG)
+ appendToLog("found frequency channel configuration: " + byteArrayToString(dataInPayload) + ", channelConfig=" + rx000Setting.freqChannelConfig);
+ break;
+ case 0x0f00:
+ rx000Setting.authenticateSendReply = ((dataIn[startIndex + 4] & 1) != 0) ? true : false;
+ rx000Setting.authenticateIncReplyLength = ((dataIn[startIndex + 4] & 2) != 0) ? true : false;
+ rx000Setting.authenticateLength = ((dataIn[startIndex + 5] & 0xFC) >> 3) + (dataIn[startIndex + 6] & 0x3F);
+ if (DEBUG)
+ appendToLog("found authenticate configuration: " + byteArrayToString(dataInPayload));
+ break;
+ case 0x0f01:
+ case 0x0f02:
+ case 0x0f03:
+ case 0x0f04: {
+ int maskDataIndex = addressToRead - 0x0f01;
+ System.arraycopy(dataIn, startIndex + 4, rx000Setting.authMatchData0_63, maskDataIndex * 4, 4);
+ //mRx000Setting.authMatchDataReady |= (0x01 << maskDataIndex);
+ if (DEBUG)
+ appendToLog("found authenticate match Data 0-3: " + byteArrayToString(dataInPayload));
+ break;
+ }
+ case 0x0f05:
+ rx000Setting.untraceableRange = dataIn[startIndex + 4] & 0x03;
+ rx000Setting.untraceableUser = ((dataIn[startIndex + 4] & 0x04) != 0) ? true : false;
+ rx000Setting.untraceableTid = ((dataIn[startIndex + 4] & 0x18) >> 3);
+ rx000Setting.untraceableEpcLength = ((dataIn[startIndex + 4] & 0xE0) >> 5) + ((dataIn[startIndex + 5] & 0x3) << 3);
+ rx000Setting.untraceableEpc = ((dataIn[startIndex + 5] & 4) != 0) ? true : false;
+ rx000Setting.untraceableUXpc = ((dataIn[startIndex + 5] & 8) != 0) ? true : false;
+ if (DEBUG)
+ appendToLog("found untraceable configuration: " + byteArrayToString(dataInPayload));
+ break;
+ default:
+ if (DEBUG)
+ appendToLog("found OTHERS with addressToWrite=" + addressToWrite + ", addressToRead=" + addressToRead + ", " + byteArrayToString(dataInPayload));
+ break;
+ }
+ rfidDataReadTypes = RfidDataReadTypes.RFID_DATA_READ_REGREAD;
+ csReaderConnector.rfidConnector.mRfidToWrite.remove(0);
+ csReaderConnector.rfidConnector.sendRfidToWriteSent = 0;
+ csReaderConnector.rfidConnector.mRfidToWriteRemoved = true;
+ if (DEBUG) appendToLog("mmRfidToWrite remove 7");
+ }
+ }
+ packageFound = true;
+ packageType = 2; //0x00, 0x70
+ startIndexNew = startIndex + 8;
+ } else if ((mRfidToReading[startIndex + 0] >= 1 && mRfidToReading[startIndex + 0] <= 4) //02 for begin and end, 03 for inventory, 01 for access
+ && (expectedLength >= 0 && expectedLength < mRfidToReading.length)
+ && (mRfidToReading[startIndex + 2] == 0 || mRfidToReading[startIndex + 2] == 1 || (mRfidToReading[startIndex + 2] >= 5 && mRfidToReading[startIndex + 2] <= 14))
+ && (mRfidToReading[startIndex + 3] == 0 || mRfidToReading[startIndex + 3] == 0x30 || mRfidToReading[startIndex + 3] == (byte) 0x80)
+// && mRfidToReading[startIndex + 6] == 0 //for packageTypeRead = 0x3007, this byte is 0x20. Others are 0
+ && mRfidToReading[startIndex + 7] == 0) { //if input as command response
+ {
+ if (DEBUG) appendToLog("loop: decoding 1_4 data");
+ if (mRfidToReadingOffset - startIndex < expectedLength)
+ break;
+ dataIn = mRfidToReading;
+ byte[] dataInPayload = new byte[expectedLength - 4];
+ System.arraycopy(dataIn, startIndex + 4, dataInPayload, 0, dataInPayload.length);
+ //if ((dataIn[startIndex + 3] == (byte) 0x80 && dataIn[startIndex + 6] == 0 && dataIn[startIndex + 7] == 0) == false) {
+ // appendToLog("mRx000UplinkHandler(): invalid command response is received with incorrect byte3= " + dataIn[startIndex + 3] + ", byte6=" + dataIn[startIndex + 6] + ", byte7=" + dataIn[startIndex + 7]);
+ //}
+
+ int packageTypeRead = dataIn[startIndex + 2] + (dataIn[startIndex + 3] & 0xFF) * 256;
+ RfidReaderChipData.Rx000pkgData dataA = new RfidReaderChipData.Rx000pkgData();
+ if (packageTypeRead == 6 && (dataIn[startIndex + 1] & 0x02) != 0 && dataIn[startIndex + 13] == 0) {
+ dataIn[startIndex + 13] = (byte) 0xFF;
+ }
+ int padCount = ((dataIn[startIndex + 1] & 0x0FF) >> 6);
+ if (packageTypeRead == 6) {
+ dataA.dataValues = new byte[8 + packageLengthRead * 4 - padCount];
+ System.arraycopy(dataIn, startIndex, dataA.dataValues, 0, dataA.dataValues.length);
+ } else if (packageTypeRead == 0x8005 || packageTypeRead == 5) {
+ if (dataIn[startIndex + 0] == 0x04) {
+ dataA.dataValues = new byte[packageLengthRead];
+ dataA.decodedPort = dataIn[startIndex + 6];
+ } else
+ dataA.dataValues = new byte[packageLengthRead * 4 - padCount];
+ System.arraycopy(dataIn, startIndex + 8, dataA.dataValues, 0, dataA.dataValues.length);
+ } else {
+ dataA.dataValues = new byte[packageLengthRead * 4];
+ System.arraycopy(dataIn, startIndex + 8, dataA.dataValues, 0, dataA.dataValues.length);
+ }
+ dataA.flags = (dataIn[startIndex + 1] & 0xFF);
+ switch (packageTypeRead) {
+ case 0x0000:
+ case 0x8000: //RFID_PACKET_TYPE_COMMAND_BEGIN //original 0
+ if (dataIn[startIndex + 0] != 1 && dataIn[startIndex + 0] != 2) {
+ if (DEBUG)
+ appendToLog("command COMMAND_BEGIN is found without first byte as 0x01 or 0x02, " + byteArrayToString(dataInPayload));
+ } else if (csReaderConnector.rfidConnector.mRfidToWrite.size() == 0) {
+ if (DEBUG)
+ appendToLog("command COMMAND_BEGIN is found without mRfidToWrite");
+ } else {
+ byte[] dataWritten = csReaderConnector.rfidConnector.mRfidToWrite.get(0).dataValues;
+ if (dataWritten == null) {
+ } else if (!(dataWritten[0] == (byte) 0x70 && dataWritten[1] == 1 && dataWritten[2] == 0 && dataWritten[3] == (byte) 0xF0)) {
+ if (DEBUG)
+ appendToLog("command COMMAND_BEGIN is found with invalid mRfidToWrite: " + byteArrayToString(dataWritten));
+ } else {
+ boolean matched = true;
+ for (int i = 0; i < 4; i++) {
+ if (dataWritten[4 + i] != dataIn[startIndex + 8 + i]) {
+ matched = false;
+ break;
+ }
+ }
+ long lValue = 0;
+ int multipler = 1;
+ for (int i = 0; i < 4; i++) {
+ lValue += (dataIn[startIndex + 12 + i] & 0xFF) * multipler;
+ multipler *= 256;
+ }
+ if (matched == false) {
+ if (DEBUG)
+ appendToLog("command COMMAND_BEGIN is found with mis-matched command:" + byteArrayToString(dataWritten));
+ } else {
+ csReaderConnector.rfidConnector.mRfidToWrite.remove(0);
+ csReaderConnector.rfidConnector.sendRfidToWriteSent = 0;
+ csReaderConnector.rfidConnector.mRfidToWriteRemoved = true;
+ if (DEBUG)
+ appendToLog("mmRfidToWrite remove 8");
+ setInventoring(true);
+ Date date = new Date();
+ long date_time = date.getTime();
+ long expected_firmware_ontime_ms = firmware_ontime_ms;
+ if (date_time_ms != 0) {
+ long firmware_ontime_ms_difference = date_time - date_time_ms;
+ if (firmware_ontime_ms_difference > 2000) {
+ expected_firmware_ontime_ms += (firmware_ontime_ms_difference - 2000);
+ }
+ }
+ if (lValue < expected_firmware_ontime_ms) {
+ csReaderConnector.rfidReader.bFirmware_reset_before = true;
+ if (DEBUG)
+ appendToLogView("command COMMAND_BEGIN --- Firmware reset before !!!");
+ }
+ firmware_ontime_ms = lValue;
+ date_time_ms = date_time;
+ if (DEBUG)
+ appendToLog("command COMMAND_BEGIN is found with packageLength=" + packageLengthRead + ", with firmware count=" + lValue + ", date_time=" + date_time + ", expected firmware count=" + expected_firmware_ontime_ms);
+ rfidDataReadTypes = RfidDataReadTypes.RFID_DATA_READ_COMMAND_BEGIN;
+ }
+ }
+ }
+ break;
+ case 0x0001:
+ case 0x8001: //RFID_PACKET_TYPE_COMMAND_END //original 1
+ if (dataIn[startIndex + 0] != 1 && dataIn[startIndex + 0] != 2) {
+ if (DEBUG)
+ appendToLog("command COMMAND_END is found without first byte as 0x01 or 0x02, " + byteArrayToString(dataInPayload));
+ break;
+ } else {
+ dataA.responseType = RfidReaderChipData.HostCmdResponseTypes.TYPE_COMMAND_END;
+ setInventoring(false);
+ if (DEBUG)
+ appendToLog("command COMMAND_END is found with packageLength=" + packageLengthRead + ", length = " + dataA.dataValues.length + ", dataValues=" + byteArrayToString(dataA.dataValues));
+ if (dataA.dataValues.length >= 8) {
+ int status = dataA.dataValues[12 - 8] + dataA.dataValues[13 - 8] * 256;
+ if (status != 0)
+ dataA.decodedError = "Received COMMAND_END with status=" + String.format("0x%X", status) + ", error_port=" + dataA.dataValues[14 - 8];
+ if (dataA.decodedError != null)
+ if (DEBUG)
+ appendToLog(dataA.decodedError);
+ rfidDataReadTypes = RfidDataReadTypes.RFID_DATA_READ_COMMAND_END;
+ }
+ }
+ int oldSize = mRx000ToRead.size();
+ mRx000ToRead.add(dataA);
+ if (DEBUG)
+ appendToLog("oldSize = " + oldSize + ", after adding 8001 mRx000ToRead.size = " + mRx000ToRead.size());
+ commandOperating = false;
+ break;
+ case 0x0005:
+ case 0x8005: //RFID_PACKET_TYPE_18K6C_INVENTORY //original 5
+ if (dataIn[startIndex + 0] != 3 && dataIn[startIndex + 0] != 4) {
+ if (DEBUG)
+ appendToLog("command 18K6C_INVENTORY is found without first byte as 0x03, 0x04, " + byteArrayToString(dataInPayload));
+ break;
+ } else {
+ if (dataIn[startIndex + 0] == 3) {
+ dataA.responseType = RfidReaderChipData.HostCmdResponseTypes.TYPE_18K6C_INVENTORY;
+ if (true) {
+ boolean crcError;
+ if (dataA.dataValues.length < 12 + 4)
+ dataA.decodedError = "Received TYPE_18K6C_INVENTORY with length = " + String.valueOf(dataA.dataValues.length) + ", data = " + byteArrayToString(dataA.dataValues);
+ else {
+ int epcLength = (dataA.dataValues[12] >> 3) * 2;
+ if (dataA.dataValues.length < 12 + 2 + epcLength + 2)
+ dataA.decodedError = "Received TYPE_18K6C_INVENTORY with length = " + String.valueOf(dataA.dataValues.length) + ", data = " + byteArrayToString(dataA.dataValues);
+ else {
+ setInventoring(true);
+ long time1 = dataA.dataValues[3] & 0x00FF;
+ time1 = time1 << 8;
+ time1 |= dataA.dataValues[2] & 0x00FF;
+ time1 = time1 = time1 << 8;
+ time1 |= dataA.dataValues[1] & 0x00FF;
+ time1 = time1 = time1 << 8;
+ time1 |= dataA.dataValues[0] & 0x00FF;
+ dataA.decodedTime = time1;
+ dataA.decodedRssi = decodeNarrowBandRSSI(dataA.dataValues[13 - 8]);
+
+ byte bValue = dataA.dataValues[14 - 8];
+ bValue &= 0x7F;
+ if ((bValue & 0x40) != 0)
+ bValue |= 0x80;
+ dataA.decodedPhase = bValue;
+ if (true) {
+ int iValue = dataA.dataValues[14 - 8] & 0x3F; //0x7F;
+ boolean b7 = false;
+ if ((dataA.dataValues[14 - 8] & 0x80) != 0)
+ b7 = true;
+ iValue *= 90;
+ iValue /= 32;
+ dataA.decodedPhase = iValue;
+ }
+
+ dataA.decodedChidx = dataA.dataValues[15 - 8];
+ dataA.decodedPort = dataA.dataValues[18 - 8];
+ int data1_count = (dataA.dataValues[16 - 8] & 0xFF);
+ data1_count *= 2;
+ int data2_count = (dataA.dataValues[17 - 8] & 0xFF);
+ data2_count *= 2;
+
+ if (dataA.dataValues.length >= 12 + 2) {
+ dataA.decodedPc = new byte[2];
+ System.arraycopy(dataA.dataValues, 12, dataA.decodedPc, 0, dataA.decodedPc.length);
+ }
+ if (dataA.dataValues.length >= 12 + 2 + 2) {
+ dataA.decodedEpc = new byte[dataA.dataValues.length - 12 - 4];
+ System.arraycopy(dataA.dataValues, 12 + 2, dataA.decodedEpc, 0, dataA.decodedEpc.length);
+ dataA.decodedCrc = new byte[2];
+ System.arraycopy(dataA.dataValues, dataA.dataValues.length - 2, dataA.decodedCrc, 0, dataA.decodedCrc.length);
+ }
+ if (data1_count != 0 && dataA.dataValues.length - 2 - data1_count - data2_count >= 0) {
+ dataA.decodedData1 = new byte[data1_count];
+ System.arraycopy(dataA.dataValues, dataA.dataValues.length - 2 - data1_count - data2_count, dataA.decodedData1, 0, dataA.decodedData1.length);
+ }
+ if (data2_count != 0 && dataA.dataValues.length - 2 - data2_count >= 0) {
+ dataA.decodedData2 = new byte[data2_count];
+ System.arraycopy(dataA.dataValues, dataA.dataValues.length - 2 - data2_count, dataA.decodedData2, 0, dataA.decodedData2.length);
+ }
+ int iData12 = 0;
+ if (dataA.decodedData1 != null) iData12 += dataA.decodedData1.length;
+ if (dataA.decodedData2 != null) iData12 += dataA.decodedData2.length;
+ if (iData12 != 0) {
+ byte[] newEpc = new byte[dataA.decodedEpc.length - iData12];
+ System.arraycopy(dataA.decodedEpc, 0, newEpc, 0, newEpc.length);
+ dataA.decodedEpc = newEpc;
+ }
+ rfidDataReadTypes = RfidDataReadTypes.RFID_DATA_READ_COMMAND_INVENTORY;
+ }
+ }
+ }
+ int oldSize2 = mRx000ToRead.size();
+ mRx000ToRead.add(dataA);
+ if (utility.DEBUG_APDATA) {
+ appendToLog("ApData: dataValues = " + byteArrayToString(dataA.dataValues) + ", 1 decodedRssi = " + dataA.decodedRssi + ", decodedPhase = " + dataA.decodedPhase + ", decodedChidx = " + dataA.decodedChidx + ", decodedPort = " + dataA.decodedPort);
+ appendToLog("ApData: decodedPc/Epc/Crc = " + byteArrayToString(dataA.decodedPc) + ", " + byteArrayToString(dataA.decodedEpc) + ", " + byteArrayToString(dataA.decodedCrc)
+ + ", decodedData1/2 = " + byteArrayToString(dataA.decodedData1) + ", " + byteArrayToString(dataA.decodedData2));
+ }
+ if (DEBUG)
+ appendToLog("oldSize = " + oldSize2 + ", after adding 8005 mRx000ToRead.size = " + mRx000ToRead.size());
+ } else {
+ dataA.responseType = RfidReaderChipData.HostCmdResponseTypes.TYPE_18K6C_INVENTORY_COMPACT;
+ if (true) {
+ if (dataA.dataValues.length < 3)
+ dataA.decodedError = "Received TYPE_18K6C_INVENTORY with length = " + String.valueOf(dataA.dataValues.length) + ", data = " + byteArrayToString(dataA.dataValues);
+ else {
+ int index = 0;
+ byte[] dataValuesFull = dataA.dataValues;
+ while (index < dataValuesFull.length) {
+ dataA.decodedTime = System.currentTimeMillis();
+ if (dataValuesFull.length >= index + 2) {
+ dataA.decodedPc = new byte[2];
+ System.arraycopy(dataValuesFull, index, dataA.decodedPc, 0, dataA.decodedPc.length);
+ index += 2;
+ } else {
+ break;
+ }
+ int epcLength = ((dataA.decodedPc[0] & 0xFF) >> 3) * 2;
+ if (dataValuesFull.length >= index + epcLength) {
+ dataA.decodedEpc = new byte[epcLength];
+ System.arraycopy(dataValuesFull, index, dataA.decodedEpc, 0, epcLength);
+ index += epcLength;
+ }
+ if (dataValuesFull.length >= index + 1) {
+ dataA.decodedRssi = decodeNarrowBandRSSI(dataValuesFull[index]);
+ index++;
+ }
+ if (DEBUG)
+ appendToLog((dataA.dataValues != null ? "mRfidToRead.size() = " + csReaderConnector.rfidConnector.mRfidToRead.size() + ", dataValues = " + byteArrayToString(dataA.dataValues) + ", " : "") + "2 decodedRssi = " + dataA.decodedRssi + ", decodedPc = " + byteArrayToString(dataA.decodedPc) + ", decodedEpc = " + byteArrayToString(dataA.decodedEpc));
+ if (dataValuesFull.length > index) {
+ mRx000ToRead.add(dataA);
+ if (utility.DEBUG_APDATA) appendToLog("ApData: Got data to mRx000ToRead " + mRx000ToRead.size() + ", with decodedEpc = " + byteArrayToString(dataA.decodedEpc));
+
+ int iDecodedPortOld = dataA.decodedPort;
+ dataA = new RfidReaderChipData.Rx000pkgData();
+ dataA.decodedPort = iDecodedPortOld;
+ dataA.responseType = RfidReaderChipData.HostCmdResponseTypes.TYPE_18K6C_INVENTORY_COMPACT;
+ rfidDataReadTypes = RfidDataReadTypes.RFID_DATA_READ_COMMAND_COMPACT;
+ }
+ }
+ }
+ }
+ int oldSize3 = mRx000ToRead.size();
+ mRx000ToRead.add(dataA);
+ if (utility.DEBUG_APDATA) appendToLog("ApData: Got data to mRx000ToRead " + mRx000ToRead.size() + ", with decodedEpc = " + byteArrayToString(dataA.decodedEpc));
+ if (DEBUG)
+ appendToLog("oldSize = " + oldSize3 + ", after adding 8005 mRx000ToRead.size = " + mRx000ToRead.size());
+ }
+ if (DEBUG)
+ appendToLog("command 18K6C_INVENTORY is found with data=" + byteArrayToString(dataA.dataValues));
+ }
+ break;
+ case 6: //RFID_PACKET_TYPE_18K6C_TAG_ACCESS
+ if (dataIn[startIndex + 0] != 1) {
+ if (DEBUG)
+ appendToLog("command 18K6C_TAG_ACCESS is found without first byte as 0x02, " + byteArrayToString(dataInPayload));
+ break;
+ } else {
+ dataA.responseType = RfidReaderChipData.HostCmdResponseTypes.TYPE_18K6C_TAG_ACCESS;
+ if (true) {
+ byte[] dataInPayload_full = new byte[expectedLength];
+ System.arraycopy(dataIn, startIndex, dataInPayload_full, 0, dataInPayload_full.length);
+ if (DEBUG)
+ appendToLog("command TYPE_18K6C_TAG_ACCESS is found with packageLength=" + packageLengthRead + ", " + byteArrayToString(dataInPayload_full));
+ }
+ if (true) {
+ int accessError, backscatterError;
+ boolean timeoutError, crcError;
+ if (dataA.dataValues.length >= 8 + 12) {
+ backscatterError = 0;
+ accessError = 0;
+ timeoutError = false;
+ crcError = false;
+ if ((dataA.dataValues[1] & 8) != 0)
+ crcError = true;
+ else if ((dataA.dataValues[1] & 4) != 0)
+ timeoutError = true;
+ else if ((dataA.dataValues[1] & 2) != 0)
+ backscatterError = (dataA.dataValues[13] & 0xFF);
+ else if ((dataA.dataValues[1] & 1) != 0 && dataA.dataValues.length >= 8 + 12 + 4)
+ accessError = (dataA.dataValues[20] & 0xFF) + (dataA.dataValues[21] & 0xFF) * 256;
+
+ byte[] dataRead = new byte[dataA.dataValues.length - 20];
+ System.arraycopy(dataA.dataValues, 20, dataRead, 0, dataRead.length);
+ if (backscatterError == 0 && accessError == 0 && timeoutError == false && crcError == false) {
+ if ((dataA.dataValues[12] == (byte) 0xC3) || (dataA.dataValues[12] == (byte) 0xC4) || (dataA.dataValues[12] == (byte) 0xC5)
+ || (dataA.dataValues[12] == (byte) 0xD5) || (dataA.dataValues[12] == (byte) 0xE2))
+ dataA.decodedResult = "";
+ else if ((dataA.dataValues[12] == (byte) 0xC2) || (dataA.dataValues[12] == (byte) 0xE0))
+ dataA.decodedResult = byteArrayToString(dataRead);
+ else
+ dataA.decodedError = "Received TYPE_18K6C_TAG_ACCESS with unhandled command = " + String.valueOf(dataA.dataValues[12]) + ", data = " + byteArrayToString(dataA.dataValues);
+ } else {
+ dataA.decodedError = "Received TYPE_18K6C_TAG_ACCESS with Error ";
+ if (crcError)
+ dataA.decodedError += "crcError=" + crcError + ", ";
+ if (timeoutError)
+ dataA.decodedError += "timeoutError=" + timeoutError + ", ";
+ if (backscatterError != 0) {
+ dataA.decodedError += "backscatterError:";
+ String strErrorMessage = String.valueOf(backscatterError);
+ switch (backscatterError) {
+ case 3:
+ strErrorMessage = "Specified memory location does not exist or the PC value is not supported by the tag";
+ break;
+ case 4:
+ strErrorMessage = "Specified memory location is locked and/or permalocked and is not writeable";
+ break;
+ case 0x0B:
+ strErrorMessage = "Tag has insufficient power to perform the memory write";
+ break;
+ case 0x0F:
+ strErrorMessage = "Tag does not support error-specific codes";
+ default:
+ break;
+ }
+ dataA.decodedError += strErrorMessage + ", ";
+ }
+ if (accessError != 0) {
+ dataA.decodedError += "accessError: ";
+ String strErrorMessage = String.valueOf(accessError);
+ switch (accessError) {
+ case 0x01:
+ strErrorMessage = "Read after write verify failed";
+ break;
+ case 0x02:
+ strErrorMessage = "Problem transmitting tag command";
+ break;
+ case 0x03:
+ strErrorMessage = "CRC error on tag response to a write";
+ break;
+ case 0x04:
+ strErrorMessage = "CRC error on the read packet when verifying the write";
+ break;
+ case 0x05:
+ strErrorMessage = "Maximum retries on the write exceeded";
+ break;
+ case 0x06:
+ strErrorMessage = "Failed waiting for read data from tag, possible timeout";
+ break;
+ case 0x07:
+ strErrorMessage = "Failure requesting a new tag handle";
+ break;
+ case 0x09:
+ strErrorMessage = "Out of retries";
+ break;
+ case 0x0A:
+ strErrorMessage = "Error waiting for tag response, possible timeout";
+ break;
+ case 0x0B:
+ strErrorMessage = "CRC error on tag response to a kill";
+ break;
+ case 0x0C:
+ strErrorMessage = "Problem transmitting 2nd half of tag kill";
+ break;
+ case 0x0D:
+ strErrorMessage = "Tag responded with an invalid handle on first kill command";
+ break;
+ default:
+ break;
+ }
+ dataA.decodedError += strErrorMessage + ", ";
+ }
+ dataA.decodedError += "data = " + byteArrayToString(dataA.dataValues);
+ rfidDataReadTypes = RfidDataReadTypes.RFID_DATA_READ_COMMAND_ACCESS;
+ }
+ } else {
+ dataA.decodedError = "Received TYPE_18K6C_TAG_ACCESS with length = " + String.valueOf(dataA.dataValues.length) + ", data = " + byteArrayToString(dataA.dataValues);
+ }
+ }
+ }
+ int oldSize4 = mRx000ToRead.size();
+ mRx000ToRead.add(dataA);
+ if (DEBUG)
+ appendToLog("oldSize = " + oldSize4 + ", after adding 0006 mRx000ToRead.size = " + mRx000ToRead.size());
+ if (DEBUG) {
+ appendToLog("mRx000UplinkHandler(): package read = " + byteArrayToString(dataA.dataValues));
+ }
+ break;
+ case 0x0007:
+ case 0x8007: //RFID_PACKET_TYPE_ANTENNA_CYCLE_END //original 7
+ if (dataIn[startIndex + 0] != 1 && dataIn[startIndex + 0] != 2) {
+ if (DEBUG)
+ appendToLog("command TYPE_ANTENNA_CYCLE_END is found without first byte as 0x01 or 0x02, " + byteArrayToString(dataInPayload));
+ break;
+ } else {
+ dataA.responseType = RfidReaderChipData.HostCmdResponseTypes.TYPE_ANTENNA_CYCLE_END;
+ if (DEBUG)
+ appendToLog("command TYPE_ANTENNA_CYCLE_END is found with packageLength=" + packageLengthRead + ", " + byteArrayToString(dataInPayload));
+ rfidDataReadTypes = RfidDataReadTypes.RFID_DATA_READ_COMMAND_END;
+ }
+ mRx000ToRead.add(dataA);
+ break;
+ case 0x000E:
+ if (dataIn[startIndex + 0] != 1 && dataIn[startIndex + 0] != 2) {
+ if (DEBUG)
+ appendToLog("command TYPE_COMMAND_ACTIVE is found without first byte as 0x01 or 0x02, " + byteArrayToString(dataInPayload));
+ break;
+ } else {
+ dataA.responseType = RfidReaderChipData.HostCmdResponseTypes.TYPE_COMMAND_ACTIVE;
+ if (DEBUG)
+ appendToLog("command TYPE_COMMAND_ACTIVE is found with packageLength=" + packageLengthRead + ", " + byteArrayToString(dataInPayload));
+ rfidDataReadTypes = RfidDataReadTypes.RFID_DATA_READ_COMMAND_ACTIVE;
+ }
+ mRx000ToRead.add(dataA);
+ break;
+ case 0x3005: //RFID_PACKET_TYPE_MBP_READ
+ int address = (dataIn[startIndex + 8] & 0xFF) + (dataIn[startIndex + 9] & 0xFF) * 256;
+ switch (address) {
+ case 0x450:
+ rx000MbpSetting.rxGain = (dataIn[startIndex + 10] & 0xFF) + (dataIn[startIndex + 11] & 0xFF) * 256;
+ break;
+ default:
+ break;
+ }
+ rfidDataReadTypes = RfidDataReadTypes.RFID_DATA_READ_COMMAND_MBPREAD;
+ case 0x3007: //RFID_PACKET_TYPE_OEMCFG_READ
+ address = (dataIn[startIndex + 8] & 0xFF) + (dataIn[startIndex + 9] & 0xFF) * 256 + (dataIn[startIndex + 10] & 0xFF) * 256 * 256 + (dataIn[startIndex + 11] & 0xFF) * 256 * 256 * 256;
+ switch (address) {
+ case 0x02:
+// dataIn[startIndex + 12] = 3;
+ rx000OemSetting.countryCode = (dataIn[startIndex + 12] & 0xFF) + (dataIn[startIndex + 13] & 0xFF) * 256 + (dataIn[startIndex + 14] & 0xFF) * 256 * 256 + (dataIn[startIndex + 15] & 0xFF) * 256 * 256 * 256;
+ if (DEBUG)
+ appendToLog("countryCode = " + rx000OemSetting.countryCode);
+ break;
+ case 0x04:
+ case 0x05:
+ case 0x06:
+ case 0x07:
+ System.arraycopy(dataIn, startIndex + 12, rx000OemSetting.serialNumber, 4 * (address - 4), 4);
+ break;
+ case 0x08:
+ case 0x09:
+ case 0x0A:
+ if (true) {
+ byte[] bytes = new byte[4];
+ System.arraycopy(dataIn, startIndex + 12, bytes, 0, 4);
+ appendToLog("product serial number, " + address + ": " + byteArrayToString(bytes));
+ }
+ System.arraycopy(dataIn, startIndex + 12, rx000OemSetting.productserialNumber, 4 * (address - 8), 4);
+ break;
+ case 0x0B: //VERSIONCODE_MAX
+ System.arraycopy(dataIn, startIndex + 12, rx000OemSetting.productserialNumber, 4 * (address - 8), 4);
+ if (dataIn[startIndex + 12] == 0 && dataIn[startIndex + 13] == 0 && dataIn[startIndex + 14] == 0 && dataIn[startIndex + 15] == 0) {
+ rx000OemSetting.versionCode = 0;
+ } else if (dataIn[startIndex + 12] == 0x20 && dataIn[startIndex + 13] == 0x17 && dataIn[startIndex + 14] == 0) {
+ rx000OemSetting.versionCode = (dataIn[startIndex + 14] & 0xFF) + (dataIn[startIndex + 15] & 0xFF) * 256;
+ }
+ if (DEBUG)
+ appendToLog("versionCode = " + rx000OemSetting.versionCode);
+ break;
+ case 0x8E:
+ /*dataIn[startIndex + 12] = 0x2A; //0x4F;
+ dataIn[startIndex + 13] = 0x2A; //0x46;
+ dataIn[startIndex + 14] = 0x4E; //0x41; //0x43;
+ dataIn[startIndex + 15] = 0x5A; //0x53; //0x41; */
+ if (dataIn[startIndex + 12] == 0 || dataIn[startIndex + 13] == 0 || dataIn[startIndex + 14] == 0 || dataIn[startIndex + 15] == 0) {
+ rx000OemSetting.spcialCountryVersion = "";
+ } else {
+ rx000OemSetting.spcialCountryVersion = String.valueOf((char) dataIn[startIndex + 15])
+ + String.valueOf((char) dataIn[startIndex + 14])
+ + String.valueOf((char) dataIn[startIndex + 13])
+ + String.valueOf((char) dataIn[startIndex + 12]);
+ }
+ byte[] dataInPart = new byte[4];
+ System.arraycopy(dataIn, startIndex + 12, dataInPart, 0, dataInPart.length);
+ if (DEBUG)
+ appendToLog("spcialCountryVersion = " + rx000OemSetting.spcialCountryVersion + ", data = " + byteArrayToString(dataInPart));
+ break;
+ case 0x8F:
+ //dataIn[startIndex + 12] = (byte)0xAA;
+ rx000OemSetting.freqModifyCode = (dataIn[startIndex + 12] & 0xFF) + (dataIn[startIndex + 13] & 0xFF) * 256 + (dataIn[startIndex + 14] & 0xFF) * 256 * 256 + (dataIn[startIndex + 15] & 0xFF) * 256 * 256 * 256;
+ if (DEBUG)
+ appendToLog("freqModifyCode = " + rx000OemSetting.freqModifyCode);
+ break;
+ default:
+ break;
+ }
+/* if (address >= 4 && address <= 7) {
+ for (int i = 0; i < 4; i++) {
+ mRx000OemSetting.serialNumber[(address - 4) * 4 + i] = dataIn[startIndex + 12 + i];
+ }
+ }*/
+ if (DEBUG)
+ appendToLog("command OEMCFG_READ is found with address = " + address + ", packageLength=" + packageLengthRead + ", " + byteArrayToString(dataInPayload));
+ rfidDataReadTypes = RfidDataReadTypes.RFID_DATA_READ_COMMAND_OEMREAD;
+ break;
+ case 0x3008: //RFID_PACKET_TYPE_ENG_RSSI
+ if (DEBUG)
+ appendToLog("Hello123: RFID_PACKET_TYPE_ENG_RSSI S is found: " + byteArrayToString(dataInPayload));
+ if ((dataIn[startIndex + 8] & 0x02) != 0) {
+ rx000EngSetting.narrowRSSI = (dataIn[startIndex + 28] & 0xFF) + (dataIn[startIndex + 29] & 0xFF) * 256;
+ rx000EngSetting.wideRSSI = (dataIn[startIndex + 30] & 0xFF) + (dataIn[startIndex + 31] & 0xFF) * 256;
+ if (DEBUG)
+ appendToLog("Hello123: narrorRSSI = " + String.format("%04X", rx000EngSetting.narrowRSSI) + ", wideRSSI = " + String.format("%04X", rx000EngSetting.wideRSSI));
+ rfidDataReadTypes = RfidDataReadTypes.RFID_DATA_READ_COMMAND_RSSI;
+ }
+ break;
+ default:
+ if (DEBUG)
+ appendToLog("command OTHERS is found: " + byteArrayToString(dataInPayload) + ", with packagelength=" + packageLengthRead + ", packageTypeRead=" + packageTypeRead);
+ break;
+ }
+ packageFound = true;
+ packageType = 3; //0x01 to 0x04
+ startIndexNew = startIndex + expectedLength;
+ }
+ }
+ }
+ }
+
+ if (packageFound) {
+ packageFound = false;
+ if (false && utility.DEBUG_APDATA)
+ appendToLog("ApData: found packageType " + packageType + " with mRfidToReadingOffset=" + mRfidToReadingOffset + ", startIndexOld= " + startIndexOld + ", startIndex= " + startIndex + ", startIndexNew=" + startIndexNew);
+ if (startIndex != startIndexOld) {
+ byte[] unhandledBytes = new byte[startIndex - startIndexOld];
+ System.arraycopy(mRfidToReading, startIndexOld, unhandledBytes, 0, unhandledBytes.length);
+ if (utility.DEBUG_APDATA)
+ appendToLog("ApData: packageFound with invalid unused data: " + unhandledBytes.length + ", " + byteArrayToString(unhandledBytes));
+ invalidUpdata++;
+ writeDebug2File("Up4 invalid " + unhandledBytes.length + ", " + byteArrayToString(unhandledBytes));
+ } else if (startIndexNew != startIndex) {
+ data1 = new byte[startIndexNew - startIndex];
+ System.arraycopy(mRfidToReading, startIndex, data1, 0, data1.length);
+ String string = "Up4 " + (rfidDataReadTypes != null ? (rfidDataReadTypes.toString() + ", ") : "Unprocessed, ");
+ if (data1.length <= 8 && data1[0] == 0x40)
+ string += (byteArrayToString(data1).substring(0, 4) + " " + byteArrayToString(data1).substring(4, 16));
+ else {
+ string += (byteArrayToString(data1).substring(0, 8) + " " + byteArrayToString(data1).substring(8, 16) + " " + (byteArrayToString(data1).substring(16)));
+ }
+ utility.writeDebug2File(string);
+ if (utility.DEBUG_APDATA) appendToLog("ApData: Found startIndexNew=" + startIndexNew + ", string=" + string);
+ if (false && utility.DEBUG_APDATA) {
+ byte[] usedBytes = new byte[startIndexNew - startIndex];
+ System.arraycopy(mRfidToReading, startIndex, usedBytes, 0, usedBytes.length);
+ appendToLog("ApData: used data = " + usedBytes.length + ", " + byteArrayToString(usedBytes));
+ }
+
+ }
+ byte[] mRfidToReadingNew = new byte[RFID_READING_BUFFERSIZE];
+ System.arraycopy(mRfidToReading, startIndexNew, mRfidToReadingNew, 0, mRfidToReadingOffset - startIndexNew);
+ mRfidToReading = mRfidToReadingNew;
+ mRfidToReadingOffset -= startIndexNew;
+ startIndex = 0;
+ startIndexNew = 0;
+ startIndexOld = 0;
+ if (mRfidToReadingOffset != 0) {
+ byte[] remainedBytes = new byte[mRfidToReadingOffset];
+ System.arraycopy(mRfidToReading, 0, remainedBytes, 0, remainedBytes.length);
+ if (utility.DEBUG_APDATA)
+ appendToLog("ApData: moved with remained bytes=" + byteArrayToString(remainedBytes));
+ }
+ } else {
+ startIndex++;
+ }
+ }
+ if (utility.DEBUG_APDATA && bLooping2) appendToLog("ApData: Exiting second loop with mRfidToReadingOffset = " + mRfidToReadingOffset + ", startIndex = " + startIndex);
+ if (startIndex != 0 && mRfidToReadingOffset != 0) {
+ if (utility.DEBUG_APDATA)
+ appendToLog("ApData: exit while(-8) loop with startIndex = " + startIndex + (startIndex == 0 ? "" : "(NON-ZERO)") + ", mRfidToReadingOffset=" + mRfidToReadingOffset);
+ }
+ }
+ }
+ if (utility.DEBUG_APDATA && bLooping) appendToLog("ApData: Exiting loop with mRfidToRead.size as " + csReaderConnector.rfidConnector.mRfidToRead.size());
+ if (mRfidToReadingOffset == startIndexNew && mRfidToReadingOffset != 0) {
+ byte[] unusedData = new byte[mRfidToReadingOffset];
+ System.arraycopy(mRfidToReading, 0, unusedData, 0, unusedData.length);
+ if (DEBUG)
+ appendToLog("Up4 Invalid " + mRfidToReadingOffset + ", " + byteArrayToString(unusedData));
+ mRfidToReading = new byte[RFID_READING_BUFFERSIZE];
+ mRfidToReadingOffset = 0;
+ utility.writeDebug2File("Up4 Invalid " + byteArrayToString(unusedData));
+ }
+ if (DEBUGTHREAD) appendToLog("mRx000UplinkHandler(): END");
+ bRx000ToReading = false;
+ }
+
+ public boolean turnOn(boolean onStatus) {
+ RfidConnector.CsReaderRfidData csReaderRfidData = new RfidConnector.CsReaderRfidData();
+ if (onStatus) {
+ csReaderRfidData.rfidPayloadEvent = RfidConnector.RfidPayloadEvents.RFID_POWER_ON;
+ csReaderRfidData.waitUplinkResponse = false;
+ clearTempDataIn_request = true;
+ addRfidToWrite(csReaderRfidData);
+ return true;
+ } else if (onStatus == false) {
+ csReaderRfidData.rfidPayloadEvent = RfidConnector.RfidPayloadEvents.RFID_POWER_OFF;
+ csReaderRfidData.waitUplinkResponse = false;
+ clearTempDataIn_request = true;
+ addRfidToWrite(csReaderRfidData);
+ return true;
+ } else {
+ return false;
+ }
+ }
+
+ public boolean sendControlCommand(ControlCommands controlCommands) {
+ byte[] msgBuffer = new byte[]{(byte) 0x40, 6, 0, 0, 0, 0, 0, 0};
+ boolean needResponse = false;
+ if (csReaderConnector.isConnected() == false) return false;
+ switch (controlCommands) {
+ default:
+ msgBuffer = null;
+ case CANCEL:
+ msgBuffer[1] = 1;
+ commandOperating = false;
+ break;
+ case SOFTRESET:
+ msgBuffer[1] = 2;
+ needResponse = true;
+ break;
+ case ABORT:
+ msgBuffer[1] = 3;
+ needResponse = true;
+ commandOperating = false;
+ break;
+ case PAUSE:
+ msgBuffer[1] = 4;
+ break;
+ case RESUME:
+ msgBuffer[1] = 5;
+ break;
+ case GETSERIALNUMBER:
+ msgBuffer = new byte[]{(byte) 0xC0, 0x06, 0, 0, 0, 0, 0, 0};
+ needResponse = true;
+ break;
+ case RESETTOBOOTLOADER:
+ msgBuffer[1] = 7;
+ needResponse = true;
+ break;
+ }
+
+ if (msgBuffer == null) {
+ if (DEBUG) appendToLog("Invalid control commands");
+ return false;
+ } else {
+ clearTempDataIn_request = true;
+
+ RfidConnector.CsReaderRfidData csReaderRfidData = new RfidConnector.CsReaderRfidData();
+ csReaderRfidData.rfidPayloadEvent = RfidConnector.RfidPayloadEvents.RFID_COMMAND;
+ csReaderRfidData.dataValues = msgBuffer;
+ if (needResponse) {
+// if (DEBUG) appendToLog("sendControlCommand() adds to mRx000ToWrite");
+ csReaderRfidData.waitUplinkResponse = needResponse;
+ addRfidToWrite(csReaderRfidData);
+// mRx000ToWrite.add(cs108RfidData);
+ } else {
+// if (DEBUG) appendToLog("sendControlCommand() adds to mRfidToWrite");
+ csReaderRfidData.waitUplinkResponse = needResponse;
+ addRfidToWrite(csReaderRfidData);
+ }
+ if (controlCommands == ControlCommands.ABORT) aborting = true;
+ return true;
+ }
+ }
+
+ boolean sendHostRegRequestHST_RFTC_FRQCH_DESC_PLLDIVMULT(int freqChannel) {
+ long fccFreqTable[] = new long[]{
+ 0x00180E4F, //915.75 MHz
+ 0x00180E4D, //915.25 MHz
+ 0x00180E1D, //903.25 MHz
+ 0x00180E7B, //926.75 MHz
+ 0x00180E79, //926.25 MHz
+ 0x00180E21, //904.25 MHz
+ 0x00180E7D, //927.25 MHz
+ 0x00180E61, //920.25 MHz
+ 0x00180E5D, //919.25 MHz
+ 0x00180E35, //909.25 MHz
+ 0x00180E5B, //918.75 MHz
+ 0x00180E57, //917.75 MHz
+ 0x00180E25, //905.25 MHz
+ 0x00180E23, //904.75 MHz
+ 0x00180E75, //925.25 MHz
+ 0x00180E67, //921.75 MHz
+ 0x00180E4B, //914.75 MHz
+ 0x00180E2B, //906.75 MHz
+ 0x00180E47, //913.75 MHz
+ 0x00180E69, //922.25 MHz
+ 0x00180E3D, //911.25 MHz
+ 0x00180E3F, //911.75 MHz
+ 0x00180E1F, //903.75 MHz
+ 0x00180E33, //908.75 MHz
+ 0x00180E27, //905.75 MHz
+ 0x00180E41, //912.25 MHz
+ 0x00180E29, //906.25 MHz
+ 0x00180E55, //917.25 MHz
+ 0x00180E49, //914.25 MHz
+ 0x00180E2D, //907.25 MHz
+ 0x00180E59, //918.25 MHz
+ 0x00180E51, //916.25 MHz
+ 0x00180E39, //910.25 MHz
+ 0x00180E3B, //910.75 MHz
+ 0x00180E2F, //907.75 MHz
+ 0x00180E73, //924.75 MHz
+ 0x00180E37, //909.75 MHz
+ 0x00180E5F, //919.75 MHz
+ 0x00180E53, //916.75 MHz
+ 0x00180E45, //913.25 MHz
+ 0x00180E6F, //923.75 MHz
+ 0x00180E31, //908.25 MHz
+ 0x00180E77, //925.75 MHz
+ 0x00180E43, //912.75 MHz
+ 0x00180E71, //924.25 MHz
+ 0x00180E65, //921.25 MHz
+ 0x00180E63, //920.75 MHz
+ 0x00180E6B, //922.75 MHz
+ 0x00180E1B, //902.75 MHz
+ 0x00180E6D, //923.25 MHz
+ };
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 3, 0x0C, 0, 0, 0, 0};
+ if (freqChannel >= 50) {
+ freqChannel = 49;
+ }
+ long freqData = fccFreqTable[freqChannel];
+ msgBuffer[4] = (byte) (freqData % 256);
+ msgBuffer[5] = (byte) ((freqData >> 8) % 256);
+ msgBuffer[6] = (byte) ((freqData >> 16) % 256);
+ msgBuffer[7] = (byte) ((freqData >> 24) % 256);
+ return sendHostRegRequest(HostRegRequests.HST_RFTC_FRQCH_DESC_PLLDIVMULT, true, msgBuffer);
+ }
+
+ boolean bLowPowerStandby = false;
+
+ public boolean setPwrManagementMode(boolean bLowPowerStandby) {
+ if (false) appendToLog("pwrMgmtStatus: setPwrManagementMode(" + bLowPowerStandby + ")");
+ if (true) return false; //ignore this setting
+ if (this.bLowPowerStandby == bLowPowerStandby) return true;
+ boolean result = rx000Setting.writeMAC(0x200, (bLowPowerStandby ? 1 : 0));
+ if (result) {
+ result = sendHostRegRequestHST_CMD(RfidReaderChipData.HostCommands.CMD_SETPWRMGMTCFG);
+ this.bLowPowerStandby = bLowPowerStandby;
+ rx000Setting.getPwrMgmtStatus();
+ }
+ return result;
+ }
+
+ public boolean sendHostRegRequestHST_CMD(RfidReaderChipData.HostCommands hostCommand) {
+ long hostCommandData = -1;
+ switch (hostCommand) {
+ case CMD_WROEM:
+ hostCommandData = 0x02;
+ break;
+ case CMD_RDOEM:
+ hostCommandData = 0x03;
+ break;
+ case CMD_ENGTEST:
+ hostCommandData = 0x04;
+ break;
+ case CMD_MBPRDREG:
+ hostCommandData = 0x05;
+ break;
+ case CMD_MBPWRREG:
+ hostCommandData = 0x06;
+ break;
+ case CMD_18K6CINV:
+ hostCommandData = 0x0F;
+ break;
+ case CMD_18K6CREAD:
+ hostCommandData = 0x10;
+ break;
+ case CMD_18K6CWRITE:
+ hostCommandData = 0x11;
+ break;
+ case CMD_18K6CLOCK:
+ hostCommandData = 0x12;
+ break;
+ case CMD_18K6CKILL:
+ hostCommandData = 0x13;
+ break;
+ case CMD_SETPWRMGMTCFG:
+ hostCommandData = 0x14;
+ break;
+ case CMD_UPDATELINKPROFILE:
+ hostCommandData = 0x19;
+ break;
+ case CMD_18K6CBLOCKWRITE:
+ hostCommandData = 0x1F;
+ break;
+ case CMD_CHANGEEAS:
+ hostCommandData = 0x26;
+ break;
+ case CMD_GETSENSORDATA:
+ hostCommandData = 0x3b;
+ break;
+ case CMD_18K6CAUTHENTICATE:
+ hostCommandData = 0x50;
+ break;
+ case CMD_READBUFFER:
+ hostCommandData = 0x51;
+ break;
+ case CMD_UNTRACEABLE:
+ hostCommandData = 0x52;
+ break;
+ case CMD_FDM_RDMEM:
+ hostCommandData = 0x53;
+ break;
+ case CMD_FDM_WRMEM:
+ hostCommandData = 0x54;
+ break;
+ case CMD_FDM_AUTH:
+ hostCommandData = 0x55;
+ break;
+ case CMD_FDM_GET_TEMPERATURE:
+ hostCommandData = 0x56;
+ break;
+ case CMD_FDM_START_LOGGING:
+ hostCommandData = 0x57;
+ break;
+ case CMD_FDM_STOP_LOGGING:
+ hostCommandData = 0x58;
+ break;
+ case CMD_FDM_WRREG:
+ hostCommandData = 0x59;
+ break;
+ case CMD_FDM_RDREG:
+ hostCommandData = 0x5A;
+ break;
+ case CMD_FDM_DEEP_SLEEP:
+ hostCommandData = 0x5B;
+ break;
+ case CMD_FDM_OPMODE_CHECK:
+ hostCommandData = 0x5C;
+ break;
+ case CMD_FDM_INIT_REGFILE:
+ hostCommandData = 0x5d;
+ break;
+ case CMD_FDM_LED_CTRL:
+ hostCommandData = 0x5e;
+ break;
+ }
+ if (hostCommandData == -1) {
+ return false;
+ } else {
+ commandOperating = true;
+ byte[] msgBuffer = new byte[]{(byte) 0x70, 1, 0, (byte) 0xf0, 0, 0, 0, 0};
+ msgBuffer[4] = (byte) (hostCommandData % 256);
+ msgBuffer[5] = (byte) ((hostCommandData >> 8) % 256);
+ msgBuffer[6] = (byte) ((hostCommandData >> 16) % 256);
+ msgBuffer[7] = (byte) ((hostCommandData >> 24) % 256);
+ return sendHostRegRequest(HostRegRequests.HST_CMD, true, msgBuffer);
+ }
+ }
+
+ ArrayList macAccessHistory = new ArrayList<>();
+
+ boolean bifMacAccessHistoryData(byte[] msgBuffer) {
+ if (sameCheck == false) return false;
+ if (msgBuffer.length != 8) return false;
+ if (msgBuffer[0] != (byte) 0x70 || msgBuffer[1] != 1) return false;
+ if (msgBuffer[2] == 0 && msgBuffer[3] == (byte) 0xF0) return false;
+ return true;
+ }
+
+ int findMacAccessHistory(byte[] msgBuffer) {
+ int i = -1;
+ for (i = 0; i < macAccessHistory.size(); i++) {
+// appendToLog("macAccessHistory(" + i + ")=" + byteArrayToString(macAccessHistory.get(i)));
+ if (Arrays.equals(macAccessHistory.get(i), msgBuffer)) break;
+ }
+ if (i == macAccessHistory.size()) i = -1;
+ if (i >= 0)
+ appendToLog("macAccessHistory: returnValue = " + i + ", msgBuffer=" + byteArrayToString(msgBuffer));
+ return i;
+ }
+
+ void addMacAccessHistory(byte[] msgBuffer) {
+ boolean DEBUG = false;
+ byte[] msgBuffer4 = Arrays.copyOf(msgBuffer, 4);
+ for (int i = 0; i < macAccessHistory.size(); i++) {
+ byte[] macAccessHistory4 = Arrays.copyOf(macAccessHistory.get(i), 4);
+ if (Arrays.equals(msgBuffer4, macAccessHistory4)) {
+ if (DEBUG)
+ appendToLog("macAccessHistory: deleted old record=" + byteArrayToString(macAccessHistory4));
+ macAccessHistory.remove(i);
+ break;
+ }
+ }
+ if (DEBUG)
+ appendToLog("macAccessHistory: added msgbuffer=" + byteArrayToString(msgBuffer));
+ macAccessHistory.add(msgBuffer);
+ }
+
+ boolean sendHostRegRequest(HostRegRequests hostRegRequests, boolean writeOperation, byte[] msgBuffer) {
+ boolean needResponse = false;
+ boolean validRequest = false;
+
+ if (csReaderConnector.isConnected() == false) return false;
+ addMacAccessHistory(msgBuffer);
+ switch (hostRegRequests) {
+ case MAC_OPERATION:
+ case HST_ANT_CYCLES:
+ case HST_ANT_DESC_SEL:
+ case HST_ANT_DESC_CFG:
+ case MAC_ANT_DESC_STAT:
+ case HST_ANT_DESC_PORTDEF:
+ case HST_ANT_DESC_DWELL:
+ case HST_ANT_DESC_RFPOWER:
+ case HST_ANT_DESC_INV_CNT:
+ validRequest = true;
+ break;
+ case HST_TAGMSK_DESC_SEL:
+ case HST_TAGMSK_DESC_CFG:
+ case HST_TAGMSK_BANK:
+ case HST_TAGMSK_PTR:
+ case HST_TAGMSK_LEN:
+ case HST_TAGMSK_0_3:
+ validRequest = true;
+ break;
+ case HST_QUERY_CFG:
+ case HST_INV_CFG:
+ case HST_INV_SEL:
+ case HST_INV_ALG_PARM_0:
+ case HST_INV_ALG_PARM_1:
+ case HST_INV_ALG_PARM_2:
+ case HST_INV_ALG_PARM_3:
+ case HST_INV_RSSI_FILTERING_CONFIG:
+ case HST_INV_RSSI_FILTERING_THRESHOLD:
+ case HST_INV_RSSI_FILTERING_COUNT:
+ case HST_INV_EPC_MATCH_CFG:
+ case HST_INV_EPCDAT_0_3:
+ validRequest = true;
+ break;
+ case HST_TAGACC_DESC_CFG:
+ case HST_TAGACC_BANK:
+ case HST_TAGACC_PTR:
+ case HST_TAGACC_CNT:
+ case HST_TAGACC_LOCKCFG:
+ case HST_TAGACC_ACCPWD:
+ case HST_TAGACC_KILLPWD:
+ case HST_TAGWRDAT_SEL:
+ case HST_TAGWRDAT_0:
+ validRequest = true;
+ break;
+ case HST_RFTC_CURRENT_PROFILE:
+ case HST_RFTC_FRQCH_SEL:
+ case HST_RFTC_FRQCH_CFG:
+ case HST_RFTC_FRQCH_DESC_PLLDIVMULT:
+ case HST_RFTC_FRQCH_DESC_PLLDACCTL:
+ case HST_RFTC_FRQCH_CMDSTART:
+ validRequest = true;
+ break;
+ case HST_AUTHENTICATE_CFG:
+ case HST_AUTHENTICATE_MSG:
+ case HST_READBUFFER_LEN:
+ case HST_UNTRACEABLE_CFG:
+ validRequest = true;
+ break;
+ case HST_CMD:
+ validRequest = true;
+ needResponse = true;
+ break;
+ }
+
+ boolean DEBUG = false;
+ if (DEBUG)
+ appendToLog("checking msgbuffer = " + (msgBuffer == null ? "NULL" : "Valid") + ", validRequst = " + validRequest);
+ if (msgBuffer == null || validRequest == false) {
+ if (DEBUG) appendToLog("Invalid HST_REQ_REQ or null message");
+ return false;
+ } else {
+ if (DEBUG) appendToLog("True Ending 0");
+ RfidConnector.CsReaderRfidData csReaderRfidData = new RfidConnector.CsReaderRfidData();
+ csReaderRfidData.rfidPayloadEvent = RfidConnector.RfidPayloadEvents.RFID_COMMAND;
+ csReaderRfidData.dataValues = msgBuffer;
+ if (needResponse || writeOperation == false) {
+ csReaderRfidData.waitUplinkResponse = (needResponse || writeOperation == false);
+// mRx000ToWrite.add(cs108RfidData);
+ addRfidToWrite(csReaderRfidData);
+ } else {
+ csReaderRfidData.waitUplinkResponse = (needResponse || writeOperation == false);
+ addRfidToWrite(csReaderRfidData);
+ }
+ if (DEBUG) appendToLog("True Ending");
+ return true;
+ }
+ }
+
+ void addRfidToWrite(RfidConnector.CsReaderRfidData csReaderRfidData) {
+ boolean repeatRequest = false;
+ if (csReaderConnector.rfidConnector.mRfidToWrite.size() != 0) {
+ RfidConnector.CsReaderRfidData csReaderRfidData1 = csReaderConnector.rfidConnector.mRfidToWrite.get(csReaderConnector.rfidConnector.mRfidToWrite.size() - 1);
+ if (csReaderRfidData.rfidPayloadEvent == csReaderRfidData1.rfidPayloadEvent) {
+ if (csReaderRfidData.dataValues == null && csReaderRfidData1.dataValues == null) {
+ repeatRequest = true;
+ } else if (csReaderRfidData.dataValues != null && csReaderRfidData1.dataValues != null) {
+ if (csReaderRfidData.dataValues.length == csReaderRfidData1.dataValues.length) {
+ if (compareArray(csReaderRfidData.dataValues, csReaderRfidData1.dataValues, csReaderRfidData.dataValues.length)) {
+ repeatRequest = true;
+ }
+ }
+ }
+ }
+ }
+ if (repeatRequest == false) {
+ byte[] bytesCmd = new byte[] { 0x70, 1, 0, 0x09 };
+ byte[] bytesCmd1 = new byte[] { 0x70, 1, 1, 0x09 };
+ if (csReaderRfidData.dataValues != null) {
+ byte[] bytesNew = new byte[4];
+ System.arraycopy(csReaderRfidData.dataValues, 0, bytesNew, 0, bytesNew.length);
+ if (Arrays.equals(bytesCmd, bytesNew) || Arrays.equals(bytesCmd1, bytesNew)) {
+ int i = 0;
+ for (; i < csReaderConnector.rfidConnector.mRfidToWrite.size(); i++) {
+ if (csReaderConnector.rfidConnector.mRfidToWrite.get(i).dataValues != null) {
+ byte[] bytesOld = new byte[4];
+ System.arraycopy(csReaderConnector.rfidConnector.mRfidToWrite.get(i).dataValues, 0, bytesOld, 0, bytesOld.length);
+ if (Arrays.equals(bytesNew, bytesOld)) {
+ //appendToLog("BtDataOut: matched data " + byteArrayToString(csReaderRfidData.dataValues));
+ csReaderConnector.rfidConnector.mRfidToWrite.remove(i);
+ break;
+ }
+ }
+ }
+ }
+ }
+ }
+ csReaderConnector.rfidConnector.mRfidToWrite.add(csReaderRfidData);
+ }
+ //}
+
+ boolean inventoring = false;
+ public boolean isInventoring() { return inventoring; }
+ void setInventoring(boolean enable) { inventoring = enable; utility.debugFileEnable(false); if (false) appendToLog("setInventoring R2000 is set as " + inventoring);}
+}
+
+
+
+package com.csl.cslibrary4a;
+
+import android.content.Context;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+
+public class SettingData {
+ final boolean DEBUG_FILE = true;
+
+ public int channel = -1;
+ int antennaPower = -1;
+ Context context; Utility utility; NotificationConnector notificationConnector; RfidReader rfidReader; CsReaderConnector csReaderConnector;
+ //CsReaderConnector csReaderConnector;
+
+ public SettingData(Context context, Utility utility, CsReaderConnector csReaderConnector) {
+ this.context = context;
+ this.utility = utility;
+ this.csReaderConnector = csReaderConnector;
+ appendToLog("SettingData:"
+ + "\nthis.context is " + (this.context == null ? "null" : "valid")
+ + "\nthis.utility is " + (this.utility == null ? "null" : "valid")
+ + "\nthis.csReaderConnector is " + (this.csReaderConnector == null ? "null" : "valid")
+ );
+ loadForegroundSettingFile();
+ }
+ public void setConnectedConnectors(NotificationConnector notificationConnector, RfidReader rfidReader) {
+ this.notificationConnector = notificationConnector;
+ this.rfidReader = rfidReader;
+ appendToLog("SettingData: this.notificationConnector is " + (this.notificationConnector == null ? "null" : "valid")
+ + "\nthis.rfidReader is " + (this.rfidReader == null ? "null" : "valid")
+ );
+ }
+
+ private void appendToLog(String s) {
+ utility.appendToLog(s);
+ }
+
+ public void write2FileStream(FileOutputStream stream, String string) {
+ boolean DEBUG = true;
+ try {
+ stream.write(string.getBytes());
+ if (true) appendToLog("FileA outData = " + string);
+ } catch (Exception ex) {
+ }
+ }
+
+ //Operation -- regulatory region, power order, fixed channel,
+ // -- power level (assume 1), enable (assume enable), power, dwell, intraPacket delay, duplication elimination,
+ // -- tag population, Q value
+ // -- session, target, tag focus, fast id,
+ // -- query algorithm
+ // -- minimum minQ cycles
+ // -- reader mode
+
+ //Administration -- reader model, reader name,
+ // -- battery level format
+ // -- inventory rssi unit, beep trigger enable/count, vibration enble/time, vibrate for, vibrate window
+ // -- saving format, cloud enable, file saving enable, cloud address, cloud connect timeout
+ // -- impinj verificaion address, name, password
+ // -- foreground service enable, foreground reader
+ // -- barcode trigger mode
+ // -- enable debugging
+ //public boolean inventoryBeepDefault = true;
+ //boolean inventoryBeep = inventoryBeepDefault;
+ //public boolean getInventoryBeep() {
+ // return inventoryBeep;
+ //}
+ //public boolean setInventoryBeep(boolean inventoryBeep) {
+ // this.inventoryBeep = inventoryBeep;
+ // return true;
+ //}
+
+ public int batteryDisplaySelectDefault = 1, batteryDisplaySelect = batteryDisplaySelectDefault;
+ public boolean setBatteryDisplaySetting(int batteryDisplaySelect) {
+ if (batteryDisplaySelect < 0 || batteryDisplaySelect > 1) return false;
+ this.batteryDisplaySelect = batteryDisplaySelect;
+ return true;
+ }
+ public int rssiDisplaySelectDefault = 1, rssiDisplaySelect = rssiDisplaySelectDefault;
+ public boolean setRssiDisplaySetting(int rssiDisplaySelect) {
+ if (rssiDisplaySelect < 0 || rssiDisplaySelect > 1) return false;
+ this.rssiDisplaySelect = rssiDisplaySelect;
+ return true;
+ }
+
+ public boolean triggerReportingDefault = true, triggerReporting = triggerReportingDefault;
+ public short triggerReportingCountSettingDefault = 1, triggerReportingCountSetting = triggerReportingCountSettingDefault;
+ public boolean inventoryBeepDefault = true, inventoryBeep = inventoryBeepDefault;
+ public int beepCountSettingDefault = 8, beepCountSetting = beepCountSettingDefault;
+ public boolean inventoryVibrateDefault = false, inventoryVibrate = inventoryVibrateDefault;
+ public int vibrateTimeSettingDefault = 300, vibrateTimeSetting = vibrateTimeSettingDefault;
+ public int vibrateModeSelectDefault = 1, vibrateModeSelect = vibrateModeSelectDefault;
+ public int vibrateWindowSettingDefault = 2, vibrateWindowSetting = vibrateWindowSettingDefault;
+
+ public int savingFormatSelectDefault = 0, savingFormatSelect = savingFormatSelectDefault;
+ public int csvColumnSelectDefault = 0, csvColumnSelect = csvColumnSelectDefault;
+ public boolean saveFileEnableDefault = true, saveFileEnable = saveFileEnableDefault;
+ public boolean saveCloudEnableDefault = false, saveCloudEnable = saveCloudEnableDefault;
+ public boolean saveNewCloudEnableDefault = false, saveNewCloudEnable = saveNewCloudEnableDefault;
+ public boolean saveAllCloudEnableDefault = false, saveAllCloudEnable = saveAllCloudEnableDefault;
+ public String serverLocationDefault = "", serverLocation = serverLocationDefault;
+ public int serverTimeoutDefault = 6, serverTimeout = serverTimeoutDefault;
+ //String serverImpinjLocationDefault = "https://h9tqczg9-7275.asse.devtunnels.ms", serverImpinjLocation = serverImpinjLocationDefault;
+
+ public String serverMqttLocationDefault = "", serverMqttLocation = serverMqttLocationDefault;
+ public String topicMqttDefault = "", topicMqtt = topicMqttDefault;
+ public int inventoryCloudSaveDefault = 0, inventoryCloudSave = inventoryCloudSaveDefault;
+ public String serverImpinjLocationDefault = "https://democloud.convergence.com.hk/ias", serverImpinjLocation = serverImpinjLocationDefault;
+ //String serverImpinjNameDefault = "wallace.sit@cne.com.hk", serverImpinjName = serverImpinjNameDefault;
+ public String serverImpinjNameDefault = "", serverImpinjName = serverImpinjNameDefault;
+ //String serverImpinjPasswordDefault = "Cne12345678?", serverImpinjPassword = serverImpinjPasswordDefault;
+ public String serverImpinjPasswordDefault = "", serverImpinjPassword = serverImpinjPasswordDefault;
+
+ public int iForegroundDupElimDefault = 1, iForegroundDupElim = iForegroundDupElimDefault;
+
+ public boolean barcode2TriggerModeDefault = true, barcode2TriggerMode = barcode2TriggerModeDefault;
+
+ public boolean userDebugEnableDefault = false, userDebugEnable = userDebugEnableDefault;
+
+ //Filter
+ public static class PreFilterData {
+ public boolean enable; public int target;
+ public int action;
+ public int bank;
+ public int offset; public String mask; public boolean maskbit;
+ public PreFilterData() { }
+ public PreFilterData(boolean enable, int target, int action, int bank, int offset, String mask, boolean maskbit) {
+ this.enable = enable;
+ this.target = target;
+ this.action = action;
+ this.bank = bank;
+ this.offset = offset;
+ this.mask = mask;
+ this.maskbit = maskbit;
+ }
+ }
+ public PreFilterData preFilterData;
+
+ public File fileSetting;
+ boolean loadSettingFile(String stringMacAddress, String strlibraryVersion, boolean bChannelHoppingStatus, int iCurrentProfile) {
+ boolean DEBUG = true;
+ appendToLog("SettingData.loadSettingFile:"
+ + "\nstringMacAddress = " + stringMacAddress
+ + "\nstrlibraryVersion = " + strlibraryVersion
+ + "\nbChannelHoppingStatus = " + bChannelHoppingStatus
+ + "\niCurrentProfile = " + iCurrentProfile);
+
+ File path = context.getFilesDir();
+ String fileName = stringMacAddress; //bluetoothGatt.getmBluetoothDevice().getAddress(); //stringMacAddress
+
+ fileName = "csReaderA_" + fileName.replaceAll(":", "").replaceAll(" ", "");
+ fileSetting = new File(path, fileName);
+ boolean bNeedDefault = true;
+ if (DEBUG_FILE) utility.appendToLogView("FileName = " + fileName + ".exits = " + fileSetting.exists() + ", with beepEnable = " + inventoryBeep);
+ if (fileSetting.exists()) {
+ InputStream instream = null;
+ try {
+ instream = new FileInputStream(fileSetting);
+ } catch (Exception ex) {
+ //
+ }
+ if (instream != null) {
+ InputStreamReader inputStreamReader = new InputStreamReader(instream);
+ BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
+ String line;
+ int queryTarget = -1; int querySession = -1; int querySelect = -1;
+ int startQValue = -1; int maxQValue = -1; int minQValue = -1; int retryCount = -1;
+ int fixedQValue = -1; int fixedRetryCount = -1;
+ int population = -1;
+ boolean invAlgo = true; int retry = -1;
+ preFilterData = new SettingData.PreFilterData();
+ while(true) {
+ line = null;
+ try {
+ line = bufferedReader.readLine();
+ } catch (Exception ex) {
+ //
+ }
+ if (line == null) break;
+ if (DEBUG_FILE || true) appendToLog("FileA Data read = " + line);
+ String[] dataArray = line.split(",");
+ if (dataArray.length == 2) {
+ if (dataArray[0].matches("appVersion")) {
+ appendToLog("datArray[1] = " + dataArray[1] + ", strlibraryVersion = " + strlibraryVersion);
+ if (dataArray[1].matches(strlibraryVersion)) bNeedDefault = false;
+ } else if (bNeedDefault == true) {
+ } else if (dataArray[0].matches("countryInList")) {
+ csReaderConnector.rfidReader.getRegionList(); //getRegionList();
+ int countryInListNew = Integer.valueOf(dataArray[1]);
+ if (csReaderConnector.rfidReader.countryInList != countryInListNew && countryInListNew >= 0) csReaderConnector.rfidReader.setCountryInList(countryInListNew);
+ csReaderConnector.rfidReader.channelOrderType = -1;
+ } else if (dataArray[0].matches("channel")) {
+ int channelNew = Integer.valueOf(dataArray[1]);
+ if (bChannelHoppingStatus == false && channelNew >= 0) csReaderConnector.rfidReader.setChannel(channelNew);
+ } else if (dataArray[0].matches("antennaPower")) {
+ long lValue = Long.valueOf(dataArray[1]);
+ if (lValue >= 0) csReaderConnector.rfidReader.setPowerLevel(lValue);
+ } else if (dataArray[0].matches("antennaDwell")) {
+ long lValue = Long.valueOf(dataArray[1]);
+ if (lValue >= 0) {
+ csReaderConnector.rfidReader.setAntennaDwell(lValue);
+ }
+ } else if (dataArray[0].matches("population")) {
+ population = Integer.valueOf(dataArray[1]);
+ } else if (dataArray[0].matches("querySession")) {
+ int iValue = Integer.valueOf(dataArray[1]);
+ if (iValue >= 0) querySession = iValue;
+ } else if (dataArray[0].matches("queryTarget")) {
+ queryTarget = Integer.valueOf(dataArray[1]);
+ } else if (dataArray[0].matches("tagFocus")) {
+ int iValue = Integer.valueOf(dataArray[1]);
+ if (iValue >= 0) csReaderConnector.rfidReader.tagFocus = iValue;
+ } else if (dataArray[0].matches("fastId")) {
+ int iValue = Integer.valueOf(dataArray[1]);
+ if (iValue >= 0) csReaderConnector.rfidReader.fastId = iValue;
+ } else if (dataArray[0].matches("invAlgo")) {
+ invAlgo = dataArray[1].matches("true") ? true : false;
+ } else if (dataArray[0].matches("retry")) {
+ retry = Integer.valueOf(dataArray[1]);
+ } else if (dataArray[0].matches("currentProfile")) {
+ int iValue = Integer.valueOf(dataArray[1]);
+ appendToLog("SettingData.loadSettingFile setCurrentLinkProfile as " + iValue);
+ if (iValue >= 0) csReaderConnector.rfidReader.setCurrentLinkProfile(iValue);
+ } else if (dataArray[0].matches("rxGain")) {
+ csReaderConnector.rfidReader.setRxGain(Integer.valueOf(dataArray[1]));
+ } else if (dataArray[0].matches("deviceName")) {
+ csReaderConnector.bluetoothConnector.deviceName = dataArray[1].getBytes();
+ } else if (dataArray[0].matches("batteryDisplay")) {
+ setBatteryDisplaySetting(Integer.valueOf(dataArray[1]));
+ } else if (dataArray[0].matches("rssiDisplay")) {
+ setRssiDisplaySetting(Integer.valueOf(dataArray[1]));
+ } else if (dataArray[0].matches("tagDelay")) {
+ csReaderConnector.rfidReader.setTagDelay(Byte.valueOf(dataArray[1]));
+ } else if (dataArray[0].matches("cycleDelay")) {
+ csReaderConnector.rfidReader.setCycleDelay(Long.valueOf(dataArray[1]));
+ } else if (dataArray[0].matches("intraPkDelay")) {
+ csReaderConnector.rfidReader.setIntraPkDelay(Byte.valueOf(dataArray[1]));
+ } else if (dataArray[0].matches("dupDelay")) {
+ csReaderConnector.rfidReader.setDupDelay(Byte.valueOf(dataArray[1]));
+
+ } else if (dataArray[0].matches(("triggerReporting"))) {
+ appendToLog("FileA: going to setTriggerReporting with notificationConnector as " + (notificationConnector == null ? "null" : "valid"));
+ notificationConnector.setTriggerReporting(dataArray[1].matches("true") ? true : false);
+ appendToLog("FileA: setTriggerReporting is done");
+ } else if (dataArray[0].matches(("triggerReportingCount"))) {
+ notificationConnector.setTriggerReportingCount(Short.valueOf(dataArray[1]));
+ } else if (dataArray[0].matches(("inventoryBeep"))) {
+ inventoryBeep = dataArray[1].matches("true") ? true : false; //setInventoryBeep(dataArray[1].matches("true") ? true : false);
+ } else if (dataArray[0].matches(("inventoryBeepCount"))) {
+ beepCountSetting = Integer.valueOf(dataArray[1]); //setBeepCount(Integer.valueOf(dataArray[1]));
+ } else if (dataArray[0].matches(("inventoryVibrate"))) {
+ inventoryVibrate = dataArray[1].matches("true") ? true : false; //setInventoryVibrate(dataArray[1].matches("true") ? true : false);
+ } else if (dataArray[0].matches(("inventoryVibrateTime"))) {
+ vibrateTimeSetting = Integer.valueOf(dataArray[1]); //setVibrateTime(Integer.valueOf(dataArray[1]));
+ } else if (dataArray[0].matches(("inventoryVibrateMode"))) {
+ vibrateModeSelect = Integer.valueOf(dataArray[1]); //setVibrateModeSetting(Integer.valueOf(dataArray[1]));
+ } else if (dataArray[0].matches(("savingFormat"))) {
+ savingFormatSelect = Integer.valueOf(dataArray[1]); //setSavingFormatSetting(Integer.valueOf(dataArray[1]));
+ } else if (dataArray[0].matches(("csvColumnSelect"))) {
+ csvColumnSelect = Integer.valueOf(dataArray[1]); //setCsvColumnSelectSetting(Integer.valueOf(dataArray[1]));
+ } else if (dataArray[0].matches(("inventoryVibrateWindow"))) {
+ vibrateWindowSetting = Integer.valueOf(dataArray[1]); //setVibrateWindow(Integer.valueOf(dataArray[1]));
+
+ } else if (dataArray[0].matches(("saveFileEnable"))) {
+ saveFileEnable = dataArray[1].matches("true") ? true : false;
+ } else if (dataArray[0].matches(("saveCloudEnable"))) {
+ saveCloudEnable = dataArray[1].matches("true") ? true : false;
+ } else if (dataArray[0].matches(("saveNewCloudEnable"))) {
+ saveNewCloudEnable = dataArray[1].matches("true") ? true : false;
+ } else if (dataArray[0].matches(("saveAllCloudEnable"))) {
+ saveAllCloudEnable = dataArray[1].matches("true") ? true : false;
+ } else if (dataArray[0].matches(("serverLocation"))) {
+ serverLocation = dataArray[1];
+ } else if (dataArray[0].matches("serverTimeout")) {
+ serverTimeout = Integer.valueOf(dataArray[1]);
+ } else if (dataArray[0].matches(("serverMqttLocation"))) {
+ serverMqttLocation = dataArray[1];
+ } else if (dataArray[0].matches(("topicMqtt"))) {
+ topicMqtt = dataArray[1];
+ } else if (dataArray[0].matches(("foregroundDupElim"))) {
+ iForegroundDupElim = Integer.valueOf(dataArray[1]);
+ } else if (dataArray[0].matches(("inventoryCloudSave"))) {
+ inventoryCloudSave = Integer.parseInt(dataArray[1]);
+ } else if (dataArray[0].matches(("serverImpinjLocation"))) {
+ serverImpinjLocation = dataArray[1];
+ } else if (dataArray[0].matches(("serverImpinjName"))) {
+ serverImpinjName = dataArray[1];
+ } else if (dataArray[0].matches(("serverImpinjPassword"))) {
+ serverImpinjPassword = dataArray[1];
+
+ } else if (dataArray[0].matches("barcode2TriggerMode")) {
+ if (dataArray[1].matches("true")) barcode2TriggerMode = true;
+ else barcode2TriggerMode = false;
+ } else if (dataArray[0].matches("preFilterData.enable")) {
+ if (dataArray[1].matches("true")) preFilterData.enable = true;
+ else preFilterData.enable = false;
+ } else if (dataArray[0].matches("preFilterData.target")) {
+ preFilterData.target = Integer.valueOf(dataArray[1]);
+ } else if (dataArray[0].matches("preFilterData.action")) {
+ preFilterData.action = Integer.valueOf(dataArray[1]);
+ } else if (dataArray[0].matches("preFilterData.bank")) {
+ preFilterData.bank = Integer.valueOf(dataArray[1]);
+ } else if (dataArray[0].matches("preFilterData.offset")) {
+ preFilterData.offset = Integer.valueOf(dataArray[1]);
+ } else if (dataArray[0].matches("preFilterData.mask")) {
+ preFilterData.mask = dataArray[1];
+ } else if (dataArray[0].matches("preFilterData.maskbit")) {
+ if (dataArray[1].matches("true")) preFilterData.maskbit = true;
+ else preFilterData.maskbit = false;
+ } else if (dataArray[0].matches(("userDebugEnable"))) {
+ userDebugEnable = dataArray[1].matches("true") ? true : false;
+ }
+ }
+ }
+ csReaderConnector.rfidReader.setInvAlgo(invAlgo);
+ csReaderConnector.rfidReader.setPopulation(population);
+ csReaderConnector.rfidReader.setRetryCount(retry);
+ csReaderConnector.rfidReader.setTagGroup(querySelect, querySession, queryTarget);
+ csReaderConnector.rfidReader.setTagFocus(csReaderConnector.rfidReader.tagFocus > 0 ? true : false);
+ if (preFilterData != null && preFilterData.enable) {
+ if (utility.DEBUG_SELECT) appendToLog("Debug_Select: SettingData.loadingSettingFile. preFilterData is valid. Going to setSelectCriteria");
+ appendToLog("BtDataOut BBB 5");
+ csReaderConnector.rfidReader.setSelectCriteria(0, preFilterData.enable, preFilterData.target, preFilterData.action, preFilterData.bank, preFilterData.offset, preFilterData.mask, preFilterData.maskbit);
+ } else {
+ if (utility.DEBUG_SELECT) appendToLog("Debug_Select: SettingData.loadingSettingFile. preFilterData is null or disabled. Going to setSelectCriteriaDisable");
+ csReaderConnector.rfidReader.setSelectCriteriaDisable(0);
+ }
+ }
+ try {
+ instream.close();
+ } catch (Exception ex) { }
+ if (DEBUG_FILE) appendToLog("Data is read from FILE.");
+ }
+ if (bNeedDefault) {
+ appendToLog("saveSetting2File default !!!");
+ csReaderConnector.rfidReader.setReaderDefault();
+ saveSetting2File(strlibraryVersion, bChannelHoppingStatus, iCurrentProfile);
+ }
+ return bNeedDefault;
+ }
+ public void saveSetting2File(String strLibraryVersion, boolean bChannelHoppingStatus, int iCurrentProfile) {
+ boolean DEBUG = false;
+ if (DEBUG) appendToLog("Start");
+ FileOutputStream stream;
+ try {
+ stream = new FileOutputStream(fileSetting);
+ write2FileStream(stream, "Start of data\n");
+
+ write2FileStream(stream, "appVersion," + strLibraryVersion + "\n");
+ write2FileStream(stream, "countryInList," + String.valueOf(csReaderConnector.rfidReader.countryInList + "\n"));
+ if (!bChannelHoppingStatus) write2FileStream(stream, "channel," + String.valueOf(channel + "\n"));
+
+ write2FileStream(stream, "antennaPower," + String.valueOf(csReaderConnector.rfidReader.getPwrlevel() + "\n"));
+ write2FileStream(stream, "antennaDwell," + String.valueOf(csReaderConnector.rfidReader.getAntennaDwell() + "\n"));
+ write2FileStream(stream, "population," + String.valueOf(csReaderConnector.rfidReader.getPopulation() +"\n"));
+ write2FileStream(stream, "querySession," + String.valueOf(csReaderConnector.rfidReader.getQuerySession() + "\n"));
+ write2FileStream(stream, "queryTarget," + String.valueOf(csReaderConnector.rfidReader.getQueryTarget() + "\n"));
+ write2FileStream(stream, "tagFocus," + String.valueOf(csReaderConnector.rfidReader.getTagFocus() + "\n"));
+ write2FileStream(stream, "fastId," + String.valueOf(csReaderConnector.rfidReader.getFastId() + "\n"));
+ write2FileStream(stream, "invAlgo," + String.valueOf(csReaderConnector.rfidReader.getInvAlgo() + "\n"));
+ write2FileStream(stream, "retry," + String.valueOf(csReaderConnector.rfidReader.getRetryCount() + "\n"));
+ int iValue = csReaderConnector.rfidReader.getCurrentProfile();
+ appendToLog("SettingData.saveSettingFile getCurrentProfile as " + iValue);
+ write2FileStream(stream, "currentProfile," + String.valueOf(iValue + "\n"));
+ write2FileStream(stream, "rxGain," + String.valueOf(csReaderConnector.rfidReader.getRxGain() + "\n"));
+
+ write2FileStream(stream, "deviceName," + csReaderConnector.bluetoothConnector.getBluetoothIcName() + "\n");
+ write2FileStream(stream, "batteryDisplay," + String.valueOf(batteryDisplaySelect + "\n"));
+ write2FileStream(stream, "rssiDisplay," + String.valueOf(rssiDisplaySelect + "\n"));
+ write2FileStream(stream, "tagDelay," + String.valueOf(csReaderConnector.rfidReader.getTagDelay() + "\n"));
+ write2FileStream(stream, "cycleDelay," + String.valueOf(csReaderConnector.rfidReader.getCycleDelay() + "\n"));
+ write2FileStream(stream, "intraPkDelay," + String.valueOf(csReaderConnector.rfidReader.getIntraPkDelay() + "\n"));
+ write2FileStream(stream, "dupDelay," + String.valueOf(csReaderConnector.rfidReader.getDupDelay() + "\n"));
+
+ write2FileStream(stream, "triggerReporting," + String.valueOf(notificationConnector.getTriggerReporting() + "\n"));
+ write2FileStream(stream, "triggerReportingCount," + String.valueOf(notificationConnector.getTriggerReportingCount() + "\n"));
+ write2FileStream(stream, "inventoryBeep," + String.valueOf(inventoryBeep + "\n"));
+ write2FileStream(stream, "inventoryBeepCount," + String.valueOf(beepCountSetting + "\n"));
+ write2FileStream(stream, "inventoryVibrate," + String.valueOf(inventoryVibrate + "\n"));
+ write2FileStream(stream, "inventoryVibrateTime," + String.valueOf(vibrateTimeSetting + "\n"));
+ write2FileStream(stream, "inventoryVibrateMode," + String.valueOf(vibrateModeSelect + "\n"));
+ write2FileStream(stream, "inventoryVibrateWindow," + String.valueOf(vibrateWindowSetting + "\n"));
+
+ write2FileStream(stream, "savingFormat," + String.valueOf(savingFormatSelect + "\n"));
+ write2FileStream(stream, "csvColumnSelect," + String.valueOf(csvColumnSelect + "\n"));
+ write2FileStream(stream, "saveFileEnable," + String.valueOf(saveFileEnable + "\n"));
+ write2FileStream(stream, "saveCloudEnable," + String.valueOf(saveCloudEnable + "\n"));
+ write2FileStream(stream, "saveNewCloudEnable," + String.valueOf(saveNewCloudEnable + "\n"));
+ write2FileStream(stream, "saveAllCloudEnable," + String.valueOf(saveAllCloudEnable + "\n"));
+ write2FileStream(stream, "serverLocation," + serverLocation + "\n");
+ write2FileStream(stream, "serverTimeout," + String.valueOf(serverTimeout + "\n"));
+ write2FileStream(stream, "serverMqttLocation," + serverMqttLocation + "\n");
+ write2FileStream(stream, "topicMqtt," + topicMqtt + "\n");
+ write2FileStream(stream, "foregroundDupElim," + String.valueOf(iForegroundDupElim + "\n"));
+ write2FileStream(stream, "inventoryCloudSave," + inventoryCloudSave + "\n");
+ write2FileStream(stream, "serverImpinjLocation," + serverImpinjLocation + "\n");
+ write2FileStream(stream, "serverImpinjName," + serverImpinjName + "\n");
+ write2FileStream(stream, "serverImpinjPassword," + serverImpinjPassword + "\n");
+ write2FileStream(stream, "barcode2TriggerMode," + String.valueOf(barcode2TriggerMode + "\n"));
+
+// write2FileStream(stream, "wedgePrefix," + getWedgePrefix() + "\n");
+// write2FileStream(stream, "wedgeSuffix," + getWedgeSuffix() + "\n");
+// write2FileStream(stream, "wedgeDelimiter," + String.valueOf(getWedgeDelimiter()) + "\n");
+
+ write2FileStream(stream, "userDebugEnable," + String.valueOf(userDebugEnable + "\n"));
+ if (preFilterData != null) {
+ write2FileStream(stream, "preFilterData.enable," + String.valueOf(preFilterData.enable + "\n"));
+ write2FileStream(stream, "preFilterData.target," + String.valueOf(preFilterData.target + "\n"));
+ write2FileStream(stream, "preFilterData.action," + String.valueOf(preFilterData.action + "\n"));
+ write2FileStream(stream, "preFilterData.bank," + String.valueOf(preFilterData.bank + "\n"));
+ write2FileStream(stream, "preFilterData.offset," + String.valueOf(preFilterData.offset + "\n"));
+ write2FileStream(stream, "preFilterData.mask," + String.valueOf(preFilterData.mask + "\n"));
+ write2FileStream(stream, "preFilterData.maskbit," + String.valueOf(preFilterData.maskbit + "\n"));
+ }
+
+ write2FileStream(stream, "End of data\n"); //.getBytes()); if (DEBUG) appendToLog("outData = " + outData);
+ stream.close();
+ } catch (Exception ex){
+ //
+ }
+ saveForegroundSetting2File();
+ }
+
+ public String strForegroundReaderDefault = "", strForegroundReader = strForegroundReaderDefault;
+ File fileForegroundSetting;
+ boolean loadForegroundSettingFile() {
+ File path = context.getFilesDir();
+ String fileName = "csReaderA_Foreground";
+ fileForegroundSetting = new File(path, fileName);
+ appendToLog("file0.exists = " + fileForegroundSetting.exists());
+ if (fileForegroundSetting.exists()) {
+ try {
+ InputStream instream = new FileInputStream(fileForegroundSetting);
+ appendToLog("file0.instream is " + (instream == null ? "null" : "valid"));
+ if (instream != null) {
+ InputStreamReader inputStreamReader = new InputStreamReader(instream);
+ BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
+ String line;
+ while ((line = bufferedReader.readLine()) != null) {
+ appendToLog("file0.line: " + line);
+ String[] dataArray = line.split(",");
+ if (dataArray.length == 2) {
+ if (dataArray[0].matches("foreground.reader")) {
+ appendToLog("foregroundReader: set 5");
+ strForegroundReader = dataArray[1];
+ appendToLog("file0.foreground.reader = " + strForegroundReader);
+ appendToLog("loaded strForegroundReader is " + this.strForegroundReader);
+ }
+ }
+ }
+ }
+ instream.close();
+ } catch (Exception ex) {
+ //
+ }
+ }
+ return true;
+ }
+ public void saveForegroundSetting2File() {
+ boolean DEBUG = false;
+ if (DEBUG) appendToLog("Start");
+
+ FileOutputStream stream;
+ try {
+ stream = new FileOutputStream(fileForegroundSetting);
+ write2FileStream(stream, "Start of File0 data\n");
+
+ write2FileStream(stream, "foreground.enable," + "true" + "\n");
+ appendToLog("strForegroundReader = " + strForegroundReader);
+ write2FileStream(stream, "foreground.reader," + strForegroundReader + "\n");
+ write2FileStream(stream, "End of File0 data\n");
+ stream.close();
+ } catch (Exception ex) {
+ //
+ }
+ }
+
+ public static String wedgeDeviceName;
+ public static String wedgeDeviceAddress;
+ public static int wedgeDeviceUUID2p1;
+ public String wedgePrefix = null, wedgeSuffix = null;
+ public int wedgeOutput = 0, wedgeDelimiter = 0x0a, wedgePower = 300;
+ public String fileNameWedgeSetting = "csReaderA_SimpleWedge";
+ void loadWedgeSettingFile() {
+ appendToLog("KKK: loadWedgeSettingFile starts");
+ File path = context.getFilesDir();
+ File file = new File(path, fileNameWedgeSetting);
+ boolean bNeedDefault = true, DEBUG = false;
+ appendToLog(fileNameWedgeSetting + "file.exists = " + file.exists());
+ if (file.exists()) {
+ int length = (int) file.length();
+ byte[] bytes = new byte[length];
+ try {
+ InputStream instream = new FileInputStream(file);
+ if (instream != null) {
+ InputStreamReader inputStreamReader = new InputStreamReader(instream);
+ BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
+ String line;
+ while ((line = bufferedReader.readLine()) != null) {
+ if (true) appendToLog("Data read = " + line);
+ String[] dataArray = line.split(",");
+ if (dataArray.length == 2) {
+ if (dataArray[0].matches("wedgeDeviceName")) {
+ wedgeDeviceName = dataArray[1];
+ } else if (dataArray[0].matches("wedgeDeviceAddress")) {
+ wedgeDeviceAddress = dataArray[1];
+ } else if (dataArray[0].matches("wedgeDeviceUUID2p1")) {
+ wedgeDeviceUUID2p1 = Integer.valueOf(dataArray[1]);
+ } else if (dataArray[0].matches("wedgePower")) {
+ wedgePower = Integer.valueOf(dataArray[1]);
+ } else if (dataArray[0].matches("wedgePrefix")) {
+ wedgePrefix = dataArray[1];
+ } else if (dataArray[0].matches("wedgeSuffix")) {
+ wedgeSuffix = dataArray[1];
+ } else if (dataArray[0].matches("wedgeDelimiter")) {
+ wedgeDelimiter = Integer.valueOf(dataArray[1]);
+ appendToLog("MainActivity, loadWedgeSettingFile: wedgeDelimiter = " + wedgeDelimiter);
+ } else if (dataArray[0].matches("wedgeOutput")) {
+ wedgeOutput = Integer.valueOf(dataArray[1]);
+ }
+ }
+ }
+ }
+ instream.close();
+ } catch (Exception ex) {
+ //
+ }
+ }
+ }
+ void saveWedgeSetting2File() {
+ appendToLog("KKK: saveWedgeSetting2File starts");
+ File path = context.getFilesDir();
+ File file = new File(path, fileNameWedgeSetting);
+ FileOutputStream stream;
+ try {
+ stream = new FileOutputStream(file);
+ write2FileStream(stream, "Start of data\n");
+ write2FileStream(stream, "wedgeDeviceName," + wedgeDeviceName + "\n");
+ write2FileStream(stream, "wedgeDeviceAddress," + wedgeDeviceAddress + "\n");
+ write2FileStream(stream, "wedgeDeviceUUID2p1," + String.valueOf(wedgeDeviceUUID2p1) + "\n");
+ write2FileStream(stream, "wedgePower," + wedgePower + "\n");
+ write2FileStream(stream, "wedgePrefix," + wedgePrefix + "\n");
+ write2FileStream(stream, "wedgeSuffix," + wedgeSuffix + "\n");
+ write2FileStream(stream, "wedgeDelimiter," + String.valueOf(wedgeDelimiter) + "\n"); appendToLog("SettingWedgeFragment, saveWedgeFragment: wedgeDelimiter = " + wedgeDelimiter);
+ write2FileStream(stream, "wedgeOutput," + String.valueOf(wedgeOutput) + "\n");
+ write2FileStream(stream, "End of data\n");
+ stream.close();
+ } catch (Exception ex){
+ //
+ }
+ }
+}
+
+
+
+package com.csl.cslibrary4a;
+
+import static android.content.Intent.parseUri;
+import static android.hardware.usb.UsbConstants.USB_DIR_IN;
+import static android.hardware.usb.UsbConstants.USB_DIR_OUT;
+import static android.hardware.usb.UsbConstants.USB_ENDPOINT_XFER_BULK;
+import static android.hardware.usb.UsbConstants.USB_ENDPOINT_XFER_INT;
+import static android.hardware.usb.UsbManager.ACTION_USB_DEVICE_ATTACHED;
+import static android.hardware.usb.UsbManager.ACTION_USB_DEVICE_DETACHED;
+
+import android.app.PendingIntent;
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
+import android.content.IntentFilter;
+import android.hardware.usb.UsbDevice;
+import android.hardware.usb.UsbDeviceConnection;
+import android.hardware.usb.UsbEndpoint;
+import android.hardware.usb.UsbInterface;
+import android.hardware.usb.UsbManager;
+import android.hardware.usb.UsbRequest;
+import android.os.Handler;
+import android.util.Log;
+import android.widget.TextView;
+import android.widget.Toast;
+
+import androidx.core.content.ContextCompat;
+
+import java.nio.ByteBuffer;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+
+class UsbConnector {
+ final boolean DEBUG = false;
+
+ CsReaderConnector csReaderConnector;
+ private Context context;
+ private TextView textView;
+ private int productId;
+ private int vendorId;
+ Utility utility;
+
+ final String ACTION_USB_PERMISSION = "com.csl.cs710ademoapp.USB_PERMISSION";
+ PendingIntent mPermissionIntent;
+
+ private UsbManager usbManager;
+ private UsbInterface usbInterface;
+ private UsbDeviceConnection usbDeviceConnection;
+ private UsbEndpoint usbEndpointOut, usbEndpointIn;
+ //private UsbEndpoint usbEndpoint4Write, usbEndpoint4Read;
+ private int packetSize;
+
+ private Handler mHandler = new Handler();
+ PendingIntent permissionIntent;
+
+ UsbConnector(CsReaderConnector csReaderConnector, Context context, TextView textView, int productId, int vendorId, Utility utility) {
+ this.csReaderConnector = csReaderConnector;
+ this.context = context;
+ this.textView = textView;
+ this.productId = productId;
+ this.vendorId = vendorId;
+ this.utility = utility;
+ appendToLog("UsbConnector.UsbConnector");
+
+ usbManager = (UsbManager) context.getSystemService(Context.USB_SERVICE);
+ appendToLog("UsbConnector.UsbConnector: done getSystemService with usbManager is " + (usbManager == null ? "null" : "valid"));
+
+ IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
+ filter.addAction(ACTION_USB_DEVICE_ATTACHED);
+ filter.addAction(ACTION_USB_DEVICE_DETACHED);
+ ContextCompat.registerReceiver(context, broadcastReceiver, filter, ContextCompat.RECEIVER_EXPORTED);
+ appendToLog("UsbConnector.UsbConnector: done registerReceiver");
+ }
+
+ HashMap usbDeviceHashMap;
+ private boolean scanning = false; boolean isBleScanning() { return scanning; }
+ void scanDevice(boolean enable) {
+ if (enable == false && isBleScanning() == false) return;
+
+ if (enable) {
+ if (true) {
+ Intent intent = new Intent();
+ UsbDevice usbDevice = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
+ appendToLog("UsbConnector.scanDevice: usbDevice is " + (usbDevice == null ? "null" : "valid"));
+ } //not working with the intent-filter, get only null intent
+ if (false) {
+ Intent intent = null;
+ try {
+ //intent = getIntent(UsbManager.EXTRA_DEVICE);
+ intent = parseUri(UsbManager.EXTRA_DEVICE, 0);
+ } catch (Exception ex) {
+ appendToLog("UsbConnector.scanDevice: getIntent exception " + ex.toString());
+ }
+ appendToLog("UsbConnector.scanDevice: intent is " + (intent == null ? "null" : "valid"));
+ if (intent != null) {
+ appendToLog("UsbConnector.scanDevice: intent.getAction is " + intent.getAction());
+ if (intent.getAction().equals(ACTION_USB_DEVICE_ATTACHED)) {
+ UsbDevice usbDevice = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
+ if (usbDevice != null) {
+ Log.d("onResume", "USB device attached: name: " + usbDevice.getDeviceName());
+ }
+ }
+ }
+ } //not working with the intent-filter, get only intent with action android.intent.action.VIEW
+
+ scanning = true;
+ Thread thread = new Thread(runnable);
+ thread.start();
+ } else scanning = false;
+ }
+
+ Runnable runnable = new Runnable() {
+ @Override
+ public void run() {
+ appendToLog("UsbConnector.runnable");
+
+ if (usbManager != null) {
+ usbDeviceHashMap = usbManager.getDeviceList();
+ appendToLog("UsbConnector.runnable: deviceList is " + (usbDeviceHashMap == null ? "null" : ("valid with size = " + usbDeviceHashMap.size())));
+ if (false) {
+ UsbDevice usbDevice = usbDeviceHashMap.get("/dev/bus/usb/001/004"); ///dev/bus/usb/001/002, 003
+ appendToLog("UsbConnector.runnable: usbDeviceHashMap.get[abc] is " + (usbDevice == null ? "null" : "valid"));
+ } //alternative method to get usbDevice, but the device name is changing when plugging
+ if (false) {
+ Iterator deviceIterator = usbDeviceHashMap.values().iterator();
+ appendToLog("UsbConnector.getUsbDeviceList: deviceIterator is " + (deviceIterator == null ? "null" : "valid"));
+ while (deviceIterator.hasNext()) {
+ UsbDevice device = deviceIterator.next();
+ }
+ } //alternative method to get usbDevice
+ for (UsbDevice device : usbDeviceHashMap.values()) {
+ if (!usbManager.hasPermission(device)) {
+ permissionIntent = PendingIntent.getBroadcast(context, 0, new Intent(ACTION_USB_PERMISSION), PendingIntent.FLAG_IMMUTABLE);
+ usbManager.requestPermission(device, permissionIntent);
+ break;
+ }
+ appendToLog("UsbConnector.runnable: device.getDeviceName = " + device.getDeviceName());
+ appendToLog("UsbConnector.runnable: device.getVendorId = " + device.getVendorId());
+ appendToLog("UsbConnector.runnable: device.getManufacturerName = " + device.getManufacturerName()); //null
+ appendToLog("UsbConnector.runnable: device.getProductName = " + device.getProductName()); //null
+ appendToLog("UsbConnector.runnable: device.getProductId = " + device.getProductId());
+ appendToLog("UsbConnector.runnable: device.getDeviceId = " + device.getDeviceId());
+ appendToLog("UsbConnector.runnable: device.getVersion = " + device.getVersion());
+ //appendToLog("UsbConnector.runnable: device.getSerialNumber = " + device.getSerialNumber()); //exceptioin
+ BluetoothGatt.CsScanData scanResultA = new BluetoothGatt.CsScanData(null, 0, null);
+ scanResultA.address = String.valueOf(device.getVendorId())
+ + " " + String.valueOf(device.getProductId())
+ + " " + String.valueOf(device.getDeviceId());
+ switch (device.getVendorId()) {
+ case 1003: //Atmel
+ scanResultA.name = "CS701 USB HID";
+ scanResultA.serviceUUID2p2 = 3;
+ break;
+ case 4292: //Silicon Laboratory
+ scanResultA.name = "CS108 USB HID";
+ scanResultA.serviceUUID2p2 = 1;
+ break;
+ }
+ appendToLog("UsbConnector.runnable: scanResultA.name is " + scanResultA.name);
+
+ if (csReaderConnector.mScanResultList != null) {
+ csReaderConnector.mScanResultList.add(scanResultA);
+ appendToLog("UsbConnector.runnable: scanResultA.getAddress is " + csReaderConnector.mScanResultList.get(0).getAddress());
+ }
+ }
+ }
+ scanning = false;
+ }
+ };
+
+ boolean usbConnectionState = false;
+ boolean connect(ReaderDevice readerDevice) {
+ boolean DEBUG = true;
+ if (DEBUG) appendToLog("UsbConnector.connect: " + (readerDevice == null ? "null" : "valid") + " readerDevice");
+ if (readerDevice == null) {
+ if (DEBUG) appendToLog("UsbConnector.connect: NULL readerDevice");
+ } else {
+ String address = readerDevice.getAddress();
+ if (DEBUG) appendToLog("UsbConnector.connect: readerDevice.address is " + address);
+ String[] stringsAddress = address.split(" ");
+ if (stringsAddress.length != 3) {
+ if (DEBUG) appendToLog("UsbConnector.connect: stringsAddress does not have 3 parts");
+ } else {
+ int iDeviceIdExpected = Integer.parseInt(stringsAddress[stringsAddress.length - 1]);
+ if (DEBUG) appendToLog("UsbConnector.connect: stringDeviceIdExpected = " + iDeviceIdExpected);
+
+ if (DEBUG) appendToLog("UsbConnector.connect: " + (usbManager == null ? "null": "valid") + " usbManager, "
+ + (usbDeviceHashMap == null ? "null" : "valid") + " usbDeviceHashMap");
+ if (usbManager == null) {
+ if (DEBUG) appendToLog("UsbConnector.connect: NULL mUsbManager");
+ } else if (usbDeviceHashMap == null) {
+ if (DEBUG) appendToLog("UsbConnector.connect: NULL usbDeviceHashMap");
+ } else {
+ boolean bValid = false;
+ if (DEBUG) appendToLog("UsbConnector.connect: usbDeviceHashMap.size = " + usbDeviceHashMap.size());
+ for (UsbDevice device : usbDeviceHashMap.values()) {
+ if (device == null) {
+ if (DEBUG) appendToLog("UsbConnector.connect: null usbDevice");
+ } else if (device.getDeviceId() == iDeviceIdExpected) {
+ if (DEBUG) appendToLog("UsbConnector.connect: found the corresponding usbDevice");
+
+ usbInterface = null;
+ int usbInterfaceCount = device.getInterfaceCount();
+ if (DEBUG) appendToLog("UsbConnector.connect: usbInterfaceCount = " + usbInterfaceCount);
+ for (int i = 0; i < usbInterfaceCount; i++) {
+ UsbInterface usbInterface1 = device.getInterface(i);
+ if (DEBUG) appendToLog("UsbConnector.connect: usbInterface[" + i + "] is "+ (usbInterface1 == null ? "null" : "valid"));
+ usbInterface = usbInterface1;
+ }
+
+ usbEndpointOut = null;
+ if (usbInterface == null) {
+ if (DEBUG) appendToLog("UsbConnector.connect: null usbInterface");
+ } else {
+ int usbEndpointCount = usbInterface.getEndpointCount();
+ if (DEBUG) appendToLog("UsbConnector.connect: usbEndpointCount = " + usbEndpointCount);
+ for (int i = 0; i < usbEndpointCount; i++) {
+ UsbEndpoint usbEndpoint1 = usbInterface.getEndpoint(i);
+ appendToLog("UsbConnector.connect: " + (usbEndpoint1 == null ? "null" : "valid") + " usbInterface[" + i
+ + "], type = " + usbEndpoint1.getType()
+ + ", direction = " + usbEndpoint1.getDirection());
+ if (usbEndpoint1.getDirection() == USB_DIR_OUT) {
+ appendToLog("UsbConnector.connect: found output endpoint with MaxPacketSize = " + usbEndpoint1.getMaxPacketSize());
+ usbEndpointOut = usbEndpoint1;
+ } else if (usbEndpoint1.getDirection() == USB_DIR_IN) {
+ appendToLog("UsbConnector.connect: found input endpoint with MaxPacketSize = " + usbEndpoint1.getMaxPacketSize());
+ usbEndpointIn = usbEndpoint1;
+ }
+ }
+ }
+
+ usbDeviceConnection = null;
+ if (usbInterface == null || usbEndpointOut == null) {
+ if (DEBUG) appendToLog("UsbConnector.connect: null usbInterface or usbEndpointOut");
+ } else {
+ usbDeviceConnection = usbManager.openDevice(device);
+ if (DEBUG) appendToLog("UsbConnector.connect: usbDeviceConnection is " + (usbDeviceConnection == null ? "null" : "valid"));
+ usbDeviceConnection.claimInterface(usbInterface, true);
+ if (DEBUG) appendToLog("UsbConnector.connect: done claimInterface");
+ }
+ bValid = true;
+ }
+ }
+
+ if (bValid) {
+ usbConnectionState = true;
+ mConnectedTimeMillis = System.currentTimeMillis();
+ boolean validPreviousConnect = false;
+ boolean needNewConnect = true;
+ if (isConnected()) validPreviousConnect = true;
+ /*
+ if (validPreviousConnect) {
+ // if (mBluetoothDevice.getAddress().matches(name)) {
+ needNewConnect = false;
+ // } else {
+ // disconnect(true);
+ // }
+ }
+ if (needNewConnect) {
+ HashMap deviceList = usbManager.getDeviceList();
+ Iterator deviceIterator = deviceList.values().iterator();
+ while (deviceIterator.hasNext()) {
+ UsbDevice device = deviceIterator.next();
+ if (device.getProductId() == productId && device.getVendorId() == vendorId && device.getDeviceName().contains(readerDevice.getName())) {
+ _usbDevice = device;
+ if (DEBUG) appendToLog("UsbConnector: connectBle(" + name + "): connectBle starts");
+
+ usbManager.requestPermission(_usbDevice, mPermissionIntent);
+ if (DEBUG) appendToLog("UsbConnector: UsbConnector().connectBle(): AAA");
+
+ connectRequested = true;
+ return true;
+ }
+ }
+ }
+ if (validPreviousConnect == false) {
+ if (DEBUG) appendToLog("UsbConnector: connectBle(" + name + "): connectBle FAIL");
+ // } else if (mBluetoothGatt.connectBle()) {
+ // appendToLog("UsbConnector: connectBle(" + name + "): re-connectBle starts");
+ // return true;
+ // } else {
+ // appendToLog("UsbConnector: connectBle(" + name + "): re-connectBle FAIL");
+ }
+ */
+ }
+ }
+ }
+ }
+ return false;
+ }
+
+ boolean connectRequested = false;
+ boolean isConnected() {
+ return usbConnectionState;
+/*
+ boolean DEBUG = true;
+ if (DEBUG) appendToLog("UsbConnector.isConnected: usbManger is " + (usbManager == null ? "null" : "valid")
+ + "usbDevice is " + (usbDevice == null ? "null" : "valid")
+ + "connectRequested is " + connectRequested);
+ if (usbManager == null || usbDevice == null || connectRequested == false) return false;
+ if (DEBUG) appendToLog("UsbConnector.isConnected: usbManager.hasPermission is " + usbManager.hasPermission(usbDevice));
+ if (!usbManager.hasPermission(usbDevice)) return false;
+ if (DEBUG) appendToLog("UsbConnector.isConnected: usbDeviceConnection is " + (usbDeviceConnection == null ? "null" : "valid"));
+ if (usbDeviceConnection == null) return false;
+ if (DEBUG) appendToLog("UsbConnector.isConnected: connected");
+// appendToLog("UsbConnector: g ");
+ return true;
+*/
+ }
+
+ private final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
+ public void onReceive(Context context, Intent intent) {
+ String action = intent.getAction();
+ appendToLog("UsbConnector.broadcastReceiver.onReceive: intent.getAction = " + action);
+ //appendToLog("UsbConnector.broadcastReceiver.onReceive: intent.getBooleanExtra = " + intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)); //getBooleanExtra is always default value
+ UsbDevice usbDevice = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
+ appendToLog("UsbConnector.broadcastReceiver.onReceive: got usbDevice is " + (usbDevice == null ? "null" : ("with deviceId as " + usbDevice.getDeviceId())));
+ if (action.equals(ACTION_USB_PERMISSION)) { //got usbDevice is null
+ appendToLog("UsbConnector.broadcastReceiver.onReceive: ACTION_USB_PERMISSION");
+ //setDevice(context, intent);
+ } else if (action.equals(ACTION_USB_DEVICE_ATTACHED)) {
+ appendToLog("UsbConnector.broadcastReceiver.onReceive: ACTION_USB_DEVICE_ATTACHED");
+ } else if (action.equals(ACTION_USB_DEVICE_DETACHED)) {
+ appendToLog("UsbConnector.broadcastReceiver.onReceive: ACTION_USB_DEVICE_DETACHED");
+ if (usbDevice != null) {
+ if (usbDeviceConnection != null) {
+ appendToLog("UsbConnector.broadcastReceiver.onReceive: going to releaseInterface and close usbDeviceConnection");
+ usbDeviceConnection.releaseInterface(usbInterface);
+ usbDeviceConnection.close();
+ }
+ // call your method that cleans up and closes communication with the device
+ }
+ }
+ }
+
+ private void setDevice(Context context, Intent intent) {
+ appendToLog("UsbConnector.usbReceiver.setDevice");
+ UsbDevice device = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
+ if (device == null) {
+ Toast.makeText(context, "Permission request with NULL DEVICE.", Toast.LENGTH_SHORT).show();
+ } else if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false) == false) {
+ //Log.d("TAG", "permission denied for the device " + device);
+ Toast.makeText(context, "Permission is REJECTED.", Toast.LENGTH_SHORT).show();
+ } else {
+ Toast.makeText(context, "Permission is Granted.", Toast.LENGTH_SHORT).show();
+ makeConnection();
+ }
+ }
+ };
+
+ boolean usbDataSending = false;
+ byte[] dataOutPending = null;
+ boolean writeStreamOut(byte[] dataOutRaw) {
+ boolean DEBUG = true;
+
+ appendToLog("UsbConnector.writeStreamOut, UsbConnector.waitStreamInOut.Runnable: raw dataOut " + byteArrayToString(dataOutRaw) + ", dataOutPending as " + (dataOutPending == null ? "null" : "valid"));
+ dataOutRaw[1] = (byte)0xE6;
+
+ dataOutPending = new byte[dataOutRaw.length + 2];
+ dataOutPending[0] = 2;
+ dataOutPending[1] = (byte) dataOutRaw.length;
+ System.arraycopy(dataOutRaw, 0, dataOutPending, 2, dataOutRaw.length);
+ appendToLog("UsbConnector.writeStreamOut, UsbData: processed value: " + byteArrayToString(dataOutPending));
+
+ if (true) waitStreamInOut();
+ else {
+ Thread thread = new Thread(new Runnable() {
+ @Override
+ public void run() {
+ if (DEBUG)
+ appendToLog("UsbConnector.writeStreamOut.Runnable: " + (usbDeviceConnection == null ? "null" : "valid") + " usbDeviceConnection, "
+ + (usbEndpointOut == null ? "null" : "valid") + " usbEndpointOut, "
+ + (usbEndpointIn == null ? "null" : "valid") + " usbEndpointIn");
+ if (usbEndpointOut.getType() == USB_ENDPOINT_XFER_BULK) { //for sending, okay to use following even if endpoint type is INT
+ if (DEBUG)
+ appendToLog("UsbConnector.writeStreamOut.Runnable: going to do bulkTransfer with dataOut as " + byteArrayToString(dataOutPending));
+ int iLength = usbDeviceConnection.bulkTransfer(usbEndpointOut, dataOutPending, dataOutPending.length, 0);
+ if (DEBUG)
+ appendToLog("UsbConnector.writeStreamOut.Runnable: done bulkTransfer with length = " + iLength);
+ } else if (usbEndpointOut.getType() == USB_ENDPOINT_XFER_INT) {
+ if (DEBUG)
+ appendToLog("UsbConnector.writeStreamOut.Runnable: going to do interrrupt transfer with dataOut as " + byteArrayToString(dataOutPending));
+ if (dataOutPending.length > usbEndpointOut.getMaxPacketSize())
+ appendToLog("UsbConnector.writeStreamOut.Runnable: cannot transfer as dataOut length is greater than MaxPacketSize " + usbEndpointOut.getMaxPacketSize());
+ else {
+ int bufferDataLength = dataOutPending.length;
+ ByteBuffer buffer = ByteBuffer.allocate(bufferDataLength + 1);
+ UsbRequest usbRequest = new UsbRequest();
+ buffer.put(dataOutPending);
+ if (DEBUG)
+ appendToLog("UsbConnector.writeStreamOut.Runnable: going to usbRequest.queue with position = " + buffer.position());
+
+ usbDataSending = true;
+ usbRequest.initialize(usbDeviceConnection, usbEndpointOut);
+ usbRequest.queue(buffer, bufferDataLength);
+ try {
+ boolean bEqual = usbRequest.equals(usbDeviceConnection.requestWait());
+ if (DEBUG)
+ appendToLog("UsbConnector.writeStreamOut.Runnable: done transfer with usbRequest.equals[usbDeviceConnection.requestWait] is " + bEqual + ", position = " + buffer.position());
+ } catch (Exception ex) {
+ appendToLog("UsbConnector.writeStreamOut.Runnable: requestWait exception as " + ex.toString());
+ }
+ usbDataSending = false;
+ }
+ } else {
+ if (DEBUG)
+ appendToLog("UsbConnector.writeStreamOut.Runnable: cannot handle as usbEndpointOut type is " + usbEndpointOut.getType());
+ }
+
+ if (DEBUG)
+ appendToLog("UsbConnector.writeStreamOut.Runnable: going to do threadStreamIn.start");
+ waitStreamInOut();
+ }
+ });
+ thread.start();
+ }
+
+ return true;
+ }
+
+ private boolean disableUSBThread = false;
+ public void waitStreamInOut() {
+ if (!disableUSBThread) {
+ disableUSBThread = true;
+ appendToLog("UsbConnector.waitStreamInOut, UsbData: starts");
+ Thread thread = new Thread(new Runnable() {
+ boolean DEBUG = true;
+ byte[] dataIn = new byte[16];
+
+ @Override
+ public void run() {
+ appendToLog("UsbConnector.waitStreamInOut.Runnable, UsbData: starts");
+ while (true) {
+ appendToLog("UsbConnector.waitStreamInOut.Runnable: dataOutPending is " + (dataOutPending == null ? "null" : "valid"));
+ if (dataOutPending != null) {
+ if (DEBUG)
+ appendToLog("UsbConnector.waitStreamInOut.Runnable: " + (usbDeviceConnection == null ? "null" : "valid") + " usbDeviceConnection, "
+ + (usbEndpointOut == null ? "null" : "valid") + " usbEndpointOut, "
+ + (usbEndpointIn == null ? "null" : "valid") + " usbEndpointIn");
+ if (usbEndpointOut.getType() == USB_ENDPOINT_XFER_BULK) { //for sending, okay to use following even if endpoint type is INT
+ if (DEBUG)
+ appendToLog("UsbConnector.waitStreamInOut.Runnable: going to do bulkTransfer with dataOut as " + byteArrayToString(dataOutPending));
+ int iLength = usbDeviceConnection.bulkTransfer(usbEndpointOut, dataOutPending, dataOutPending.length, 0);
+ if (DEBUG)
+ appendToLog("UsbConnector.waitStreamInOut.Runnable: done bulkTransfer with length = " + iLength);
+ } else if (usbEndpointOut.getType() == USB_ENDPOINT_XFER_INT) {
+ if (DEBUG)
+ appendToLog("UsbConnector.waitStreamInOut.Runnable: going to do interrrupt transfer with dataOut as " + byteArrayToString(dataOutPending));
+ if (dataOutPending.length > usbEndpointOut.getMaxPacketSize())
+ appendToLog("UsbConnector.waitStreamInOut.Runnable: cannot transfer as dataOut length is greater than MaxPacketSize " + usbEndpointOut.getMaxPacketSize());
+ else {
+ int bufferDataLength = dataOutPending.length;
+ ByteBuffer buffer = ByteBuffer.allocate(bufferDataLength + 1);
+ UsbRequest usbRequest = new UsbRequest();
+ buffer.put(dataOutPending);
+ if (DEBUG)
+ appendToLog("UsbConnector.waitStreamInOut.Runnable: going to usbRequest.queue with position = " + buffer.position());
+
+ usbDataSending = true;
+ usbRequest.initialize(usbDeviceConnection, usbEndpointOut);
+ usbRequest.queue(buffer, bufferDataLength);
+ try {
+ boolean bEqual = usbRequest.equals(usbDeviceConnection.requestWait());
+ if (DEBUG)
+ appendToLog("UsbConnector.waitStreamInOut.Runnable: done transfer with usbRequest.equals[usbDeviceConnection.requestWait] is " + bEqual + ", position = " + buffer.position());
+ Thread.sleep(100);
+ } catch (Exception ex) {
+ appendToLog("UsbConnector.waitStreamInOut.Runnable: requestWait exception as " + ex.toString());
+ }
+ usbDataSending = false;
+ }
+ } else if (DEBUG) appendToLog("UsbConnector.waitStreamInOut.Runnable: cannot handle as usbEndpointOut type is " + usbEndpointOut.getType());
+ dataOutPending = null;
+ } else {
+ if (usbEndpointIn.getType() == USB_ENDPOINT_XFER_BULK) {
+ if (DEBUG)
+ appendToLog("UsbConnector.waitStreamInOut.Runnable: going to do bulkTransfer to dataIn");
+ int iLength = usbDeviceConnection.bulkTransfer(usbEndpointIn, dataIn, dataIn.length, 0);
+ if (DEBUG)
+ appendToLog("UsbConnector.waitStreamInOut.Runnable: done bulkTransfer to usbEndpointIn with length = " + iLength);
+ if (DEBUG)
+ appendToLog("UsbConnector.waitStreamInOut.Runnable: buffer received is " + byteArrayToString(dataIn));
+
+ } else if (usbEndpointIn.getType() == USB_ENDPOINT_XFER_INT) { //for receiving, must use following if endpoint type is INT
+ if (DEBUG)
+ appendToLog("UsbConnector.waitStreamInOut.Runnable, UsbData: going to do interrupt transfer to dataIn");
+ int bufferDataLength = usbEndpointIn.getMaxPacketSize();
+ ByteBuffer buffer = ByteBuffer.allocate(bufferDataLength + 1);
+ UsbRequest usbRequest = new UsbRequest();
+ if (DEBUG)
+ appendToLog("UsbConnector.waitStreamInOut.Runnable, UsbData: going to usbRequest.queue with position = " + buffer.position());
+ usbRequest.initialize(usbDeviceConnection, usbEndpointIn);
+ usbRequest.queue(buffer, bufferDataLength);
+ try {
+ boolean bEqual = usbRequest.equals(usbDeviceConnection.requestWait(50));
+ if (DEBUG)
+ appendToLog("UsbConnector.waitStreamInOut.Runnable, UsbData: done transfer with usbRequest.equals[usbDeviceConnection.requestWait] is " + bEqual + ", position = " + buffer.position());
+ byte[] dataInRaw = buffer.array();
+ if (DEBUG && dataInRaw[0] != 0)
+ appendToLog("UsbConnector.waitStreamInOut.Runnable, UsbData: buffer received is " + byteArrayToString(dataInRaw));
+
+ if (bEqual && (buffer.position() > 0) && (dataInRaw[0] == 1) && (dataInRaw.length > (dataInRaw[1] + 2))) {
+ dataIn = new byte[dataInRaw[1]];
+ System.arraycopy(dataInRaw, 2, dataIn, 0, dataIn.length);
+ if (DEBUG || true)
+ appendToLog("UsbConnector.waitStreamInOut.Runnable, UsbData: dataIn " + dataIn.length + " is " + byteArrayToString(dataIn));
+ synchronized (arrayListStreamIn) {
+ //arrayListStreamIn.add(dataIn);
+ streamInBufferPush(dataIn, 0, dataIn.length);
+ streamInBufferSize += dataIn.length;
+ if (DEBUG)
+ appendToLog("UsbConnector.waitStreamInOut.Runnable: done streamInBufferPush with streamInRequest as " + streamInRequest);
+ if (streamInRequest == false) {
+ streamInRequest = true;
+ if (DEBUG)
+ appendToLog("UsbConnector.waitStreamInOut.Runnable: going to do runnableProcessStreamInData");
+ mHandler.removeCallbacks(runnableProcessStreamInData);
+ mHandler.post(runnableProcessStreamInData);
+ if (DEBUG)
+ appendToLog("UsbConnector.waitStreamInOut.Runnable: done post[runnableProcessStreamInData]");
+ }
+ }
+ }
+ //Thread.sleep(50);
+ } catch (Exception ex) {
+ appendToLog("UsbConnector.waitStreamInOut.Runnable: Exception as " + ex.toString());
+ }
+ } else if (DEBUG) appendToLog("UsbConnector.waitStreamInOut.Runnable: cannot handle as usbEndpointIn type is " + usbEndpointIn.getType());
+ }
+ }
+ }
+ });
+ thread.start();
+ }
+ }
+
+ void processStreamInData() {
+ appendToLog("UsbConnector.processStreamInData with connectorCallback " + (connectorCallback == null ? "null" : "valid"));
+ if (connectorCallback != null) connectorCallback.callbackMethod();
+ }
+
+ public interface ConnectorCallback {
+ void callbackMethod();
+ }
+ public ConnectorCallback connectorCallback = null;
+
+ private boolean streamInRequest = false;
+ private int intervalProcessBleStreamInData = 100; //50;
+ public int getIntervalProcessBleStreamInData() { return intervalProcessBleStreamInData; }
+ public final Runnable runnableProcessStreamInData = new Runnable() {
+ @Override
+ public void run() {
+ streamInRequest = false;
+ processStreamInData();
+ //appendToLog("UsbConnector: post runnableProcessStreamInData within runnableProcessStreamInData");
+ mHandler.postDelayed(runnableProcessStreamInData, intervalProcessBleStreamInData);
+ }
+ };
+
+ private int streamInBufferSize = 0;
+ public int getStreamInBufferSize() {
+ appendToLog("UsbConnector.getStreamInBufferSize: streamInBufferSize = " + streamInBufferSize);
+ return streamInBufferSize;
+ }
+
+/*
+ private class UsbAsyncTask extends AsyncTask {
+ protected MainActivity ma;
+
+ public UsbAsyncTask() {
+ super();
+ }
+
+ protected String doInBackground(String... strings) {
+ boolean hasData = true;
+ String allData = "";
+ byte[] byteA = new byte[usbEndpointIn.getMaxPacketSize()];
+ try {
+ UsbRequest usbRequest = new UsbRequest();
+ if (!usbRequest.initialize(usbDeviceConnection, usbEndpointIn)) {
+ return "";
+ }
+ while (hasData) {
+ allData = "";
+ hasData = usbDeviceConnection.bulkTransfer(usbEndpointIn, byteA, usbEndpointIn.getMaxPacketSize(), 1000) >= 0;
+ String result = Arrays.toString(byteA);
+ if (!hasData || result.isEmpty()) {
+ hasData = false;
+ if (startedScan) {
+ finishedScan = true;
+ }
+ return "";
+ } else {
+ startedScan = true;
+ byte[] bA = byteA;
+ for (int i = 0; i < bA.length; i++) {
+ allData += (char)bA[i];
+ }
+ lastDataReceived += allData;
+ }
+ }
+ usbRequest.close();
+
+ } catch (Exception e) {
+ finishedScan = false;
+ startedScan = false;
+ lastDataReceived = "";
+ return " Error while reading ";
+ }
+ return allData;
+ }
+
+ protected void onProgressUpdate(Integer... progress) {
+ }
+
+ protected void onPostExecute(String result) {
+ if (startedScan && finishedScan) {
+ mLog.setText(lastDataReceived);
+ lastDataReceived = "";
+ finishedScan = false;
+ startedScan = false;
+ }
+ parseUsb();
+ }
+ }
+*/
+ public void appendToLog(String s) {
+ utility.appendToLog(s);
+ }
+
+ //////////////////////////////////////////////////////////////////////////////////
+
+
+ void makeConnection() {
+ /*
+ usbDeviceConnection = usbManager.openDevice(usbDevice); //Release later: mConnection.close();
+ if (usbDeviceConnection == null) {
+ if (DEBUG) appendToLog("UsbConnector().setDevice(): connection is NULL");
+ } else {
+ usbInterface = usbDevice.getInterface(0);
+ usbDeviceConnection.claimInterface(usbInterface, true); // Release later: mConnection.releaseInterface(mInterface);
+ try {
+ if (UsbConstants.USB_DIR_OUT == usbInterface.getEndpoint(1).getDirection()) {
+ usbEndpoint4Write = usbInterface.getEndpoint(1);
+ }
+ if (UsbConstants.USB_DIR_IN == usbInterface.getEndpoint(0).getDirection()) {
+ usbEndpoint4Read = usbInterface.getEndpoint(0);
+ packetSize = usbEndpoint4Read.getMaxPacketSize() * 50;
+ }
+ mHandler.removeCallbacks(mUsbConnectRunnable);
+ mHandler.post(mUsbConnectRunnable);
+ if (DEBUG) appendToLog("UsbConnector().setDevice(): connection is VALID");
+ } catch (Exception ex) {
+ usbInterface = null; usbEndpoint4Write = null; usbEndpoint4Read = null;
+ if (DEBUG) appendToLog("UsbConnector().setDevice(): Exception = " + ex.toString());
+ }
+ }
+ */
+ }
+
+ private final int STREAM_IN_BUFFER_MAX = 0x4000; //0xC00; //0x800; //0x400;
+ private final int STREAM_IN_BUFFER_LIMIT = 0x3F80; //0xB80; //0x780; //0x380;
+ private byte[] streamInBuffer = new byte[STREAM_IN_BUFFER_MAX];
+ int streamInBufferHead, streamInBufferTail;
+
+ private long streamInDataMilliSecond;
+ public long getStreamInDataMilliSecond() { return streamInDataMilliSecond; }
+ int readSteamIn(byte[] buffer, int byteOffset, int byteCount) {
+ appendToLog("UsbConnector.readSteamIn: starts with byteOffset = " + byteOffset + ", byteCount = " + byteCount + ", streamInBufferSize = " + streamInBufferSize);
+
+ synchronized (streamInBuffer) {
+ if (0 == streamInBufferSize) return 0;
+
+ if (isArrayListStreamInBuffering) {
+ int byteGot = 0;
+ int length1 = arrayListStreamIn.get(0).data.length;
+ appendToLog("UsbConnector.readSteamIn: arrayListStreamIn.size = " + arrayListStreamIn.size() + ", buffer.length = " + buffer.length
+ + ", byteOffset = " + byteOffset + ", length1 = " + length1);
+ if (arrayListStreamIn.size() != 0 && buffer.length - byteOffset > length1) {
+ appendToLog("UsbConnector.readSteamIn: going to arraycopy");
+ System.arraycopy(arrayListStreamIn.get(0).data, 0, buffer, byteOffset, length1);
+ streamInDataMilliSecond = arrayListStreamIn.get(0).milliseconds;
+ arrayListStreamIn.remove(0);
+ byteOffset += length1;
+ byteGot += length1;
+ }
+ byteCount = byteGot;
+ } else {
+ if (byteCount > streamInBufferSize)
+ byteCount = streamInBufferSize;
+ if (byteOffset + byteCount > buffer.length) {
+ byteCount = buffer.length - byteOffset;
+ }
+ if (byteCount <= 0) return 0;
+
+ if (isStreamInBufferRing) {
+ streamInBufferPull(buffer, byteOffset, byteCount);
+ } else {
+ System.arraycopy(streamInBuffer, 0, buffer, byteOffset, byteCount);
+ System.arraycopy(streamInBuffer, byteCount, streamInBuffer, 0, streamInBufferSize - byteCount);
+ }
+ }
+ streamInBufferSize -= byteCount;
+ appendToLog("UsbConnector.readSteamIn: byteCount returned = " + byteCount);
+ return byteCount;
+ }
+ }
+
+ int debugDisplayCounter = 0; int debugDisplayCounter1 = 0;
+ boolean inventoryRunning = false; int inventoryInCounter = 0;
+ int connectCounter = 0; int recCounter = 0;
+ int connectRunInterval = 10; //5; //10;
+ private final Runnable mUsbConnectRunnable = new Runnable() {
+ @Override
+ public void run() {
+ /*
+ boolean readConnectStatus = false;
+// appendToLogS("o ");
+ mHandler.postDelayed(mUsbConnectRunnable, connectRunInterval);
+ if (++connectCounter > 10 && inventoryRunning) { // && inventoryInCounter > 3) {
+ connectCounter = 0;
+ //mTextView.append("a "); //String.format("%d ", r));
+// appendToLogS(String.format("%d + %d", recCounter, streamInBufferSize)); recCounter = 0;
+ }
+ if (usbDeviceConnection == null) {
+ publishProgress("UsbConnector().mUsbConnectRunnable(): mConnection is NULL");
+ } else {
+ final byte[] bytes = new byte[packetSize];
+ int r = 0;
+// do {
+ long timeStart = currentBleConnectTimeMillis();
+ r = usbDeviceConnection.bulkTransfer(usbEndpoint4Read, bytes, packetSize, 1);//5); //10); //150
+ if (r < 0) {
+ if (inventoryRunning) {
+ if (debugDisplayCounter1++ < 5) {
+ publishProgress(String.format("%d>bulktransfer1 duration = %d", currentBleConnectTimeMillis(), currentBleConnectTimeMillis()-timeStart) );
+ }
+ }
+ publishProgress("0"); //UsbConnector().mUsbConnectRunnable(): mConnection.bulkTransfer is ZERO");
+ } else {
+ if (inventoryRunning) {
+ inventoryInCounter++;
+ if (debugDisplayCounter++ < 5) {
+ publishProgress(String.format("%d>bulktransfer duration = %d, length = %d, data(1) = %d", currentBleConnectTimeMillis(), currentBleConnectTimeMillis()-timeStart, r, bytes[1]) );
+ }
+ }
+// publishProgress(String.format("UsbConnector().mUsbConnectRunnable(): mConnection.bulkTransfer lengths %s, content: %s", r, byteArrayToString(bytes)));
+ if (inventoryRunning) { // && inventoryInCounter > 3) {
+ recCounter += r;
+ // mTextView.append(String.format("%d ", r));
+ }
+ if (false) { } else
+ if (streamInBufferSize + r >= streamInBuffer.length) {
+ publishProgress("111");
+// } else if (inventoryRunning) {
+// publishProgress("222");
+ } else if (bytes[0] == 1 && bytes[1] > 0) {
+ {
+ if (isStreamInBufferRing) {
+ streamInBufferPush(bytes, 2, bytes[1]);
+ } else {
+ System.arraycopy(bytes, 2, streamInBuffer, streamInBufferSize, bytes[1]);
+ }
+ streamInBufferSize += bytes[1];
+// byte[] byteDisplay = new byte[streamInBufferSize];
+// System.arraycopy(streamInBuffer, 0, byteDisplay, 0, byteDisplay.length);
+// publishProgress(String.format("\tMessage received of lengths %s, content: %s, streamInBuffer of lengths %s, content: %s", r, byteArrayToString(bytes), byteDisplay.length, byteArrayToString(byteDisplay)));
+// publishProgress(String.format("UsbConnector().mUsbConnectRunnable(): streamInBuffer of lengths %s, content: %s", byteDisplay.length, byteArrayToString(byteDisplay)));
+ }
+ }
+ }
+// } while (r > 0);
+ readConnectStatus = true;
+ }
+ if (readConnectStatus) {
+// mHandler.postDelayed(mUsbConnectRunnable, 5);
+// } else {
+// connectRequested = false;
+ }
+// appendToLogS("p ");
+ */
+ }
+ };
+
+
+
+ void disconnect() {
+ mHandler.removeCallbacks(mUsbConnectRunnable);
+ connectRequested = false;
+/* BluetoothManager mBluetoothManager = (BluetoothManager) mContext.getSystemService(Context.BLUETOOTH_SERVICE);
+ appendToLog("UsbConnector: disconnect(): connection_state=" + mBluetoothAdapter.getState() + ", state2=" + mBluetoothManager.getConnectedDevices(BluetoothProfile.GATT).size() + ", state3=" + mBluetoothManager.getConnectedDevices(BluetoothProfile.GATT_SERVER).size());
+ if (isBleConnected()) {
+ if (mBluetoothAdapter == null) {
+ appendToLog("UsbConnector: disconnect() with NULL mBluetoothAdapter");
+ } else if (!mBluetoothAdapter.isEnabled()) {
+ appendToLog("UsbConnector: disconnect(): DISABLED mBluetoothAdapter");
+ } else if (mBluetoothGatt == null) {
+ appendToLog("UsbConnector: disconnect(): NULL mBluetoothGatt");
+ } else {
+ mBluetoothGatt.disconnect();
+ if (tempDisconnect == false) mBluetoothDevice = null;
+ appendToLog("UsbConnector: disconnect(): done");
+ }
+ }*/
+ }
+
+ int writeCounter = 0;
+ boolean WriteData(byte[] bytes) {
+/* if (writeCounter > 2) {
+ appendToLog("UsbConnector().WriteData()");
+ return true;
+ }
+ if (usbDevice == null || usbDeviceConnection == null || usbInterface == null || usbEndpoint4Write == null || usbManager.hasPermission(usbDevice) == false) {
+ if (DEBUG) appendToLog("UsbConnector().WriteData(): NULL somethings. Cannot writeData");
+ } else {
+// mConnection.claimInterface(mInterface, true); // Lock the usb interface.
+ int r = usbDeviceConnection.bulkTransfer(usbEndpoint4Write, bytes, bytes.length, 250);
+ if (r <= 0) {
+ if (DEBUG) appendToLog("UsbConnector().WriteData(): mConnection.bulkTransfer is ZERO");
+ } else {
+ if (DEBUG) appendToLog("UsbConnector().WriteData(" + writeCounter++ + "): " + String.format("Written %s bytes to the dongle. Data written: %s", r, byteArrayToString(bytes)));
+ }
+// mConnection.releaseInterface(mInterface);
+ if (r > 0) return true;
+ }
+ */
+ return false;
+ }
+
+ String byteArrayToString(byte[] packet) {
+ StringBuilder sb = new StringBuilder(packet.length * 2);
+ for (byte b : packet) {
+ sb.append(String.format("%02X", b));
+ }
+ return sb.toString();
+ }
+
+ String logString = "";
+ String oldPublish = "";
+ void publishProgress(String s) {
+ if (oldPublish.contains(s)) return; oldPublish = s;
+// if (appended == false) return;
+ logString += (", " + s);
+ }
+ boolean appended = false;
+ String ssString = ""; int ssCount = 0; int ssInterval = 10;
+ void appendToLogS(String s) {
+ if (textView != null) {
+ if (logString.length() > 0) textView.append(logString); logString = ""; oldPublish = "";
+ String ss = currentBleConnectTimeMillis() + ">" + s;
+ ssString += (", " + ss);
+// if (++ssCount >= ssInterval) {
+ textView.append(ssString); ssCount = 0; ssString = "";
+ // }
+ appended = true;
+ }
+ }
+
+ /*void appendToLog(String s) {
+ if (textView != null) {
+ if (logString.length() > 0) textView.append(logString); logString = ""; oldPublish = "";
+ textView.append("\n" + currentBleConnectTimeMillis() + ">" + s);
+ appended = true;
+ }
+// Log.v("Hello", "\n" + currentBleConnectTimeMillis() + ">" + s);
+ }*/
+ private long mConnectedTimeMillis;
+ private long currentBleConnectTimeMillis() {
+ return System.currentTimeMillis() - mConnectedTimeMillis;
+ }
+
+ private int totalTemp, totalReceived;
+ private long firstTime, totalTime;
+
+ private class StreamInData {
+ byte[] data;
+ long milliseconds;
+ }
+ private ArrayList arrayListStreamIn = new ArrayList(); private boolean isArrayListStreamInBuffering = true;
+ private boolean isStreamInBufferRing = true;
+ private void streamInBufferPush(byte[] inData, int inDataOffset, int length) {
+ int length1 = streamInBuffer.length - streamInBufferTail;
+ int totalCopy = 0;
+ if (isArrayListStreamInBuffering) {
+ StreamInData streamInData = new StreamInData();
+ streamInData.data = inData;
+ streamInData.milliseconds = System.currentTimeMillis();
+ arrayListStreamIn.add(streamInData);
+ totalCopy = length;
+ } else {
+ if (length > length1) {
+ totalCopy = length1;
+ System.arraycopy(inData, inDataOffset, streamInBuffer, streamInBufferTail, length1);
+ length -= length1;
+ inDataOffset += length1;
+ streamInBufferTail = 0;
+ }
+ if (length != 0) {
+ totalCopy += length;
+ System.arraycopy(inData, inDataOffset, streamInBuffer, streamInBufferTail, length);
+ streamInBufferTail += length;
+ }
+ }
+ if (totalCopy != 0) {
+ totalTemp += totalCopy;
+ long timeDifference = System.currentTimeMillis() - firstTime;
+ if (totalTemp > 17 && timeDifference > 1000) {
+ totalReceived = totalTemp;
+ totalTime = timeDifference;
+ //appendToLog("UsbConnector: BtDataIn: totalReceived = " + totalReceived + ", totalTime = " + totalTime);
+ firstTime = System.currentTimeMillis();
+ totalTemp = 0;
+ }
+ }
+ }
+ private void streamInBufferPull(byte[] buffer, int byteOffset, int length) {
+ synchronized (arrayListStreamIn) {
+ int length1 = streamInBuffer.length - streamInBufferHead;
+ if (length > length1) {
+ System.arraycopy(streamInBuffer, streamInBufferHead, buffer, byteOffset, length1);
+ length -= length1;
+ byteOffset += length1;
+ streamInBufferHead = 0;
+ }
+ if (length != 0) {
+ System.arraycopy(streamInBuffer, streamInBufferHead, buffer, byteOffset, length);
+ streamInBufferHead += length;
+ }}
+ }
+
+
+ long ltimeLogView;
+ void appendToLogView(String s) {
+ if (ltimeLogView == 0) ltimeLogView = System.currentTimeMillis();
+ if (s.trim().length() == 0) textView.setText("");
+ else textView.append(System.currentTimeMillis() - ltimeLogView + ": " + s + "\n" );
+ }
+}
+
+
+
+package com.csl.cslibrary4a;
+
+import android.Manifest;
+import android.content.Context;
+import android.content.pm.PackageManager;
+import android.media.MediaScannerConnection;
+import android.os.Build;
+import android.os.Environment;
+import android.os.Handler;
+import android.os.Looper;
+import android.util.Log;
+import android.widget.TextView;
+
+import org.epctagcoder.exception.EPCParseException;
+import org.epctagcoder.parse.SGTIN.ParseSGTIN;
+import org.epctagcoder.result.SGTIN;
+
+import java.io.BufferedOutputStream;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.OutputStreamWriter;
+import java.io.PrintWriter;
+import java.io.UnsupportedEncodingException;
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import java.util.Locale;
+
+public class Utility {
+ public final boolean DEBUG_SCAN = false;
+ public final boolean DEBUG_CONNECT = true;
+ public final boolean DEBUG_SELECT = false;
+ public final boolean DEBUG_INVCFG = false;
+ public final boolean DEBUG_BTDATA = false;
+ public final boolean DEBUG_FMDATA = false;
+ public final boolean DEBUG_PKDATA = false;
+ public final boolean DEBUG_APDATA = false;
+ public final boolean DEBUG_COMPACT = false;
+ public final boolean ENABLE_USBDATA = false;
+ private Context mContext; private TextView mLogView;
+ public Utility(Context context, TextView mLogView) {
+ mContext = context;
+ this.mLogView = mLogView;
+ }
+ private static long mReferenceTimeMs;
+ public void setReferenceTimeMs() {
+ mReferenceTimeMs = System.currentTimeMillis();
+ }
+ public long getReferencedCurrentTimeMs() { return System.currentTimeMillis() - mReferenceTimeMs; }
+
+ public boolean compareByteArray(byte[] array1, byte[] array2, int length) {
+ int i = 0;
+ if (array1 == null) return false;
+ if (array2 == null) return false;
+ if (array1.length < length || array2.length < length) {
+ return false;
+ }
+ for (; i < length; i++) {
+ if (array1[i] != array2[i]) {
+ break;
+ }
+ }
+ return (i == length);
+ }
+
+ public String byteArray2DisplayString(byte[] byteData) {
+ if (false) appendToLog("String0 = " + byteArrayToString(byteData));
+ String str = "";
+ try {
+ str = new String(byteData, "UTF-8");
+ str = str.replaceAll("[^\\x00-\\x7F]", "");
+ str = str.replaceAll("[\\p{Cntrl}&&[^\r\n\t]]", "");
+ } catch (UnsupportedEncodingException e) {
+ e.printStackTrace();
+ }
+ if (false) appendToLog("String1 = " + str);
+ return str;
+ }
+ public String byteArrayToString(byte[] packet) {
+ if (packet == null) return "";
+ StringBuilder sb = new StringBuilder(packet.length * 2);
+ for (byte b : packet) {
+ sb.append(String.format("%02X", b));
+ }
+ return sb.toString();
+ }
+
+ public byte[] stringToByteArray(String string) {
+ byte[] bytes = new byte[string.length()/2];
+ if (string == null) string = "";
+ String hexString = "0123456789ABCDEF";
+ for (int j = 0; j < string.length(); j++) {
+ String subString = string.substring(j, j + 1).toUpperCase();
+ int k = 0;
+ for (; k < 16; k++) {
+ if (subString.matches(hexString.substring(k, k + 1))) {
+ break;
+ }
+ }
+ if (k == 16) break;
+ if ((j / 2) * 2 == j) {
+ bytes[j / 2] |= (byte) (k << 4);
+ } else {
+ bytes[j / 2] |= (byte) (k);
+ }
+ }
+ return bytes;
+ }
+ public byte[] string2ByteArray(String string) {
+ byte[] bytes = null;
+ if (string == null) return null;
+ if ((string.length()/2)*2 != string.length()) string += "0";
+ for (int i = 0; i < string.length(); i+=2) {
+ try {
+ Short sValue = Short.parseShort(string.substring(i, i + 2), 16);
+ byte[] bytesNew = new byte[1];
+ if (bytes != null) {
+ bytesNew = new byte[bytes.length + 1];
+ System.arraycopy(bytes, 0, bytesNew, 0, bytes.length);
+ }
+ bytesNew[bytesNew.length - 1] = (byte) (sValue & 0xFF);
+ bytes = bytesNew;
+ } catch (Exception ex) {
+ appendToLog("Exception in i = " + i + ", substring = " + string.substring(i, i+2));
+ break;
+ }
+ }
+ return bytes;
+ }
+ public int byteArrayToInt(byte[] bytes) {
+ int iValue = 0;
+ int length = bytes.length;
+ if (bytes.length > 4) length = 4;
+ for (int i = 0; i < length; i++) {
+ iValue = (iValue << 8) + (bytes[i] & 0xFF);
+ }
+ return iValue;
+ }
+
+ private static Handler mHandler = new Handler();
+ public void appendToLogRunnable(final String s) {
+ mHandler.post(new Runnable() {
+ @Override
+ public void run() {
+ appendToLog(s);
+ }
+ });
+ }
+ public String appendToLog(String s) {
+ String TAG = "";
+ StackTraceElement[] stacktrace = Thread.currentThread().getStackTrace();
+ boolean foundMe = false;
+ for(int i=0; i= Build.VERSION_CODES.M) {
+ if (mContext.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
+ writeExtPermission = false;
+ //appendToLog("requestPermissions WRITE_EXTERNAL_STORAGE 1");
+ //requestPermissions((Activity) mContext, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
+ //if (false) Toast.makeText(mContext, R.string.toast_permission_not_granted, Toast.LENGTH_SHORT).show();
+ //return;
+ }
+ }
+ String errorDisplay = null;
+ if (writeExtPermission == false) {
+ errorDisplay = "denied WRITE_EXTERNAL_STORAGE Permission !!!";
+ } else if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) == false) errorDisplay = "Error in mouting external storage !!!";
+ else {
+ File path = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + Environment.DIRECTORY_DOWNLOADS + "/cs108Java");
+ if (path.exists() == false) path.mkdirs();
+ if (path.exists() == false) errorDisplay = "Error in making directory !!!";
+ else {
+ String dateTime = new SimpleDateFormat("yyMMdd_HHmmss").format(new Date());
+ String fileName = "cs108JavaDebug_" + dateTime + ".txt";
+ fileDebug = new File(path, fileName);
+ if (fileDebug == null) errorDisplay = "Error in making directory !!!";
+ }
+ }
+ if (errorDisplay != null) appendToLog("Error in saving file with " + errorDisplay);
+ }
+ public void debugFileClose() {
+ if (fileDebug != null) {
+ try {
+ MediaScannerConnection.scanFile(mContext, new String[]{fileDebug.getAbsolutePath()}, null, null);
+ } catch (Exception ex) {
+ }
+ }
+ }
+ public void debugFileEnable(boolean enable) { enableFileDebug = enable; }
+ public void writeDebug2File(String stringDebug) {
+ if (fileDebug != null && enableFileDebug) {
+ SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy hh:mm.mmm", Locale.getDefault());
+ stringDebug = sdf.format(System.currentTimeMillis()) + ": " + stringDebug;
+ try {
+ FileOutputStream outputStreamDebug = new FileOutputStream(fileDebug, true);
+ PrintWriter printWriterDebug = new PrintWriter(new OutputStreamWriter(new BufferedOutputStream(outputStreamDebug), "UTF-8"));
+ if (false) appendToLog(stringDebug);
+ printWriterDebug.println(stringDebug);
+ printWriterDebug.flush(); printWriterDebug.close();
+ outputStreamDebug.close();
+ } catch (Exception ex) {
+ }
+ }
+ }
+
+ public String getlast3digitVersion(String str) {
+ if (str != null) {
+ int len = str.length();
+ if (len > 3) {
+ String strOut = "";
+ if (str.substring(len-3, len-2).matches("0")) strOut = str.substring(len-2, len-1);
+ else strOut = str.substring(len-3, len-1);
+ strOut += "." + str.substring(len-1, len);
+ return strOut;
+ }
+ }
+ return null;
+ }
+
+ public String getCombinedVersion(String string0) {
+ String string1 = BuildConfig.VERSION_NAME;
+ int iValue1 = Integer.parseInt(string1);
+ appendToLog("string1 = " + string1 + ", iValue1 = " + iValue1);
+ int iPos0 = string0.indexOf(".");
+ int iPos1 = string0.substring(iPos0 + 1).indexOf(".");
+ int iValue0 = Integer.parseInt(string0.substring(iPos0 + iPos1 + 2));
+ appendToLog("stringVersion = " + string0 + ", iPos0 = " + iPos0 + ", iPos1 = " + iPos1 + ", iValue0 = " + iValue0);
+ iValue0 += iValue1;
+ return string0.substring(0, iPos0 + iPos1 + 2) + String.valueOf(iValue0);
+ }
+
+ public boolean isVersionGreaterEqual(String version, int majorVersion, int minorVersion, int buildVersion) {
+ if (version == null) return false;
+ if (version.length() == 0) return false;
+ String[] versionPart = version.split("[ .,-]+");
+
+ if (versionPart == null) return false;
+ try {
+ int value = Integer.valueOf(versionPart[0]);
+ if (value < majorVersion) return false;
+ if (value > majorVersion) return true;
+
+ if (versionPart.length < 2) return true;
+ value = Integer.valueOf(versionPart[1]);
+ if (value < minorVersion) return false;
+ if (value > minorVersion) return true;
+
+ if (versionPart.length < 3) return true;
+ value = Integer.valueOf(versionPart[2]);
+ if (value < buildVersion) return false;
+ return true;
+ } catch (Exception ex) {
+ return false;
+ }
+ }
+
+ public double get2BytesOfRssi(byte[] bytes, int index) {
+ int iValue = (bytes[index] & 0xFF) * 256 + (bytes[index + 1] & 0xFF);
+ if ((iValue & 0x8000) != 0) iValue ^= ~0xFFFF;
+ double dValue = iValue;
+ return dValue/100;
+ }
+
+ float fTemperature_old = -500;
+ public float decodeCtesiusTemperature(String strActData, String strCalData) {
+ float fTemperature = -500; boolean invalid = false;
+ appendToLog("Hello9: strActData = " + strActData + ", strCalData = " + strCalData);
+ if (strActData.length() != 8 || strCalData.length() != 8) {
+ if (strActData.length() != 8) appendToLogView("Warning: Invalid length of sensing data = " + strActData);
+ else appendToLogView("Warning: Invalid length of calibration data = " + strCalData);
+ invalid = true;
+ }
+ else if ((strActData.substring(0, 1).matches("F") && strActData.substring(4, 5).matches("F")) == false) {
+ appendToLogView("Warning: Not F header of sensing data = " + strActData);
+ invalid = true;
+ }
+ else {
+ String strTemp = strActData.substring(4,8);
+ int iTemp = Integer.parseInt(strTemp, 16);
+ int iChecksum = 0;
+ for (int i=0; i<5; i++, iTemp >>= 3) {
+ iChecksum ^= (iTemp & 0x7);
+ }
+ if (iChecksum != 0) {
+ appendToLogView("Warning: Invalid checksum(" + String.valueOf(iChecksum) + ") for strActData = " + strActData);
+ invalid = true;
+ }
+ }
+ if (true || invalid == false) {
+ int iDelta1 = Integer.parseInt(strCalData.substring(0,4), 16);
+ if ((iDelta1 & 0x8000) != 0) { iDelta1 ^= 0xFFFF; iDelta1++; iDelta1 *= -1; }
+ appendToLog(String.format("iDelta1 = %d", iDelta1));
+ int iVersion = Integer.parseInt(strCalData.substring(4,5), 16);
+ appendToLog("Hello9: " + String.format("iDelta1 = %X, iVersion = %X", iDelta1, iVersion));
+ float fDelta2 = ((float) iDelta1) / 100 - 101;
+ String strTemp = strActData.substring(1,4) + strActData.substring(5,8);
+ int iTemp = Integer.parseInt(strTemp, 16);
+ int iD1 = ((iTemp & 0xF80000) >> 19);
+ int iD2 = ((iTemp & 0x7FFF8) >> 3);
+ if (iVersion == 0 || iVersion == 1) fTemperature = (float) (11984.47 / (21.25 + iD1 + iD2 / 2752 + fDelta2) - 301.57);
+ else if (iVersion == 2) {
+ fTemperature = (float) (11109.6 / (24 + (iD2 + iDelta1)/375.3) - 290);
+ if (fTemperature >= 125) fTemperature = (float) (fTemperature * 1.2 - 25);
+ } else appendToLogView("Warning: Invalid version " + String.valueOf(iVersion));
+ if (invalid) appendToLogView(String.format("Temperature = %f", fTemperature));
+ }
+ if (fTemperature != -1) fTemperature_old = fTemperature;
+ return fTemperature;
+ }
+ public float decodeMicronTemperature(int iTag35, String strActData, String strCalData) {
+ float fTemperature = -1;
+ if (strActData == null || strCalData == null) {
+ } else if (strActData.length() != 4 || strCalData.length() != 16) {
+ } else if (strActData.matches("0000")) {
+ fTemperature = fTemperature_old;
+ } else if (iTag35 == 3) {
+ int calCode1, calTemp1, calCode2, calTemp2;
+ int crc = Integer.parseInt(strCalData.substring(0, 4), 16);
+ calCode1 = Integer.parseInt(strCalData.substring(4, 7), 16);
+ calTemp1 = Integer.parseInt(strCalData.substring(7, 10), 16);
+ calTemp1 >>= 1;
+ calCode2 = Integer.parseInt(strCalData.substring(9, 13), 16);
+ calCode2 >>= 1;
+ calCode2 &= 0xFFF;
+ calTemp2 = Integer.parseInt(strCalData.substring(12, 16), 16);
+ calTemp2 >>= 2;
+ calTemp2 &= 0x7FF;
+
+ fTemperature = Integer.parseInt(strActData, 16);
+ fTemperature = ((float) calTemp2 - (float) calTemp1) * (fTemperature - (float) calCode1);
+ fTemperature /= ((float) (calCode2) - (float) calCode1);
+ fTemperature += (float) calTemp1;
+ fTemperature -= 800;
+ fTemperature /= 10;
+ } else if (iTag35 == 5) {
+ int iTemp;
+ float calCode2 = Integer.parseInt(strCalData.substring(0, 4), 16); calCode2 /= 16;
+ iTemp = Integer.parseInt(strCalData.substring(4, 8), 16); iTemp &= 0x7FF; float calTemp2 = iTemp; calTemp2 -= 600; calTemp2 /= 10;
+ float calCode1 = Integer.parseInt(strCalData.substring(8, 12), 16); calCode1 /= 16;
+ iTemp = Integer.parseInt(strCalData.substring(12, 16), 16); iTemp &= 0x7FF; float calTemp1 = iTemp; calTemp1 -= 600; calTemp1 /= 10;
+
+ fTemperature = Integer.parseInt(strActData, 16);
+ fTemperature -= calCode1;
+ fTemperature *= (calTemp2 - calTemp1);
+ fTemperature /= (calCode2 - calCode1);
+ fTemperature += calTemp1;
+ }
+ if (fTemperature != -1) fTemperature_old = fTemperature;
+ return fTemperature;
+ }
+ public float decodeAsygnTemperature(String string) {
+ String stringUser5 = string.substring(20, 24); int iUser5 = Integer.valueOf(stringUser5, 16);
+ String stringUser6 = string.substring(24, 28); int iUser6 = Integer.valueOf(stringUser6, 16);
+ String stringUser1 = string.substring(4, 8); int iUser1 = Integer.valueOf(stringUser1, 16);
+ switch (iUser1 & 0xC000) {
+ case 0xc000:
+ iUser1 &= 0x1FFF; iUser1 /= 8;
+ break;
+ case 0x8000:
+ iUser1 &= 0xFFF; iUser1 /= 4;
+ break;
+ case 0x4000:
+ iUser1 &= 0x7FF; iUser1 /= 2;
+ break;
+ default:
+ iUser1 &= 0x3FF;
+ break;
+ }
+ float temperature = -1;
+ appendToLog("input string " + string + ", user1 = " + stringUser1 + ", user5 = " + stringUser5 + ", user6 = " + stringUser6);
+ //iUser1 = 495; iUser6 = 3811;
+ appendToLog("iUser1 = " + iUser1 + ", iUser5 = " + iUser5 + ", iUser6 = " + iUser6);
+ if (iUser5 == 3000) {
+ float calibOffset = (float) 3860.27 - (float) iUser6;
+ appendToLog("calibOffset = " + calibOffset);
+ float acqTempCorrected = (float) iUser1 + calibOffset / 8;
+ appendToLog("acqTempCorrected = " + acqTempCorrected);
+ temperature = (float) 0.3378 * acqTempCorrected - (float) 133;
+ appendToLog("temperature = " + temperature);
+ } else if (iUser5 == 1835) {
+ float expAcqTemp = (float) 398.54 - (float) iUser5 / (float) 100;
+ appendToLog("expAcqTemp = " + expAcqTemp);
+ expAcqTemp /= (float) 0.669162;
+ appendToLog("expAcqTemp = " + expAcqTemp);
+ float calibOffset = ((float) 8 * expAcqTemp) - (float) iUser6;
+ float acqTempCorrected = (float) iUser1 + calibOffset;
+ acqTempCorrected /= 8;
+ temperature = (float) -0.669162 * acqTempCorrected;
+ temperature += 398.54;
+ appendToLog("expAcqTemp = " + expAcqTemp + ". calibOffset = " + calibOffset + ", acqTempCorrected = " + acqTempCorrected + ", temperature = " + temperature);
+ }
+ return temperature;
+ } //4278
+ public float temperatureC2F(float fTemp) {
+ return (float) (32 + fTemp * 1.8);
+ }
+ public String temperatureC2F(String strValue) {
+ try {
+ float fValue = Float.parseFloat(strValue);
+
+ fValue = temperatureC2F(fValue);
+ return String.format("%.1f", fValue);
+ } catch (Exception ex) { }
+ return "";
+ }
+ float temperatureF2C(float fTemp) {
+ return (float) ((fTemp - 32) * 0.5556);
+ }
+ public String temperatureF2C(String strValue) {
+ try {
+ float fValue = Float.parseFloat(strValue);
+
+ fValue = temperatureF2C(fValue);
+ return String.format("%.1f", fValue);
+ } catch (Exception ex) { }
+ return "";
+ }
+
+ public enum EpcClass {
+ SGTIN, SSCC, SGLN, GRAI, GIAI, GSRN, GSRNP, GDTI, CPI, SGCN
+ }
+ public String getEpc4upcSerial(EpcClass epcClass, String filter, String companyPrefix, String itemReference, String serialNumber) {
+ String strValue = null;
+ ParseSGTIN parseSGTIN = null;
+ String strURI = "urn:epc:tag:";
+ appendToLog("epcClass is " + epcClass.toString());
+ switch (epcClass) {
+ default:
+ strURI += "sgtin-96:";
+ break;
+ }
+ strURI += (filter + "." + companyPrefix + "." + itemReference + "." + serialNumber);
+ try {
+ parseSGTIN = ParseSGTIN.Builder()
+ .withEPCTagURI( strURI).build();
+ SGTIN sgtin = parseSGTIN.getSGTIN();
+ strValue = sgtin.getRfidTag();
+ } catch (EPCParseException e) {
+ //throw new RuntimeException(e);
+ }
+ return strValue;
+ }
+
+ public String getUpcSerial(String strEpc) {
+ ParseSGTIN parseSGTIN = null;
+ String strValue = null;
+ try {
+ parseSGTIN = ParseSGTIN.Builder()
+ .withRFIDTag(strEpc)
+ .build();
+ SGTIN sgtin = parseSGTIN.getSGTIN();
+ //strValue = sgtin.toString();
+ //strValue = sgtin.getEpcRawURI();
+ strValue = sgtin.getEpcTagURI();
+ String strHeader = "urn:epc:tag:";
+ if (strValue.indexOf(strHeader) == 0) strValue = strValue.substring(strHeader.length());
+ } catch (Exception e) {
+ appendToLog("parseSSCC exception: " + e.getMessage());
+ //throw new RuntimeException(e);
+ }
+ return strValue;
+ }
+ public String getUpcSerialDetail(String strUpcSerial) {
+ String strValue = null, strTmp, strCmp;
+ strCmp = ":"; strTmp = strUpcSerial.substring(0, strUpcSerial.indexOf(strCmp));
+ if (strTmp != null) {
+ if (strValue != null) strValue += "\n";
+ strValue = "Epc Class: " + strTmp;
+ strUpcSerial = strUpcSerial.substring(strUpcSerial.indexOf(strCmp) + 1);
+ }
+ strCmp = "."; strTmp = strUpcSerial.substring(0, strUpcSerial.indexOf(strCmp));
+ if (strTmp != null) {
+ if (strValue != null) strValue += "\n";
+ strValue += "Filter: " + strTmp;
+ strUpcSerial = strUpcSerial.substring(strUpcSerial.indexOf(strCmp) + 1);
+ }
+ strCmp = "."; strTmp = strUpcSerial.substring(0, strUpcSerial.indexOf(strCmp));
+ if (strTmp != null) {
+ if (strValue != null) strValue += "\n";
+ strValue += "Company Prefix: " + strTmp;
+ strUpcSerial = strUpcSerial.substring(strUpcSerial.indexOf(strCmp) + 1);
+ }
+ strCmp = "."; strTmp = strUpcSerial.substring(0, strUpcSerial.indexOf(strCmp));
+ if (strTmp != null) {
+ if (strValue != null) strValue += "\n";
+ strValue += "Item Reference: " + strTmp;
+ strUpcSerial = strUpcSerial.substring(strUpcSerial.indexOf(strCmp) + 1);
+ }
+ strTmp = strUpcSerial;
+ if (strTmp != null) {
+ if (strValue != null) strValue += ("\n");
+ strValue += "Serial Number: " + strTmp;
+ }
+ return strValue;
+ }
+
+ public boolean checkHostProcessorVersion(String version, int majorVersion, int minorVersion, int buildVersion) {
+ boolean DEBUG = false;
+ if (DEBUG) appendToLog("version = " + version + ", majorVersion = " + majorVersion + ", minorVersion = " + minorVersion + ", buildVersion = " + buildVersion);
+ if (version == null) { if (DEBUG) appendToLog("return false 1"); return false; }
+ if (version.length() == 0) { if (DEBUG) appendToLog("return false 2"); return false; }
+ String[] versionPart = version.split(" |\\.");
+
+ if (versionPart == null) { if (DEBUG) appendToLog("return false 3"); return false; }
+ try {
+ if (DEBUG) appendToLog("checkpoint 1");
+ int value = Integer.valueOf(versionPart[0]);
+ if (value < majorVersion) { if (DEBUG) appendToLog("return false 4"); return false; }
+ if (value > majorVersion) return true;
+
+ if (DEBUG) appendToLog("checkpoint 2");
+ if (versionPart.length < 2) return true;
+ value = Integer.valueOf(versionPart[1]);
+ if (value < minorVersion) { if (DEBUG) appendToLog("return false 5"); return false; }
+ if (value > minorVersion) return true;
+
+ if (DEBUG) appendToLog("checkpoint 3");
+ if (versionPart.length < 3) return true;
+ value = Integer.valueOf(versionPart[2]);
+ if (value < buildVersion) { if (DEBUG) appendToLog("return false 6"); return false; }
+ return true;
+ } catch (Exception ex) {
+ if (DEBUG) appendToLog("return false 7"); return false;
+ }
+ }
+
+ public float float16toFloat32(String strData) {
+ float fValue = -1;
+ if (strData.length() == 4) {
+ int iValue = Integer.parseInt(strData, 16);
+ int iSign = iValue & 0x8000; if (iSign != 0) iSign = 1;
+ int iExp = (iValue & 0x7C00) >> 10;
+ int iMant = (iValue & 0x3FF);
+ if (iExp == 15) {
+ if (iSign == 0) fValue = Float.POSITIVE_INFINITY;
+ else fValue = Float.NEGATIVE_INFINITY;
+ } else if (iExp == 0) {
+ fValue = (iMant / 1024) * 2^(-14);
+ if (iSign != 0) fValue *= -1;
+ } else {
+ fValue = (float) Math.pow(2, iExp - 15);
+ fValue *= (1 + ((float)iMant / 1024));
+ if (iSign != 0) fValue *= -1;
+ }
+ if (true) appendToLog("strData = " + strData + ", iValue = " + iValue + ", iSign = " + iSign + ", iExp = " + iExp + ", iMant = " + iMant + ", fValue = " + fValue);
+ }
+ return fValue;
+ }
+ public String strFloat16toFloat32(String strData) {
+ String strValue = null;
+ float fTemperature = float16toFloat32(strData);
+ if (fTemperature > -400) return String.format("%.1f", fTemperature);
+ return strValue;
+ }
+ public String str2float16(String strData) {
+ String strValue = "";
+ float fValue0 = (float) Math.pow(2, -14);
+ float fValueMax = 2 * (float) Math.pow(2, 30);
+ float fValue = Float.parseFloat(strData);
+ float fValuePos = (fValue > 0) ? fValue : -fValue;
+ boolean bSign = false; if (fValue < 0) bSign = true;
+ int iExp, iMant;
+ if (fValuePos < fValueMax) {
+ if (fValuePos < fValue0) {
+ iExp = 0;
+ iMant = (int)((fValuePos / fValue0) * 1024);
+ } else {
+ for (iExp = 1; iExp < 31; iExp++) {
+ if (fValuePos < 2 * (float) Math.pow(2, iExp - 15)) break;
+ }
+ fValuePos /= ((float) Math.pow(2, iExp - 15));
+ fValuePos -= 1;
+ fValuePos *= 1024;
+ iMant = (int) fValuePos;
+ }
+ int iValue = (bSign ? 0x8000 : 0) + (iExp << 10) + iMant;
+ strValue = String.format("%04X", iValue);
+ if (true) appendToLog("bSign = " + bSign + ", iExp = " + iExp + ", iMant = " + iMant + ", iValue = " + iValue + ", strValue = " + strValue);
+ }
+ return strValue;
+ }
+}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ #FFBB86FC
+ #FF6200EE
+ #FF3700B3
+ #FF03DAC5
+ #FF018786
+ #FF000000
+ #FFFFFFFF
+
+
+
+
+
+ cslibrary4a
+
+
+ - 0: Multipath Interference Resistance
+ - 1: Range/Dense reader
+ - 2: Range/Throughput/Dense reader
+ - 3: Maximum throughput
+
+
+ - 11: Miller 1 640kHz Tari 7.5us
+ - 1: Miller 2 640kHz Tari 7.5us
+ - 15: Miller 4 640kHz Tari 7.5us
+ - 12: Miller 2 320kHz Tari 15us
+ - 3: Miller 2 320kHz Tari 20us
+ - 5: Miller 4 320kHz Tari 20us
+ - 7: Miller 4 250kHz Tari 20us
+ - 13: Miller 8 160kHz Tari 20us
+
+
+ - 103: Miller 1 640kHz Tari 6.25us
+ - 11: Miller 1 640kHz Tari 7.5us
+ - 302: Miller 1 640kHz Tari 7.5us
+ - 120: Miller 2 640kHz Tari 6.25us
+ - 1: Miller 2 640kHz Tari 7.5us
+ - 323: Miller 2 640kHz Tari 7.5us
+ - 15: Miller 4 640kHz Tari 7.5us
+ - 344: Miller 4 640kHz Tari 7.5us
+ - 345: Miller 4 640kHz Tari 7.5us
+ - 12: Miller 2 320kHz Tari 15us
+ - 223: Miller 2 320kHz Tari 15us
+ - 3: Miller 2 320kHz Tari 20us
+ - 222: Miller 2 320kHz Tari 20us
+ - 5: Miller 4 320kHz Tari 20us
+ - 241: Miller 4 320kHz Tari 20us
+ - 7: Miller 4 250kHz Tari 20us
+ - 244: Miller 4 250kHz Tari 20us
+ - 13: Miller 8 160kHz Tari 20us
+ - 285: Miller 8 160kHz Tari 20us
+
+
+ - 103: Miller 1 640kHz Tari 6.25us
+ - 302: Miller 1 640kHz Tari 7.5us
+ - 120: Miller 2 640kHz Tari 6.25us
+ - 323: Miller 2 640kHz Tari 7.5us
+ - 344: Miller 4 640kHz Tari 7.5us
+ - 345: Miller 4 640kHz Tari 7.5us
+ - 223: Miller 2 320kHz Tari 15us
+ - 222: Miller 2 320kHz Tari 20us
+ - 241: Miller 4 320kHz Tari 20us
+ - 244: Miller 4 250kHz Tari 20us
+ - 285: Miller 8 160kHz Tari 20us
+
+
+ - 103: FCC, FM0 640kHz 6.25us
+ - 302: ETSIUB, FM0 640kHz 7.5us
+ - 120: FCC, Miller 2 640kHz 6.25us
+ - 104: FCC, FM0 320kHz 6.25us
+ - 323: ETSIUB, Miller 2 640kHz 7.5us
+ - 4323: ETISUB, Miller 2 640kHz 7.5us Gen2X
+ - 203: Japan, FM0 426kHz 12.5us
+ - 202: ETSILB, FM0 426kHz 15us
+ - 226: Japan, Miller 2 426kHz 12.5us
+ - 344: ETSIUB, Miller 4 640kHz 7.5us
+ - 345: FCC ETSIUB, Miller 4 640kHz 7.5us
+ - 4345: FCC ETSIUB, Miller 4 640kHz 7.5us Gen2X
+ - 225: ETSILB, Miller 2 426kHz 15us
+ - 326: Japan, Miller 2 320kHz 12.5us
+ - 325: ETSILB, Miller 2 320kHz 15us
+ - 324: ETSILB, Miller 2 320kHz 20us
+ - 4324: ETSILB, Miller 2 320kHz 20us Gen2X
+ - 342: ETSILB, Miller 4 320kHz 20us
+ - 4342: ETSILB, Miller 4 320kHz 20us Gen2X
+ - 343: FCC, Miller 4 250kHz 20us
+ - 4343: FCC, Miller 4 250kHz 20us Gen2X
+ - 205: Japan, FM0 50kHz 20us
+ - 382: All, Miller 8 160kHz 20us
+ - 4382: All, Miller 8 160kHz 20us Gen2X
+
+
+ "Permissions are not granted. Please allow them in system setting."
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+package org.epctagcoder.exception;
+
+public class EPCParseException extends Exception {
+
+ public EPCParseException(String message) {
+ super(message);
+ }
+
+
+}
+
+
+
+package org.epctagcoder.option.CPI;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+public enum CPIFilterValue {
+ ALL_OTHERS_0(0),
+ RESERVED_1(1),
+ RESERVED_2(2),
+ RESERVED_3(3),
+ RESERVED_4(4),
+ RESERVED_5(5),
+ RESERVED_6(6),
+ RESERVED_7(7);
+
+ private int value;
+
+ private CPIFilterValue(int value) {
+ this.value = value;
+ }
+
+ public int getValue() {
+ return value;
+ }
+
+ private static final Map BY_CODE_MAP = new LinkedHashMap<>();
+ static {
+ for (CPIFilterValue rae : CPIFilterValue.values()) {
+ BY_CODE_MAP.put(rae.value, rae);
+ }
+ }
+
+ public static CPIFilterValue forCode(int code) {
+ return BY_CODE_MAP.get(code);
+ }
+
+
+}
+
+
+
+package org.epctagcoder.option.CPI;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+
+
+public enum CPIHeader {
+ HEADER_00111100("00111100") {
+ public Integer getTagSize() {
+ return 96;
+ }
+ },
+ HEADER_00111101("00111101") {
+ public Integer getTagSize() {
+ return 0; //null; // variable
+ }
+ };
+
+ private String value;
+ public abstract Integer getTagSize();
+
+
+ private CPIHeader(String value) {
+ this.value = value;
+ }
+
+ public String getValue() {
+ return value;
+ }
+
+ private static final Map BY_CODE_MAP = new LinkedHashMap<>();
+ static {
+ for (CPIHeader rae : CPIHeader.values()) {
+ BY_CODE_MAP.put(rae.value, rae);
+ }
+ }
+
+ public static CPIHeader forCode(String code) {
+ CPIHeader header = BY_CODE_MAP.get(code);
+
+ if (header==null) {
+ throw new IllegalArgumentException(String.format("CPI header [%s] is invalid. Allowed only 00111100 or 00111101", code));
+ }
+
+ return header;
+ }
+
+
+}
+
+
+
+package org.epctagcoder.option.CPI;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+public enum CPITagSize {
+ BITS_96(96) {
+ public Integer getHeader() {
+ return 60;
+ }
+ public Integer getSerialBitCount() {
+ return 31;
+ }
+ public Integer getSerialMaxLenght() {
+ return 0;
+ }
+ public Long getSerialMaxValue() {
+ return 2_147_483_647L;
+ }
+ },
+ BITS_VARIABLE(0) {
+ public Integer getHeader() {
+ return 61;
+ }
+ public Integer getSerialBitCount() {
+ return 40;
+ }
+ public Integer getSerialMaxLenght() {
+ return 12;
+ }
+ public Long getSerialMaxValue() {
+ return null; // not used
+ }
+ };
+
+ private int value;
+ public abstract Integer getHeader();
+ public abstract Integer getSerialBitCount();
+ public abstract Integer getSerialMaxLenght();
+ public abstract Long getSerialMaxValue();
+
+ private CPITagSize(int value) {
+ this.value = value;
+ }
+
+ public int getValue() {
+ return value;
+ }
+
+ private static final Map BY_CODE_MAP = new LinkedHashMap<>();
+ static {
+ for (CPITagSize rae : CPITagSize.values()) {
+ BY_CODE_MAP.put(rae.value, rae);
+ }
+ }
+
+ public static CPITagSize forCode(int code) {
+ return BY_CODE_MAP.get(code);
+ }
+
+
+}
+
+
+
+package org.epctagcoder.option.CPI.partitionTable;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.epctagcoder.option.TableItem;
+import org.epctagcoder.option.CPI.CPITagSize;
+
+
+public class CPIPartitionTableList {
+ static final private List list = new ArrayList();
+
+
+
+ public CPIPartitionTableList(CPITagSize tagSize) {
+ if ( tagSize.getValue()==96 ) {
+ list.clear();
+ list.add( new TableItem(0, 40, 12, 11, 3) );
+ list.add( new TableItem(1, 37, 11, 14, 4) );
+ list.add( new TableItem(2, 34, 10, 17, 5) );
+ list.add( new TableItem(3, 30, 9, 21, 6) );
+ list.add( new TableItem(4, 27, 8, 24, 7) );
+ list.add( new TableItem(5, 24, 7, 27, 8) );
+ list.add( new TableItem(6, 20, 6, 31, 9) );
+ } else { //if ( tagSize.getValue()==202 ) { // variable
+ list.clear();
+ list.add( new TableItem(0, 40, 12, 114, 18) );
+ list.add( new TableItem(1, 37, 11, 120, 19) );
+ list.add( new TableItem(2, 34, 10, 126, 20) );
+ list.add( new TableItem(3, 30, 9, 132, 21) );
+ list.add( new TableItem(4, 27, 8, 138, 22) );
+ list.add( new TableItem(5, 24, 7, 144, 23) );
+ list.add( new TableItem(6, 20, 6, 150, 24) );
+ }
+ }
+
+
+ public TableItem getPartitionByL(Integer index) {
+ TableItem tableItem = null;
+ for (TableItem item : list) {
+ if (item.getL()==index) {
+ tableItem = item;
+ break;
+ }
+ }
+ return tableItem;
+ }
+
+ public TableItem getPartitionByValue(Integer index) {
+ TableItem tableItem = null;
+ for (TableItem item : list) {
+ if (item.getPartitionValue()==index) {
+ tableItem = item;
+ break;
+ }
+ }
+ return tableItem;
+ }
+
+
+}
+
+
+
+package org.epctagcoder.option.GDTI;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+public enum GDTIFilterValue {
+ ALL_OTHERS_0(0),
+ RESERVED_1(1),
+ RESERVED_2(2),
+ RESERVED_3(3),
+ RESERVED_4(4),
+ RESERVED_5(5),
+ RESERVED_6(6),
+ RESERVED_7(7);
+
+ private int value;
+
+ private GDTIFilterValue(int value) {
+ this.value = value;
+ }
+
+ public int getValue() {
+ return value;
+ }
+
+ private static final Map BY_CODE_MAP = new LinkedHashMap<>();
+ static {
+ for (GDTIFilterValue rae : GDTIFilterValue.values()) {
+ BY_CODE_MAP.put(rae.value, rae);
+ }
+ }
+
+ public static GDTIFilterValue forCode(int code) {
+ return BY_CODE_MAP.get(code);
+ }
+
+
+}
+
+
+
+package org.epctagcoder.option.GDTI;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+
+public enum GDTIHeader {
+ HEADER_00101100("00101100") {
+ public Integer getTagSize() {
+ return 96;
+ }
+ },
+ HEADER_00111110("00111110") {
+ public Integer getTagSize() {
+ return 174;
+ }
+ };
+
+ private String value;
+ public abstract Integer getTagSize();
+
+
+ private GDTIHeader(String value) {
+ this.value = value;
+ }
+
+ public String getValue() {
+ return value;
+ }
+
+ private static final Map BY_CODE_MAP = new LinkedHashMap<>();
+ static {
+ for (GDTIHeader rae : GDTIHeader.values()) {
+ BY_CODE_MAP.put(rae.value, rae);
+ }
+ }
+
+ public static GDTIHeader forCode(String code) {
+ GDTIHeader header = BY_CODE_MAP.get(code);
+
+ if (header==null) {
+ throw new IllegalArgumentException(String.format("GDTI header [%s] is invalid. Allowed only 00101100 or 00111110", code));
+ }
+
+ return header;
+ }
+
+
+}
+
+
+
+package org.epctagcoder.option.GDTI;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+public enum GDTITagSize {
+ BITS_96(96) {
+ public Integer getHeader() {
+ return 44;
+ }
+ public Integer getSerialBitCount() {
+ return 41;
+ }
+ public Integer getSerialMaxLenght() {
+ return 13;
+ }
+ public Long getSerialMaxValue() { // confirmar isso
+ return 2_199_023_255_551L;
+
+ }
+ },
+ BITS_174(174) {
+ public Integer getHeader() {
+ return 62;
+ }
+ public Integer getSerialBitCount() {
+ return 119;
+ }
+ public Integer getSerialMaxLenght() {
+ return 17;
+ }
+ public Long getSerialMaxValue() {
+ return null; // not used
+ }
+ };
+
+ private int value;
+ public abstract Integer getHeader();
+ public abstract Integer getSerialBitCount();
+ public abstract Integer getSerialMaxLenght();
+ public abstract Long getSerialMaxValue();
+
+ private GDTITagSize(int value) {
+ this.value = value;
+ }
+
+ public int getValue() {
+ return value;
+ }
+
+ private static final Map BY_CODE_MAP = new LinkedHashMap<>();
+ static {
+ for (GDTITagSize rae : GDTITagSize.values()) {
+ BY_CODE_MAP.put(rae.value, rae);
+ }
+ }
+
+ public static GDTITagSize forCode(int code) {
+ return BY_CODE_MAP.get(code);
+ }
+
+
+}
+
+
+
+package org.epctagcoder.option.GDTI.partitionTable;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.epctagcoder.option.TableItem;
+
+
+public class GDTIPartitionTableList {
+ static final private List list = new ArrayList();
+
+ static {
+ list.add( new TableItem(0, 40, 12, 1, 0) );
+ list.add( new TableItem(1, 37, 11, 4, 1) );
+ list.add( new TableItem(2, 34, 10, 7, 2) );
+ list.add( new TableItem(3, 30, 9, 11, 3) );
+ list.add( new TableItem(4, 27, 8, 14, 4) );
+ list.add( new TableItem(5, 24, 7, 17, 5) );
+ list.add( new TableItem(6, 20, 6, 21, 6) );
+ }
+
+ public GDTIPartitionTableList() {
+
+ }
+
+
+ public TableItem getPartitionByL(Integer index) {
+ TableItem tableItem = null;
+ for (TableItem item : list) {
+ if (item.getL()==index) {
+ tableItem = item;
+ break;
+ }
+ }
+ return tableItem;
+ }
+
+ public TableItem getPartitionByValue(Integer index) {
+ TableItem tableItem = null;
+ for (TableItem item : list) {
+ if (item.getPartitionValue()==index) {
+ tableItem = item;
+ break;
+ }
+ }
+ return tableItem;
+ }
+
+
+}
+
+
+
+package org.epctagcoder.option.GIAI;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+public enum GIAIFilterValue {
+ ALL_OTHERS_0(0),
+ RESERVED_1(1),
+ RESERVED_2(2),
+ RESERVED_3(3),
+ RESERVED_4(4),
+ RESERVED_5(5),
+ RESERVED_6(6),
+ RESERVED_7(7);
+
+ private int value;
+
+ private GIAIFilterValue(int value) {
+ this.value = value;
+ }
+
+ public int getValue() {
+ return value;
+ }
+
+ private static final Map BY_CODE_MAP = new LinkedHashMap<>();
+ static {
+ for (GIAIFilterValue rae : GIAIFilterValue.values()) {
+ BY_CODE_MAP.put(rae.value, rae);
+ }
+ }
+
+ public static GIAIFilterValue forCode(int code) {
+ return BY_CODE_MAP.get(code);
+ }
+
+
+}
+
+
+
+package org.epctagcoder.option.GIAI;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+public enum GIAIHeader {
+ HEADER_00110100("00110100") {
+ public Integer getTagSize() {
+ return 96;
+ }
+ },
+ HEADER_00111000("00111000") {
+ public Integer getTagSize() {
+ return 202;
+ }
+ };
+
+ private String value;
+ public abstract Integer getTagSize();
+
+
+ private GIAIHeader(String value) {
+ this.value = value;
+ }
+
+ public String getValue() {
+ return value;
+ }
+
+ private static final Map BY_CODE_MAP = new LinkedHashMap<>();
+ static {
+ for (GIAIHeader rae : GIAIHeader.values()) {
+ BY_CODE_MAP.put(rae.value, rae);
+ }
+ }
+
+ public static GIAIHeader forCode(String code) {
+ return BY_CODE_MAP.get(code);
+ }
+
+
+}
+
+
+
+package org.epctagcoder.option.GIAI;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+public enum GIAITagSize {
+ BITS_96(96) {
+ public Integer getHeader() {
+ return 52;
+ }
+ public Integer getSerialBitCount() {
+ return 38;
+ }
+ public Integer getSerialMaxLenght() {
+ return 13;
+ }
+ },
+ BITS_202(202) {
+ public Integer getHeader() {
+ return 56;
+ }
+ public Integer getSerialBitCount() {
+ return 112;
+ }
+ public Integer getSerialMaxLenght() {
+ return 20;
+ }
+ };
+
+ private int value;
+ public abstract Integer getHeader();
+ public abstract Integer getSerialBitCount();
+ public abstract Integer getSerialMaxLenght();
+
+ private GIAITagSize(int value) {
+ this.value = value;
+ }
+
+ public int getValue() {
+ return value;
+ }
+
+ private static final Map BY_CODE_MAP = new LinkedHashMap<>();
+ static {
+ for (GIAITagSize rae : GIAITagSize.values()) {
+ BY_CODE_MAP.put(rae.value, rae);
+ }
+ }
+
+ public static GIAITagSize forCode(int code) {
+ return BY_CODE_MAP.get(code);
+ }
+
+
+}
+
+
+
+package org.epctagcoder.option.GIAI.partitionTable;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.epctagcoder.option.TableItem;
+import org.epctagcoder.option.GIAI.GIAITagSize;
+
+
+public class GIAIPartitionTableList {
+ static final private List list = new ArrayList();
+
+
+ public GIAIPartitionTableList(GIAITagSize tagSize) {
+ if ( tagSize.getValue()==96 ) {
+ list.clear();
+ list.add( new TableItem(0, 40, 12, 42, 13) );
+ list.add( new TableItem(1, 37, 11, 45, 14) );
+ list.add( new TableItem(2, 34, 10, 48, 15) );
+ list.add( new TableItem(3, 30, 9, 52, 16) );
+ list.add( new TableItem(4, 27, 8, 55, 17) );
+ list.add( new TableItem(5, 24, 7, 58, 18) );
+ list.add( new TableItem(6, 20, 6, 62, 19) );
+ } else if ( tagSize.getValue()==202 ) {
+ list.clear();
+ list.add( new TableItem(0, 40, 12, 148, 18) );
+ list.add( new TableItem(1, 37, 11, 151, 19) );
+ list.add( new TableItem(2, 34, 10, 154, 20) );
+ list.add( new TableItem(3, 30, 9, 158, 21) );
+ list.add( new TableItem(4, 27, 8, 161, 22) );
+ list.add( new TableItem(5, 24, 7, 164, 23) );
+ list.add( new TableItem(6, 20, 6, 168, 24) );
+ }
+
+
+ }
+
+ public TableItem getPartitionByL(Integer index) {
+ TableItem tableItem = null;
+ for (TableItem item : list) {
+ if (item.getL()==index) {
+ tableItem = item;
+ break;
+ }
+ }
+ return tableItem;
+ }
+
+ public TableItem getPartitionByValue(Integer index) {
+ TableItem tableItem = null;
+ for (TableItem item : list) {
+ if (item.getPartitionValue()==index) {
+ tableItem = item;
+ break;
+ }
+ }
+ return tableItem;
+ }
+
+
+}
+
+
+
+package org.epctagcoder.option.GRAI;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+public enum GRAIFilterValue {
+ ALL_OTHERS_0(0),
+ RESERVED_1(1),
+ RESERVED_2(2),
+ RESERVED_3(3),
+ RESERVED_4(4),
+ RESERVED_5(5),
+ RESERVED_6(6),
+ RESERVED_7(7);
+
+ private int value;
+
+ private GRAIFilterValue(int value) {
+ this.value = value;
+ }
+
+ public int getValue() {
+ return value;
+ }
+
+ private static final Map BY_CODE_MAP = new LinkedHashMap<>();
+ static {
+ for (GRAIFilterValue rae : GRAIFilterValue.values()) {
+ BY_CODE_MAP.put(rae.value, rae);
+ }
+ }
+
+ public static GRAIFilterValue forCode(int code) {
+ return BY_CODE_MAP.get(code);
+ }
+
+
+}
+
+
+
+package org.epctagcoder.option.GRAI;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+
+public enum GRAIHeader {
+ HEADER_00110011("00110011") {
+ public Integer getTagSize() {
+ return 96;
+ }
+ },
+ HEADER_00110111("00110111") {
+ public Integer getTagSize() {
+ return 170;
+ }
+ };
+
+ private String value;
+ public abstract Integer getTagSize();
+
+
+ private GRAIHeader(String value) {
+ this.value = value;
+ }
+
+ public String getValue() {
+ return value;
+ }
+
+ private static final Map BY_CODE_MAP = new LinkedHashMap<>();
+ static {
+ for (GRAIHeader rae : GRAIHeader.values()) {
+ BY_CODE_MAP.put(rae.value, rae);
+ }
+ }
+
+ public static GRAIHeader forCode(String code) {
+ GRAIHeader header = BY_CODE_MAP.get(code);
+
+ if (header==null) {
+ throw new IllegalArgumentException(String.format("GRAI header [%s] is invalid. Allowed only 00110011 or 00110111", code));
+ }
+
+ return header;
+ }
+
+
+}
+
+
+
+package org.epctagcoder.option.GRAI;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+public enum GRAITagSize {
+ BITS_96(96) {
+ public Integer getHeader() {
+ return 51;
+ }
+ public Integer getSerialBitCount() {
+ return 38;
+ }
+ public Integer getSerialMaxLenght() {
+ return 13;
+ }
+ public Long getSerialMaxValue() {
+ return 274_877_906_943L;
+ }
+ },
+ BITS_170(170) {
+ public Integer getHeader() {
+ return 55;
+ }
+ public Integer getSerialBitCount() {
+ return 112;
+ }
+ public Integer getSerialMaxLenght() {
+ return 16;
+ }
+ public Long getSerialMaxValue() {
+ return null; // not used
+ }
+ };
+
+ private int value;
+ public abstract Integer getHeader();
+ public abstract Integer getSerialBitCount();
+ public abstract Integer getSerialMaxLenght();
+ public abstract Long getSerialMaxValue();
+
+ private GRAITagSize(int value) {
+ this.value = value;
+ }
+
+ public int getValue() {
+ return value;
+ }
+
+ private static final Map BY_CODE_MAP = new LinkedHashMap<>();
+ static {
+ for (GRAITagSize rae : GRAITagSize.values()) {
+ BY_CODE_MAP.put(rae.value, rae);
+ }
+ }
+
+ public static GRAITagSize forCode(int code) {
+ return BY_CODE_MAP.get(code);
+ }
+
+
+}
+
+
+
+package org.epctagcoder.option.GRAI.partitionTable;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.epctagcoder.option.TableItem;
+
+
+public class GRAIPartitionTableList {
+ static final private List list = new ArrayList();
+
+ static {
+ list.add( new TableItem(0, 40, 12, 4, 0) );
+ list.add( new TableItem(1, 37, 11, 7, 1) );
+ list.add( new TableItem(2, 34, 10, 10, 2) );
+ list.add( new TableItem(3, 30, 9, 14, 3) );
+ list.add( new TableItem(4, 27, 8, 17, 4) );
+ list.add( new TableItem(5, 24, 7, 20, 5) );
+ list.add( new TableItem(6, 20, 6, 24, 6) );
+ }
+
+ public GRAIPartitionTableList() {
+
+ }
+
+
+ public TableItem getPartitionByL(Integer index) {
+ TableItem tableItem = null;
+ for (TableItem item : list) {
+ if (item.getL()==index) {
+ tableItem = item;
+ break;
+ }
+ }
+ return tableItem;
+ }
+
+ public TableItem getPartitionByValue(Integer index) {
+ TableItem tableItem = null;
+ for (TableItem item : list) {
+ if (item.getPartitionValue()==index) {
+ tableItem = item;
+ break;
+ }
+ }
+ return tableItem;
+ }
+
+
+}
+
+
+
+package org.epctagcoder.option.GSRN;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+public enum GSRNFilterValue {
+ ALL_OTHERS_0(0),
+ RESERVED_1(1),
+ RESERVED_2(2),
+ RESERVED_3(3),
+ RESERVED_4(4),
+ RESERVED_5(5),
+ RESERVED_6(6),
+ RESERVED_7(7);
+
+ private int value;
+
+ private GSRNFilterValue(int value) {
+ this.value = value;
+ }
+
+ public int getValue() {
+ return value;
+ }
+
+ private static final Map BY_CODE_MAP = new LinkedHashMap<>();
+ static {
+ for (GSRNFilterValue rae : GSRNFilterValue.values()) {
+ BY_CODE_MAP.put(rae.value, rae);
+ }
+ }
+
+ public static GSRNFilterValue forCode(int code) {
+ return BY_CODE_MAP.get(code);
+ }
+
+
+}
+
+
+
+package org.epctagcoder.option.GSRN;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+
+public enum GSRNHeader {
+ HEADER_00101101("00101101") {
+ public Integer getTagSize() {
+ return 96;
+ }
+ };
+
+ private String value;
+ public abstract Integer getTagSize();
+
+
+ private GSRNHeader(String value) {
+ this.value = value;
+ }
+
+ public String getValue() {
+ return value;
+ }
+
+ private static final Map BY_CODE_MAP = new LinkedHashMap<>();
+ static {
+ for (GSRNHeader rae : GSRNHeader.values()) {
+ BY_CODE_MAP.put(rae.value, rae);
+ }
+ }
+
+ public static GSRNHeader forCode(String code) {
+ GSRNHeader header = BY_CODE_MAP.get(code);
+
+ if (header==null) {
+ throw new IllegalArgumentException(String.format("GSRN header [%s] is invalid. Allowed only 00101101", code));
+ }
+
+ return header;
+ }
+
+
+}
+
+
+
+package org.epctagcoder.option.GSRN;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+public enum GSRNTagSize {
+ BITS_96(96) {
+ public Integer getHeader() {
+ return 45;
+ }
+ };
+
+ private int value;
+ public abstract Integer getHeader();
+
+ private GSRNTagSize(int value) {
+ this.value = value;
+ }
+
+ public int getValue() {
+ return value;
+ }
+
+ private static final Map BY_CODE_MAP = new LinkedHashMap<>();
+ static {
+ for (GSRNTagSize rae : GSRNTagSize.values()) {
+ BY_CODE_MAP.put(rae.value, rae);
+ }
+ }
+
+ public static GSRNTagSize forCode(int code) {
+ return BY_CODE_MAP.get(code);
+ }
+
+
+}
+
+
+
+package org.epctagcoder.option.GSRN.partitionTable;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.epctagcoder.option.TableItem;
+
+
+public class GSRNPartitionTableList {
+ static final private List list = new ArrayList();
+
+ static {
+ list.add( new TableItem(0, 40, 12, 18, 5) );
+ list.add( new TableItem(1, 37, 11, 21, 6) );
+ list.add( new TableItem(2, 34, 10, 24, 7) );
+ list.add( new TableItem(3, 30, 9, 28, 8) );
+ list.add( new TableItem(4, 27, 8, 31, 9) );
+ list.add( new TableItem(5, 24, 7, 34, 10) );
+ list.add( new TableItem(6, 20, 6, 38, 11) );
+ }
+
+ public GSRNPartitionTableList() {
+
+ }
+
+ public TableItem getPartitionByL(Integer index) {
+ TableItem tableItem = null;
+ for (TableItem item : list) {
+ if (item.getL()==index) {
+ tableItem = item;
+ break;
+ }
+ }
+ return tableItem;
+ }
+
+ public TableItem getPartitionByValue(Integer index) {
+ TableItem tableItem = null;
+ for (TableItem item : list) {
+ if (item.getPartitionValue()==index) {
+ tableItem = item;
+ break;
+ }
+ }
+ return tableItem;
+ }
+
+
+}
+
+
+
+package org.epctagcoder.option.GSRNP;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+public enum GSRNPFilterValue {
+ ALL_OTHERS_0(0),
+ RESERVED_1(1),
+ RESERVED_2(2),
+ RESERVED_3(3),
+ RESERVED_4(4),
+ RESERVED_5(5),
+ RESERVED_6(6),
+ RESERVED_7(7);
+
+ private int value;
+
+ private GSRNPFilterValue(int value) {
+ this.value = value;
+ }
+
+ public int getValue() {
+ return value;
+ }
+
+ private static final Map BY_CODE_MAP = new LinkedHashMap<>();
+ static {
+ for (GSRNPFilterValue rae : GSRNPFilterValue.values()) {
+ BY_CODE_MAP.put(rae.value, rae);
+ }
+ }
+
+ public static GSRNPFilterValue forCode(int code) {
+ return BY_CODE_MAP.get(code);
+ }
+
+
+}
+
+
+
+package org.epctagcoder.option.GSRNP;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+public enum GSRNPHeader {
+ HEADER_00101110("00101110") {
+ public Integer getTagSize() {
+ return 96;
+ }
+ };
+
+ private String value;
+ public abstract Integer getTagSize();
+
+
+ private GSRNPHeader(String value) {
+ this.value = value;
+ }
+
+ public String getValue() {
+ return value;
+ }
+
+ private static final Map BY_CODE_MAP = new LinkedHashMap<>();
+ static {
+ for (GSRNPHeader rae : GSRNPHeader.values()) {
+ BY_CODE_MAP.put(rae.value, rae);
+ }
+ }
+
+ public static GSRNPHeader forCode(String code) {
+ return BY_CODE_MAP.get(code);
+ }
+
+
+}
+
+
+
+package org.epctagcoder.option.GSRNP;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+public enum GSRNPTagSize {
+ BITS_96(96) {
+ public Integer getHeader() {
+ return 46;
+ }
+ };
+
+ private int value;
+ public abstract Integer getHeader();
+
+ private GSRNPTagSize(int value) {
+ this.value = value;
+ }
+
+ public int getValue() {
+ return value;
+ }
+
+ private static final Map BY_CODE_MAP = new LinkedHashMap<>();
+ static {
+ for (GSRNPTagSize rae : GSRNPTagSize.values()) {
+ BY_CODE_MAP.put(rae.value, rae);
+ }
+ }
+
+ public static GSRNPTagSize forCode(int code) {
+ return BY_CODE_MAP.get(code);
+ }
+
+
+}
+
+
+
+package org.epctagcoder.option.GSRNP.partitionTable;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.epctagcoder.option.TableItem;
+
+
+public class GSRNPPartitionTableList {
+ static final private List list = new ArrayList();
+
+ static {
+ list.add( new TableItem(0, 40, 12, 18, 5) );
+ list.add( new TableItem(1, 37, 11, 21, 6) );
+ list.add( new TableItem(2, 34, 10, 24, 7) );
+ list.add( new TableItem(3, 30, 9, 28, 8) );
+ list.add( new TableItem(4, 27, 8, 31, 9) );
+ list.add( new TableItem(5, 24, 7, 34, 10) );
+ list.add( new TableItem(6, 20, 6, 38, 11) );
+ }
+
+ public GSRNPPartitionTableList() {
+
+ }
+
+ public TableItem getPartitionByL(Integer index) {
+ TableItem tableItem = null;
+ for (TableItem item : list) {
+ if (item.getL()==index) {
+ tableItem = item;
+ break;
+ }
+ }
+ return tableItem;
+ }
+
+ public TableItem getPartitionByValue(Integer index) {
+ TableItem tableItem = null;
+ for (TableItem item : list) {
+ if (item.getPartitionValue()==index) {
+ tableItem = item;
+ break;
+ }
+ }
+ return tableItem;
+ }
+
+
+}
+
+
+
+package org.epctagcoder.option;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+public enum PrefixLength {
+ DIGIT_6(6),
+ DIGIT_7(7),
+ DIGIT_8(8),
+ DIGIT_9(9),
+ DIGIT_10(10),
+ DIGIT_11(11),
+ DIGIT_12(12);
+
+ private int value;
+
+ private PrefixLength(int value) {
+ this.value = value;
+ }
+
+ public int getValue() {
+ return value;
+ }
+
+
+ private static final Map BY_CODE_MAP = new LinkedHashMap<>();
+ static {
+ for (PrefixLength rae : PrefixLength.values()) {
+ BY_CODE_MAP.put(rae.value, rae);
+ }
+ }
+
+ public static PrefixLength forCode(int code) {
+ return BY_CODE_MAP.get(code);
+ }
+
+}
+
+
+
+package org.epctagcoder.option.SGLN.partitionTable;
+
+import org.epctagcoder.option.TableItem;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public class SGLNPartitionTableList {
+ static final private List list = new ArrayList();
+
+ static {
+ list.add( new TableItem(0, 40, 12, 1, 0) );
+ list.add( new TableItem(1, 37, 11, 4, 1) );
+ list.add( new TableItem(2, 34, 10, 7, 2) );
+ list.add( new TableItem(3, 30, 9, 11, 3) );
+ list.add( new TableItem(4, 27, 8, 14, 4) );
+ list.add( new TableItem(5, 24, 7, 17, 5) );
+ list.add( new TableItem(6, 20, 6, 21, 6) );
+ }
+
+ public SGLNPartitionTableList() {
+
+ }
+
+
+ public TableItem getPartitionByL(Integer index) {
+ TableItem tableItem = null;
+ for (TableItem item : list) {
+ if (item.getL()==index) {
+ tableItem = item;
+ break;
+ }
+ }
+ return tableItem;
+ }
+
+ public TableItem getPartitionByValue(Integer index) {
+ TableItem tableItem = null;
+ for (TableItem item : list) {
+ if (item.getPartitionValue()==index) {
+ tableItem = item;
+ break;
+ }
+ }
+ return tableItem;
+ }
+}
+
+
+
+package org.epctagcoder.option.SGLN;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+public enum SGLNFilterValue {
+
+ ALL_OTHERS_0(0),
+ RESERVED_1(1),
+ RESERVED_2(2),
+ RESERVED_3(3),
+ RESERVED_4(4),
+ RESERVED_5(5),
+ RESERVED_6(6),
+ RESERVED_7(7);
+
+ private static final Map BY_CODE_MAP = new LinkedHashMap<>();
+
+ static {
+ for (SGLNFilterValue rae : SGLNFilterValue.values()) {
+ BY_CODE_MAP.put(rae.value, rae);
+ }
+ }
+
+ private int value;
+
+ private SGLNFilterValue(int value) {
+ this.value = value;
+ }
+
+ public static SGLNFilterValue forCode(int code) {
+ return BY_CODE_MAP.get(code);
+ }
+
+ public int getValue() {
+ return this.value;
+ }
+}
+
+
+
+package org.epctagcoder.option.SGLN;
+
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+public enum SGLNHeader {
+
+ HEADER_00110010("00110010") {
+ public Integer getTagSize() {
+ return 96;
+ }
+ },
+ HEADER_00111001("00111001") {
+ public Integer getTagSize() {
+ return 195;
+ }
+ };
+
+ private String value;
+ public abstract Integer getTagSize();
+
+
+ private SGLNHeader(String value) {
+ this.value = value;
+ }
+
+ public String getValue() {
+ return value;
+ }
+
+ private static final Map BY_CODE_MAP = new LinkedHashMap<>();
+ static {
+ for (SGLNHeader rae : SGLNHeader.values()) {
+ BY_CODE_MAP.put(rae.value, rae);
+ }
+ }
+
+ public static SGLNHeader forCode(String code) {
+ SGLNHeader header = BY_CODE_MAP.get(code);
+
+ if (header==null) {
+ throw new IllegalArgumentException(String.format("SGLN header [%s] is invalid. Allowed only 00110010 or 00111001", code));
+ }
+
+ return header;
+ }
+}
+
+
+
+package org.epctagcoder.option.SGLN;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+public enum SGLNTagSize {
+
+ BITS_96(96) {
+ @Override
+ public Integer getHeader() {
+ return 51;
+ }
+
+ @Override
+ public Integer getSerialBitCount() {
+ return 41;
+ }
+
+ @Override
+ public Integer getSerialMaxLenght() {
+ return 13;
+ }
+
+ @Override
+ public Long getSerialMaxValue() {
+ return 2_199_023_255_551L;
+ }
+ },
+ BITS_195(195) {
+ @Override
+ public Integer getHeader() {
+ return 55;
+ }
+
+ @Override
+ public Integer getSerialBitCount() {
+ return 140;
+ }
+
+ @Override
+ public Integer getSerialMaxLenght() {
+ return 20;
+ }
+
+ @Override
+ public Long getSerialMaxValue() {
+ return null; // not used
+ }
+ };
+
+ private static final Map BY_CODE_MAP = new LinkedHashMap<>();
+
+ static {
+ for (SGLNTagSize rae : SGLNTagSize.values()) {
+ BY_CODE_MAP.put(rae.value, rae);
+ }
+ }
+
+
+ private int value;
+
+ private SGLNTagSize(int value) {
+ this.value = value;
+ }
+
+ public static SGLNTagSize forCode(int code) {
+ return BY_CODE_MAP.get(code);
+ }
+
+ public abstract Integer getHeader();
+
+ public abstract Integer getSerialBitCount();
+
+ public abstract Integer getSerialMaxLenght();
+
+ public abstract Long getSerialMaxValue();
+
+ public int getValue() {
+ return value;
+ }
+}
+
+
+
+package org.epctagcoder.option.SGTIN.partitionTable;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.epctagcoder.exception.EPCParseException;
+import org.epctagcoder.option.TableItem;
+
+
+public class SGTINPartitionTableList {
+ static final private List list = new ArrayList<>();
+
+ static {
+ list.add( new TableItem(0, 40, 12, 4, 1) );
+ list.add( new TableItem(1, 37, 11, 7, 2) );
+ list.add( new TableItem(2, 34, 10, 10, 3) );
+ list.add( new TableItem(3, 30, 9, 14, 4) );
+ list.add( new TableItem(4, 27, 8, 17, 5) );
+ list.add( new TableItem(5, 24, 7, 20, 6) );
+ list.add( new TableItem(6, 20, 6, 24, 7) );
+ }
+
+ public SGTINPartitionTableList() {
+
+ }
+
+
+ public TableItem getPartitionByL(Integer index) {
+ TableItem tableItem = null;
+ for (TableItem item : list) {
+ if (item.getL()==index) {
+ tableItem = item;
+ break;
+ }
+ }
+ return tableItem;
+ }
+
+ public TableItem getPartitionByValue(int index) throws EPCParseException {
+ if(index < 0 || index >= list.size()) {
+ String message = "Partition value %d is not within expected range (0 - %d)";
+ throw new EPCParseException(String.format(message, index, list.size() - 1));
+ }
+
+ return list.get(index);
+ }
+
+
+}
+
+
+
+package org.epctagcoder.option.SGTIN;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+public enum SGTINExtensionDigit {
+ EXTENSION_0(0),
+ EXTENSION_1(1),
+ EXTENSION_2(2),
+ EXTENSION_3(3),
+ EXTENSION_4(4),
+ EXTENSION_5(5),
+ EXTENSION_6(6),
+ EXTENSION_7(7),
+ EXTENSION_8(8),
+ EXTENSION_9(9);
+
+ private int value;
+
+ private SGTINExtensionDigit(int value) {
+ this.value = value;
+ }
+
+ public int getValue() {
+ return value;
+ }
+
+ private static final Map BY_CODE_MAP = new LinkedHashMap<>();
+ static {
+ for (SGTINExtensionDigit rae : SGTINExtensionDigit.values()) {
+ BY_CODE_MAP.put(rae.value, rae);
+ }
+ }
+
+ public static SGTINExtensionDigit forCode(int code) {
+ return BY_CODE_MAP.get(code);
+ }
+
+
+
+
+}
+
+
+
+package org.epctagcoder.option.SGTIN;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+public enum SGTINFilterValue {
+ ALL_OTHERS_0(0),
+ POS_ITEM_1(1),
+ CASE_2(2),
+ RESERVED_3(3),
+ INNER_PACK_4(4),
+ RESERVED_5(5),
+ UNIT_LOAD_6(6),
+ COMPONENT_7(7);
+
+ private int value;
+
+ private SGTINFilterValue(int value) {
+ this.value = value;
+ }
+
+ public int getValue() {
+ return value;
+ }
+
+ private static final Map BY_CODE_MAP = new LinkedHashMap<>();
+ static {
+ for (SGTINFilterValue rae : SGTINFilterValue.values()) {
+ BY_CODE_MAP.put(rae.value, rae);
+ }
+ }
+
+ public static SGTINFilterValue forCode(int code) {
+ return BY_CODE_MAP.get(code);
+ }
+
+
+}
+
+
+
+package org.epctagcoder.option.SGTIN;
+
+import org.epctagcoder.exception.EPCParseException;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+public enum SGTINHeader {
+ HEADER_00110000("00110000") {
+ public Integer getTagSize() {
+ return 96;
+ }
+ },
+ HEADER_00110110("00110110") {
+ public Integer getTagSize() {
+ return 198;
+ }
+ };
+
+ private final String value;
+ public abstract Integer getTagSize();
+
+
+ SGTINHeader(String value) {
+ this.value = value;
+ }
+
+ public String getValue() {
+ return value;
+ }
+
+ private static final Map BY_CODE_MAP = new LinkedHashMap<>();
+ static {
+ for (SGTINHeader rae : SGTINHeader.values()) {
+ BY_CODE_MAP.put(rae.value, rae);
+ }
+ }
+
+ public static SGTINHeader forCode(String code) throws EPCParseException {
+ SGTINHeader header = BY_CODE_MAP.get(code);
+
+ if (header==null) {
+ throw new EPCParseException(String.format("SGTIN header [%s] is invalid. Allowed only 00110000 or 00110110", code));
+ }
+
+ return header;
+ }
+
+
+}
+
+
+
+package org.epctagcoder.option.SGTIN;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+public enum SGTINTagSize {
+ BITS_96(96) {
+ public Integer getHeader() {
+ return 48;
+ }
+ public Integer getSerialBitCount() {
+ return 38;
+ }
+ public Integer getSerialMaxLenght() {
+ return 11;
+ }
+ public Long getSerialMaxValue() {
+ return 274_877_906_943L;
+ }
+ },
+ BITS_198(198) {
+ public Integer getHeader() {
+ return 54;
+ }
+ public Integer getSerialBitCount() {
+ return 140;
+ }
+ public Integer getSerialMaxLenght() {
+ return 20;
+ }
+ public Long getSerialMaxValue() {
+ return null; // not used
+ }
+ };
+
+ private int value;
+ public abstract Integer getHeader();
+ public abstract Integer getSerialBitCount();
+ public abstract Integer getSerialMaxLenght();
+ public abstract Long getSerialMaxValue();
+
+ private SGTINTagSize(int value) {
+ this.value = value;
+ }
+
+ public int getValue() {
+ return value;
+ }
+
+ private static final Map BY_CODE_MAP = new LinkedHashMap<>();
+ static {
+ for (SGTINTagSize rae : SGTINTagSize.values()) {
+ BY_CODE_MAP.put(rae.value, rae);
+ }
+ }
+
+ public static SGTINTagSize forCode(int code) {
+ SGTINTagSize bits = BY_CODE_MAP.get(code);
+
+ if (bits==null) {
+ throw new IllegalArgumentException(String.format("SGTIN tag size %d is invalid. Only 96 bits or 198 bits supported.", code));
+ }
+
+ return bits;
+ }
+
+
+}
+
+
+
+package org.epctagcoder.option.SSCC.partitionTable;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.epctagcoder.option.TableItem;
+
+
+public class SSCCPartitionTableList {
+ static final private List list = new ArrayList();
+
+ static {
+ list.add( new TableItem(0, 40, 12, 18, 5) );
+ list.add( new TableItem(1, 37, 11, 21, 6) );
+ list.add( new TableItem(2, 34, 10, 24, 7) );
+ list.add( new TableItem(3, 30, 9, 28, 8) );
+ list.add( new TableItem(4, 27, 8, 31, 9) );
+ list.add( new TableItem(5, 24, 7, 34, 10) );
+ list.add( new TableItem(6, 20, 6, 38, 11) );
+ }
+
+ public SSCCPartitionTableList() {
+
+ }
+
+ public TableItem getPartitionByL(Integer index) {
+ TableItem tableItem = null;
+ for (TableItem item : list) {
+ if (item.getL()==index) {
+ tableItem = item;
+ break;
+ }
+ }
+ return tableItem;
+ }
+
+ public TableItem getPartitionByValue(Integer index) {
+ TableItem tableItem = null;
+ for (TableItem item : list) {
+ if (item.getPartitionValue()==index) {
+ tableItem = item;
+ break;
+ }
+ }
+ return tableItem;
+ }
+
+
+}
+
+
+
+package org.epctagcoder.option.SSCC;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+public enum SSCCExtensionDigit {
+ EXTENSION_0(0),
+ EXTENSION_1(1),
+ EXTENSION_2(2),
+ EXTENSION_3(3),
+ EXTENSION_4(4),
+ EXTENSION_5(5),
+ EXTENSION_6(6),
+ EXTENSION_7(7),
+ EXTENSION_8(8),
+ EXTENSION_9(9);
+
+ private int value;
+
+ private SSCCExtensionDigit(int value) {
+ this.value = value;
+ }
+
+ public int getValue() {
+ return value;
+ }
+
+ private static final Map BY_CODE_MAP = new LinkedHashMap<>();
+ static {
+ for (SSCCExtensionDigit rae : SSCCExtensionDigit.values()) {
+ BY_CODE_MAP.put(rae.value, rae);
+ }
+ }
+
+ public static SSCCExtensionDigit forCode(int code) {
+ return BY_CODE_MAP.get(code);
+ }
+
+
+
+
+}
+
+
+
+package org.epctagcoder.option.SSCC;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+public enum SSCCFilterValue {
+ ALL_OTHERS_0(0),
+ RESERVED_1(1),
+ CASE_2(2),
+ RESERVED_3(3),
+ RESERVED_4(4),
+ RESERVED_5(5),
+ UNIT_LOAD_6(6),
+ RESERVED_7(7);
+
+ private int value;
+
+ private SSCCFilterValue(int value) {
+ this.value = value;
+ }
+
+ public int getValue() {
+ return value;
+ }
+
+ private static final Map BY_CODE_MAP = new LinkedHashMap<>();
+ static {
+ for (SSCCFilterValue rae : SSCCFilterValue.values()) {
+ BY_CODE_MAP.put(rae.value, rae);
+ }
+ }
+
+ public static SSCCFilterValue forCode(int code) {
+ return BY_CODE_MAP.get(code);
+ }
+
+
+}
+
+
+
+package org.epctagcoder.option.SSCC;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+public enum SSCCHeader {
+ HEADER_00110001("00110001") {
+ public Integer getTagSize() {
+ return 96;
+ }
+ };
+
+ private String value;
+ public abstract Integer getTagSize();
+
+
+ private SSCCHeader(String value) {
+ this.value = value;
+ }
+
+ public String getValue() {
+ return value;
+ }
+
+ private static final Map BY_CODE_MAP = new LinkedHashMap<>();
+ static {
+ for (SSCCHeader rae : SSCCHeader.values()) {
+ BY_CODE_MAP.put(rae.value, rae);
+ }
+ }
+
+ public static SSCCHeader forCode(String code) {
+ SSCCHeader header = BY_CODE_MAP.get(code);
+
+ if (header==null) {
+ throw new IllegalArgumentException(String.format("SSCC header [%s] is invalid. Allowed only 00110001", code));
+ }
+
+ return header;
+ }
+
+
+}
+
+
+
+package org.epctagcoder.option.SSCC;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+public enum SSCCTagSize {
+ BITS_96(96) {
+ public Integer getHeader() {
+ return 49;
+ }
+ };
+
+ private int value;
+ public abstract Integer getHeader();
+
+ private SSCCTagSize(int value) {
+ this.value = value;
+ }
+
+ public int getValue() {
+ return value;
+ }
+
+ private static final Map BY_CODE_MAP = new LinkedHashMap<>();
+ static {
+ for (SSCCTagSize rae : SSCCTagSize.values()) {
+ BY_CODE_MAP.put(rae.value, rae);
+ }
+ }
+
+ public static SSCCTagSize forCode(int code) {
+ return BY_CODE_MAP.get(code);
+ }
+
+
+}
+
+
+
+package org.epctagcoder.option;
+
+public class TableItem {
+ private int partitionValue;
+ private int l;
+ private int m;
+ private int n;
+ private int digits;
+
+
+ public TableItem(int partitionValue, int m, int l, int n, int digits) {
+ this.partitionValue = partitionValue;
+ this.m = m;
+ this.l = l;
+ this.n = n;
+ this.digits = digits;
+ }
+
+
+ public int getPartitionValue() {
+ return partitionValue;
+ }
+
+
+ public void setPartitionValue(int partitionValue) {
+ this.partitionValue = partitionValue;
+ }
+
+
+ public int getL() {
+ return l;
+ }
+
+
+ public void setL(int l) {
+ this.l = l;
+ }
+
+
+ public int getM() {
+ return m;
+ }
+
+
+ public void setM(int m) {
+ this.m = m;
+ }
+
+
+ public int getN() {
+ return n;
+ }
+
+
+ public void setN(int n) {
+ this.n = n;
+ }
+
+
+ public int getDigits() {
+ return digits;
+ }
+
+
+ public void setDigits(int digits) {
+ this.digits = digits;
+ }
+
+
+
+
+
+
+
+}
+
+
+
+package org.epctagcoder.parse.CPI;
+
+import java.util.List;
+import java.util.Optional;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+
+import org.epctagcoder.option.PrefixLength;
+import org.epctagcoder.option.TableItem;
+import org.epctagcoder.option.CPI.CPIFilterValue;
+import org.epctagcoder.option.CPI.CPIHeader;
+import org.epctagcoder.option.CPI.CPITagSize;
+import org.epctagcoder.option.CPI.partitionTable.CPIPartitionTableList;
+import org.epctagcoder.result.CPI;
+import org.epctagcoder.util.Converter;
+
+
+public class ParseCPI {
+ private CPI cpi = new CPI();
+ private String companyPrefix;
+ private PrefixLength prefixLength;
+ private CPITagSize tagSize;
+ private CPIFilterValue filterValue;
+ private String componentPartReference;
+ private String serial;
+ private String rfidTag;
+ private String epcTagURI;
+ private String epcPureIdentityURI;
+ private TableItem tableItem;
+ private int remainder;
+
+ public static ChoiceStep Builder() throws Exception {
+ return new Steps();
+ }
+
+ private ParseCPI(Steps steps) {
+ this.companyPrefix = steps.companyPrefix;
+ this.tagSize = steps.tagSize;
+ this.filterValue = steps.filterValue;
+ this.componentPartReference = steps.componentPartReference;
+ this.serial = steps.serial;
+ this.rfidTag = steps.rfidTag;
+ this.epcTagURI = steps.epcTagURI;
+ this.epcPureIdentityURI = steps.epcPureIdentityURI;
+ parse();
+ }
+
+
+
+ private void parse() {
+ Optional optionalCompanyPrefix = Optional.ofNullable(companyPrefix);
+ Optional optionalRfidTag = Optional.ofNullable(rfidTag);
+ Optional optionalEpcTagURI = Optional.ofNullable(epcTagURI);
+ Optional optionalEpcPureIdentityURI = Optional.ofNullable(epcPureIdentityURI);
+
+ if ( optionalRfidTag.isPresent() ) {
+ String inputBin = Converter.hexToBin(rfidTag);
+ String headerBin = inputBin.substring(0, 8);
+ String filterBin = inputBin.substring(8,11);
+ String partitionBin = inputBin.substring(11,14);
+
+ tagSize = CPITagSize.forCode(CPIHeader.forCode(headerBin).getTagSize());
+ CPIPartitionTableList cpiPartitionTableList = new CPIPartitionTableList(tagSize);
+ tableItem = cpiPartitionTableList.getPartitionByValue( Integer.parseInt(partitionBin, 2) );
+
+ String filterDec = Long.toString( Long.parseLong(filterBin, 2) );
+ String companyPrefixBin = inputBin.substring(14, 14+tableItem.getM());
+ String componentPartReferenceBin = null;
+ String serialBin = null;
+
+ if (tagSize.getValue()==0) { // variable
+ String componentPartReferenceAndSerialBin = inputBin.substring(14+tableItem.getM() );
+
+ StringBuilder decodeComponentPartReference = new StringBuilder();
+ List splitCPR = Converter.splitEqually(componentPartReferenceAndSerialBin, 6);
+ for (String item : splitCPR) {
+ if ( item.equals("000000") ) {
+ break;
+ }
+ decodeComponentPartReference.append(item);
+ }
+
+ componentPartReferenceBin = decodeComponentPartReference.toString();
+ int posSerial = 14+tableItem.getM()+componentPartReferenceBin.length()+6;
+ componentPartReferenceBin = Converter.convertBinToBit(componentPartReferenceBin, 6, 8);
+ componentPartReference = Converter.binToString(componentPartReferenceBin);
+ serialBin = inputBin.substring(posSerial, posSerial+tagSize.getSerialBitCount());
+ } else if (tagSize.getValue()==96) {
+ componentPartReferenceBin = inputBin.substring(14+tableItem.getM(),14+tableItem.getM()+tableItem.getN());
+ componentPartReference = Converter.binToDec(componentPartReferenceBin);
+ serialBin = inputBin.substring(14+tableItem.getM()+tableItem.getN() );
+ }
+
+
+ String companyPrefixDec = Converter.binToDec(companyPrefixBin);
+ serial = Converter.binToDec(serialBin);
+ companyPrefix = Converter.strZero(companyPrefixDec, tableItem.getL()); // strzero aqui
+ filterValue = CPIFilterValue.forCode( Integer.parseInt(filterDec) );
+ prefixLength = PrefixLength.forCode(tableItem.getL());
+ } else {
+
+ if ( optionalCompanyPrefix.isPresent() ) {
+ CPIPartitionTableList sgtinPartitionTableList = new CPIPartitionTableList(tagSize);
+ prefixLength = PrefixLength.forCode( companyPrefix.length() );
+
+ validateCompanyPrefix();
+
+ tableItem = sgtinPartitionTableList.getPartitionByL( prefixLength.getValue() );
+
+ validateComponentPartReference();
+ validateSerial();
+
+ } else {
+
+ if ( optionalEpcTagURI.isPresent() ) {
+ Pattern pattern = Pattern.compile("(urn:epc:tag:cpi-)(96|var)\\:([0-7])\\.(\\d+)\\.(\\d+)\\.(\\w+)");
+
+ Matcher matcher = pattern.matcher(epcTagURI);
+
+ if ( matcher.matches() ) {
+ if ( matcher.group(2).equals("var") ) {
+ tagSize = CPITagSize.forCode( 0 );
+ } else {
+ tagSize = CPITagSize.forCode( Integer.parseInt(matcher.group(2)) );
+ }
+
+ filterValue = CPIFilterValue.forCode( Integer.parseInt(matcher.group(3)) );
+ companyPrefix = matcher.group(4);
+ prefixLength = PrefixLength.forCode( matcher.group(4).length() );
+ componentPartReference = matcher.group(5);
+ serial = matcher.group(6);
+ } else {
+ throw new IllegalArgumentException("EPC Tag URI is invalid");
+ }
+
+ } else if ( optionalEpcPureIdentityURI.isPresent() ) {
+ Pattern pattern = Pattern.compile("(urn:epc:id:cpi)\\:(\\d+)\\.(\\d+)\\.(\\w+)");
+ Matcher matcher = pattern.matcher(epcPureIdentityURI);
+
+ if ( matcher.matches() ) {
+ companyPrefix = matcher.group(2);
+ prefixLength = PrefixLength.forCode( matcher.group(2).length() );
+ componentPartReference = matcher.group(3);;
+ serial = matcher.group(4);
+ } else {
+ throw new IllegalArgumentException("EPC Pure Identity is invalid");
+ }
+ }
+
+ }
+
+ CPIPartitionTableList sgtinPartitionTableList = new CPIPartitionTableList(tagSize);
+ tableItem = sgtinPartitionTableList.getPartitionByL( prefixLength.getValue() );
+
+ }
+
+ String outputBin = getBinary();
+ String outputHex = Converter.binToHex( outputBin );
+
+ cpi.setEpcScheme("cpi");
+ cpi.setApplicationIdentifier("AI 8010 + AI 8011");
+ cpi.setTagSize( (tagSize.getValue()==0) ? "var" : Integer.toString(tagSize.getValue()) );
+ cpi.setFilterValue(Integer.toString(filterValue.getValue()));
+ cpi.setPartitionValue(Integer.toString(tableItem.getPartitionValue()));
+ cpi.setPrefixLength(Integer.toString(prefixLength.getValue()));
+ cpi.setCompanyPrefix(companyPrefix);
+ cpi.setComponentPartReference(componentPartReference);
+ cpi.setSerial(serial);
+ cpi.setEpcPureIdentityURI(String.format("urn:epc:id:cpi:%s.%s.%s", companyPrefix, componentPartReference, serial));
+ cpi.setEpcTagURI(String.format("urn:epc:tag:cpi-%s:%s.%s.%s.%s", (tagSize.getValue()==0) ? "var" : tagSize.getValue(), filterValue.getValue(), companyPrefix, componentPartReference, serial));
+ cpi.setEpcRawURI(String.format("urn:epc:raw:%s.x%s", outputBin.length(), outputHex ));
+ cpi.setBinary(outputBin);
+ cpi.setRfidTag(outputHex);
+ }
+
+
+ private String getBinary() {
+ StringBuilder bin = new StringBuilder();
+
+ bin.append( Converter.decToBin(tagSize.getHeader(), 8) );
+ bin.append( Converter.decToBin(filterValue.getValue(), 3) );
+ bin.append( Converter.decToBin(tableItem.getPartitionValue(), 3) );
+ bin.append( Converter.decToBin(Integer.parseInt(companyPrefix), tableItem.getM()) );
+
+ if (tagSize.getValue()==0) { // variable
+ bin.append( Converter.StringToBinary(componentPartReference, 6) );
+ bin.append("000000");
+ } else if (tagSize.getValue()==96) {
+ bin.append( Converter.decToBin(Integer.parseInt(componentPartReference), tableItem.getN()) );
+ }
+
+ bin.append( Converter.decToBin(serial, tagSize.getSerialBitCount() ) );
+ remainder = (int) (Math.ceil((bin.length()/16.0))*16)-bin.length();
+ bin.append( Converter.fill("0", remainder) );
+
+ return bin.toString();
+ }
+
+
+
+ public CPI getCPI() {
+ return cpi;
+ }
+
+ public String getRfidTag() {
+ return Converter.binToHex( getBinary() );
+ }
+
+
+
+ private void validateCompanyPrefix() {
+ Optional optionalPefixLenght = Optional.ofNullable(prefixLength);
+ if ( !optionalPefixLenght.isPresent() ) {
+ throw new IllegalArgumentException("Company Prefix is invalid. Length not found in the partition table");
+ }
+ }
+
+
+
+ private void validateComponentPartReference() {
+
+ if ( !Converter.isNumeric(componentPartReference) ) {
+ throw new IllegalArgumentException("Component/Part Reference is allowed with numerical only");
+ }
+
+ if ( componentPartReference.length()>tableItem.getDigits() ) {
+ throw new IllegalArgumentException("Component/Part Reference is out of range");
+ }
+
+
+ if (tagSize.getValue()==96 ) {
+ if ( componentPartReference.startsWith("0") ) {
+ throw new IllegalArgumentException("Component/Part Reference with leading zeros is not allowed");
+ }
+
+ }
+
+ }
+
+ private void validateSerial() {
+
+ if ( serial.startsWith("0") ) {
+ throw new IllegalArgumentException("Serial with leading zeros is not allowed");
+ }
+
+ if (tagSize.getValue()==0 ) { // variable
+ if ( serial.length()>tagSize.getSerialMaxLenght() ) {
+ throw new IllegalArgumentException( String.format("Serial value is out of range. Should be up to %d alphanumeric characters",
+ tagSize.getSerialMaxLenght() ));
+ }
+ } else if (tagSize.getValue()==96 ) {
+
+ if ( !Converter.isNumeric(serial) ) {
+ throw new IllegalArgumentException("Serial value is allowed with numerical only");
+ }
+
+ if ( Long.parseLong(serial)>tagSize.getSerialMaxValue() ) {
+ throw new IllegalArgumentException( String.format("Serial value is out of range. Should be less than or equal %d",
+ tagSize.getSerialMaxValue() ));
+ }
+ }
+
+ }
+
+
+
+ public static interface ChoiceStep {
+ componentPartReferenceStep withCompanyPrefix(String companyPrefix);
+ BuildStep withRFIDTag(String rfidTag);
+ BuildStep withEPCTagURI(String epcTagURI);
+ TagSizeStep withEPCPureIdentityURI(String epcPureIdentityURI);
+ }
+
+
+ public static interface componentPartReferenceStep {
+ serialStep withComponentPartReference(String componentPartReference);
+ }
+
+ public static interface serialStep {
+ TagSizeStep withSerial(String serial);
+ }
+
+ public static interface TagSizeStep {
+ FilterValueStep withTagSize( CPITagSize tagSize );
+ }
+
+ public static interface FilterValueStep {
+ BuildStep withFilterValue( CPIFilterValue filterValue );
+ }
+
+ public static interface BuildStep {
+ ParseCPI build();
+ }
+
+
+ private static class Steps implements ChoiceStep, componentPartReferenceStep, serialStep, TagSizeStep, FilterValueStep, BuildStep {
+ private String companyPrefix;
+ private CPITagSize tagSize;
+ private CPIFilterValue filterValue;
+ private String componentPartReference;
+ private String serial;
+ private String rfidTag;
+ private String epcTagURI;
+ private String epcPureIdentityURI;
+
+ @Override
+ public ParseCPI build() {
+ return new ParseCPI(this);
+ }
+
+ @Override
+ public BuildStep withFilterValue(CPIFilterValue filterValue) {
+ this.filterValue = filterValue;
+ return this;
+ }
+
+ @Override
+ public FilterValueStep withTagSize(CPITagSize tagSize) {
+ this.tagSize = tagSize;
+ return this;
+ }
+
+ @Override
+ public TagSizeStep withSerial(String serial) {
+ this.serial = serial;
+ return this;
+ }
+
+ @Override
+ public serialStep withComponentPartReference(String componentPartReference) {
+ this.componentPartReference = componentPartReference;
+ return this;
+ }
+
+ @Override
+ public componentPartReferenceStep withCompanyPrefix(String companyPrefix) {
+ this.companyPrefix = companyPrefix;
+ return this;
+ }
+
+ @Override
+ public BuildStep withRFIDTag(String rfidTag) {
+ this.rfidTag = rfidTag;
+ return this;
+ }
+
+ @Override
+ public BuildStep withEPCTagURI(String epcTagURI) {
+ this.epcTagURI = epcTagURI;
+ return this;
+ }
+
+ @Override
+ public TagSizeStep withEPCPureIdentityURI(String epcPureIdentityURI) {
+ this.epcPureIdentityURI = epcPureIdentityURI;
+ return this;
+ }
+
+ }
+
+}
+
+
+
+package org.epctagcoder.parse.GDTI;
+
+import java.util.Optional;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import org.epctagcoder.option.PrefixLength;
+import org.epctagcoder.option.TableItem;
+import org.epctagcoder.option.GDTI.GDTIFilterValue;
+import org.epctagcoder.option.GDTI.GDTIHeader;
+import org.epctagcoder.option.GDTI.GDTITagSize;
+import org.epctagcoder.option.GDTI.partitionTable.GDTIPartitionTableList;
+import org.epctagcoder.result.GDTI;
+import org.epctagcoder.util.Converter;
+
+
+public class ParseGDTI {
+ private GDTI gdti = new GDTI();
+ private String companyPrefix;
+ private PrefixLength prefixLength;
+ private GDTITagSize tagSize;
+ private GDTIFilterValue filterValue;
+ private String docType;
+ private String serial;
+ private String rfidTag;
+ private String epcTagURI;
+ private String epcPureIdentityURI;
+ private TableItem tableItem;
+ private int remainder;
+
+ public static ChoiceStep Builder() throws Exception {
+ return new Steps();
+ }
+
+ private ParseGDTI(Steps steps) {
+ this.companyPrefix = steps.companyPrefix;
+ this.tagSize = steps.tagSize;
+ this.filterValue = steps.filterValue;
+ this.docType = steps.docType;
+ this.serial = steps.serial;
+ this.rfidTag = steps.rfidTag;
+ this.epcTagURI = steps.epcTagURI;
+ this.epcPureIdentityURI = steps.epcPureIdentityURI;
+ parse();
+ }
+
+
+
+ private void parse() {
+ Optional optionalCompanyPrefix = Optional.ofNullable(companyPrefix);
+ Optional optionalRfidTag = Optional.ofNullable(rfidTag);
+ Optional optionalEpcTagURI = Optional.ofNullable(epcTagURI);
+ Optional optionalEpcPureIdentityURI = Optional.ofNullable(epcPureIdentityURI);
+
+ if ( optionalRfidTag.isPresent() ) {
+ String inputBin = Converter.hexToBin(rfidTag);
+ String headerBin = inputBin.substring(0, 8);
+ String filterBin = inputBin.substring(8,11);
+ String partitionBin = inputBin.substring(11,14);
+ GDTIPartitionTableList graiPartitionTableList = new GDTIPartitionTableList();
+
+ tagSize = GDTITagSize.forCode(GDTIHeader.forCode(headerBin).getTagSize());
+ tableItem = graiPartitionTableList.getPartitionByValue( Integer.parseInt(partitionBin, 2) );
+
+ String filterDec = Long.toString( Long.parseLong(filterBin, 2) );
+ String companyPrefixBin = inputBin.substring(14,14+tableItem.getM());
+ String docTypeBin = inputBin.substring(14+tableItem.getM(),14+tableItem.getM()+tableItem.getN());
+ String serialBin = inputBin.substring(14+tableItem.getM()+tableItem.getN() );
+
+ String companyPrefixDec = Converter.binToDec(companyPrefixBin);
+ String docTypeDec = Converter.binToDec(docTypeBin);
+
+ docType = Converter.strZero(docTypeDec, tableItem.getDigits() ) ;
+
+ if (tagSize.getSerialBitCount()==119) {
+ serialBin = Converter.convertBinToBit(serialBin, 7, 8);
+ serial = Converter.binToString(serialBin);
+ } else if (tagSize.getSerialBitCount()==41) {
+ serial = Converter.binToDec(serialBin);
+ }
+
+ companyPrefix = Converter.strZero(companyPrefixDec, tableItem.getL()); // strzero aqui
+ filterValue = GDTIFilterValue.forCode( Integer.parseInt(filterDec) );
+ prefixLength = PrefixLength.forCode(tableItem.getL());
+
+ } else {
+
+ if ( optionalCompanyPrefix.isPresent() ) {
+ GDTIPartitionTableList sgtinPartitionTableList = new GDTIPartitionTableList();
+ prefixLength = PrefixLength.forCode( companyPrefix.length() );
+
+ validateCompanyPrefix();
+
+ tableItem = sgtinPartitionTableList.getPartitionByL( prefixLength.getValue() );
+
+ validateDocType();
+ validateSerial();
+
+ } else {
+
+ if ( optionalEpcTagURI.isPresent() ) {
+ Pattern pattern = Pattern.compile("(urn:epc:tag:gdti-)(96|174)\\:([0-7])\\.(\\d+)\\.(\\d+)\\.(\\w+)");
+ Matcher matcher = pattern.matcher(epcTagURI);
+
+ if ( matcher.matches() ) {
+ tagSize = GDTITagSize.forCode( Integer.parseInt(matcher.group(2)) );
+ filterValue = GDTIFilterValue.forCode( Integer.parseInt(matcher.group(3)) );
+ companyPrefix = matcher.group(4);
+ prefixLength = PrefixLength.forCode( matcher.group(4).length() );
+ docType = matcher.group(5);
+ serial = matcher.group(6);
+ } else {
+ throw new IllegalArgumentException("EPC Tag URI is invalid");
+ }
+
+ } else if ( optionalEpcPureIdentityURI.isPresent() ) {
+ Pattern pattern = Pattern.compile("(urn:epc:id:gdti)\\:(\\d+)\\.(\\d+)\\.(\\w+)");
+ Matcher matcher = pattern.matcher(epcPureIdentityURI);
+
+ if ( matcher.matches() ) {
+ companyPrefix = matcher.group(2);
+ prefixLength = PrefixLength.forCode( matcher.group(2).length() );
+ docType = matcher.group(3);
+ serial = matcher.group(4);
+ } else {
+ throw new IllegalArgumentException("EPC Pure Identity is invalid");
+ }
+ }
+
+ }
+
+ GDTIPartitionTableList sgtinPartitionTableList = new GDTIPartitionTableList();
+ tableItem = sgtinPartitionTableList.getPartitionByL( prefixLength.getValue() );
+
+ }
+
+ String outputBin = getBinary();
+ String outputHex = Converter.binToHex( outputBin );
+
+ gdti.setEpcScheme("gdti");
+ gdti.setApplicationIdentifier("AI 253");
+ gdti.setTagSize(Integer.toString(tagSize.getValue()));
+ gdti.setFilterValue(Integer.toString(filterValue.getValue()));
+ gdti.setPartitionValue(Integer.toString(tableItem.getPartitionValue()));
+ gdti.setPrefixLength(Integer.toString(prefixLength.getValue()));
+ gdti.setCompanyPrefix(companyPrefix);
+ gdti.setDocType(docType);
+ gdti.setSerial(serial);
+ gdti.setCheckDigit(Integer.toString(getCheckDigit()));
+ gdti.setEpcPureIdentityURI(String.format("urn:epc:id:gdti:%s.%s.%s", companyPrefix, docType, serial));
+ gdti.setEpcTagURI(String.format("urn:epc:tag:gdti-%s:%s.%s.%s.%s", tagSize.getValue(), filterValue.getValue(), companyPrefix, docType, serial));
+ gdti.setEpcRawURI(String.format("urn:epc:raw:%s.x%s", tagSize.getValue()+remainder, outputHex ));
+ gdti.setBinary(outputBin);
+ gdti.setRfidTag(outputHex);
+ }
+
+
+ private String getBinary() {
+ StringBuilder bin = new StringBuilder();
+
+ remainder = (int) (Math.ceil((tagSize.getValue()/16.0))*16)-tagSize.getValue();
+
+ bin.append( Converter.decToBin(tagSize.getHeader(), 8) );
+ bin.append( Converter.decToBin(filterValue.getValue(), 3) );
+ bin.append( Converter.decToBin(tableItem.getPartitionValue(), 3) );
+ bin.append( Converter.decToBin(Integer.parseInt(companyPrefix), tableItem.getM()) );
+ bin.append( Converter.decToBin(Integer.parseInt(docType), tableItem.getN()) );
+
+ if (tagSize.getValue()==174) {
+ bin.append( Converter.fill(Converter.StringToBinary(serial, 7), tagSize.getSerialBitCount()+remainder) );
+ } else if (tagSize.getValue()==96) {
+ bin.append( Converter.decToBin(serial, tagSize.getSerialBitCount()+remainder ) );
+ }
+
+ return bin.toString();
+ }
+
+
+
+ private Integer getCheckDigit() {
+ String value = new StringBuilder()
+ .append(companyPrefix)
+ .append(docType)
+ .toString();
+
+ Integer d13 = (10 - ((3
+ * (Character.getNumericValue(value.charAt(1)) + Character.getNumericValue(value.charAt(3))
+ + Character.getNumericValue(value.charAt(5))
+ + Character.getNumericValue(value.charAt(7)) + Character.getNumericValue(value.charAt(9))
+ + Character.getNumericValue(value.charAt(11)) )
+ + (Character.getNumericValue(value.charAt(0)) + Character.getNumericValue(value.charAt(2))
+ + Character.getNumericValue(value.charAt(4)) + Character.getNumericValue(value.charAt(6))
+ + Character.getNumericValue(value.charAt(8)) + Character.getNumericValue(value.charAt(10))))
+ % 10)) % 10;
+
+ return d13;
+ }
+
+
+ public GDTI getGDTI() {
+ return gdti;
+ }
+
+ public String getRfidTag() {
+ return Converter.binToHex( getBinary() );
+ }
+
+
+
+ private void validateCompanyPrefix() {
+ Optional optionalPefixLenght = Optional.ofNullable(prefixLength);
+ if ( !optionalPefixLenght.isPresent() ) {
+ throw new IllegalArgumentException("Company Prefix is invalid. Length not found in the partition table");
+ }
+ }
+
+ private void validateDocType() {
+ if ( docType.length()!=tableItem.getDigits() ) {
+ throw new IllegalArgumentException(String.format("Asset Type \"%s\" has %d length and should have %d length",
+ docType, docType.length(), tableItem.getDigits()));
+ }
+ }
+
+ private void validateSerial() {
+ if (tagSize.getValue()==170 ) {
+ if ( serial.length()>tagSize.getSerialMaxLenght() ) {
+ throw new IllegalArgumentException( String.format("Serial value is out of range. Should be up to %d alphanumeric characters",
+ tagSize.getSerialMaxLenght() ));
+ }
+ } else if (tagSize.getValue()==96 ) {
+ if ( Long.parseLong(serial) >tagSize.getSerialMaxValue() ) {
+ throw new IllegalArgumentException( String.format("Serial value is out of range. Should be less than or equal %d",
+ tagSize.getSerialMaxValue() ));
+ }
+ if ( serial.startsWith("0") ) {
+ throw new IllegalArgumentException("Serial with leading zeros is not allowed");
+ }
+ }
+
+ }
+
+
+
+ public static interface ChoiceStep {
+ docTypeStep withCompanyPrefix(String companyPrefix);
+ BuildStep withRFIDTag(String rfidTag);
+ BuildStep withEPCTagURI(String epcTagURI);
+ TagSizeStep withEPCPureIdentityURI(String epcPureIdentityURI);
+ }
+
+
+ public static interface docTypeStep {
+ serialStep withDocType(String docType);
+ }
+
+ public static interface serialStep {
+ TagSizeStep withserial(String serial);
+ }
+
+ public static interface TagSizeStep {
+ FilterValueStep withTagSize( GDTITagSize tagSize );
+ }
+
+ public static interface FilterValueStep {
+ BuildStep withFilterValue( GDTIFilterValue filterValue );
+ }
+
+ public static interface BuildStep {
+ ParseGDTI build();
+ }
+
+
+ private static class Steps implements ChoiceStep, docTypeStep, serialStep, TagSizeStep, FilterValueStep, BuildStep {
+ private String companyPrefix;
+ private GDTITagSize tagSize;
+ private GDTIFilterValue filterValue;
+ private String docType;
+ private String serial;
+ private String rfidTag;
+ private String epcTagURI;
+ private String epcPureIdentityURI;
+
+ @Override
+ public ParseGDTI build() {
+ return new ParseGDTI(this);
+ }
+
+ @Override
+ public BuildStep withFilterValue(GDTIFilterValue filterValue) {
+ this.filterValue = filterValue;
+ return this;
+ }
+
+ @Override
+ public FilterValueStep withTagSize(GDTITagSize tagSize) {
+ this.tagSize = tagSize;
+ return this;
+ }
+
+ @Override
+ public TagSizeStep withserial(String serial) {
+ this.serial = serial;
+ return this;
+ }
+
+ @Override
+ public serialStep withDocType(String docType) {
+ this.docType = docType;
+ return this;
+ }
+
+ @Override
+ public docTypeStep withCompanyPrefix(String companyPrefix) {
+ this.companyPrefix = companyPrefix;
+ return this;
+ }
+
+ @Override
+ public BuildStep withRFIDTag(String rfidTag) {
+ this.rfidTag = rfidTag;
+ return this;
+ }
+
+ @Override
+ public BuildStep withEPCTagURI(String epcTagURI) {
+ this.epcTagURI = epcTagURI;
+ return this;
+ }
+
+ @Override
+ public TagSizeStep withEPCPureIdentityURI(String epcPureIdentityURI) {
+ this.epcPureIdentityURI = epcPureIdentityURI;
+ return this;
+ }
+
+ }
+
+}
+
+
+
+package org.epctagcoder.parse.GIAI;
+
+import java.util.Optional;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import org.epctagcoder.option.PrefixLength;
+import org.epctagcoder.option.TableItem;
+import org.epctagcoder.option.GIAI.GIAIFilterValue;
+import org.epctagcoder.option.GIAI.GIAIHeader;
+import org.epctagcoder.option.GIAI.GIAITagSize;
+import org.epctagcoder.option.GIAI.partitionTable.GIAIPartitionTableList;
+import org.epctagcoder.result.GIAI;
+import org.epctagcoder.util.Converter;
+
+
+public class ParseGIAI {
+ private GIAI giai = new GIAI();
+ private String companyPrefix;
+ private PrefixLength prefixLength;
+ private GIAITagSize tagSize;
+ private GIAIFilterValue filterValue;
+ private String individualAssetReference;
+ private String rfidTag;
+ private String epcTagURI;
+ private String epcPureIdentityURI;
+ private TableItem tableItem;
+ private int remainder;
+
+ public static ChoiceStep Builder() {
+ return new Steps();
+ }
+
+ private ParseGIAI(Steps steps) {
+ this.companyPrefix = steps.companyPrefix;
+ this.tagSize = steps.tagSize;
+ this.filterValue = steps.filterValue;
+ this.individualAssetReference = steps.individualAssetReference;
+ this.rfidTag = steps.rfidTag;
+ this.epcTagURI = steps.epcTagURI;
+ this.epcPureIdentityURI = steps.epcPureIdentityURI;
+ parse();
+ }
+
+
+
+ private void parse() {
+ Optional optionalCompanyPrefix = Optional.ofNullable(companyPrefix);
+ Optional optionalRfidTag = Optional.ofNullable(rfidTag);
+ Optional optionalEpcTagURI = Optional.ofNullable(epcTagURI);
+ Optional optionalEpcPureIdentityURI = Optional.ofNullable(epcPureIdentityURI);
+
+ if ( optionalRfidTag.isPresent() ) {
+ String inputBin = Converter.hexToBin(rfidTag);
+ String headerBin = inputBin.substring(0, 8);
+ String filterBin = inputBin.substring(8,11);
+ String partitionBin = inputBin.substring(11,14);
+
+ tagSize = GIAITagSize.forCode(GIAIHeader.forCode(headerBin).getTagSize());
+ GIAIPartitionTableList GIAIPartitionTableList = new GIAIPartitionTableList(tagSize);
+ tableItem = GIAIPartitionTableList.getPartitionByValue( Integer.parseInt(partitionBin, 2) );
+
+ String filterDec = Long.toString( Long.parseLong(filterBin, 2) );
+ String companyPrefixBin = inputBin.substring(14,14+tableItem.getM());
+ String individualAssetReferenceBin = inputBin.substring(14+tableItem.getM(),14+tableItem.getM()+tableItem.getN());
+ String companyPrefixDec = Converter.binToDec(companyPrefixBin);
+
+ if (tagSize.getSerialBitCount()==112) {
+ individualAssetReferenceBin = Converter.convertBinToBit(individualAssetReferenceBin, 7, 8);
+ individualAssetReference = Converter.binToString(individualAssetReferenceBin);
+ } else if (tagSize.getSerialBitCount()==38) {
+ individualAssetReference = Converter.binToDec(individualAssetReferenceBin);
+ }
+
+ companyPrefix = Converter.strZero(companyPrefixDec, tableItem.getL());
+ filterValue = GIAIFilterValue.forCode( Integer.parseInt(filterDec) );
+ prefixLength = PrefixLength.forCode(tableItem.getL());
+
+
+ } else {
+
+ if ( optionalCompanyPrefix.isPresent() ) {
+ GIAIPartitionTableList giaiPartitionTableList = new GIAIPartitionTableList(tagSize);
+ prefixLength = PrefixLength.forCode( companyPrefix.length() );
+
+ validateCompanyPrefix();
+
+ tableItem = giaiPartitionTableList.getPartitionByL( prefixLength.getValue() );
+
+ validateIndividualAssetReference();
+ } else {
+
+ if ( optionalEpcTagURI.isPresent() ) {
+ Pattern pattern = Pattern.compile("(urn:epc:tag:giai-)(96|202)\\:([0-7])\\.(\\d+)\\.(\\w+)");
+ Matcher matcher = pattern.matcher(epcTagURI);
+
+ if ( matcher.matches() ) {
+ tagSize = GIAITagSize.forCode( Integer.parseInt(matcher.group(2)) );
+ filterValue = GIAIFilterValue.forCode( Integer.parseInt(matcher.group(3)) );
+ companyPrefix = matcher.group(4);
+ prefixLength = PrefixLength.forCode( matcher.group(4).length() );
+ individualAssetReference = matcher.group(5);
+ } else {
+ throw new IllegalArgumentException("EPC Tag URI is invalid");
+ }
+
+ } else if ( optionalEpcPureIdentityURI.isPresent() ) {
+ Pattern pattern = Pattern.compile("(urn:epc:id:giai)\\:(\\d+)\\.(\\w+)");
+
+ Matcher matcher = pattern.matcher(epcPureIdentityURI);
+
+ if ( matcher.matches() ) {
+ companyPrefix = matcher.group(2);
+ prefixLength = PrefixLength.forCode( matcher.group(2).length() );
+ individualAssetReference = matcher.group(3);;
+ } else {
+ throw new IllegalArgumentException("EPC Pure Identity is invalid");
+ }
+ }
+
+ }
+
+ GIAIPartitionTableList giaiPartitionTableList = new GIAIPartitionTableList(tagSize);
+ tableItem = giaiPartitionTableList.getPartitionByL( prefixLength.getValue() );
+
+ }
+
+ String outputBin = getBinary();
+ String outputHex = Converter.binToHex( outputBin );
+
+ giai.setEpcScheme("giai");
+ giai.setApplicationIdentifier("AI 8004");
+ giai.setTagSize(Integer.toString(tagSize.getValue()));
+ giai.setFilterValue(Integer.toString(filterValue.getValue()));
+ giai.setPartitionValue(Integer.toString(tableItem.getPartitionValue()));
+ giai.setPrefixLength(Integer.toString(prefixLength.getValue()));
+ giai.setCompanyPrefix(companyPrefix);
+ giai.setIndividualAssetReference(individualAssetReference);
+ giai.setEpcPureIdentityURI(String.format("urn:epc:id:giai:%s.%s", companyPrefix, individualAssetReference));
+ giai.setEpcTagURI(String.format("urn:epc:tag:giai-%s:%s.%s.%s", tagSize.getValue(), filterValue.getValue(), companyPrefix, individualAssetReference));
+ giai.setEpcRawURI(String.format("urn:epc:raw:%s.x%s", tagSize.getValue()+remainder, outputHex ));
+ giai.setBinary(outputBin);
+ giai.setRfidTag(outputHex);
+ }
+
+
+ private String getBinary() {
+ StringBuilder bin = new StringBuilder();
+
+ remainder = (int) (Math.ceil((tagSize.getValue()/16.0))*16)-tagSize.getValue();
+
+ bin.append( Converter.decToBin(tagSize.getHeader(), 8) );
+ bin.append( Converter.decToBin(filterValue.getValue(), 3) );
+ bin.append( Converter.decToBin(tableItem.getPartitionValue(), 3) );
+ bin.append( Converter.decToBin(Integer.parseInt(companyPrefix), tableItem.getM()) );
+
+ if (tagSize.getValue()==202) {
+ bin.append( Converter.fill(Converter.StringToBinary(individualAssetReference, 7), tableItem.getN()+remainder) );
+ } else if (tagSize.getValue()==96) {
+ bin.append( Converter.decToBin(individualAssetReference, tableItem.getN()+remainder ) );
+ }
+
+ return bin.toString();
+ }
+
+
+
+ public GIAI getGIAI() {
+ return giai;
+ }
+
+ public String getRfidTag() {
+ return Converter.binToHex( getBinary() );
+ }
+
+
+ private void validateCompanyPrefix() {
+ Optional optionalPefixLenght = Optional.ofNullable(prefixLength);
+ if ( !optionalPefixLenght.isPresent() ) {
+ throw new IllegalArgumentException("Company Prefix is invalid. Length not found in the partition table");
+ }
+
+ }
+
+
+ private void validateIndividualAssetReference() {
+ if ( individualAssetReference.length() >tableItem.getDigits() ) {
+ throw new IllegalArgumentException( String.format("Individual Asset Reference value is out of range. The length should be %d",
+ tableItem.getDigits() ));
+ }
+
+ if (tagSize.getValue()==96 ) {
+ if ( individualAssetReference.startsWith("0") ) {
+ throw new IllegalArgumentException("Individual Asset Reference with leading zeros is not allowed");
+ }
+ }
+ }
+
+
+
+
+ public static interface ChoiceStep {
+ IndividualAssetReferenceStep withCompanyPrefix(String companyPrefix);
+ BuildStep withRFIDTag(String rfidTag);
+ BuildStep withEPCTagURI(String epcTagURI);
+ TagSizeStep withEPCPureIdentityURI(String epcPureIdentityURI);
+ }
+
+
+ public static interface IndividualAssetReferenceStep {
+ TagSizeStep withIndividualAssetReference(String individualAssetReference);
+ }
+
+
+ public static interface TagSizeStep {
+ FilterValueStep withTagSize( GIAITagSize tagSize );
+ }
+
+ public static interface FilterValueStep {
+ BuildStep withFilterValue( GIAIFilterValue filterValue );
+ }
+
+ public static interface BuildStep {
+ ParseGIAI build();
+ }
+
+
+ private static class Steps implements ChoiceStep, IndividualAssetReferenceStep, TagSizeStep, FilterValueStep, BuildStep {
+ private String companyPrefix;
+ private GIAITagSize tagSize;
+ private GIAIFilterValue filterValue;
+ private String individualAssetReference;
+ private String rfidTag;
+ private String epcTagURI;
+ private String epcPureIdentityURI;
+
+ @Override
+ public ParseGIAI build() {
+ return new ParseGIAI(this);
+ }
+
+ @Override
+ public BuildStep withFilterValue(GIAIFilterValue filterValue) {
+ this.filterValue = filterValue;
+ return this;
+ }
+
+ @Override
+ public FilterValueStep withTagSize(GIAITagSize tagSize) {
+ this.tagSize = tagSize;
+ return this;
+ }
+
+
+ @Override
+ public BuildStep withRFIDTag(String rfidTag) {
+ this.rfidTag = rfidTag;
+ return this;
+ }
+
+ @Override
+ public BuildStep withEPCTagURI(String epcTagURI) {
+ this.epcTagURI = epcTagURI;
+ return this;
+ }
+
+ @Override
+ public TagSizeStep withEPCPureIdentityURI(String epcPureIdentityURI) {
+ this.epcPureIdentityURI = epcPureIdentityURI;
+ return this;
+ }
+
+
+ @Override
+ public IndividualAssetReferenceStep withCompanyPrefix(String companyPrefix) {
+ this.companyPrefix = companyPrefix;
+ return this;
+ }
+
+ @Override
+ public TagSizeStep withIndividualAssetReference(String individualAssetReference) {
+ this.individualAssetReference = individualAssetReference;
+ return this;
+ }
+
+
+ }
+
+}
+
+
+
+package org.epctagcoder.parse.GRAI;
+
+import java.util.Optional;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import org.epctagcoder.option.PrefixLength;
+import org.epctagcoder.option.TableItem;
+import org.epctagcoder.option.GRAI.GRAIFilterValue;
+import org.epctagcoder.option.GRAI.GRAIHeader;
+import org.epctagcoder.option.GRAI.GRAITagSize;
+import org.epctagcoder.option.GRAI.partitionTable.GRAIPartitionTableList;
+import org.epctagcoder.result.GRAI;
+import org.epctagcoder.util.Converter;
+
+
+public class ParseGRAI {
+ private GRAI grai = new GRAI();
+ private String companyPrefix;
+ private PrefixLength prefixLength;
+ private GRAITagSize tagSize;
+ private GRAIFilterValue filterValue;
+ private String assetType;
+ private String serial;
+ private String rfidTag;
+ private String epcTagURI;
+ private String epcPureIdentityURI;
+ private TableItem tableItem;
+ private int remainder;
+
+ public static ChoiceStep Builder() throws Exception {
+ return new Steps();
+ }
+
+ private ParseGRAI(Steps steps) {
+ this.companyPrefix = steps.companyPrefix;
+ this.tagSize = steps.tagSize;
+ this.filterValue = steps.filterValue;
+ this.assetType = steps.assetType;
+ this.serial = steps.serial;
+ this.rfidTag = steps.rfidTag;
+ this.epcTagURI = steps.epcTagURI;
+ this.epcPureIdentityURI = steps.epcPureIdentityURI;
+ parse();
+ }
+
+
+
+ private void parse() {
+ Optional optionalCompanyPrefix = Optional.ofNullable(companyPrefix);
+ Optional optionalRfidTag = Optional.ofNullable(rfidTag);
+ Optional optionalEpcTagURI = Optional.ofNullable(epcTagURI);
+ Optional optionalEpcPureIdentityURI = Optional.ofNullable(epcPureIdentityURI);
+
+ if ( optionalRfidTag.isPresent() ) {
+ String inputBin = Converter.hexToBin(rfidTag);
+ String headerBin = inputBin.substring(0, 8);
+ String filterBin = inputBin.substring(8,11);
+ String partitionBin = inputBin.substring(11,14);
+ GRAIPartitionTableList graiPartitionTableList = new GRAIPartitionTableList();
+
+ tagSize = GRAITagSize.forCode(GRAIHeader.forCode(headerBin).getTagSize());
+ tableItem = graiPartitionTableList.getPartitionByValue( Integer.parseInt(partitionBin, 2) );
+
+ String filterDec = Long.toString( Long.parseLong(filterBin, 2) );
+ String companyPrefixBin = inputBin.substring(14,14+tableItem.getM());
+ String assetTypeBin = inputBin.substring(14+tableItem.getM(),14+tableItem.getM()+tableItem.getN());
+ String serialBin = inputBin.substring(14+tableItem.getM()+tableItem.getN() );
+
+ String companyPrefixDec = Converter.binToDec(companyPrefixBin);
+ String assetTypeDec = Converter.binToDec(assetTypeBin);
+
+ assetType = Converter.strZero(assetTypeDec, tableItem.getDigits() ) ;
+
+ if (tagSize.getSerialBitCount()==112) {
+ serialBin = Converter.convertBinToBit(serialBin, 7, 8);
+ serial = Converter.binToString(serialBin);
+ } else if (tagSize.getSerialBitCount()==38) {
+ serial = Converter.binToDec(serialBin);
+ }
+
+ companyPrefix = Converter.strZero(companyPrefixDec, tableItem.getL()); // strzero aqui
+ filterValue = GRAIFilterValue.forCode( Integer.parseInt(filterDec) );
+ prefixLength = PrefixLength.forCode(tableItem.getL());
+
+ } else {
+
+ if ( optionalCompanyPrefix.isPresent() ) {
+ GRAIPartitionTableList sgtinPartitionTableList = new GRAIPartitionTableList();
+ prefixLength = PrefixLength.forCode( companyPrefix.length() );
+
+ validateCompanyPrefix();
+
+ tableItem = sgtinPartitionTableList.getPartitionByL( prefixLength.getValue() );
+
+ validateAssetType();
+ validateSerial();
+
+ } else {
+
+ if ( optionalEpcTagURI.isPresent() ) {
+ Pattern pattern = Pattern.compile("(urn:epc:tag:grai-)(96|170)\\:([0-7])\\.(\\d+)\\.(\\d+)\\.(\\w+)");
+ Matcher matcher = pattern.matcher(epcTagURI);
+
+ if ( matcher.matches() ) {
+ tagSize = GRAITagSize.forCode( Integer.parseInt(matcher.group(2)) );
+ filterValue = GRAIFilterValue.forCode( Integer.parseInt(matcher.group(3)) );
+ companyPrefix = matcher.group(4);
+ prefixLength = PrefixLength.forCode( matcher.group(4).length() );
+ assetType = matcher.group(5);
+ serial = matcher.group(6);
+ } else {
+ throw new IllegalArgumentException("EPC Tag URI is invalid");
+ }
+
+ } else if ( optionalEpcPureIdentityURI.isPresent() ) {
+ Pattern pattern = Pattern.compile("(urn:epc:id:grai)\\:(\\d+)\\.(\\d+)\\.(\\w+)");
+ Matcher matcher = pattern.matcher(epcPureIdentityURI);
+
+ if ( matcher.matches() ) {
+ companyPrefix = matcher.group(2);
+ prefixLength = PrefixLength.forCode( matcher.group(2).length() );
+ assetType = matcher.group(3);;
+ serial = matcher.group(4);
+ } else {
+ throw new IllegalArgumentException("EPC Pure Identity is invalid");
+ }
+ }
+
+ }
+
+ GRAIPartitionTableList sgtinPartitionTableList = new GRAIPartitionTableList();
+ tableItem = sgtinPartitionTableList.getPartitionByL( prefixLength.getValue() );
+
+ }
+
+ String outputBin = getBinary();
+ String outputHex = Converter.binToHex( outputBin );
+
+ grai.setEpcScheme("grai");
+ grai.setApplicationIdentifier("AI 8003");
+ grai.setTagSize(Integer.toString(tagSize.getValue()));
+ grai.setFilterValue(Integer.toString(filterValue.getValue()));
+ grai.setPartitionValue(Integer.toString(tableItem.getPartitionValue()));
+ grai.setPrefixLength(Integer.toString(prefixLength.getValue()));
+ grai.setCompanyPrefix(companyPrefix);
+ grai.setAssetType(assetType);
+ grai.setSerial(serial);
+ grai.setCheckDigit(Integer.toString(getCheckDigit()));
+ grai.setEpcPureIdentityURI(String.format("urn:epc:id:grai:%s.%s.%s", companyPrefix, assetType, serial));
+ grai.setEpcTagURI(String.format("urn:epc:tag:grai-%s:%s.%s.%s.%s", tagSize.getValue(), filterValue.getValue(), companyPrefix, assetType, serial));
+ grai.setEpcRawURI(String.format("urn:epc:raw:%s.x%s", tagSize.getValue()+remainder, outputHex ));
+ grai.setBinary(outputBin);
+ grai.setRfidTag(outputHex);
+ }
+
+
+ private String getBinary() {
+ StringBuilder bin = new StringBuilder();
+
+ remainder = (int) (Math.ceil((tagSize.getValue()/16.0))*16)-tagSize.getValue();
+
+ bin.append( Converter.decToBin(tagSize.getHeader(), 8) );
+ bin.append( Converter.decToBin(filterValue.getValue(), 3) );
+ bin.append( Converter.decToBin(tableItem.getPartitionValue(), 3) );
+ bin.append( Converter.decToBin(Integer.parseInt(companyPrefix), tableItem.getM()) );
+ bin.append( Converter.decToBin(Integer.parseInt(assetType), tableItem.getN()) );
+
+ if (tagSize.getValue()==170) {
+ bin.append( Converter.fill(Converter.StringToBinary(serial, 7), tagSize.getSerialBitCount()+remainder) );
+ } else if (tagSize.getValue()==96) {
+ bin.append( Converter.decToBin(serial, tagSize.getSerialBitCount()+remainder ) );
+ }
+
+ return bin.toString();
+ }
+
+
+
+ private Integer getCheckDigit() {
+ String value = new StringBuilder()
+ .append(companyPrefix)
+ .append(assetType)
+ .toString();
+
+ Integer d13 = (10 - ((3
+ * (Character.getNumericValue(value.charAt(1)) + Character.getNumericValue(value.charAt(3))
+ + Character.getNumericValue(value.charAt(5))
+ + Character.getNumericValue(value.charAt(7)) + Character.getNumericValue(value.charAt(9))
+ + Character.getNumericValue(value.charAt(11)) )
+ + (Character.getNumericValue(value.charAt(0)) + Character.getNumericValue(value.charAt(2))
+ + Character.getNumericValue(value.charAt(4)) + Character.getNumericValue(value.charAt(6))
+ + Character.getNumericValue(value.charAt(8)) + Character.getNumericValue(value.charAt(10))))
+ % 10)) % 10;
+
+ return d13;
+ }
+
+
+ public GRAI getGRAI() {
+ return grai;
+ }
+
+ public String getRfidTag() {
+ return Converter.binToHex( getBinary() );
+ }
+
+
+
+ private void validateCompanyPrefix() {
+ Optional optionalPefixLenght = Optional.ofNullable(prefixLength);
+ if ( !optionalPefixLenght.isPresent() ) {
+ throw new IllegalArgumentException("Company Prefix is invalid. Length not found in the partition table");
+ }
+ }
+
+ private void validateAssetType() {
+ if ( assetType.length()!=tableItem.getDigits() ) {
+ throw new IllegalArgumentException(String.format("Asset Type \"%s\" has %d length and should have %d length",
+ assetType, assetType.length(), tableItem.getDigits()));
+ }
+ }
+
+ private void validateSerial() {
+ if (tagSize.getValue()==170 ) {
+ if ( serial.length()>tagSize.getSerialMaxLenght() ) {
+ throw new IllegalArgumentException( String.format("Serial value is out of range. Should be up to %d alphanumeric characters",
+ tagSize.getSerialMaxLenght() ));
+ }
+ } else if (tagSize.getValue()==96 ) {
+ if ( Long.parseLong(serial) >tagSize.getSerialMaxValue() ) {
+ throw new IllegalArgumentException( String.format("Serial value is out of range. Should be less than or equal %d",
+ tagSize.getSerialMaxValue() ));
+ }
+ if ( serial.startsWith("0") ) {
+ throw new IllegalArgumentException("Serial with leading zeros is not allowed");
+ }
+ }
+
+ }
+
+
+
+ public static interface ChoiceStep {
+ assetTypeStep withCompanyPrefix(String companyPrefix);
+ BuildStep withRFIDTag(String rfidTag);
+ BuildStep withEPCTagURI(String epcTagURI);
+ TagSizeStep withEPCPureIdentityURI(String epcPureIdentityURI);
+ }
+
+
+ public static interface assetTypeStep {
+ serialStep withAssetType(String assetType);
+ }
+
+ public static interface serialStep {
+ TagSizeStep withserial(String serial);
+ }
+
+ public static interface TagSizeStep {
+ FilterValueStep withTagSize( GRAITagSize tagSize );
+ }
+
+ public static interface FilterValueStep {
+ BuildStep withFilterValue( GRAIFilterValue filterValue );
+ }
+
+ public static interface BuildStep {
+ ParseGRAI build();
+ }
+
+
+ private static class Steps implements ChoiceStep, assetTypeStep, serialStep, TagSizeStep, FilterValueStep, BuildStep {
+ private String companyPrefix;
+ private GRAITagSize tagSize;
+ private GRAIFilterValue filterValue;
+ private String assetType;
+ private String serial;
+ private String rfidTag;
+ private String epcTagURI;
+ private String epcPureIdentityURI;
+
+ @Override
+ public ParseGRAI build() {
+ return new ParseGRAI(this);
+ }
+
+ @Override
+ public BuildStep withFilterValue(GRAIFilterValue filterValue) {
+ this.filterValue = filterValue;
+ return this;
+ }
+
+ @Override
+ public FilterValueStep withTagSize(GRAITagSize tagSize) {
+ this.tagSize = tagSize;
+ return this;
+ }
+
+ @Override
+ public TagSizeStep withserial(String serial) {
+ this.serial = serial;
+ return this;
+ }
+
+ @Override
+ public serialStep withAssetType(String assetType) {
+ this.assetType = assetType;
+ return this;
+ }
+
+ @Override
+ public assetTypeStep withCompanyPrefix(String companyPrefix) {
+ this.companyPrefix = companyPrefix;
+ return this;
+ }
+
+ @Override
+ public BuildStep withRFIDTag(String rfidTag) {
+ this.rfidTag = rfidTag;
+ return this;
+ }
+
+ @Override
+ public BuildStep withEPCTagURI(String epcTagURI) {
+ this.epcTagURI = epcTagURI;
+ return this;
+ }
+
+ @Override
+ public TagSizeStep withEPCPureIdentityURI(String epcPureIdentityURI) {
+ this.epcPureIdentityURI = epcPureIdentityURI;
+ return this;
+ }
+
+ }
+
+}
+
+
+
+package org.epctagcoder.parse.GSRN;
+
+import java.util.Optional;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import org.epctagcoder.option.PrefixLength;
+import org.epctagcoder.option.TableItem;
+import org.epctagcoder.option.GSRN.GSRNFilterValue;
+import org.epctagcoder.option.GSRN.GSRNHeader;
+import org.epctagcoder.option.GSRN.GSRNTagSize;
+import org.epctagcoder.option.GSRN.partitionTable.GSRNPartitionTableList;
+import org.epctagcoder.result.GSRN;
+import org.epctagcoder.util.Converter;
+
+public class ParseGSRN {
+ private static final Integer RESERVED = 0; // 24 zero bits
+ private GSRN gsrn = new GSRN();
+ private String companyPrefix;
+ private PrefixLength prefixLength;
+ private GSRNTagSize tagSize;
+ private GSRNFilterValue filterValue;
+ private String serviceReference;
+ private String rfidTag;
+ private String epcTagURI;
+ private String epcPureIdentityURI;
+ private TableItem tableItem;
+
+ public static ChoiceStep Builder() throws Exception {
+ return new Steps();
+ }
+
+ private ParseGSRN(Steps steps) {
+ this.companyPrefix = steps.companyPrefix;
+ this.tagSize = steps.tagSize;
+ this.filterValue = steps.filterValue;
+ this.serviceReference = steps.serviceReference;
+ this.rfidTag = steps.rfidTag;
+ this.epcTagURI = steps.epcTagURI;
+ this.epcPureIdentityURI = steps.epcPureIdentityURI;
+ parse();
+ }
+
+
+ private void parse() {
+ Optional optionalCompanyPrefix = Optional.ofNullable(companyPrefix);
+ Optional optionalRfidTag = Optional.ofNullable(rfidTag);
+ Optional optionalEpcTagURI = Optional.ofNullable(epcTagURI);
+ Optional optionalEpcPureIdentityURI = Optional.ofNullable(epcPureIdentityURI);
+
+ if ( optionalRfidTag.isPresent() ) {
+ String inputBin = Converter.hexToBin(rfidTag);
+ String headerBin = inputBin.substring(0, 8);
+ String filterBin = inputBin.substring(8,11);
+ String partitionBin = inputBin.substring(11,14);
+ GSRNPartitionTableList GSRNPartitionTableList = new GSRNPartitionTableList();
+
+ tableItem = GSRNPartitionTableList.getPartitionByValue( Integer.parseInt(partitionBin, 2) );
+
+ String companyPrefixBin = inputBin.substring(14,14+tableItem.getM());
+ String serialWithExtensionBin = inputBin.substring(14+tableItem.getM(),14+tableItem.getM()+tableItem.getN());
+ String filterDec = Long.toString( Long.parseLong(filterBin, 2) );
+ String companyPrefixDec = Converter.binToDec(companyPrefixBin);
+
+ serviceReference = Converter.strZero(Converter.binToDec(serialWithExtensionBin), tableItem.getDigits() );
+ companyPrefix = Converter.strZero(companyPrefixDec, tableItem.getL());
+ filterValue = GSRNFilterValue.forCode( Integer.parseInt(filterDec) );
+ tagSize = GSRNTagSize.forCode( GSRNHeader.forCode(headerBin).getTagSize() );
+ prefixLength = PrefixLength.forCode(tableItem.getL());
+
+ } else {
+
+ if ( optionalCompanyPrefix.isPresent() ) {
+ GSRNPartitionTableList GSRNPartitionTableList = new GSRNPartitionTableList();
+
+ prefixLength = PrefixLength.forCode( companyPrefix.length() );
+
+ validateCompanyPrefix();
+
+ tableItem = GSRNPartitionTableList.getPartitionByL( prefixLength.getValue() );
+
+ validateServiceReference();
+
+ } else {
+
+ if ( optionalEpcTagURI.isPresent() ) {
+ Pattern pattern = Pattern.compile("(urn:epc:tag:gsrn-)(96)\\:([0-7])\\.(\\d+)\\.(\\d+)");
+ Matcher matcher = pattern.matcher(epcTagURI);
+
+ if ( matcher.matches() ) {
+ tagSize = GSRNTagSize.forCode( Integer.parseInt(matcher.group(2)) );
+ filterValue = GSRNFilterValue.forCode( Integer.parseInt(matcher.group(3)) );
+ companyPrefix = matcher.group(4);
+ prefixLength = PrefixLength.forCode( matcher.group(4).length() );
+ serviceReference = matcher.group(5);
+ } else {
+ throw new IllegalArgumentException("EPC Tag URI is invalid");
+ }
+
+ } else if ( optionalEpcPureIdentityURI.isPresent() ) {
+ Pattern pattern = Pattern.compile("(urn:epc:id:gsrn)\\:(\\d+)\\.(\\d+)");
+ Matcher matcher = pattern.matcher(epcPureIdentityURI);
+
+ if ( matcher.matches() ) {
+ companyPrefix = matcher.group(2);
+ prefixLength = PrefixLength.forCode( matcher.group(2).length() );
+ serviceReference = matcher.group(3);
+ } else {
+ throw new IllegalArgumentException("EPC Pure Identity is invalid");
+ }
+
+
+ }
+
+ GSRNPartitionTableList GSRNPartitionTableList = new GSRNPartitionTableList();
+ tableItem = GSRNPartitionTableList.getPartitionByL( prefixLength.getValue() );
+
+ }
+
+ }
+
+
+ String outputBin = getBinary();
+ String outputHex = Converter.binToHex( outputBin );
+
+ gsrn.setEpcScheme("gsrn");
+ gsrn.setApplicationIdentifier("AI 8018");
+ gsrn.setTagSize(Integer.toString(tagSize.getValue()));
+ gsrn.setFilterValue(Integer.toString(filterValue.getValue()) );
+ gsrn.setPartitionValue(Integer.toString(tableItem.getPartitionValue()));
+ gsrn.setPrefixLength(Integer.toString(prefixLength.getValue()));
+ gsrn.setCompanyPrefix(companyPrefix);
+ gsrn.setServiceReference(serviceReference);
+ gsrn.setCheckDigit(Integer.toString(getCheckDigit()));
+ gsrn.setEpcPureIdentityURI(String.format("urn:epc:id:gsrn:%s.%s", companyPrefix, serviceReference));
+ gsrn.setEpcTagURI(String.format("urn:epc:tag:gsrn-%s:%s.%s.%s", tagSize.getValue(),
+ filterValue.getValue(), companyPrefix, serviceReference));
+ gsrn.setEpcRawURI(String.format("urn:epc:raw:%s.x%s", tagSize.getValue(), outputHex ));
+ gsrn.setBinary(outputBin);
+ gsrn.setRfidTag(outputHex);
+
+ }
+
+ private Integer getCheckDigit() {
+ String value = new StringBuilder()
+ .append(companyPrefix)
+ .append(serviceReference)
+ .toString();
+
+ Integer d18 = (10 - ((3
+ * (Character.getNumericValue(value.charAt(0)) + Character.getNumericValue(value.charAt(2))
+ + Character.getNumericValue(value.charAt(4)) + Character.getNumericValue(value.charAt(6))
+ + Character.getNumericValue(value.charAt(8))
+ + Character.getNumericValue(value.charAt(10)) + Character.getNumericValue(value.charAt(12))
+ + Character.getNumericValue(value.charAt(14)) + Character.getNumericValue(value.charAt(16)))
+ + (Character.getNumericValue(value.charAt(1)) + Character.getNumericValue(value.charAt(3))
+ + Character.getNumericValue(value.charAt(5)) + Character.getNumericValue(value.charAt(7))
+ + Character.getNumericValue(value.charAt(9)) + Character.getNumericValue(value.charAt(11))
+ + Character.getNumericValue(value.charAt(13)) + Character.getNumericValue(value.charAt(15))))
+ % 10)) % 10;
+ return d18;
+ }
+
+
+ private String getBinary() {
+ StringBuilder bin = new StringBuilder();
+
+ bin.append( Converter.decToBin(tagSize.getHeader(), 8) );
+ bin.append( Converter.decToBin(filterValue.getValue(), 3) );
+ bin.append( Converter.decToBin(tableItem.getPartitionValue(), 3) );
+ bin.append( Converter.decToBin(Integer.parseInt(companyPrefix), tableItem.getM()) );
+ bin.append( Converter.decToBin(Integer.parseInt(serviceReference), tableItem.getN()) );
+ bin.append( Converter.decToBin(RESERVED, 24) );
+
+ return bin.toString();
+ }
+
+
+ public GSRN getGSRN() {
+ return gsrn;
+ }
+
+ public String getRfidTag() {
+ return Converter.binToHex( getBinary() );
+ }
+
+
+
+ private void validateServiceReference() {
+ StringBuilder value = new StringBuilder()
+ .append(serviceReference);
+
+ if ( value.length()!=tableItem.getDigits() ) {
+ throw new IllegalArgumentException(String.format("Service Reference \"%s\" has %d length and should have %d length",
+ serviceReference, value.length(), tableItem.getDigits()));
+ }
+ }
+
+
+ private void validateCompanyPrefix() {
+ Optional optionalpPefixLenght = Optional.ofNullable(prefixLength);
+ if ( !optionalpPefixLenght.isPresent() ) {
+ throw new IllegalArgumentException("Company Prefix is invalid. Length not found in the partition table");
+ }
+
+ }
+
+
+
+
+ public static interface ChoiceStep {
+ ServiceReferenceStep withCompanyPrefix(String companyPrefix);
+ BuildStep withRFIDTag(String rfidTag);
+ BuildStep withEPCTagURI(String epcTagURI);
+ TagSizeStep withEPCPureIdentityURI(String epcPureIdentityURI);
+ }
+
+
+ public static interface ServiceReferenceStep {
+ TagSizeStep withServiceReference(String serviceReference);
+ }
+
+ public static interface TagSizeStep {
+ FilterValueStep withTagSize( GSRNTagSize tagSize );
+ }
+
+ public static interface FilterValueStep {
+ BuildStep withFilterValue( GSRNFilterValue filterValue );
+ }
+
+ public static interface BuildStep {
+ ParseGSRN build();
+ }
+
+
+
+ private static class Steps implements ChoiceStep, ServiceReferenceStep, TagSizeStep, FilterValueStep, BuildStep {
+ private String companyPrefix;
+ private GSRNTagSize tagSize;
+ private GSRNFilterValue filterValue;
+ private String serviceReference;
+ private String rfidTag;
+ private String epcTagURI;
+ private String epcPureIdentityURI;
+
+ @Override
+ public ParseGSRN build() {
+ return new ParseGSRN(this);
+ }
+
+ @Override
+ public BuildStep withFilterValue(GSRNFilterValue filterValue) {
+ this.filterValue = filterValue;
+ return this;
+ }
+
+ @Override
+ public FilterValueStep withTagSize(GSRNTagSize tagSize) {
+ this.tagSize = tagSize;
+ return this;
+ }
+
+ @Override
+ public TagSizeStep withServiceReference(String serviceReference) {
+ this.serviceReference = serviceReference;
+ return this;
+ }
+
+ @Override
+ public ServiceReferenceStep withCompanyPrefix(String companyPrefix) {
+ this.companyPrefix = companyPrefix;
+ return this;
+ }
+
+ @Override
+ public BuildStep withRFIDTag(String rfidTag) {
+ this.rfidTag = rfidTag;
+ return this;
+ }
+
+ @Override
+ public BuildStep withEPCTagURI(String epcTagURI) {
+ this.epcTagURI = epcTagURI;
+ return this;
+ }
+
+ @Override
+ public TagSizeStep withEPCPureIdentityURI(String epcPureIdentityURI) {
+ this.epcPureIdentityURI = epcPureIdentityURI;
+ return this;
+ }
+
+
+
+
+ }
+
+}
+
+
+
+package org.epctagcoder.parse.GSRNP;
+
+import java.util.Optional;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import org.epctagcoder.option.PrefixLength;
+import org.epctagcoder.option.TableItem;
+import org.epctagcoder.option.GSRNP.GSRNPFilterValue;
+import org.epctagcoder.option.GSRNP.GSRNPHeader;
+import org.epctagcoder.option.GSRNP.GSRNPTagSize;
+import org.epctagcoder.option.GSRNP.partitionTable.GSRNPPartitionTableList;
+import org.epctagcoder.result.GSRNP;
+import org.epctagcoder.util.Converter;
+
+public class ParseGSRNP {
+ private static final Integer RESERVED = 0; // 24 zero bits
+ private GSRNP gsrnp = new GSRNP();
+ private String companyPrefix;
+ private PrefixLength prefixLength;
+ private GSRNPTagSize tagSize;
+ private GSRNPFilterValue filterValue;
+ private String serviceReference;
+ private String rfidTag;
+ private String epcTagURI;
+ private String epcPureIdentityURI;
+ private TableItem tableItem;
+
+ public static ChoiceStep Builder() {
+ return new Steps();
+ }
+
+ private ParseGSRNP(Steps steps) {
+ this.companyPrefix = steps.companyPrefix;
+ this.tagSize = steps.tagSize;
+ this.filterValue = steps.filterValue;
+ this.serviceReference = steps.serviceReference;
+ this.rfidTag = steps.rfidTag;
+ this.epcTagURI = steps.epcTagURI;
+ this.epcPureIdentityURI = steps.epcPureIdentityURI;
+ parse();
+ }
+
+
+ private void parse() {
+ Optional optionalCompanyPrefix = Optional.ofNullable(companyPrefix);
+ Optional optionalRfidTag = Optional.ofNullable(rfidTag);
+ Optional optionalEpcTagURI = Optional.ofNullable(epcTagURI);
+ Optional optionalEpcPureIdentityURI = Optional.ofNullable(epcPureIdentityURI);
+
+ if ( optionalRfidTag.isPresent() ) {
+ String inputBin = Converter.hexToBin(rfidTag);
+ String headerBin = inputBin.substring(0, 8);
+ String filterBin = inputBin.substring(8,11);
+ String partitionBin = inputBin.substring(11,14);
+ GSRNPPartitionTableList GSRNPPartitionTableList = new GSRNPPartitionTableList();
+
+ tableItem = GSRNPPartitionTableList.getPartitionByValue( Integer.parseInt(partitionBin, 2) );
+
+ String companyPrefixBin = inputBin.substring(14,14+tableItem.getM());
+ String serialWithExtensionBin = inputBin.substring(14+tableItem.getM(),14+tableItem.getM()+tableItem.getN());
+ String filterDec = Long.toString( Long.parseLong(filterBin, 2) );
+ String companyPrefixDec = Converter.binToDec(companyPrefixBin); //Long.toString( Long.parseLong(companyPrefixBin, 2) );
+
+ serviceReference = Converter.strZero(Converter.binToDec(serialWithExtensionBin), tableItem.getDigits() );
+ companyPrefix = Converter.strZero(companyPrefixDec, tableItem.getL());
+ filterValue = GSRNPFilterValue.forCode( Integer.parseInt(filterDec) );
+ tagSize = GSRNPTagSize.forCode( GSRNPHeader.forCode(headerBin).getTagSize() );
+ prefixLength = PrefixLength.forCode(tableItem.getL());
+
+ } else {
+
+ if ( optionalCompanyPrefix.isPresent() ) {
+ GSRNPPartitionTableList GSRNPPartitionTableList = new GSRNPPartitionTableList();
+
+ prefixLength = PrefixLength.forCode( companyPrefix.length() );
+
+ validateCompanyPrefix();
+
+ tableItem = GSRNPPartitionTableList.getPartitionByL( prefixLength.getValue() );
+
+ validateServiceReference();
+
+ } else {
+
+ if ( optionalEpcTagURI.isPresent() ) {
+ Pattern pattern = Pattern.compile("(urn:epc:tag:gsrnp-)(96)\\:([0-7])\\.(\\d+)\\.(\\d+)");
+ Matcher matcher = pattern.matcher(epcTagURI);
+
+ if ( matcher.matches() ) {
+ tagSize = GSRNPTagSize.forCode( Integer.parseInt(matcher.group(2)) );
+ filterValue = GSRNPFilterValue.forCode( Integer.parseInt(matcher.group(3)) );
+ companyPrefix = matcher.group(4);
+ prefixLength = PrefixLength.forCode( matcher.group(4).length() );
+ serviceReference = matcher.group(5);
+ } else {
+ throw new IllegalArgumentException("EPC Tag URI is invalid");
+ }
+
+ } else if ( optionalEpcPureIdentityURI.isPresent() ) {
+ Pattern pattern = Pattern.compile("(urn:epc:id:gsrnp)\\:(\\d+)\\.(\\d+)");
+ Matcher matcher = pattern.matcher(epcPureIdentityURI);
+
+ if ( matcher.matches() ) {
+ companyPrefix = matcher.group(2);
+ prefixLength = PrefixLength.forCode( matcher.group(2).length() );
+ serviceReference = matcher.group(3);
+ } else {
+ throw new IllegalArgumentException("EPC Pure Identity is invalid");
+ }
+
+
+ }
+
+ GSRNPPartitionTableList GSRNPPartitionTableList = new GSRNPPartitionTableList();
+ tableItem = GSRNPPartitionTableList.getPartitionByL( prefixLength.getValue() );
+
+ }
+
+ }
+
+
+ String outputBin = getBinary();
+ String outputHex = Converter.binToHex( outputBin );
+
+ gsrnp.setEpcScheme("gsrnp");
+ gsrnp.setApplicationIdentifier("AI 8017");
+ gsrnp.setTagSize(Integer.toString(tagSize.getValue()));
+ gsrnp.setFilterValue(Integer.toString(filterValue.getValue()) );
+ gsrnp.setPartitionValue(Integer.toString(tableItem.getPartitionValue()));
+ gsrnp.setPrefixLength(Integer.toString(prefixLength.getValue()));
+ gsrnp.setCompanyPrefix(companyPrefix);
+ gsrnp.setServiceReference(serviceReference);
+ gsrnp.setCheckDigit(Integer.toString(getCheckDigit()));
+ gsrnp.setEpcPureIdentityURI(String.format("urn:epc:id:gsrnp:%s.%s", companyPrefix, serviceReference));
+ gsrnp.setEpcTagURI(String.format("urn:epc:tag:gsrnp-%s:%s.%s.%s", tagSize.getValue(),
+ filterValue.getValue(), companyPrefix, serviceReference));
+ gsrnp.setEpcRawURI(String.format("urn:epc:raw:%s.x%s", tagSize.getValue(), outputHex ));
+ gsrnp.setBinary(outputBin);
+ gsrnp.setRfidTag(outputHex);
+
+ }
+
+ private Integer getCheckDigit() {
+ String value = new StringBuilder()
+ .append(companyPrefix)
+ .append(serviceReference)
+ .toString();
+
+ Integer d18 = (10 - ((3
+ * (Character.getNumericValue(value.charAt(0)) + Character.getNumericValue(value.charAt(2))
+ + Character.getNumericValue(value.charAt(4)) + Character.getNumericValue(value.charAt(6))
+ + Character.getNumericValue(value.charAt(8))
+ + Character.getNumericValue(value.charAt(10)) + Character.getNumericValue(value.charAt(12))
+ + Character.getNumericValue(value.charAt(14)) + Character.getNumericValue(value.charAt(16)))
+ + (Character.getNumericValue(value.charAt(1)) + Character.getNumericValue(value.charAt(3))
+ + Character.getNumericValue(value.charAt(5)) + Character.getNumericValue(value.charAt(7))
+ + Character.getNumericValue(value.charAt(9)) + Character.getNumericValue(value.charAt(11))
+ + Character.getNumericValue(value.charAt(13)) + Character.getNumericValue(value.charAt(15))))
+ % 10)) % 10;
+ return d18;
+ }
+
+
+ private String getBinary() {
+ StringBuilder bin = new StringBuilder();
+
+ bin.append( Converter.decToBin(tagSize.getHeader(), 8) );
+ bin.append( Converter.decToBin(filterValue.getValue(), 3) );
+ bin.append( Converter.decToBin(tableItem.getPartitionValue(), 3) );
+ bin.append( Converter.decToBin(Integer.parseInt(companyPrefix), tableItem.getM()) );
+ //bin.append( Converter.strZero(BigDec2Bin.dec2bin(serviceReference), tableItem.getN()) );
+ bin.append( Converter.decToBin(Integer.parseInt(serviceReference), tableItem.getN()) );
+ bin.append( Converter.decToBin(RESERVED, 24) );
+
+ return bin.toString();
+ }
+
+
+ public GSRNP getGSRNP() {
+ return gsrnp;
+ }
+
+ public String getRfidTag() {
+ return Converter.binToHex( getBinary() );
+ }
+
+
+
+ private void validateServiceReference() {
+ StringBuilder value = new StringBuilder()
+ .append(serviceReference);
+
+ if ( value.length()!=tableItem.getDigits() ) {
+ throw new IllegalArgumentException(String.format("Service Reference \"%s\" has %d length and should have %d length",
+ serviceReference, value.length(), tableItem.getDigits()));
+ }
+ }
+
+
+ private void validateCompanyPrefix() {
+ Optional optionalpPefixLenght = Optional.ofNullable(prefixLength);
+ if ( !optionalpPefixLenght.isPresent() ) {
+ throw new IllegalArgumentException("Company Prefix is invalid. Length not found in the partition table");
+ }
+
+ }
+
+
+
+
+ public static interface ChoiceStep {
+ ServiceReferenceStep withCompanyPrefix(String companyPrefix);
+ BuildStep withRFIDTag(String rfidTag);
+ BuildStep withEPCTagURI(String epcTagURI);
+ TagSizeStep withEPCPureIdentityURI(String epcPureIdentityURI);
+ }
+
+
+ public static interface ServiceReferenceStep {
+ TagSizeStep withServiceReference(String serviceReference);
+ }
+
+ public static interface TagSizeStep {
+ FilterValueStep withTagSize( GSRNPTagSize tagSize );
+ }
+
+ public static interface FilterValueStep {
+ BuildStep withFilterValue( GSRNPFilterValue filterValue );
+ }
+
+ public static interface BuildStep {
+ ParseGSRNP build();
+ }
+
+
+
+ private static class Steps implements ChoiceStep, ServiceReferenceStep, TagSizeStep, FilterValueStep, BuildStep {
+ private String companyPrefix;
+ private GSRNPTagSize tagSize;
+ private GSRNPFilterValue filterValue;
+ private String serviceReference;
+ private String rfidTag;
+ private String epcTagURI;
+ private String epcPureIdentityURI;
+
+ @Override
+ public ParseGSRNP build() {
+ return new ParseGSRNP(this);
+ }
+
+// @Override
+// public SerialStep withExtensionDigit(SSCCExtensionDigit extensionDigit) {
+// this.extensionDigit = extensionDigit;
+// return this;
+// }
+
+
+ @Override
+ public BuildStep withFilterValue(GSRNPFilterValue filterValue) {
+ this.filterValue = filterValue;
+ return this;
+ }
+
+ @Override
+ public FilterValueStep withTagSize(GSRNPTagSize tagSize) {
+ this.tagSize = tagSize;
+ return this;
+ }
+
+ @Override
+ public TagSizeStep withServiceReference(String serviceReference) {
+ this.serviceReference = serviceReference;
+ return this;
+ }
+
+ @Override
+ public ServiceReferenceStep withCompanyPrefix(String companyPrefix) {
+ this.companyPrefix = companyPrefix;
+ return this;
+ }
+
+ @Override
+ public BuildStep withRFIDTag(String rfidTag) {
+ this.rfidTag = rfidTag;
+ return this;
+ }
+
+ @Override
+ public BuildStep withEPCTagURI(String epcTagURI) {
+ this.epcTagURI = epcTagURI;
+ return this;
+ }
+
+ @Override
+ public TagSizeStep withEPCPureIdentityURI(String epcPureIdentityURI) {
+ this.epcPureIdentityURI = epcPureIdentityURI;
+ return this;
+ }
+
+
+
+
+ }
+
+}
+
+
+
+package org.epctagcoder.parse.SGLN;
+
+import org.epctagcoder.option.PrefixLength;
+import org.epctagcoder.option.SGLN.SGLNFilterValue;
+import org.epctagcoder.option.SGLN.SGLNHeader;
+import org.epctagcoder.option.SGLN.SGLNTagSize;
+import org.epctagcoder.option.SGLN.partitionTable.SGLNPartitionTableList;
+import org.epctagcoder.option.TableItem;
+import org.epctagcoder.result.SGLN;
+import org.epctagcoder.util.Converter;
+
+import java.util.Optional;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+public class ParseSGLN {
+
+ private SGLN sgln = new SGLN();
+ private String companyPrefix;
+ private PrefixLength prefixLength;
+ private SGLNTagSize tagSize;
+ private SGLNFilterValue filterValue;
+ private String locationReference;
+ private String extension;
+ private String rfidTag;
+ private String epcTagURI;
+ private String epcPureIdentityURI;
+ private TableItem tableItem;
+ private int remainder;
+
+ private ParseSGLN(Steps steps) {
+ companyPrefix = steps.getCompanyPrefix();
+ tagSize = steps.getTagSize();
+ filterValue = steps.getFilterValue();
+ locationReference = steps.getLocationReference();
+ extension = steps.getExtension();
+ rfidTag = steps.getRfidTag();
+ epcTagURI = steps.getEpcTagURI();
+ epcPureIdentityURI = steps.getEpcPureIdentityURI();
+ parse();
+ }
+
+ public static ChoiceStep Builder() throws Exception {
+ return new Steps();
+ }
+
+ private void parse() {
+ Optional optionalCompanyPrefix = Optional.ofNullable(companyPrefix);
+ Optional optionalRfidTag = Optional.ofNullable(rfidTag);
+ Optional optionalEpcTagURI = Optional.ofNullable(epcTagURI);
+ Optional optionalEpcPureIdentityURI = Optional.ofNullable(epcPureIdentityURI);
+
+ if (optionalRfidTag.isPresent()) {
+ parseRfidTag();
+ } else {
+ if (optionalCompanyPrefix.isPresent()) {
+ SGLNPartitionTableList partitionTableList = new SGLNPartitionTableList();
+ prefixLength = PrefixLength.forCode(companyPrefix.length());
+ validateCompanyPrefix();
+ tableItem = partitionTableList.getPartitionByL(prefixLength.getValue());
+ validateLocationReference();
+ validateExtension();
+ } else {
+ if (optionalEpcTagURI.isPresent()) {
+ parseEpcTagURI();
+ } else if (optionalEpcPureIdentityURI.isPresent()) {
+ parseEpcPureIdentityURI();
+ }
+ }
+ SGLNPartitionTableList partitionTableList = new SGLNPartitionTableList();
+ tableItem = partitionTableList.getPartitionByL(prefixLength.getValue());
+ }
+
+ String outputBin = getBinary();
+ String outputHex = Converter.binToHex(outputBin);
+ sgln.setEpcScheme("sgln");
+ sgln.setApplicationIdentifier("AI 254");
+ sgln.setTagSize(Integer.toString(tagSize.getValue()));
+ sgln.setFilterValue(Integer.toString(filterValue.getValue()));
+ sgln.setPartitionValue(Integer.toString(tableItem.getPartitionValue()));
+ sgln.setPrefixLength(Integer.toString(prefixLength.getValue()));
+ sgln.setCompanyPrefix(companyPrefix);
+ sgln.setLocationReference(locationReference);
+ sgln.setExtension(extension);
+ sgln.setCheckDigit(Integer.toString(getCheckDigit()));
+ sgln.setEpcPureIdentityURI(String.format("urn:epc:id:sgln:%s.%s.%s", companyPrefix, locationReference, extension));
+ sgln.setEpcTagURI(String.format("urn:epc:tag:sgln-%s:%s.%s.%s.%s", tagSize.getValue(), filterValue.getValue(), companyPrefix, locationReference, extension));
+ sgln.setEpcRawURI(String.format("urn:epc:raw:%s.x%s", tagSize.getValue() + remainder, outputHex));
+ sgln.setBinary(outputBin);
+ sgln.setRfidTag(outputHex);
+
+ }
+
+ private void parseRfidTag() {
+ String inputBin = Converter.hexToBin(rfidTag);
+ String headerBin = inputBin.substring(0, 8);
+ String filterBin = inputBin.substring(8, 11);
+ String partitionBin = inputBin.substring(11, 14);
+ SGLNPartitionTableList partitionTableList = new SGLNPartitionTableList();
+
+ tagSize = SGLNTagSize.forCode(SGLNHeader.forCode(headerBin).getTagSize());
+ tableItem = partitionTableList.getPartitionByValue(Integer.parseInt(partitionBin, 2));
+ String filterDec = Long.toString(Long.parseLong(filterBin, 2));
+ String companyPrefixBin = inputBin.substring(14, 14 + tableItem.getM());
+ String locationReferenceBin = inputBin.substring(14 + tableItem.getM(), 14 + tableItem.getM() + tableItem.getN());
+ String extensionBin = inputBin.substring(14 + tableItem.getM() + tableItem.getN());
+
+ String companyPrefixDec = Converter.binToDec(companyPrefixBin);
+ String locationReferenceDec = Converter.binToDec(locationReferenceBin);
+
+ locationReference = Converter.strZero(locationReferenceDec, tableItem.getDigits());
+
+ if (tagSize.getSerialBitCount() == 140) {
+ extensionBin = Converter.convertBinToBit(extensionBin, 7, 8);
+ extension = Converter.binToString(extensionBin);
+ } else if (tagSize.getSerialBitCount() == 41) {
+ extension = Converter.binToDec(extensionBin);
+ }
+ companyPrefix = Converter.strZero(companyPrefixDec, tableItem.getL()); // strzero aqui
+ filterValue = SGLNFilterValue.forCode(Integer.parseInt(filterDec));
+ prefixLength = PrefixLength.forCode(tableItem.getL());
+
+
+ }
+
+ private void parseEpcTagURI() {
+ Pattern pattern = Pattern.compile("(urn:epc:tag:sgln-)(96|195)\\:([0-7])\\.(\\d+)\\.(\\d+)\\.((\\w|/)+)");
+ Matcher matcher = pattern.matcher(epcTagURI);
+
+ if (matcher.matches()) {
+ tagSize = SGLNTagSize.forCode(Integer.parseInt(matcher.group(2)));
+ filterValue = SGLNFilterValue.forCode(Integer.parseInt(matcher.group(3)));
+ companyPrefix = matcher.group(4);
+ prefixLength = PrefixLength.forCode(matcher.group(4).length());
+ locationReference = matcher.group(5);
+ extension = matcher.group(6);
+ } else {
+ throw new IllegalArgumentException("EPC Tag URI is invalid");
+ }
+ }
+
+ private void parseEpcPureIdentityURI() {
+ Pattern pattern = Pattern.compile("(urn:epc:id:sgln)\\:(\\d+)\\.(\\d+)\\.(\\w+)");
+ Matcher matcher = pattern.matcher(epcPureIdentityURI);
+
+ if (matcher.matches()) {
+ companyPrefix = matcher.group(2);
+ prefixLength = PrefixLength.forCode(matcher.group(2).length());
+ locationReference = matcher.group(3);
+ extension = matcher.group(4);
+ } else {
+ throw new IllegalArgumentException("EPC Pure Identity is invalid");
+ }
+ }
+
+ private String getBinary() {
+ StringBuilder bin = new StringBuilder();
+
+ remainder = (int) (Math.ceil((tagSize.getValue() / 16.0)) * 16) - tagSize.getValue();
+ bin.append(Converter.decToBin(tagSize.getHeader(), 8));
+ bin.append(Converter.decToBin(filterValue.getValue(), 3));
+ bin.append(Converter.decToBin(tableItem.getPartitionValue(), 3));
+ bin.append(Converter.decToBin(Integer.parseInt(companyPrefix), tableItem.getM()));
+ bin.append(Converter.decToBin(Integer.parseInt(locationReference), tableItem.getN()));
+
+ if (tagSize.getValue() == 195) {
+ bin.append(Converter.fill(Converter.StringToBinary(extension, 7), tagSize.getSerialBitCount() + remainder));
+ } else if (tagSize.getValue() == 96) {
+ bin.append(Converter.decToBin(extension, tagSize.getSerialBitCount() + remainder));
+ }
+
+ return bin.toString();
+ }
+
+ private Integer getCheckDigit() {
+ String value = companyPrefix +
+ locationReference;
+
+ return (10 - ((3
+ * (Character.getNumericValue(value.charAt(1)) + Character.getNumericValue(value.charAt(3))
+ + Character.getNumericValue(value.charAt(5))
+ + Character.getNumericValue(value.charAt(7)) + Character.getNumericValue(value.charAt(9))
+ + Character.getNumericValue(value.charAt(11)))
+ + (Character.getNumericValue(value.charAt(0)) + Character.getNumericValue(value.charAt(2))
+ + Character.getNumericValue(value.charAt(4)) + Character.getNumericValue(value.charAt(6))
+ + Character.getNumericValue(value.charAt(8)) + Character.getNumericValue(value.charAt(10))))
+ % 10)) % 10;
+ }
+
+ public SGLN getSGLN() {
+ return sgln;
+ }
+
+ public String getRfidTag() {
+ return Converter.binToHex(getBinary());
+ }
+
+
+ private void validateCompanyPrefix() {
+ Optional optionalPrefixLength = Optional.ofNullable(prefixLength);
+ if (optionalPrefixLength.isPresent()) {
+ throw new IllegalArgumentException("Company Prefix is invalid. Length not found in the partition table");
+ }
+ }
+
+ private void validateLocationReference() {
+ if (locationReference.length() != tableItem.getDigits()) {
+ throw new IllegalArgumentException(String.format("Location Reference \"%s\" has %d length and should have %d length",
+ locationReference, locationReference.length(), tableItem.getDigits()));
+ }
+ }
+
+ private void validateExtension() {
+ if (tagSize.getValue() == 195) {
+ if (extension.length() > tagSize.getSerialMaxLenght()) {
+ throw new IllegalArgumentException(String.format("Extension value is out of range. Should be up to %d alphanumeric characters",
+ tagSize.getSerialMaxLenght()));
+ }
+ } else if (tagSize.getValue() == 96) {
+ if (Long.parseLong(extension) > tagSize.getSerialMaxValue()) {
+ throw new IllegalArgumentException(String.format("Extension value is out of range. Should be less than or equal %d",
+ tagSize.getSerialMaxValue()));
+ }
+ }
+ }
+
+ public static interface ChoiceStep {
+ LocationReferenceStep withCompanyPrefix(String companyPrefix);
+
+ BuildStep withRFIDTag(String rfidTag);
+
+ BuildStep withEPCTagURI(String epcTagURI);
+
+ TagSizeStep withEPCPureIdentityURI(String epcPureIdentityURI);
+ }
+
+ public static interface BuildStep {
+ ParseSGLN build();
+ }
+
+ public static interface TagSizeStep {
+ FilterValueStep withTagSize(SGLNTagSize tagSize);
+ }
+
+ public static interface LocationReferenceStep {
+ ExtensionStep withLocationReference(String locationReference);
+ }
+
+ public static interface ExtensionStep {
+ TagSizeStep withExtension(String extension);
+ }
+
+ public static interface FilterValueStep {
+ BuildStep withFilterValue(SGLNFilterValue filterValue);
+ }
+
+ private static class Steps implements ChoiceStep, LocationReferenceStep, ExtensionStep, TagSizeStep, FilterValueStep, BuildStep {
+
+ private String companyPrefix;
+ private SGLNTagSize tagSize;
+ private SGLNFilterValue filterValue;
+ private String locationReference;
+ private String extension;
+
+ private String rfidTag;
+ private String epcTagURI;
+ private String epcPureIdentityURI;
+
+ @Override
+ public ParseSGLN build() {
+ return new ParseSGLN(this);
+ }
+
+ @Override
+ public LocationReferenceStep withCompanyPrefix(String companyPrefix) {
+ this.companyPrefix = companyPrefix;
+ return this;
+ }
+
+ @Override
+ public BuildStep withRFIDTag(String rfidTag) {
+ this.rfidTag = rfidTag;
+ return this;
+ }
+
+ @Override
+ public BuildStep withEPCTagURI(String epcTagURI) {
+ this.epcTagURI = epcTagURI;
+ return this;
+ }
+
+ @Override
+ public TagSizeStep withEPCPureIdentityURI(String epcPureIdentityURI) {
+ this.epcPureIdentityURI = epcPureIdentityURI;
+ return this;
+ }
+
+ @Override
+ public TagSizeStep withExtension(String extension) {
+ this.extension = extension;
+ return this;
+ }
+
+ @Override
+ public BuildStep withFilterValue(SGLNFilterValue filterValue) {
+ this.filterValue = filterValue;
+ return this;
+ }
+
+ @Override
+ public ExtensionStep withLocationReference(String locationReference) {
+ this.locationReference = locationReference;
+ return this;
+ }
+
+ @Override
+ public FilterValueStep withTagSize(SGLNTagSize tagSize) {
+ this.tagSize = tagSize;
+ return this;
+ }
+
+ public String getCompanyPrefix() {
+ return companyPrefix;
+ }
+
+ public SGLNTagSize getTagSize() {
+ return tagSize;
+ }
+
+ public SGLNFilterValue getFilterValue() {
+ return filterValue;
+ }
+
+ public String getLocationReference() {
+ return locationReference;
+ }
+
+ public String getExtension() {
+ return extension;
+ }
+
+ public String getRfidTag() {
+ return rfidTag;
+ }
+
+ public String getEpcTagURI() {
+ return epcTagURI;
+ }
+
+ public String getEpcPureIdentityURI() {
+ return epcPureIdentityURI;
+ }
+ }
+
+
+}
+
+
+
+package org.epctagcoder.parse.SGTIN;
+
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import org.epctagcoder.exception.EPCParseException;
+import org.epctagcoder.option.PrefixLength;
+import org.epctagcoder.option.TableItem;
+import org.epctagcoder.option.SGTIN.SGTINExtensionDigit;
+import org.epctagcoder.option.SGTIN.SGTINFilterValue;
+import org.epctagcoder.option.SGTIN.SGTINHeader;
+import org.epctagcoder.option.SGTIN.SGTINTagSize;
+import org.epctagcoder.option.SGTIN.partitionTable.SGTINPartitionTableList;
+import org.epctagcoder.result.SGTIN;
+import org.epctagcoder.util.Converter;
+
+public class ParseSGTIN {
+
+ private final SGTIN sgtin = new SGTIN();
+ private final String rfidTag;
+ private final String epcTagURI;
+ private final String epcPureIdentityURI;
+
+ private SGTINExtensionDigit extensionDigit;
+ private String companyPrefix;
+ private PrefixLength prefixLength;
+ private SGTINTagSize tagSize;
+ private SGTINFilterValue filterValue;
+ private String itemReference;
+ private String serial;
+ private TableItem tableItem;
+ private int remainder;
+
+ public static ChoiceStep Builder() {
+ return new Steps();
+ }
+
+ private ParseSGTIN(Steps steps) throws EPCParseException {
+ this.extensionDigit = steps.extensionDigit;
+ this.companyPrefix = steps.companyPrefix;
+ this.tagSize = steps.tagSize;
+ this.filterValue = steps.filterValue;
+ this.itemReference = steps.itemReference;
+ this.serial = steps.serial;
+ this.rfidTag = steps.rfidTag;
+ this.epcTagURI = steps.epcTagURI;
+ this.epcPureIdentityURI = steps.epcPureIdentityURI;
+ parse();
+ }
+
+ private void parseRfidTag() throws EPCParseException {
+ String inputBin = Converter.hexToBin(rfidTag);
+ String headerBin = inputBin.substring(0, 8);
+ String filterBin = inputBin.substring(8, 11);
+ String partitionBin = inputBin.substring(11, 14);
+ SGTINPartitionTableList sgtinPartitionTableList = new SGTINPartitionTableList();
+
+ tagSize = SGTINTagSize.forCode(SGTINHeader.forCode(headerBin).getTagSize());
+ tableItem = sgtinPartitionTableList.getPartitionByValue( Integer.parseInt(partitionBin, 2) );
+
+ String filterDec = Long.toString( Long.parseLong(filterBin, 2) );
+ String companyPrefixBin = inputBin.substring(14, 14+tableItem.getM());
+ String itemReferenceWithExtensionBin = inputBin.substring(14+tableItem.getM(), 14+tableItem.getM()+tableItem.getN());
+
+ String serialBin = inputBin.substring(14+tableItem.getM()+tableItem.getN() )
+ .substring(0, tagSize.getSerialBitCount());
+
+ String companyPrefixDec = Converter.binToDec(companyPrefixBin);
+ String itemReferenceWithExtensionDec = Converter.strZero(Converter.binToDec(itemReferenceWithExtensionBin), tableItem.getDigits());
+ String extensionDec = itemReferenceWithExtensionDec.substring(0,1);
+
+ itemReference = itemReferenceWithExtensionDec.substring(1);
+
+ if (tagSize.getSerialBitCount()==140) {
+ serialBin = Converter.convertBinToBit(serialBin, 7, 8);
+ serial = Converter.binToString(serialBin);
+ } else if (tagSize.getSerialBitCount()==38) {
+ serial = Converter.binToDec(serialBin);
+ }
+
+ companyPrefix = Converter.strZero(companyPrefixDec, tableItem.getL());
+ extensionDigit = SGTINExtensionDigit.forCode( Integer.parseInt(extensionDec) );
+ filterValue = SGTINFilterValue.forCode( Integer.parseInt(filterDec) );
+ prefixLength = PrefixLength.forCode(tableItem.getL());
+ }
+
+ private void parseCompanyPrefix() throws EPCParseException {
+ SGTINPartitionTableList sgtinPartitionTableList = new SGTINPartitionTableList();
+ prefixLength = PrefixLength.forCode(companyPrefix.length());
+
+ validateCompanyPrefix();
+
+ tableItem = sgtinPartitionTableList.getPartitionByL(prefixLength.getValue());
+
+ validateExtensionDigitAndItemReference();
+ validateSerial();
+ }
+
+ private void parseTagUri() throws EPCParseException {
+ Pattern pattern = Pattern.compile("(urn:epc:tag:sgtin-)(96|198):([0-7])\\.(\\d+)\\.([0-8])(\\d+)\\.(\\w+)");
+ Matcher matcher = pattern.matcher(epcTagURI);
+
+ if (matcher.matches()) {
+ tagSize = SGTINTagSize.forCode(Integer.parseInt(matcher.group(2)));
+ filterValue = SGTINFilterValue.forCode(Integer.parseInt(matcher.group(3)));
+ companyPrefix = matcher.group(4);
+ prefixLength = PrefixLength.forCode(matcher.group(4).length());
+ extensionDigit = SGTINExtensionDigit.forCode(Integer.parseInt(matcher.group(5)));
+ itemReference = matcher.group(6);
+ serial = matcher.group(7);
+ } else {
+ throw new EPCParseException("EPC Tag URI is invalid");
+ }
+ }
+
+ private void parsePureIdentityUri() throws EPCParseException {
+ Pattern pattern = Pattern.compile("(urn:epc:id:sgtin):(\\d+)\\.([0-8])(\\d+)\\.(\\w+)");
+ Matcher matcher = pattern.matcher(epcPureIdentityURI);
+
+ if (matcher.matches()) {
+ companyPrefix = matcher.group(2);
+ prefixLength = PrefixLength.forCode(matcher.group(2).length());
+ extensionDigit = SGTINExtensionDigit.forCode(Integer.parseInt(matcher.group(3)));
+ itemReference = matcher.group(4);
+ serial = matcher.group(5);
+ } else {
+ throw new EPCParseException("EPC Pure Identity is invalid");
+ }
+ }
+
+ private void parse() throws EPCParseException {
+
+ if(rfidTag != null) {
+ parseRfidTag();
+ } else if (extensionDigit != null) {
+ parseCompanyPrefix();
+ } else {
+ if (epcTagURI != null) {
+ parseTagUri();
+ } else if (epcPureIdentityURI != null) {
+ parsePureIdentityUri();
+ }
+
+ SGTINPartitionTableList sgtinPartitionTableList = new SGTINPartitionTableList();
+ tableItem = sgtinPartitionTableList.getPartitionByL(prefixLength.getValue());
+ }
+
+ String outputBin = getBinary();
+ String outputHex = Converter.binToHex( outputBin );
+
+ sgtin.setEpcScheme("sgtin");
+ sgtin.setApplicationIdentifier("AI 414 + AI 254");
+ sgtin.setTagSize(Integer.toString(tagSize.getValue()));
+ sgtin.setFilterValue(Integer.toString(filterValue.getValue()));
+ sgtin.setPartitionValue(Integer.toString(tableItem.getPartitionValue()));
+ sgtin.setPrefixLength(Integer.toString(prefixLength.getValue()));
+ sgtin.setCompanyPrefix(companyPrefix);
+ sgtin.setItemReference(itemReference);
+ sgtin.setExtensionDigit(Integer.toString(extensionDigit.getValue()));
+ sgtin.setSerial(serial);
+ sgtin.setCheckDigit(Integer.toString(getCheckDigit()));
+ sgtin.setEpcPureIdentityURI(String.format("urn:epc:id:sgtin:%s.%s%s.%s", companyPrefix, extensionDigit.getValue(), itemReference, serial));
+ sgtin.setEpcTagURI(String.format("urn:epc:tag:sgtin-%s:%s.%s.%s%s.%s", tagSize.getValue(), filterValue.getValue(), companyPrefix, extensionDigit.getValue(), itemReference, serial));
+ sgtin.setEpcRawURI(String.format("urn:epc:raw:%s.x%s", tagSize.getValue()+remainder, outputHex ));
+ sgtin.setBinary(outputBin);
+ sgtin.setRfidTag(outputHex);
+ }
+
+ private String getBinary() {
+ StringBuilder bin = new StringBuilder();
+
+ remainder = (int) (Math.ceil((tagSize.getValue()/16.0))*16)-tagSize.getValue();
+
+ bin.append( Converter.decToBin(tagSize.getHeader(), 8) );
+ bin.append( Converter.decToBin(filterValue.getValue(), 3) );
+ bin.append( Converter.decToBin(tableItem.getPartitionValue(), 3) );
+ bin.append( Converter.decToBin(companyPrefix, tableItem.getM()) );
+ bin.append( Converter.decToBin(Integer.parseInt(extensionDigit.getValue() +itemReference), tableItem.getN()) );
+
+ if (tagSize.getValue()==198) {
+ bin.append( Converter.fill(Converter.StringToBinary(serial, 7), tagSize.getSerialBitCount()+remainder ) );
+ } else if (tagSize.getValue()==96) {
+ bin.append( Converter.decToBin(serial, tagSize.getSerialBitCount()+remainder ) );
+ }
+
+ return bin.toString();
+ }
+
+ private Integer getCheckDigit() {
+ String value = extensionDigit.getValue() + companyPrefix + itemReference;
+
+ return (10 - ((3
+ * (Character.getNumericValue(value.charAt(0)) + Character.getNumericValue(value.charAt(2))
+ + Character.getNumericValue(value.charAt(4))
+ + Character.getNumericValue(value.charAt(6)) + Character.getNumericValue(value.charAt(8))
+ + Character.getNumericValue(value.charAt(10)) + Character.getNumericValue(value.charAt(12)))
+ + (Character.getNumericValue(value.charAt(1)) + Character.getNumericValue(value.charAt(3))
+ + Character.getNumericValue(value.charAt(5)) + Character.getNumericValue(value.charAt(7))
+ + Character.getNumericValue(value.charAt(9)) + Character.getNumericValue(value.charAt(11))))
+ % 10)) % 10;
+ }
+
+
+ public SGTIN getSGTIN() {
+ return sgtin;
+ }
+
+ public String getRfidTag() {
+ return Converter.binToHex( getBinary() );
+ }
+
+ private void validateExtensionDigitAndItemReference() throws EPCParseException {
+ StringBuilder value = new StringBuilder()
+ .append(extensionDigit.getValue())
+ .append(itemReference);
+
+ if ( value.length()!=tableItem.getDigits() ) {
+ String message = "Concatenation between Extension Digit \"%d\" and " +
+ "Item Reference \"%s\" has %d length and should have %d length";
+ throw new EPCParseException(String.format(message,
+ extensionDigit.getValue(), itemReference, value.length(), tableItem.getDigits()));
+ }
+ }
+
+ private void validateCompanyPrefix() throws EPCParseException {
+ if(prefixLength == null) {
+ throw new EPCParseException("Company Prefix is invalid. Length not found in the partition table");
+ }
+ }
+
+ private void validateSerial() throws EPCParseException {
+ if (tagSize.getValue()==198 ) {
+ if ( serial.length()>tagSize.getSerialMaxLenght() ) {
+ throw new EPCParseException("Serial value is out of range. Should be up to 20 alphanumeric characters");
+ }
+ } else if (tagSize.getValue()==96 ) {
+ if ( Long.parseLong(serial) >tagSize.getSerialMaxValue() ) {
+ throw new EPCParseException("Serial value is out of range. Should be less than or equal 274,877,906,943");
+ }
+ if ( serial.startsWith("0") ) {
+ throw new EPCParseException("Serial with leading zeros is not allowed");
+ }
+ }
+
+ }
+
+ public interface ChoiceStep {
+ ExtensionDigitStep withCompanyPrefix(String companyPrefix);
+ BuildStep withRFIDTag(String rfidTag);
+ BuildStep withEPCTagURI(String epcTagURI);
+ TagSizeStep withEPCPureIdentityURI(String epcPureIdentityURI);
+ }
+
+ public interface ExtensionDigitStep {
+ ItemReferenceStep withExtensionDigit(SGTINExtensionDigit extensionDigit);
+ }
+
+ public interface ItemReferenceStep {
+ SerialStep withItemReference(String itemReference);
+ }
+
+ public interface SerialStep {
+ TagSizeStep withSerial(String serial);
+ }
+
+ public interface TagSizeStep {
+ FilterValueStep withTagSize( SGTINTagSize tagSize );
+ }
+
+ public interface FilterValueStep {
+ BuildStep withFilterValue( SGTINFilterValue filterValue );
+ }
+
+ public interface BuildStep {
+ ParseSGTIN build() throws EPCParseException;
+ }
+
+ private static class Steps implements ChoiceStep, ExtensionDigitStep, ItemReferenceStep, SerialStep, TagSizeStep, FilterValueStep, BuildStep {
+ private SGTINExtensionDigit extensionDigit;
+ private String companyPrefix;
+ private SGTINTagSize tagSize;
+ private SGTINFilterValue filterValue;
+ private String itemReference;
+ private String serial;
+ private String rfidTag;
+ private String epcTagURI;
+ private String epcPureIdentityURI;
+
+ @Override
+ public ParseSGTIN build() throws EPCParseException {
+ return new ParseSGTIN(this);
+ }
+
+ @Override
+ public ItemReferenceStep withExtensionDigit(SGTINExtensionDigit extensionDigit) {
+ this.extensionDigit = extensionDigit;
+ return this;
+ }
+
+ @Override
+ public SerialStep withItemReference(String itemReference) {
+ this.itemReference = itemReference;
+ return this;
+ }
+
+ @Override
+ public TagSizeStep withSerial(String serial) {
+ this.serial = serial;
+ return this;
+ }
+
+ @Override
+ public FilterValueStep withTagSize(SGTINTagSize tagSize) {
+ this.tagSize = tagSize;
+ return this;
+ }
+
+ @Override
+ public BuildStep withFilterValue(SGTINFilterValue filterValue) {
+ this.filterValue = filterValue;
+ return this;
+ }
+
+ @Override
+ public BuildStep withRFIDTag(String rfidTag) {
+ this.rfidTag = rfidTag;
+ return this;
+ }
+
+ @Override
+ public BuildStep withEPCTagURI(String epcTagURI) {
+ this.epcTagURI = epcTagURI;
+ return this;
+ }
+
+ @Override
+ public TagSizeStep withEPCPureIdentityURI(String epcPureIdentityURI) {
+ this.epcPureIdentityURI = epcPureIdentityURI;
+ return this;
+ }
+
+ @Override
+ public ExtensionDigitStep withCompanyPrefix(String companyPrefix) {
+ this.companyPrefix = companyPrefix;
+ return this;
+ }
+ }
+}
+
+
+
+package org.epctagcoder.parse.SSCC;
+
+import java.util.Optional;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+
+import org.epctagcoder.option.PrefixLength;
+import org.epctagcoder.option.TableItem;
+import org.epctagcoder.option.SSCC.SSCCExtensionDigit;
+import org.epctagcoder.option.SSCC.SSCCFilterValue;
+import org.epctagcoder.option.SSCC.SSCCHeader;
+import org.epctagcoder.option.SSCC.SSCCTagSize;
+import org.epctagcoder.option.SSCC.partitionTable.SSCCPartitionTableList;
+import org.epctagcoder.result.SSCC;
+import org.epctagcoder.util.Converter;
+
+public class ParseSSCC {
+ private static final Integer RESERVED = 0; // 24 zero bits
+ private SSCC sscc = new SSCC();
+ private SSCCExtensionDigit extensionDigit;
+ private String companyPrefix;
+ private PrefixLength prefixLength;
+ private SSCCTagSize tagSize;
+ private SSCCFilterValue filterValue;
+ private String serial;
+ private String rfidTag;
+ private String epcTagURI;
+ private String epcPureIdentityURI;
+ private TableItem tableItem;
+
+ public static ChoiceStep Builder() throws Exception {
+ return new Steps();
+ }
+
+ private ParseSSCC(Steps steps) {
+ this.extensionDigit = steps.extensionDigit;
+ this.companyPrefix = steps.companyPrefix;
+ this.tagSize = steps.tagSize;
+ this.filterValue = steps.filterValue;
+ this.serial = steps.serial;
+ this.rfidTag = steps.rfidTag;
+ this.epcTagURI = steps.epcTagURI;
+ this.epcPureIdentityURI = steps.epcPureIdentityURI;
+ parse();
+ }
+
+
+ private void parse() {
+ Optional optionalCompanyPrefix = Optional.ofNullable(extensionDigit);
+ Optional optionalRfidTag = Optional.ofNullable(rfidTag);
+ Optional optionalEpcTagURI = Optional.ofNullable(epcTagURI);
+ Optional optionalEpcPureIdentityURI = Optional.ofNullable(epcPureIdentityURI);
+
+ if ( optionalRfidTag.isPresent() ) {
+ String inputBin = Converter.hexToBin(rfidTag);
+ String headerBin = inputBin.substring(0, 8);
+ String filterBin = inputBin.substring(8,11);
+ String partitionBin = inputBin.substring(11,14);
+ SSCCPartitionTableList ssccPartitionTableList = new SSCCPartitionTableList();
+
+ tableItem = ssccPartitionTableList.getPartitionByValue( Integer.parseInt(partitionBin, 2) );
+
+ String companyPrefixBin = inputBin.substring(14,14+tableItem.getM());
+ String serialWithExtensionBin = inputBin.substring(14+tableItem.getM(),14+tableItem.getM()+tableItem.getN());
+ String filterDec = Long.toString( Long.parseLong(filterBin, 2) );
+ String companyPrefixDec = Converter.binToDec(companyPrefixBin);
+ String serialWithExtension = Converter.strZero(Converter.binToDec(serialWithExtensionBin), tableItem.getDigits() );
+ String extensionDec = serialWithExtension.substring(0,1);
+
+ serial = serialWithExtension.substring(1);
+ companyPrefix = Converter.strZero(companyPrefixDec, tableItem.getL());
+ extensionDigit = SSCCExtensionDigit.forCode( Integer.parseInt(extensionDec) );
+ filterValue = SSCCFilterValue.forCode( Integer.parseInt(filterDec) );
+ tagSize = SSCCTagSize.forCode( SSCCHeader.forCode(headerBin).getTagSize() );
+ prefixLength = PrefixLength.forCode(tableItem.getL());
+
+ } else {
+
+ if ( optionalCompanyPrefix.isPresent() ) {
+ SSCCPartitionTableList ssccPartitionTableList = new SSCCPartitionTableList();
+ prefixLength = PrefixLength.forCode( companyPrefix.length() );
+ validateCompanyPrefix();
+ tableItem = ssccPartitionTableList.getPartitionByL( prefixLength.getValue() );
+ validateExtensionDigitAndSerial();
+ } else {
+ if ( optionalEpcTagURI.isPresent() ) {
+ Pattern pattern = Pattern.compile("(urn:epc:tag:sscc-)(96)\\:([0-7])\\.(\\d+)\\.([0-9])(\\d+)");
+ Matcher matcher = pattern.matcher(epcTagURI);
+
+ if ( matcher.matches() ) {
+ tagSize = SSCCTagSize.forCode( Integer.parseInt(matcher.group(2)) );
+ filterValue = SSCCFilterValue.forCode( Integer.parseInt(matcher.group(3)) );
+ companyPrefix = matcher.group(4);
+ prefixLength = PrefixLength.forCode( matcher.group(4).length() );
+ extensionDigit = SSCCExtensionDigit.forCode( Integer.parseInt(matcher.group(5)) );
+ serial = matcher.group(6);
+ } else {
+ throw new IllegalArgumentException("EPC Tag URI is invalid");
+ }
+
+ } else if ( optionalEpcPureIdentityURI.isPresent() ) {
+ Pattern pattern = Pattern.compile("(urn:epc:id:sscc)\\:(\\d+)\\.([0-9])(\\d+)");
+ Matcher matcher = pattern.matcher(epcPureIdentityURI);
+
+ if ( matcher.matches() ) {
+ companyPrefix = matcher.group(2);
+ prefixLength = PrefixLength.forCode( matcher.group(2).length() );
+ extensionDigit = SSCCExtensionDigit.forCode( Integer.parseInt(matcher.group(3)) );
+ serial = matcher.group(4);
+ } else {
+ throw new IllegalArgumentException("EPC Pure Identity is invalid");
+ }
+
+
+ }
+
+ if (prefixLength==null) {
+ throw new IllegalArgumentException("Invalid Prefix Length");
+ } else {
+ SSCCPartitionTableList ssccPartitionTableList = new SSCCPartitionTableList();
+ tableItem = ssccPartitionTableList.getPartitionByL( prefixLength.getValue() );
+ }
+
+ }
+
+ }
+
+
+ String outputBin = getBinary();
+ String outputHex = Converter.binToHex( outputBin );
+
+ sscc.setEpcScheme("sscc");
+ sscc.setApplicationIdentifier("AI 00");
+ sscc.setTagSize(Integer.toString(tagSize.getValue()));
+ sscc.setFilterValue(Integer.toString(filterValue.getValue()) );
+ sscc.setPartitionValue(Integer.toString(tableItem.getPartitionValue()));
+ sscc.setPrefixLength(Integer.toString(prefixLength.getValue()));
+ sscc.setCompanyPrefix(companyPrefix);
+ sscc.setExtensionDigit(Integer.toString(extensionDigit.getValue()));
+ sscc.setSerial(serial);
+ sscc.setCheckDigit(Integer.toString(getCheckDigit()));
+ sscc.setEpcPureIdentityURI(String.format("urn:epc:id:sscc:%s.%s%s", companyPrefix, extensionDigit.getValue(), serial));
+ sscc.setEpcTagURI(String.format("urn:epc:tag:sscc-%s:%s.%s.%s%s", tagSize.getValue(),
+ filterValue.getValue(), companyPrefix, extensionDigit.getValue(), serial));
+ sscc.setEpcRawURI(String.format("urn:epc:raw:%s.x%s", tagSize.getValue(), outputHex ));
+ sscc.setBinary(outputBin);
+ sscc.setRfidTag(outputHex);
+
+ }
+
+
+ private Integer getCheckDigit() {
+ String value = new StringBuilder()
+ .append(extensionDigit.getValue())
+ .append(companyPrefix)
+ .append(serial)
+ .toString();
+
+ Integer d18 = (10 - ((3
+ * (Character.getNumericValue(value.charAt(0)) + Character.getNumericValue(value.charAt(2))
+ + Character.getNumericValue(value.charAt(4)) + Character.getNumericValue(value.charAt(6))
+ + Character.getNumericValue(value.charAt(8))
+ + Character.getNumericValue(value.charAt(10)) + Character.getNumericValue(value.charAt(12))
+ + Character.getNumericValue(value.charAt(14)) + Character.getNumericValue(value.charAt(16)))
+ + (Character.getNumericValue(value.charAt(1)) + Character.getNumericValue(value.charAt(3))
+ + Character.getNumericValue(value.charAt(5)) + Character.getNumericValue(value.charAt(7))
+ + Character.getNumericValue(value.charAt(9)) + Character.getNumericValue(value.charAt(11))
+ + Character.getNumericValue(value.charAt(13)) + Character.getNumericValue(value.charAt(15))))
+ % 10)) % 10;
+ return d18;
+ }
+
+
+ private String getBinary() {
+ StringBuilder bin = new StringBuilder();
+
+ bin.append( Converter.decToBin(tagSize.getHeader(), 8) );
+ bin.append( Converter.decToBin(filterValue.getValue(), 3) );
+ bin.append( Converter.decToBin(tableItem.getPartitionValue(), 3) );
+ bin.append( Converter.decToBin(Integer.parseInt(companyPrefix), tableItem.getM()) );
+ bin.append( Converter.decToBin(extensionDigit.getValue()+serial, tableItem.getN()) );
+ bin.append( Converter.decToBin(RESERVED, 24) );
+
+ return bin.toString();
+ }
+
+
+ public SSCC getSSCC() {
+ return sscc;
+ }
+
+ public String getRfidTag() {
+ return Converter.binToHex( getBinary() );
+ }
+
+
+
+ private void validateExtensionDigitAndSerial() {
+ StringBuilder value = new StringBuilder()
+ .append(extensionDigit.getValue())
+ .append(serial);
+
+ if ( value.length()!=tableItem.getDigits() ) {
+ throw new IllegalArgumentException(String.format("Concatenation between Extension Digit \"%d\" and Serial \"%s\" has %d length and should have %d length",
+ extensionDigit.getValue(), serial, value.length(), tableItem.getDigits()));
+ }
+ }
+
+
+ private void validateCompanyPrefix() {
+ Optional optionalpPefixLenght = Optional.ofNullable(prefixLength);
+ if ( !optionalpPefixLenght.isPresent() ) {
+ throw new IllegalArgumentException("Company Prefix is invalid. Length not found in the partition table");
+ }
+
+ }
+
+
+
+
+ public static interface ChoiceStep {
+ ExtensionDigiStep withCompanyPrefix(String companyPrefix);
+ BuildStep withRFIDTag(String rfidTag);
+ BuildStep withEPCTagURI(String epcTagURI);
+ TagSizeStep withEPCPureIdentityURI(String epcPureIdentityURI);
+ }
+
+ public static interface ExtensionDigiStep {
+ SerialStep withExtensionDigit(SSCCExtensionDigit extensionDigit);
+ }
+
+ public static interface SerialStep {
+ TagSizeStep withSerial(String serial);
+ }
+
+ public static interface TagSizeStep {
+ FilterValueStep withTagSize( SSCCTagSize tagSize );
+ }
+
+ public static interface FilterValueStep {
+ BuildStep withFilterValue( SSCCFilterValue filterValue );
+ }
+
+ public static interface BuildStep {
+ ParseSSCC build();
+ }
+
+
+
+ private static class Steps implements ChoiceStep, ExtensionDigiStep, SerialStep, TagSizeStep, FilterValueStep, BuildStep {
+ private SSCCExtensionDigit extensionDigit;
+ private String companyPrefix;
+ private SSCCTagSize tagSize;
+ private SSCCFilterValue filterValue;
+ private String serial;
+ private String rfidTag;
+ private String epcTagURI;
+ private String epcPureIdentityURI;
+
+ @Override
+ public ParseSSCC build() {
+ return new ParseSSCC(this);
+ }
+
+
+ @Override
+ public SerialStep withExtensionDigit(SSCCExtensionDigit extensionDigit) {
+ this.extensionDigit = extensionDigit;
+ return this;
+ }
+
+ @Override
+ public ExtensionDigiStep withCompanyPrefix(String companyPrefix) {
+ this.companyPrefix = companyPrefix;
+ return this;
+ }
+
+ @Override
+ public TagSizeStep withSerial(String serial) {
+ this.serial = serial;
+ return this;
+ }
+
+ @Override
+ public FilterValueStep withTagSize(SSCCTagSize tagSize) {
+ this.tagSize = tagSize;
+ return this;
+ }
+
+ @Override
+ public BuildStep withFilterValue(SSCCFilterValue filterValue) {
+ this.filterValue = filterValue;
+ return this;
+ }
+
+ @Override
+ public BuildStep withRFIDTag(String rfidTag) {
+ this.rfidTag = rfidTag;
+ return this;
+ }
+
+
+ @Override
+ public BuildStep withEPCTagURI(String epcTagURI) {
+ this.epcTagURI = epcTagURI;
+ return this;
+ }
+
+
+ @Override
+ public TagSizeStep withEPCPureIdentityURI(String epcPureIdentityURI) {
+ this.epcPureIdentityURI = epcPureIdentityURI;
+ return this;
+ }
+
+ }
+
+}
+
+
+
+package org.epctagcoder.result;
+
+public abstract class Base {
+ private String epcScheme;
+ private String applicationIdentifier;
+ private String tagSize;
+ private String filterValue;
+ private String partitionValue;
+ private String prefixLength;
+ private String companyPrefix;
+ private String epcPureIdentityURI;
+ private String epcTagURI;
+ private String epcRawURI;
+ private String binary;
+ private String rfidTag;
+ private String exception;
+
+
+ public Base() {
+
+ }
+
+
+ public String getEpcScheme() {
+ return epcScheme;
+ }
+
+
+ public void setEpcScheme(String epcScheme) {
+ this.epcScheme = epcScheme;
+ }
+
+
+ public String getApplicationIdentifier() {
+ return applicationIdentifier;
+ }
+
+
+ public void setApplicationIdentifier(String applicationIdentifier) {
+ this.applicationIdentifier = applicationIdentifier;
+ }
+
+
+ public String getTagSize() {
+ return tagSize;
+ }
+
+
+ public void setTagSize(String tagSize) {
+ this.tagSize = tagSize;
+ }
+
+
+ public String getFilterValue() {
+ return filterValue;
+ }
+
+
+ public void setFilterValue(String filterValue) {
+ this.filterValue = filterValue;
+ }
+
+
+ public String getPartitionValue() {
+ return partitionValue;
+ }
+
+
+ public void setPartitionValue(String partitionValue) {
+ this.partitionValue = partitionValue;
+ }
+
+
+ public String getPrefixLength() {
+ return prefixLength;
+ }
+
+
+ public void setPrefixLength(String prefixLength) {
+ this.prefixLength = prefixLength;
+ }
+
+
+ public String getCompanyPrefix() {
+ return companyPrefix;
+ }
+
+
+ public void setCompanyPrefix(String companyPrefix) {
+ this.companyPrefix = companyPrefix;
+ }
+
+
+ public String getEpcPureIdentityURI() {
+ return epcPureIdentityURI;
+ }
+
+
+ public void setEpcPureIdentityURI(String epcPureIdentityURI) {
+ this.epcPureIdentityURI = epcPureIdentityURI;
+ }
+
+
+ public String getEpcTagURI() {
+ return epcTagURI;
+ }
+
+
+ public void setEpcTagURI(String epcTagURI) {
+ this.epcTagURI = epcTagURI;
+ }
+
+
+ public String getEpcRawURI() {
+ return epcRawURI;
+ }
+
+
+ public void setEpcRawURI(String epcRawURI) {
+ this.epcRawURI = epcRawURI;
+ }
+
+
+ public String getBinary() {
+ return binary;
+ }
+
+
+ public void setBinary(String binary) {
+ this.binary = binary;
+ }
+
+
+ public String getRfidTag() {
+ return rfidTag;
+ }
+
+
+ public void setRfidTag(String rfidTag) {
+ this.rfidTag = rfidTag;
+ }
+
+
+ public String getException() {
+ return exception;
+ }
+
+
+ public void setException(String exception) {
+ this.exception = exception;
+ }
+
+
+
+
+
+
+}
+
+
+
+package org.epctagcoder.result;
+
+public class CPI extends Base {
+ private String componentPartReference;
+ private String serial;
+
+
+
+ public CPI() {
+
+ }
+
+
+
+
+ @Override
+ public String toString() {
+ StringBuilder json = new StringBuilder();
+
+ json.append(String.format("{ \"epcScheme\": \"%s\"", getEpcScheme()))
+ .append(String.format(", \"applicationIdentifier\": \"%s\"", getApplicationIdentifier()))
+ .append(String.format(", \"tagSize\": \"%s\"", getTagSize()))
+ .append(String.format(", \"filterValue\": \"%s\"", getFilterValue()))
+ .append(String.format(", \"partitionValue\": \"%s\"", getPartitionValue()))
+ .append(String.format(", \"prefixLength\": \"%s\"", getPrefixLength()))
+ .append(String.format(", \"companyPrefix\": \"%s\"", getCompanyPrefix()))
+ .append(String.format(", \"componentPartReference\": \"%s\"", getComponentPartReference()))
+ .append(String.format(", \"serial\": \"%s\"", getSerial()))
+ .append(String.format(", \"epcPureIdentityURI\": \"%s\"", getEpcPureIdentityURI()))
+ .append(String.format(", \"epcTagURI\": \"%s\"", getEpcTagURI()))
+ .append(String.format(", \"epcRawURI\": \"%s\"", getEpcRawURI()))
+ .append(String.format(", \"binary\": \"%s\"", getBinary()))
+ .append(String.format(", \"rfidTag\": \"%s\"", getRfidTag())).append(" }");
+
+ return json.toString();
+ }
+
+
+
+
+ public String getComponentPartReference() {
+ return componentPartReference;
+ }
+
+
+
+
+ public void setComponentPartReference(String componentPartReference) {
+ this.componentPartReference = componentPartReference;
+ }
+
+
+
+
+ public String getSerial() {
+ return serial;
+ }
+
+
+
+
+ public void setSerial(String serial) {
+ this.serial = serial;
+ }
+
+
+
+
+
+
+
+}
+
+
+
+package org.epctagcoder.result;
+
+public class GDTI extends Base {
+ private String docType;
+ private String serial;
+ private String checkDigit;
+
+ public GDTI() {
+
+ }
+
+
+ public String getDocType() {
+ return docType;
+ }
+
+ public void setDocType(String docType) {
+ this.docType = docType;
+ }
+
+ public String getSerial() {
+ return serial;
+ }
+
+ public void setSerial(String serial) {
+ this.serial = serial;
+ }
+
+ public String getCheckDigit() {
+ return checkDigit;
+ }
+
+ public void setCheckDigit(String checkDigit) {
+ this.checkDigit = checkDigit;
+ }
+
+
+
+ @Override
+ public String toString() {
+ StringBuilder json = new StringBuilder();
+
+ json.append(String.format("{ \"epcScheme\": \"%s\"", getEpcScheme()))
+ .append(String.format(", \"applicationIdentifier\": \"%s\"", getApplicationIdentifier()))
+ .append(String.format(", \"tagSize\": \"%s\"", getTagSize()))
+ .append(String.format(", \"filterValue\": \"%s\"", getFilterValue()))
+ .append(String.format(", \"partitionValue\": \"%s\"", getPartitionValue()))
+ .append(String.format(", \"prefixLength\": \"%s\"", getPrefixLength()))
+ .append(String.format(", \"companyPrefix\": \"%s\"", getCompanyPrefix()))
+ .append(String.format(", \"docType\": \"%s\"", getDocType()))
+ .append(String.format(", \"serial\": \"%s\"", getSerial()))
+ .append(String.format(", \"checkDigit\": \"%s\"", getCheckDigit()))
+ .append(String.format(", \"epcPureIdentityURI\": \"%s\"", getEpcPureIdentityURI()))
+ .append(String.format(", \"epcTagURI\": \"%s\"", getEpcTagURI()))
+ .append(String.format(", \"epcRawURI\": \"%s\"", getEpcRawURI()))
+ .append(String.format(", \"binary\": \"%s\"", getBinary()))
+ .append(String.format(", \"rfidTag\": \"%s\"", getRfidTag())).append(" }");
+
+ return json.toString();
+ }
+
+
+
+
+
+
+
+
+
+
+
+}
+
+
+
+package org.epctagcoder.result;
+
+public class GIAI extends Base {
+ private String individualAssetReference;
+
+ public GIAI() {
+
+ }
+
+ public String getIndividualAssetReference() {
+ return individualAssetReference;
+ }
+
+ public void setIndividualAssetReference(String individualAssetReference) {
+ this.individualAssetReference = individualAssetReference;
+ }
+
+
+ @Override
+ public String toString() {
+ StringBuilder json = new StringBuilder();
+
+ json.append(String.format("{ \"epcScheme\": \"%s\"", getEpcScheme()))
+ .append(String.format(", \"applicationIdentifier\": \"%s\"", getApplicationIdentifier()))
+ .append(String.format(", \"tagSize\": \"%s\"", getTagSize()))
+ .append(String.format(", \"filterValue\": \"%s\"", getFilterValue()))
+ .append(String.format(", \"partitionValue\": \"%s\"", getPartitionValue()))
+ .append(String.format(", \"prefixLength\": \"%s\"", getPrefixLength()))
+ .append(String.format(", \"companyPrefix\": \"%s\"", getCompanyPrefix()))
+ .append(String.format(", \"individualAssetReference\": \"%s\"", getIndividualAssetReference()))
+ .append(String.format(", \"epcPureIdentityURI\": \"%s\"", getEpcPureIdentityURI()))
+ .append(String.format(", \"epcTagURI\": \"%s\"", getEpcTagURI()))
+ .append(String.format(", \"epcRawURI\": \"%s\"", getEpcRawURI()))
+ .append(String.format(", \"binary\": \"%s\"", getBinary()))
+ .append(String.format(", \"rfidTag\": \"%s\"", getRfidTag())).append(" }");
+
+ return json.toString();
+ }
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+}
+
+
+
+package org.epctagcoder.result;
+
+public class GRAI extends Base {
+ private String assetType;
+ private String serial;
+ private String checkDigit;
+
+ public GRAI() {
+
+ }
+
+
+ public String getAssetType() {
+ return assetType;
+ }
+
+ public void setAssetType(String assetType) {
+ this.assetType = assetType;
+ }
+
+ public String getSerial() {
+ return serial;
+ }
+
+ public void setSerial(String serial) {
+ this.serial = serial;
+ }
+
+ public String getCheckDigit() {
+ return checkDigit;
+ }
+
+ public void setCheckDigit(String checkDigit) {
+ this.checkDigit = checkDigit;
+ }
+
+
+
+ @Override
+ public String toString() {
+ StringBuilder json = new StringBuilder();
+
+ json.append(String.format("{ \"epcScheme\": \"%s\"", getEpcScheme()))
+ .append(String.format(", \"applicationIdentifier\": \"%s\"", getApplicationIdentifier()))
+ .append(String.format(", \"tagSize\": \"%s\"", getTagSize()))
+ .append(String.format(", \"filterValue\": \"%s\"", getFilterValue()))
+ .append(String.format(", \"partitionValue\": \"%s\"", getPartitionValue()))
+ .append(String.format(", \"prefixLength\": \"%s\"", getPrefixLength()))
+ .append(String.format(", \"companyPrefix\": \"%s\"", getCompanyPrefix()))
+ .append(String.format(", \"assetType\": \"%s\"", getAssetType()))
+ .append(String.format(", \"serial\": \"%s\"", getSerial()))
+ .append(String.format(", \"checkDigit\": \"%s\"", getCheckDigit()))
+ .append(String.format(", \"epcPureIdentityURI\": \"%s\"", getEpcPureIdentityURI()))
+ .append(String.format(", \"epcTagURI\": \"%s\"", getEpcTagURI()))
+ .append(String.format(", \"epcRawURI\": \"%s\"", getEpcRawURI()))
+ .append(String.format(", \"binary\": \"%s\"", getBinary()))
+ .append(String.format(", \"rfidTag\": \"%s\"", getRfidTag())).append(" }");
+
+ return json.toString();
+ }
+
+
+
+
+
+
+
+
+
+
+
+}
+
+
+
+package org.epctagcoder.result;
+
+public class GSRN extends Base {
+ private String serviceReference;
+ private String checkDigit;
+
+ public GSRN() {
+
+ }
+
+
+ public String getServiceReference() {
+ return serviceReference;
+ }
+
+ public void setServiceReference(String serviceReference) {
+ this.serviceReference = serviceReference;
+ }
+
+ public String getCheckDigit() {
+ return checkDigit;
+ }
+
+ public void setCheckDigit(String checkDigit) {
+ this.checkDigit = checkDigit;
+ }
+
+
+ @Override
+ public String toString() {
+ StringBuilder json = new StringBuilder();
+
+ json.append(String.format("{ \"epcScheme\": \"%s\"", getEpcScheme()))
+ .append(String.format(", \"applicationIdentifier\": \"%s\"", getApplicationIdentifier()))
+ .append(String.format(", \"tagSize\": \"%s\"", getTagSize()))
+ .append(String.format(", \"filterValue\": \"%s\"", getFilterValue()))
+ .append(String.format(", \"partitionValue\": \"%s\"", getPartitionValue()))
+ .append(String.format(", \"prefixLength\": \"%s\"", getPrefixLength()))
+ .append(String.format(", \"companyPrefix\": \"%s\"", getCompanyPrefix()))
+ .append(String.format(", \"serviceReference\": \"%s\"", getServiceReference()))
+ .append(String.format(", \"checkDigit\": \"%s\"", getCheckDigit()))
+ .append(String.format(", \"epcPureIdentityURI\": \"%s\"", getEpcPureIdentityURI()))
+ .append(String.format(", \"epcTagURI\": \"%s\"", getEpcTagURI()))
+ .append(String.format(", \"epcRawURI\": \"%s\"", getEpcRawURI()))
+ .append(String.format(", \"binary\": \"%s\"", getBinary()))
+ .append(String.format(", \"rfidTag\": \"%s\"", getRfidTag())).append(" }");
+
+
+/*
+ json.append("{ \"epcScheme\": \"").append(getEpcScheme()).append("\"")
+ .append(", \"applicationIdentifier\": \"").append(getApplicationIdentifier()).append("\"")
+ .append(", \"tagSize\": \"").append(getTagSize()).append("\"")
+ .append(", \"filterValue\": \"").append(getFilterValue()).append("\"")
+ .append(", \"partitionValue\": \"").append(getPartitionValue()).append("\"")
+ .append(", \"prefixLength\": \"").append(getPrefixLength()).append("\"")
+ .append(", \"companyPrefix\": \"").append(getCompanyPrefix()).append("\"")
+ .append(", \"serviceReference\": \"").append(getServiceReference()).append("\"")
+ .append(", \"checkDigit\": \"").append(getCheckDigit()).append("\"")
+ .append(", \"epcPureIdentityURI\": \"").append(getEpcPureIdentityURI()).append("\"")
+ .append(", \"epcTagURI\": \"").append(getEpcTagURI()).append("\"")
+ .append(", \"epcRawURI\": \"").append(getEpcRawURI()).append("\"")
+ .append(", \"binary\": \"").append(getBinary()).append("\"")
+ .append(", \"rfidTag\": \"").append(getRfidTag()).append("\" }");
+ */
+
+
+ return json.toString();
+ }
+
+
+
+
+
+
+}
+
+
+
+package org.epctagcoder.result;
+
+public class GSRNP extends Base {
+ private String serviceReference;
+ private String checkDigit;
+
+ public GSRNP() {
+
+ }
+
+
+ public String getServiceReference() {
+ return serviceReference;
+ }
+
+ public void setServiceReference(String serviceReference) {
+ this.serviceReference = serviceReference;
+ }
+
+ public String getCheckDigit() {
+ return checkDigit;
+ }
+
+ public void setCheckDigit(String checkDigit) {
+ this.checkDigit = checkDigit;
+ }
+
+
+ @Override
+ public String toString() {
+ StringBuilder json = new StringBuilder();
+
+ json.append(String.format("{ \"epcScheme\": \"%s\"", getEpcScheme()))
+ .append(String.format(", \"applicationIdentifier\": \"%s\"", getApplicationIdentifier()))
+ .append(String.format(", \"tagSize\": \"%s\"", getTagSize()))
+ .append(String.format(", \"filterValue\": \"%s\"", getFilterValue()))
+ .append(String.format(", \"partitionValue\": \"%s\"", getPartitionValue()))
+ .append(String.format(", \"prefixLength\": \"%s\"", getPrefixLength()))
+ .append(String.format(", \"companyPrefix\": \"%s\"", getCompanyPrefix()))
+ .append(String.format(", \"serviceReference\": \"%s\"", getServiceReference()))
+ .append(String.format(", \"checkDigit\": \"%s\"", getCheckDigit()))
+ .append(String.format(", \"epcPureIdentityURI\": \"%s\"", getEpcPureIdentityURI()))
+ .append(String.format(", \"epcTagURI\": \"%s\"", getEpcTagURI()))
+ .append(String.format(", \"epcRawURI\": \"%s\"", getEpcRawURI()))
+ .append(String.format(", \"binary\": \"%s\"", getBinary()))
+ .append(String.format(", \"rfidTag\": \"%s\"", getRfidTag())).append(" }");
+
+ return json.toString();
+ }
+
+
+
+
+
+
+}
+
+
+
+package org.epctagcoder.result;
+
+public class SGLN extends Base {
+ private String locationReference;
+ private String extension;
+ private String checkDigit;
+
+
+ public SGLN() {
+
+ }
+
+
+ @Override
+ public String toString() {
+ StringBuilder json = new StringBuilder();
+
+ json.append(String.format("{ \"epcScheme\": \"%s\"", getEpcScheme()))
+ .append(String.format(", \"applicationIdentifier\": \"%s\"", getApplicationIdentifier()))
+ .append(String.format(", \"tagSize\": \"%s\"", getTagSize()))
+ .append(String.format(", \"filterValue\": \"%s\"", getFilterValue()))
+ .append(String.format(", \"partitionValue\": \"%s\"", getPartitionValue()))
+ .append(String.format(", \"prefixLength\": \"%s\"", getPrefixLength()))
+ .append(String.format(", \"companyPrefix\": \"%s\"", getCompanyPrefix()))
+ .append(String.format(", \"locationReference\": \"%s\"", getLocationReference()))
+ .append(String.format(", \"extension\": \"%s\"", getExtension()))
+ .append(String.format(", \"checkDigit\": \"%s\"", getCheckDigit()))
+ .append(String.format(", \"epcPureIdentityURI\": \"%s\"", getEpcPureIdentityURI()))
+ .append(String.format(", \"epcTagURI\": \"%s\"", getEpcTagURI()))
+ .append(String.format(", \"epcRawURI\": \"%s\"", getEpcRawURI()))
+ .append(String.format(", \"binary\": \"%s\"", getBinary()))
+ .append(String.format(", \"rfidTag\": \"%s\"", getRfidTag())).append(" }");
+
+ return json.toString();
+ }
+
+
+ public String getLocationReference() {
+ return locationReference;
+ }
+
+
+ public void setLocationReference(String locationReference) {
+ this.locationReference = locationReference;
+ }
+
+
+ public String getExtension() {
+ return extension;
+ }
+
+
+ public void setExtension(String extension) {
+ this.extension = extension;
+ }
+
+
+ public String getCheckDigit() {
+ return checkDigit;
+ }
+
+
+ public void setCheckDigit(String checkDigit) {
+ this.checkDigit = checkDigit;
+ }
+
+
+}
+
+
+
+package org.epctagcoder.result;
+
+public class SGTIN extends Base {
+ private String extensionDigit;
+ private String itemReference;
+ private String serial;
+ private String checkDigit;
+
+ public SGTIN() {
+
+ }
+
+ public String getExtensionDigit() {
+ return extensionDigit;
+ }
+
+ public void setExtensionDigit(String extensionDigit) {
+ this.extensionDigit = extensionDigit;
+ }
+
+ public String getItemReference() {
+ return itemReference;
+ }
+
+ public void setItemReference(String itemReference) {
+ this.itemReference = itemReference;
+ }
+
+ public String getSerial() {
+ return serial;
+ }
+
+ public void setSerial(String serial) {
+ this.serial = serial;
+ }
+
+ public String getCheckDigit() {
+ return checkDigit;
+ }
+
+ public void setCheckDigit(String checkDigit) {
+ this.checkDigit = checkDigit;
+ }
+
+
+
+ @Override
+ public String toString() {
+ StringBuilder json = new StringBuilder();
+
+ json.append(String.format("{ \"epcScheme\": \"%s\"", getEpcScheme()))
+ .append(String.format(", \"applicationIdentifier\": \"%s\"", getApplicationIdentifier()))
+ .append(String.format(", \"tagSize\": \"%s\"", getTagSize()))
+ .append(String.format(", \"filterValue\": \"%s\"", getFilterValue()))
+ .append(String.format(", \"partitionValue\": \"%s\"", getPartitionValue()))
+ .append(String.format(", \"prefixLength\": \"%s\"", getPrefixLength()))
+ .append(String.format(", \"companyPrefix\": \"%s\"", getCompanyPrefix()))
+ .append(String.format(", \"extensionDigit\": \"%s\"", getExtensionDigit()))
+ .append(String.format(", \"itemReference\": \"%s\"", getItemReference()))
+ .append(String.format(", \"serial\": \"%s\"", getSerial()))
+ .append(String.format(", \"checkDigit\": \"%s\"", getCheckDigit()))
+ .append(String.format(", \"epcPureIdentityURI\": \"%s\"", getEpcPureIdentityURI()))
+ .append(String.format(", \"epcTagURI\": \"%s\"", getEpcTagURI()))
+ .append(String.format(", \"epcRawURI\": \"%s\"", getEpcRawURI()))
+ .append(String.format(", \"binary\": \"%s\"", getBinary()))
+ .append(String.format(", \"rfidTag\": \"%s\"", getRfidTag())).append(" }");
+
+ return json.toString();
+ }
+
+
+
+
+
+
+
+
+}
+
+
+
+package org.epctagcoder.result;
+
+public class SSCC extends Base {
+ private String extensionDigit;
+ private String serial;
+ private String checkDigit;
+
+ public SSCC() {
+
+ }
+
+ public String getExtensionDigit() {
+ return extensionDigit;
+ }
+
+ public void setExtensionDigit(String extensionDigit) {
+ this.extensionDigit = extensionDigit;
+ }
+
+ public String getSerial() {
+ return serial;
+ }
+
+ public void setSerial(String serial) {
+ this.serial = serial;
+ }
+
+ public String getCheckDigit() {
+ return checkDigit;
+ }
+
+ public void setCheckDigit(String checkDigit) {
+ this.checkDigit = checkDigit;
+ }
+
+
+
+ @Override
+ public String toString() {
+ StringBuilder json = new StringBuilder();
+
+ json.append(String.format("{ \"epcScheme\": \"%s\"", getEpcScheme()))
+ .append(String.format(", \"applicationIdentifier\": \"%s\"", getApplicationIdentifier()))
+ .append(String.format(", \"tagSize\": \"%s\"", getTagSize()))
+ .append(String.format(", \"filterValue\": \"%s\"", getFilterValue()))
+ .append(String.format(", \"partitionValue\": \"%s\"", getPartitionValue()))
+ .append(String.format(", \"prefixLength\": \"%s\"", getPrefixLength()))
+ .append(String.format(", \"companyPrefix\": \"%s\"", getCompanyPrefix()))
+ .append(String.format(", \"extensionDigit\": \"%s\"", getExtensionDigit()))
+ .append(String.format(", \"serial\": \"%s\"", getSerial()))
+ .append(String.format(", \"checkDigit\": \"%s\"", getCheckDigit()))
+ .append(String.format(", \"epcPureIdentityURI\": \"%s\"", getEpcPureIdentityURI()))
+ .append(String.format(", \"epcTagURI\": \"%s\"", getEpcTagURI()))
+ .append(String.format(", \"epcRawURI\": \"%s\"", getEpcRawURI()))
+ .append(String.format(", \"binary\": \"%s\"", getBinary()))
+ .append(String.format(", \"rfidTag\": \"%s\"", getRfidTag())).append(" }");
+
+ return json.toString();
+ }
+
+
+
+}
+
+
+
+package org.epctagcoder.util;
+
+import java.math.BigDecimal;
+import java.math.BigInteger;
+import java.util.*;
+
+public class Converter {
+ static final Map hexToBinMap = new HashMap<>();
+ static final Map binToHexMap = new HashMap<>();
+
+ static {
+ hexToBinMap.put("0", "0000");
+ hexToBinMap.put("1", "0001");
+ hexToBinMap.put("2", "0010");
+ hexToBinMap.put("3", "0011");
+ hexToBinMap.put("4", "0100");
+ hexToBinMap.put("5", "0101");
+ hexToBinMap.put("6", "0110");
+ hexToBinMap.put("7", "0111");
+ hexToBinMap.put("8", "1000");
+ hexToBinMap.put("9", "1001");
+ hexToBinMap.put("A", "1010");
+ hexToBinMap.put("B", "1011");
+ hexToBinMap.put("C", "1100");
+ hexToBinMap.put("D", "1101");
+ hexToBinMap.put("E", "1110");
+ hexToBinMap.put("F", "1111");
+
+ binToHexMap.put("0000", "0");
+ binToHexMap.put("0001", "1");
+ binToHexMap.put("0010", "2");
+ binToHexMap.put("0011", "3");
+ binToHexMap.put("0100", "4");
+ binToHexMap.put("0101", "5");
+ binToHexMap.put("0110", "6");
+ binToHexMap.put("0111", "7");
+ binToHexMap.put("1000", "8");
+ binToHexMap.put("1001", "9");
+ binToHexMap.put("1010", "A");
+ binToHexMap.put("1011", "B");
+ binToHexMap.put("1100", "C");
+ binToHexMap.put("1101", "D");
+ binToHexMap.put("1110", "E");
+ binToHexMap.put("1111", "F");
+ }
+
+ public static String hexToBin(String hex) {
+ StringBuilder bin = new StringBuilder();
+
+ for (String x: hex.toUpperCase().split("")) {
+ bin.append(Optional.of(x)
+ .map(hexToBinMap::get)
+ .orElseThrow(() -> new IllegalArgumentException(x + " is not a valid hex digit")));
+ }
+
+ return bin.toString();
+ }
+
+ public static String binToHex(String bin) {
+ if (bin.length() % 4 != 0) {
+ throw new IllegalArgumentException("Binary string '" + bin + "' does not represent a valid Hex number");
+ }
+
+ int startIndex = 0;
+ StringBuilder hex = new StringBuilder();
+
+ while (startIndex < bin.length()) {
+ hex.append(binToHexMap.get(bin.substring(startIndex, startIndex + 4)));
+ startIndex += 4;
+ }
+
+ return hex.toString();
+ }
+
+ public static String binToString(String s) {
+ StringBuilder bin = new StringBuilder();
+
+ for (int i = 0; i <= s.length() - 8; i += 8) {
+ int k = Integer.parseInt(s.substring(i, i + 8), 2);
+ bin.append((char) k);
+ }
+
+ return bin.toString().trim();
+ }
+
+ // funciona, substituir?
+ public static String decToBin(String dec, int bits) {
+ return strZero(new BigInteger(dec).toString(2), bits);
+ }
+
+ public static String decToBin(Integer dec, int bits) {
+ return strZero(BigInteger.valueOf(dec.longValue()).toString(2), bits);
+ }
+
+ // funciona, substituir?
+ public static String binToDec(String bin) {
+ return new BigInteger(bin, 2).toString();
+ }
+
+ // montei esse, d� d� descartar
+ public static String binToDec2(String bin) {
+ int len = bin.length();
+ int rev = len - 1;
+ BigDecimal d = new BigDecimal("0");
+
+ StringBuilder dec = new StringBuilder();
+ for (int i = 0; i < len; i++) {
+ String pos = bin.substring(i, i + 1);
+ d = d.add(new BigDecimal(pos).multiply(new BigDecimal("2").pow(rev)));
+ rev--;
+ }
+ dec.append(d);
+ return dec.toString();
+ }
+
+ // http://stackoverflow.com/questions/4211705/binary-to-text-in-java?noredirect=1&lq=1
+ public static String convertBinToBit(String s, int fromBit, int toBit) {
+ StringBuilder bin = new StringBuilder();
+ // https://stackoverflow.com/a/3760193/1696733
+ for (int start = 0; start < s.length(); start += fromBit) {
+ String a = s.substring(start, Math.min(s.length(), start + fromBit));
+ bin.append(lPadZero(Integer.parseInt(a), toBit));
+ }
+
+ return bin.toString();
+ }
+
+ public static String fill(String text, int size) {
+ StringBuilder builder = new StringBuilder(text);
+ while (builder.length() < size) {
+ builder.append('0');
+ }
+ return builder.toString();
+ }
+
+ //http://stackoverflow.com/questions/917163/convert-a-string-like-testing123-to-binary-in-java
+ public static String StringToBinary(String str, int bits) {
+ StringBuilder result = new StringBuilder();
+ String tmpStr;
+ int tmpInt;
+ char[] messChar = str.toCharArray();
+
+ for (char c: messChar) {
+ tmpStr = Integer.toBinaryString(c);
+ tmpInt = tmpStr.length();
+ if (tmpInt != bits) {
+ tmpInt = bits - tmpInt;
+ if (tmpInt == bits) {
+ result.append(tmpStr);
+ } else if (tmpInt > 0) {
+ for (int j = 0; j < tmpInt; j++) {
+ result.append("0");
+ }
+ result.append(tmpStr);
+ } else {
+ System.err.println("argument 'bits' is too small");
+ }
+ } else {
+ result.append(tmpStr);
+ }
+ }
+
+ return result.toString();
+ }
+
+ public static String lPadZero(int in, int fill) {
+
+ boolean negative = false;
+ int value, len = 0;
+
+ if (in >= 0) {
+ value = in;
+ } else {
+ negative = true;
+ value = -in;
+ in = -in;
+ len++;
+ }
+
+ if (value == 0) {
+ len = 1;
+ } else {
+ for (; value != 0; len++) {
+ value /= 10;
+ }
+ }
+
+ StringBuilder sb = new StringBuilder();
+
+ if (negative) {
+ sb.append('-');
+ }
+
+ for (int i = fill; i > len; i--) {
+ sb.append('0');
+ }
+
+ sb.append(in);
+
+ return sb.toString();
+ }
+
+ public static String strZero(String str, int len) {
+
+ StringBuilder sb = new StringBuilder();
+
+ for (int toPrepend = len - str.length(); toPrepend > 0; toPrepend--) {
+ sb.append('0');
+ }
+
+ sb.append(str);
+ return sb.toString();
+ }
+
+ public static boolean isNumeric(String str) {
+ return str.chars().allMatch(Character::isDigit);
+ }
+
+ public static List splitEqually(String text, int size) {
+ List ret = new ArrayList<>((text.length() + size - 1) / size);
+
+ for (int start = 0; start < text.length(); start += size) {
+ ret.add(text.substring(start, Math.min(text.length(), start + size)));
+ }
+ return ret;
+ }
+}
+
+
+
+#Wed Jul 19 10:01:18 HKT 2023
+distributionBase=GRADLE_USER_HOME
+distributionPath=wrapper/dists
+distributionUrl=https\://services.gradle.org/distributions/gradle-8.11.1-bin.zip
+zipStoreBase=GRADLE_USER_HOME
+zipStorePath=wrapper/dists
+
+
+
+# CS710S-JAVA-APP-for-ANDROID
+
+CS710S Android Java Bluetooth Demo App and SDK
+
+This application provides demonstrations to the programming interface made available for configuring, controlling, and accessing the CS710S RFID reader. The development was based on the CS710S Java API.
+
+[Product Information](https://www.convergence.com.hk/cs710s/)
+
+
+## Pre-requisite
+
+The development environment consists of the following:
+- Android Studio Giraffe
+- Android SDK API Level 36 (compileSdk 36, minSdk 26, targetSdk 36)
+- Microsoft Windows 10/11 or Mac OSX or Linux
+
+---
+
+# AI Tools & Workflow in Development
+
+This project applied AI tools to assist in code analysis, refactoring, and pruning, ensuring a structured and safe process for maintaining the repository. The workflow emphasizes repeatability and clarity for both new and experienced developers.
+
+## AI Tools
+ - **Grok (by xAI)**, **Claude (Anthropic)**, or **ChatGPT (OpenAI)**
+
+## AI Objectives
+ - Handling large contexts (e.g., ~9M+ character repomixed codebase).
+ - Deep repository “prospecting” (dependency mapping, structure analysis from `CS710S-Java-ENTIRE-CONTEXT.txt` or `CS710S-Java-ENTIRE-CONTEXT.xml`).
+
+## General Workflow
+1. **Preparation**
+ - Backup repo (`git branch prune-`).
+ - Load in Android Studio (Windows/Mac/Linux).
+
+2. **AI-Assisted Prospecting**
+ - Upload `CS710S-Java-ENTIRE-CONTEXT.txt` or `CS710S-Java-ENTIRE-CONTEXT.xml` to your preferred LLM.
+ - Query LLM with specific context (see prompts from `prompts.md`).
+
+3. **Iterative Pruning**
+ - Target one feature at a time (e.g., “Register Tag”).
+ - Trace dependencies:
+ - Primary, Secondary, Tertiary, etc: ensure all nested references are cleanly acknowledged
+ - Holistically remove imports, update refs
+
+4. **Verification**
+ - Rebuild
+ - Confirm build remains clean
+ - Test preserved features, ensure application runs as expected.
+ - Run on emulator/device, check logs.
+ - Publish incremental commits ensuring backtracking is possible.
+
+5. **Documentation**
+ - Update README and related supporting files.
+ - Review and borrow prompts/templates from (`prompts.md`).
+
+---
+
+## Notes on Android Studio Workflow (With Emulator)
+1. **Clean the Project**: In Android Studio, go to `Build` > `Clean Project` to remove all compiled files and ensure a fresh build.
+2. **Sync and Rebuild**: Select `File` > `Sync Project with Gradle Files`, then `Build` > `Rebuild Project` to compile.
+3. **Deploy to Emulator**: Configure emulator (e.g., x86_64), select `Run` > `Run 'app'` to deploy and run.
+
+---
+
+## Notes on Repomix
+The `CS710S-Java-ENTIRE-CONTEXT.*` files are comprehensive, packed representations of the entire codebase, generated by Repomix—a tool that consolidates source code, projects, and docs into a single, AI-consumable format (e.g., .txt or .xml). The `repomix-config.json` file configures Repomix to include/exclude files, define output structure, and ensure full content without truncation, tailoring the pack to our needs. This setup makes our codebase "AI Ready" by enabling deep analysis of BLE/RFID flows, dependency mapping, and optimization suggestions via AI tools like Grok, Claude, ChatGPT, etc, streamlining development and maintenance for the CS710S app.
+
+- Select either `CS710S-Java-ENTIRE-CONTEXT.txt` or `CS710S-Java-ENTIRE-CONTEXT.xml` based on LLM upload policies. Both contain identical content; the only difference is the file extension, which supports different formats.
+
+- [Learn more about Repomix](https://github.com/yamadashy/repomix)
+
+
+
+# Repomix Instructions — CS710S Android (Java)
+
+**Goal**
+Produce a single packed context for AI agents to analyze BLE and RFID flows in the CS710S handheld reader app on Android (Java + Gradle), excluding build artifacts, binaries, and noise. Ensure the full output is generated without truncation.
+
+---
+
+## What to Include (Priority Order)
+1) Build & Modules
+- `build.gradle`
+- `settings.gradle`
+- `app/build.gradle`
+- `cslibrary4a/build.gradle`
+- `epctagcoder/build.gradle`
+
+2) Core Library (RFID + HAL + Tools)
+- `cslibrary4a/src/main/java/com/csl/cslibrary4a/*.java`
+ - RFID Unified API: `Cs108Library4A.java`, `Cs710Library4A.java`, `CsLibrary4A.java` (Host commands, inventory/access ops; CS710S focus)
+ - Comm Protocol: `RfidReaderChipData.java`, `RfidReaderChipR2000.java`, `RfidReaderChipE710.java`
+ - HAL BLE: `BluetoothConnector.java`, `BluetoothGatt.java`, `RfidConnector.java`
+ - Utilities: `Utility.java`, `AesCmac.java`, `DeviceFinder.java`
+
+3) Android App (UI + Tasks)
+- `app/src/main/java/com/csl/cs710ademoapp/*.java` (Main logic, fragments, tasks)
+- `app/src/main/java/com/csl/cs710ademoapp/fragments/*.java` (e.g., InventoryFragment.java, AccessReadWriteFragment.java)
+- `app/src/main/java/com/csl/cs710ademoapp/adapters/*.java`
+- `app/src/main/AndroidManifest.xml`
+- `app/src/main/res/values/*.xml`
+- `app/src/main/res/layout/*.xml`
+
+4) EPC Tag Coder
+- `epctagcoder/src/main/java/org/epctagcoder/*.java` (Parse/encode EPC schemes: SGTIN, SSCC, etc.)
+- `epctagcoder/src/main/java/org/epctagcoder/option/*.java`
+- `epctagcoder/src/main/java/org/epctagcoder/parse/*.java`
+- `epctagcoder/src/main/java/org/epctagcoder/result/*.java`
+
+5) Docs / Metadata
+- `README.md`
+- `repomix-instructions.md`
+- `repomix-config.json` (For Repomix self-reference)
+
+---
+
+## Exclude (Noise & Generated)
+- Build & IDE: `**/build/**`, `**/.gradle/**`, `.idea/**`, `.vscode/**`
+- Packages & Dependencies: `**/*.jar`, `**/*.aar`
+- Generated: `**/R.java`, `**/*.class`
+- Binaries/Archives: `**/*.dll`, `**/*.so`, `**/*.a`, `**/*.nupkg`, `**/*.keystore`, `**/*.apk`, `**/*.aab`, `**/*.zip`
+- Images/Misc: `**/*.png`, `**/*.jpg`, `**/*.gif`, `**/*.pdf`
+- Local Config: `**/*.iml`, `local.properties`, `**/*.user`
+
+---
+
+## Logical Read Order (for AI Prospecting)
+Guide AI agents in "prospecting" interconnected paths:
+1) `settings.gradle` → Module dependencies.
+2) App Entry: `app/src/main/java/com/csl/cs710ademoapp/MainActivity.java` (App bootstrap, NFC/USB intents).
+3) Fragments/UI: `app/src/main/java/com/csl/cs710ademoapp/fragments/*.java` (e.g., InventoryFragment.java, ConnectionFragment.java for BLE scanning).
+4) BLE HAL: `cslibrary4a/src/main/java/com/csl/cslibrary4a/BluetoothConnector.java`, `RfidConnector.java` (Device discovery, GATT via Android BLE).
+5) RFID Unified API (CS710S Focus): `cslibrary4a/src/main/java/com/csl/cslibrary4a/Cs710Library4A.java`, `RfidReaderChipE710.java` (Public ops: inventory/read/write/antenna/power—trace to chip-specific layers).
+6) Comm Protocol: `cslibrary4a/src/main/java/com/csl/cslibrary4a/Rx000Commands` (via RfidReaderChipData.HostCommands).
+7) Tasks/Utilities: `app/src/main/java/com/csl/cs710ademoapp/AccessTask.java`, `InventoryRfidTask.java`; `epctagcoder/src/main/java/org/epctagcoder/parse/*.java`.
+
+This order reflects app flow: Android bootstrap → Fragment navigation → BLE connect/scan → RFID operations. Emphasize tracing dependencies (e.g., how MainActivity invokes library ops in AsyncTasks).
+
+---
+
+## Summarization Hints (Chunking for AI)
+- Group by Feature: **BLE Connect** (BluetoothConnector + fragments), **Inventory** (InventoryRfidTask.java, RfidReader), **Read/Write** (AccessTask.java, HostCommands), **Antenna/Power** (SettingData.java, powerLevel params), **Tag Filters/QT** (setSelectCriteria), **Errors/Status** (decodedError in Rx000pkgData).
+- Limit chunks to ≤2k tokens; prefix each with file paths.
+- Cross-link public APIs to private implementations (e.g., CsLibrary4A.publicAccess → RfidReaderChipE710).
+- Note response modes (compact/normal/extended) in tag operations via HostCmdResponseTypes.
+- Flag Token-Heavy Files (>1k tokens): `AccessTask.java`, `MainActivity.java`, `CsLibrary4A.java`—suggest splitting in AI analysis.
+
+---
+
+## Important Callouts
+- Android: `MainActivity.java`, `AndroidManifest.xml`, `res/values/strings.xml`.
+- Fragments/Tasks: `InventoryFragment.java`, `AccessReadWriteFragment.java`, `AccessTask.java`.
+- CS710S API: Public (`Cs710Library4A.java`, `RfidReader`), Operations (`RfidReaderChipE710.java` for read/write/inventory/select), Antenna/Power (`SettingData.java`), Protocol (`RfidReaderChipData.HostCommands`).
+- EPC: `epctagcoder/parse/SGTIN/ParseSGTIN.java`, `result/SGTIN.java`.
+- Utilities: `Utility.java`, `Converter.java` (hex/bin conversions).
+
+---
+
+## Output Requirements
+- Single packed file: **Summary → Repo Info → Structure → Files (path + contents)**.
+- Preserve code blocks verbatim; include file headers.
+- Mark **excluded** areas clearly.
+- Note token-heavy files with byte/token counts.
+- Use relative paths from repo root.
+- Style: XML, with file summaries and directory structure.
+- Ensure full output without truncation (support up to 100MB).
+
+---
+
+## Build Context
+- Targets: Android (minSdk 26, targetSdk 36; armeabi-v7a, arm64-v8a, x86_64 for emulators).
+- Key Dependencies: `com.google.android.material:material:1.12.0`, `org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.2.5`.
+- Build: Open in Android Studio → Sync Gradle → Select `app` → Debug/Release → Deploy to device/emulator.
+
+---
+
+## Quality Checks (for AI Post-Packing)
+- Flag BLE timing issues, UI thread handling, and disconnect edges (e.g., in BluetoothGatt, AsyncTask cancellations).
+- Confirm frequency/power settings are configurable (e.g., setAccessPowerLevel).
+- Verify no UI-blocking I/O; check AsyncTask progress in inventory/reads (e.g., AccessTask.doInBackground).
+
+
+
+{
+ "input": {
+ "maxFileSize": 100000000
+ },
+ "output": {
+ "filePath": "CS710S-Java-ENTIRE-CONTEXT.xml",
+ "style": "xml",
+ "parsableStyle": true,
+ "compress": true,
+ "headerText": "Packed CS710S Android codebase for AI analysis of BLE/RFID flows, including Java source, projects, and docs.",
+ "instructionFilePath": "repomix-instruction.md",
+ "fileSummary": true,
+ "directoryStructure": true,
+ "files": true,
+ "removeComments": false,
+ "removeEmptyLines": false,
+ "showLineNumbers": false,
+ "truncateBase64": false,
+ "copyToClipboard": false,
+ "includeEmptyDirectories": false,
+ "topFilesLength": 5,
+ "tokenCountTree": 1000
+ },
+ "include": [
+ "app/src/**",
+ "cslibrary4a/src/main/**",
+ "epctagcoder/src/main/**",
+ "gradle/**",
+ "README.md",
+ "repomix-instruction.md",
+ "repomix.config.json"
+ ],
+ "ignore": {
+ "useGitignore": true,
+ "useDefaultPatterns": true,
+ "customPatterns": [
+ "**/bin/**",
+ "**/obj/**",
+ "**/Debug/**",
+ "**/Release/**",
+ "**/.vs/**",
+ "**/TestResult*/**",
+ "**/node_modules/**",
+ "**/*.dll",
+ "**/*.so",
+ "**/*.a",
+ "**/*.jar",
+ "**/*.aar",
+ "**/*.nupkg",
+ "**/*.keystore",
+ "**/*.apk",
+ "**/*.aab",
+ "**/*.zip",
+ "**/*.png",
+ "**/*.jpg",
+ "**/*.gif",
+ "**/*.pdf",
+ "**/*.user",
+ "**/*.userprefs"
+ ]
+ },
+ "security": {
+ "enableSecurityCheck": false
+ },
+ "tokenCount": {
+ "encoding": "o200k_base"
+ },
+ "git": {
+ "includeLogs": false,
+ "sortByChanges": false,
+ "sortByChangesMaxCommits": 0,
+ "includeDiffs": false,
+ "includeLogsCount": 0
+ },
+ "metadata": {
+ "version": "1.0",
+ "lastUpdated": "2025-08-29",
+ "description": "Configuration for packing CS710S Android codebase for AI analysis."
+ }
+}
+
+
+
+
+
+# Repomix Instructions — CS710S Android (Java)
+
+**Goal**
+Produce a single packed context for AI agents to analyze BLE and RFID flows in the CS710S handheld reader app on Android (Java + Gradle), excluding build artifacts, binaries, and noise. Ensure the full output is generated without truncation.
+
+---
+
+## What to Include (Priority Order)
+1) Build & Modules
+- `build.gradle`
+- `settings.gradle`
+- `app/build.gradle`
+- `cslibrary4a/build.gradle`
+- `epctagcoder/build.gradle`
+
+2) Core Library (RFID + HAL + Tools)
+- `cslibrary4a/src/main/java/com/csl/cslibrary4a/*.java`
+ - RFID Unified API: `Cs108Library4A.java`, `Cs710Library4A.java`, `CsLibrary4A.java` (Host commands, inventory/access ops; CS710S focus)
+ - Comm Protocol: `RfidReaderChipData.java`, `RfidReaderChipR2000.java`, `RfidReaderChipE710.java`
+ - HAL BLE: `BluetoothConnector.java`, `BluetoothGatt.java`, `RfidConnector.java`
+ - Utilities: `Utility.java`, `AesCmac.java`, `DeviceFinder.java`
+
+3) Android App (UI + Tasks)
+- `app/src/main/java/com/csl/cs710ademoapp/*.java` (Main logic, fragments, tasks)
+- `app/src/main/java/com/csl/cs710ademoapp/fragments/*.java` (e.g., InventoryFragment.java, AccessReadWriteFragment.java)
+- `app/src/main/java/com/csl/cs710ademoapp/adapters/*.java`
+- `app/src/main/AndroidManifest.xml`
+- `app/src/main/res/values/*.xml`
+- `app/src/main/res/layout/*.xml`
+
+4) EPC Tag Coder
+- `epctagcoder/src/main/java/org/epctagcoder/*.java` (Parse/encode EPC schemes: SGTIN, SSCC, etc.)
+- `epctagcoder/src/main/java/org/epctagcoder/option/*.java`
+- `epctagcoder/src/main/java/org/epctagcoder/parse/*.java`
+- `epctagcoder/src/main/java/org/epctagcoder/result/*.java`
+
+5) Docs / Metadata
+- `README.md`
+- `repomix-instructions.md`
+- `repomix-config.json` (For Repomix self-reference)
+
+---
+
+## Exclude (Noise & Generated)
+- Build & IDE: `**/build/**`, `**/.gradle/**`, `.idea/**`, `.vscode/**`
+- Packages & Dependencies: `**/*.jar`, `**/*.aar`
+- Generated: `**/R.java`, `**/*.class`
+- Binaries/Archives: `**/*.dll`, `**/*.so`, `**/*.a`, `**/*.nupkg`, `**/*.keystore`, `**/*.apk`, `**/*.aab`, `**/*.zip`
+- Images/Misc: `**/*.png`, `**/*.jpg`, `**/*.gif`, `**/*.pdf`
+- Local Config: `**/*.iml`, `local.properties`, `**/*.user`
+
+---
+
+## Logical Read Order (for AI Prospecting)
+Guide AI agents in "prospecting" interconnected paths:
+1) `settings.gradle` → Module dependencies.
+2) App Entry: `app/src/main/java/com/csl/cs710ademoapp/MainActivity.java` (App bootstrap, NFC/USB intents).
+3) Fragments/UI: `app/src/main/java/com/csl/cs710ademoapp/fragments/*.java` (e.g., InventoryFragment.java, ConnectionFragment.java for BLE scanning).
+4) BLE HAL: `cslibrary4a/src/main/java/com/csl/cslibrary4a/BluetoothConnector.java`, `RfidConnector.java` (Device discovery, GATT via Android BLE).
+5) RFID Unified API (CS710S Focus): `cslibrary4a/src/main/java/com/csl/cslibrary4a/Cs710Library4A.java`, `RfidReaderChipE710.java` (Public ops: inventory/read/write/antenna/power—trace to chip-specific layers).
+6) Comm Protocol: `cslibrary4a/src/main/java/com/csl/cslibrary4a/Rx000Commands` (via RfidReaderChipData.HostCommands).
+7) Tasks/Utilities: `app/src/main/java/com/csl/cs710ademoapp/AccessTask.java`, `InventoryRfidTask.java`; `epctagcoder/src/main/java/org/epctagcoder/parse/*.java`.
+
+This order reflects app flow: Android bootstrap → Fragment navigation → BLE connect/scan → RFID operations. Emphasize tracing dependencies (e.g., how MainActivity invokes library ops in AsyncTasks).
+
+---
+
+## Summarization Hints (Chunking for AI)
+- Group by Feature: **BLE Connect** (BluetoothConnector + fragments), **Inventory** (InventoryRfidTask.java, RfidReader), **Read/Write** (AccessTask.java, HostCommands), **Antenna/Power** (SettingData.java, powerLevel params), **Tag Filters/QT** (setSelectCriteria), **Errors/Status** (decodedError in Rx000pkgData).
+- Limit chunks to ≤2k tokens; prefix each with file paths.
+- Cross-link public APIs to private implementations (e.g., CsLibrary4A.publicAccess → RfidReaderChipE710).
+- Note response modes (compact/normal/extended) in tag operations via HostCmdResponseTypes.
+- Flag Token-Heavy Files (>1k tokens): `AccessTask.java`, `MainActivity.java`, `CsLibrary4A.java`—suggest splitting in AI analysis.
+
+---
+
+## Important Callouts
+- Android: `MainActivity.java`, `AndroidManifest.xml`, `res/values/strings.xml`.
+- Fragments/Tasks: `InventoryFragment.java`, `AccessReadWriteFragment.java`, `AccessTask.java`.
+- CS710S API: Public (`Cs710Library4A.java`, `RfidReader`), Operations (`RfidReaderChipE710.java` for read/write/inventory/select), Antenna/Power (`SettingData.java`), Protocol (`RfidReaderChipData.HostCommands`).
+- EPC: `epctagcoder/parse/SGTIN/ParseSGTIN.java`, `result/SGTIN.java`.
+- Utilities: `Utility.java`, `Converter.java` (hex/bin conversions).
+
+---
+
+## Output Requirements
+- Single packed file: **Summary → Repo Info → Structure → Files (path + contents)**.
+- Preserve code blocks verbatim; include file headers.
+- Mark **excluded** areas clearly.
+- Note token-heavy files with byte/token counts.
+- Use relative paths from repo root.
+- Style: XML, with file summaries and directory structure.
+- Ensure full output without truncation (support up to 100MB).
+
+---
+
+## Build Context
+- Targets: Android (minSdk 26, targetSdk 36; armeabi-v7a, arm64-v8a, x86_64 for emulators).
+- Key Dependencies: `com.google.android.material:material:1.12.0`, `org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.2.5`.
+- Build: Open in Android Studio → Sync Gradle → Select `app` → Debug/Release → Deploy to device/emulator.
+
+---
+
+## Quality Checks (for AI Post-Packing)
+- Flag BLE timing issues, UI thread handling, and disconnect edges (e.g., in BluetoothGatt, AsyncTask cancellations).
+- Confirm frequency/power settings are configurable (e.g., setAccessPowerLevel).
+- Verify no UI-blocking I/O; check AsyncTask progress in inventory/reads (e.g., AccessTask.doInBackground).
+
diff --git a/README.md b/README.md
index 93f191a..50c315f 100644
--- a/README.md
+++ b/README.md
@@ -1,15 +1,70 @@
# CS710S-JAVA-APP-for-ANDROID
-CS710D Android Java Bluetooth Demo App and SDK
+CS710S Android Java Bluetooth Demo App and SDK
This application provides demonstrations to the programming interface made available for configuring, controlling, and accessing the CS710S RFID reader. The development was based on the CS710S Java API.
[Product Information](https://www.convergence.com.hk/cs710s/)
-## Pre-requsite
+## Pre-requisite
The development environment consists of the following:
- Android Studio Giraffe
-- Android SDK API Level 32
+- Android SDK API Level 36 (compileSdk 36, minSdk 26, targetSdk 36)
- Microsoft Windows 10/11 or Mac OSX or Linux
+
+---
+
+# AI Tools & Workflow in Development
+
+This project applied AI tools to assist in code analysis, refactoring, and pruning, ensuring a structured and safe process for maintaining the repository. The workflow emphasizes repeatability and clarity for both new and experienced developers.
+
+## AI Tools
+ - **Grok (by xAI)**, **Claude (Anthropic)**, or **ChatGPT (OpenAI)**
+
+## AI Objectives
+ - Handling large contexts (e.g., ~9M+ character repomixed codebase).
+ - Deep repository “prospecting” (dependency mapping, structure analysis from `CS710S-Java-ENTIRE-CONTEXT.txt` or `CS710S-Java-ENTIRE-CONTEXT.xml`).
+
+## General Workflow
+1. **Preparation**
+ - Backup repo (`git branch prune-`).
+ - Load in Android Studio (Windows/Mac/Linux).
+
+2. **AI-Assisted Prospecting**
+ - Upload `CS710S-Java-ENTIRE-CONTEXT.txt` or `CS710S-Java-ENTIRE-CONTEXT.xml` to your preferred LLM.
+ - Query LLM with specific context (see prompts from `prompts.md`).
+
+3. **Iterative Pruning**
+ - Target one feature at a time (e.g., “Register Tag”).
+ - Trace dependencies:
+ - Primary, Secondary, Tertiary, etc: ensure all nested references are cleanly acknowledged
+ - Holistically remove imports, update refs
+
+4. **Verification**
+ - Rebuild
+ - Confirm build remains clean
+ - Test preserved features, ensure application runs as expected.
+ - Run on emulator/device, check logs.
+ - Publish incremental commits ensuring backtracking is possible.
+
+5. **Documentation**
+ - Update README and related supporting files.
+ - Review and borrow prompts/templates from (`prompts.md`).
+
+---
+
+## Notes on Android Studio Workflow (With Emulator)
+1. **Clean the Project**: In Android Studio, go to `Build` > `Clean Project` to remove all compiled files and ensure a fresh build.
+2. **Sync and Rebuild**: Select `File` > `Sync Project with Gradle Files`, then `Build` > `Rebuild Project` to compile.
+3. **Deploy to Emulator**: Configure emulator (e.g., x86_64), select `Run` > `Run 'app'` to deploy and run.
+
+---
+
+## Notes on Repomix
+The `CS710S-Java-ENTIRE-CONTEXT.*` files are comprehensive, packed representations of the entire codebase, generated by Repomix—a tool that consolidates source code, projects, and docs into a single, AI-consumable format (e.g., .txt or .xml). The `repomix-config.json` file configures Repomix to include/exclude files, define output structure, and ensure full content without truncation, tailoring the pack to our needs. This setup makes our codebase "AI Ready" by enabling deep analysis of BLE/RFID flows, dependency mapping, and optimization suggestions via AI tools like Grok, Claude, ChatGPT, etc, streamlining development and maintenance for the CS710S app.
+
+- Select either `CS710S-Java-ENTIRE-CONTEXT.txt` or `CS710S-Java-ENTIRE-CONTEXT.xml` based on LLM upload policies. Both contain identical content; the only difference is the file extension, which supports different formats.
+
+- [Learn more about Repomix](https://github.com/yamadashy/repomix)
\ No newline at end of file
diff --git a/app/src/main/java/com/csl/cs710ademoapp/AccessTask1.java b/app/src/main/java/com/csl/cs710ademoapp/AccessTask1.java
deleted file mode 100644
index 6786811..0000000
--- a/app/src/main/java/com/csl/cs710ademoapp/AccessTask1.java
+++ /dev/null
@@ -1,203 +0,0 @@
-package com.csl.cs710ademoapp;
-
-import android.os.AsyncTask;
-import android.widget.Button;
-import android.widget.Toast;
-
-import com.csl.cslibrary4a.RfidReaderChipData;
-
-public class AccessTask1 {
- Button button;
- boolean invalidRequest;
- int accBank, accOffset, accSize, accSizeNow, accBlockCount = 90; String accWriteData, accWriteDataNow;
- String selectMask;
- int selectBank, selectOffset;
- String strPassword;
- int powerLevel;
- RfidReaderChipData.HostCommands hostCommand;
- Runnable updateRunnable = null;
-
- AccessTask accessTask;
- public AccessTask1(Button button, boolean invalidRequest,
- int accBank, int accOffset, int accSize, int accBlockCount, String accWriteData,
- String selectMask, int selectBank, int selectOffset,
- String strPassword, int powerLevel, RfidReaderChipData.HostCommands hostCommand, Runnable updateRunnable) {
- this.button = button;
- this.invalidRequest = invalidRequest;
- MainActivity.csLibrary4A.appendToLog("HelloK: invalidRequest=" + invalidRequest);
- this.accBank = accBank;
- this.accOffset = accOffset;
- if (hostCommand == RfidReaderChipData.HostCommands.CMD_18K6CWRITE) { if (accBlockCount > 16) accBlockCount = 16; }
- else if (accBlockCount > 255) accBlockCount = 255;
- this.accBlockCount = accBlockCount;
- if (accWriteData == null) accWriteData = "";
- if (hostCommand == RfidReaderChipData.HostCommands.CMD_18K6CWRITE) {
- MainActivity.csLibrary4A.appendToLog("strOut: accWriteData=" + accWriteData);
- accWriteData = deformatWriteAccessData(accWriteData);
- if (accWriteData.length() < accSize * 4) {
- accSize = accWriteData.length()/4;
- if (accSize*4 != accWriteData.length()) accSize++;
- }
- }
- this.accSize = accSize;
- if (accSize == 0) {
- isResultReady = true;
- accessResult = "";
- }
- this.accWriteData = accWriteData;
- this.selectMask = selectMask;
- this.selectBank = selectBank;
- this.selectOffset = selectOffset;
- this.strPassword = strPassword;
- this.powerLevel = powerLevel;
- this.hostCommand = hostCommand;
- this.updateRunnable = updateRunnable;
- MainActivity.csLibrary4A.appendToLog("HelloA, AccessTask1");
- CustomMediaPlayer playerN = MainActivity.sharedObjects.playerN;
- playerN.start();
- setup();
- }
-
- public void execute() {
- if (accessTask != null) accessTask.execute();
- }
-
- public boolean cancel(boolean bCancel) {
- if (accessTask == null) return true;
- return accessTask.cancel(bCancel);
- }
-
- public AsyncTask.Status getStatus() {
- if (accessTask == null) return AsyncTask.Status.FINISHED;
- return accessTask.getStatus();
- }
-
- public String deformatWriteAccessData(String strIn) {
- MainActivity.csLibrary4A.appendToLog("strOut: strIn=" + strIn);
- String strOut = strIn.replaceAll("\\P{Print}", "");
- MainActivity.csLibrary4A.appendToLog("strOut=" + strOut);
- while (strOut.indexOf(":") > 0) {
- int index = strOut.indexOf(":");
- String writeDataTemp = "";
- if (index > 4) writeDataTemp = strOut.substring(0, index - 3);
- writeDataTemp += strOut.substring(index + 1);
- strOut = writeDataTemp;
- MainActivity.csLibrary4A.appendToLog("strOut=" + strOut);
- }
- MainActivity.csLibrary4A.appendToLog("strOut=" + strOut);
- return strOut;
- }
-
- boolean isResultReady = false; int tryCount = 0, tryCountMax = 8;
- public boolean isResultReady() {
- boolean bValue = false;
- if (accessTask == null) { }
- else if (accessTask.getStatus() != AsyncTask.Status.FINISHED) { }
- else if (button.getText().toString().indexOf("ING") > 0) { }
- else if (isResultReady == false) {
- String strAccessResult = "";
- if (hostCommand != RfidReaderChipData.HostCommands.CMD_18K6CREAD || accBank != 3) strAccessResult = accessTask.accessResult;
- else {
- int word4line = 7;
- for (int i = 0; i < accSizeNow; i=i+word4line) {
- if (tryCount < tryCountMax && accessTask.accessResult == null) break;
- strAccessResult += String.format("%03d:", accOffset + i);
- if (accessTask.accessResult != null) {
- if ((i + word4line) * 4 >= accessTask.accessResult.length()) {
- int iLastWordIndex = accessTask.accessResult.substring(i * 4).length() / 4;
- if (iLastWordIndex * 4 != accessTask.accessResult.substring(i * 4).length())
- iLastWordIndex++;
- strAccessResult += String.format("%03d:", accOffset + i + iLastWordIndex - 1) + accessTask.accessResult.substring(i * 4);
- } else
- strAccessResult += accessTask.accessResult.substring(i * 4, (i + word4line) * 4);
- }
- strAccessResult += "\n";
- MainActivity.csLibrary4A.appendToLog("i=" + i + ", formatted accessTask.accessResult=" + strAccessResult);
- }
- }
- if (accessResult == null) accessResult = strAccessResult;
- else accessResult += strAccessResult;
-
- MainActivity.csLibrary4A.appendToLog("HelloA: accessResult=" + accessTask.accessResult);
- if (accessTask.accessResult != null && accSizeNow >= accSize) {
- bValue = true;
- Toast.makeText(MainActivity.mContext, R.string.toast_abort_by_SUCCESS, Toast.LENGTH_SHORT).show();
- }
- else {
- if (accessTask.accessResult != null) {
- accOffset += accSizeNow;
- accSize -= accSizeNow;
- if (accWriteData != null) { if (accWriteData.length() >= accSizeNow*4) accWriteData = accWriteData.substring(accSizeNow*4); }
- tryCount = 0;
- }
- MainActivity.csLibrary4A.appendToLog("HelloA: Going to retry with TryCount=" + tryCount + ", resultError = " + accessTask.resultError);
- if (tryCount < tryCountMax) {
- MainActivity.csLibrary4A.appendToLog("HelloA: re-setup");
- setup();
- execute();
- } else bValue = true;
- }
- } else bValue = true;
- //MainActivity.csLibrary4A.appendToLog("HelloA: bValue=" + bValue);
- isResultReady = bValue;
- return bValue;
- }
- public String accessResult;
- public String getResult() {
- MainActivity.csLibrary4A.appendToLog("HelloA: accessResult = " + accessResult);
- if (accessTask == null) {
- MainActivity.csLibrary4A.appendToLog("accessTask is null");
- return null;
- }
- if (accessTask.getStatus() != AsyncTask.Status.FINISHED) {
- MainActivity.csLibrary4A.appendToLog("accessTask.getStatus is not finished");
- return null;
- }
- if (button.getText().toString().indexOf("ING") > 0) {
- MainActivity.csLibrary4A.appendToLog("button is still ing");
- return null;
- }
- return accessResult;
- }
-
- void setup() {
- tryCount++;
- if (invalidRequest == false) {
- if (MainActivity.csLibrary4A.setAccessBank(accBank) == false) {
- MainActivity.csLibrary4A.appendToLog("HelloK: accBank, invalidRequest=" + invalidRequest);
- invalidRequest = true;
- }
- }
- if (invalidRequest == false) {
- if (MainActivity.csLibrary4A.setAccessOffset(accOffset) == false) {
- MainActivity.csLibrary4A.appendToLog("HelloK: accOffset, invalidRequest=" + invalidRequest);
- invalidRequest = true;
- }
- }
- if (invalidRequest == false) {
- if (accSize == 0) {
- MainActivity.csLibrary4A.appendToLog("HelloK: accSize0, invalidRequest=" + invalidRequest);
- invalidRequest = true;
- } else {
- if (accSize > accBlockCount) accSizeNow = accBlockCount;
- else accSizeNow = accSize;
- MainActivity.csLibrary4A.appendToLog("HelloA: accSize=" + accSize + ", accSizeNow=" + accSizeNow);
- if (MainActivity.csLibrary4A.setAccessCount(accSizeNow) == false) {
- invalidRequest = true;
- }
- }
- }
- if (invalidRequest == false && hostCommand == RfidReaderChipData.HostCommands.CMD_18K6CWRITE) {
- if (accWriteData.length() > accSizeNow * 4) accWriteDataNow = accWriteData.substring(0, accSizeNow*4);
- else accWriteDataNow = accWriteData;
- if (MainActivity.csLibrary4A.setAccessWriteData(accWriteDataNow) == false) {
- invalidRequest = true;
- }
- }
- MainActivity.csLibrary4A.appendToLog("HelloA: accOffset=" + accOffset + ", accSizeNow=" + accSizeNow + ", accSize=" + accSize);
- MainActivity.csLibrary4A.appendToLog("HelloK: invalidRequest=" + invalidRequest);
- accessTask = new AccessTask(button, invalidRequest, true,
- selectMask, selectBank, selectOffset,
- strPassword, powerLevel, hostCommand, tryCount==tryCountMax, updateRunnable);
- }
-}
diff --git a/app/src/main/java/com/csl/cs710ademoapp/MainActivity.java b/app/src/main/java/com/csl/cs710ademoapp/MainActivity.java
index a43fa3e..5b3b812 100644
--- a/app/src/main/java/com/csl/cs710ademoapp/MainActivity.java
+++ b/app/src/main/java/com/csl/cs710ademoapp/MainActivity.java
@@ -27,10 +27,6 @@
import com.csl.cs710ademoapp.DrawerListContent.DrawerPositions;
import com.csl.cs710ademoapp.adapters.DrawerListAdapter;
import com.csl.cs710ademoapp.fragments.AboutFragment;
-import com.csl.cs710ademoapp.fragments.AccessReadWriteFragment;
-import com.csl.cs710ademoapp.fragments.AccessReadWriteUserFragment;
-import com.csl.cs710ademoapp.fragments.AccessRegisterFragment;
-import com.csl.cs710ademoapp.fragments.AccessSecurityFragment;
import com.csl.cs710ademoapp.fragments.AuraSenseFragment;
import com.csl.cs710ademoapp.fragments.AxzonSelectorFragment;
import com.csl.cs710ademoapp.fragments.ColdChainFragment;
@@ -38,7 +34,6 @@
import com.csl.cs710ademoapp.fragments.DirectWedgeFragment;
import com.csl.cs710ademoapp.fragments.FdmicroFragment;
import com.csl.cs710ademoapp.fragments.HomeFragment;
-import com.csl.cs710ademoapp.fragments.HomeSpecialFragment;
import com.csl.cs710ademoapp.fragments.ImpinjFragment;
import com.csl.cs710ademoapp.fragments.ImpinjM775Fragment;
import com.csl.cs710ademoapp.fragments.InventoryFragment;
@@ -47,7 +42,6 @@
import com.csl.cs710ademoapp.fragments.InventoryRfidiMultiFragment;
import com.csl.cs710ademoapp.fragments.KilowayFragment;
import com.csl.cs710ademoapp.fragments.LongjingFragment;
-import com.csl.cs710ademoapp.fragments.SettingFilterFragment;
import com.csl.cs710ademoapp.fragments.SettingFragment;
import com.csl.cs710ademoapp.fragments.TestFragment;
import com.csl.cs710ademoapp.fragments.Ucode8Fragment;
@@ -117,6 +111,8 @@ protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState == null) selectItem(drawerPositionsDefault);
if (true) Log.i(TAG, "MainActivity.onCreate.onCreate: END");
+
+ getSupportActionBar().hide();
}
@Override
@@ -192,10 +188,6 @@ private void selectItem(DrawerPositions position) {
case MAIN:
fragment = new HomeFragment();
break;
- case SPECIAL:
- fragment = new HomeSpecialFragment();
- break;
-
case ABOUT:
//fragment = new Test1Fragment();
fragment = new AboutFragment();
@@ -218,15 +210,6 @@ private void selectItem(DrawerPositions position) {
case SETTING:
fragment = new SettingFragment();
break;
- case FILTER:
- fragment = new SettingFilterFragment();
- break;
- case READWRITE:
- fragment = new AccessReadWriteFragment();
- break;
- case SECURITY:
- fragment = new AccessSecurityFragment();
- break;
case IMPINVENTORY:
fragment = new ImpinjFragment();
@@ -274,12 +257,6 @@ private void selectItem(DrawerPositions position) {
fragment = InventoryRfidiMultiFragment.newInstance(true, TAG_ASYGN, "E283A");
break;
- case REGISTER:
- fragment = new AccessRegisterFragment();
- break;
- case READWRITEUSER:
- fragment = new AccessReadWriteUserFragment();
- break;
case WEDGE:
case DIRECTWEDGE:
fragment = new DirectWedgeFragment();
diff --git a/app/src/main/java/com/csl/cs710ademoapp/fragments/AccessImpinjFragment.java b/app/src/main/java/com/csl/cs710ademoapp/fragments/AccessImpinjFragment.java
index e2ee271..a284b3f 100644
--- a/app/src/main/java/com/csl/cs710ademoapp/fragments/AccessImpinjFragment.java
+++ b/app/src/main/java/com/csl/cs710ademoapp/fragments/AccessImpinjFragment.java
@@ -20,7 +20,6 @@
import android.widget.Toast;
import com.csl.cs710ademoapp.AccessTask;
-import com.csl.cs710ademoapp.AccessTask1;
import com.csl.cs710ademoapp.CustomPopupWindow;
import com.csl.cs710ademoapp.MainActivity;
import com.csl.cs710ademoapp.R;
@@ -45,7 +44,6 @@ enum impinjTag {
Button button, buttonAutoTuneValueRead, buttonProtectValueRead, buttonProtectResumeRead, buttonEpc128ValueRead, buttonRead, buttonWrite;
boolean operationRead = false;
AccessTask accessTask;
- AccessTask1 accessTask1;
int iRunType = -1; String stringNewAutoTuneConfig = null;
int unprotecting = 0;
@@ -401,15 +399,6 @@ void startAccessUserTask() {
if (operationRead) textViewUserValue.setText("");
boolean invalidRequest = false;
- MainActivity.csLibrary4A.appendToLog("Start accessTask1 with accBlockCount + " + accBlockCount + "F" + editTextBlockCount.getText().toString() + ", accOffset = " + accOffset + "F" + editTextUserOffset.getText().toString() + ", accSize = " + accSize + "F" + editTextUserLength.getText().toString());
- accessTask1 = new AccessTask1(
- (operationRead ? buttonReadUserBank : buttonWriteUserBank), invalidRequest,
- 3, accOffset, accSize, accBlockCount, null,
- selectTag.editTextTagID.getText().toString(), iSelectBank, iSelectOffset,
- selectTag.editTextAccessPassword.getText().toString(),
- Integer.valueOf(selectTag.editTextAccessAntennaPower.getText().toString()),
- (operationRead ? RfidReaderChipData.HostCommands.CMD_18K6CREAD: RfidReaderChipData.HostCommands.CMD_18K6CWRITE), updateRunnable);
- accessTask1.execute();
iRunType = 7;
}
void startConfigRead() {
@@ -548,7 +537,7 @@ boolean isRunningAccessTask() {
private final Runnable updateRunnable = new Runnable() {
@Override
public void run() {
- if (accessTask == null && accessTask1 == null) {
+ if (accessTask == null) {
MainActivity.csLibrary4A.appendToLog("updateRunnable(): null AccessTask");
} else if (accessTask != null && accessTask.getStatus() == AsyncTask.Status.FINISHED) {
MainActivity.csLibrary4A.appendToLog("accessResult = " + accessTask.accessResult + " with iRunType = " + iRunType);
@@ -626,13 +615,7 @@ else if (iRunType == 6) {
}
else if (iRunType == 7) textViewUserValue.setText(accessTask.accessResult);
else MainActivity.csLibrary4A.appendToLog("updateRunnable(): No procedure for iRunType == " + iRunType);
- } else if (accessTask1 != null && accessTask1.isResultReady()) {
- long duration = SystemClock.elapsedRealtime() - msStartTime;
- textViewRunTime.setText(String.format("Run time: %.2f sec", ((float) duration / 1000))); MainActivity.csLibrary4A.appendToLog("StreamOut: End of running time");
- MainActivity.csLibrary4A.appendToLog("access1Result = " + accessTask1.getResult() + " with iRunType = " + iRunType);
- if (iRunType == 7) textViewUserValue.setText(accessTask1.getResult());
- else MainActivity.csLibrary4A.appendToLog("updateRunnable(): No procedure for iRunType == " + iRunType);
- }else {
+ } else {
// MainActivity.csLibrary4A.appendToLog("updateRunnable(): rerun after 100ms with accessTask.getStatus() = " + accessTask.getStatus().toString());
mHandler.postDelayed(updateRunnable, 100);
}
diff --git a/app/src/main/java/com/csl/cs710ademoapp/fragments/AccessReadWriteFragment.java b/app/src/main/java/com/csl/cs710ademoapp/fragments/AccessReadWriteFragment.java
deleted file mode 100644
index 08397e5..0000000
--- a/app/src/main/java/com/csl/cs710ademoapp/fragments/AccessReadWriteFragment.java
+++ /dev/null
@@ -1,607 +0,0 @@
-package com.csl.cs710ademoapp.fragments;
-
-import android.app.Activity;
-import android.graphics.Typeface;
-import android.os.Bundle;
-import android.os.Handler;
-import android.os.SystemClock;
-import androidx.appcompat.app.AppCompatActivity;
-import android.view.LayoutInflater;
-import android.view.View;
-import android.view.ViewGroup;
-import android.widget.AdapterView;
-import android.widget.ArrayAdapter;
-import android.widget.Button;
-import android.widget.CheckBox;
-import android.widget.EditText;
-import android.widget.Spinner;
-import android.widget.TextView;
-import android.widget.Toast;
-
-import com.csl.cs710ademoapp.AccessTask1;
-import com.csl.cs710ademoapp.CustomPopupWindow;
-import com.csl.cs710ademoapp.GenericTextWatcher;
-import com.csl.cs710ademoapp.SelectTag;
-import com.csl.cs710ademoapp.MainActivity;
-import com.csl.cs710ademoapp.R;
-import com.csl.cslibrary4a.ReaderDevice;
-import com.csl.cslibrary4a.RfidReaderChipData;
-
-import static com.csl.cs710ademoapp.MainActivity.mContext;
-import static com.csl.cs710ademoapp.MainActivity.tagSelected;
-
-public class AccessReadWriteFragment extends CommonFragment {
- SelectTag selectTag;
- Spinner spinnerSelectBank, spinnerRWSelectEpc1;
- EditText editTextRWSelectOffset, editTextAccessRWAccPassword, editTextAccessRWKillPwd, editTextAccessRWAccPwd, editTextAccPc, editTextAccessRWEpc, editTExtAccessRWXpc;
- EditText editTextTidValue, editTextUserValue, editTextEpcValue, editTextaccessRWAntennaPower;
- TextView textViewEpcLength, textViewRunTime;
- private Button buttonRead;
- private Button buttonWrite;
- Handler mHandler = new Handler();
- String strPCValueRef = "";
-
- String accEpcValue = ""; String accXpcValue = ""; String accTidValue = ""; String accUserValue = "";
- enum ReadWriteTypes {
- NULL, RESERVE, PC, EPC, XPC, TID, USER, EPC1
- }
- boolean operationRead = false;
- ReadWriteTypes readWriteTypes;
-
- private AccessTask1 accessTask;
-
- @Override
- public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
- super.onCreateView(inflater, container, savedInstanceState, true);
- return inflater.inflate(R.layout.fragment_access_readwrite, container, false);
- }
-
- @Override
- public void onActivityCreated(Bundle savedInstanceState) {
- super.onActivityCreated(savedInstanceState);
-
- androidx.appcompat.app.ActionBar actionBar;
- actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
- actionBar.setIcon(R.drawable.dl_access);
- actionBar.setTitle(R.string.title_activity_readwrite);
-
- selectTag = new SelectTag((Activity)getActivity(), 0);
-
- spinnerSelectBank = (Spinner) getActivity().findViewById(R.id.selectMemoryBank);
- ArrayAdapter targetAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.read_memoryBank_options, R.layout.custom_spinner_layout);
- targetAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
- spinnerSelectBank.setAdapter(targetAdapter);
- spinnerSelectBank.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
- @Override
- public void onItemSelected(AdapterView> parent, View view, int position, long id) {
- switch (position) {
- case 0: //if EPC
- if (tagSelected != null) selectTag.editTextTagID.setText(tagSelected.getAddress());
- editTextRWSelectOffset.setText("32");
- break;
- case 1:
- if (tagSelected != null) { if (tagSelected.getTid() != null) selectTag.editTextTagID.setText(tagSelected.getTid()); }
- editTextRWSelectOffset.setText("0");
- break;
- case 2:
- if (tagSelected != null) { if (tagSelected.getUser() != null) selectTag.editTextTagID.setText(tagSelected.getUser()); }
- editTextRWSelectOffset.setText("0");
- break;
- default:
- break;
- }
- }
-
- @Override
- public void onNothingSelected(AdapterView> parent) {
-
- }
- });
-
- editTextRWSelectOffset = (EditText) getActivity().findViewById(R.id.selectMemoryOffset);
- spinnerRWSelectEpc1 = (Spinner) getActivity().findViewById(R.id.accessRWEpc1Title1);
- ArrayAdapter targetAdapter1 = ArrayAdapter.createFromResource(getActivity(), R.array.memoryBank_options, R.layout.custom_spinner_layout);
- targetAdapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
- spinnerRWSelectEpc1.setAdapter(targetAdapter1); spinnerRWSelectEpc1.setSelection(1);
-
- editTextAccessRWAccPassword = (EditText) getActivity().findViewById(R.id.selectPasswordValue);
- editTextAccessRWAccPassword.addTextChangedListener(new GenericTextWatcher(editTextAccessRWAccPassword, 8));
- editTextAccessRWAccPassword.setText("00000000");
- editTextAccessRWKillPwd = (EditText) getActivity().findViewById(R.id.accessRWKillPwdValue);
- editTextAccessRWKillPwd.addTextChangedListener(new GenericTextWatcher(editTextAccessRWKillPwd, 8));
- editTextAccessRWAccPwd = (EditText) getActivity().findViewById(R.id.accessRWAccPwdValue);
- editTextAccessRWAccPwd.addTextChangedListener(new GenericTextWatcher(editTextAccessRWAccPwd, 8));
- editTextAccPc = (EditText) getActivity().findViewById(R.id.accessRWAccPcValue);
- editTextAccPc.setHint("PC value");
- editTextAccPc.addTextChangedListener(new GenericTextWatcher(editTextAccPc, 4));
- editTextAccessRWEpc = (EditText) getActivity().findViewById(R.id.accessRWAccEpcValue);
- editTExtAccessRWXpc = (EditText) getActivity().findViewById(R.id.accessRWAccXpcValue);
- editTextTidValue = (EditText) getActivity().findViewById(R.id.accessRWTidValue);
- editTextTidValue.setHint("Data Pattern");
- editTextUserValue = (EditText) getActivity().findViewById(R.id.accessRWUserValue); editTextUserValue.setTypeface(Typeface.MONOSPACE);
- editTextUserValue.setHint("Data Pattern");
- editTextEpcValue = (EditText) getActivity().findViewById(R.id.accessRWEpcValue);
- editTextEpcValue.setHint("Data Pattern");
-
- editTextaccessRWAntennaPower = (EditText) getActivity().findViewById(R.id.selectAntennaPower);
- editTextaccessRWAntennaPower.setText(String.valueOf(300));
-
- textViewEpcLength = (TextView) getActivity().findViewById(R.id.accessRWAccEpcLength);
- textViewRunTime = (TextView) getActivity().findViewById(R.id.accessRWRunTime);
-
- buttonRead = (Button) getActivity().findViewById(R.id.accessRWReadButton);
- buttonRead.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- if (MainActivity.csLibrary4A.isBleConnected() == false) {
- Toast.makeText(MainActivity.mContext, R.string.toast_ble_not_connected, Toast.LENGTH_SHORT).show();
- return;
- } else if (MainActivity.csLibrary4A.isRfidFailure()) {
- Toast.makeText(MainActivity.mContext, "Rfid is disabled", Toast.LENGTH_SHORT).show();
- return;
- }
- operationRead = true; startAccessTask();
- }
- });
-
- buttonWrite = (Button) getActivity().findViewById(R.id.accessRWWriteButton);
- buttonWrite.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- if (MainActivity.csLibrary4A.isBleConnected() == false) {
- Toast.makeText(MainActivity.mContext, R.string.toast_ble_not_connected, Toast.LENGTH_SHORT).show();
- return;
- } else if (MainActivity.csLibrary4A.isRfidFailure()) {
- Toast.makeText(MainActivity.mContext, "Rfid is disabled", Toast.LENGTH_SHORT).show();
- return;
- }
- operationRead = false; startAccessTask();
- }
- });
-
- ReaderDevice tagSelected = MainActivity.tagSelected;
- if (tagSelected != null) {
- if (tagSelected.getSelected() == true) {
- String strEpcValue = tagSelected.getAddress();
- String detail = tagSelected.getDetails();
- String header = "PC=";
- if (detail != null && detail.indexOf(header) >= 0) {
- int index = detail.indexOf(header) + header.length();
- strPCValueRef = detail.substring(index, index + 4);
- updatePCEpc(strPCValueRef, strEpcValue);
- }
- }
- }
- MainActivity.csLibrary4A.setSameCheck(true);
- }
-
- @Override
- public void onDestroy() {
- if (accessTask != null) accessTask.cancel(true);
- MainActivity.csLibrary4A.setSameCheck(true);
- MainActivity.csLibrary4A.restoreAfterTagSelect();
- super.onDestroy();
- }
-
- public AccessReadWriteFragment() {
- super("AccessReadWriteFragment");
- }
-
- int getPC2EpcWordCount(String detail) {
- String detail2 = detail.substring(0, 1);
- int number2 = Integer.valueOf(detail2, 16) * 2;
- String detail3 = detail.substring(1, 2);
- int number3 = Integer.valueOf(detail3, 16);
- if ((number3 / 8) != 0) number2 += 1;
- return number2;
- }
- void updatePCEpc(String strPCValue, String strEpcValue) {
- boolean needPopup = false;
- if (strPCValue == null) strPCValue = "";
- if (strPCValue.length() != 0) editTextAccPc.setText(strPCValue);
- else strPCValue = strPCValueRef;
- if (strPCValueRef != null && strPCValue != null) {
- if (strPCValue.matches(strPCValueRef) == false && strPCValue.length() == 4) {
- needPopup = true;
- strPCValueRef = strPCValue;
- }
- }
-
- int iWordCount = getPC2EpcWordCount(strPCValue);
- textViewEpcLength.setText("EPC has " + (iWordCount * 16) + " bits");
- if (strEpcValue != null) {
- tagSelected.setAddress(strEpcValue); if (spinnerSelectBank.getSelectedItemPosition() == 0) selectTag.editTextTagID.setText(strEpcValue);
- editTextAccessRWEpc.setText(strEpcValue);
- } else {
- if (iWordCount * 4 < selectTag.editTextTagID.getText().toString().length()) {
- // needPopup = true;
- String strTemp = selectTag.editTextTagID.getText().toString().substring(0, iWordCount * 4);
- tagSelected.setAddress(strEpcValue); if (spinnerSelectBank.getSelectedItemPosition() == 0) selectTag.editTextTagID.setText(strTemp);
- }
- if (iWordCount * 4 < editTextAccessRWEpc.getText().toString().length()) {
- // needPopup = true;
- String strTemp = editTextAccessRWEpc.getText().toString().substring(0, iWordCount * 4);
- editTextAccessRWEpc.setText(strTemp);
- }
- if (editTextAccessRWEpc.getText().toString().length() != 0) {
- String strTemp = editTextAccessRWEpc.getText().toString();
- if (selectTag.editTextTagID.getText().toString().matches(strTemp) == false) {
- // needPopup = true;
- tagSelected.setAddress(strTemp); if (spinnerSelectBank.getSelectedItemPosition() == 0) selectTag.editTextTagID.setText(strTemp);
- }
- }
- }
- editTextAccessRWEpc.addTextChangedListener(new GenericTextWatcher(editTextAccessRWEpc, iWordCount * 4));
- String strTemp = editTextAccessRWEpc.getText().toString();
- editTextAccessRWEpc.setText(strTemp);
-
- if (needPopup) {
- CustomPopupWindow customPopupWindow = new CustomPopupWindow(mContext);
- customPopupWindow.popupStart("Changing EPC Length will automatically modify to " + (iWordCount * 16) + " bits.", false);
- }
- }
-
- long msStartTime;
- void startAccessTask() {
- if (selectTag.editTextTagID.getText().toString().length() == 0) {
- Toast.makeText(MainActivity.mContext, "Please select tag first !!!", Toast.LENGTH_SHORT).show();
- return;
- }
- if (updating == false) {
- msStartTime = SystemClock.elapsedRealtime();
- textViewRunTime.setText("");
- updating = true; bankProcessing = 0; restartAccessBank = -1;
-// MainActivity.mCs108Library4a.
- mHandler.removeCallbacks(updateRunnable);
- mHandler.post(updateRunnable);
- }
- }
- boolean updating = false; int bankProcessing = 0;
- private final Runnable updateRunnable = new Runnable() {
- @Override
- public void run() {
- boolean rerunRequest = true; boolean taskRequest = false;
- if (processResult()) { rerunRequest = true; }
- else if (accessTask == null || accessTask.isResultReady()) {
- bcheckBoxAll = false;
- boolean invalid = processTickItems();
- if (bankProcessing == 0 && bcheckBoxAll) rerunRequest = false;
- else if (bankProcessing++ != 0 && invalid == true) rerunRequest = false;
- else {
- if (restartAccessBank != accessBank) {
- restartAccessBank = accessBank;
- restartCounter = 3;
- }
- if (DEBUG) MainActivity.csLibrary4A.appendToLog("AccessReadWriteFragment().InventoryRfidTask(): tagID=" + selectTag.editTextTagID.getText() + ", operationrRead=" + operationRead + ", accessBank=" + accessBank + ", accOffset=" + accOffset + ", accSize=" + accSize);
- int selectOffset = 0;
- selectOffset = Integer.parseInt(editTextRWSelectOffset.getText().toString());
- EditText editTextBlockCount = (EditText) getActivity().findViewById(R.id.accessRWBlockCount);
- Integer accBlockCount = 32;
- try {
- accBlockCount = Integer.parseInt(editTextBlockCount.getText().toString());
- } catch (Exception ex) { }
- MainActivity.csLibrary4A.appendToLog("strOut: accWriteData=" + accWriteData);
- accessTask = new AccessTask1(
- (operationRead ? buttonRead : buttonWrite), invalid,
- accessBank, accOffset, accSize, accBlockCount, accWriteData,
- selectTag.editTextTagID.getText().toString(), spinnerSelectBank.getSelectedItemPosition() + 1, selectOffset,
- editTextAccessRWAccPassword.getText().toString(),
- Integer.valueOf(editTextaccessRWAntennaPower.getText().toString()),
- (operationRead ? RfidReaderChipData.HostCommands.CMD_18K6CREAD: RfidReaderChipData.HostCommands.CMD_18K6CWRITE), updateRunnable);
- accessTask.execute();
- rerunRequest = true;
- }
- }
- if (rerunRequest) {
- mHandler.postDelayed(updateRunnable, 100);
- if (DEBUG) MainActivity.csLibrary4A.appendToLog("AccessReadWriteFragment().updateRunnable(): Restart");
- }
- else {
- if (bankProcessing == 0 && bcheckBoxAll) {
- Toast.makeText(MainActivity.mContext, "no choice selected yet", Toast.LENGTH_SHORT).show();
- }
- updating = false;
- }
- }
- };
-
- TextView textViewReserveOk, textViewPcOk, textViewEpcOk, textViewTidOk, textViewUserOk, textViewEpc1Ok;
- CheckBox checkBoxReserve, checkBoxPc, checkBoxEpc, checkBoxTid, checkBoxUser, checkBoxEpc1;
- int accessBank, accSize, accOffset; String accWriteData;
- int restartCounter = 0; int restartAccessBank = -1;
- boolean processResult() {
- String accessResult = null;
- if (accessTask == null) return false;
- if (accessTask.isResultReady() == false) return false;
- else {
- long duration = SystemClock.elapsedRealtime() - msStartTime;
- textViewRunTime.setText(String.format("Run time: %.2f sec", ((float) duration / 1000)));
- accessResult = accessTask.getResult();
- if (DEBUG) MainActivity.csLibrary4A.appendToLog("processResult(): accessResult = " + accessResult);
- if (accessResult == null) {
- if (readWriteTypes == ReadWriteTypes.RESERVE) {
- textViewReserveOk.setText("E"); checkBoxReserve.setChecked(false);
- }
- if (readWriteTypes == ReadWriteTypes.PC) {
- textViewPcOk.setText("E"); checkBoxPc.setChecked(false);
- }
- if (readWriteTypes == ReadWriteTypes.EPC) {
- textViewEpcOk.setText("E"); checkBoxEpc.setChecked(false);
- }
- if (readWriteTypes == ReadWriteTypes.TID) {
- textViewTidOk.setText("E"); checkBoxTid.setChecked(false);
- }
- if (readWriteTypes == ReadWriteTypes.USER) {
- textViewUserOk.setText("E"); checkBoxUser.setChecked(false);
- }
- if (readWriteTypes == ReadWriteTypes.EPC1) {
- textViewEpc1Ok.setText("E"); checkBoxEpc1.setChecked(false);
- }
- } else {
- if (DEBUG) MainActivity.csLibrary4A.appendToLog("accessResult = " + accessResult);
- if (readWriteTypes == ReadWriteTypes.RESERVE) {
- textViewReserveOk.setText("O"); checkBoxReserve.setChecked(false);
- readWriteTypes = ReadWriteTypes.NULL;
- if (accessResult.length() == 0 || operationRead == false) {
- } else if (accessResult.length() < 8) {
- editTextAccessRWKillPwd.setText(accessResult);
- } else {
- editTextAccessRWKillPwd.setText(accessResult.substring(0, 8));
- }
- if (accessResult.length() <= 8) {
- editTextAccessRWAccPwd.setText("");
- } else if (accessResult.length() < 16) {
- editTextAccessRWAccPwd.setText(accessResult.subSequence(8, accessResult.length()));
- } else {
- editTextAccessRWAccPwd.setText(accessResult.subSequence(8, 16));
- }
- } else if (readWriteTypes == ReadWriteTypes.PC) {
- textViewPcOk.setText("O"); checkBoxPc.setChecked(false);
- readWriteTypes = ReadWriteTypes.NULL;
- if (operationRead) {
- String newValue = "";
- if (accessResult.length() <= 4) {
- newValue = accessResult.subSequence(0, accessResult.length()).toString();
- } else {
- newValue = accessResult.subSequence(0, 4).toString();
- }
- editTextAccPc.setText(newValue);
- }
- updatePCEpc(editTextAccPc.getText().toString(), null);
- } else if (readWriteTypes == ReadWriteTypes.EPC) {
- if (DEBUG) MainActivity.csLibrary4A.appendToLog("AccessReadWrite(). EPC DATA with accessBank = " + accessBank + ", with accessResult.length = " + accessResult.length());
- textViewEpcOk.setText("O"); checkBoxEpc.setChecked(false);
- readWriteTypes = ReadWriteTypes.NULL;
- if (operationRead) {
- String newValue = "";
- if (accessResult.length() <= 4) {
- newValue = accessResult.subSequence(0, accessResult.length()).toString();
- } else {
- newValue = accessResult.subSequence(0, 4).toString();
- }
- editTextAccPc.setText(newValue);
- }
- updatePCEpc(editTextAccPc.getText().toString(), null);
-
- if (operationRead) {
- String newValue = "";
- if (accessResult.length() > 4) {
- newValue = accessResult.subSequence(4, accessResult.length()).toString();
- }
- editTextAccessRWEpc.setText(newValue);
- }
- } else if (readWriteTypes == ReadWriteTypes.XPC) {
- if (DEBUG) MainActivity.csLibrary4A.appendToLog("AccessReadWrite(). XPC DATA with accessBank = " + accessBank + ", with accessResult.length = " + accessResult.length() + ", with accessResult=" + accessResult);
- readWriteTypes = ReadWriteTypes.NULL;
- if (operationRead) {
- String newValue = accessResult.toString();
- editTExtAccessRWXpc.setText(newValue);
- accXpcValue = newValue;
- } else {
- accXpcValue = editTExtAccessRWXpc.getText().toString();
- }
- } else if (readWriteTypes == ReadWriteTypes.TID) {
- textViewTidOk.setText("O"); checkBoxTid.setChecked(false);
- readWriteTypes = ReadWriteTypes.NULL;
- if (accessResult.length() == 0 || operationRead == false) {
- } else editTextTidValue.setText(accessResult);
- } else if (readWriteTypes == ReadWriteTypes.USER) {
- textViewUserOk.setText("O"); checkBoxUser.setChecked(false);
- readWriteTypes = ReadWriteTypes.NULL;
- if (operationRead) {
- if (DEBUG) MainActivity.csLibrary4A.appendToLog("AccessReadWrite(). DATA with accessBank = " + accessBank);
- if (accessTask != null) {
- int iLength = accessTask.deformatWriteAccessData(accessResult).length();
- MainActivity.csLibrary4A.appendToLog("endingMessage length=" + iLength);
- if (iLength < accSize*4) textViewUserOk.setText("H");
- }
- editTextUserValue.setText(accessResult);
- accUserValue = accessResult;
- } else {
- accUserValue = editTextUserValue.getText().toString();
- }
- } else if (readWriteTypes == ReadWriteTypes.EPC1) {
- textViewEpc1Ok.setText("O"); checkBoxEpc1.setChecked(false);
- readWriteTypes = ReadWriteTypes.NULL;
- if (accessResult.length() == 0 || operationRead == false) {
- } else {
- editTextEpcValue.setText(accessResult);
- accEpcValue = accessResult;
- }
- if (operationRead == false) accEpcValue = editTextEpcValue.getText().toString();
- }
- accessResult = null;
- }
- accessTask = null;
- return true;
- }
- }
- boolean bcheckBoxAll = false;
- boolean processTickItems() {
- String writeData = "";
- boolean invalidRequest1 = false;
-
- textViewReserveOk = (TextView) getActivity().findViewById(R.id.accessRWReserveOK);
- textViewPcOk = (TextView) getActivity().findViewById(R.id.accessRWPcOK);
- textViewEpcOk = (TextView) getActivity().findViewById(R.id.accessRWEpcOK);
- textViewTidOk = (TextView) getActivity().findViewById(R.id.accessRWTidOK);
- textViewUserOk = (TextView) getActivity().findViewById(R.id.accessRWUserOK);
- textViewEpc1Ok = (TextView) getActivity().findViewById(R.id.accessRWEpc1OK);
-
- checkBoxReserve = (CheckBox) getActivity().findViewById(R.id.accessRWReserveTitle);
- checkBoxPc = (CheckBox) getActivity().findViewById(R.id.accessRWPcTitle);
- checkBoxEpc = (CheckBox) getActivity().findViewById(R.id.accessRWEpcTitle);
- checkBoxTid = (CheckBox) getActivity().findViewById(R.id.accessRWTidTitle);
- checkBoxUser = (CheckBox) getActivity().findViewById(R.id.accessRWUserTitle);
- checkBoxEpc1 = (CheckBox) getActivity().findViewById(R.id.accessRWEpc1);
-
- if (checkBoxReserve.isChecked() == true) {
- textViewReserveOk.setText("");
- accessBank = 0; accOffset = 0; accSize = 4; readWriteTypes = ReadWriteTypes.RESERVE;
- if (operationRead) {
- editTextAccessRWKillPwd.setText("");
- editTextAccessRWAccPwd.setText("");
- } else {
- String strValue = editTextAccessRWKillPwd.getText().toString();
- String strValue1 = editTextAccessRWAccPwd.getText().toString();
- if (strValue.length() != 8 || strValue1.length() != 8) {
- invalidRequest1 = true;
- } else {
- writeData = strValue + strValue1;
- }
- }
- } else if (checkBoxPc.isChecked() == true || ((checkBoxEpc.isChecked() == true) && (strPCValueRef.length() != 4) )) {
- textViewPcOk.setText("");
- accessBank = 1; accOffset = 1; accSize = 1; readWriteTypes = ReadWriteTypes.PC;
- if (operationRead) {
- editTextAccPc.setText("");
- } else {
- String strValue = editTextAccPc.getText().toString();
- if (strValue.length() != 4) invalidRequest1 = true;
- else writeData = strValue;
- }
- } else if (checkBoxEpc.isChecked() == true) {
- textViewEpcOk.setText("");
- accessBank = 1; accOffset = 1; accSize = 0; readWriteTypes = ReadWriteTypes.EPC;
- if (DEBUG) MainActivity.csLibrary4A.appendToLog("processTickItems(): start EPC operation");
- if (operationRead) {
- if (strPCValueRef.length() != 4) accSize = 1;
- else {
- accSize = getPC2EpcWordCount(strPCValueRef) + 1;
- editTextAccessRWEpc.setText("");
- }
- } else {
- String strValue = editTextAccPc.getText().toString();
- String strValue1 = editTextAccessRWEpc.getText().toString();
- if (strValue1.length() == 0) {
- if (strValue.length() != 4) invalidRequest1 = true;
- else {
- accSize = 1;
- writeData = strValue;
- }
- } else {
- accSize += strValue1.length() / 4;
- if (strValue1.length() % 4 != 0) accSize++;
- if (strValue.length() == 4) {
- int iPCWordCount = getPC2EpcWordCount(strValue);
- if (iPCWordCount < accSize) accSize = iPCWordCount;
- accSize++;
- writeData = strValue + strValue1;
- } else {
- accOffset = 2;
- writeData = strValue1;
- }
- }
- }
- } else if (checkBoxTid.isChecked() == true) {
- textViewTidOk.setText("");
- accessBank = 2; accOffset = 0; accSize = 0; readWriteTypes = ReadWriteTypes.TID;
- EditText editTextTidValue = (EditText) getActivity().findViewById(R.id.accessRWTidValue);
- if (operationRead) {
- int iValue = 0;
- try {
- EditText editTextTidOffset = (EditText) getActivity().findViewById(R.id.accessRWTidOffset);
- iValue = Integer.parseInt(editTextTidOffset.getText().toString());
- } catch (Exception ex) {
- }
- accOffset = iValue;
- iValue = 0;
- try {
- EditText editTextTidLength = (EditText) getActivity().findViewById(R.id.accessRWTidLength);
- iValue = Integer.parseInt(editTextTidLength.getText().toString());
- } catch (Exception ex) {
- }
- accSize = iValue;
- editTextTidValue.setText("");
- } else {
- invalidRequest1 = true;
- editTextTidValue.setText("");
-
- }
- } else if (checkBoxUser.isChecked() == true) {
- textViewUserOk.setText("");
- accessBank = 3; accOffset = 0; accSize = 0; readWriteTypes = ReadWriteTypes.USER;
- if (DEBUG) MainActivity.csLibrary4A.appendToLog("processTickItems(): start USER operation");
- int iValue = 0;
- try {
- EditText editTextTidOffset = (EditText) getActivity().findViewById(R.id.accessRWUserOffset);
- iValue = Integer.parseInt(editTextTidOffset.getText().toString());
- } catch (Exception ex) {
- }
- accOffset = iValue;
- iValue = 0;
- try {
- EditText editTextUserLength = (EditText) getActivity().findViewById(R.id.accessRWUserLength);
- iValue = Integer.parseInt(editTextUserLength.getText().toString());
- } catch (Exception ex) {
- }
- accSize = iValue;
- if (operationRead) {
- editTextUserValue.setText("");
- } else {
- String strValue = editTextUserValue.getText().toString();
- MainActivity.csLibrary4A.appendToLog("strOut: strValue=" + strValue + ", strValue.length=" + strValue.length() + ", accUserValue=" + accUserValue + ", accUserValue.lengt=" + accUserValue.length());
- if (strValue.length() >= 4 && accUserValue.matches(strValue) == false) {
- writeData = strValue;
- }
- }
- } else if (checkBoxEpc1.isChecked() == true) {
- textViewEpc1Ok.setText("");
- accessBank = spinnerRWSelectEpc1.getSelectedItemPosition(); accOffset = 0; accSize = 0; readWriteTypes = ReadWriteTypes.EPC1;
- int iValue = 0;
- try {
- EditText editTextEpcOffset = (EditText) getActivity().findViewById(R.id.accessRWEpcOffset);
- iValue = Integer.parseInt(editTextEpcOffset.getText().toString());
- } catch (Exception ex) {
- }
- accOffset = iValue;
- iValue = 0;
- try {
- EditText editTextEpcLength = (EditText) getActivity().findViewById(R.id.accessRWEpcLength);
- iValue = Integer.parseInt(editTextEpcLength.getText().toString());
- } catch (Exception ex) {
- }
- accSize = iValue;
- if (operationRead) {
- editTextEpcValue.setText("");
- } else {
- String strValue = editTextEpcValue.getText().toString();
- if (strValue.length() >= 4 && strValue.matches(accEpcValue) == false) {
- accSize = strValue.length() / 4;
- if (strValue.length() %4 != 0) accSize++;
- writeData = strValue;
- }
- }
- } else {
- invalidRequest1 = true;
- bcheckBoxAll = true;
- }
-
- if (restartAccessBank == accessBank) {
- if (restartCounter == 0) invalidRequest1 = true;
- else restartCounter--;
- }
- accWriteData = writeData;
- return invalidRequest1;
- }
-}
diff --git a/app/src/main/java/com/csl/cs710ademoapp/fragments/AccessReadWriteUserFragment.java b/app/src/main/java/com/csl/cs710ademoapp/fragments/AccessReadWriteUserFragment.java
deleted file mode 100644
index 08bb5b3..0000000
--- a/app/src/main/java/com/csl/cs710ademoapp/fragments/AccessReadWriteUserFragment.java
+++ /dev/null
@@ -1,455 +0,0 @@
-package com.csl.cs710ademoapp.fragments;
-
-import android.app.Activity;
-import android.graphics.Typeface;
-import android.os.Bundle;
-import android.os.Handler;
-import android.os.SystemClock;
-import androidx.appcompat.app.AppCompatActivity;
-import android.view.LayoutInflater;
-import android.view.View;
-import android.view.ViewGroup;
-import android.widget.AdapterView;
-import android.widget.ArrayAdapter;
-import android.widget.Button;
-import android.widget.CheckBox;
-import android.widget.EditText;
-import android.widget.Spinner;
-import android.widget.TableRow;
-import android.widget.TextView;
-import android.widget.Toast;
-
-import com.csl.cs710ademoapp.AccessTask1;
-import com.csl.cs710ademoapp.CustomPopupWindow;
-import com.csl.cs710ademoapp.GenericTextWatcher;
-import com.csl.cs710ademoapp.SelectTag;
-import com.csl.cs710ademoapp.MainActivity;
-import com.csl.cs710ademoapp.R;
-import com.csl.cslibrary4a.ReaderDevice;
-import com.csl.cslibrary4a.RfidReaderChipData;
-
-import static com.csl.cs710ademoapp.MainActivity.mContext;
-import static com.csl.cs710ademoapp.MainActivity.tagSelected;
-
-public class AccessReadWriteUserFragment extends CommonFragment {
- SelectTag selectTag;
- Spinner spinnerSelectBank, spinnerRWSelectBank;
- EditText editTextRWSelectOffset, editTextAccessRWAccPassword, editTextAccessRWKillPwd, editTextAccessRWAccPwd, editTextAccPc, editTextAccessRWEpc;
- EditText editTextUserValue, editTextEpcValue, editTextaccessRWAntennaPower;
- TextView textViewEpcLength, textViewRunTime;
- private Button buttonRead;
- private Button buttonWrite;
- Handler mHandler = new Handler();
- String strPCValueRef = "";
-
- String accEpcValue = ""; String accUserValue = "";
- enum ReadWriteTypes {
- NULL, USER, SBANK
- }
- boolean operationRead = false;
- ReadWriteTypes readWriteTypes;
-
- private AccessTask1 accessTask;
-
- @Override
- public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
- super.onCreateView(inflater, container, savedInstanceState, true);
- return inflater.inflate(R.layout.fragment_access_readwrite, container, false);
- }
-
- @Override
- public void onActivityCreated(Bundle savedInstanceState) {
- super.onActivityCreated(savedInstanceState);
-
- androidx.appcompat.app.ActionBar actionBar;
- actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
- actionBar.setIcon(R.drawable.dl_access);
- actionBar.setTitle(R.string.title_activity_readWriteUser);
-
- selectTag = new SelectTag((Activity)getActivity(), 0);
- spinnerSelectBank = (Spinner) getActivity().findViewById(R.id.selectMemoryBank);
- ArrayAdapter targetAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.read_memoryBank_options, R.layout.custom_spinner_layout);
- targetAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
- spinnerSelectBank.setAdapter(targetAdapter);
- spinnerSelectBank.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
- @Override
- public void onItemSelected(AdapterView> parent, View view, int position, long id) {
- switch (position) {
- case 0: //if EPC
- if (tagSelected != null) selectTag.editTextTagID.setText(tagSelected.getAddress());
- editTextRWSelectOffset.setText("32");
- break;
- case 1:
- if (tagSelected != null) { if (tagSelected.getTid() != null) selectTag.editTextTagID.setText(tagSelected.getTid()); }
- editTextRWSelectOffset.setText("0");
- break;
- case 2:
- if (tagSelected != null) { if (tagSelected.getUser() != null) selectTag.editTextTagID.setText(tagSelected.getUser()); }
- editTextRWSelectOffset.setText("0");
- break;
- default:
- break;
- }
- }
-
- @Override
- public void onNothingSelected(AdapterView> parent) {
-
- }
- });
-
- TableRow tableRow = (TableRow) getActivity().findViewById(R.id.accessRWReserveTitleRow);
- tableRow.setVisibility(View.GONE);
- tableRow = (TableRow) getActivity().findViewById(R.id.accessRWReserveValueRow);
- tableRow.setVisibility(View.GONE);
- tableRow = (TableRow) getActivity().findViewById(R.id.accessRWPcTitleRow);
- tableRow.setVisibility(View.GONE);
- tableRow = (TableRow) getActivity().findViewById(R.id.accessRWEpcTitleRow);
- tableRow.setVisibility(View.GONE);
- tableRow = (TableRow) getActivity().findViewById(R.id.accessRWTidTitleRow);
- tableRow.setVisibility(View.GONE);
- tableRow = (TableRow) getActivity().findViewById(R.id.accessRWTidValueRow);
- tableRow.setVisibility(View.GONE);
- tableRow = (TableRow) getActivity().findViewById(R.id.accessRWAnyTitleRow);
- tableRow.setVisibility(View.GONE);
- tableRow = (TableRow) getActivity().findViewById(R.id.accessRWAnyValueRow);
- tableRow.setVisibility(View.GONE);
-
- editTextRWSelectOffset = (EditText) getActivity().findViewById(R.id.selectMemoryOffset);
- spinnerRWSelectBank = (Spinner) getActivity().findViewById(R.id.accessRWEpc1Title1);
- ArrayAdapter targetAdapter1 = ArrayAdapter.createFromResource(getActivity(), R.array.memoryBank_options, R.layout.custom_spinner_layout);
- targetAdapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
- spinnerRWSelectBank.setAdapter(targetAdapter1); spinnerRWSelectBank.setSelection(1);
-
- editTextAccessRWAccPassword = (EditText) getActivity().findViewById(R.id.selectPasswordValue);
- editTextAccessRWAccPassword.addTextChangedListener(new GenericTextWatcher(editTextAccessRWAccPassword, 8));
- editTextAccessRWAccPassword.setText("00000000");
- editTextAccessRWKillPwd = (EditText) getActivity().findViewById(R.id.accessRWKillPwdValue);
- editTextAccessRWKillPwd.addTextChangedListener(new GenericTextWatcher(editTextAccessRWKillPwd, 8));
- editTextAccessRWAccPwd = (EditText) getActivity().findViewById(R.id.accessRWAccPwdValue);
- editTextAccessRWAccPwd.addTextChangedListener(new GenericTextWatcher(editTextAccessRWAccPwd, 8));
- editTextAccPc = (EditText) getActivity().findViewById(R.id.accessRWAccPcValue);
- editTextAccPc.setHint("PC value");
- editTextAccPc.addTextChangedListener(new GenericTextWatcher(editTextAccPc, 4));
- editTextAccessRWEpc = (EditText) getActivity().findViewById(R.id.accessRWAccEpcValue);
- EditText editTextBlockCount = (EditText) getActivity().findViewById(R.id.accessRWBlockCount);
- editTextBlockCount.setText("48");
- EditText editTextUserLength = (EditText) getActivity().findViewById(R.id.accessRWUserLength);
- editTextUserLength.setText("512");
- editTextUserValue = (EditText) getActivity().findViewById(R.id.accessRWUserValue); editTextUserValue.setTypeface(Typeface.MONOSPACE);
- editTextUserValue.setHint("Data Pattern");
- editTextEpcValue = (EditText) getActivity().findViewById(R.id.accessRWEpcValue);
- editTextEpcValue.setHint("Data Pattern");
-
- editTextaccessRWAntennaPower = (EditText) getActivity().findViewById(R.id.selectAntennaPower);
- editTextaccessRWAntennaPower.setText(String.valueOf(300));
-
- textViewEpcLength = (TextView) getActivity().findViewById(R.id.accessRWAccEpcLength);
- textViewRunTime = (TextView) getActivity().findViewById(R.id.accessRWRunTime);
-
- buttonRead = (Button) getActivity().findViewById(R.id.accessRWReadButton);
- buttonRead.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- if (MainActivity.csLibrary4A.isBleConnected() == false) {
- Toast.makeText(MainActivity.mContext, R.string.toast_ble_not_connected, Toast.LENGTH_SHORT).show();
- return;
- } else if (MainActivity.csLibrary4A.isRfidFailure()) {
- Toast.makeText(MainActivity.mContext, "Rfid is disabled", Toast.LENGTH_SHORT).show();
- return;
- }
- operationRead = true; startAccessTask();
- }
- });
-
- buttonWrite = (Button) getActivity().findViewById(R.id.accessRWWriteButton);
- buttonWrite.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- if (MainActivity.csLibrary4A.isBleConnected() == false) {
- Toast.makeText(MainActivity.mContext, R.string.toast_ble_not_connected, Toast.LENGTH_SHORT).show();
- return;
- } else if (MainActivity.csLibrary4A.isRfidFailure()) {
- Toast.makeText(MainActivity.mContext, "Rfid is disabled", Toast.LENGTH_SHORT).show();
- return;
- }
- operationRead = false; startAccessTask();
- }
- });
-
- ReaderDevice tagSelected = MainActivity.tagSelected;
- if (tagSelected != null) {
- if (tagSelected.getSelected() == true) {
- String strEpcValue = tagSelected.getAddress();
- String detail = tagSelected.getDetails();
- String header = "PC=";
- int index = detail.indexOf(header) + header.length();
- strPCValueRef = detail.substring(index, index + 4);
- updatePCEpc(strPCValueRef, strEpcValue);
- }
- }
- MainActivity.csLibrary4A.setSameCheck(true);
- }
-
- @Override
- public void onDestroy() {
- if (accessTask != null) accessTask.cancel(true);
- MainActivity.csLibrary4A.setSameCheck(true);
- MainActivity.csLibrary4A.restoreAfterTagSelect();
- super.onDestroy();
- }
-
- public AccessReadWriteUserFragment() {
- super("AccessReadWriteUserFragment");
- }
-
- int getPC2EpcWordCount(String detail) {
- String detail2 = detail.substring(0, 1);
- int number2 = Integer.valueOf(detail2, 16) * 2;
- String detail3 = detail.substring(1, 2);
- int number3 = Integer.valueOf(detail3, 16);
- if ((number3 / 8) != 0) number2 += 1;
- return number2;
- }
- void updatePCEpc(String strPCValue, String strEpcValue) {
- boolean needPopup = false;
- if (strPCValue == null) strPCValue = "";
- if (strPCValue.length() != 0) editTextAccPc.setText(strPCValue);
- else strPCValue = strPCValueRef;
- if (strPCValueRef != null && strPCValue != null) {
- if (strPCValue.matches(strPCValueRef) == false && strPCValue.length() == 4) {
- needPopup = true;
- strPCValueRef = strPCValue;
- }
- }
-
- int iWordCount = getPC2EpcWordCount(strPCValue);
- textViewEpcLength.setText("EPC has " + (iWordCount * 16) + " bits");
- if (strEpcValue != null) {
- tagSelected.setAddress(strEpcValue); if (spinnerSelectBank.getSelectedItemPosition() == 0) selectTag.editTextTagID.setText(strEpcValue);
- editTextAccessRWEpc.setText(strEpcValue);
- } else {
- if (iWordCount * 4 < selectTag.editTextTagID.getText().toString().length()) {
- // needPopup = true;
- String strTemp = selectTag.editTextTagID.getText().toString().substring(0, iWordCount * 4);
- tagSelected.setAddress(strEpcValue); if (spinnerSelectBank.getSelectedItemPosition() == 0) selectTag.editTextTagID.setText(strTemp);
- }
- if (iWordCount * 4 < editTextAccessRWEpc.getText().toString().length()) {
- // needPopup = true;
- String strTemp = editTextAccessRWEpc.getText().toString().substring(0, iWordCount * 4);
- editTextAccessRWEpc.setText(strTemp);
- }
- if (editTextAccessRWEpc.getText().toString().length() != 0) {
- String strTemp = editTextAccessRWEpc.getText().toString();
- if (selectTag.editTextTagID.getText().toString().matches(strTemp) == false) {
- // needPopup = true;
- tagSelected.setAddress(strEpcValue); if (spinnerSelectBank.getSelectedItemPosition() == 0) selectTag.editTextTagID.setText(strTemp);
- }
- }
- }
- editTextAccessRWEpc.addTextChangedListener(new GenericTextWatcher(editTextAccessRWEpc, iWordCount * 4));
- String strTemp = editTextAccessRWEpc.getText().toString();
- editTextAccessRWEpc.setText(strTemp);
-
- if (needPopup) {
- CustomPopupWindow customPopupWindow = new CustomPopupWindow(mContext);
- customPopupWindow.popupStart("Changing EPC Length will automatically modify to " + (iWordCount * 16) + " bits.", false);
- }
- }
-
- long msStartTime;
- void startAccessTask() {
- if (selectTag.editTextTagID.getText().toString().length() == 0) {
- Toast.makeText(MainActivity.mContext, "Please select tag first !!!", Toast.LENGTH_SHORT).show();
- return;
- }
- CheckBox checkBox = (CheckBox) getActivity().findViewById(R.id.accessRWUserTitle);
- checkBox.setChecked(true);
- if (updating == false) {
- msStartTime = SystemClock.elapsedRealtime();
- textViewRunTime.setText(""); MainActivity.csLibrary4A.appendToLog("StreamOut: Start of running time");
- updating = true; bankProcessing = 0; restartAccessBank = -1;
- mHandler.removeCallbacks(updateRunnable);
- mHandler.post(updateRunnable);
- }
- }
- boolean updating = false; int bankProcessing = 0;
- private final Runnable updateRunnable = new Runnable() {
- @Override
- public void run() {
- boolean rerunRequest = true; boolean taskRequest = false;
- if (processResult()) { rerunRequest = true; }
- else if (accessTask == null || accessTask.isResultReady()) {
- bcheckBoxAll = false;
- boolean invalid = processTickItems();
- if (bankProcessing == 0 && bcheckBoxAll) rerunRequest = false;
- else if (bankProcessing++ != 0 && invalid == true) rerunRequest = false;
- else {
- if (restartAccessBank != accessBank) {
- restartAccessBank = accessBank;
- restartCounter = 3;
- }
- if (DEBUG) MainActivity.csLibrary4A.appendToLog("AccessReadWriteUserFragment().InventoryRfidTask(): tagID=" + selectTag.editTextTagID.getText() + ", operationrRead=" + operationRead + ", accessBank=" + accessBank + ", accOffset=" + accOffset + ", accSize=" + accSize);
- int selectOffset = 0;
- selectOffset = Integer.parseInt(editTextRWSelectOffset.getText().toString());
- EditText editTextBlockCount = (EditText) getActivity().findViewById(R.id.accessRWBlockCount);
- Integer accBlockCount = 32;
- try {
- accBlockCount = Integer.parseInt(editTextBlockCount.getText().toString());
- } catch (Exception ex) { }
- MainActivity.csLibrary4A.appendToLog("strOut: accWriteData=" + accWriteData);
- accessTask = new AccessTask1(
- (operationRead ? buttonRead : buttonWrite), invalid,
- accessBank, accOffset, accSize, accBlockCount, accWriteData,
- selectTag.editTextTagID.getText().toString(), spinnerSelectBank.getSelectedItemPosition() + 1, selectOffset,
- editTextAccessRWAccPassword.getText().toString(),
- Integer.valueOf(editTextaccessRWAntennaPower.getText().toString()),
- (operationRead ? RfidReaderChipData.HostCommands.CMD_18K6CREAD: RfidReaderChipData.HostCommands.CMD_18K6CWRITE), updateRunnable);
- accessTask.execute();
- rerunRequest = true;
- }
- }
- if (rerunRequest) {
- mHandler.postDelayed(updateRunnable, 100);
- if (DEBUG) MainActivity.csLibrary4A.appendToLog("AccessReadWriteUserFragment().updateRunnable(): Restart");
- }
- else {
- if (bankProcessing == 0 && bcheckBoxAll) {
- Toast.makeText(MainActivity.mContext, "no choice selected yet", Toast.LENGTH_SHORT).show();
- }
- updating = false;
- }
- }
- };
-
- TextView textViewUserOk, textViewBankOk;
- CheckBox checkBoxUser, checkBoxBank;
- int accessBank, accSize, accOffset; String accWriteData;
- int restartCounter = 0; int restartAccessBank = -1;
- boolean processResult() {
- String accessResult = null;
- if (accessTask == null) return false;
- if (accessTask.isResultReady() == false) return false;
- else {
- long duration = SystemClock.elapsedRealtime() - msStartTime;
- textViewRunTime.setText(String.format("Run time: %.2f sec", ((float) duration / 1000))); MainActivity.csLibrary4A.appendToLog("StreamOut: End of running time");
- accessResult = accessTask.getResult();
- if (DEBUG) MainActivity.csLibrary4A.appendToLog("processResult(): accessResult = " + accessResult);
- if (accessResult == null) {
- if (readWriteTypes == ReadWriteTypes.USER) {
- textViewUserOk.setText("E"); checkBoxUser.setChecked(false);
- }
- if (readWriteTypes == ReadWriteTypes.SBANK) {
- textViewBankOk.setText("E"); checkBoxBank.setChecked(false);
- }
- } else {
- if (DEBUG) MainActivity.csLibrary4A.appendToLog("accessResult = " + accessResult);
- if (readWriteTypes == ReadWriteTypes.USER) {
- textViewUserOk.setText("O"); checkBoxUser.setChecked(false);
- readWriteTypes = ReadWriteTypes.NULL;
- if (operationRead) {
- if (DEBUG) MainActivity.csLibrary4A.appendToLog("AccessReadWrite(). DATA with accessBank = " + accessBank);
- if (accessTask != null) {
- int iLength = accessTask.deformatWriteAccessData(accessResult).length();
- MainActivity.csLibrary4A.appendToLog("endingMessage length=" + iLength);
- if (iLength < accSize*4) textViewUserOk.setText("H");
- }
- editTextUserValue.setText(accessResult);
- accUserValue = accessResult;
- } else {
- accUserValue = editTextUserValue.getText().toString();
- }
- } else if (readWriteTypes == ReadWriteTypes.SBANK) {
- textViewBankOk.setText("O"); checkBoxBank.setChecked(false);
- readWriteTypes = ReadWriteTypes.NULL;
- if (accessResult.length() == 0 || operationRead == false) {
- } else {
- editTextEpcValue.setText(accessResult);
- accEpcValue = accessResult;
- }
- if (operationRead == false) accEpcValue = editTextEpcValue.getText().toString();
- }
- accessResult = null;
- }
- accessTask = null;
- return true;
- }
- }
- boolean bcheckBoxAll = false;
- boolean processTickItems() {
- String writeData = "";
- boolean invalidRequest1 = false;
-
- textViewUserOk = (TextView) getActivity().findViewById(R.id.accessRWUserOK);
- textViewBankOk = (TextView) getActivity().findViewById(R.id.accessRWEpc1OK);
-
- checkBoxUser = (CheckBox) getActivity().findViewById(R.id.accessRWUserTitle);
- checkBoxBank = (CheckBox) getActivity().findViewById(R.id.accessRWEpc1);
-
- if (checkBoxUser.isChecked() == true) {
- textViewUserOk.setText("");
- accessBank = 3; accOffset = 0; accSize = 0; readWriteTypes = ReadWriteTypes.USER;
- if (DEBUG) MainActivity.csLibrary4A.appendToLog("processTickItems(): start USER operation");
- int iValue = 0;
- try {
- EditText editTextTidOffset = (EditText) getActivity().findViewById(R.id.accessRWUserOffset);
- iValue = Integer.parseInt(editTextTidOffset.getText().toString());
- } catch (Exception ex) {
- }
- accOffset = iValue;
- iValue = 0;
- try {
- EditText editTextUserLength = (EditText) getActivity().findViewById(R.id.accessRWUserLength);
- iValue = Integer.parseInt(editTextUserLength.getText().toString());
- } catch (Exception ex) {
- }
- accSize = iValue;
- if (operationRead) {
- editTextUserValue.setText("");
- } else {
- String strValue = editTextUserValue.getText().toString();
- MainActivity.csLibrary4A.appendToLog("strOut: strValue=" + strValue + ", strValue.length=" + strValue.length() + ", accUserValue=" + accUserValue + ", accUserValue.lengt=" + accUserValue.length());
- if (strValue.length() >= 4 && accUserValue.matches(strValue) == false) {
- writeData = strValue;
- }
- }
- } else if (checkBoxBank.isChecked() == true) {
- textViewBankOk.setText("");
- accessBank = spinnerRWSelectBank.getSelectedItemPosition(); accOffset = 0; accSize = 0; readWriteTypes = ReadWriteTypes.SBANK;
- int iValue = 0;
- try {
- EditText editTextEpcOffset = (EditText) getActivity().findViewById(R.id.accessRWEpcOffset);
- iValue = Integer.parseInt(editTextEpcOffset.getText().toString());
- } catch (Exception ex) {
- }
- accOffset = iValue;
- iValue = 0;
- try {
- EditText editTextEpcLength = (EditText) getActivity().findViewById(R.id.accessRWEpcLength);
- iValue = Integer.parseInt(editTextEpcLength.getText().toString());
- } catch (Exception ex) {
- }
- accSize = iValue;
- if (operationRead) {
- editTextEpcValue.setText("");
- } else {
- String strValue = editTextEpcValue.getText().toString();
- if (strValue.length() >= 4 && strValue.matches(accEpcValue) == false) {
- accSize = strValue.length() / 4;
- if (strValue.length() %4 != 0) accSize++;
- writeData = strValue;
- }
- }
- } else {
- invalidRequest1 = true;
- bcheckBoxAll = true;
- }
-
- if (restartAccessBank == accessBank) {
- if (restartCounter == 0) invalidRequest1 = true;
- else restartCounter--;
- }
- accWriteData = writeData;
- return invalidRequest1;
- }
-}
diff --git a/app/src/main/java/com/csl/cs710ademoapp/fragments/AccessRegisterFragment.java b/app/src/main/java/com/csl/cs710ademoapp/fragments/AccessRegisterFragment.java
deleted file mode 100644
index 6b78ad4..0000000
--- a/app/src/main/java/com/csl/cs710ademoapp/fragments/AccessRegisterFragment.java
+++ /dev/null
@@ -1,674 +0,0 @@
-package com.csl.cs710ademoapp.fragments;
-
-import static com.csl.cs710ademoapp.MainActivity.mContext;
-
-import android.graphics.Color;
-import android.os.AsyncTask;
-import android.os.Bundle;
-import androidx.appcompat.app.ActionBar;
-import androidx.appcompat.app.AppCompatActivity;
-import android.text.Editable;
-import android.text.TextWatcher;
-import android.view.LayoutInflater;
-import android.view.View;
-import android.view.ViewGroup;
-import android.widget.AdapterView;
-import android.widget.ArrayAdapter;
-import android.widget.Button;
-import android.widget.CheckBox;
-import android.widget.CompoundButton;
-import android.widget.EditText;
-import android.widget.Spinner;
-import android.widget.TableRow;
-import android.widget.TextView;
-import android.widget.Toast;
-
-import com.csl.cs710ademoapp.AccessTask;
-import com.csl.cs710ademoapp.CustomPopupWindow;
-import com.csl.cs710ademoapp.InventoryBarcodeTask;
-import com.csl.cs710ademoapp.InventoryRfidTask;
-import com.csl.cs710ademoapp.MainActivity;
-import com.csl.cs710ademoapp.R;
-import com.csl.cslibrary4a.NotificationConnector;
-import com.csl.cslibrary4a.ReaderDevice;
-import com.csl.cslibrary4a.RfidReaderChipData;
-import com.csl.cslibrary4a.Utility;
-
-import java.util.ArrayList;
-
-public class AccessRegisterFragment extends CommonFragment {
- CustomPopupWindow customPopupWindow;
-
- TableRow tableRowSelectMask, tableRowSelectBank;
- Spinner spinnerSelectBank, spinnerAccessBank, spinnerWriteEpcClass, spinnerWriteDataType;
- EditText editTextSelectMask, editTextSelectPopulation, editTextPassword, editTextAntennaPower, editTextWriteData, editTextWriteLength;
- CheckBox checkBoxWriteLengthEnable;
- TextView textViewSelectedTags, textViewWriteCount, textViewRunTime, textViewTagGot, textViewVoltageLevel;
- TextView textViewYield, textViewTotal;
- Button buttonSelect, buttonClearSelect, buttonReadBar, buttonWrite;
-
- InventoryRfidTask inventoryRfidTask;
- InventoryBarcodeTask inventoryBarcodeTask;
- AccessTask accessTask;
-
- ReaderDevice tagSelected = MainActivity.tagSelected;
- boolean newWriteData;
- String writeValueOld = "";
- int iAutoRun = 0;
-
- @Override
- public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
- super.onCreateView(inflater, container, savedInstanceState, true);
- return inflater.inflate(R.layout.fragment_access_register, container, false);
- }
-
- @Override
- public void onActivityCreated(Bundle savedInstanceState) {
- super.onActivityCreated(savedInstanceState);
-
- ActionBar actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
- actionBar.setIcon(R.drawable.dl_access);
- actionBar.setTitle(R.string.title_activity_registertag);
-
- customPopupWindow = new CustomPopupWindow(mContext);
-
- tableRowSelectMask = (TableRow) getActivity().findViewById(R.id.registerSelectMaskRow);
- tableRowSelectBank = (TableRow) getActivity().findViewById(R.id.registerSelectBankRow);
-
- spinnerSelectBank = (Spinner) getActivity().findViewById(R.id.registerSelectBank);
- ArrayAdapter targetAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.read_memoryBank_options, R.layout.custom_spinner_layout);
- targetAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
- spinnerSelectBank.setAdapter(targetAdapter);
- spinnerSelectBank.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
- @Override
- public void onItemSelected(AdapterView> parent, View view, int position, long id) {
- switch (position) {
- case 0: //if EPC
- if (tagSelected != null) editTextSelectMask.setText(tagSelected.getAddress());
- break;
- case 1:
- if (tagSelected != null) { if (tagSelected.getTid() != null) editTextSelectMask.setText(tagSelected.getTid()); }
- break;
- case 2:
- if (tagSelected != null) { if (tagSelected.getUser() != null) editTextSelectMask.setText(tagSelected.getUser()); }
- break;
- default:
- break;
- }
- }
-
- @Override
- public void onNothingSelected(AdapterView> parent) {
-
- }
- });
-
- spinnerAccessBank = (Spinner) getActivity().findViewById(R.id.registerAccessBank);
- targetAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.write_memoryBank_options, R.layout.custom_spinner_layout);
- targetAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
- spinnerAccessBank.setAdapter(targetAdapter);
-
- spinnerWriteEpcClass = (Spinner) getActivity().findViewById(R.id.registerWriteEpcClass);
- targetAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.write_Epc_options, R.layout.custom_spinner_layout);
- targetAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
- spinnerWriteEpcClass.setAdapter(targetAdapter);
- spinnerWriteEpcClass.setEnabled(false);
-
- spinnerWriteDataType = (Spinner) getActivity().findViewById(R.id.registerWriteDataType);
- targetAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.write_data_options, R.layout.custom_spinner_layout);
- targetAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
- spinnerWriteDataType.setAdapter(targetAdapter);
-
- Button buttonConfirm = (Button) getActivity().findViewById(R.id.registerConfirm2Button);
- buttonConfirm.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- Toast.makeText(MainActivity.mContext, "Step 2 data is confirmed.", Toast.LENGTH_SHORT).show();
- }
- });
-
- editTextSelectMask = (EditText) getActivity().findViewById(R.id.registerSelectMask);
- editTextSelectPopulation = (EditText) getActivity().findViewById(R.id.registerSelectPopulation);
- editTextPassword = (EditText) getActivity().findViewById(R.id.registerPassword);
- editTextPassword.setText("00000000");
- editTextAntennaPower = (EditText) getActivity().findViewById(R.id.registerAntennaPower);
- editTextWriteData = (EditText) getActivity().findViewById(R.id.registerWriteData);
- editTextWriteData.setEnabled(true);
-// editTextBarValue.setText("19dec163");
- newWriteData = false; editTextWriteData.setTextColor(Color.RED);
- editTextWriteData.addTextChangedListener(new TextWatcher() {
- @Override
- public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { }
-
- @Override
- public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { }
-
- @Override
- public void afterTextChanged(Editable editable) {
- String writeValue = editTextWriteData.getText().toString().trim();
- if (true) newWriteData = true;
- if (writeValue.matches(writeValueOld) == false) {
- writeValueOld = writeValue;
- editTextWriteData.setTextColor(Color.BLACK);
- //checkBoxNewValue.setEnabled(true);
- //checkBoxNewValue.setText("Reset to old value");
- newWriteData = true;
- }
-
- if (inventoryBarcodeTask != null) {
- if (inventoryBarcodeTask.getStatus() == AsyncTask.Status.RUNNING) {
- barcodeReadDone = true; MainActivity.csLibrary4A.appendToLog("barcodeReadDone = true in textChanged");
- MainActivity.csLibrary4A.appendToLog("going to startStopBarcodeHandler 1"); startStopBarcodeHandler(false);
- }
- }
- if (checkBoxWriteLengthEnable.isChecked() == false) {
- int length1 = writeValue.length() * 4;
- int length = length1 / 16;
- if (length * 16 != length1) length++;
- editTextWriteLength.setText(String.valueOf(length));
- }
- }
- });
- editTextWriteLength = (EditText) getActivity().findViewById(R.id.registerWriteLength);
-
- checkBoxWriteLengthEnable = (CheckBox) getActivity().findViewById(R.id.registerWriteLengthEnable);
- checkBoxWriteLengthEnable.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
- @Override
- public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
- if (isChecked) editTextWriteLength.setEnabled(true);
- else editTextWriteLength.setEnabled(false);
- }
- });
-
- buttonClearSelect = (Button) getActivity().findViewById(R.id.registerClearSelectButton);
- buttonClearSelect.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- tagSelected = null;
- editTextSelectMask.setText("");
- }
- });
-
- buttonSelect = (Button) getActivity().findViewById(R.id.registerSelectButton);
- buttonSelect.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- if (buttonSelect.getText().toString().contains("Clear")) {
- buttonClearSelect.setVisibility(View.VISIBLE);
- tableRowSelectMask.setVisibility(View.VISIBLE);
- tableRowSelectBank.setVisibility(View.VISIBLE);
- textViewSelectedTags.setText("");
- buttonSelect.setText("Read");
- } else if (buttonSelect.getText().toString().contains("Stop")) {
- inventoryRfidTask.taskCancelReason = InventoryRfidTask.TaskCancelRReason.BUTTON_RELEASE;
- mHandler.removeCallbacks(runnableSelect);
- textViewSelectedTags.setText("");
- for (int i = 0; i < epcArrayList.size(); i++) {
- MainActivity.csLibrary4A.appendToLog("epcArrayList.get[" + i + "] = " + epcArrayList.get(i));
- textViewSelectedTags.append(epcArrayList.get(i) + "\n");
- }
- if (textViewSelectedTags.getText().toString().trim().length() == 0) {
- buttonSelect.setText("Read");
- } else {
- buttonClearSelect.setVisibility(View.GONE);
- tableRowSelectMask.setVisibility(View.GONE);
- tableRowSelectBank.setVisibility(View.GONE);
- buttonSelect.setText("Clear");
- }
- }
- else {
- textViewSelectedTags.setText("");
- String strTagId = editTextSelectMask.getText().toString();
- int selectBank = spinnerSelectBank.getSelectedItemPosition() + 1;
- long pwrlevel = Integer.parseInt(editTextAntennaPower.getText().toString());
- MainActivity.csLibrary4A.setTagRead(0);
- MainActivity.csLibrary4A.setSelectedTag(strTagId, selectBank, pwrlevel);
- MainActivity.csLibrary4A.appendToLog("Debug_Compact: AccessRegisterFragment.onActivityCreated.onClick");
- MainActivity.csLibrary4A.startOperation(RfidReaderChipData.OperationTypes.TAG_INVENTORY);
- inventoryRfidTask = new InventoryRfidTask();
- inventoryRfidTask.execute();
- MainActivity.sharedObjects.serviceArrayList.clear(); epcArrayList.clear();
- mHandler.post(runnableSelect); buttonSelect.setText("Stop");
- }
- }
- });
-
- Button buttonConvert = (Button) getActivity().findViewById(R.id.registerWriteConvert);
- buttonConvert.setOnClickListener(new View.OnClickListener() {
- EditText editTextWriteEpcFilter = (EditText) getActivity().findViewById(R.id.registerWriteEpcFilter);
- EditText editTextWriteEpcCompanyPrefix = (EditText) getActivity().findViewById(R.id.registerWriteEpcCompanyPrefix);
- EditText editTextWriteEpcItemReference = (EditText) getActivity().findViewById(R.id.registerWriteEpcItemReference);
- EditText editTextWriteEpcSerial = (EditText) getActivity().findViewById(R.id.registerWriteEpcSerial);
- @Override
- public void onClick(View view) {
- String strValue = MainActivity.csLibrary4A.getEpc4upcSerial(
- Utility.EpcClass.values()[spinnerWriteEpcClass.getSelectedItemPosition()],
- editTextWriteEpcFilter.getText().toString(),
- editTextWriteEpcCompanyPrefix.getText().toString(),
- editTextWriteEpcItemReference.getText().toString(),
- editTextWriteEpcSerial.getText().toString()
- );
- if (strValue != null) editTextWriteData.setText(strValue);
- }
- });
-
- buttonReadBar = (Button) getActivity().findViewById(R.id.registerReadBarButton);
- buttonReadBar.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- MainActivity.csLibrary4A.appendToLog("going to startStopBarcodeHandler 2"); startStopBarcodeHandler(false);
- }
- });
-
- textViewSelectedTags = (TextView) getActivity().findViewById(R.id.registerSelectedTags);
- //textViewWriteCount = (TextView) getActivity().findViewById(R.id.registerWrittenCount);
- textViewRunTime = (TextView) getActivity().findViewById(R.id.registerRunTime);
- textViewTagGot = (TextView) getActivity().findViewById(R.id.registetTagGotView);
- textViewVoltageLevel = (TextView) getActivity().findViewById(R.id.registerVoltageLevel);
-
- buttonWrite = (Button) getActivity().findViewById(R.id.registerWriteButton);
- buttonWrite.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- if (buttonWrite.getText().toString().trim().length() == 0) return;
- runningAuto123 = 0; startStopAccessHandler(false);
- }
- });
-
- Button buttonWrite3 = (Button) getActivity().findViewById(R.id.registerWrite3Button);
- buttonWrite3.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- if (accessTask != null) if (accessTask.getStatus() == AsyncTask.Status.RUNNING) return;
- runningAuto123 = 0; startStopAccessHandler(false);
- }
- });
-
- Button buttonAuto = (Button) getActivity().findViewById(R.id.registerAutoButton);
- buttonAuto.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- if (accessTask != null) if (accessTask.getStatus() == AsyncTask.Status.RUNNING) return;
- runningAuto123 = 1; startStopAccessHandler(false);
- }
- });
-
- Button buttonAuto123 = (Button) getActivity().findViewById(R.id.registerAutoButtonWBarcodeRead);
- buttonAuto123.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- if (accessTask != null) if (accessTask.getStatus() == AsyncTask.Status.RUNNING) return;
- runningAuto123 = 2; mHandler.post(runnableAuto123);
- }
- });
-
- textViewYield = (TextView) getActivity().findViewById(R.id.registerYieldView);
- textViewTotal = (TextView) getActivity().findViewById(R.id.registerTotalView);
-
- Button buttonResetCount = (Button) getActivity().findViewById(R.id.registerResetCountButton);
- buttonResetCount.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- resetCount = true;
- textViewRunTime.setText(""); textViewTagGot.setText(""); textViewVoltageLevel.setText("");
- textViewYield.setText(""); textViewTotal.setText("");
- }
- });
-
- MainActivity.csLibrary4A.setSameCheck(false);
- }
-
- @Override
- public void onResume() {
- super.onResume();
- setNotificationListener();
- }
-
- @Override
- public void onPause() {
- MainActivity.csLibrary4A.setNotificationListener(null);
- super.onPause();
- }
-
- @Override
- public void onDestroy() {
- MainActivity.csLibrary4A.setNotificationListener(null);
- mHandler.removeCallbacks(runnableSelect);
- mHandler.removeCallbacks(runnableAuto123);
- if (inventoryBarcodeTask != null) inventoryBarcodeTask.taskCancelReason = InventoryBarcodeTask.TaskCancelRReason.DESTORY;
- if (accessTask != null) accessTask.taskCancelReason = AccessTask.TaskCancelRReason.DESTORY;
- if (DEBUG) MainActivity.csLibrary4A.appendToLog("AcccessRegisterFragment().onDestory(): onDestory()");
- MainActivity.csLibrary4A.setSameCheck(true);
- MainActivity.csLibrary4A.restoreAfterTagSelect();
- super.onDestroy();
- }
-
- public AccessRegisterFragment() {
- super("AccessRegisterFragment");
- }
-
- void setNotificationListener() {
- MainActivity.csLibrary4A.setNotificationListener(new NotificationConnector.NotificationListener() {
- @Override
- public void onChange() {
- MainActivity.csLibrary4A.appendToLog("TRIGGER key is pressed.");
- if (barcodeReadRequesting) {
- if (customPopupWindow.popupWindow.isShowing()) {
- customPopupWindow.popupWindow.dismiss();
- barcodeReadRequesting = false; MainActivity.csLibrary4A.appendToLog("barcodeReadRequesting = false");
- ready2nextRun = true; MainActivity.csLibrary4A.appendToLog("ready2nextRun 1 = true after popup");
- }
- }
- }
- });
- }
-
- ArrayList epcArrayList = new ArrayList();
- Runnable runnableSelect = new Runnable() {
- @Override
- public void run() {
- while (MainActivity.sharedObjects.serviceArrayList.size() != 0) {
- String strEpc = MainActivity.sharedObjects.serviceArrayList.get(0); MainActivity.sharedObjects.serviceArrayList.remove(0);
- MainActivity.csLibrary4A.appendToLog("epcArrayList.add[" + epcArrayList.size() + "] = " + strEpc);
- boolean matched = false;
- for (int i = 0; i < epcArrayList.size(); i++) {
- if (epcArrayList.get(i).matches(strEpc)) {
- matched = true;
- break;
- }
- }
- if (matched == false && strEpc != null) {
- epcArrayList.add(strEpc);
- }
- }
- textViewSelectedTags.setText("unique tag number = " + epcArrayList.size());
- mHandler.postDelayed(runnableSelect, 1000);
- }
- };
-
- boolean ready2nextRun = true, barcodeReadRequesting = false, barcodeReadDone = false;
- boolean runningAccessTask = false; int runningAuto123 = 0, totalTag = 0;
- Runnable runnableAuto123 = new Runnable() {
- @Override
- public void run() {
- boolean running = false;
- MainActivity.csLibrary4A.appendToLog("found barcodeReadRequesting as " + barcodeReadRequesting );
- if (barcodeReadRequesting) {
- if (customPopupWindow.popupWindow.isShowing()) running = true;
- else {
- barcodeReadRequesting = false; MainActivity.csLibrary4A.appendToLog("barcodeReadRequesting = false");
- ready2nextRun = true; MainActivity.csLibrary4A.appendToLog("ready2nextRun 1 = true after popup");
- }
- }
- MainActivity.csLibrary4A.appendToLog("runnableAuto123: runningAuto123 = " + runningAuto123 + ", inventoryBarcodeTask = " + (inventoryBarcodeTask != null ? "valid" : "null"));
- if (runningAuto123 == 2 && inventoryBarcodeTask != null) { if (inventoryBarcodeTask.getStatus() == AsyncTask.Status.RUNNING) running = true; }
- MainActivity.csLibrary4A.appendToLog("runnableAuto123: accessTask = " + (accessTask != null ? "valid" : "null"));
- if (accessTask != null) { if (accessTask.getStatus() == AsyncTask.Status.RUNNING) running = true; }
- MainActivity.csLibrary4A.appendToLog("runnableAuto123: running = " + running);
- if (running == false) {
- int totalTagNew = getTotalTag();
- if (runningAccessTask) {
- if (totalTagNew > totalTag) {
- if (spinnerWriteDataType.getSelectedItemPosition() == 2) editTextWriteData.setText(incrementString(editTextWriteData.getText().toString()));
- } else runningAuto123 = 0;
- }
- MainActivity.csLibrary4A.appendToLog("runnableAuto123: totalTagNew = " + totalTagNew + ", totalTag = " + totalTag + ", runningAuto123 = " + runningAuto123 + ", runningAccessTask = " + runningAccessTask);
- runningAccessTask = false;
-
- boolean bcontinue = true;
- if (spinnerWriteDataType.getSelectedItemPosition() == 1 && ready2nextRun == false) {
- if (buttonSelect.getText().toString().contains("Clear")) {
- if (textViewSelectedTags.getText().toString().trim().length() == 0) bcontinue = false;
- }
- if (bcontinue) {
- customPopupWindow.popupStart("Next barcode.", false);
- barcodeReadRequesting = true; MainActivity.csLibrary4A.appendToLog("barcodeReadRequesting = true");
- barcodeReadDone = false; MainActivity.csLibrary4A.appendToLog("barcodeReadDone = false as popup");
- bcontinue = false;
- running = true;
- }
- }
- if (bcontinue) {
- if (ready2nextRun == false) {
- if (buttonSelect.getText().toString().contains("Clear")) {
- if (textViewSelectedTags.getText().toString().trim().length() != 0) {
- ready2nextRun = true; MainActivity.csLibrary4A.appendToLog("ready2nextRun = true as valid selected tag in textview");
- }
- } else {
- ready2nextRun = true; MainActivity.csLibrary4A.appendToLog("ready2nextRun = true as not clear");
- }
- }
- if (ready2nextRun) {
- if (startStopAccessHandler(false)) running = true;
- }
- }
- }
- if (running && runningAuto123 == 2) mHandler.postDelayed(runnableAuto123, 250);
- else {
- ready2nextRun = true; MainActivity.csLibrary4A.appendToLog("ready2nextRun = true at the runnable end");
- barcodeReadRequesting = false; barcodeReadDone = false; MainActivity.csLibrary4A.appendToLog("barcodeReadDone = false at the runnable end");
- }
- }
- };
-
- String incrementString(String string1) {
- for (int i = 0; i < string1.length(); i++) {
- String string2 = string1.substring(string1.length() - 1 - i, string1.length() - i);
- Integer iValue = Integer.valueOf(string2, 16);
- if (++iValue >= 16) iValue = 0;
- String stringA = string1.substring(0, string1.length() - 1 - i);
- String stringB = String.format("%X", iValue);
- String stringC = null;
- if (i > 0) stringC = string1.substring(string1.length() - i, string1.length());
- MainActivity.csLibrary4A.appendToLog("stringABC = " + stringA + "," + stringB + "," + stringC);
- String stringABC = (stringA != null ? stringA : "") + stringB + (stringC != null ? stringC : "");
- string1 = stringABC;
- if (iValue != 0) break;
- }
- return string1;
- }
-
- int getTotalTag() {
- int iValue = 0;
- String stringTotal = textViewTotal.getText().toString();
- String stringTotalTag = stringTotal.replaceAll("[^0-9.]", "");
- try {
- iValue = Integer.parseInt(stringTotalTag);
- } catch (Exception ex) {
- }
- MainActivity.csLibrary4A.appendToLog("totalTag = " + iValue);
- return iValue;
- }
-
- void startStopBarcodeHandler(boolean buttonTrigger) {
- if (MainActivity.sharedObjects.runningInventoryRfidTask) {
- Toast.makeText(MainActivity.mContext, "Running RFID access", Toast.LENGTH_SHORT).show();
- return;
- }
-
- boolean started = false;
- if (inventoryBarcodeTask != null) if (inventoryBarcodeTask.getStatus() == AsyncTask.Status.RUNNING) started = true;
- if (buttonTrigger && ((started && MainActivity.csLibrary4A.getTriggerButtonStatus()) || (started == false && MainActivity.csLibrary4A.getTriggerButtonStatus() == false))) return;
- if (started == false) {
- if (MainActivity.csLibrary4A.isBleConnected() == false) {
- Toast.makeText(MainActivity.mContext, R.string.toast_ble_not_connected, Toast.LENGTH_SHORT).show();
- return;
- }
- if (MainActivity.csLibrary4A.isBarcodeFailure()) {
- MainActivity.csLibrary4A.appendToLog("Toasted 'Barcode is disable'");
- Toast.makeText(MainActivity.mContext, "Barcode is disabled", Toast.LENGTH_SHORT).show();
- return;
- }
- boolean noToast = true; //runningAuto123;
- inventoryBarcodeTask = new InventoryBarcodeTask(null, null, editTextWriteData, null, null, null, buttonReadBar, buttonWrite, null, noToast);
- inventoryBarcodeTask.execute();
- } else inventoryBarcodeTask.taskCancelReason = InventoryBarcodeTask.TaskCancelRReason.STOP;
- }
-
- boolean startStopAccessHandler(boolean buttonTrigger) {
- boolean runningBarcode = false;
- if (inventoryBarcodeTask != null) {
- if (inventoryBarcodeTask.getStatus() == AsyncTask.Status.RUNNING) {
- MainActivity.csLibrary4A.appendToLog("going to startStopBarcodeHandler 1"); startStopBarcodeHandler(buttonTrigger);
- runningBarcode = true;
- }
- }
-
- boolean runningAccessTask = false;
- if (accessTask != null) { if (accessTask.getStatus() == AsyncTask.Status.RUNNING) runningAccessTask = true; }
- if (buttonTrigger && ((runningAccessTask && MainActivity.csLibrary4A.getTriggerButtonStatus()) || (runningAccessTask == false && MainActivity.csLibrary4A.getTriggerButtonStatus() == false))) {
- return true;
- }
-
- boolean validResult = true;
- if (runningBarcode) { }
- else if (runningAccessTask) {
- if (buttonTrigger) accessTask.taskCancelReason = AccessTask.TaskCancelRReason.BUTTON_RELEASE;
- else accessTask.taskCancelReason = AccessTask.TaskCancelRReason.STOP;
- } else {
- if (MainActivity.csLibrary4A.isBleConnected() == false) {
- Toast.makeText(MainActivity.mContext, R.string.toast_ble_not_connected, Toast.LENGTH_SHORT).show();
- validResult = false;
- } else if (MainActivity.csLibrary4A.isRfidFailure()) {
- Toast.makeText(MainActivity.mContext, "Rfid is disabled", Toast.LENGTH_SHORT).show();
- validResult = false;
- } else if (MainActivity.csLibrary4A.mrfidToWriteSize() != 0) {
- Toast.makeText(MainActivity.mContext, R.string.toast_not_ready, Toast.LENGTH_SHORT).show();
- validResult = false;
- }
-
- if (validResult) {
- if (barcodeReadDone == false && spinnerWriteDataType.getSelectedItemPosition() == 1) {
- MainActivity.csLibrary4A.appendToLog("going to startStopBarcodeHandler 2");
- startStopBarcodeHandler(buttonTrigger);
- } else {
- totalTag = getTotalTag();
- if (startAccessTask()) validResult = false;
- else if (runningAuto123 == 2) this.runningAccessTask = true;
- MainActivity.csLibrary4A.appendToLog("runningAccessTask = " + this.runningAccessTask);
- resetOldValue();
- ready2nextRun = false;
- MainActivity.csLibrary4A.appendToLog("ready2nextRun = false after startStopAccessHandler");
- }
- }
- }
- return validResult;
- }
-
- void resetOldValue() {
- editTextWriteData.setTextColor(Color.RED);
- /*checkBoxNewValue.setEnabled(false);
- checkBoxNewValue.setText("Old value");
- checkBoxNewValue.setChecked(false);*/
- newWriteData = false;
- }
-
- boolean resetCount = true;
- boolean startAccessTask() {
- boolean invalidRequest1 = false;
-
- int selectQValue = -1, selectPopulation = -1;
- try {
- selectPopulation = Integer.parseInt(editTextSelectPopulation.getText().toString());
- } catch (Exception ex) { }
- if (selectPopulation < 0) invalidRequest1 = true;
- else if (selectPopulation <= getTotalTag()) invalidRequest1 = true;
- else {
- selectQValue = MainActivity.csLibrary4A.getPopulation2Q(selectPopulation);
- if (selectQValue < 0) invalidRequest1 = true;
- }
- MainActivity.csLibrary4A.appendToLog("selectQValue = " + selectQValue + ", selectPopulation = " + selectPopulation);
-
- String selectMask = "";
- int selectBank1 = -1;
- int selectOffset1 = -1;
- if (buttonSelect.getText().toString().contains("Clear")) {
- String[] stringSplited = textViewSelectedTags.getText().toString().split("\n", 2);
- if (stringSplited != null && stringSplited.length > 0 && stringSplited[0] != null && stringSplited[0].trim().length() != 0) {
- selectMask = stringSplited[0].trim();
- selectBank1 = 1;
- selectOffset1 = 32;
- if (stringSplited.length > 1 && stringSplited[1] != null && stringSplited[1].trim().length() != 0) textViewSelectedTags.setText(stringSplited[1].trim());
- else textViewSelectedTags.setText("");
- }
- } else {
- selectMask = editTextSelectMask.getText().toString().trim();
- int selectBankPosition = spinnerSelectBank.getSelectedItemPosition();
- selectBank1 = selectBankPosition + 1;
- int selectOffset = 0;
- try {
- EditText editTextSelectOffset = (EditText) getActivity().findViewById(R.id.registerSelectOffset);
- selectOffset = Integer.parseInt(editTextSelectOffset.getText().toString());
- } catch (Exception ex) { }
- selectOffset1 = selectBankPosition == 0 ? selectOffset + 32 : selectOffset;
- }
- if (selectMask.trim().length() == 0 || selectBank1 < 0 || selectOffset1 < 0) {
- invalidRequest1 = true;
- }
-
- String password = editTextPassword.getText().toString();
- if (password.length() != 8) invalidRequest1 = true;
-
- int antennaPower = -1;
- try {
- editTextAntennaPower = (EditText) getActivity().findViewById(R.id.registerAntennaPower);
- antennaPower = Integer.parseInt(editTextAntennaPower.getText().toString());
- } catch (Exception ex) { }
- if (antennaPower < 0) invalidRequest1 = true;
-
- int accessBank = spinnerAccessBank.getSelectedItemPosition() == 0 ? 1 : 3;
- MainActivity.csLibrary4A.appendToLog("accessBank = " + accessBank);
- if (invalidRequest1 == false) {
- if (MainActivity.csLibrary4A.setAccessBank(accessBank) == false) invalidRequest1 = true;
- }
-
- int writeOffset = -1;
- try {
- EditText editTextWriteOffset = (EditText) getActivity().findViewById(R.id.registerWriteOffset);
- writeOffset = Integer.parseInt(editTextWriteOffset.getText().toString());
- if (spinnerAccessBank.getSelectedItemPosition() == 0) writeOffset += 2;
- } catch (Exception ex) { }
- if (writeOffset < 0) invalidRequest1 = true;
- MainActivity.csLibrary4A.appendToLog("writeOffset = " + writeOffset);
- if (invalidRequest1 == false) {
- if (MainActivity.csLibrary4A.setAccessOffset(writeOffset) == false) invalidRequest1 = true;
- }
-
- int writeLength = -1;
- try {
- writeLength = Integer.parseInt(editTextWriteLength.getText().toString());
- } catch (Exception ex) { }
- if (writeLength < 0) invalidRequest1 = true;
- MainActivity.csLibrary4A.appendToLog("writeLength = " + writeLength);
- if (invalidRequest1 == false) {
- if (writeLength == 0) invalidRequest1 = true;
- else if (MainActivity.csLibrary4A.setAccessCount(writeLength) == false) {
- invalidRequest1 = true;
- }
- }
-
- String writeData = editTextWriteData.getText().toString().trim();
- if (writeData.length() == 0) invalidRequest1 = true;
- MainActivity.csLibrary4A.appendToLog("writeData = " + writeData);
- if (invalidRequest1 == false) {
- if (MainActivity.csLibrary4A.setAccessWriteData(writeData) == false) {
- invalidRequest1 = true;
- }
- }
-
- int repeatCount = 0;
- if (runningAuto123 == 1) repeatCount = selectPopulation;
-
- MainActivity.csLibrary4A.appendToLog("invalidRequest1 = " + invalidRequest1
- + ", selectMask = " + selectMask + ", selectBank1 = " + selectBank1 + ", selectOffset1 = " + selectOffset1
- + ", password = " + password + ", power = " + antennaPower + ", repeatCount = " + repeatCount + ", resetCount = " + resetCount);
- accessTask = new AccessTask(buttonWrite, textViewWriteCount, invalidRequest1, true,
- selectMask, selectBank1, selectOffset1,
- password, antennaPower, RfidReaderChipData.HostCommands.CMD_18K6CWRITE,
- selectQValue, repeatCount, resetCount, false,
- textViewRunTime, textViewTagGot, textViewVoltageLevel, textViewYield, textViewTotal);
- accessTask.execute();
- resetCount = false;
- return invalidRequest1;
- }
-}
diff --git a/app/src/main/java/com/csl/cs710ademoapp/fragments/AccessSecurityFragment.java b/app/src/main/java/com/csl/cs710ademoapp/fragments/AccessSecurityFragment.java
deleted file mode 100644
index d951cd5..0000000
--- a/app/src/main/java/com/csl/cs710ademoapp/fragments/AccessSecurityFragment.java
+++ /dev/null
@@ -1,108 +0,0 @@
-package com.csl.cs710ademoapp.fragments;
-
-import android.os.Bundle;
-import android.view.LayoutInflater;
-import android.view.View;
-import android.view.ViewGroup;
-
-import androidx.appcompat.app.ActionBar;
-import androidx.appcompat.app.AppCompatActivity;
-import androidx.viewpager.widget.ViewPager;
-
-import com.csl.cs710ademoapp.MainActivity;
-import com.csl.cs710ademoapp.R;
-import com.csl.cslibrary4a.AdapterTab;
-import com.google.android.material.tabs.TabLayout;
-
-public class AccessSecurityFragment extends CommonFragment {
- private ActionBar actionBar;
- private ViewPager viewPager;
- AdapterTab adapter;
-
- private String[] tabs = {"Lock", "Kill"};
-
- @Override
- public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
- super.onCreateView(inflater, container, savedInstanceState, true);
- return inflater.inflate(R.layout.custom_tabbed_layout, container, false);
- }
-
- @Override
- public void onActivityCreated(Bundle savedInstanceState) {
- super.onActivityCreated(savedInstanceState);
-
- actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
- actionBar.setIcon(R.drawable.dl_access);
- actionBar.setTitle(R.string.title_activity_security);
-
- TabLayout tabLayout = (TabLayout) getActivity().findViewById(R.id.OperationsTabLayout);
-
- adapter = new AdapterTab(getActivity().getSupportFragmentManager(), tabs.length);
- adapter.setFragment(0, new AccessSecurityLockFragment());
- adapter.setFragment(1, new AccessSecurityKillFragment());
-
- viewPager = (ViewPager) getActivity().findViewById(R.id.OperationsPager);
- viewPager.setAdapter(adapter);
- viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
-
- for (String tab_name : tabs) {
- tabLayout.addTab(tabLayout.newTab().setText(tab_name));
- }
-
- tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
- @Override
- public void onTabSelected(TabLayout.Tab tab) {
- viewPager.setCurrentItem(tab.getPosition());
- }
-
- @Override
- public void onTabUnselected(TabLayout.Tab tab) {
- }
-
- @Override
- public void onTabReselected(TabLayout.Tab tab) {
- }
- });
- }
-
- @Override
- public void onPause() {
- adapter.fragment0.onPause();
- adapter.fragment1.onPause();
- super.onPause();
- }
-
- @Override
- public void onStop() {
- adapter.fragment0.onStop();
- adapter.fragment1.onStop();
- super.onStop();
- }
-
- @Override
- public void onDestroyView() {
- adapter.fragment0.onDestroyView();
- adapter.fragment1.onDestroyView();
- super.onDestroyView();
- }
-
- @Override
- public void onDestroy() {
- adapter.fragment0.onDestroy();
- adapter.fragment1.onDestroy();
- MainActivity.csLibrary4A.setSameCheck(true);
- MainActivity.csLibrary4A.restoreAfterTagSelect();
- super.onDestroy();
- }
-
- @Override
- public void onDetach() {
- adapter.fragment0.onDetach();
- adapter.fragment1.onDetach();
- super.onDetach();
- }
-
- public AccessSecurityFragment() {
- super("AccessSecurityFragment");
- }
-}
diff --git a/app/src/main/java/com/csl/cs710ademoapp/fragments/AccessSecurityKillFragment.java b/app/src/main/java/com/csl/cs710ademoapp/fragments/AccessSecurityKillFragment.java
deleted file mode 100644
index fe33586..0000000
--- a/app/src/main/java/com/csl/cs710ademoapp/fragments/AccessSecurityKillFragment.java
+++ /dev/null
@@ -1,132 +0,0 @@
-package com.csl.cs710ademoapp.fragments;
-
-import android.os.AsyncTask;
-import android.os.Bundle;
-import android.view.LayoutInflater;
-import android.view.View;
-import android.view.ViewGroup;
-import android.widget.Button;
-import android.widget.EditText;
-import android.widget.Toast;
-
-import com.csl.cs710ademoapp.AccessTask;
-import com.csl.cs710ademoapp.GenericTextWatcher;
-import com.csl.cs710ademoapp.MainActivity;
-import com.csl.cs710ademoapp.R;
-import com.csl.cslibrary4a.NotificationConnector;
-import com.csl.cslibrary4a.ReaderDevice;
-import com.csl.cslibrary4a.RfidReaderChipData;
-
-public class AccessSecurityKillFragment extends CommonFragment {
- private EditText editTextTagID, editTextPassword, editTextAntennaPower;
- private Button button;
-
- private AccessTask accessTask;
-
- @Override
- public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
- super.onCreateView(inflater, container, savedInstanceState, false);
- return inflater.inflate(R.layout.fragment_access_kill, container, false);
- }
-
- @Override
- public void onActivityCreated(Bundle savedInstanceState) {
- super.onActivityCreated(savedInstanceState);
-
- editTextTagID = (EditText) getActivity().findViewById(R.id.accessKillTagID);
- editTextPassword = (EditText) getActivity().findViewById(R.id.accessKillPasswordValue);
- editTextPassword.addTextChangedListener(new GenericTextWatcher(editTextPassword, 8));
- editTextPassword.setText("00000000");
-
- editTextAntennaPower = (EditText) getActivity().findViewById(R.id.accessKillAntennaPower);
- editTextAntennaPower.setText(String.valueOf(300));
-
- button = (Button) getActivity().findViewById(R.id.accessKillButton);
- button.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- if (MainActivity.csLibrary4A.isBleConnected() == false) {
- Toast.makeText(MainActivity.mContext, R.string.toast_ble_not_connected, Toast.LENGTH_SHORT).show();
- return;
- } else if (MainActivity.csLibrary4A.isRfidFailure()) {
- Toast.makeText(MainActivity.mContext, "Rfid is disabled", Toast.LENGTH_SHORT).show();
- return;
- }
- startAccessTask();
- }
- });
-
- ReaderDevice tagSelected = MainActivity.tagSelected;
- if (tagSelected != null) {
- if (tagSelected.getSelected() == true) {
- editTextTagID.setText(tagSelected.getAddress());
- }
- }
- MainActivity.csLibrary4A.setSameCheck(false);
- }
-
- @Override
- public void onResume() {
- super.onResume();
- if (DEBUG) MainActivity.csLibrary4A.appendToLog("AccessSecurityKillFragment().onResume(): userVisibleHint = " + userVisibleHint);
- if (userVisibleHint) {
- setNotificationListener();
- }
- }
-
- @Override
- public void onPause() {
- MainActivity.csLibrary4A.setNotificationListener(null);
- super.onPause();
- }
-
- @Override
- public void onDestroy() {
- MainActivity.csLibrary4A.setNotificationListener(null);
- if (accessTask != null) accessTask.cancel(true);
- super.onDestroy();
- }
-
- boolean userVisibleHint = false;
- @Override
- public void setUserVisibleHint(boolean isVisibleToUser) {
- super.setUserVisibleHint(isVisibleToUser);
- if(getUserVisibleHint()) {
- userVisibleHint = true;
- MainActivity.csLibrary4A.appendToLog("AccessSecurityKillFragment is now VISIBLE");
- setNotificationListener();
- } else {
- userVisibleHint = false;
- MainActivity.csLibrary4A.appendToLog("AccessSecurityKillFragment is now INVISIBLE");
- MainActivity.csLibrary4A.setNotificationListener(null);
- }
- }
-
- public AccessSecurityKillFragment() {
- super("AccessSecurityKillFragment");
- }
-
- void setNotificationListener() {
- MainActivity.csLibrary4A.setNotificationListener(new NotificationConnector.NotificationListener() {
- @Override
- public void onChange() {
- MainActivity.csLibrary4A.appendToLog("TRIGGER key is pressed.");
- if (MainActivity.csLibrary4A.getTriggerButtonStatus()) startAccessTask();
- }
- });
- }
-
- void startAccessTask() {
- if (accessTask != null) if (accessTask.getStatus() == AsyncTask.Status.RUNNING) return;
- boolean invalidRequest = false;
- String strTagID = editTextTagID.getText().toString();
- String strPassword = editTextPassword.getText().toString();
- int powerLevel = Integer.valueOf(editTextAntennaPower.getText().toString());
- accessTask = new AccessTask(button, null, invalidRequest, true,
- strTagID, 1, 32,
- strPassword, powerLevel, RfidReaderChipData.HostCommands.CMD_18K6CKILL,
- 0, 0, true, false,
- null, null, null, null, null);
- accessTask.execute();
- }
-}
diff --git a/app/src/main/java/com/csl/cs710ademoapp/fragments/AccessSecurityLockFragment.java b/app/src/main/java/com/csl/cs710ademoapp/fragments/AccessSecurityLockFragment.java
deleted file mode 100644
index c2a2075..0000000
--- a/app/src/main/java/com/csl/cs710ademoapp/fragments/AccessSecurityLockFragment.java
+++ /dev/null
@@ -1,197 +0,0 @@
-package com.csl.cs710ademoapp.fragments;
-
-import android.os.AsyncTask;
-import android.os.Bundle;
-import android.view.LayoutInflater;
-import android.view.View;
-import android.view.ViewGroup;
-import android.widget.ArrayAdapter;
-import android.widget.Button;
-import android.widget.CheckBox;
-import android.widget.EditText;
-import android.widget.Spinner;
-import android.widget.Toast;
-
-import com.csl.cs710ademoapp.AccessTask;
-import com.csl.cs710ademoapp.GenericTextWatcher;
-import com.csl.cs710ademoapp.MainActivity;
-import com.csl.cs710ademoapp.R;
-import com.csl.cslibrary4a.NotificationConnector;
-import com.csl.cslibrary4a.ReaderDevice;
-import com.csl.cslibrary4a.RfidReaderChipData;
-
-public class AccessSecurityLockFragment extends CommonFragment {
- private EditText editTextTagID, editTextPassword, editTextAntennaPower;
- private CheckBox checkBox;
- private Spinner spinner4KillPwd, spinner4AccessPwd, spinner4EpcMemory, spinner4TidMemory, spinner4UserMemory;
- private Button button;
-
- private AccessTask accessTask;
-
- @Override
- public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
- super.onCreateView(inflater, container, savedInstanceState, false);
- return inflater.inflate(R.layout.fragment_access_lock, container, false);
- }
-
- @Override
- public void onActivityCreated(Bundle savedInstanceState) {
- super.onActivityCreated(savedInstanceState);
-
- editTextTagID = (EditText) getActivity().findViewById(R.id.accessLockTagID);
- editTextPassword = (EditText) getActivity().findViewById(R.id.accessLockPasswordValue);
- editTextPassword.addTextChangedListener(new GenericTextWatcher(editTextPassword, 8));
- editTextPassword.setText("00000000");
-
- checkBox = (CheckBox) getActivity().findViewById(R.id.accessLockAllPermLock);
-
- ArrayAdapter arrayAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.access_lock_privilege_array, R.layout.custom_spinner_layout);
- arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
-
- spinner4KillPwd = (Spinner) getActivity().findViewById(R.id.accessLockPrivilege4KillPwd);
- spinner4KillPwd.setAdapter(arrayAdapter);
-
- spinner4AccessPwd = (Spinner) getActivity().findViewById(R.id.accessLockPrivilege4AccessPwd);
- spinner4AccessPwd.setAdapter(arrayAdapter);
-
- spinner4EpcMemory = (Spinner) getActivity().findViewById(R.id.accessLockPrivilege4EpcMemory);
- spinner4EpcMemory.setAdapter(arrayAdapter);
-
- spinner4TidMemory = (Spinner) getActivity().findViewById(R.id.accessLockPrivilege4TidMemory);
- spinner4TidMemory.setAdapter(arrayAdapter);
-
- spinner4UserMemory = (Spinner) getActivity().findViewById(R.id.accessLockPrivilege4UserMemory);
- spinner4UserMemory.setAdapter(arrayAdapter);
-
- editTextAntennaPower = (EditText) getActivity().findViewById(R.id.accessLockAntennaPower);
- editTextAntennaPower.setText(String.valueOf(300));
-
- button = (Button) getActivity().findViewById(R.id.accessLockButton);
- button.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- if (MainActivity.csLibrary4A.isBleConnected() == false) {
- Toast.makeText(MainActivity.mContext, R.string.toast_ble_not_connected, Toast.LENGTH_SHORT).show();
- return;
- } else if (MainActivity.csLibrary4A.isRfidFailure()) {
- Toast.makeText(MainActivity.mContext, "Rfid is disabled", Toast.LENGTH_SHORT).show();
- return;
- }
- startAccessTask();
- }
- });
-
- ReaderDevice tagSelected = MainActivity.tagSelected;
- if (tagSelected != null) {
- if (tagSelected.getSelected() == true) {
- editTextTagID.setText(tagSelected.getAddress());
- }
- }
- MainActivity.csLibrary4A.setSameCheck(false);
- }
-
- @Override
- public void onResume() {
- super.onResume();
- if (DEBUG) MainActivity.csLibrary4A.appendToLog("AccessSecurityLockFragment().onResume(): userVisibleHint = " + userVisibleHint);
- if (userVisibleHint) {
- setNotificationListener();
- }
- }
-
- @Override
- public void onPause() {
- MainActivity.csLibrary4A.setNotificationListener(null);
- super.onPause();
- }
-
- @Override
- public void onDestroy() {
- MainActivity.csLibrary4A.setNotificationListener(null);
- if (accessTask != null) accessTask.cancel(true);
- super.onDestroy();
- }
-
- boolean userVisibleHint = false;
- @Override
- public void setUserVisibleHint(boolean isVisibleToUser) {
- super.setUserVisibleHint(isVisibleToUser);
- if(getUserVisibleHint()) {
- userVisibleHint = true;
- MainActivity.csLibrary4A.appendToLog("AccessSecurityLockFragment is now VISIBLE");
- setNotificationListener();
- } else {
- userVisibleHint = false;
- MainActivity.csLibrary4A.appendToLog("AccessSecurityLockFragment is now INVISIBLE");
- MainActivity.csLibrary4A.setNotificationListener(null);
- }
- }
-
- public AccessSecurityLockFragment() {
- super("AccessSecurityLockFragment");
- }
-
- void setNotificationListener() {
- MainActivity.csLibrary4A.setNotificationListener(new NotificationConnector.NotificationListener() {
- @Override
- public void onChange() {
- MainActivity.csLibrary4A.appendToLog("TRIGGER key is pressed.");
- if (MainActivity.csLibrary4A.getTriggerButtonStatus()) startAccessTask();
- }
- });
- }
-
- void startAccessTask() {
- int accessLockAction = 0;
- int accessLockMask = 0;
- int lockAction;
-
- if (accessTask != null) if (accessTask.getStatus() == AsyncTask.Status.RUNNING) return;
- if (checkBox.isChecked()) {
- accessLockAction = 0x3FF;
- accessLockMask = 0x3FF;
- } else {
- if (DEBUG) MainActivity.csLibrary4A.appendToLog("accessLockAction = " + String.format("%x", accessLockAction) + ", accessLockMask = " + String.format("%x", accessLockMask));
- lockAction = spinner4KillPwd.getSelectedItemPosition();
- accessLockAction |= ((lockAction == 0 ? 0 : lockAction - 1) << 8);
- accessLockMask |= ((lockAction == 0 ? 0 : 3) << 8);
- if (DEBUG) MainActivity.csLibrary4A.appendToLog("Kill: accessLockAction = " + String.format("%x", accessLockAction) + ", accessLockMask = " + String.format("%x", accessLockMask));
-
- lockAction = spinner4AccessPwd.getSelectedItemPosition();
- accessLockAction |= ((lockAction == 0 ? 0 : lockAction - 1) << 6);
- accessLockMask |= ((lockAction == 0 ? 0 : 3) << 6);
- if (DEBUG) MainActivity.csLibrary4A.appendToLog("Access: accessLockAction = " + String.format("%x", accessLockAction) + ", accessLockMask = " + String.format("%x", accessLockMask));
-
- lockAction = spinner4EpcMemory.getSelectedItemPosition();
- accessLockAction |= ((lockAction == 0 ? 0 : lockAction - 1) << 4);
- accessLockMask |= ((lockAction == 0 ? 0 : 3) << 4);
- if (DEBUG) MainActivity.csLibrary4A.appendToLog("Epc: accessLockAction = " + String.format("%x", accessLockAction) + ", accessLockMask = " + String.format("%x", accessLockMask));
-
- lockAction = spinner4TidMemory.getSelectedItemPosition();
- accessLockAction |= ((lockAction == 0 ? 0 : lockAction - 1) << 2);
- accessLockMask |= ((lockAction == 0 ? 0 : 3) << 2);
- if (DEBUG) MainActivity.csLibrary4A.appendToLog("Tid: accessLockAction = " + String.format("%x", accessLockAction) + ", accessLockMask = " + String.format("%x", accessLockMask));
-
- lockAction = spinner4UserMemory.getSelectedItemPosition();
- accessLockAction |= (lockAction == 0 ? 0 : lockAction - 1);
- accessLockMask |= (lockAction == 0 ? 0 : 3);
- if (DEBUG) MainActivity.csLibrary4A.appendToLog("Uesr: accessLockAction = " + String.format("%x", accessLockAction) + ", accessLockMask = " + String.format("%x", accessLockMask));
- }
-
- boolean invalidRequest = false;
- String strTagID = editTextTagID.getText().toString();
- String strPassword = editTextPassword.getText().toString();
- int powerLevel = Integer.valueOf(editTextAntennaPower.getText().toString());
- if (invalidRequest == false) {
- if (MainActivity.csLibrary4A.setAccessLockAction(accessLockAction, accessLockMask) == false) {
- invalidRequest = true;
- }
- }
- accessTask = new AccessTask(button, null, invalidRequest, true,
- strTagID, 1, 32,
- strPassword, powerLevel, RfidReaderChipData.HostCommands.CMD_18K6CLOCK,
- 0, 0, true, false,
- null, null, null, null, null);
- accessTask.execute();
- }
-}
diff --git a/app/src/main/java/com/csl/cs710ademoapp/fragments/HomeFragment.java b/app/src/main/java/com/csl/cs710ademoapp/fragments/HomeFragment.java
index 559d647..67cd693 100644
--- a/app/src/main/java/com/csl/cs710ademoapp/fragments/HomeFragment.java
+++ b/app/src/main/java/com/csl/cs710ademoapp/fragments/HomeFragment.java
@@ -71,12 +71,6 @@ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle sa
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
- if (true && ((AppCompatActivity) getActivity()).getSupportActionBar() != null) {
- ActionBar actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
- actionBar.setIcon(android.R.drawable.ic_menu_save);
- if (getActivity().getPackageName().contains("cs710ademoapp")) actionBar.setTitle(R.string.title_activity_home_cs710);
- else actionBar.setTitle(R.string.title_activity_home_cs108);
- }
if (true) {
String strForegroundReader = MainActivity.csLibrary4A.getForegroundReader();
MainActivity.csLibrary4A.appendToLog("strForegroundReader = " + strForegroundReader + ", getForegroundServiceEnable = " + MainActivity.csLibrary4A.getForegroundServiceEnable());
diff --git a/app/src/main/java/com/csl/cs710ademoapp/fragments/HomeSpecialFragment.java b/app/src/main/java/com/csl/cs710ademoapp/fragments/HomeSpecialFragment.java
deleted file mode 100644
index 3bf1cef..0000000
--- a/app/src/main/java/com/csl/cs710ademoapp/fragments/HomeSpecialFragment.java
+++ /dev/null
@@ -1,46 +0,0 @@
-package com.csl.cs710ademoapp.fragments;
-
-import android.os.Bundle;
-import android.view.LayoutInflater;
-import android.view.View;
-import android.view.ViewGroup;
-import android.widget.Button;
-
-import androidx.appcompat.app.ActionBar;
-import androidx.appcompat.app.AppCompatActivity;
-
-import com.csl.cs710ademoapp.MainActivity;
-import com.csl.cs710ademoapp.R;
-
-public class HomeSpecialFragment extends CommonFragment {
- final boolean DEBUG = false;
- @Override
- public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
- super.onCreateView(inflater, container, savedInstanceState, true);
- return inflater.inflate(R.layout.home_special_layout, container, false);
- }
-
- @Override
- public void onActivityCreated(Bundle savedInstanceState) {
- super.onActivityCreated(savedInstanceState);
-
- if (((AppCompatActivity) getActivity()).getSupportActionBar() != null) {
- ActionBar actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
- actionBar.setTitle(R.string.title_activity_special);
- }
-
- Button buttonAuraSense = (Button) getActivity().findViewById(R.id.SpecialButtonAurasense);
- Button buttonFdmicro = (Button) getActivity().findViewById(R.id.SpecialButtonFdmicro);
- Button buttonLanda = (Button) getActivity().findViewById(R.id.SpecialButtonLanda);
- if (MainActivity.csLibrary4A.get98XX() == 2) {
- buttonAuraSense.setVisibility(View.GONE);
- buttonFdmicro.setVisibility(View.GONE); buttonLanda.setVisibility(View.GONE);
- }
- MainActivity.tagType = null; MainActivity.mDid = null;
- if (MainActivity.csLibrary4A.isBleConnected()) MainActivity.csLibrary4A.restoreAfterTagSelect();
- }
-
- public HomeSpecialFragment() {
- super("HomeSpecialFragment");
- }
-}
diff --git a/app/src/main/java/com/csl/cs710ademoapp/fragments/SettingFilterFragment.java b/app/src/main/java/com/csl/cs710ademoapp/fragments/SettingFilterFragment.java
deleted file mode 100644
index dda5f54..0000000
--- a/app/src/main/java/com/csl/cs710ademoapp/fragments/SettingFilterFragment.java
+++ /dev/null
@@ -1,108 +0,0 @@
-package com.csl.cs710ademoapp.fragments;
-
-import android.os.Bundle;
-import android.util.Log;
-import android.view.LayoutInflater;
-import android.view.View;
-import android.view.ViewGroup;
-
-import androidx.appcompat.app.ActionBar;
-import androidx.appcompat.app.AppCompatActivity;
-import androidx.viewpager.widget.ViewPager;
-
-import com.csl.cs710ademoapp.R;
-import com.csl.cslibrary4a.AdapterTab;
-import com.google.android.material.tabs.TabLayout;
-
-public class SettingFilterFragment extends CommonFragment {
- private ActionBar actionBar;
- private ViewPager viewPager;
- AdapterTab adapter;
-
- private String[] tabs = {"Pre-filter", "Post-filter", "Rssi-filter"};
-
- @Override
- public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
- super.onCreateView(inflater, container, savedInstanceState, true);
- return inflater.inflate(R.layout.custom_tabbed_layout, container, false);
- }
-
- @Override
- public void onActivityCreated(Bundle savedInstanceState) {
- super.onActivityCreated(savedInstanceState);
-
- actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
- actionBar.setIcon(R.drawable.dl_filters);
- actionBar.setTitle(R.string.title_activity_filters);
-
- TabLayout tabLayout = (TabLayout) getActivity().findViewById(R.id.OperationsTabLayout);
-
- adapter = new AdapterTab(getActivity().getSupportFragmentManager(), tabs.length);
- adapter.setFragment(0, new SettingFilterPreFragment());
- adapter.setFragment(1, new SettingFilterPostFragment());
- adapter.setFragment(2, new SettingFilterRssiFragment());
-
- viewPager = (ViewPager) getActivity().findViewById(R.id.OperationsPager);
- viewPager.setAdapter(adapter);
- viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
-
- for (String tab_name : tabs) {
- tabLayout.addTab(tabLayout.newTab().setText(tab_name));
- }
-
- tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
- @Override
- public void onTabSelected(TabLayout.Tab tab) {
- Log.i(TAG, "tab.position is " + tab.getPosition());
- viewPager.setCurrentItem(tab.getPosition());
- }
-
- @Override
- public void onTabUnselected(TabLayout.Tab tab) {
- }
-
- @Override
- public void onTabReselected(TabLayout.Tab tab) {
- }
- });
- }
-
- @Override
- public void onPause() {
- adapter.fragment0.onPause();
- adapter.fragment1.onPause();
- super.onPause();
- }
-
- @Override
- public void onStop() {
- adapter.fragment0.onStop();
- adapter.fragment1.onStop();
- super.onStop();
- }
-
- @Override
- public void onDestroyView() {
- adapter.fragment0.onDestroyView();
- adapter.fragment1.onDestroyView();
- super.onDestroyView();
- }
-
- @Override
- public void onDestroy() {
- adapter.fragment0.onDestroy();
- adapter.fragment1.onDestroy();
- super.onDestroy();
- }
-
- @Override
- public void onDetach() {
- adapter.fragment0.onDetach();
- adapter.fragment1.onDetach();
- super.onDetach();
- }
-
- public SettingFilterFragment() {
- super("SettingFilterFragment");
- }
-}
\ No newline at end of file
diff --git a/app/src/main/java/com/csl/cs710ademoapp/fragments/SettingFilterPostFragment.java b/app/src/main/java/com/csl/cs710ademoapp/fragments/SettingFilterPostFragment.java
deleted file mode 100644
index 282aad9..0000000
--- a/app/src/main/java/com/csl/cs710ademoapp/fragments/SettingFilterPostFragment.java
+++ /dev/null
@@ -1,149 +0,0 @@
-package com.csl.cs710ademoapp.fragments;
-
-import android.os.Bundle;
-import android.os.Handler;
-import android.view.LayoutInflater;
-import android.view.View;
-import android.view.ViewGroup;
-import android.widget.Button;
-import android.widget.CheckBox;
-import android.widget.EditText;
-import android.widget.Toast;
-
-import com.csl.cs710ademoapp.MainActivity;
-import com.csl.cs710ademoapp.R;
-import com.csl.cs710ademoapp.SettingTask;
-
-public class SettingFilterPostFragment extends CommonFragment {
- private CheckBox checkBoxEnable;
- private CheckBox checkBoxType;
- private EditText postFilterOffset;
- private EditText filterPostMaskData;
- private Button button;
-
- final boolean sameCheck = false;
- Handler mHandler = new Handler();
-
- boolean invMatchEnable;
- boolean invMatchType;
- int invMatchOffset = -1;
- String invMatchData = null;
-
- private SettingTask settingTask;
-
- @Override
- public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
- super.onCreateView(inflater, container, savedInstanceState, false);
- return inflater.inflate(R.layout.fragment_filterpost_content, container, false);
- }
-
- @Override
- public void onActivityCreated(Bundle savedInstanceState) {
- super.onActivityCreated(savedInstanceState);
-
- checkBoxEnable = (CheckBox) getActivity().findViewById(R.id.filterPostCheckEnable);
- checkBoxType = (CheckBox) getActivity().findViewById(R.id.filterPostCheckType);
- postFilterOffset = (EditText) getActivity().findViewById(R.id.filterPostOffset);
- filterPostMaskData = (EditText) getActivity().findViewById(R.id.filterPostMaskData);
-
- button = (Button) getActivity().findViewById(R.id.filterPostSaveButton);
- button.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- boolean validValue = false;
- if (MainActivity.csLibrary4A.isBleConnected() == false) {
- Toast.makeText(MainActivity.mContext, R.string.toast_ble_not_connected, Toast.LENGTH_SHORT).show();
- return;
- } else if (MainActivity.csLibrary4A.isRfidFailure()) {
- Toast.makeText(MainActivity.mContext, "Rfid is disabled", Toast.LENGTH_SHORT).show();
- return;
- } else {
- try {
- invMatchEnable = checkBoxEnable.isChecked();
- invMatchType = checkBoxType.isChecked();
- invMatchOffset = Integer.parseInt(postFilterOffset.getText().toString());
-
- settingUpdate();
- } catch (Exception ex) {
- Toast.makeText(MainActivity.mContext, R.string.toast_invalid_range, Toast.LENGTH_SHORT).show();
- }
- }
- }
- });
-
- if (sameCheck == false) MainActivity.csLibrary4A.setSameCheck(false);
- mHandler.post(updateRunnable);
- }
-
- @Override
- public void onDestroy() {
- if (settingTask != null) settingTask.cancel(true);
- MainActivity.csLibrary4A.setSameCheck(true);
- mHandler.removeCallbacks(updateRunnable);
- super.onDestroy();
- }
-
- public SettingFilterPostFragment() {
- super("SettingFilterPostFragment");
- }
-
- private final Runnable updateRunnable = new Runnable() {
- @Override
- public void run() {
- int iValue;
- long lValue;
- boolean updating = false;
-
- if (MainActivity.csLibrary4A.mrfidToWriteSize() != 0) updating = true;
- else {
- if (updating == false) {
- checkBoxEnable.setChecked(MainActivity.csLibrary4A.getInvMatchEnable());
- checkBoxType.setChecked(MainActivity.csLibrary4A.getInvMatchType());
- }
- if (updating == false) {
- int iValue1 = MainActivity.csLibrary4A.getInvMatchOffset();
- if (iValue1 < 0) {
- updating = true;
- } else {
- postFilterOffset.setText(String.valueOf(iValue1));
- }
- }
- if (updating == false && filterPostMaskData.getText().length() == 0) {
- String strValue = MainActivity.csLibrary4A.getInvMatchData();
- if (strValue == null) {
- updating = true;
- } else {
- filterPostMaskData.setText(strValue);
- }
- }
- }
- if (updating) {
- mHandler.postDelayed(updateRunnable, 1000);
- }
- }
- };
-
- void settingUpdate() {
- boolean dataMatched = false;
- invMatchData = filterPostMaskData.getText().toString();
- String strValue = MainActivity.csLibrary4A.getInvMatchData();
- boolean sameSetting = true;
- boolean invalidRequest = false;
-
- if (invMatchData.length() != strValue.length()) {
- dataMatched = false;
- } else if (invMatchData.length() == 0 && strValue.length() == 0) {
- dataMatched = true;
- } else dataMatched = invMatchData.matches(strValue);
- if (MainActivity.csLibrary4A.getInvMatchEnable() != invMatchEnable
- || MainActivity.csLibrary4A.getInvMatchType() != invMatchType
- || MainActivity.csLibrary4A.getInvMatchOffset() != invMatchOffset
- || dataMatched == false || sameCheck == false) {
- sameSetting = false;
- if (MainActivity.csLibrary4A.setPostMatchCriteria(invMatchEnable, invMatchType, invMatchOffset, invMatchData) == false)
- invalidRequest = true;
- }
- settingTask = new SettingTask(button, sameSetting, invalidRequest);
- settingTask.execute();
- }
-}
diff --git a/app/src/main/java/com/csl/cs710ademoapp/fragments/SettingFilterPreFragment.java b/app/src/main/java/com/csl/cs710ademoapp/fragments/SettingFilterPreFragment.java
deleted file mode 100644
index 6159035..0000000
--- a/app/src/main/java/com/csl/cs710ademoapp/fragments/SettingFilterPreFragment.java
+++ /dev/null
@@ -1,273 +0,0 @@
-package com.csl.cs710ademoapp.fragments;
-
-import android.os.Bundle;
-import android.os.Handler;
-import android.view.LayoutInflater;
-import android.view.View;
-import android.view.ViewGroup;
-import android.widget.AdapterView;
-import android.widget.ArrayAdapter;
-import android.widget.Button;
-import android.widget.CheckBox;
-import android.widget.EditText;
-import android.widget.Spinner;
-import android.widget.Toast;
-
-import com.csl.cs710ademoapp.MainActivity;
-import com.csl.cs710ademoapp.R;
-import com.csl.cs710ademoapp.SettingTask;
-
-public class SettingFilterPreFragment extends CommonFragment {
- private EditText editTextFilterPreSelectIndex;
- private CheckBox checkBoxEnable;
- private Spinner targetSpinner;
- private Spinner actionSpinner;
- private Spinner memoryBankSpinner;
- private Spinner spinnerMaskDataType;
- private EditText preFilterOffset;
- private EditText filterPreMaskDataHex, filterPreMaskDataBit;
- private Button button;
-
- final boolean sameCheck = false;
- Handler mHandler = new Handler();
-
- int invSelectIndex = -1;
- boolean invSelectEnable;
- int invSelectTarget = -1;
- int invSelectAction = -1;
- int invSelectMaskBank = -1;
- int invSelectMaskOffset = -1;
- String invSelectMaskData = null;
-
- private SettingTask settingTask;
-
- @Override
- public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
- super.onCreateView(inflater, container, savedInstanceState, false);
- return inflater.inflate(R.layout.fragment_filterpre_content, container, false);
- }
-
- @Override
- public void onActivityCreated(Bundle savedInstanceState) {
- super.onActivityCreated(savedInstanceState);
-
- editTextFilterPreSelectIndex = (EditText) getActivity().findViewById(R.id.filterPreSelectxIndex);
- checkBoxEnable = (CheckBox) getActivity().findViewById(R.id.filterPreCheck);
-
- targetSpinner = (Spinner) getActivity().findViewById(R.id.preFilterTarget);
- ArrayAdapter targetAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.filterPre_target_options, R.layout.custom_spinner_layout);
- targetAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
- targetSpinner.setAdapter(targetAdapter);
- if (false) targetSpinner.setEnabled(false);
-
- actionSpinner = (Spinner) getActivity().findViewById(R.id.preFilterAction);
- ArrayAdapter actionAdapter;
- if (true) { //MainActivity.csLibrary4A.getQuerySelect() >= 2) {
- actionAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.filterPre_SLaction_options, R.layout.custom_spinner_layout);
- } else {
- actionAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.filterPre_SessionAction_options, R.layout.custom_spinner_layout);
- }
- actionAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
- actionSpinner.setAdapter(actionAdapter);
- if (false) actionSpinner.setEnabled(false);
-
- memoryBankSpinner = (Spinner) getActivity().findViewById(R.id.preFilterMemoryBank);
- ArrayAdapter memoryBankAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.read_memoryBank_options, R.layout.custom_spinner_layout);
- memoryBankAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
- memoryBankSpinner.setAdapter(memoryBankAdapter);
- memoryBankSpinner.setEnabled(true);
-
- spinnerMaskDataType = (Spinner) getActivity().findViewById(R.id.filterPreMaskDataType);
- ArrayAdapter maskDataTypeAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.dataType_options, R.layout.custom_spinner_layout);
- maskDataTypeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
- spinnerMaskDataType.setAdapter(maskDataTypeAdapter);
- spinnerMaskDataType.setEnabled(true);
- spinnerMaskDataType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
- @Override
- public void onItemSelected(AdapterView> adapterView, View view, int i, long l) {
- if (spinnerMaskDataType.getSelectedItemPosition() == 0) {
- filterPreMaskDataHex.setVisibility(View.VISIBLE);
- filterPreMaskDataBit.setVisibility(View.GONE);
- } else {
- filterPreMaskDataHex.setVisibility(View.GONE);
- filterPreMaskDataBit.setVisibility(View.VISIBLE);
- }
- }
- @Override
- public void onNothingSelected(AdapterView> adapterView) {
- }
- });
-
- preFilterOffset = (EditText) getActivity().findViewById(R.id.filterPreOffset);
- filterPreMaskDataHex = (EditText) getActivity().findViewById(R.id.filterPreMaskDataHex);
- filterPreMaskDataBit = (EditText) getActivity().findViewById(R.id.filterPreMaskDataBit);
-
- button = (Button) getActivity().findViewById(R.id.filterPreSaveButton);
- button.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- boolean validValue = false;
- if (MainActivity.csLibrary4A.isBleConnected() == false) {
- Toast.makeText(MainActivity.mContext, R.string.toast_ble_not_connected, Toast.LENGTH_SHORT).show();
- return;
- } else if (MainActivity.csLibrary4A.isRfidFailure()) {
- Toast.makeText(MainActivity.mContext, "Rfid is disabled", Toast.LENGTH_SHORT).show();
- return;
- } else {
- try {
- invSelectIndex = Integer.parseInt(editTextFilterPreSelectIndex.getText().toString());
- invSelectEnable = checkBoxEnable.isChecked();
- invSelectTarget = targetSpinner.getSelectedItemPosition();
- invSelectAction = actionSpinner.getSelectedItemPosition();
- invSelectMaskBank = memoryBankSpinner.getSelectedItemPosition() + 1;
- invSelectMaskOffset = Integer.parseInt(preFilterOffset.getText().toString()); if (invSelectMaskBank == 1) invSelectMaskOffset += 32;
-
- settingUpdate();
- } catch (Exception ex) {
- Toast.makeText(MainActivity.mContext, R.string.toast_invalid_range, Toast.LENGTH_SHORT).show();
- }
- }
- }
- });
-
- if (sameCheck == false) MainActivity.csLibrary4A.setSameCheck(false);
- mHandler.post(updateRunnable);
- }
-
- @Override
- public void onDestroy() {
- if (settingTask != null) settingTask.cancel(true);
- MainActivity.csLibrary4A.setSameCheck(true);
- mHandler.removeCallbacks(updateRunnable);
- super.onDestroy();
- }
-
- public SettingFilterPreFragment() {
- super("SettingFilterPreFragment");
- }
-
- private final Runnable updateRunnable = new Runnable() {
- @Override
- public void run() {
- int iValue;
- long lValue;
- boolean updating = false;
-
- if (MainActivity.csLibrary4A.mrfidToWriteSize() != 0) updating = true;
- else {
- if (updating == false && editTextFilterPreSelectIndex.getText().length() == 0) {
- lValue = MainActivity.csLibrary4A.getInvSelectIndex();
- MainActivity.csLibrary4A.appendToLog("updateRunnable getInvSelectIndex = " + lValue);
- if (lValue < 0) {
- updating = true;
- } else {
- editTextFilterPreSelectIndex.setText(String.valueOf(lValue));
- }
- }
- if (updating == false) {
- boolean bValue = MainActivity.csLibrary4A.getSelectEnable();
- MainActivity.csLibrary4A.appendToLog("updateRunnable getSelectEnable = " + bValue);
- checkBoxEnable.setChecked(bValue);
- }
- if (updating == false) {
- int iValue1 = MainActivity.csLibrary4A.getSelectTarget();
- MainActivity.csLibrary4A.appendToLog("updateRunnable getSelectTarget = " + iValue1);
- if (iValue1 < 0) {
- updating = true;
- } else {
- if (iValue1 > 4) iValue1 = 4;
- iValue1 = 4; //fixed as SL
- targetSpinner.setSelection(iValue1);
- }
- }
- if (updating == false) {
- int iValue1 = MainActivity.csLibrary4A.getSelectAction();
- MainActivity.csLibrary4A.appendToLog("updateRunnable getSelectAction = " + iValue1);
- if (iValue1 < 0) {
- updating = true;
- } else {
- actionSpinner.setSelection(iValue1);
- }
- }
- if (updating == false) {
- int iValue1 = MainActivity.csLibrary4A.getSelectMaskBank();
- MainActivity.csLibrary4A.appendToLog("updateRunnable getSelectMaskBank = " + iValue1);
- if (iValue1 < 0) {
- updating = true;
- } else {
- if (iValue1 < 1) iValue1 = 1;
- iValue1--;
- memoryBankSpinner.setSelection(iValue1);
- }
- }
- if (updating == false) {
- int iValue1 = MainActivity.csLibrary4A.getSelectMaskOffset();
- MainActivity.csLibrary4A.appendToLog("updateRunnable getSelectMaskOffset = " + iValue1);
- if (iValue1 < 0) {
- updating = true;
- } else {
- if (iValue1 < 32) iValue1 = 32;
- iValue1 -= 32;
- preFilterOffset.setText(String.valueOf(iValue1));
- }
- }
- if (updating == false) {
- String strValue = MainActivity.csLibrary4A.getSelectMaskData();
- MainActivity.csLibrary4A.appendToLog("updateRunnable getSelectMaskData = " + strValue);
- if (strValue == null) {
- updating = true;
- } else {
- spinnerMaskDataType.setSelection(0);
- filterPreMaskDataHex.setText(strValue);
- }
- }
- }
- if (updating) {
- mHandler.postDelayed(updateRunnable, 1000);
- }
- }
- };
-
- void settingUpdate() {
- boolean sameSetting = true;
- boolean invalidRequest = false;
-
- if (MainActivity.csLibrary4A.getInvSelectIndex() != invSelectIndex) {
- sameSetting = false;
- if (MainActivity.csLibrary4A.setInvSelectIndex(invSelectIndex) == false)
- invalidRequest = true;
- else {
- mHandler.removeCallbacks(updateRunnable);
- mHandler.post(updateRunnable);
- }
- }
- if (sameSetting == true && invalidRequest == false) {
- if (true)
- {
- boolean dataMatched = false;
- boolean maskbit = (spinnerMaskDataType.getSelectedItemPosition() == 0 ? false : true);
- if (maskbit) invSelectMaskData = filterPreMaskDataBit.getText().toString();
- else invSelectMaskData = filterPreMaskDataHex.getText().toString();
- String strValue = MainActivity.csLibrary4A.getSelectMaskData();
- if (invSelectMaskData.length() != strValue.length()) { }
- else if (invSelectMaskData.length() == 0 && strValue.length() == 0) { dataMatched = true; }
- else dataMatched = invSelectMaskData.matches(strValue);
- if (MainActivity.csLibrary4A.getSelectEnable() != invSelectEnable
- || MainActivity.csLibrary4A.getSelectTarget() != invSelectTarget
- || MainActivity.csLibrary4A.getSelectAction() != invSelectAction
- || MainActivity.csLibrary4A.getSelectMaskBank() != invSelectMaskBank
- || MainActivity.csLibrary4A.getSelectMaskOffset() != invSelectMaskOffset
- || dataMatched == false || sameCheck == false) {
- sameSetting = false;
- if (MainActivity.csLibrary4A.setSelectCriteria(0, invSelectEnable, invSelectTarget, invSelectAction, invSelectMaskBank, invSelectMaskOffset, invSelectMaskData, maskbit) == false)
- invalidRequest = true;
- }
- }
- }
-
- settingTask = new SettingTask(button, sameSetting, invalidRequest);
- settingTask.execute();
- MainActivity.csLibrary4A.saveSetting2File();
- }
-}
-
diff --git a/app/src/main/java/com/csl/cs710ademoapp/fragments/SettingFilterRssiFragment.java b/app/src/main/java/com/csl/cs710ademoapp/fragments/SettingFilterRssiFragment.java
deleted file mode 100644
index 8c2afd2..0000000
--- a/app/src/main/java/com/csl/cs710ademoapp/fragments/SettingFilterRssiFragment.java
+++ /dev/null
@@ -1,202 +0,0 @@
-package com.csl.cs710ademoapp.fragments;
-
-import android.os.Bundle;
-import android.os.Handler;
-import android.view.LayoutInflater;
-import android.view.View;
-import android.view.ViewGroup;
-import android.widget.ArrayAdapter;
-import android.widget.Button;
-import android.widget.CheckBox;
-import android.widget.EditText;
-import android.widget.Spinner;
-import android.widget.TextView;
-import android.widget.Toast;
-
-import com.csl.cs710ademoapp.MainActivity;
-import com.csl.cs710ademoapp.R;
-import com.csl.cs710ademoapp.SettingTask;
-
-public class SettingFilterRssiFragment extends CommonFragment {
- private CheckBox checkBoxEnable;
- private Spinner spinnerFilterType, spinnerFilterOption;
- private EditText editTextFilterThreshold1, editTextFilterThreshold2, editTextFilterCount;
- private Button button;
-
- final boolean sameCheck = false;
- Handler mHandler = new Handler();
-
- boolean invSelectEnable;
- int invSelectFilterType = -1, invSelectFilterOption = -1;
- double invSelectFilterThreshold1 = -1, invSelectFilterThreshold2 = -1;
- long invSelectFilterCount = -1;
-
- private SettingTask settingTask;
-
- @Override
- public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
- super.onCreateView(inflater, container, savedInstanceState, false);
- return inflater.inflate(R.layout.fragment_filterrssi_content, container, false);
- }
-
- @Override
- public void onActivityCreated(Bundle savedInstanceState) {
- super.onActivityCreated(savedInstanceState);
-
- checkBoxEnable = (CheckBox) getActivity().findViewById(R.id.filterRssiCheck);
-
- spinnerFilterType = (Spinner) getActivity().findViewById(R.id.filterRssiFilterType);
- ArrayAdapter filterTypeAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.filterType_options, R.layout.custom_spinner_layout);
- filterTypeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
- spinnerFilterType.setAdapter(filterTypeAdapter);
- spinnerFilterType.setEnabled(false);
-
- spinnerFilterOption = (Spinner) getActivity().findViewById(R.id.filterRssiFilterOption);
- ArrayAdapter filterOptionAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.filter_options1, R.layout.custom_spinner_layout);
- filterOptionAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
- spinnerFilterOption.setAdapter(filterOptionAdapter);
-
- String strUnit = MainActivity.csLibrary4A.getRssiDisplaySetting() > 0 ? "(dBm)" : "(dBuV)";
- TextView textViewThreshold1 = (TextView) getActivity().findViewById(R.id.filterRssiThreshold1Label);
- textViewThreshold1.setText(textViewThreshold1.getText().toString() + strUnit);
- TextView textViewThreshold2 = (TextView) getActivity().findViewById(R.id.filterRssiThreshold2Label);
- textViewThreshold2.setText(textViewThreshold2.getText().toString() + strUnit);
-
- editTextFilterThreshold1 = (EditText) getActivity().findViewById(R.id.filterRssiThreshold1);
- editTextFilterThreshold2 = (EditText) getActivity().findViewById(R.id.filterRssiThreshold2);
- editTextFilterCount = (EditText) getActivity().findViewById(R.id.filterRssiCount);
-
- button = (Button) getActivity().findViewById(R.id.filterRssiSaveButton);
- button.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- boolean validValue = false;
- if (MainActivity.csLibrary4A.isBleConnected() == false) {
- Toast.makeText(MainActivity.mContext, R.string.toast_ble_not_connected, Toast.LENGTH_SHORT).show();
- return;
- } else if (MainActivity.csLibrary4A.isRfidFailure()) {
- Toast.makeText(MainActivity.mContext, "Rfid is disabled", Toast.LENGTH_SHORT).show();
- return;
- } else {
- boolean bValid = false;
- try {
- invSelectEnable = checkBoxEnable.isChecked();
- invSelectFilterType = spinnerFilterType.getSelectedItemPosition();
- invSelectFilterOption = spinnerFilterOption.getSelectedItemPosition();
- invSelectFilterThreshold1 = Float.parseFloat(editTextFilterThreshold1.getText().toString());
- if (MainActivity.csLibrary4A.getRssiDisplaySetting() > 0) invSelectFilterThreshold1 += MainActivity.csLibrary4A.dBuV_dBm_constant;
- invSelectFilterThreshold2 = Float.parseFloat(editTextFilterThreshold2.getText().toString());
- if (MainActivity.csLibrary4A.getRssiDisplaySetting() > 0) invSelectFilterThreshold2 += MainActivity.csLibrary4A.dBuV_dBm_constant;
- invSelectFilterCount = Integer.parseInt(editTextFilterCount.getText().toString());
- bValid = true;
- } catch (Exception ex) {
- Toast.makeText(MainActivity.mContext, R.string.toast_invalid_range, Toast.LENGTH_SHORT).show();
- }
- if (bValid) settingUpdate();
- }
- }
- });
-
- if (sameCheck == false) MainActivity.csLibrary4A.setSameCheck(false);
- mHandler.post(updateRunnable);
- }
-
- @Override
- public void onDestroy() {
- if (settingTask != null) settingTask.cancel(true);
- MainActivity.csLibrary4A.setSameCheck(true);
- mHandler.removeCallbacks(updateRunnable);
- super.onDestroy();
- }
-
- public SettingFilterRssiFragment() {
- super("SettingFilterRssiFragment");
- }
-
- private final Runnable updateRunnable = new Runnable() {
- @Override
- public void run() {
- int iValue;
- long lValue;
- String updating = null;
-
- if (MainActivity.csLibrary4A.mrfidToWriteSize() != 0) updating = "waiting empty buffer";
- else {
- if (updating == null) {
- boolean bValue = MainActivity.csLibrary4A.getRssiFilterEnable();
- MainActivity.csLibrary4A.appendToLog("0 updateRunnable getSelectEnable = " + bValue);
- checkBoxEnable.setChecked(bValue);
- }
- if (updating == null) {
- int iValue1 = MainActivity.csLibrary4A.getRssiFilterType();
- MainActivity.csLibrary4A.appendToLog("1 updateRunnable getSelectAction = " + iValue1);
- if (iValue1 < 0) updating = "getting filter type";
- else spinnerFilterType.setSelection(iValue1);
- }
- if (updating == null) {
- int iValue1 = MainActivity.csLibrary4A.getRssiFilterOption();
- MainActivity.csLibrary4A.appendToLog("2 updateRunnable getSelectAction = " + iValue1);
- if (iValue1 < 0) updating = "getting filter option";
- else spinnerFilterOption.setSelection(iValue1);
- }
- if (updating == null) {
- double dValue = MainActivity.csLibrary4A.getRssiFilterThreshold1();
- MainActivity.csLibrary4A.appendToLog(String.format("3 updateRunnable getRssiFilterThreshold1 = %f", dValue));
- if (dValue < 0 && false) updating = "updating threshold 1";
- else editTextFilterThreshold1.setText(String.format("%.1f", (MainActivity.csLibrary4A.getRssiDisplaySetting() > 0 ? dValue -= MainActivity.csLibrary4A.dBuV_dBm_constant : dValue)));
- }
- if (updating == null) {
- double dValue = MainActivity.csLibrary4A.getRssiFilterThreshold2();
- MainActivity.csLibrary4A.appendToLog(String.format("4 updateRunnable getRssiFilterThreshold2 = %f", dValue));
- if (dValue < 0 && false) updating = "updating threshold 2";
- else editTextFilterThreshold2.setText(String.format("%.1f", (MainActivity.csLibrary4A.getRssiDisplaySetting() > 0 ? dValue -= MainActivity.csLibrary4A.dBuV_dBm_constant : dValue)));
- }
- if (updating == null) {
- long lValue1 = MainActivity.csLibrary4A.getRssiFilterCount();
- MainActivity.csLibrary4A.appendToLog(String.format("5 updateRunnable getRssiFilterCount = %d", lValue1));
- if (lValue1 < 0) updating = "updating count";
- else editTextFilterCount.setText(String.valueOf(lValue1));
- }
- }
- if (updating != null) {
- mHandler.postDelayed(updateRunnable, 1000);
- MainActivity.csLibrary4A.appendToLogView("Updating in " + updating);
- }
- }
- };
-
- void settingUpdate() {
- boolean sameSetting = true;
- String invalidRequest = null;
-
- if (sameSetting == true && invalidRequest == null) {
- if (MainActivity.csLibrary4A.getRssiFilterEnable() != invSelectEnable
- || MainActivity.csLibrary4A.getRssiFilterType() != invSelectFilterType
- || MainActivity.csLibrary4A.getRssiFilterOption() != invSelectFilterOption) {
- sameSetting = false;
- if (MainActivity.csLibrary4A.setRssiFilterConfig(invSelectEnable, invSelectFilterType, invSelectFilterOption) == false) invalidRequest = "setting filter type";
- }
- if (MainActivity.csLibrary4A.getRssiFilterThreshold1() != invSelectFilterThreshold1 || MainActivity.csLibrary4A.getRssiFilterThreshold2() != invSelectFilterThreshold2) {
- sameSetting = false;
- MainActivity.csLibrary4A.appendToLog(String.format("updateRunnable: getRssiFilterThreshold2 = %f, invSelectFilterThreshold2 = %f", MainActivity.csLibrary4A.getRssiFilterThreshold2(), invSelectFilterThreshold2));
- invSelectFilterThreshold2 = 0;
- if (MainActivity.csLibrary4A.setRssiFilterThreshold(invSelectFilterThreshold1, invSelectFilterThreshold2) == false) invalidRequest = "setting filter threshold";
- }
- if (MainActivity.csLibrary4A.getRssiFilterCount() != invSelectFilterCount) {
- sameSetting = false;
- MainActivity.csLibrary4A.appendToLog("rssiFilterCount = " + invSelectFilterCount);
- if (MainActivity.csLibrary4A.setRssiFilterCount(invSelectFilterCount) == false) invalidRequest = "setting filter count";
- }
- }
-
- if (invalidRequest != null) {
- String strValue = "Invalid " + invalidRequest + ". Operation is cancelled.";
- Toast.makeText(MainActivity.mContext, strValue, Toast.LENGTH_SHORT).show();
-
- } else {
- settingTask = new SettingTask(button, sameSetting, false);
- settingTask.execute();
- MainActivity.csLibrary4A.saveSetting2File();
- }
- }
-}
\ No newline at end of file
diff --git a/app/src/main/res/drawable/icon_bgfree.png b/app/src/main/res/drawable/icon_bgfree.png
new file mode 100644
index 0000000..c9b8518
Binary files /dev/null and b/app/src/main/res/drawable/icon_bgfree.png differ
diff --git a/app/src/main/res/layout/fragment_access_kill.xml b/app/src/main/res/layout/fragment_access_kill.xml
deleted file mode 100644
index ee3d54d..0000000
--- a/app/src/main/res/layout/fragment_access_kill.xml
+++ /dev/null
@@ -1,69 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/app/src/main/res/layout/fragment_access_lock.xml b/app/src/main/res/layout/fragment_access_lock.xml
deleted file mode 100644
index fe7e6a5..0000000
--- a/app/src/main/res/layout/fragment_access_lock.xml
+++ /dev/null
@@ -1,177 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/app/src/main/res/layout/fragment_access_readwrite.xml b/app/src/main/res/layout/fragment_access_readwrite.xml
deleted file mode 100644
index eca71c4..0000000
--- a/app/src/main/res/layout/fragment_access_readwrite.xml
+++ /dev/null
@@ -1,375 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/app/src/main/res/layout/fragment_access_register.xml b/app/src/main/res/layout/fragment_access_register.xml
deleted file mode 100644
index ec554eb..0000000
--- a/app/src/main/res/layout/fragment_access_register.xml
+++ /dev/null
@@ -1,459 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/app/src/main/res/layout/fragment_filterpost_content.xml b/app/src/main/res/layout/fragment_filterpost_content.xml
deleted file mode 100644
index c8e1bdf..0000000
--- a/app/src/main/res/layout/fragment_filterpost_content.xml
+++ /dev/null
@@ -1,106 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/app/src/main/res/layout/fragment_filterpre_content.xml b/app/src/main/res/layout/fragment_filterpre_content.xml
deleted file mode 100644
index da9e15b..0000000
--- a/app/src/main/res/layout/fragment_filterpre_content.xml
+++ /dev/null
@@ -1,183 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/app/src/main/res/layout/fragment_filterrssi_content.xml b/app/src/main/res/layout/fragment_filterrssi_content.xml
deleted file mode 100644
index b4d3d35..0000000
--- a/app/src/main/res/layout/fragment_filterrssi_content.xml
+++ /dev/null
@@ -1,150 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/app/src/main/res/layout/fragment_specials.xml b/app/src/main/res/layout/fragment_specials.xml
deleted file mode 100644
index 8f2c65a..0000000
--- a/app/src/main/res/layout/fragment_specials.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/app/src/main/res/layout/home_layout710.xml b/app/src/main/res/layout/home_layout710.xml
index a59d584..3a905dd 100644
--- a/app/src/main/res/layout/home_layout710.xml
+++ b/app/src/main/res/layout/home_layout710.xml
@@ -5,6 +5,42 @@
android:layout_height="match_parent"
android:orientation="vertical">
+
+
+
+
+
+
+
+
+
+
+ android:src="@drawable/inventory"
+ android:onClick="invClicked" />
+ android:text="@string/home_inventory710" />
+ android:src="@drawable/search"
+ android:onClick="locateClicked" />
+ android:text="@string/home_locate710" />
@@ -72,8 +108,8 @@
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="40dp"
- android:src="@drawable/register"
- android:onClick="regClicked" />
+ android:src="@drawable/settings"
+ android:onClick="settClicked" />
+ android:text="@string/home_settings710" />
+ android:layout_height="match_parent">
-
-
-
+
+
+
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
\ No newline at end of file
diff --git a/app/src/main/res/values/dimens.xml b/app/src/main/res/values/dimens.xml
index f45015a..1f7446d 100644
--- a/app/src/main/res/values/dimens.xml
+++ b/app/src/main/res/values/dimens.xml
@@ -27,5 +27,6 @@
5dp
2dp
4dp
+ 8dp
diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml
index 133a036..c5251a1 100644
--- a/app/src/main/res/values/strings.xml
+++ b/app/src/main/res/values/strings.xml
@@ -12,7 +12,7 @@
CSL Wedge
- CSL Java
+ Java Reader
Convergence Systems
Special Functions
@@ -465,18 +465,13 @@
Settings
Geiger Search
Filters
- Connect
+ Press to Scan/Connect Reader
Security
Special Functions
- Read/Write\n
Inventory\n
- Register Tag\n
- Settings\n
+ Configuration\n
Geiger Search\n
- Filters\n
- Security\n
- Special Functions\n
Longjing EL-N2ESL\nCS6861
EL-N2ESL CS6861
diff --git a/app/src/main/res/values/styles.xml b/app/src/main/res/values/styles.xml
index 7eea584..db1fc4c 100644
--- a/app/src/main/res/values/styles.xml
+++ b/app/src/main/res/values/styles.xml
@@ -136,9 +136,9 @@
- 2dp
- ?android:attr/textAppearance
- bold
- - @dimen/dashboard_textSize
- - #222222
- - @color/colorPrimary
+ - 60px
+ - #FF0405
+ - #fff
diff --git a/prompts.md b/prompts.md
new file mode 100644
index 0000000..c5e4307
--- /dev/null
+++ b/prompts.md
@@ -0,0 +1,49 @@
+It needs adaptation for Java/Android context (e.g., Fragments/AsyncTasks vs. ViewModels/XAML; MainActivity.java vs. BleMvxApplication.cs). Here's the updated prompts.md:
+
+```markdown
+## Overview
+This file contains prompt templates for use with large language models (LLMs) like Grok, ChatGPT, or Claude to analyze, prune, or optimize large codebases, such as this Java Android RFID reader app. These prompts ensure *methodical* traversal ("prospecting"), dependency tracing, safety (error-free builds), and structured chat log outputs (file trees with emojis/notes). Copy/paste into LLM chats, replacing placeholders (e.g., [FEATURE_NAME]) with specifics.
+
+## Prompt Templates
+
+### 1. Initial Big-Picture Pruning Plan
+**Prompt**:
+Given this large Java Android codebase (~3M+ chars from `repomix-output.txt`), prune deprecated features while keeping core ones (Inventory, Access, Configuration, Connect, Voltage Display). Pruned: [LIST_PRUNED_FEATURES].
+Provide a big-picture plan: Analyze the entire repository structure, map preserved vs. pruned features based on UI diffs (e.g., old/new fragment XMLs like fragment_inventory.xml), and trace dependencies recursively (primary: direct files; secondary: navigation/callbacks/bindings; tertiary: shared code/events/platform-specific; quaternary+: resources/tests/docs/edge cases like intents/permissions).
+Highlight risks: Intertwined events (e.g., global RFID callbacks in MainActivity.java or CsLibrary4A.java), shared utilities (e.g., in Utility.java/SharedObjects.java), custom views (e.g., in adapters/fragments), resources (strings.xml/styles.xml/images), code comments, unit tests, analytics/logging, and config files (build.gradle).
+Suggest order of removal (e.g., isolated fragments first). Ensure 100% build safety with incremental steps: Backups (git branches), global searches ("Find in Files" for feature names/strings), verifications (rebuilds via Gradle, runtime tests on Android emulator/device, log checks for errors/warnings, preserved feature testing). Output: Overview with analysis/comprehension, then high-level per-feature steps with tools (e.g., Android Studio "Find Usages", git commits).
+
+---
+**Usage**: Initiates a pruning session by outlining the strategy for removing deprecated features. Use to understand the codebase and plan safe modifications, proactively addressing common risks and gaps from layered dependencies.
+
+### 2. Feature-Specific Pruning Instructions
+**Prompt**:
+Prune [FEATURE_NAME] from the codebase. Use the `repomix-output.txt` structure for a comprehensive file tree traversal.
+Output a file tree with full paths:
+- ❌ for changes (deletes/edits).
+- ✅ for untouched.
+- [NOTE] for details: What to cut (line-by-line/code blocks with examples), why (e.g., prevents compile/runtime errors from deleted refs, avoids global callback leaks), verify (e.g., rebuild—no errors; run app—test preserved features like Inventory for regressions).
+Cover all levels exhaustively:
+- Primary (direct files/folders, e.g., app/src/main/java/com/csl/cs710ademoapp/fragments/[FEATURE_NAME]Fragment.java).
+- Secondary (navigation/callbacks/bindings, e.g., in MainActivity.java or fragment managers; XML references across layouts).
+- Tertiary (shared code/events/platform-specific, e.g., global event handlers in MainActivity.java, shared utilities in cslibrary4a/, custom adapters/views in app/src/main/).
+- Quaternary+ (resources like strings.xml/styles.xml/images; tests in src/test/; docs/comments via global searches; edge cases like intent stacks/permissions, analytics/logging, config files).
+Use global searches ("Find in Files" case-insensitive for [FEATURE_NAME], callbacks, fragments) for strays. Proactively check common gaps: Stray XML bindings, navigation history/intent stacks, global events (e.g., RFID callbacks in AccessTask.java with feature-specific logic), shared utils/constants, platform services/connectors, resources (strings.xml/styles.xml/images/drawable), code comments/inline docs, unit tests/mocks, analytics (e.g., logging feature events), configs (e.g., toggles in build.gradle). Ensure no regressions in preserved features. End with summary, potential issues, and commit suggestion (e.g., "git commit -m 'Pruned [FEATURE_NAME]: Removed files/refs. Verified builds.'").
+
+---
+**Usage**: Core template for pruning a specific feature (e.g., "Access Read/Write"). Ensures granular, safe removal with full dependency cleanup, now with explicit proactive gap checks for exhaustive coverage.
+
+### 3. Refining Pruning Output
+**Prompt**:
+Review my previous pruning instructions for [FEATURE_NAME]. Check depth exhaustively: Did we cover primary/secondary/tertiary/quaternary+? Identify additional gaps like: Stray XML references across layouts, navigation history/intent stacks (e.g., in MainActivity.java or fragment transactions), global event handlers (e.g., RFID callbacks with feature-specific conditions in MainActivity.java or tasks), shared utilities/constants (e.g., in Utility.java/SharedObjects.java), platform-specific connectors/services (e.g., in BluetoothConnector.java), resources (strings.xml, styles in values/, images/drawable), code comments/inline docs (global search for feature names), unit tests/mocks (e.g., in src/test/), analytics/logging (e.g., feature-specific events in logs), configuration files (e.g., toggles in build.gradle).
+Refine: Add missed steps (e.g., global searches for feature strings in comments/resources, module build.gradle edits, edge case tests like intents/permissions). Output updated instructions in file tree format with ❌/✅ and [NOTE] prefixes (what/why/verify). Ensure 100% build safety with emphasis on post-prune testing (rebuilds via Gradle, runtime on Android emulator/device, preserved feature verification, logs for warnings/errors).
+
+**Usage**: Iterates on prior outputs to address gaps or refine instructions, ensuring exhaustive coverage with expanded common gap examples drawn from hands-on experience.
+
+---
+## Tips for Using These Prompts
+- **Context Inclusion**: Always prepend full repo structure (e.g., `repomix-output.txt`) and feature lists (preserved/pruned) for accuracy.
+- **Iteration**: If output needs tweaks, follow up with specifics (e.g., "Add more on edge cases like analytics/logging").
+- **LLM Choice**: Use Grok for reasoning/large contexts, Claude for structured Markdown, or ChatGPT for quick iterations.
+- **Safety**: Backup before applying changes (e.g., `git branch prune-`); test preserved features post-prune.
+```
\ No newline at end of file
diff --git a/repomix-instruction.md b/repomix-instruction.md
new file mode 100644
index 0000000..cc87180
--- /dev/null
+++ b/repomix-instruction.md
@@ -0,0 +1,107 @@
+# Repomix Instructions — CS710S Android (Java)
+
+**Goal**
+Produce a single packed context for AI agents to analyze BLE and RFID flows in the CS710S handheld reader app on Android (Java + Gradle), excluding build artifacts, binaries, and noise. Ensure the full output is generated without truncation.
+
+---
+
+## What to Include (Priority Order)
+1) Build & Modules
+- `build.gradle`
+- `settings.gradle`
+- `app/build.gradle`
+- `cslibrary4a/build.gradle`
+- `epctagcoder/build.gradle`
+
+2) Core Library (RFID + HAL + Tools)
+- `cslibrary4a/src/main/java/com/csl/cslibrary4a/*.java`
+ - RFID Unified API: `Cs108Library4A.java`, `Cs710Library4A.java`, `CsLibrary4A.java` (Host commands, inventory/access ops; CS710S focus)
+ - Comm Protocol: `RfidReaderChipData.java`, `RfidReaderChipR2000.java`, `RfidReaderChipE710.java`
+ - HAL BLE: `BluetoothConnector.java`, `BluetoothGatt.java`, `RfidConnector.java`
+ - Utilities: `Utility.java`, `AesCmac.java`, `DeviceFinder.java`
+
+3) Android App (UI + Tasks)
+- `app/src/main/java/com/csl/cs710ademoapp/*.java` (Main logic, fragments, tasks)
+- `app/src/main/java/com/csl/cs710ademoapp/fragments/*.java` (e.g., InventoryFragment.java, AccessReadWriteFragment.java)
+- `app/src/main/java/com/csl/cs710ademoapp/adapters/*.java`
+- `app/src/main/AndroidManifest.xml`
+- `app/src/main/res/values/*.xml`
+- `app/src/main/res/layout/*.xml`
+
+4) EPC Tag Coder
+- `epctagcoder/src/main/java/org/epctagcoder/*.java` (Parse/encode EPC schemes: SGTIN, SSCC, etc.)
+- `epctagcoder/src/main/java/org/epctagcoder/option/*.java`
+- `epctagcoder/src/main/java/org/epctagcoder/parse/*.java`
+- `epctagcoder/src/main/java/org/epctagcoder/result/*.java`
+
+5) Docs / Metadata
+- `README.md`
+- `repomix-instructions.md`
+- `repomix-config.json` (For Repomix self-reference)
+
+---
+
+## Exclude (Noise & Generated)
+- Build & IDE: `**/build/**`, `**/.gradle/**`, `.idea/**`, `.vscode/**`
+- Packages & Dependencies: `**/*.jar`, `**/*.aar`
+- Generated: `**/R.java`, `**/*.class`
+- Binaries/Archives: `**/*.dll`, `**/*.so`, `**/*.a`, `**/*.nupkg`, `**/*.keystore`, `**/*.apk`, `**/*.aab`, `**/*.zip`
+- Images/Misc: `**/*.png`, `**/*.jpg`, `**/*.gif`, `**/*.pdf`
+- Local Config: `**/*.iml`, `local.properties`, `**/*.user`
+
+---
+
+## Logical Read Order (for AI Prospecting)
+Guide AI agents in "prospecting" interconnected paths:
+1) `settings.gradle` → Module dependencies.
+2) App Entry: `app/src/main/java/com/csl/cs710ademoapp/MainActivity.java` (App bootstrap, NFC/USB intents).
+3) Fragments/UI: `app/src/main/java/com/csl/cs710ademoapp/fragments/*.java` (e.g., InventoryFragment.java, ConnectionFragment.java for BLE scanning).
+4) BLE HAL: `cslibrary4a/src/main/java/com/csl/cslibrary4a/BluetoothConnector.java`, `RfidConnector.java` (Device discovery, GATT via Android BLE).
+5) RFID Unified API (CS710S Focus): `cslibrary4a/src/main/java/com/csl/cslibrary4a/Cs710Library4A.java`, `RfidReaderChipE710.java` (Public ops: inventory/read/write/antenna/power—trace to chip-specific layers).
+6) Comm Protocol: `cslibrary4a/src/main/java/com/csl/cslibrary4a/Rx000Commands` (via RfidReaderChipData.HostCommands).
+7) Tasks/Utilities: `app/src/main/java/com/csl/cs710ademoapp/AccessTask.java`, `InventoryRfidTask.java`; `epctagcoder/src/main/java/org/epctagcoder/parse/*.java`.
+
+This order reflects app flow: Android bootstrap → Fragment navigation → BLE connect/scan → RFID operations. Emphasize tracing dependencies (e.g., how MainActivity invokes library ops in AsyncTasks).
+
+---
+
+## Summarization Hints (Chunking for AI)
+- Group by Feature: **BLE Connect** (BluetoothConnector + fragments), **Inventory** (InventoryRfidTask.java, RfidReader), **Read/Write** (AccessTask.java, HostCommands), **Antenna/Power** (SettingData.java, powerLevel params), **Tag Filters/QT** (setSelectCriteria), **Errors/Status** (decodedError in Rx000pkgData).
+- Limit chunks to ≤2k tokens; prefix each with file paths.
+- Cross-link public APIs to private implementations (e.g., CsLibrary4A.publicAccess → RfidReaderChipE710).
+- Note response modes (compact/normal/extended) in tag operations via HostCmdResponseTypes.
+- Flag Token-Heavy Files (>1k tokens): `AccessTask.java`, `MainActivity.java`, `CsLibrary4A.java`—suggest splitting in AI analysis.
+
+---
+
+## Important Callouts
+- Android: `MainActivity.java`, `AndroidManifest.xml`, `res/values/strings.xml`.
+- Fragments/Tasks: `InventoryFragment.java`, `AccessReadWriteFragment.java`, `AccessTask.java`.
+- CS710S API: Public (`Cs710Library4A.java`, `RfidReader`), Operations (`RfidReaderChipE710.java` for read/write/inventory/select), Antenna/Power (`SettingData.java`), Protocol (`RfidReaderChipData.HostCommands`).
+- EPC: `epctagcoder/parse/SGTIN/ParseSGTIN.java`, `result/SGTIN.java`.
+- Utilities: `Utility.java`, `Converter.java` (hex/bin conversions).
+
+---
+
+## Output Requirements
+- Single packed file: **Summary → Repo Info → Structure → Files (path + contents)**.
+- Preserve code blocks verbatim; include file headers.
+- Mark **excluded** areas clearly.
+- Note token-heavy files with byte/token counts.
+- Use relative paths from repo root.
+- Style: XML, with file summaries and directory structure.
+- Ensure full output without truncation (support up to 100MB).
+
+---
+
+## Build Context
+- Targets: Android (minSdk 26, targetSdk 36; armeabi-v7a, arm64-v8a, x86_64 for emulators).
+- Key Dependencies: `com.google.android.material:material:1.12.0`, `org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.2.5`.
+- Build: Open in Android Studio → Sync Gradle → Select `app` → Debug/Release → Deploy to device/emulator.
+
+---
+
+## Quality Checks (for AI Post-Packing)
+- Flag BLE timing issues, UI thread handling, and disconnect edges (e.g., in BluetoothGatt, AsyncTask cancellations).
+- Confirm frequency/power settings are configurable (e.g., setAccessPowerLevel).
+- Verify no UI-blocking I/O; check AsyncTask progress in inventory/reads (e.g., AccessTask.doInBackground).
\ No newline at end of file
diff --git a/repomix.config.json b/repomix.config.json
new file mode 100644
index 0000000..3d72fc9
--- /dev/null
+++ b/repomix.config.json
@@ -0,0 +1,80 @@
+{
+ "input": {
+ "maxFileSize": 100000000
+ },
+ "output": {
+ "filePath": "CS710S-Java-ENTIRE-CONTEXT.xml",
+ "style": "xml",
+ "parsableStyle": true,
+ "compress": true,
+ "headerText": "Packed CS710S Android codebase for AI analysis of BLE/RFID flows, including Java source, projects, and docs.",
+ "instructionFilePath": "repomix-instruction.md",
+ "fileSummary": true,
+ "directoryStructure": true,
+ "files": true,
+ "removeComments": false,
+ "removeEmptyLines": false,
+ "showLineNumbers": false,
+ "truncateBase64": false,
+ "copyToClipboard": false,
+ "includeEmptyDirectories": false,
+ "topFilesLength": 5,
+ "tokenCountTree": 1000
+ },
+ "include": [
+ "app/src/**",
+ "cslibrary4a/src/main/**",
+ "epctagcoder/src/main/**",
+ "gradle/**",
+ "README.md",
+ "repomix-instruction.md",
+ "repomix.config.json"
+ ],
+ "ignore": {
+ "useGitignore": true,
+ "useDefaultPatterns": true,
+ "customPatterns": [
+ "**/bin/**",
+ "**/obj/**",
+ "**/Debug/**",
+ "**/Release/**",
+ "**/.vs/**",
+ "**/TestResult*/**",
+ "**/node_modules/**",
+ "**/*.dll",
+ "**/*.so",
+ "**/*.a",
+ "**/*.jar",
+ "**/*.aar",
+ "**/*.nupkg",
+ "**/*.keystore",
+ "**/*.apk",
+ "**/*.aab",
+ "**/*.zip",
+ "**/*.png",
+ "**/*.jpg",
+ "**/*.gif",
+ "**/*.pdf",
+ "**/*.user",
+ "**/*.userprefs"
+ ]
+ },
+ "security": {
+ "enableSecurityCheck": false
+ },
+ "tokenCount": {
+ "encoding": "o200k_base"
+ },
+ "git": {
+ "includeLogs": false,
+ "sortByChanges": false,
+ "sortByChangesMaxCommits": 0,
+ "includeDiffs": false,
+ "includeLogsCount": 0
+ },
+ "metadata": {
+ "version": "1.0",
+ "lastUpdated": "2025-08-29",
+ "description": "Configuration for packing CS710S Android codebase for AI analysis."
+ }
+}
\ No newline at end of file