Browse Source

Merge branch 'master' of http://jiecheng2024.tpddns.cn:3000/liyuezong/SmartPDCode

guohui 1 year ago
parent
commit
0dd784bf9d
37 changed files with 4411 additions and 4963 deletions
  1. 51 0
      Qt/Android/SmartPDU_QT/Android/AndroidManifest.xml
  2. 85 0
      Qt/Android/SmartPDU_QT/Android/build.gradle
  3. 18 0
      Qt/Android/SmartPDU_QT/Android/gradle.properties
  4. BIN
      Qt/Android/SmartPDU_QT/Android/gradle/wrapper/gradle-wrapper.jar
  5. 7 0
      Qt/Android/SmartPDU_QT/Android/gradle/wrapper/gradle-wrapper.properties
  6. 252 0
      Qt/Android/SmartPDU_QT/Android/gradlew
  7. 94 0
      Qt/Android/SmartPDU_QT/Android/gradlew.bat
  8. 21 0
      Qt/Android/SmartPDU_QT/Android/res/values/libs.xml
  9. 4 0
      Qt/Android/SmartPDU_QT/Android/res/xml/qtprovider_paths.xml
  10. 0 359
      Qt/Android/SmartPDU_QT/Android/src/com/hoho/android/usbserial/driver/CdcAcmSerialDriver.java
  11. 0 387
      Qt/Android/SmartPDU_QT/Android/src/com/hoho/android/usbserial/driver/Ch34xSerialDriver.java
  12. 0 96
      Qt/Android/SmartPDU_QT/Android/src/com/hoho/android/usbserial/driver/ChromeCcdSerialDriver.java
  13. 0 336
      Qt/Android/SmartPDU_QT/Android/src/com/hoho/android/usbserial/driver/CommonUsbSerialPort.java
  14. 0 335
      Qt/Android/SmartPDU_QT/Android/src/com/hoho/android/usbserial/driver/Cp21xxSerialDriver.java
  15. 0 444
      Qt/Android/SmartPDU_QT/Android/src/com/hoho/android/usbserial/driver/FtdiSerialDriver.java
  16. 0 106
      Qt/Android/SmartPDU_QT/Android/src/com/hoho/android/usbserial/driver/GsmModemSerialDriver.java
  17. 0 102
      Qt/Android/SmartPDU_QT/Android/src/com/hoho/android/usbserial/driver/ProbeTable.java
  18. 0 585
      Qt/Android/SmartPDU_QT/Android/src/com/hoho/android/usbserial/driver/ProlificSerialDriver.java
  19. 0 15
      Qt/Android/SmartPDU_QT/Android/src/com/hoho/android/usbserial/driver/SerialTimeoutException.java
  20. 0 56
      Qt/Android/SmartPDU_QT/Android/src/com/hoho/android/usbserial/driver/UsbId.java
  21. 0 38
      Qt/Android/SmartPDU_QT/Android/src/com/hoho/android/usbserial/driver/UsbSerialDriver.java
  22. 0 284
      Qt/Android/SmartPDU_QT/Android/src/com/hoho/android/usbserial/driver/UsbSerialPort.java
  23. 0 90
      Qt/Android/SmartPDU_QT/Android/src/com/hoho/android/usbserial/driver/UsbSerialProber.java
  24. 0 155
      Qt/Android/SmartPDU_QT/Android/src/com/hoho/android/usbserial/util/HexDump.java
  25. 0 14
      Qt/Android/SmartPDU_QT/Android/src/com/hoho/android/usbserial/util/MonotonicClock.java
  26. 0 261
      Qt/Android/SmartPDU_QT/Android/src/com/hoho/android/usbserial/util/SerialInputOutputManager.java
  27. 0 30
      Qt/Android/SmartPDU_QT/Android/src/com/hoho/android/usbserial/util/UsbUtils.java
  28. 33 7
      Qt/Android/SmartPDU_QT/SmartPDU_QT.pro
  29. 1435 288
      Qt/Android/SmartPDU_QT/SmartPDU_QT.pro.user
  30. 248 256
      Qt/Android/SmartPDU_QT/mainwidget.cpp
  31. 5 14
      Qt/Android/SmartPDU_QT/mainwidget.h
  32. 1706 705
      Qt/Android/SmartPDU_QT/mainwidget.ui
  33. 10 0
      Qt/Android/SmartPDU_QT/pduresource.qrc
  34. BIN
      Qt/Android/SmartPDU_QT/resource/Serial.png
  35. 85 0
      Qt/Android/SmartPDU_QT/widget.cpp
  36. 32 0
      Qt/Android/SmartPDU_QT/widget.h
  37. 325 0
      Qt/Android/SmartPDU_QT/widget.ui

+ 51 - 0
Qt/Android/SmartPDU_QT/Android/AndroidManifest.xml

@@ -0,0 +1,51 @@
+<?xml version="1.0"?>
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="org.qtproject.example"
+    android:installLocation="auto"
+    android:versionCode="-- %%INSERT_VERSION_CODE%% --"
+    android:versionName="-- %%INSERT_VERSION_NAME%% --">
+    <!-- %%INSERT_PERMISSIONS -->
+    <!-- %%INSERT_FEATURES -->
+    <supports-screens
+        android:anyDensity="true"
+        android:largeScreens="true"
+        android:normalScreens="true"
+        android:smallScreens="true" />
+    <application
+        android:name="org.qtproject.qt.android.bindings.QtApplication"
+        android:hardwareAccelerated="true"
+        android:label="-- %%INSERT_APP_NAME%% --"
+        android:requestLegacyExternalStorage="true"
+        android:allowBackup="true"
+        android:fullBackupOnly="false">
+        <activity
+            android:name="org.qtproject.qt.android.bindings.QtActivity"
+            android:configChanges="orientation|uiMode|screenLayout|screenSize|smallestScreenSize|layoutDirection|locale|fontScale|keyboard|keyboardHidden|navigation|mcc|mnc|density"
+            android:launchMode="singleTop"
+            android:screenOrientation="unspecified"
+            android:exported="true">
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+                <category android:name="android.intent.category.LAUNCHER" />
+            </intent-filter>
+
+          <meta-data
+                android:name="android.app.lib_name"
+                android:value="-- %%INSERT_APP_LIB_NAME%% --" />
+
+          <meta-data
+                android:name="android.app.arguments"
+                android:value="-- %%INSERT_APP_ARGUMENTS%% --" />
+        </activity>
+
+        <provider
+            android:name="androidx.core.content.FileProvider"
+            android:authorities="${applicationId}.qtprovider"
+            android:exported="false"
+            android:grantUriPermissions="true">
+            <meta-data
+                android:name="android.support.FILE_PROVIDER_PATHS"
+                android:resource="@xml/qtprovider_paths"/>
+        </provider>
+    </application>
+</manifest>

+ 85 - 0
Qt/Android/SmartPDU_QT/Android/build.gradle

@@ -0,0 +1,85 @@
+buildscript {
+    repositories {
+        google()
+        mavenCentral()
+    }
+
+    dependencies {
+        classpath 'com.android.tools.build:gradle:8.6.0'
+    }
+}
+
+repositories {
+    google()
+    mavenCentral()
+}
+
+apply plugin: qtGradlePluginType
+
+dependencies {
+    implementation fileTree(dir: 'libs', include: ['*.jar', '*.aar'])
+    //noinspection GradleDependency
+    implementation 'androidx.core:core:1.13.1'
+}
+
+android {
+    /*******************************************************
+     * The following variables:
+     * - androidBuildToolsVersion,
+     * - androidCompileSdkVersion
+     * - qtAndroidDir - holds the path to qt android files
+     *                   needed to build any Qt application
+     *                   on Android.
+     * - qtGradlePluginType - whether to build an app or a library
+     *
+     * are defined in gradle.properties file. This file is
+     * updated by QtCreator and androiddeployqt tools.
+     * Changing them manually might break the compilation!
+     *******************************************************/
+
+    namespace androidPackageName
+    compileSdkVersion androidCompileSdkVersion
+    buildToolsVersion androidBuildToolsVersion
+    ndkVersion androidNdkVersion
+
+    // Extract native libraries from the APK
+    packagingOptions.jniLibs.useLegacyPackaging true
+
+    sourceSets {
+        main {
+            manifest.srcFile 'AndroidManifest.xml'
+            java.srcDirs = [qtAndroidDir + '/src', 'src', 'java']
+            aidl.srcDirs = [qtAndroidDir + '/src', 'src', 'aidl']
+            res.srcDirs = [qtAndroidDir + '/res', 'res']
+            resources.srcDirs = ['resources']
+            renderscript.srcDirs = ['src']
+            assets.srcDirs = ['assets']
+            jniLibs.srcDirs = ['libs']
+       }
+    }
+
+    tasks.withType(JavaCompile) {
+        options.incremental = true
+    }
+
+    compileOptions {
+        sourceCompatibility JavaVersion.VERSION_1_8
+        targetCompatibility JavaVersion.VERSION_1_8
+    }
+
+    lintOptions {
+        abortOnError false
+    }
+
+    // Do not compress Qt binary resources file
+    aaptOptions {
+        noCompress 'rcc'
+    }
+
+    defaultConfig {
+        resConfig "en"
+        minSdkVersion qtMinSdkVersion
+        targetSdkVersion qtTargetSdkVersion
+        ndk.abiFilters = qtTargetAbiList.split(",")
+    }
+}

+ 18 - 0
Qt/Android/SmartPDU_QT/Android/gradle.properties

@@ -0,0 +1,18 @@
+# Project-wide Gradle settings.
+# For more details on how to configure your build environment visit
+# http://www.gradle.org/docs/current/userguide/build_environment.html
+# Specifies the JVM arguments used for the daemon process.
+# The setting is particularly useful for tweaking memory settings.
+org.gradle.jvmargs=-Xmx2500m -XX:MaxMetaspaceSize=768m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
+
+# Enable building projects in parallel
+org.gradle.parallel=true
+
+# Gradle caching allows reusing the build artifacts from a previous
+# build with the same inputs. However, over time, the cache size will
+# grow. Uncomment the following line to enable it.
+#org.gradle.caching=true
+#org.gradle.configuration-cache=true
+
+# Allow AndroidX usage
+android.useAndroidX=true

BIN
Qt/Android/SmartPDU_QT/Android/gradle/wrapper/gradle-wrapper.jar


+ 7 - 0
Qt/Android/SmartPDU_QT/Android/gradle/wrapper/gradle-wrapper.properties

@@ -0,0 +1,7 @@
+distributionBase=GRADLE_USER_HOME
+distributionPath=wrapper/dists
+distributionUrl=https\://mirrors.cloud.tencent.com/gradle/gradle-8.10-bin.zip
+networkTimeout=10000
+validateDistributionUrl=true
+zipStoreBase=GRADLE_USER_HOME
+zipStorePath=wrapper/dists

+ 252 - 0
Qt/Android/SmartPDU_QT/Android/gradlew

@@ -0,0 +1,252 @@
+#!/bin/sh
+
+#
+# Copyright © 2015-2021 the original authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      https://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# SPDX-License-Identifier: Apache-2.0
+#
+
+##############################################################################
+#
+#   Gradle start up script for POSIX generated by Gradle.
+#
+#   Important for running:
+#
+#   (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
+#       noncompliant, but you have some other compliant shell such as ksh or
+#       bash, then to run this script, type that shell name before the whole
+#       command line, like:
+#
+#           ksh Gradle
+#
+#       Busybox and similar reduced shells will NOT work, because this script
+#       requires all of these POSIX shell features:
+#         * functions;
+#         * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
+#           «${var#prefix}», «${var%suffix}», and «$( cmd )»;
+#         * compound commands having a testable exit status, especially «case»;
+#         * various built-in commands including «command», «set», and «ulimit».
+#
+#   Important for patching:
+#
+#   (2) This script targets any POSIX shell, so it avoids extensions provided
+#       by Bash, Ksh, etc; in particular arrays are avoided.
+#
+#       The "traditional" practice of packing multiple parameters into a
+#       space-separated string is a well documented source of bugs and security
+#       problems, so this is (mostly) avoided, by progressively accumulating
+#       options in "$@", and eventually passing that to Java.
+#
+#       Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
+#       and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
+#       see the in-line comments for details.
+#
+#       There are tweaks for specific operating systems such as AIX, CygWin,
+#       Darwin, MinGW, and NonStop.
+#
+#   (3) This script is generated from the Groovy template
+#       https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
+#       within the Gradle project.
+#
+#       You can find Gradle at https://github.com/gradle/gradle/.
+#
+##############################################################################
+
+# Attempt to set APP_HOME
+
+# Resolve links: $0 may be a link
+app_path=$0
+
+# Need this for daisy-chained symlinks.
+while
+    APP_HOME=${app_path%"${app_path##*/}"}  # leaves a trailing /; empty if no leading path
+    [ -h "$app_path" ]
+do
+    ls=$( ls -ld "$app_path" )
+    link=${ls#*' -> '}
+    case $link in             #(
+      /*)   app_path=$link ;; #(
+      *)    app_path=$APP_HOME$link ;;
+    esac
+done
+
+# This is normally unused
+# shellcheck disable=SC2034
+APP_BASE_NAME=${0##*/}
+# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
+APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s
+' "$PWD" ) || exit
+
+# Use the maximum available, or set MAX_FD != -1 to use that value.
+MAX_FD=maximum
+
+warn () {
+    echo "$*"
+} >&2
+
+die () {
+    echo
+    echo "$*"
+    echo
+    exit 1
+} >&2
+
+# OS specific support (must be 'true' or 'false').
+cygwin=false
+msys=false
+darwin=false
+nonstop=false
+case "$( uname )" in                #(
+  CYGWIN* )         cygwin=true  ;; #(
+  Darwin* )         darwin=true  ;; #(
+  MSYS* | MINGW* )  msys=true    ;; #(
+  NONSTOP* )        nonstop=true ;;
+esac
+
+CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
+
+
+# Determine the Java command to use to start the JVM.
+if [ -n "$JAVA_HOME" ] ; then
+    if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
+        # IBM's JDK on AIX uses strange locations for the executables
+        JAVACMD=$JAVA_HOME/jre/sh/java
+    else
+        JAVACMD=$JAVA_HOME/bin/java
+    fi
+    if [ ! -x "$JAVACMD" ] ; then
+        die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+    fi
+else
+    JAVACMD=java
+    if ! command -v java >/dev/null 2>&1
+    then
+        die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+    fi
+fi
+
+# Increase the maximum file descriptors if we can.
+if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
+    case $MAX_FD in #(
+      max*)
+        # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
+        # shellcheck disable=SC2039,SC3045
+        MAX_FD=$( ulimit -H -n ) ||
+            warn "Could not query maximum file descriptor limit"
+    esac
+    case $MAX_FD in  #(
+      '' | soft) :;; #(
+      *)
+        # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
+        # shellcheck disable=SC2039,SC3045
+        ulimit -n "$MAX_FD" ||
+            warn "Could not set maximum file descriptor limit to $MAX_FD"
+    esac
+fi
+
+# Collect all arguments for the java command, stacking in reverse order:
+#   * args from the command line
+#   * the main class name
+#   * -classpath
+#   * -D...appname settings
+#   * --module-path (only if needed)
+#   * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
+
+# For Cygwin or MSYS, switch paths to Windows format before running java
+if "$cygwin" || "$msys" ; then
+    APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
+    CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
+
+    JAVACMD=$( cygpath --unix "$JAVACMD" )
+
+    # Now convert the arguments - kludge to limit ourselves to /bin/sh
+    for arg do
+        if
+            case $arg in                                #(
+              -*)   false ;;                            # don't mess with options #(
+              /?*)  t=${arg#/} t=/${t%%/*}              # looks like a POSIX filepath
+                    [ -e "$t" ] ;;                      #(
+              *)    false ;;
+            esac
+        then
+            arg=$( cygpath --path --ignore --mixed "$arg" )
+        fi
+        # Roll the args list around exactly as many times as the number of
+        # args, so each arg winds up back in the position where it started, but
+        # possibly modified.
+        #
+        # NB: a `for` loop captures its iteration list before it begins, so
+        # changing the positional parameters here affects neither the number of
+        # iterations, nor the values presented in `arg`.
+        shift                   # remove old arg
+        set -- "$@" "$arg"      # push replacement arg
+    done
+fi
+
+
+# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+DEFAULT_JVM_OPTS='-Dfile.encoding=UTF-8 "-Xmx64m" "-Xms64m"'
+
+# Collect all arguments for the java command:
+#   * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
+#     and any embedded shellness will be escaped.
+#   * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
+#     treated as '${Hostname}' itself on the command line.
+
+set -- \
+        "-Dorg.gradle.appname=$APP_BASE_NAME" \
+        -classpath "$CLASSPATH" \
+        org.gradle.wrapper.GradleWrapperMain \
+        "$@"
+
+# Stop when "xargs" is not available.
+if ! command -v xargs >/dev/null 2>&1
+then
+    die "xargs is not available"
+fi
+
+# Use "xargs" to parse quoted args.
+#
+# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
+#
+# In Bash we could simply go:
+#
+#   readarray ARGS < <( xargs -n1 <<<"$var" ) &&
+#   set -- "${ARGS[@]}" "$@"
+#
+# but POSIX shell has neither arrays nor command substitution, so instead we
+# post-process each arg (as a line of input to sed) to backslash-escape any
+# character that might be a shell metacharacter, then use eval to reverse
+# that process (while maintaining the separation between arguments), and wrap
+# the whole thing up as a single "set" statement.
+#
+# This will of course break if any of these variables contains a newline or
+# an unmatched quote.
+#
+
+eval "set -- $(
+        printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
+        xargs -n1 |
+        sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
+        tr '\n' ' '
+    )" '"$@"'
+
+exec "$JAVACMD" "$@"

+ 94 - 0
Qt/Android/SmartPDU_QT/Android/gradlew.bat

@@ -0,0 +1,94 @@
+@rem
+@rem Copyright 2015 the original author or authors.
+@rem
+@rem Licensed under the Apache License, Version 2.0 (the "License");
+@rem you may not use this file except in compliance with the License.
+@rem You may obtain a copy of the License at
+@rem
+@rem      https://www.apache.org/licenses/LICENSE-2.0
+@rem
+@rem Unless required by applicable law or agreed to in writing, software
+@rem distributed under the License is distributed on an "AS IS" BASIS,
+@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+@rem See the License for the specific language governing permissions and
+@rem limitations under the License.
+@rem
+@rem SPDX-License-Identifier: Apache-2.0
+@rem
+
+@if "%DEBUG%"=="" @echo off
+@rem ##########################################################################
+@rem
+@rem  Gradle startup script for Windows
+@rem
+@rem ##########################################################################
+
+@rem Set local scope for the variables with windows NT shell
+if "%OS%"=="Windows_NT" setlocal
+
+set DIRNAME=%~dp0
+if "%DIRNAME%"=="" set DIRNAME=.
+@rem This is normally unused
+set APP_BASE_NAME=%~n0
+set APP_HOME=%DIRNAME%
+
+@rem Resolve any "." and ".." in APP_HOME to make it shorter.
+for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
+
+@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+set DEFAULT_JVM_OPTS=-Dfile.encoding=UTF-8 "-Xmx64m" "-Xms64m"
+
+@rem Find java.exe
+if defined JAVA_HOME goto findJavaFromJavaHome
+
+set JAVA_EXE=java.exe
+%JAVA_EXE% -version >NUL 2>&1
+if %ERRORLEVEL% equ 0 goto execute
+
+echo. 1>&2
+echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
+echo. 1>&2
+echo Please set the JAVA_HOME variable in your environment to match the 1>&2
+echo location of your Java installation. 1>&2
+
+goto fail
+
+:findJavaFromJavaHome
+set JAVA_HOME=%JAVA_HOME:"=%
+set JAVA_EXE=%JAVA_HOME%/bin/java.exe
+
+if exist "%JAVA_EXE%" goto execute
+
+echo. 1>&2
+echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
+echo. 1>&2
+echo Please set the JAVA_HOME variable in your environment to match the 1>&2
+echo location of your Java installation. 1>&2
+
+goto fail
+
+:execute
+@rem Setup the command line
+
+set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
+
+
+@rem Execute Gradle
+"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
+
+:end
+@rem End local scope for the variables with windows NT shell
+if %ERRORLEVEL% equ 0 goto mainEnd
+
+:fail
+rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
+rem the _cmd.exe /c_ return code!
+set EXIT_CODE=%ERRORLEVEL%
+if %EXIT_CODE% equ 0 set EXIT_CODE=1
+if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
+exit /b %EXIT_CODE%
+
+:mainEnd
+if "%OS%"=="Windows_NT" endlocal
+
+:omega

+ 21 - 0
Qt/Android/SmartPDU_QT/Android/res/values/libs.xml

@@ -0,0 +1,21 @@
+<?xml version='1.0' encoding='utf-8'?>
+<resources>
+    <!-- DO NOT EDIT THIS: This file is populated automatically by the deployment tool. -->
+
+    <array name="bundled_libs">
+        <!-- %%INSERT_EXTRA_LIBS%% -->
+    </array>
+
+    <array name="qt_libs">
+        <!-- %%INSERT_QT_LIBS%% -->
+    </array>
+
+    <array name="load_local_libs">
+        <!-- %%INSERT_LOCAL_LIBS%% -->
+    </array>
+
+    <string name="static_init_classes"><!-- %%INSERT_INIT_CLASSES%% --></string>
+    <string name="use_local_qt_libs"><!-- %%USE_LOCAL_QT_LIBS%% --></string>
+    <string name="bundle_local_qt_libs"><!-- %%BUNDLE_LOCAL_QT_LIBS%% --></string>
+    <string name="system_libs_prefix"><!-- %%SYSTEM_LIBS_PREFIX%% --></string>
+</resources>

+ 4 - 0
Qt/Android/SmartPDU_QT/Android/res/xml/qtprovider_paths.xml

@@ -0,0 +1,4 @@
+<?xml version="1.0" encoding="utf-8"?>
+<paths xmlns:android="http://schemas.android.com/apk/res/android">
+    <files-path name="files_path" path="/"/>
+</paths>

+ 0 - 359
Qt/Android/SmartPDU_QT/Android/src/com/hoho/android/usbserial/driver/CdcAcmSerialDriver.java

@@ -1,359 +0,0 @@
-/* Copyright 2011-2013 Google Inc.
- * Copyright 2013 mike wakerly <opensource@hoho.com>
- *
- * Project home page: https://github.com/mik3y/usb-serial-for-android
- */
-
-package com.hoho.android.usbserial.driver;
-
-import android.hardware.usb.UsbConstants;
-import android.hardware.usb.UsbDevice;
-import android.hardware.usb.UsbEndpoint;
-import android.hardware.usb.UsbInterface;
-import android.util.Log;
-
-import com.hoho.android.usbserial.util.HexDump;
-import com.hoho.android.usbserial.util.UsbUtils;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.EnumSet;
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.Map;
-
-/**
- * USB CDC/ACM serial driver implementation.
- *
- * @author mike wakerly (opensource@hoho.com)
- * @see <a
- *      href="http://www.usb.org/developers/devclass_docs/usbcdc11.pdf">Universal
- *      Serial Bus Class Definitions for Communication Devices, v1.1</a>
- */
-public class CdcAcmSerialDriver implements UsbSerialDriver {
-
-    public static final int USB_SUBCLASS_ACM = 2;
-
-    private final String TAG = CdcAcmSerialDriver.class.getSimpleName();
-
-    private final UsbDevice mDevice;
-    private final List<UsbSerialPort> mPorts;
-
-    public CdcAcmSerialDriver(UsbDevice device) {
-        mDevice = device;
-        mPorts = new ArrayList<>();
-        int ports = countPorts(device);
-        for (int port = 0; port < ports; port++) {
-            mPorts.add(new CdcAcmSerialPort(mDevice, port));
-        }
-        if (mPorts.size() == 0) {
-            mPorts.add(new CdcAcmSerialPort(mDevice, -1));
-        }
-    }
-
-    @SuppressWarnings({"unused"})
-    public static boolean probe(UsbDevice device) {
-        return countPorts(device) > 0;
-    }
-
-    private static int countPorts(UsbDevice device) {
-        int controlInterfaceCount = 0;
-        int dataInterfaceCount = 0;
-        for (int i = 0; i < device.getInterfaceCount(); i++) {
-            if (device.getInterface(i).getInterfaceClass() == UsbConstants.USB_CLASS_COMM &&
-                    device.getInterface(i).getInterfaceSubclass() == USB_SUBCLASS_ACM)
-                controlInterfaceCount++;
-            if (device.getInterface(i).getInterfaceClass() == UsbConstants.USB_CLASS_CDC_DATA)
-                dataInterfaceCount++;
-        }
-        return Math.min(controlInterfaceCount, dataInterfaceCount);
-    }
-
-    @Override
-    public UsbDevice getDevice() {
-        return mDevice;
-    }
-
-    @Override
-    public List<UsbSerialPort> getPorts() {
-        return mPorts;
-    }
-
-    public class CdcAcmSerialPort extends CommonUsbSerialPort {
-
-        private UsbInterface mControlInterface;
-        private UsbInterface mDataInterface;
-
-        private UsbEndpoint mControlEndpoint;
-
-        private int mControlIndex;
-
-        private boolean mRts = false;
-        private boolean mDtr = false;
-
-        private static final int USB_RECIP_INTERFACE = 0x01;
-        private static final int USB_RT_ACM = UsbConstants.USB_TYPE_CLASS | USB_RECIP_INTERFACE;
-
-        private static final int SET_LINE_CODING = 0x20;  // USB CDC 1.1 section 6.2
-        private static final int GET_LINE_CODING = 0x21;
-        private static final int SET_CONTROL_LINE_STATE = 0x22;
-        private static final int SEND_BREAK = 0x23;
-
-        public CdcAcmSerialPort(UsbDevice device, int portNumber) {
-            super(device, portNumber);
-        }
-
-        @Override
-        public UsbSerialDriver getDriver() {
-            return CdcAcmSerialDriver.this;
-        }
-
-        @Override
-        protected void openInt() throws IOException {
-            Log.d(TAG, "interfaces:");
-            for (int i = 0; i < mDevice.getInterfaceCount(); i++) {
-                Log.d(TAG, mDevice.getInterface(i).toString());
-            }
-            if (mPortNumber == -1) {
-                Log.d(TAG,"device might be castrated ACM device, trying single interface logic");
-                openSingleInterface();
-            } else {
-                Log.d(TAG,"trying default interface logic");
-                openInterface();
-            }
-        }
-
-        private void openSingleInterface() throws IOException {
-            // the following code is inspired by the cdc-acm driver in the linux kernel
-
-            mControlIndex = 0;
-            mControlInterface = mDevice.getInterface(0);
-            mDataInterface = mDevice.getInterface(0);
-            if (!mConnection.claimInterface(mControlInterface, true)) {
-                throw new IOException("Could not claim shared control/data interface");
-            }
-
-            for (int i = 0; i < mControlInterface.getEndpointCount(); ++i) {
-                UsbEndpoint ep = mControlInterface.getEndpoint(i);
-                if ((ep.getDirection() == UsbConstants.USB_DIR_IN) && (ep.getType() == UsbConstants.USB_ENDPOINT_XFER_INT)) {
-                    mControlEndpoint = ep;
-                } else if ((ep.getDirection() == UsbConstants.USB_DIR_IN) && (ep.getType() == UsbConstants.USB_ENDPOINT_XFER_BULK)) {
-                    mReadEndpoint = ep;
-                } else if ((ep.getDirection() == UsbConstants.USB_DIR_OUT) && (ep.getType() == UsbConstants.USB_ENDPOINT_XFER_BULK)) {
-                    mWriteEndpoint = ep;
-                }
-            }
-            if (mControlEndpoint == null) {
-                throw new IOException("No control endpoint");
-            }
-        }
-
-        private void openInterface() throws IOException {
-
-            mControlInterface = null;
-            mDataInterface = null;
-            int j = getInterfaceIdFromDescriptors();
-            Log.d(TAG, "interface count=" + mDevice.getInterfaceCount() + ", IAD=" + j);
-            if (j >= 0) {
-                for (int i = 0; i < mDevice.getInterfaceCount(); i++) {
-                    UsbInterface usbInterface = mDevice.getInterface(i);
-                    if (usbInterface.getId() == j || usbInterface.getId() == j+1) {
-                        if (usbInterface.getInterfaceClass() == UsbConstants.USB_CLASS_COMM &&
-                                usbInterface.getInterfaceSubclass() == USB_SUBCLASS_ACM) {
-                            mControlIndex = usbInterface.getId();
-                            mControlInterface = usbInterface;
-                        }
-                        if (usbInterface.getInterfaceClass() == UsbConstants.USB_CLASS_CDC_DATA) {
-                            mDataInterface = usbInterface;
-                        }
-                    }
-                }
-            }
-            if (mControlInterface == null || mDataInterface == null) {
-                Log.d(TAG, "no IAD fallback");
-                int controlInterfaceCount = 0;
-                int dataInterfaceCount = 0;
-                for (int i = 0; i < mDevice.getInterfaceCount(); i++) {
-                    UsbInterface usbInterface = mDevice.getInterface(i);
-                    if (usbInterface.getInterfaceClass() == UsbConstants.USB_CLASS_COMM &&
-                            usbInterface.getInterfaceSubclass() == USB_SUBCLASS_ACM) {
-                        if (controlInterfaceCount == mPortNumber) {
-                            mControlIndex = usbInterface.getId();
-                            mControlInterface = usbInterface;
-                        }
-                        controlInterfaceCount++;
-                    }
-                    if (usbInterface.getInterfaceClass() == UsbConstants.USB_CLASS_CDC_DATA) {
-                        if (dataInterfaceCount == mPortNumber) {
-                            mDataInterface = usbInterface;
-                        }
-                        dataInterfaceCount++;
-                    }
-                }
-            }
-
-            if(mControlInterface == null) {
-                throw new IOException("No control interface");
-            }
-            Log.d(TAG, "Control interface id " + mControlInterface.getId());
-
-            if (!mConnection.claimInterface(mControlInterface, true)) {
-                throw new IOException("Could not claim control interface");
-            }
-            mControlEndpoint = mControlInterface.getEndpoint(0);
-            if (mControlEndpoint.getDirection() != UsbConstants.USB_DIR_IN || mControlEndpoint.getType() != UsbConstants.USB_ENDPOINT_XFER_INT) {
-                throw new IOException("Invalid control endpoint");
-            }
-
-            if(mDataInterface == null) {
-                throw new IOException("No data interface");
-            }
-            Log.d(TAG, "data interface id " + mDataInterface.getId());
-            if (!mConnection.claimInterface(mDataInterface, true)) {
-                throw new IOException("Could not claim data interface");
-            }
-            for (int i = 0; i < mDataInterface.getEndpointCount(); i++) {
-                UsbEndpoint ep = mDataInterface.getEndpoint(i);
-                if (ep.getDirection() == UsbConstants.USB_DIR_IN && ep.getType() == UsbConstants.USB_ENDPOINT_XFER_BULK)
-                    mReadEndpoint = ep;
-                if (ep.getDirection() == UsbConstants.USB_DIR_OUT && ep.getType() == UsbConstants.USB_ENDPOINT_XFER_BULK)
-                    mWriteEndpoint = ep;
-            }
-        }
-
-        private int getInterfaceIdFromDescriptors() {
-            ArrayList<byte[]> descriptors = UsbUtils.getDescriptors(mConnection);
-            Log.d(TAG, "USB descriptor:");
-            for(byte[] descriptor : descriptors)
-                Log.d(TAG, HexDump.toHexString(descriptor));
-
-            if (descriptors.size() > 0 &&
-                    descriptors.get(0).length == 18 &&
-                    descriptors.get(0)[1] == 1 && // bDescriptorType
-                    descriptors.get(0)[4] == (byte)(UsbConstants.USB_CLASS_MISC) && //bDeviceClass
-                    descriptors.get(0)[5] == 2 && // bDeviceSubClass
-                    descriptors.get(0)[6] == 1) { // bDeviceProtocol
-                // is IAD device, see https://www.usb.org/sites/default/files/iadclasscode_r10.pdf
-                int port = -1;
-                for (int d = 1; d < descriptors.size(); d++) {
-                    if (descriptors.get(d).length == 8 &&
-                            descriptors.get(d)[1] == 0x0b && // bDescriptorType == IAD
-                            descriptors.get(d)[4] == UsbConstants.USB_CLASS_COMM && // bFunctionClass == CDC
-                            descriptors.get(d)[5] == USB_SUBCLASS_ACM) { // bFunctionSubClass == ACM
-                        port++;
-                        if (port == mPortNumber &&
-                                descriptors.get(d)[3] == 2) { // bInterfaceCount
-                            return descriptors.get(d)[2]; // bFirstInterface
-                        }
-                    }
-                }
-            }
-            return -1;
-        }
-
-        private int sendAcmControlMessage(int request, int value, byte[] buf) throws IOException {
-            int len = mConnection.controlTransfer(
-                    USB_RT_ACM, request, value, mControlIndex, buf, buf != null ? buf.length : 0, 5000);
-            if(len < 0) {
-                throw new IOException("controlTransfer failed");
-            }
-            return len;
-        }
-
-        @Override
-        protected void closeInt() {
-            try {
-                mConnection.releaseInterface(mControlInterface);
-                mConnection.releaseInterface(mDataInterface);
-            } catch(Exception ignored) {}
-        }
-
-        @Override
-        public void setParameters(int baudRate, int dataBits, int stopBits, @Parity int parity) throws IOException {
-            if(baudRate <= 0) {
-                throw new IllegalArgumentException("Invalid baud rate: " + baudRate);
-            }
-            if(dataBits < DATABITS_5 || dataBits > DATABITS_8) {
-                throw new IllegalArgumentException("Invalid data bits: " + dataBits);
-            }
-            byte stopBitsByte;
-            switch (stopBits) {
-                case STOPBITS_1: stopBitsByte = 0; break;
-                case STOPBITS_1_5: stopBitsByte = 1; break;
-                case STOPBITS_2: stopBitsByte = 2; break;
-                default: throw new IllegalArgumentException("Invalid stop bits: " + stopBits);
-            }
-
-            byte parityBitesByte;
-            switch (parity) {
-                case PARITY_NONE: parityBitesByte = 0; break;
-                case PARITY_ODD: parityBitesByte = 1; break;
-                case PARITY_EVEN: parityBitesByte = 2; break;
-                case PARITY_MARK: parityBitesByte = 3; break;
-                case PARITY_SPACE: parityBitesByte = 4; break;
-                default: throw new IllegalArgumentException("Invalid parity: " + parity);
-            }
-            byte[] msg = {
-                    (byte) ( baudRate & 0xff),
-                    (byte) ((baudRate >> 8 ) & 0xff),
-                    (byte) ((baudRate >> 16) & 0xff),
-                    (byte) ((baudRate >> 24) & 0xff),
-                    stopBitsByte,
-                    parityBitesByte,
-                    (byte) dataBits};
-            sendAcmControlMessage(SET_LINE_CODING, 0, msg);
-        }
-
-        @Override
-        public boolean getDTR() throws IOException {
-            return mDtr;
-        }
-
-        @Override
-        public void setDTR(boolean value) throws IOException {
-            mDtr = value;
-            setDtrRts();
-        }
-
-        @Override
-        public boolean getRTS() throws IOException {
-            return mRts;
-        }
-
-        @Override
-        public void setRTS(boolean value) throws IOException {
-            mRts = value;
-            setDtrRts();
-        }
-
-        private void setDtrRts() throws IOException {
-            int value = (mRts ? 0x2 : 0) | (mDtr ? 0x1 : 0);
-            sendAcmControlMessage(SET_CONTROL_LINE_STATE, value, null);
-        }
-
-        @Override
-        public EnumSet<ControlLine> getControlLines() throws IOException {
-            EnumSet<ControlLine> set = EnumSet.noneOf(ControlLine.class);
-            if(mRts) set.add(ControlLine.RTS);
-            if(mDtr) set.add(ControlLine.DTR);
-            return set;
-        }
-
-        @Override
-        public EnumSet<ControlLine> getSupportedControlLines() throws IOException {
-            return EnumSet.of(ControlLine.RTS, ControlLine.DTR);
-        }
-
-        @Override
-        public void setBreak(boolean value) throws IOException {
-            sendAcmControlMessage(SEND_BREAK, value ? 0xffff : 0, null);
-        }
-
-    }
-
-    @SuppressWarnings({"unused"})
-    public static Map<Integer, int[]> getSupportedDevices() {
-        return new LinkedHashMap<>();
-    }
-
-}

+ 0 - 387
Qt/Android/SmartPDU_QT/Android/src/com/hoho/android/usbserial/driver/Ch34xSerialDriver.java

@@ -1,387 +0,0 @@
-/* Copyright 2014 Andreas Butti
- *
- * Project home page: https://github.com/mik3y/usb-serial-for-android
- */
-
-package com.hoho.android.usbserial.driver;
-
-import android.hardware.usb.UsbConstants;
-import android.hardware.usb.UsbDevice;
-import android.hardware.usb.UsbEndpoint;
-import android.hardware.usb.UsbInterface;
-import android.util.Log;
-
-import com.hoho.android.usbserial.BuildConfig;
-
-import java.io.IOException;
-import java.util.Collections;
-import java.util.EnumSet;
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.Map;
-
-public class Ch34xSerialDriver implements UsbSerialDriver {
-
-    private static final String TAG = Ch34xSerialDriver.class.getSimpleName();
-
-    private final UsbDevice mDevice;
-    private final UsbSerialPort mPort;
-
-    private static final int LCR_ENABLE_RX   = 0x80;
-    private static final int LCR_ENABLE_TX   = 0x40;
-    private static final int LCR_MARK_SPACE  = 0x20;
-    private static final int LCR_PAR_EVEN    = 0x10;
-    private static final int LCR_ENABLE_PAR  = 0x08;
-    private static final int LCR_STOP_BITS_2 = 0x04;
-    private static final int LCR_CS8         = 0x03;
-    private static final int LCR_CS7         = 0x02;
-    private static final int LCR_CS6         = 0x01;
-    private static final int LCR_CS5         = 0x00;
-
-    private static final int GCL_CTS = 0x01;
-    private static final int GCL_DSR = 0x02;
-    private static final int GCL_RI  = 0x04;
-    private static final int GCL_CD  = 0x08;
-    private static final int SCL_DTR = 0x20;
-    private static final int SCL_RTS = 0x40;
-
-    public Ch34xSerialDriver(UsbDevice device) {
-        mDevice = device;
-        mPort = new Ch340SerialPort(mDevice, 0);
-    }
-
-    @Override
-    public UsbDevice getDevice() {
-        return mDevice;
-    }
-
-    @Override
-    public List<UsbSerialPort> getPorts() {
-        return Collections.singletonList(mPort);
-    }
-
-    public class Ch340SerialPort extends CommonUsbSerialPort {
-
-        private static final int USB_TIMEOUT_MILLIS = 5000;
-
-        private final int DEFAULT_BAUD_RATE = 9600;
-
-        private boolean dtr = false;
-        private boolean rts = false;
-
-        public Ch340SerialPort(UsbDevice device, int portNumber) {
-            super(device, portNumber);
-        }
-
-        @Override
-        public UsbSerialDriver getDriver() {
-            return Ch34xSerialDriver.this;
-        }
-
-        @Override
-        protected void openInt() throws IOException {
-            for (int i = 0; i < mDevice.getInterfaceCount(); i++) {
-                UsbInterface usbIface = mDevice.getInterface(i);
-                if (!mConnection.claimInterface(usbIface, true)) {
-                    throw new IOException("Could not claim data interface");
-                }
-            }
-
-            UsbInterface dataIface = mDevice.getInterface(mDevice.getInterfaceCount() - 1);
-            for (int i = 0; i < dataIface.getEndpointCount(); i++) {
-                UsbEndpoint ep = dataIface.getEndpoint(i);
-                if (ep.getType() == UsbConstants.USB_ENDPOINT_XFER_BULK) {
-                    if (ep.getDirection() == UsbConstants.USB_DIR_IN) {
-                        mReadEndpoint = ep;
-                    } else {
-                        mWriteEndpoint = ep;
-                    }
-                }
-            }
-
-            initialize();
-            setBaudRate(DEFAULT_BAUD_RATE);
-        }
-
-        @Override
-        protected void closeInt() {
-            try {
-                for (int i = 0; i < mDevice.getInterfaceCount(); i++)
-                    mConnection.releaseInterface(mDevice.getInterface(i));
-            } catch(Exception ignored) {}
-        }
-
-        private int controlOut(int request, int value, int index) {
-            final int REQTYPE_HOST_TO_DEVICE = UsbConstants.USB_TYPE_VENDOR | UsbConstants.USB_DIR_OUT;
-            return mConnection.controlTransfer(REQTYPE_HOST_TO_DEVICE, request,
-                    value, index, null, 0, USB_TIMEOUT_MILLIS);
-        }
-
-
-        private int controlIn(int request, int value, int index, byte[] buffer) {
-            final int REQTYPE_DEVICE_TO_HOST = UsbConstants.USB_TYPE_VENDOR | UsbConstants.USB_DIR_IN;
-            return mConnection.controlTransfer(REQTYPE_DEVICE_TO_HOST, request,
-                    value, index, buffer, buffer.length, USB_TIMEOUT_MILLIS);
-        }
-
-
-        private void checkState(String msg, int request, int value, int[] expected) throws IOException {
-            byte[] buffer = new byte[expected.length];
-            int ret = controlIn(request, value, 0, buffer);
-
-            if (ret < 0) {
-                throw new IOException("Failed send cmd [" + msg + "]");
-            }
-
-            if (ret != expected.length) {
-                throw new IOException("Expected " + expected.length + " bytes, but get " + ret + " [" + msg + "]");
-            }
-
-            for (int i = 0; i < expected.length; i++) {
-                if (expected[i] == -1) {
-                    continue;
-                }
-
-                int current = buffer[i] & 0xff;
-                if (expected[i] != current) {
-                    throw new IOException("Expected 0x" + Integer.toHexString(expected[i]) + " byte, but get 0x" + Integer.toHexString(current) + " [" + msg + "]");
-                }
-            }
-        }
-
-        private void setControlLines() throws IOException {
-            if (controlOut(0xa4, ~((dtr ? SCL_DTR : 0) | (rts ? SCL_RTS : 0)), 0) < 0) {
-                throw new IOException("Failed to set control lines");
-            }
-        }
-
-        private byte getStatus() throws IOException {
-            byte[] buffer = new byte[2];
-            int ret = controlIn(0x95, 0x0706, 0, buffer);
-            if (ret < 0)
-                throw new IOException("Error getting control lines");
-            return buffer[0];
-        }
-
-        private void initialize() throws IOException {
-            checkState("init #1", 0x5f, 0, new int[]{-1 /* 0x27, 0x30 */, 0x00});
-
-            if (controlOut(0xa1, 0, 0) < 0) {
-                throw new IOException("Init failed: #2");
-            }
-
-            setBaudRate(DEFAULT_BAUD_RATE);
-
-            checkState("init #4", 0x95, 0x2518, new int[]{-1 /* 0x56, c3*/, 0x00});
-
-            if (controlOut(0x9a, 0x2518, LCR_ENABLE_RX | LCR_ENABLE_TX | LCR_CS8) < 0) {
-                throw new IOException("Init failed: #5");
-            }
-
-            checkState("init #6", 0x95, 0x0706, new int[]{-1/*0xf?*/, -1/*0xec,0xee*/});
-
-            if (controlOut(0xa1, 0x501f, 0xd90a) < 0) {
-                throw new IOException("Init failed: #7");
-            }
-
-            setBaudRate(DEFAULT_BAUD_RATE);
-
-            setControlLines();
-
-            checkState("init #10", 0x95, 0x0706, new int[]{-1/* 0x9f, 0xff*/, -1/*0xec,0xee*/});
-        }
-
-
-        private void setBaudRate(int baudRate) throws IOException {
-            long factor;
-            long divisor;
-
-            if (baudRate == 921600) {
-                divisor = 7;
-                factor = 0xf300;
-            } else {
-                final long BAUDBASE_FACTOR = 1532620800;
-                final int BAUDBASE_DIVMAX = 3;
-
-                if(BuildConfig.DEBUG && (baudRate & (3<<29)) == (1<<29))
-                    baudRate &= ~(1<<29); // for testing purpose bypass dedicated baud rate handling
-                factor = BAUDBASE_FACTOR / baudRate;
-                divisor = BAUDBASE_DIVMAX;
-                while ((factor > 0xfff0) && divisor > 0) {
-                    factor >>= 3;
-                    divisor--;
-                }
-                if (factor > 0xfff0) {
-                    throw new UnsupportedOperationException("Unsupported baud rate: " + baudRate);
-                }
-                factor = 0x10000 - factor;
-            }
-
-            divisor |= 0x0080; // else ch341a waits until buffer full
-            int val1 = (int) ((factor & 0xff00) | divisor);
-            int val2 = (int) (factor & 0xff);
-            Log.d(TAG, String.format("baud rate=%d, 0x1312=0x%04x, 0x0f2c=0x%04x", baudRate, val1, val2));
-            int ret = controlOut(0x9a, 0x1312, val1);
-            if (ret < 0) {
-                throw new IOException("Error setting baud rate: #1)");
-            }
-            ret = controlOut(0x9a, 0x0f2c, val2);
-            if (ret < 0) {
-                throw new IOException("Error setting baud rate: #2");
-            }
-        }
-
-        @Override
-        public void setParameters(int baudRate, int dataBits, int stopBits, @Parity int parity) throws IOException {
-            if(baudRate <= 0) {
-                throw new IllegalArgumentException("Invalid baud rate: " + baudRate);
-            }
-            setBaudRate(baudRate);
-
-            int lcr = LCR_ENABLE_RX | LCR_ENABLE_TX;
-
-            switch (dataBits) {
-                case DATABITS_5:
-                    lcr |= LCR_CS5;
-                    break;
-                case DATABITS_6:
-                    lcr |= LCR_CS6;
-                    break;
-                case DATABITS_7:
-                    lcr |= LCR_CS7;
-                    break;
-                case DATABITS_8:
-                    lcr |= LCR_CS8;
-                    break;
-                default:
-                    throw new IllegalArgumentException("Invalid data bits: " + dataBits);
-            }
-
-            switch (parity) {
-                case PARITY_NONE:
-                    break;
-                case PARITY_ODD:
-                    lcr |= LCR_ENABLE_PAR;
-                    break;
-                case PARITY_EVEN:
-                    lcr |= LCR_ENABLE_PAR | LCR_PAR_EVEN;
-                    break;
-                case PARITY_MARK:
-                    lcr |= LCR_ENABLE_PAR | LCR_MARK_SPACE;
-                    break;
-                case PARITY_SPACE:
-                    lcr |= LCR_ENABLE_PAR | LCR_MARK_SPACE | LCR_PAR_EVEN;
-                    break;
-                default:
-                    throw new IllegalArgumentException("Invalid parity: " + parity);
-            }
-
-            switch (stopBits) {
-                case STOPBITS_1:
-                    break;
-                case STOPBITS_1_5:
-                    throw new UnsupportedOperationException("Unsupported stop bits: 1.5");
-                case STOPBITS_2:
-                    lcr |= LCR_STOP_BITS_2;
-                    break;
-                default:
-                    throw new IllegalArgumentException("Invalid stop bits: " + stopBits);
-            }
-
-            int ret = controlOut(0x9a, 0x2518, lcr);
-            if (ret < 0) {
-                throw new IOException("Error setting control byte");
-            }
-        }
-
-        @Override
-        public boolean getCD() throws IOException {
-            return (getStatus() & GCL_CD) == 0;
-        }
-
-        @Override
-        public boolean getCTS() throws IOException {
-            return (getStatus() & GCL_CTS) == 0;
-        }
-
-        @Override
-        public boolean getDSR() throws IOException {
-            return (getStatus() & GCL_DSR) == 0;
-        }
-
-        @Override
-        public boolean getDTR() throws IOException {
-            return dtr;
-        }
-
-        @Override
-        public void setDTR(boolean value) throws IOException {
-            dtr = value;
-            setControlLines();
-        }
-
-        @Override
-        public boolean getRI() throws IOException {
-            return (getStatus() & GCL_RI) == 0;
-        }
-
-        @Override
-        public boolean getRTS() throws IOException {
-            return rts;
-        }
-
-        @Override
-        public void setRTS(boolean value) throws IOException {
-            rts = value;
-            setControlLines();
-        }
-
-        @Override
-        public EnumSet<ControlLine> getControlLines() throws IOException {
-            int status = getStatus();
-            EnumSet<ControlLine> set = EnumSet.noneOf(ControlLine.class);
-            if(rts) set.add(ControlLine.RTS);
-            if((status & GCL_CTS) == 0) set.add(ControlLine.CTS);
-            if(dtr) set.add(ControlLine.DTR);
-            if((status & GCL_DSR) == 0) set.add(ControlLine.DSR);
-            if((status & GCL_CD) == 0) set.add(ControlLine.CD);
-            if((status & GCL_RI) == 0) set.add(ControlLine.RI);
-            return set;
-        }
-
-        @Override
-        public EnumSet<ControlLine> getSupportedControlLines() throws IOException {
-            return EnumSet.allOf(ControlLine.class);
-        }
-
-        @Override
-        public void setBreak(boolean value) throws IOException {
-            byte[] req = new byte[2];
-            if(controlIn(0x95, 0x1805, 0, req) < 0) {
-                throw new IOException("Error getting BREAK condition");
-            }
-            if(value) {
-                req[0] &= ~1;
-                req[1] &= ~0x40;
-            } else {
-                req[0] |= 1;
-                req[1] |= 0x40;
-            }
-            int val = (req[1] & 0xff) << 8 | (req[0] & 0xff);
-            if(controlOut(0x9a, 0x1805, val) < 0) {
-                throw new IOException("Error setting BREAK condition");
-            }
-        }
-    }
-
-    @SuppressWarnings({"unused"})
-    public static Map<Integer, int[]> getSupportedDevices() {
-        final Map<Integer, int[]> supportedDevices = new LinkedHashMap<>();
-        supportedDevices.put(UsbId.VENDOR_QINHENG, new int[]{
-                UsbId.QINHENG_CH340,
-                UsbId.QINHENG_CH341A,
-        });
-        return supportedDevices;
-    }
-
-}

+ 0 - 96
Qt/Android/SmartPDU_QT/Android/src/com/hoho/android/usbserial/driver/ChromeCcdSerialDriver.java

@@ -1,96 +0,0 @@
-package com.hoho.android.usbserial.driver;
-
-import android.hardware.usb.UsbConstants;
-import android.hardware.usb.UsbDevice;
-import android.hardware.usb.UsbEndpoint;
-import android.hardware.usb.UsbInterface;
-import android.util.Log;
-
-import java.io.IOException;
-import java.util.Collections;
-import java.util.EnumSet;
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.ArrayList;
-
-public class ChromeCcdSerialDriver implements UsbSerialDriver{
-
-    private final String TAG = ChromeCcdSerialDriver.class.getSimpleName();
-
-    private final UsbDevice mDevice;
-    private final List<UsbSerialPort> mPorts;
-
-    @Override
-    public UsbDevice getDevice() {
-        return mDevice;
-    }
-
-    @Override
-    public List<UsbSerialPort> getPorts() {
-        return mPorts;
-    }
-
-    public ChromeCcdSerialDriver(UsbDevice mDevice) {
-        this.mDevice = mDevice;
-        mPorts = new ArrayList<UsbSerialPort>();
-        for (int i = 0; i < 3; i++)
-            mPorts.add(new ChromeCcdSerialPort(mDevice, i));
-    }
-
-    public class ChromeCcdSerialPort extends CommonUsbSerialPort {
-        private UsbInterface mDataInterface;
-
-        public ChromeCcdSerialPort(UsbDevice device, int portNumber) {
-            super(device, portNumber);
-        }
-
-        @Override
-        protected void openInt() throws IOException {
-            Log.d(TAG, "claiming interfaces, count=" + mDevice.getInterfaceCount());
-            mDataInterface = mDevice.getInterface(mPortNumber);
-            if (!mConnection.claimInterface(mDataInterface, true)) {
-                throw new IOException("Could not claim shared control/data interface");
-            }
-            Log.d(TAG, "endpoint count=" + mDataInterface.getEndpointCount());
-            for (int i = 0; i < mDataInterface.getEndpointCount(); ++i) {
-                UsbEndpoint ep = mDataInterface.getEndpoint(i);
-                if ((ep.getDirection() == UsbConstants.USB_DIR_IN) && (ep.getType() == UsbConstants.USB_ENDPOINT_XFER_BULK)) {
-                    mReadEndpoint = ep;
-                } else if ((ep.getDirection() == UsbConstants.USB_DIR_OUT) && (ep.getType() == UsbConstants.USB_ENDPOINT_XFER_BULK)) {
-                    mWriteEndpoint = ep;
-                }
-            }
-        }
-
-        @Override
-        protected void closeInt() {
-            try {
-                mConnection.releaseInterface(mDataInterface);
-            } catch(Exception ignored) {}
-        }
-
-        @Override
-        public UsbSerialDriver getDriver() {
-            return ChromeCcdSerialDriver.this;
-        }
-
-        @Override
-        public void setParameters(int baudRate, int dataBits, int stopBits, int parity) throws IOException {
-            throw new UnsupportedOperationException();
-        }
-
-        @Override
-        public EnumSet<ControlLine> getSupportedControlLines() throws IOException {
-            return EnumSet.noneOf(ControlLine.class);
-        }
-    }
-
-    public static Map<Integer, int[]> getSupportedDevices() {
-        final Map<Integer, int[]> supportedDevices = new LinkedHashMap<>();
-        supportedDevices.put(UsbId.VENDOR_GOOGLE, new int[]{
-                UsbId.GOOGLE_CR50,
-        });
-        return supportedDevices;
-    }
-}

+ 0 - 336
Qt/Android/SmartPDU_QT/Android/src/com/hoho/android/usbserial/driver/CommonUsbSerialPort.java

@@ -1,336 +0,0 @@
-/* Copyright 2011-2013 Google Inc.
- * Copyright 2013 mike wakerly <opensource@hoho.com>
- *
- * Project home page: https://github.com/mik3y/usb-serial-for-android
- */
-
-package com.hoho.android.usbserial.driver;
-
-import android.hardware.usb.UsbDevice;
-import android.hardware.usb.UsbDeviceConnection;
-import android.hardware.usb.UsbEndpoint;
-import android.hardware.usb.UsbRequest;
-import android.util.Log;
-
-import com.hoho.android.usbserial.util.MonotonicClock;
-
-import java.io.IOException;
-import java.nio.ByteBuffer;
-import java.util.EnumSet;
-
-/**
- * A base class shared by several driver implementations.
- *
- * @author mike wakerly (opensource@hoho.com)
- */
-public abstract class CommonUsbSerialPort implements UsbSerialPort {
-
-    public static boolean DEBUG = false;
-
-    private static final String TAG = CommonUsbSerialPort.class.getSimpleName();
-    private static final int MAX_READ_SIZE = 16 * 1024; // = old bulkTransfer limit
-
-    protected final UsbDevice mDevice;
-    protected final int mPortNumber;
-
-    // non-null when open()
-    protected UsbDeviceConnection mConnection = null;
-    protected UsbEndpoint mReadEndpoint;
-    protected UsbEndpoint mWriteEndpoint;
-    protected UsbRequest mUsbRequest;
-
-    /**
-     * Internal write buffer.
-     *  Guarded by {@link #mWriteBufferLock}.
-     *  Default length = mReadEndpoint.getMaxPacketSize()
-     **/
-    protected byte[] mWriteBuffer;
-    protected final Object mWriteBufferLock = new Object();
-
-
-    public CommonUsbSerialPort(UsbDevice device, int portNumber) {
-        mDevice = device;
-        mPortNumber = portNumber;
-    }
-
-    @Override
-    public String toString() {
-        return String.format("<%s device_name=%s device_id=%s port_number=%s>",
-                getClass().getSimpleName(), mDevice.getDeviceName(),
-                mDevice.getDeviceId(), mPortNumber);
-    }
-
-    @Override
-    public UsbDevice getDevice() {
-        return mDevice;
-    }
-
-    @Override
-    public int getPortNumber() {
-        return mPortNumber;
-    }
-
-    @Override
-    public UsbEndpoint getWriteEndpoint() { return mWriteEndpoint; }
-
-    @Override
-    public UsbEndpoint getReadEndpoint() { return mReadEndpoint; }
-
-    /**
-     * Returns the device serial number
-     *  @return serial number
-     */
-    @Override
-    public String getSerial() {
-        return mConnection.getSerial();
-    }
-
-    /**
-     * Sets the size of the internal buffer used to exchange data with the USB
-     * stack for write operations.  Most users should not need to change this.
-     *
-     * @param bufferSize the size in bytes, <= 0 resets original size
-     */
-    public final void setWriteBufferSize(int bufferSize) {
-        synchronized (mWriteBufferLock) {
-            if (bufferSize <= 0) {
-                if (mWriteEndpoint != null) {
-                    bufferSize = mWriteEndpoint.getMaxPacketSize();
-                } else {
-                    mWriteBuffer = null;
-                    return;
-                }
-            }
-            if (mWriteBuffer != null && bufferSize == mWriteBuffer.length) {
-                return;
-            }
-            mWriteBuffer = new byte[bufferSize];
-        }
-    }
-
-    @Override
-    public void open(UsbDeviceConnection connection) throws IOException {
-        if (mConnection != null) {
-            throw new IOException("Already open");
-        }
-        if(connection == null) {
-            throw new IllegalArgumentException("Connection is null");
-        }
-        mConnection = connection;
-        try {
-            openInt();
-            if (mReadEndpoint == null || mWriteEndpoint == null) {
-                throw new IOException("Could not get read & write endpoints");
-            }
-            mUsbRequest = new UsbRequest();
-            mUsbRequest.initialize(mConnection, mReadEndpoint);
-        } catch(Exception e) {
-            try {
-                close();
-            } catch(Exception ignored) {}
-            throw e;
-        }
-    }
-
-    protected abstract void openInt() throws IOException;
-
-    @Override
-    public void close() throws IOException {
-        if (mConnection == null) {
-            throw new IOException("Already closed");
-        }
-        UsbDeviceConnection connection = mConnection;
-        mConnection = null;
-        try {
-            mUsbRequest.cancel();
-        } catch(Exception ignored) {}
-        mUsbRequest = null;
-        try {
-            closeInt();
-        } catch(Exception ignored) {}
-        try {
-            connection.close();
-        } catch(Exception ignored) {}
-    }
-
-    protected abstract void closeInt();
-
-    /**
-     * use simple USB request supported by all devices to test if connection is still valid
-     */
-    protected void testConnection(boolean full) throws IOException {
-        if(mConnection == null) {
-            throw new IOException("Connection closed");
-        }
-        if(!full) {
-            return;
-        }
-        byte[] buf = new byte[2];
-        int len = mConnection.controlTransfer(0x80 /*DEVICE*/, 0 /*GET_STATUS*/, 0, 0, buf, buf.length, 200);
-        if(len < 0)
-            throw new IOException("USB get_status request failed");
-    }
-
-    @Override
-    public int read(final byte[] dest, final int timeout) throws IOException {
-        if(dest.length == 0) {
-            throw new IllegalArgumentException("Read buffer too small");
-        }
-        return read(dest, dest.length, timeout);
-    }
-
-    @Override
-    public int read(final byte[] dest, final int length, final int timeout) throws IOException {return read(dest, length, timeout, true);}
-
-    protected int read(final byte[] dest, int length, final int timeout, boolean testConnection) throws IOException {
-        if(mConnection == null) {
-            throw new IOException("Connection closed");
-        }
-        if(length <= 0) {
-            throw new IllegalArgumentException("Read length too small");
-        }
-        length = Math.min(length, dest.length);
-        final int nread;
-        if (timeout != 0) {
-            // bulkTransfer will cause data loss with short timeout + high baud rates + continuous transfer
-            //   https://stackoverflow.com/questions/9108548/android-usb-host-bulktransfer-is-losing-data
-            // but mConnection.requestWait(timeout) available since Android 8.0 es even worse,
-            // as it crashes with short timeout, e.g.
-            //   A/libc: Fatal signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr 0x276a in tid 29846 (pool-2-thread-1), pid 29618 (.usbserial.test)
-            //     /system/lib64/libusbhost.so (usb_request_wait+192)
-            //     /system/lib64/libandroid_runtime.so (android_hardware_UsbDeviceConnection_request_wait(_JNIEnv*, _jobject*, long)+84)
-            // data loss / crashes were observed with timeout up to 200 msec
-            long endTime = testConnection ? MonotonicClock.millis() + timeout : 0;
-            int readMax = Math.min(length, MAX_READ_SIZE);
-            nread = mConnection.bulkTransfer(mReadEndpoint, dest, readMax, timeout);
-            // Android error propagation is improvable:
-            //  nread == -1 can be: timeout, connection lost, buffer to small, ???
-            if(nread == -1 && testConnection)
-                testConnection(MonotonicClock.millis() < endTime);
-
-        } else {
-            final ByteBuffer buf = ByteBuffer.wrap(dest, 0, length);
-            if (!mUsbRequest.queue(buf, length)) {
-                throw new IOException("Queueing USB request failed");
-            }
-            final UsbRequest response = mConnection.requestWait();
-            if (response == null) {
-                throw new IOException("Waiting for USB request failed");
-            }
-            nread = buf.position();
-            // Android error propagation is improvable:
-            //   response != null & nread == 0 can be: connection lost, buffer to small, ???
-            if(nread == 0) {
-                testConnection(true);
-            }
-        }
-        return Math.max(nread, 0);
-    }
-
-    @Override
-    public void write(byte[] src, int timeout) throws IOException {write(src, src.length, timeout);}
-
-    @Override
-    public void write(final byte[] src, int length, final int timeout) throws IOException {
-        int offset = 0;
-        final long endTime = (timeout == 0) ? 0 : (MonotonicClock.millis() + timeout);
-        length = Math.min(length, src.length);
-
-        if(mConnection == null) {
-            throw new IOException("Connection closed");
-        }
-        while (offset < length) {
-            int requestTimeout;
-            final int requestLength;
-            final int actualLength;
-
-            synchronized (mWriteBufferLock) {
-                final byte[] writeBuffer;
-
-                if (mWriteBuffer == null) {
-                    mWriteBuffer = new byte[mWriteEndpoint.getMaxPacketSize()];
-                }
-                requestLength = Math.min(length - offset, mWriteBuffer.length);
-                if (offset == 0) {
-                    writeBuffer = src;
-                } else {
-                    // bulkTransfer does not support offsets, make a copy.
-                    System.arraycopy(src, offset, mWriteBuffer, 0, requestLength);
-                    writeBuffer = mWriteBuffer;
-                }
-                if (timeout == 0 || offset == 0) {
-                    requestTimeout = timeout;
-                } else {
-                    requestTimeout = (int)(endTime - MonotonicClock.millis());
-                    if(requestTimeout == 0)
-                        requestTimeout = -1;
-                }
-                if (requestTimeout < 0) {
-                    actualLength = -2;
-                } else {
-                    actualLength = mConnection.bulkTransfer(mWriteEndpoint, writeBuffer, requestLength, requestTimeout);
-                }
-            }
-            if (DEBUG) {
-                Log.d(TAG, "Wrote " + actualLength + "/" + requestLength + " offset " + offset + "/" + length + " timeout " + requestTimeout);
-            }
-            if (actualLength <= 0) {
-                if (timeout != 0 && MonotonicClock.millis() >= endTime) {
-                    SerialTimeoutException ex = new SerialTimeoutException("Error writing " + requestLength + " bytes at offset " + offset + " of total " + src.length + ", rc=" + actualLength);
-                    ex.bytesTransferred = offset;
-                    throw ex;
-                } else {
-                    throw new IOException("Error writing " + requestLength + " bytes at offset " + offset + " of total " + length);
-                }
-            }
-            offset += actualLength;
-        }
-    }
-
-    @Override
-    public boolean isOpen() {
-        return mConnection != null;
-    }
-
-    @Override
-    public abstract void setParameters(int baudRate, int dataBits, int stopBits, @Parity int parity) throws IOException;
-
-    @Override
-    public boolean getCD() throws IOException { throw new UnsupportedOperationException(); }
-
-    @Override
-    public boolean getCTS() throws IOException { throw new UnsupportedOperationException(); }
-
-    @Override
-    public boolean getDSR() throws IOException { throw new UnsupportedOperationException(); }
-
-    @Override
-    public boolean getDTR() throws IOException { throw new UnsupportedOperationException(); }
-
-    @Override
-    public void setDTR(boolean value) throws IOException { throw new UnsupportedOperationException(); }
-
-    @Override
-    public boolean getRI() throws IOException { throw new UnsupportedOperationException(); }
-
-    @Override
-    public boolean getRTS() throws IOException { throw new UnsupportedOperationException(); }
-
-    @Override
-    public void setRTS(boolean value) throws IOException { throw new UnsupportedOperationException(); }
-
-    @Override
-    public EnumSet<ControlLine> getControlLines() throws IOException { throw new UnsupportedOperationException(); }
-
-    @Override
-    public abstract EnumSet<ControlLine> getSupportedControlLines() throws IOException;
-
-    @Override
-    public void purgeHwBuffers(boolean purgeWriteBuffers, boolean purgeReadBuffers) throws IOException {
-        throw new UnsupportedOperationException();
-    }
-
-    @Override
-    public void setBreak(boolean value) throws IOException { throw new UnsupportedOperationException(); }
-
-}

+ 0 - 335
Qt/Android/SmartPDU_QT/Android/src/com/hoho/android/usbserial/driver/Cp21xxSerialDriver.java

@@ -1,335 +0,0 @@
-/* Copyright 2011-2013 Google Inc.
- * Copyright 2013 mike wakerly <opensource@hoho.com>
- *
- * Project home page: https://github.com/mik3y/usb-serial-for-android
- */
-
-package com.hoho.android.usbserial.driver;
-
-import android.hardware.usb.UsbConstants;
-import android.hardware.usb.UsbDevice;
-import android.hardware.usb.UsbEndpoint;
-import android.hardware.usb.UsbInterface;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.EnumSet;
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.Map;
-
-public class Cp21xxSerialDriver implements UsbSerialDriver {
-
-    private static final String TAG = Cp21xxSerialDriver.class.getSimpleName();
-
-    private final UsbDevice mDevice;
-    private final List<UsbSerialPort> mPorts;
-
-    public Cp21xxSerialDriver(UsbDevice device) {
-        mDevice = device;
-        mPorts = new ArrayList<>();
-        for( int port = 0; port < device.getInterfaceCount(); port++) {
-            mPorts.add(new Cp21xxSerialPort(mDevice, port));
-        }
-    }
-
-    @Override
-    public UsbDevice getDevice() {
-        return mDevice;
-    }
-
-    @Override
-    public List<UsbSerialPort> getPorts() {
-        return mPorts;
-    }
-
-    public class Cp21xxSerialPort extends CommonUsbSerialPort {
-
-        private static final int USB_WRITE_TIMEOUT_MILLIS = 5000;
-
-        /*
-         * Configuration Request Types
-         */
-        private static final int REQTYPE_HOST_TO_DEVICE = 0x41;
-        private static final int REQTYPE_DEVICE_TO_HOST = 0xc1;
-
-        /*
-         * Configuration Request Codes
-         */
-        private static final int SILABSER_IFC_ENABLE_REQUEST_CODE = 0x00;
-        private static final int SILABSER_SET_LINE_CTL_REQUEST_CODE = 0x03;
-        private static final int SILABSER_SET_BREAK_REQUEST_CODE = 0x05;
-        private static final int SILABSER_SET_MHS_REQUEST_CODE = 0x07;
-        private static final int SILABSER_SET_BAUDRATE = 0x1E;
-        private static final int SILABSER_FLUSH_REQUEST_CODE = 0x12;
-        private static final int SILABSER_GET_MDMSTS_REQUEST_CODE = 0x08;
-
-        private static final int FLUSH_READ_CODE = 0x0a;
-        private static final int FLUSH_WRITE_CODE = 0x05;
-
-        /*
-         * SILABSER_IFC_ENABLE_REQUEST_CODE
-         */
-        private static final int UART_ENABLE = 0x0001;
-        private static final int UART_DISABLE = 0x0000;
-
-        /*
-         * SILABSER_SET_MHS_REQUEST_CODE
-         */
-        private static final int DTR_ENABLE = 0x101;
-        private static final int DTR_DISABLE = 0x100;
-        private static final int RTS_ENABLE = 0x202;
-        private static final int RTS_DISABLE = 0x200;
-
-        /*
-        * SILABSER_GET_MDMSTS_REQUEST_CODE
-         */
-        private static final int STATUS_CTS = 0x10;
-        private static final int STATUS_DSR = 0x20;
-        private static final int STATUS_RI = 0x40;
-        private static final int STATUS_CD = 0x80;
-
-
-        private boolean dtr = false;
-        private boolean rts = false;
-
-        // second port of Cp2105 has limited baudRate, dataBits, stopBits, parity
-        // unsupported baudrate returns error at controlTransfer(), other parameters are silently ignored
-        private boolean mIsRestrictedPort;
-
-        public Cp21xxSerialPort(UsbDevice device, int portNumber) {
-            super(device, portNumber);
-        }
-
-        @Override
-        public UsbSerialDriver getDriver() {
-            return Cp21xxSerialDriver.this;
-        }
-
-        private void setConfigSingle(int request, int value) throws IOException {
-            int result = mConnection.controlTransfer(REQTYPE_HOST_TO_DEVICE, request, value,
-                    mPortNumber, null, 0, USB_WRITE_TIMEOUT_MILLIS);
-            if (result != 0) {
-                throw new IOException("Control transfer failed: " + request + " / " + value + " -> " + result);
-            }
-        }
-
-        private byte getStatus() throws IOException {
-            byte[] buffer = new byte[1];
-            int result = mConnection.controlTransfer(REQTYPE_DEVICE_TO_HOST, SILABSER_GET_MDMSTS_REQUEST_CODE, 0,
-                    mPortNumber, buffer, buffer.length, USB_WRITE_TIMEOUT_MILLIS);
-            if (result != buffer.length) {
-                throw new IOException("Control transfer failed: " + SILABSER_GET_MDMSTS_REQUEST_CODE + " / " + 0 + " -> " + result);
-            }
-            return buffer[0];
-        }
-
-        @Override
-        protected void openInt() throws IOException {
-            mIsRestrictedPort = mDevice.getInterfaceCount() == 2 && mPortNumber == 1;
-            if(mPortNumber >= mDevice.getInterfaceCount()) {
-                throw new IOException("Unknown port number");
-            }
-            UsbInterface dataIface = mDevice.getInterface(mPortNumber);
-            if (!mConnection.claimInterface(dataIface, true)) {
-                throw new IOException("Could not claim interface " + mPortNumber);
-            }
-            for (int i = 0; i < dataIface.getEndpointCount(); i++) {
-                UsbEndpoint ep = dataIface.getEndpoint(i);
-                if (ep.getType() == UsbConstants.USB_ENDPOINT_XFER_BULK) {
-                    if (ep.getDirection() == UsbConstants.USB_DIR_IN) {
-                        mReadEndpoint = ep;
-                    } else {
-                        mWriteEndpoint = ep;
-                    }
-                }
-            }
-
-            setConfigSingle(SILABSER_IFC_ENABLE_REQUEST_CODE, UART_ENABLE);
-            setConfigSingle(SILABSER_SET_MHS_REQUEST_CODE, (dtr ? DTR_ENABLE : DTR_DISABLE) | (rts ? RTS_ENABLE : RTS_DISABLE));
-        }
-
-        @Override
-        protected void closeInt() {
-            try {
-                setConfigSingle(SILABSER_IFC_ENABLE_REQUEST_CODE, UART_DISABLE);
-            } catch (Exception ignored) {}
-            try {
-                mConnection.releaseInterface(mDevice.getInterface(mPortNumber));
-            } catch(Exception ignored) {}
-        }
-
-        private void setBaudRate(int baudRate) throws IOException {
-            byte[] data = new byte[] {
-                    (byte) ( baudRate & 0xff),
-                    (byte) ((baudRate >> 8 ) & 0xff),
-                    (byte) ((baudRate >> 16) & 0xff),
-                    (byte) ((baudRate >> 24) & 0xff)
-            };
-            int ret = mConnection.controlTransfer(REQTYPE_HOST_TO_DEVICE, SILABSER_SET_BAUDRATE,
-                    0, mPortNumber, data, 4, USB_WRITE_TIMEOUT_MILLIS);
-            if (ret < 0) {
-                throw new IOException("Error setting baud rate");
-            }
-        }
-
-        @Override
-        public void setParameters(int baudRate, int dataBits, int stopBits, @Parity int parity) throws IOException {
-            if(baudRate <= 0) {
-                throw new IllegalArgumentException("Invalid baud rate: " + baudRate);
-            }
-            setBaudRate(baudRate);
-
-            int configDataBits = 0;
-            switch (dataBits) {
-                case DATABITS_5:
-                    if(mIsRestrictedPort)
-                        throw new UnsupportedOperationException("Unsupported data bits: " + dataBits);
-                    configDataBits |= 0x0500;
-                    break;
-                case DATABITS_6:
-                    if(mIsRestrictedPort)
-                        throw new UnsupportedOperationException("Unsupported data bits: " + dataBits);
-                    configDataBits |= 0x0600;
-                    break;
-                case DATABITS_7:
-                    if(mIsRestrictedPort)
-                        throw new UnsupportedOperationException("Unsupported data bits: " + dataBits);
-                    configDataBits |= 0x0700;
-                    break;
-                case DATABITS_8:
-                    configDataBits |= 0x0800;
-                    break;
-                default:
-                    throw new IllegalArgumentException("Invalid data bits: " + dataBits);
-            }
-            
-            switch (parity) {
-                case PARITY_NONE:
-                    break;
-                case PARITY_ODD:
-                    configDataBits |= 0x0010;
-                    break;
-                case PARITY_EVEN:
-                    configDataBits |= 0x0020;
-                    break;
-                case PARITY_MARK:
-                    if(mIsRestrictedPort)
-                        throw new UnsupportedOperationException("Unsupported parity: mark");
-                    configDataBits |= 0x0030;
-                    break;
-                case PARITY_SPACE:
-                    if(mIsRestrictedPort)
-                        throw new UnsupportedOperationException("Unsupported parity: space");
-                    configDataBits |= 0x0040;
-                    break;
-                default:
-                    throw new IllegalArgumentException("Invalid parity: " + parity);
-            }
-            
-            switch (stopBits) {
-                case STOPBITS_1:
-                    break;
-                case STOPBITS_1_5:
-                    throw new UnsupportedOperationException("Unsupported stop bits: 1.5");
-                case STOPBITS_2:
-                    if(mIsRestrictedPort)
-                        throw new UnsupportedOperationException("Unsupported stop bits: 2");
-                    configDataBits |= 2;
-                    break;
-                default:
-                    throw new IllegalArgumentException("Invalid stop bits: " + stopBits);
-            }
-            setConfigSingle(SILABSER_SET_LINE_CTL_REQUEST_CODE, configDataBits);
-        }
-
-        @Override
-        public boolean getCD() throws IOException {
-            return (getStatus() & STATUS_CD) != 0;
-        }
-
-        @Override
-        public boolean getCTS() throws IOException {
-            return (getStatus() & STATUS_CTS) != 0;
-        }
-
-        @Override
-        public boolean getDSR() throws IOException {
-            return (getStatus() & STATUS_DSR) != 0;
-        }
-
-        @Override
-        public boolean getDTR() throws IOException {
-            return dtr;
-        }
-
-        @Override
-        public void setDTR(boolean value) throws IOException {
-            dtr = value;
-            setConfigSingle(SILABSER_SET_MHS_REQUEST_CODE, dtr ? DTR_ENABLE : DTR_DISABLE);
-        }
-
-        @Override
-        public boolean getRI() throws IOException {
-            return (getStatus() & STATUS_RI) != 0;
-        }
-
-        @Override
-        public boolean getRTS() throws IOException {
-            return rts;
-        }
-
-        @Override
-        public void setRTS(boolean value) throws IOException {
-            rts = value;
-            setConfigSingle(SILABSER_SET_MHS_REQUEST_CODE, rts ? RTS_ENABLE : RTS_DISABLE);
-        }
-
-        @Override
-        public EnumSet<ControlLine> getControlLines() throws IOException {
-            byte status = getStatus();
-            EnumSet<ControlLine> set = EnumSet.noneOf(ControlLine.class);
-            if(rts) set.add(ControlLine.RTS);
-            if((status & STATUS_CTS) != 0) set.add(ControlLine.CTS);
-            if(dtr) set.add(ControlLine.DTR);
-            if((status & STATUS_DSR) != 0) set.add(ControlLine.DSR);
-            if((status & STATUS_CD) != 0) set.add(ControlLine.CD);
-            if((status & STATUS_RI) != 0) set.add(ControlLine.RI);
-            return set;
-        }
-
-        @Override
-        public EnumSet<ControlLine> getSupportedControlLines() throws IOException {
-            return EnumSet.allOf(ControlLine.class);
-        }
-
-        @Override
-        // note: only working on some devices, on other devices ignored w/o error
-        public void purgeHwBuffers(boolean purgeWriteBuffers, boolean purgeReadBuffers) throws IOException {
-            int value = (purgeReadBuffers ? FLUSH_READ_CODE : 0)
-                    | (purgeWriteBuffers ? FLUSH_WRITE_CODE : 0);
-
-            if (value != 0) {
-                setConfigSingle(SILABSER_FLUSH_REQUEST_CODE, value);
-            }
-        }
-
-        @Override
-        public void setBreak(boolean value) throws IOException {
-            setConfigSingle(SILABSER_SET_BREAK_REQUEST_CODE, value ? 1 : 0);
-        }
-    }
-
-    @SuppressWarnings({"unused"})
-    public static Map<Integer, int[]> getSupportedDevices() {
-        final Map<Integer, int[]> supportedDevices = new LinkedHashMap<>();
-        supportedDevices.put(UsbId.VENDOR_SILABS,
-                new int[] {
-            UsbId.SILABS_CP2102, // same ID for CP2101, CP2103, CP2104, CP2109
-            UsbId.SILABS_CP2105,
-            UsbId.SILABS_CP2108,
-        });
-        return supportedDevices;
-    }
-
-}

+ 0 - 444
Qt/Android/SmartPDU_QT/Android/src/com/hoho/android/usbserial/driver/FtdiSerialDriver.java

@@ -1,444 +0,0 @@
-/* Copyright 2011-2013 Google Inc.
- * Copyright 2013 mike wakerly <opensource@hoho.com>
- * Copyright 2020 kai morich <mail@kai-morich.de>
- *
- * Project home page: https://github.com/mik3y/usb-serial-for-android
- */
-
-package com.hoho.android.usbserial.driver;
-
-import android.hardware.usb.UsbConstants;
-import android.hardware.usb.UsbDevice;
-import android.util.Log;
-
-import com.hoho.android.usbserial.util.MonotonicClock;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.EnumSet;
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.Map;
-
-/*
- * driver is implemented from various information scattered over FTDI documentation
- *
- * baud rate calculation https://www.ftdichip.com/Support/Documents/AppNotes/AN232B-05_BaudRates.pdf
- * control bits https://www.ftdichip.com/Firmware/Precompiled/UM_VinculumFirmware_V205.pdf
- * device type https://www.ftdichip.com/Support/Documents/AppNotes/AN_233_Java_D2XX_for_Android_API_User_Manual.pdf -> bvdDevice
- *
- */
-
-public class FtdiSerialDriver implements UsbSerialDriver {
-
-    private static final String TAG = FtdiSerialPort.class.getSimpleName();
-
-    private final UsbDevice mDevice;
-    private final List<UsbSerialPort> mPorts;
-
-    public FtdiSerialDriver(UsbDevice device) {
-        mDevice = device;
-        mPorts = new ArrayList<>();
-        for( int port = 0; port < device.getInterfaceCount(); port++) {
-            mPorts.add(new FtdiSerialPort(mDevice, port));
-        }
-    }
-
-    @Override
-    public UsbDevice getDevice() {
-        return mDevice;
-    }
-
-    @Override
-    public List<UsbSerialPort> getPorts() {
-        return mPorts;
-    }
-
-    public class FtdiSerialPort extends CommonUsbSerialPort {
-
-        private static final int USB_WRITE_TIMEOUT_MILLIS = 5000;
-        private static final int READ_HEADER_LENGTH = 2; // contains MODEM_STATUS
-
-        private static final int REQTYPE_HOST_TO_DEVICE = UsbConstants.USB_TYPE_VENDOR | UsbConstants.USB_DIR_OUT;
-        private static final int REQTYPE_DEVICE_TO_HOST = UsbConstants.USB_TYPE_VENDOR | UsbConstants.USB_DIR_IN;
-
-        private static final int RESET_REQUEST = 0;
-        private static final int MODEM_CONTROL_REQUEST = 1;
-        private static final int SET_BAUD_RATE_REQUEST = 3;
-        private static final int SET_DATA_REQUEST = 4;
-        private static final int GET_MODEM_STATUS_REQUEST = 5;
-        private static final int SET_LATENCY_TIMER_REQUEST = 9;
-        private static final int GET_LATENCY_TIMER_REQUEST = 10;
-
-        private static final int MODEM_CONTROL_DTR_ENABLE = 0x0101;
-        private static final int MODEM_CONTROL_DTR_DISABLE = 0x0100;
-        private static final int MODEM_CONTROL_RTS_ENABLE = 0x0202;
-        private static final int MODEM_CONTROL_RTS_DISABLE = 0x0200;
-        private static final int MODEM_STATUS_CTS = 0x10;
-        private static final int MODEM_STATUS_DSR = 0x20;
-        private static final int MODEM_STATUS_RI = 0x40;
-        private static final int MODEM_STATUS_CD = 0x80;
-        private static final int RESET_ALL = 0;
-        private static final int RESET_PURGE_RX = 1;
-        private static final int RESET_PURGE_TX = 2;
-
-        private boolean baudRateWithPort = false;
-        private boolean dtr = false;
-        private boolean rts = false;
-        private int breakConfig = 0;
-
-        public FtdiSerialPort(UsbDevice device, int portNumber) {
-            super(device, portNumber);
-        }
-
-        @Override
-        public UsbSerialDriver getDriver() {
-            return FtdiSerialDriver.this;
-        }
-
-
-        @Override
-        protected void openInt() throws IOException {
-            if (!mConnection.claimInterface(mDevice.getInterface(mPortNumber), true)) {
-                throw new IOException("Could not claim interface " + mPortNumber);
-            }
-            if (mDevice.getInterface(mPortNumber).getEndpointCount() < 2) {
-                throw new IOException("Not enough endpoints");
-            }
-            mReadEndpoint = mDevice.getInterface(mPortNumber).getEndpoint(0);
-            mWriteEndpoint = mDevice.getInterface(mPortNumber).getEndpoint(1);
-
-            int result = mConnection.controlTransfer(REQTYPE_HOST_TO_DEVICE, RESET_REQUEST,
-                    RESET_ALL, mPortNumber+1, null, 0, USB_WRITE_TIMEOUT_MILLIS);
-            if (result != 0) {
-                throw new IOException("Reset failed: result=" + result);
-            }
-            result = mConnection.controlTransfer(REQTYPE_HOST_TO_DEVICE, MODEM_CONTROL_REQUEST,
-                    (dtr ? MODEM_CONTROL_DTR_ENABLE : MODEM_CONTROL_DTR_DISABLE) |
-                            (rts ? MODEM_CONTROL_RTS_ENABLE : MODEM_CONTROL_RTS_DISABLE),
-                    mPortNumber+1, null, 0, USB_WRITE_TIMEOUT_MILLIS);
-            if (result != 0) {
-                throw new IOException("Init RTS,DTR failed: result=" + result);
-            }
-
-            // mDevice.getVersion() would require API 23
-            byte[] rawDescriptors = mConnection.getRawDescriptors();
-            if(rawDescriptors == null || rawDescriptors.length < 14) {
-                throw new IOException("Could not get device descriptors");
-            }
-            int deviceType = rawDescriptors[13];
-            baudRateWithPort = deviceType == 7 || deviceType == 8 || deviceType == 9 // ...H devices
-                    || mDevice.getInterfaceCount() > 1; // FT2232C
-        }
-
-        @Override
-        protected void closeInt() {
-            try {
-                mConnection.releaseInterface(mDevice.getInterface(mPortNumber));
-            } catch(Exception ignored) {}
-        }
-
-        @Override
-        public int read(final byte[] dest, final int timeout) throws IOException
-        {
-            if(dest.length <= READ_HEADER_LENGTH) {
-                throw new IllegalArgumentException("Read buffer too small");
-                // could allocate larger buffer, including space for 2 header bytes, but this would
-                // result in buffers not being 64 byte aligned any more, causing data loss at continuous
-                // data transfer at high baud rates when buffers are fully filled.
-            }
-            return read(dest, dest.length, timeout);
-        }
-
-        @Override
-        public int read(final byte[] dest, int length, final int timeout) throws IOException {
-            if(length <= READ_HEADER_LENGTH) {
-                throw new IllegalArgumentException("Read length too small");
-                // could allocate larger buffer, including space for 2 header bytes, but this would
-                // result in buffers not being 64 byte aligned any more, causing data loss at continuous
-                // data transfer at high baud rates when buffers are fully filled.
-            }
-            length = Math.min(length, dest.length);
-            int nread;
-            if (timeout != 0) {
-                long endTime = MonotonicClock.millis() + timeout;
-                do {
-                    nread = super.read(dest, length, Math.max(1, (int)(endTime - MonotonicClock.millis())), false);
-                } while (nread == READ_HEADER_LENGTH && MonotonicClock.millis() < endTime);
-                if(nread <= 0)
-                    testConnection(MonotonicClock.millis() < endTime);
-            } else {
-                do {
-                    nread = super.read(dest, length, timeout);
-                } while (nread == READ_HEADER_LENGTH);
-            }
-            return readFilter(dest, nread);
-        }
-
-        protected int readFilter(byte[] buffer, int totalBytesRead) throws IOException {
-            final int maxPacketSize = mReadEndpoint.getMaxPacketSize();
-            int destPos = 0;
-            for(int srcPos = 0; srcPos < totalBytesRead; srcPos += maxPacketSize) {
-                int length = Math.min(srcPos + maxPacketSize, totalBytesRead) - (srcPos + READ_HEADER_LENGTH);
-                if (length < 0)
-                    throw new IOException("Expected at least " + READ_HEADER_LENGTH + " bytes");
-                System.arraycopy(buffer, srcPos + READ_HEADER_LENGTH, buffer, destPos, length);
-                destPos += length;
-            }
-            //Log.d(TAG, "read filter " + totalBytesRead + " -> " + destPos);
-            return destPos;
-        }
-
-        private void setBaudrate(int baudRate) throws IOException {
-            int divisor, subdivisor, effectiveBaudRate;
-            if (baudRate > 3500000) {
-                throw new UnsupportedOperationException("Baud rate to high");
-            } else if(baudRate >= 2500000) {
-                divisor = 0;
-                subdivisor = 0;
-                effectiveBaudRate = 3000000;
-            } else if(baudRate >= 1750000) {
-                divisor = 1;
-                subdivisor = 0;
-                effectiveBaudRate = 2000000;
-            } else {
-                divisor = (24000000 << 1) / baudRate;
-                divisor = (divisor + 1) >> 1; // round
-                subdivisor = divisor & 0x07;
-                divisor >>= 3;
-                if (divisor > 0x3fff) // exceeds bit 13 at 183 baud
-                    throw new UnsupportedOperationException("Baud rate to low");
-                effectiveBaudRate = (24000000 << 1) / ((divisor << 3) + subdivisor);
-                effectiveBaudRate = (effectiveBaudRate +1) >> 1;
-            }
-            double baudRateError = Math.abs(1.0 - (effectiveBaudRate / (double)baudRate));
-            if(baudRateError >= 0.031) // can happen only > 1.5Mbaud
-                throw new UnsupportedOperationException(String.format("Baud rate deviation %.1f%% is higher than allowed 3%%", baudRateError*100));
-            int value = divisor;
-            int index = 0;
-            switch(subdivisor) {
-                case 0:                              break; // 16,15,14 = 000 - sub-integer divisor = 0
-                case 4: value |= 0x4000;             break; // 16,15,14 = 001 - sub-integer divisor = 0.5
-                case 2: value |= 0x8000;             break; // 16,15,14 = 010 - sub-integer divisor = 0.25
-                case 1: value |= 0xc000;             break; // 16,15,14 = 011 - sub-integer divisor = 0.125
-                case 3: value |= 0x0000; index |= 1; break; // 16,15,14 = 100 - sub-integer divisor = 0.375
-                case 5: value |= 0x4000; index |= 1; break; // 16,15,14 = 101 - sub-integer divisor = 0.625
-                case 6: value |= 0x8000; index |= 1; break; // 16,15,14 = 110 - sub-integer divisor = 0.75
-                case 7: value |= 0xc000; index |= 1; break; // 16,15,14 = 111 - sub-integer divisor = 0.875
-            }
-            if(baudRateWithPort) {
-                index <<= 8;
-                index |= mPortNumber+1;
-            }
-            Log.d(TAG, String.format("baud rate=%d, effective=%d, error=%.1f%%, value=0x%04x, index=0x%04x, divisor=%d, subdivisor=%d",
-                    baudRate, effectiveBaudRate, baudRateError*100, value, index, divisor, subdivisor));
-
-            int result = mConnection.controlTransfer(REQTYPE_HOST_TO_DEVICE, SET_BAUD_RATE_REQUEST,
-                    value, index, null, 0, USB_WRITE_TIMEOUT_MILLIS);
-            if (result != 0) {
-                throw new IOException("Setting baudrate failed: result=" + result);
-            }
-        }
-
-        @Override
-        public void setParameters(int baudRate, int dataBits, int stopBits, @Parity int parity) throws IOException {
-            if(baudRate <= 0) {
-                throw new IllegalArgumentException("Invalid baud rate: " + baudRate);
-            }
-            setBaudrate(baudRate);
-
-            int config = 0;
-            switch (dataBits) {
-                case DATABITS_5:
-                case DATABITS_6:
-                    throw new UnsupportedOperationException("Unsupported data bits: " + dataBits);
-                case DATABITS_7:
-                case DATABITS_8:
-                    config |= dataBits;
-                    break;
-                default:
-                    throw new IllegalArgumentException("Invalid data bits: " + dataBits);
-            }
-
-            switch (parity) {
-                case PARITY_NONE:
-                    break;
-                case PARITY_ODD:
-                    config |= 0x100;
-                    break;
-                case PARITY_EVEN:
-                    config |= 0x200;
-                    break;
-                case PARITY_MARK:
-                    config |= 0x300;
-                    break;
-                case PARITY_SPACE:
-                    config |= 0x400;
-                    break;
-                default:
-                    throw new IllegalArgumentException("Invalid parity: " + parity);
-            }
-
-            switch (stopBits) {
-                case STOPBITS_1:
-                    break;
-                case STOPBITS_1_5:
-                    throw new UnsupportedOperationException("Unsupported stop bits: 1.5");
-                case STOPBITS_2:
-                    config |= 0x1000;
-                    break;
-                default:
-                    throw new IllegalArgumentException("Invalid stop bits: " + stopBits);
-            }
-
-            int result = mConnection.controlTransfer(REQTYPE_HOST_TO_DEVICE, SET_DATA_REQUEST,
-                    config, mPortNumber+1,null, 0, USB_WRITE_TIMEOUT_MILLIS);
-            if (result != 0) {
-                throw new IOException("Setting parameters failed: result=" + result);
-            }
-            breakConfig = config;
-        }
-
-        private int getStatus() throws IOException {
-            byte[] data = new byte[2];
-            int result = mConnection.controlTransfer(REQTYPE_DEVICE_TO_HOST, GET_MODEM_STATUS_REQUEST,
-                    0, mPortNumber+1, data, data.length, USB_WRITE_TIMEOUT_MILLIS);
-            if (result != data.length) {
-                throw new IOException("Get modem status failed: result=" + result);
-            }
-            return data[0];
-        }
-
-        @Override
-        public boolean getCD() throws IOException {
-            return (getStatus() & MODEM_STATUS_CD) != 0;
-        }
-
-        @Override
-        public boolean getCTS() throws IOException {
-            return (getStatus() & MODEM_STATUS_CTS) != 0;
-        }
-
-        @Override
-        public boolean getDSR() throws IOException {
-            return (getStatus() & MODEM_STATUS_DSR) != 0;
-        }
-
-        @Override
-        public boolean getDTR() throws IOException {
-            return dtr;
-        }
-
-        @Override
-        public void setDTR(boolean value) throws IOException {
-            int result = mConnection.controlTransfer(REQTYPE_HOST_TO_DEVICE, MODEM_CONTROL_REQUEST,
-                    value ? MODEM_CONTROL_DTR_ENABLE : MODEM_CONTROL_DTR_DISABLE, mPortNumber+1, null, 0, USB_WRITE_TIMEOUT_MILLIS);
-            if (result != 0) {
-                throw new IOException("Set DTR failed: result=" + result);
-            }
-            dtr = value;
-        }
-
-        @Override
-        public boolean getRI() throws IOException {
-            return (getStatus() & MODEM_STATUS_RI) != 0;
-        }
-
-        @Override
-        public boolean getRTS() throws IOException {
-            return rts;
-        }
-
-        @Override
-        public void setRTS(boolean value) throws IOException {
-            int result = mConnection.controlTransfer(REQTYPE_HOST_TO_DEVICE, MODEM_CONTROL_REQUEST,
-                    value ? MODEM_CONTROL_RTS_ENABLE : MODEM_CONTROL_RTS_DISABLE, mPortNumber+1, null, 0, USB_WRITE_TIMEOUT_MILLIS);
-            if (result != 0) {
-                throw new IOException("Set DTR failed: result=" + result);
-            }
-            rts = value;
-        }
-
-        @Override
-        public EnumSet<ControlLine> getControlLines() throws IOException {
-            int status = getStatus();
-            EnumSet<ControlLine> set = EnumSet.noneOf(ControlLine.class);
-            if(rts) set.add(ControlLine.RTS);
-            if((status & MODEM_STATUS_CTS) != 0) set.add(ControlLine.CTS);
-            if(dtr) set.add(ControlLine.DTR);
-            if((status & MODEM_STATUS_DSR) != 0) set.add(ControlLine.DSR);
-            if((status & MODEM_STATUS_CD) != 0) set.add(ControlLine.CD);
-            if((status & MODEM_STATUS_RI) != 0) set.add(ControlLine.RI);
-            return set;
-        }
-
-        @Override
-        public EnumSet<ControlLine> getSupportedControlLines() throws IOException {
-            return EnumSet.allOf(ControlLine.class);
-        }
-
-        @Override
-        public void purgeHwBuffers(boolean purgeWriteBuffers, boolean purgeReadBuffers) throws IOException {
-            if (purgeWriteBuffers) {
-                int result = mConnection.controlTransfer(REQTYPE_HOST_TO_DEVICE, RESET_REQUEST,
-                        RESET_PURGE_RX, mPortNumber+1, null, 0, USB_WRITE_TIMEOUT_MILLIS);
-                if (result != 0) {
-                    throw new IOException("Purge write buffer failed: result=" + result);
-                }
-            }
-
-            if (purgeReadBuffers) {
-                int result = mConnection.controlTransfer(REQTYPE_HOST_TO_DEVICE, RESET_REQUEST,
-                        RESET_PURGE_TX, mPortNumber+1, null, 0, USB_WRITE_TIMEOUT_MILLIS);
-                if (result != 0) {
-                    throw new IOException("Purge read buffer failed: result=" + result);
-                }
-            }
-        }
-
-        @Override
-        public void setBreak(boolean value) throws IOException {
-            int config = breakConfig;
-            if(value) config |= 0x4000;
-            int result = mConnection.controlTransfer(REQTYPE_HOST_TO_DEVICE, SET_DATA_REQUEST,
-                    config, mPortNumber+1,null, 0, USB_WRITE_TIMEOUT_MILLIS);
-            if (result != 0) {
-                throw new IOException("Setting BREAK failed: result=" + result);
-            }
-        }
-
-        public void setLatencyTimer(int latencyTime) throws IOException {
-            int result = mConnection.controlTransfer(REQTYPE_HOST_TO_DEVICE, SET_LATENCY_TIMER_REQUEST,
-                    latencyTime, mPortNumber+1, null, 0, USB_WRITE_TIMEOUT_MILLIS);
-            if (result != 0) {
-                throw new IOException("Set latency timer failed: result=" + result);
-            }
-        }
-
-        public int getLatencyTimer() throws IOException {
-            byte[] data = new byte[1];
-            int result = mConnection.controlTransfer(REQTYPE_DEVICE_TO_HOST, GET_LATENCY_TIMER_REQUEST,
-                    0, mPortNumber+1, data, data.length, USB_WRITE_TIMEOUT_MILLIS);
-            if (result != data.length) {
-                throw new IOException("Get latency timer failed: result=" + result);
-            }
-            return data[0];
-        }
-
-    }
-
-    @SuppressWarnings({"unused"})
-    public static Map<Integer, int[]> getSupportedDevices() {
-        final Map<Integer, int[]> supportedDevices = new LinkedHashMap<>();
-        supportedDevices.put(UsbId.VENDOR_FTDI,
-                new int[] {
-                    UsbId.FTDI_FT232R,
-                    UsbId.FTDI_FT232H,
-                    UsbId.FTDI_FT2232H,
-                    UsbId.FTDI_FT4232H,
-                    UsbId.FTDI_FT231X,  // same ID for FT230X, FT231X, FT234XD
-                });
-        return supportedDevices;
-    }
-
-}

+ 0 - 106
Qt/Android/SmartPDU_QT/Android/src/com/hoho/android/usbserial/driver/GsmModemSerialDriver.java

@@ -1,106 +0,0 @@
-package com.hoho.android.usbserial.driver;
-
-import android.hardware.usb.UsbConstants;
-import android.hardware.usb.UsbDevice;
-import android.hardware.usb.UsbEndpoint;
-import android.hardware.usb.UsbInterface;
-import android.util.Log;
-
-import java.io.IOException;
-import java.util.Collections;
-import java.util.EnumSet;
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.Map;
-
-public class GsmModemSerialDriver implements UsbSerialDriver{
-
-    private final String TAG = GsmModemSerialDriver.class.getSimpleName();
-
-    private final UsbDevice mDevice;
-    private final UsbSerialPort mPort;
-
-    @Override
-    public UsbDevice getDevice() {
-        return mDevice;
-    }
-
-    @Override
-    public List<UsbSerialPort> getPorts() {
-        return Collections.singletonList(mPort);
-    }
-
-    public GsmModemSerialDriver(UsbDevice mDevice) {
-        this.mDevice = mDevice;
-        mPort = new GsmModemSerialPort(mDevice, 0);
-    }
-
-    public class GsmModemSerialPort extends CommonUsbSerialPort {
-
-        private UsbInterface mDataInterface;
-
-        public GsmModemSerialPort(UsbDevice device, int portNumber) {
-            super(device, portNumber);
-        }
-
-        @Override
-        protected void openInt() throws IOException {
-            Log.d(TAG, "claiming interfaces, count=" + mDevice.getInterfaceCount());
-            mDataInterface = mDevice.getInterface(0);
-            if (!mConnection.claimInterface(mDataInterface, true)) {
-                throw new IOException("Could not claim shared control/data interface");
-            }
-            Log.d(TAG, "endpoint count=" + mDataInterface.getEndpointCount());
-            for (int i = 0; i < mDataInterface.getEndpointCount(); ++i) {
-                UsbEndpoint ep = mDataInterface.getEndpoint(i);
-                if ((ep.getDirection() == UsbConstants.USB_DIR_IN) && (ep.getType() == UsbConstants.USB_ENDPOINT_XFER_BULK)) {
-                    mReadEndpoint = ep;
-                } else if ((ep.getDirection() == UsbConstants.USB_DIR_OUT) && (ep.getType() == UsbConstants.USB_ENDPOINT_XFER_BULK)) {
-                    mWriteEndpoint = ep;
-                }
-            }
-            initGsmModem();
-        }
-
-        @Override
-        protected void closeInt() {
-            try {
-                mConnection.releaseInterface(mDataInterface);
-            } catch(Exception ignored) {}
-
-        }
-
-        private int initGsmModem() throws IOException {
-            int len = mConnection.controlTransfer(
-                    0x21, 0x22, 0x01, 0, null, 0, 5000);
-            if(len < 0) {
-                throw new IOException("init failed");
-            }
-            return len;
-        }
-
-        @Override
-        public UsbSerialDriver getDriver() {
-            return GsmModemSerialDriver.this;
-        }
-
-        @Override
-        public void setParameters(int baudRate, int dataBits, int stopBits, int parity) throws IOException {
-            throw new UnsupportedOperationException();
-        }
-
-        @Override
-        public EnumSet<ControlLine> getSupportedControlLines() throws IOException {
-            return EnumSet.noneOf(ControlLine.class);
-        }
-    }
-
-    public static Map<Integer, int[]> getSupportedDevices() {
-        final Map<Integer, int[]> supportedDevices = new LinkedHashMap<>();
-        supportedDevices.put(UsbId.VENDOR_UNISOC, new int[]{
-                UsbId.FIBOCOM_L610,
-                UsbId.FIBOCOM_L612,
-        });
-        return supportedDevices;
-    }
-}

+ 0 - 102
Qt/Android/SmartPDU_QT/Android/src/com/hoho/android/usbserial/driver/ProbeTable.java

@@ -1,102 +0,0 @@
-/* Copyright 2011-2013 Google Inc.
- * Copyright 2013 mike wakerly <opensource@hoho.com>
- *
- * Project home page: https://github.com/mik3y/usb-serial-for-android
- */
-
-package com.hoho.android.usbserial.driver;
-
-import android.hardware.usb.UsbDevice;
-import android.util.Pair;
-
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-import java.util.LinkedHashMap;
-import java.util.Map;
-
-/**
- * Maps (vendor id, product id) pairs to the corresponding serial driver,
- * or invoke 'probe' method to check actual USB devices for matching interfaces.
- */
-public class ProbeTable {
-
-    private final Map<Pair<Integer, Integer>, Class<? extends UsbSerialDriver>> mVidPidProbeTable =
-            new LinkedHashMap<>();
-    private final Map<Method, Class<? extends UsbSerialDriver>> mMethodProbeTable = new LinkedHashMap<>();
-
-    /**
-     * Adds or updates a (vendor, product) pair in the table.
-     *
-     * @param vendorId the USB vendor id
-     * @param productId the USB product id
-     * @param driverClass the driver class responsible for this pair
-     * @return {@code this}, for chaining
-     */
-    public ProbeTable addProduct(int vendorId, int productId,
-            Class<? extends UsbSerialDriver> driverClass) {
-        mVidPidProbeTable.put(Pair.create(vendorId, productId), driverClass);
-        return this;
-    }
-
-    /**
-     * Internal method to add all supported products from
-     * {@code getSupportedProducts} static method.
-     *
-     * @param driverClass to be added
-     */
-    @SuppressWarnings("unchecked")
-    void addDriver(Class<? extends UsbSerialDriver> driverClass) {
-        Method method;
-
-        try {
-            method = driverClass.getMethod("getSupportedDevices");
-        } catch (SecurityException | NoSuchMethodException e) {
-            throw new RuntimeException(e);
-        }
-
-        final Map<Integer, int[]> devices;
-        try {
-            devices = (Map<Integer, int[]>) method.invoke(null);
-        } catch (IllegalArgumentException | IllegalAccessException | InvocationTargetException e) {
-            throw new RuntimeException(e);
-        }
-
-        for (Map.Entry<Integer, int[]> entry : devices.entrySet()) {
-            final int vendorId = entry.getKey();
-            for (int productId : entry.getValue()) {
-                addProduct(vendorId, productId, driverClass);
-            }
-        }
-
-        try {
-            method = driverClass.getMethod("probe", UsbDevice.class);
-            mMethodProbeTable.put(method, driverClass);
-        } catch (SecurityException | NoSuchMethodException ignored) {
-        }
-    }
-
-    /**
-     * Returns the driver for the given USB device, or {@code null} if no match.
-     *
-     * @param usbDevice the USB device to be probed
-     * @return the driver class matching this pair, or {@code null}
-     */
-    public Class<? extends UsbSerialDriver> findDriver(final UsbDevice usbDevice) {
-        final Pair<Integer, Integer> pair = Pair.create(usbDevice.getVendorId(), usbDevice.getProductId());
-        Class<? extends UsbSerialDriver> driverClass = mVidPidProbeTable.get(pair);
-        if (driverClass != null)
-            return driverClass;
-        for (Map.Entry<Method, Class<? extends UsbSerialDriver>> entry : mMethodProbeTable.entrySet()) {
-            try {
-                Method method = entry.getKey();
-                Object o = method.invoke(null, usbDevice);
-                if((boolean)o)
-                    return entry.getValue();
-            } catch (IllegalArgumentException | IllegalAccessException | InvocationTargetException e) {
-                throw new RuntimeException(e);
-            }
-        }
-        return null;
-    }
-
-}

+ 0 - 585
Qt/Android/SmartPDU_QT/Android/src/com/hoho/android/usbserial/driver/ProlificSerialDriver.java

@@ -1,585 +0,0 @@
-/*
- * Ported to usb-serial-for-android by Felix Hädicke <felixhaedicke@web.de>
- *
- * Based on the pyprolific driver written by Emmanuel Blot <emmanuel.blot@free.fr>
- * See https://github.com/eblot/pyftdi
- *
- * Project home page: https://github.com/mik3y/usb-serial-for-android
- */
-
-package com.hoho.android.usbserial.driver;
-
-import android.hardware.usb.UsbConstants;
-import android.hardware.usb.UsbDevice;
-import android.hardware.usb.UsbEndpoint;
-import android.hardware.usb.UsbInterface;
-import android.util.Log;
-
-import com.hoho.android.usbserial.BuildConfig;
-import com.hoho.android.usbserial.util.MonotonicClock;
-
-import java.io.IOException;
-import java.util.Collections;
-import java.util.EnumSet;
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.Map;
-
-public class ProlificSerialDriver implements UsbSerialDriver {
-
-    private final String TAG = ProlificSerialDriver.class.getSimpleName();
-
-    private final static int[] standardBaudRates = {
-            75, 150, 300, 600, 1200, 1800, 2400, 3600, 4800, 7200, 9600, 14400, 19200,
-            28800, 38400, 57600, 115200, 128000, 134400, 161280, 201600, 230400, 268800,
-            403200, 460800, 614400, 806400, 921600, 1228800, 2457600, 3000000, 6000000
-    };
-    protected enum DeviceType { DEVICE_TYPE_01, DEVICE_TYPE_T, DEVICE_TYPE_HX, DEVICE_TYPE_HXN }
-
-    private final UsbDevice mDevice;
-    private final UsbSerialPort mPort;
-
-    public ProlificSerialDriver(UsbDevice device) {
-        mDevice = device;
-        mPort = new ProlificSerialPort(mDevice, 0);
-    }
-
-    @Override
-    public List<UsbSerialPort> getPorts() {
-        return Collections.singletonList(mPort);
-    }
-
-    @Override
-    public UsbDevice getDevice() {
-        return mDevice;
-    }
-
-    class ProlificSerialPort extends CommonUsbSerialPort {
-
-        private static final int USB_READ_TIMEOUT_MILLIS = 1000;
-        private static final int USB_WRITE_TIMEOUT_MILLIS = 5000;
-
-        private static final int USB_RECIP_INTERFACE = 0x01;
-
-        private static final int VENDOR_READ_REQUEST = 0x01;
-        private static final int VENDOR_WRITE_REQUEST = 0x01;
-        private static final int VENDOR_READ_HXN_REQUEST = 0x81;
-        private static final int VENDOR_WRITE_HXN_REQUEST = 0x80;
-
-        private static final int VENDOR_OUT_REQTYPE = UsbConstants.USB_DIR_OUT | UsbConstants.USB_TYPE_VENDOR;
-        private static final int VENDOR_IN_REQTYPE = UsbConstants.USB_DIR_IN | UsbConstants.USB_TYPE_VENDOR;
-        private static final int CTRL_OUT_REQTYPE = UsbConstants.USB_DIR_OUT | UsbConstants.USB_TYPE_CLASS | USB_RECIP_INTERFACE;
-
-        private static final int WRITE_ENDPOINT = 0x02;
-        private static final int READ_ENDPOINT = 0x83;
-        private static final int INTERRUPT_ENDPOINT = 0x81;
-
-        private static final int RESET_HXN_REQUEST = 0x07;
-        private static final int FLUSH_RX_REQUEST = 0x08;
-        private static final int FLUSH_TX_REQUEST = 0x09;
-        private static final int SET_LINE_REQUEST = 0x20; // same as CDC SET_LINE_CODING
-        private static final int SET_CONTROL_REQUEST = 0x22; // same as CDC SET_CONTROL_LINE_STATE
-        private static final int SEND_BREAK_REQUEST = 0x23; // same as CDC SEND_BREAK
-        private static final int GET_CONTROL_HXN_REQUEST = 0x80;
-        private static final int GET_CONTROL_REQUEST = 0x87;
-        private static final int STATUS_NOTIFICATION = 0xa1; // similar to CDC SERIAL_STATE but different length
-
-        /* RESET_HXN_REQUEST */
-        private static final int RESET_HXN_RX_PIPE = 1;
-        private static final int RESET_HXN_TX_PIPE = 2;
-
-        /* SET_CONTROL_REQUEST */
-        private static final int CONTROL_DTR = 0x01;
-        private static final int CONTROL_RTS = 0x02;
-
-        /* GET_CONTROL_REQUEST */
-        private static final int GET_CONTROL_FLAG_CD = 0x02;
-        private static final int GET_CONTROL_FLAG_DSR = 0x04;
-        private static final int GET_CONTROL_FLAG_RI = 0x01;
-        private static final int GET_CONTROL_FLAG_CTS = 0x08;
-
-        /* GET_CONTROL_HXN_REQUEST */
-        private static final int GET_CONTROL_HXN_FLAG_CD = 0x40;
-        private static final int GET_CONTROL_HXN_FLAG_DSR = 0x20;
-        private static final int GET_CONTROL_HXN_FLAG_RI = 0x80;
-        private static final int GET_CONTROL_HXN_FLAG_CTS = 0x08;
-
-        /* interrupt endpoint read */
-        private static final int STATUS_FLAG_CD = 0x01;
-        private static final int STATUS_FLAG_DSR = 0x02;
-        private static final int STATUS_FLAG_RI = 0x08;
-        private static final int STATUS_FLAG_CTS = 0x80;
-
-        private static final int STATUS_BUFFER_SIZE = 10;
-        private static final int STATUS_BYTE_IDX = 8;
-
-        protected DeviceType mDeviceType = DeviceType.DEVICE_TYPE_HX;
-        private UsbEndpoint mInterruptEndpoint;
-        private int mControlLinesValue = 0;
-        private int mBaudRate = -1, mDataBits = -1, mStopBits = -1, mParity = -1;
-
-        private int mStatus = 0;
-        private volatile Thread mReadStatusThread = null;
-        private final Object mReadStatusThreadLock = new Object();
-        private boolean mStopReadStatusThread = false;
-        private Exception mReadStatusException = null;
-
-
-        public ProlificSerialPort(UsbDevice device, int portNumber) {
-            super(device, portNumber);
-        }
-
-        @Override
-        public UsbSerialDriver getDriver() {
-            return ProlificSerialDriver.this;
-        }
-
-        private byte[] inControlTransfer(int requestType, int request, int value, int index, int length) throws IOException {
-            byte[] buffer = new byte[length];
-            int result = mConnection.controlTransfer(requestType, request, value, index, buffer, length, USB_READ_TIMEOUT_MILLIS);
-            if (result != length) {
-                throw new IOException(String.format("ControlTransfer %s 0x%x failed: %d",mDeviceType.name(), value, result));
-            }
-            return buffer;
-        }
-
-        private void outControlTransfer(int requestType, int request, int value, int index, byte[] data) throws IOException {
-            int length = (data == null) ? 0 : data.length;
-            int result = mConnection.controlTransfer(requestType, request, value, index, data, length, USB_WRITE_TIMEOUT_MILLIS);
-            if (result != length) {
-                throw new IOException( String.format("ControlTransfer %s 0x%x failed: %d", mDeviceType.name(), value, result));
-            }
-        }
-
-        private byte[] vendorIn(int value, int index, int length) throws IOException {
-            int request = (mDeviceType == DeviceType.DEVICE_TYPE_HXN) ? VENDOR_READ_HXN_REQUEST : VENDOR_READ_REQUEST;
-            return inControlTransfer(VENDOR_IN_REQTYPE, request, value, index, length);
-        }
-
-        private void vendorOut(int value, int index, byte[] data) throws IOException {
-            int request = (mDeviceType == DeviceType.DEVICE_TYPE_HXN) ? VENDOR_WRITE_HXN_REQUEST : VENDOR_WRITE_REQUEST;
-            outControlTransfer(VENDOR_OUT_REQTYPE, request, value, index, data);
-        }
-
-        private void resetDevice() throws IOException {
-            purgeHwBuffers(true, true);
-        }
-
-        private void ctrlOut(int request, int value, int index, byte[] data) throws IOException {
-            outControlTransfer(CTRL_OUT_REQTYPE, request, value, index, data);
-        }
-
-        private boolean testHxStatus() {
-            try {
-                inControlTransfer(VENDOR_IN_REQTYPE, VENDOR_READ_REQUEST, 0x8080, 0, 1);
-                return true;
-            } catch(IOException ignored) {
-                return false;
-            }
-        }
-
-        private void doBlackMagic() throws IOException {
-            if (mDeviceType == DeviceType.DEVICE_TYPE_HXN)
-                return;
-            vendorIn(0x8484, 0, 1);
-            vendorOut(0x0404, 0, null);
-            vendorIn(0x8484, 0, 1);
-            vendorIn(0x8383, 0, 1);
-            vendorIn(0x8484, 0, 1);
-            vendorOut(0x0404, 1, null);
-            vendorIn(0x8484, 0, 1);
-            vendorIn(0x8383, 0, 1);
-            vendorOut(0, 1, null);
-            vendorOut(1, 0, null);
-            vendorOut(2, (mDeviceType == DeviceType.DEVICE_TYPE_01) ? 0x24 : 0x44, null);
-        }
-
-        private void setControlLines(int newControlLinesValue) throws IOException {
-            ctrlOut(SET_CONTROL_REQUEST, newControlLinesValue, 0, null);
-            mControlLinesValue = newControlLinesValue;
-        }
-
-        private void readStatusThreadFunction() {
-            try {
-                byte[] buffer = new byte[STATUS_BUFFER_SIZE];
-                while (!mStopReadStatusThread) {
-                    long endTime = MonotonicClock.millis() + 500;
-                    int readBytesCount = mConnection.bulkTransfer(mInterruptEndpoint, buffer, STATUS_BUFFER_SIZE, 500);
-                    if(readBytesCount == -1)
-                        testConnection(MonotonicClock.millis() < endTime);
-                    if (readBytesCount > 0) {
-                        if (readBytesCount != STATUS_BUFFER_SIZE) {
-                            throw new IOException("Invalid status notification, expected " + STATUS_BUFFER_SIZE + " bytes, got " + readBytesCount);
-                        } else if(buffer[0] != (byte)STATUS_NOTIFICATION ) {
-                            throw new IOException("Invalid status notification, expected " + STATUS_NOTIFICATION + " request, got " + buffer[0]);
-                        } else {
-                            mStatus = buffer[STATUS_BYTE_IDX] & 0xff;
-                        }
-                    }
-                }
-            } catch (Exception e) {
-                if (isOpen())
-                    mReadStatusException = e;
-            }
-            //Log.d(TAG, "end control line status thread " + mStopReadStatusThread + " " + (mReadStatusException == null ? "-" : mReadStatusException.getMessage()));
-        }
-
-        private int getStatus() throws IOException {
-            if ((mReadStatusThread == null) && (mReadStatusException == null)) {
-                synchronized (mReadStatusThreadLock) {
-                    if (mReadStatusThread == null) {
-                        mStatus = 0;
-                        if(mDeviceType == DeviceType.DEVICE_TYPE_HXN) {
-                            byte[] data = vendorIn(GET_CONTROL_HXN_REQUEST, 0, 1);
-                            if ((data[0] & GET_CONTROL_HXN_FLAG_CTS) == 0) mStatus |= STATUS_FLAG_CTS;
-                            if ((data[0] & GET_CONTROL_HXN_FLAG_DSR) == 0) mStatus |= STATUS_FLAG_DSR;
-                            if ((data[0] & GET_CONTROL_HXN_FLAG_CD) == 0) mStatus |= STATUS_FLAG_CD;
-                            if ((data[0] & GET_CONTROL_HXN_FLAG_RI) == 0) mStatus |= STATUS_FLAG_RI;
-                        } else {
-                            byte[] data = vendorIn(GET_CONTROL_REQUEST, 0, 1);
-                            if ((data[0] & GET_CONTROL_FLAG_CTS) == 0) mStatus |= STATUS_FLAG_CTS;
-                            if ((data[0] & GET_CONTROL_FLAG_DSR) == 0) mStatus |= STATUS_FLAG_DSR;
-                            if ((data[0] & GET_CONTROL_FLAG_CD) == 0) mStatus |= STATUS_FLAG_CD;
-                            if ((data[0] & GET_CONTROL_FLAG_RI) == 0) mStatus |= STATUS_FLAG_RI;
-                        }
-                        //Log.d(TAG, "start control line status thread " + mStatus);
-                        mReadStatusThread = new Thread(this::readStatusThreadFunction);
-                        mReadStatusThread.setDaemon(true);
-                        mReadStatusThread.start();
-                    }
-                }
-            }
-
-            /* throw and clear an exception which occurred in the status read thread */
-            Exception readStatusException = mReadStatusException;
-            if (mReadStatusException != null) {
-                mReadStatusException = null;
-                throw new IOException(readStatusException);
-            }
-
-            return mStatus;
-        }
-
-        private boolean testStatusFlag(int flag) throws IOException {
-            return ((getStatus() & flag) == flag);
-        }
-
-        @Override
-        public void openInt() throws IOException {
-            UsbInterface usbInterface = mDevice.getInterface(0);
-
-            if (!mConnection.claimInterface(usbInterface, true)) {
-                throw new IOException("Error claiming Prolific interface 0");
-            }
-
-            for (int i = 0; i < usbInterface.getEndpointCount(); ++i) {
-                UsbEndpoint currentEndpoint = usbInterface.getEndpoint(i);
-
-                switch (currentEndpoint.getAddress()) {
-                case READ_ENDPOINT:
-                    mReadEndpoint = currentEndpoint;
-                    break;
-
-                case WRITE_ENDPOINT:
-                    mWriteEndpoint = currentEndpoint;
-                    break;
-
-                case INTERRUPT_ENDPOINT:
-                    mInterruptEndpoint = currentEndpoint;
-                    break;
-                }
-            }
-
-            byte[] rawDescriptors = mConnection.getRawDescriptors();
-            if(rawDescriptors == null || rawDescriptors.length < 14) {
-                throw new IOException("Could not get device descriptors");
-            }
-            int usbVersion = (rawDescriptors[3] << 8) + rawDescriptors[2];
-            int deviceVersion = (rawDescriptors[13] << 8) + rawDescriptors[12];
-            byte maxPacketSize0 = rawDescriptors[7];
-            if (mDevice.getDeviceClass() == 0x02 || maxPacketSize0 != 64) {
-                mDeviceType = DeviceType.DEVICE_TYPE_01;
-            } else if(usbVersion == 0x200) {
-                if(deviceVersion == 0x300 && testHxStatus()) {
-                    mDeviceType = DeviceType.DEVICE_TYPE_T; // TA
-                } else if(deviceVersion == 0x500 && testHxStatus()) {
-                    mDeviceType = DeviceType.DEVICE_TYPE_T; // TB
-                } else {
-                    mDeviceType = DeviceType.DEVICE_TYPE_HXN;
-                }
-            } else {
-                mDeviceType = DeviceType.DEVICE_TYPE_HX;
-            }
-            Log.d(TAG, String.format("usbVersion=%x, deviceVersion=%x, deviceClass=%d, packetSize=%d => deviceType=%s",
-                    usbVersion, deviceVersion, mDevice.getDeviceClass(), maxPacketSize0, mDeviceType.name()));
-            resetDevice();
-            doBlackMagic();
-            setControlLines(mControlLinesValue);
-        }
-
-        @Override
-        public void closeInt() {
-            try {
-                synchronized (mReadStatusThreadLock) {
-                    if (mReadStatusThread != null) {
-                        try {
-                            mStopReadStatusThread = true;
-                            mReadStatusThread.join();
-                        } catch (Exception e) {
-                            Log.w(TAG, "An error occured while waiting for status read thread", e);
-                        }
-                        mStopReadStatusThread = false;
-                        mReadStatusThread = null;
-                        mReadStatusException = null;
-                    }
-                }
-                resetDevice();
-            } catch(Exception ignored) {}
-            try {
-                mConnection.releaseInterface(mDevice.getInterface(0));
-            } catch(Exception ignored) {}
-        }
-
-        private int filterBaudRate(int baudRate) {
-            if(BuildConfig.DEBUG && (baudRate & (3<<29)) == (1<<29)) {
-                return baudRate & ~(1<<29); // for testing purposes accept without further checks
-            }
-            if (baudRate <= 0) {
-                throw new IllegalArgumentException("Invalid baud rate: " + baudRate);
-            }
-            if (mDeviceType == DeviceType.DEVICE_TYPE_HXN) {
-                return baudRate;
-            }
-            for(int br : standardBaudRates) {
-                if (br == baudRate) {
-                    return baudRate;
-                }
-            }
-            /*
-             * Formula taken from Linux + FreeBSD.
-             *
-             * For TA+TB devices
-             *   baudrate = baseline / (mantissa * 2^exponent)
-             * where
-             *   mantissa = buf[10:0]
-             *   exponent = buf[15:13 16]
-             *
-             * For other devices
-             *   baudrate = baseline / (mantissa * 4^exponent)
-             * where
-             *   mantissa = buf[8:0]
-             *   exponent = buf[11:9]
-             *
-             */
-            int baseline, mantissa, exponent, buf, effectiveBaudRate;
-            baseline = 12000000 * 32;
-            mantissa = baseline / baudRate;
-            if (mantissa == 0) { // > unrealistic 384 MBaud
-                throw new UnsupportedOperationException("Baud rate to high");
-            }
-            exponent = 0;
-            if (mDeviceType == DeviceType.DEVICE_TYPE_T) {
-                while (mantissa >= 2048) {
-                    if (exponent < 15) {
-                        mantissa >>= 1;    /* divide by 2 */
-                        exponent++;
-                    } else { // < 7 baud
-                        throw new UnsupportedOperationException("Baud rate to low");
-                    }
-                }
-                buf = mantissa + ((exponent & ~1) << 12) + ((exponent & 1) << 16) + (1 << 31);
-                effectiveBaudRate = (baseline / mantissa) >> exponent;
-            } else {
-                while (mantissa >= 512) {
-                    if (exponent < 7) {
-                        mantissa >>= 2;    /* divide by 4 */
-                        exponent++;
-                    } else { // < 45.8 baud
-                        throw new UnsupportedOperationException("Baud rate to low");
-                    }
-                }
-                buf = mantissa + (exponent << 9) + (1 << 31);
-                effectiveBaudRate = (baseline / mantissa) >> (exponent << 1);
-            }
-            double baudRateError = Math.abs(1.0 - (effectiveBaudRate / (double)baudRate));
-            if(baudRateError >= 0.031) // > unrealistic 11.6 Mbaud
-                throw new UnsupportedOperationException(String.format("Baud rate deviation %.1f%% is higher than allowed 3%%", baudRateError*100));
-
-            Log.d(TAG, String.format("baud rate=%d, effective=%d, error=%.1f%%, value=0x%08x, mantissa=%d, exponent=%d",
-                    baudRate, effectiveBaudRate, baudRateError*100, buf, mantissa, exponent));
-            return buf;
-        }
-
-        @Override
-        public void setParameters(int baudRate, int dataBits, int stopBits, @Parity int parity) throws IOException {
-            baudRate = filterBaudRate(baudRate);
-            if ((mBaudRate == baudRate) && (mDataBits == dataBits)
-                    && (mStopBits == stopBits) && (mParity == parity)) {
-                // Make sure no action is performed if there is nothing to change
-                return;
-            }
-
-            byte[] lineRequestData = new byte[7];
-            lineRequestData[0] = (byte) (baudRate & 0xff);
-            lineRequestData[1] = (byte) ((baudRate >> 8) & 0xff);
-            lineRequestData[2] = (byte) ((baudRate >> 16) & 0xff);
-            lineRequestData[3] = (byte) ((baudRate >> 24) & 0xff);
-
-            switch (stopBits) {
-            case STOPBITS_1:
-                lineRequestData[4] = 0;
-                break;
-            case STOPBITS_1_5:
-                lineRequestData[4] = 1;
-                break;
-            case STOPBITS_2:
-                lineRequestData[4] = 2;
-                break;
-            default:
-                throw new IllegalArgumentException("Invalid stop bits: " + stopBits);
-            }
-
-            switch (parity) {
-            case PARITY_NONE:
-                lineRequestData[5] = 0;
-                break;
-            case PARITY_ODD:
-                lineRequestData[5] = 1;
-                break;
-            case PARITY_EVEN:
-                lineRequestData[5] = 2;
-                break;
-            case PARITY_MARK:
-                lineRequestData[5] = 3;
-                break;
-            case PARITY_SPACE:
-                lineRequestData[5] = 4;
-                break;
-            default:
-                throw new IllegalArgumentException("Invalid parity: " + parity);
-            }
-
-            if(dataBits < DATABITS_5 || dataBits > DATABITS_8) {
-                throw new IllegalArgumentException("Invalid data bits: " + dataBits);
-            }
-            lineRequestData[6] = (byte) dataBits;
-
-            ctrlOut(SET_LINE_REQUEST, 0, 0, lineRequestData);
-
-            resetDevice();
-
-            mBaudRate = baudRate;
-            mDataBits = dataBits;
-            mStopBits = stopBits;
-            mParity = parity;
-        }
-
-        @Override
-        public boolean getCD() throws IOException {
-            return testStatusFlag(STATUS_FLAG_CD);
-        }
-
-        @Override
-        public boolean getCTS() throws IOException {
-            return testStatusFlag(STATUS_FLAG_CTS);
-        }
-
-        @Override
-        public boolean getDSR() throws IOException {
-            return testStatusFlag(STATUS_FLAG_DSR);
-        }
-
-        @Override
-        public boolean getDTR() throws IOException {
-            return (mControlLinesValue & CONTROL_DTR) != 0;
-        }
-
-        @Override
-        public void setDTR(boolean value) throws IOException {
-            int newControlLinesValue;
-            if (value) {
-                newControlLinesValue = mControlLinesValue | CONTROL_DTR;
-            } else {
-                newControlLinesValue = mControlLinesValue & ~CONTROL_DTR;
-            }
-            setControlLines(newControlLinesValue);
-        }
-
-        @Override
-        public boolean getRI() throws IOException {
-            return testStatusFlag(STATUS_FLAG_RI);
-        }
-
-        @Override
-        public boolean getRTS() throws IOException {
-            return (mControlLinesValue & CONTROL_RTS) != 0;
-        }
-
-        @Override
-        public void setRTS(boolean value) throws IOException {
-            int newControlLinesValue;
-            if (value) {
-                newControlLinesValue = mControlLinesValue | CONTROL_RTS;
-            } else {
-                newControlLinesValue = mControlLinesValue & ~CONTROL_RTS;
-            }
-            setControlLines(newControlLinesValue);
-        }
-
-
-        @Override
-        public EnumSet<ControlLine> getControlLines() throws IOException {
-            int status = getStatus();
-            EnumSet<ControlLine> set = EnumSet.noneOf(ControlLine.class);
-            if((mControlLinesValue & CONTROL_RTS) != 0) set.add(ControlLine.RTS);
-            if((status & STATUS_FLAG_CTS) != 0) set.add(ControlLine.CTS);
-            if((mControlLinesValue & CONTROL_DTR) != 0) set.add(ControlLine.DTR);
-            if((status & STATUS_FLAG_DSR) != 0) set.add(ControlLine.DSR);
-            if((status & STATUS_FLAG_CD) != 0) set.add(ControlLine.CD);
-            if((status & STATUS_FLAG_RI) != 0) set.add(ControlLine.RI);
-            return set;
-        }
-
-        @Override
-        public EnumSet<ControlLine> getSupportedControlLines() throws IOException {
-            return EnumSet.allOf(ControlLine.class);
-        }
-
-        @Override
-        public void purgeHwBuffers(boolean purgeWriteBuffers, boolean purgeReadBuffers) throws IOException {
-            if (mDeviceType == DeviceType.DEVICE_TYPE_HXN) {
-                int index = 0;
-                if(purgeWriteBuffers) index |= RESET_HXN_RX_PIPE;
-                if(purgeReadBuffers) index |= RESET_HXN_TX_PIPE;
-                if(index != 0)
-                    vendorOut(RESET_HXN_REQUEST, index, null);
-            } else {
-                if (purgeWriteBuffers)
-                    vendorOut(FLUSH_RX_REQUEST, 0, null);
-                if (purgeReadBuffers)
-                    vendorOut(FLUSH_TX_REQUEST, 0, null);
-            }
-        }
-
-        @Override
-        public void setBreak(boolean value) throws IOException {
-            ctrlOut(SEND_BREAK_REQUEST, value ? 0xffff : 0, 0, null);
-        }
-    }
-
-    @SuppressWarnings({"unused"})
-    public static Map<Integer, int[]> getSupportedDevices() {
-        final Map<Integer, int[]> supportedDevices = new LinkedHashMap<>();
-        supportedDevices.put(UsbId.VENDOR_PROLIFIC,
-                new int[] {
-                        UsbId.PROLIFIC_PL2303,
-                        UsbId.PROLIFIC_PL2303GC,
-                        UsbId.PROLIFIC_PL2303GB,
-                        UsbId.PROLIFIC_PL2303GT,
-                        UsbId.PROLIFIC_PL2303GL,
-                        UsbId.PROLIFIC_PL2303GE,
-                        UsbId.PROLIFIC_PL2303GS,
-                });
-        return supportedDevices;
-    }
-}

+ 0 - 15
Qt/Android/SmartPDU_QT/Android/src/com/hoho/android/usbserial/driver/SerialTimeoutException.java

@@ -1,15 +0,0 @@
-package com.hoho.android.usbserial.driver;
-
-import java.io.InterruptedIOException;
-
-/**
- * Signals that a timeout has occurred on serial write.
- * Similar to SocketTimeoutException.
- *
- * {@see InterruptedIOException#bytesTransferred} may contain bytes transferred
- */
-public class SerialTimeoutException extends InterruptedIOException {
-    public SerialTimeoutException(String s) {
-        super(s);
-    }
-}

+ 0 - 56
Qt/Android/SmartPDU_QT/Android/src/com/hoho/android/usbserial/driver/UsbId.java

@@ -1,56 +0,0 @@
-/* Copyright 2011-2013 Google Inc.
- * Copyright 2013 mike wakerly <opensource@hoho.com>
- *
- * Project home page: https://github.com/mik3y/usb-serial-for-android
- */
-
-package com.hoho.android.usbserial.driver;
-
-/**
- * Registry of USB vendor/product ID constants.
- *
- * Culled from various sources; see
- * <a href="http://www.linux-usb.org/usb.ids">usb.ids</a> for one listing.
- *
- * @author mike wakerly (opensource@hoho.com)
- */
-public final class UsbId {
-
-    public static final int VENDOR_FTDI = 0x0403;
-    public static final int FTDI_FT232R = 0x6001;
-    public static final int FTDI_FT2232H = 0x6010;
-    public static final int FTDI_FT4232H = 0x6011;
-    public static final int FTDI_FT232H = 0x6014;
-    public static final int FTDI_FT231X = 0x6015; // same ID for FT230X, FT231X, FT234XD
-
-    public static final int VENDOR_SILABS = 0x10c4;
-    public static final int SILABS_CP2102 = 0xea60; // same ID for CP2101, CP2103, CP2104, CP2109
-    public static final int SILABS_CP2105 = 0xea70;
-    public static final int SILABS_CP2108 = 0xea71;
-
-    public static final int VENDOR_PROLIFIC = 0x067b;
-    public static final int PROLIFIC_PL2303 = 0x2303;   // device type 01, T, HX
-    public static final int PROLIFIC_PL2303GC = 0x23a3; // device type HXN
-    public static final int PROLIFIC_PL2303GB = 0x23b3; // "
-    public static final int PROLIFIC_PL2303GT = 0x23c3; // "
-    public static final int PROLIFIC_PL2303GL = 0x23d3; // "
-    public static final int PROLIFIC_PL2303GE = 0x23e3; // "
-    public static final int PROLIFIC_PL2303GS = 0x23f3; // "
-
-    public static final int VENDOR_GOOGLE = 0x18d1;
-    public static final int GOOGLE_CR50 = 0x5014;
-
-    public static final int VENDOR_QINHENG = 0x1a86;
-    public static final int QINHENG_CH340 = 0x7523;
-    public static final int QINHENG_CH341A = 0x5523;
-
-    public static final int VENDOR_UNISOC = 0x1782;
-    public static final int FIBOCOM_L610 = 0x4D10;
-    public static final int FIBOCOM_L612 = 0x4D12;
-
-
-    private UsbId() {
-        throw new IllegalAccessError("Non-instantiable class");
-    }
-
-}

+ 0 - 38
Qt/Android/SmartPDU_QT/Android/src/com/hoho/android/usbserial/driver/UsbSerialDriver.java

@@ -1,38 +0,0 @@
-/* Copyright 2011-2013 Google Inc.
- * Copyright 2013 mike wakerly <opensource@hoho.com>
- *
- * Project home page: https://github.com/mik3y/usb-serial-for-android
- */
-
-package com.hoho.android.usbserial.driver;
-
-import android.hardware.usb.UsbDevice;
-
-import java.util.List;
-
-public interface UsbSerialDriver {
-
-    /*
-     * Additional interface properties. Invoked thru reflection.
-     *
-        UsbSerialDriver(UsbDevice device);                  // constructor with device
-        static Map<Integer, int[]> getSupportedDevices();
-        static boolean probe(UsbDevice device);             // optional
-     */
-
-
-    /**
-     * Returns the raw {@link UsbDevice} backing this port.
-     *
-     * @return the device
-     */
-    UsbDevice getDevice();
-
-    /**
-     * Returns all available ports for this device. This list must have at least
-     * one entry.
-     *
-     * @return the ports
-     */
-    List<UsbSerialPort> getPorts();
-}

+ 0 - 284
Qt/Android/SmartPDU_QT/Android/src/com/hoho/android/usbserial/driver/UsbSerialPort.java

@@ -1,284 +0,0 @@
-/* Copyright 2011-2013 Google Inc.
- * Copyright 2013 mike wakerly <opensource@hoho.com>
- *
- * Project home page: https://github.com/mik3y/usb-serial-for-android
- */
-
-package com.hoho.android.usbserial.driver;
-
-import android.hardware.usb.UsbDevice;
-import android.hardware.usb.UsbDeviceConnection;
-import android.hardware.usb.UsbEndpoint;
-import android.hardware.usb.UsbManager;
-
-import androidx.annotation.IntDef;
-
-import java.io.Closeable;
-import java.io.IOException;
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.util.EnumSet;
-
-/**
- * Interface for a single serial port.
- *
- * @author mike wakerly (opensource@hoho.com)
- */
-public interface UsbSerialPort extends Closeable {
-
-    /** 5 data bits. */
-    int DATABITS_5 = 5;
-    /** 6 data bits. */
-    int DATABITS_6 = 6;
-    /** 7 data bits. */
-    int DATABITS_7 = 7;
-    /** 8 data bits. */
-    int DATABITS_8 = 8;
-
-    /** Values for setParameters(..., parity) */
-    @Retention(RetentionPolicy.SOURCE)
-    @IntDef({PARITY_NONE, PARITY_ODD, PARITY_EVEN, PARITY_MARK, PARITY_SPACE})
-    @interface Parity {}
-    /** No parity. */
-    int PARITY_NONE = 0;
-    /** Odd parity. */
-    int PARITY_ODD = 1;
-    /** Even parity. */
-    int PARITY_EVEN = 2;
-    /** Mark parity. */
-    int PARITY_MARK = 3;
-    /** Space parity. */
-    int PARITY_SPACE = 4;
-
-    /** 1 stop bit. */
-    int STOPBITS_1 = 1;
-    /** 1.5 stop bits. */
-    int STOPBITS_1_5 = 3;
-    /** 2 stop bits. */
-    int STOPBITS_2 = 2;
-
-    /** Values for get[Supported]ControlLines() */
-    enum ControlLine { RTS, CTS,  DTR, DSR,  CD, RI }
-
-    /**
-     * Returns the driver used by this port.
-     */
-    UsbSerialDriver getDriver();
-
-    /**
-     * Returns the currently-bound USB device.
-     */
-    UsbDevice getDevice();
-
-    /**
-     * Port number within driver.
-     */
-    int getPortNumber();
-
-    /**
-     * Returns the write endpoint.
-     * @return write endpoint
-     */
-    UsbEndpoint getWriteEndpoint();
-
-    /**
-     * Returns the read endpoint.
-     * @return read endpoint
-     */
-    UsbEndpoint getReadEndpoint();
-
-    /**
-     * The serial number of the underlying UsbDeviceConnection, or {@code null}.
-     *
-     * @return value from {@link UsbDeviceConnection#getSerial()}
-     * @throws SecurityException starting with target SDK 29 (Android 10) if permission for USB device is not granted
-     */
-    String getSerial();
-
-    /**
-     * Opens and initializes the port. Upon success, caller must ensure that
-     * {@link #close()} is eventually called.
-     *
-     * @param connection an open device connection, acquired with
-     *                   {@link UsbManager#openDevice(android.hardware.usb.UsbDevice)}
-     * @throws IOException on error opening or initializing the port.
-     */
-    void open(UsbDeviceConnection connection) throws IOException;
-
-    /**
-     * Closes the port and {@link UsbDeviceConnection}
-     *
-     * @throws IOException on error closing the port.
-     */
-    void close() throws IOException;
-
-    /**
-     * Reads as many bytes as possible into the destination buffer.
-     *
-     * @param dest the destination byte buffer
-     * @param timeout the timeout for reading in milliseconds, 0 is infinite
-     * @return the actual number of bytes read
-     * @throws IOException if an error occurred during reading
-     */
-    int read(final byte[] dest, final int timeout) throws IOException;
-
-    /**
-     * Reads bytes with specified length into the destination buffer.
-     *
-     * @param dest the destination byte buffer
-     * @param length the maximum length of the data to read
-     * @param timeout the timeout for reading in milliseconds, 0 is infinite
-     * @return the actual number of bytes read
-     * @throws IOException if an error occurred during reading
-     */
-    int read(final byte[] dest, int length, final int timeout) throws IOException;
-
-    /**
-     * Writes as many bytes as possible from the source buffer.
-     *
-     * @param src the source byte buffer
-     * @param timeout the timeout for writing in milliseconds, 0 is infinite
-     * @throws SerialTimeoutException if timeout reached before sending all data.
-     *                                ex.bytesTransferred may contain bytes transferred
-     * @throws IOException if an error occurred during writing
-     */
-    void write(final byte[] src, final int timeout) throws IOException;
-
-    /**
-     * Writes bytes with specified length from the source buffer.
-     *
-     * @param src the source byte buffer
-     * @param length the length of the data to write
-     * @param timeout the timeout for writing in milliseconds, 0 is infinite
-     * @throws SerialTimeoutException if timeout reached before sending all data.
-     *                                ex.bytesTransferred may contain bytes transferred
-     * @throws IOException if an error occurred during writing
-     */
-    void write(final byte[] src, int length, final int timeout) throws IOException;
-
-    /**
-     * Sets various serial port parameters.
-     *
-     * @param baudRate baud rate as an integer, for example {@code 115200}.
-     * @param dataBits one of {@link #DATABITS_5}, {@link #DATABITS_6},
-     *                 {@link #DATABITS_7}, or {@link #DATABITS_8}.
-     * @param stopBits one of {@link #STOPBITS_1}, {@link #STOPBITS_1_5}, or {@link #STOPBITS_2}.
-     * @param parity one of {@link #PARITY_NONE}, {@link #PARITY_ODD},
-     *               {@link #PARITY_EVEN}, {@link #PARITY_MARK}, or {@link #PARITY_SPACE}.
-     * @throws IOException on error setting the port parameters
-     * @throws UnsupportedOperationException if values are not supported by a specific device
-     */
-    void setParameters(int baudRate, int dataBits, int stopBits, @Parity int parity) throws IOException;
-
-    /**
-     * Gets the CD (Carrier Detect) bit from the underlying UART.
-     *
-     * @return the current state
-     * @throws IOException if an error occurred during reading
-     * @throws UnsupportedOperationException if not supported
-     */
-    boolean getCD() throws IOException;
-
-    /**
-     * Gets the CTS (Clear To Send) bit from the underlying UART.
-     *
-     * @return the current state
-     * @throws IOException if an error occurred during reading
-     * @throws UnsupportedOperationException if not supported
-     */
-    boolean getCTS() throws IOException;
-
-    /**
-     * Gets the DSR (Data Set Ready) bit from the underlying UART.
-     *
-     * @return the current state
-     * @throws IOException if an error occurred during reading
-     * @throws UnsupportedOperationException if not supported
-     */
-    boolean getDSR() throws IOException;
-
-    /**
-     * Gets the DTR (Data Terminal Ready) bit from the underlying UART.
-     *
-     * @return the current state
-     * @throws IOException if an error occurred during reading
-     * @throws UnsupportedOperationException if not supported
-     */
-    boolean getDTR() throws IOException;
-
-    /**
-     * Sets the DTR (Data Terminal Ready) bit on the underlying UART, if supported.
-     *
-     * @param value the value to set
-     * @throws IOException if an error occurred during writing
-     * @throws UnsupportedOperationException if not supported
-     */
-    void setDTR(boolean value) throws IOException;
-
-    /**
-     * Gets the RI (Ring Indicator) bit from the underlying UART.
-     *
-     * @return the current state
-     * @throws IOException if an error occurred during reading
-     * @throws UnsupportedOperationException if not supported
-     */
-    boolean getRI() throws IOException;
-
-    /**
-     * Gets the RTS (Request To Send) bit from the underlying UART.
-     *
-     * @return the current state
-     * @throws IOException if an error occurred during reading
-     * @throws UnsupportedOperationException if not supported
-     */
-    boolean getRTS() throws IOException;
-
-    /**
-     * Sets the RTS (Request To Send) bit on the underlying UART, if supported.
-     *
-     * @param value the value to set
-     * @throws IOException if an error occurred during writing
-     * @throws UnsupportedOperationException if not supported
-     */
-    void setRTS(boolean value) throws IOException;
-
-    /**
-     * Gets all control line values from the underlying UART, if supported.
-     * Requires less USB calls than calling getRTS() + ... + getRI() individually.
-     *
-     * @return EnumSet.contains(...) is {@code true} if set, else {@code false}
-     * @throws IOException if an error occurred during reading
-     */
-    EnumSet<ControlLine> getControlLines() throws IOException;
-
-    /**
-     * Gets all control line supported flags.
-     *
-     * @return EnumSet.contains(...) is {@code true} if supported, else {@code false}
-     * @throws IOException if an error occurred during reading
-     */
-    EnumSet<ControlLine> getSupportedControlLines() throws IOException;
-
-    /**
-     * Purge non-transmitted output data and / or non-read input data.
-     *
-     * @param purgeWriteBuffers {@code true} to discard non-transmitted output data
-     * @param purgeReadBuffers {@code true} to discard non-read input data
-     * @throws IOException if an error occurred during flush
-     * @throws UnsupportedOperationException if not supported
-     */
-    void purgeHwBuffers(boolean purgeWriteBuffers, boolean purgeReadBuffers) throws IOException;
-
-    /**
-     * send BREAK condition.
-     *
-     * @param value set/reset
-     */
-    void setBreak(boolean value) throws IOException;
-
-    /**
-     * Returns the current state of the connection.
-     */
-    boolean isOpen();
-
-}

+ 0 - 90
Qt/Android/SmartPDU_QT/Android/src/com/hoho/android/usbserial/driver/UsbSerialProber.java

@@ -1,90 +0,0 @@
-/* Copyright 2011-2013 Google Inc.
- * Copyright 2013 mike wakerly <opensource@hoho.com>
- *
- * Project home page: https://github.com/mik3y/usb-serial-for-android
- */
-
-package com.hoho.android.usbserial.driver;
-
-import android.hardware.usb.UsbDevice;
-import android.hardware.usb.UsbManager;
-
-import java.lang.reflect.Constructor;
-import java.lang.reflect.InvocationTargetException;
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- *
- * @author mike wakerly (opensource@hoho.com)
- */
-public class UsbSerialProber {
-
-    private final ProbeTable mProbeTable;
-
-    public UsbSerialProber(ProbeTable probeTable) {
-        mProbeTable = probeTable;
-    }
-
-    public static UsbSerialProber getDefaultProber() {
-        return new UsbSerialProber(getDefaultProbeTable());
-    }
-    
-    public static ProbeTable getDefaultProbeTable() {
-        final ProbeTable probeTable = new ProbeTable();
-        probeTable.addDriver(CdcAcmSerialDriver.class);
-        probeTable.addDriver(Cp21xxSerialDriver.class);
-        probeTable.addDriver(FtdiSerialDriver.class);
-        probeTable.addDriver(ProlificSerialDriver.class);
-        probeTable.addDriver(Ch34xSerialDriver.class);
-        probeTable.addDriver(GsmModemSerialDriver.class);
-        probeTable.addDriver(ChromeCcdSerialDriver.class);
-        return probeTable;
-    }
-
-    /**
-     * Finds and builds all possible {@link UsbSerialDriver UsbSerialDrivers}
-     * from the currently-attached {@link UsbDevice} hierarchy. This method does
-     * not require permission from the Android USB system, since it does not
-     * open any of the devices.
-     *
-     * @param usbManager usb manager
-     * @return a list, possibly empty, of all compatible drivers
-     */
-    public List<UsbSerialDriver> findAllDrivers(final UsbManager usbManager) {
-        final List<UsbSerialDriver> result = new ArrayList<>();
-
-        for (final UsbDevice usbDevice : usbManager.getDeviceList().values()) {
-            final UsbSerialDriver driver = probeDevice(usbDevice);
-            if (driver != null) {
-                result.add(driver);
-            }
-        }
-        return result;
-    }
-    
-    /**
-     * Probes a single device for a compatible driver.
-     * 
-     * @param usbDevice the usb device to probe
-     * @return a new {@link UsbSerialDriver} compatible with this device, or
-     *         {@code null} if none available.
-     */
-    public UsbSerialDriver probeDevice(final UsbDevice usbDevice) {
-        final Class<? extends UsbSerialDriver> driverClass = mProbeTable.findDriver(usbDevice);
-        if (driverClass != null) {
-            final UsbSerialDriver driver;
-            try {
-                final Constructor<? extends UsbSerialDriver> ctor =
-                        driverClass.getConstructor(UsbDevice.class);
-                driver = ctor.newInstance(usbDevice);
-            } catch (NoSuchMethodException | IllegalArgumentException | InstantiationException |
-                     IllegalAccessException | InvocationTargetException e) {
-                throw new RuntimeException(e);
-            }
-            return driver;
-        }
-        return null;
-    }
-
-}

+ 0 - 155
Qt/Android/SmartPDU_QT/Android/src/com/hoho/android/usbserial/util/HexDump.java

@@ -1,155 +0,0 @@
-/*
- * Copyright (C) 2006 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.hoho.android.usbserial.util;
-
-import java.security.InvalidParameterException;
-
-/**
- * Clone of Android's /core/java/com/android/internal/util/HexDump class, for use in debugging.
- * Changes: space separated hex strings
- */
-public class HexDump {
-    private final static char[] HEX_DIGITS = {
-            '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
-    };
-
-    public static String dumpHexString(byte[] array) {
-        return dumpHexString(array, 0, array.length);
-    }
-
-    public static String dumpHexString(byte[] array, int offset, int length) {
-        StringBuilder result = new StringBuilder();
-
-        byte[] line = new byte[8];
-        int lineIndex = 0;
-
-        for (int i = offset; i < offset + length; i++) {
-            if (lineIndex == line.length) {
-                for (int j = 0; j < line.length; j++) {
-                    if (line[j] > ' ' && line[j] < '~') {
-                        result.append(new String(line, j, 1));
-                    } else {
-                        result.append(".");
-                    }
-                }
-
-                result.append("\n");
-                lineIndex = 0;
-            }
-
-            byte b = array[i];
-            result.append(HEX_DIGITS[(b >>> 4) & 0x0F]);
-            result.append(HEX_DIGITS[b & 0x0F]);
-            result.append(" ");
-
-            line[lineIndex++] = b;
-        }
-
-        for (int i = 0; i < (line.length - lineIndex); i++) {
-            result.append("   ");
-        }
-        for (int i = 0; i < lineIndex; i++) {
-            if (line[i] > ' ' && line[i] < '~') {
-                result.append(new String(line, i, 1));
-            } else {
-                result.append(".");
-            }
-        }
-
-        return result.toString();
-    }
-
-    public static String toHexString(byte b) {
-        return toHexString(toByteArray(b));
-    }
-
-    public static String toHexString(byte[] array) {
-        return toHexString(array, 0, array.length);
-    }
-
-    public static String toHexString(byte[] array, int offset, int length) {
-        char[] buf = new char[length > 0 ? length * 3 - 1 : 0];
-
-        int bufIndex = 0;
-        for (int i = offset; i < offset + length; i++) {
-            if (i > offset)
-                buf[bufIndex++] = ' ';
-            byte b = array[i];
-            buf[bufIndex++] = HEX_DIGITS[(b >>> 4) & 0x0F];
-            buf[bufIndex++] = HEX_DIGITS[b & 0x0F];
-        }
-
-        return new String(buf);
-    }
-
-    public static String toHexString(int i) {
-        return toHexString(toByteArray(i));
-    }
-
-    public static String toHexString(short i) {
-        return toHexString(toByteArray(i));
-    }
-
-    public static byte[] toByteArray(byte b) {
-        byte[] array = new byte[1];
-        array[0] = b;
-        return array;
-    }
-
-    public static byte[] toByteArray(int i) {
-        byte[] array = new byte[4];
-
-        array[3] = (byte) (i & 0xFF);
-        array[2] = (byte) ((i >> 8) & 0xFF);
-        array[1] = (byte) ((i >> 16) & 0xFF);
-        array[0] = (byte) ((i >> 24) & 0xFF);
-
-        return array;
-    }
-
-    public static byte[] toByteArray(short i) {
-        byte[] array = new byte[2];
-
-        array[1] = (byte) (i & 0xFF);
-        array[0] = (byte) ((i >> 8) & 0xFF);
-
-        return array;
-    }
-
-    private static int toByte(char c) {
-        if (c >= '0' && c <= '9')
-            return (c - '0');
-        if (c >= 'A' && c <= 'F')
-            return (c - 'A' + 10);
-        if (c >= 'a' && c <= 'f')
-            return (c - 'a' + 10);
-
-        throw new InvalidParameterException("Invalid hex char '" + c + "'");
-    }
-
-    /** accepts any separator, e.g. space or newline */
-    public static byte[] hexStringToByteArray(String hexString) {
-        int length = hexString.length();
-        byte[] buffer = new byte[(length + 1) / 3];
-
-        for (int i = 0; i < length; i += 3) {
-            buffer[i / 3] = (byte) ((toByte(hexString.charAt(i)) << 4) | toByte(hexString.charAt(i + 1)));
-        }
-
-        return buffer;
-    }
-}

+ 0 - 14
Qt/Android/SmartPDU_QT/Android/src/com/hoho/android/usbserial/util/MonotonicClock.java

@@ -1,14 +0,0 @@
-package com.hoho.android.usbserial.util;
-
-public final class MonotonicClock {
-
-    private static final long NS_PER_MS = 1_000_000;
-
-    private MonotonicClock() {
-    }
-
-    public static long millis() {
-        return System.nanoTime() / NS_PER_MS;
-    }
-
-}

+ 0 - 261
Qt/Android/SmartPDU_QT/Android/src/com/hoho/android/usbserial/util/SerialInputOutputManager.java

@@ -1,261 +0,0 @@
-/* Copyright 2011-2013 Google Inc.
- * Copyright 2013 mike wakerly <opensource@hoho.com>
- *
- * Project home page: https://github.com/mik3y/usb-serial-for-android
- */
-
-package com.hoho.android.usbserial.util;
-
-import android.os.Process;
-import android.util.Log;
-
-import com.hoho.android.usbserial.driver.UsbSerialPort;
-
-import java.io.IOException;
-import java.nio.ByteBuffer;
-
-/**
- * Utility class which services a {@link UsbSerialPort} in its {@link #run()} method.
- *
- * @author mike wakerly (opensource@hoho.com)
- */
-public class SerialInputOutputManager implements Runnable {
-
-    public enum State {
-        STOPPED,
-        RUNNING,
-        STOPPING
-    }
-
-    public static boolean DEBUG = false;
-
-    private static final String TAG = SerialInputOutputManager.class.getSimpleName();
-    private static final int BUFSIZ = 4096;
-
-    /**
-     * default read timeout is infinite, to avoid data loss with bulkTransfer API
-     */
-    private int mReadTimeout = 0;
-    private int mWriteTimeout = 0;
-
-    private final Object mReadBufferLock = new Object();
-    private final Object mWriteBufferLock = new Object();
-
-    private ByteBuffer mReadBuffer; // default size = getReadEndpoint().getMaxPacketSize()
-    private ByteBuffer mWriteBuffer = ByteBuffer.allocate(BUFSIZ);
-
-    private int mThreadPriority = Process.THREAD_PRIORITY_URGENT_AUDIO;
-    private State mState = State.STOPPED; // Synchronized by 'this'
-    private Listener mListener; // Synchronized by 'this'
-    private final UsbSerialPort mSerialPort;
-
-    public interface Listener {
-        /**
-         * Called when new incoming data is available.
-         */
-        void onNewData(byte[] data);
-
-        /**
-         * Called when {@link SerialInputOutputManager#run()} aborts due to an error.
-         */
-        void onRunError(Exception e);
-    }
-
-    public SerialInputOutputManager(UsbSerialPort serialPort) {
-        mSerialPort = serialPort;
-        mReadBuffer = ByteBuffer.allocate(serialPort.getReadEndpoint().getMaxPacketSize());
-    }
-
-    public SerialInputOutputManager(UsbSerialPort serialPort, Listener listener) {
-        mSerialPort = serialPort;
-        mListener = listener;
-        mReadBuffer = ByteBuffer.allocate(serialPort.getReadEndpoint().getMaxPacketSize());
-    }
-
-    public synchronized void setListener(Listener listener) {
-        mListener = listener;
-    }
-
-    public synchronized Listener getListener() {
-        return mListener;
-    }
-
-    /**
-     * setThreadPriority. By default a higher priority than UI thread is used to prevent data loss
-     *
-     * @param threadPriority  see {@link Process#setThreadPriority(int)}
-     * */
-    public void setThreadPriority(int threadPriority) {
-        if (mState != State.STOPPED)
-            throw new IllegalStateException("threadPriority only configurable before SerialInputOutputManager is started");
-        mThreadPriority = threadPriority;
-    }
-
-    /**
-     * read/write timeout
-     */
-    public void setReadTimeout(int timeout) {
-        // when set if already running, read already blocks and the new value will not become effective now
-        if(mReadTimeout == 0 && timeout != 0 && mState != State.STOPPED)
-            throw new IllegalStateException("readTimeout only configurable before SerialInputOutputManager is started");
-        mReadTimeout = timeout;
-    }
-
-    public int getReadTimeout() {
-        return mReadTimeout;
-    }
-
-    public void setWriteTimeout(int timeout) {
-        mWriteTimeout = timeout;
-    }
-
-    public int getWriteTimeout() {
-        return mWriteTimeout;
-    }
-
-    /**
-     * read/write buffer size
-     */
-    public void setReadBufferSize(int bufferSize) {
-        if (getReadBufferSize() == bufferSize)
-            return;
-        synchronized (mReadBufferLock) {
-            mReadBuffer = ByteBuffer.allocate(bufferSize);
-        }
-    }
-
-    public int getReadBufferSize() {
-        return mReadBuffer.capacity();
-    }
-
-    public void setWriteBufferSize(int bufferSize) {
-        if(getWriteBufferSize() == bufferSize)
-            return;
-        synchronized (mWriteBufferLock) {
-            ByteBuffer newWriteBuffer = ByteBuffer.allocate(bufferSize);
-            if(mWriteBuffer.position() > 0)
-                newWriteBuffer.put(mWriteBuffer.array(), 0, mWriteBuffer.position());
-            mWriteBuffer = newWriteBuffer;
-        }
-    }
-
-    public int getWriteBufferSize() {
-        return mWriteBuffer.capacity();
-    }
-
-    /**
-     * when using writeAsync, it is recommended to use readTimeout != 0,
-     * else the write will be delayed until read data is available
-     */
-    public void writeAsync(byte[] data) {
-        synchronized (mWriteBufferLock) {
-            mWriteBuffer.put(data);
-        }
-    }
-
-    /**
-     * start SerialInputOutputManager in separate thread
-     */
-    public void start() {
-        if(mState != State.STOPPED)
-            throw new IllegalStateException("already started");
-        new Thread(this, this.getClass().getSimpleName()).start();
-    }
-
-    /**
-     * stop SerialInputOutputManager thread
-     *
-     * when using readTimeout == 0 (default), additionally use usbSerialPort.close() to
-     * interrupt blocking read
-     */
-    public synchronized void stop() {
-        if (getState() == State.RUNNING) {
-            Log.i(TAG, "Stop requested");
-            mState = State.STOPPING;
-        }
-    }
-
-    public synchronized State getState() {
-        return mState;
-    }
-
-    /**
-     * Continuously services the read and write buffers until {@link #stop()} is
-     * called, or until a driver exception is raised.
-     */
-    @Override
-    public void run() {
-        synchronized (this) {
-            if (getState() != State.STOPPED) {
-                throw new IllegalStateException("Already running");
-            }
-            mState = State.RUNNING;
-        }
-        Log.i(TAG, "Running ...");
-        try {
-            if(mThreadPriority != Process.THREAD_PRIORITY_DEFAULT)
-                Process.setThreadPriority(mThreadPriority);
-            while (true) {
-                if (getState() != State.RUNNING) {
-                    Log.i(TAG, "Stopping mState=" + getState());
-                    break;
-                }
-                step();
-            }
-        } catch (Exception e) {
-            if(mSerialPort.isOpen()) {
-                Log.w(TAG, "Run ending due to exception: " + e.getMessage(), e);
-            } else {
-                Log.i(TAG, "Socket closed");
-            }
-            final Listener listener = getListener();
-            if (listener != null) {
-              listener.onRunError(e);
-            }
-        } finally {
-            synchronized (this) {
-                mState = State.STOPPED;
-                Log.i(TAG, "Stopped");
-            }
-        }
-    }
-
-    private void step() throws IOException {
-        // Handle incoming data.
-        byte[] buffer;
-        synchronized (mReadBufferLock) {
-            buffer = mReadBuffer.array();
-        }
-        int len = mSerialPort.read(buffer, mReadTimeout);
-        if (len > 0) {
-            if (DEBUG) {
-                Log.d(TAG, "Read data len=" + len);
-            }
-            final Listener listener = getListener();
-            if (listener != null) {
-                final byte[] data = new byte[len];
-                System.arraycopy(buffer, 0, data, 0, len);
-                listener.onNewData(data);
-            }
-        }
-
-        // Handle outgoing data.
-        buffer = null;
-        synchronized (mWriteBufferLock) {
-            len = mWriteBuffer.position();
-            if (len > 0) {
-                buffer = new byte[len];
-                mWriteBuffer.rewind();
-                mWriteBuffer.get(buffer, 0, len);
-                mWriteBuffer.clear();
-            }
-        }
-        if (buffer != null) {
-            if (DEBUG) {
-                Log.d(TAG, "Writing data len=" + len);
-            }
-            mSerialPort.write(buffer, mWriteTimeout);
-        }
-    }
-
-}

+ 0 - 30
Qt/Android/SmartPDU_QT/Android/src/com/hoho/android/usbserial/util/UsbUtils.java

@@ -1,30 +0,0 @@
-package com.hoho.android.usbserial.util;
-
-import android.hardware.usb.UsbDeviceConnection;
-
-import java.util.ArrayList;
-
-public class UsbUtils {
-
-    public static  ArrayList<byte[]> getDescriptors(UsbDeviceConnection connection) {
-        ArrayList<byte[]> descriptors = new ArrayList<>();
-        byte[] rawDescriptors = connection.getRawDescriptors();
-        if (rawDescriptors != null) {
-            int pos = 0;
-            while (pos < rawDescriptors.length) {
-                int len = rawDescriptors[pos] & 0xFF;
-                if (len == 0)
-                    break;
-                if (pos + len > rawDescriptors.length)
-                    len = rawDescriptors.length - pos;
-                byte[] descriptor = new byte[len];
-                System.arraycopy(rawDescriptors, pos, descriptor, 0, len);
-                descriptors.add(descriptor);
-                pos += len;
-            }
-        }
-        return descriptors;
-    }
-
-
-}

+ 33 - 7
Qt/Android/SmartPDU_QT/SmartPDU_QT.pro

@@ -20,22 +20,48 @@ SOURCES += \
     Data_Ctrl.cpp \
     USB485_Ctrl.cpp \
     main.cpp \
-    mainwidget.cpp
+    mainwidget.cpp \
+    widget.cpp
 
 HEADERS += \
     Data_Ctrl.h \
     USB485_Ctrl.h \
-    mainwidget.h
+    mainwidget.h \
+    widget.h
 
 FORMS += \
-    mainwidget.ui
-
-#DISTFILES +=
-#    Android/src/com/hoho/android/usbserial/driver/*.java \
-#    Android/src/com/hoho/android/usbserial/util/*.java
+    mainwidget.ui \
+    widget.ui
 
 
 # Default rules for deployment.
 qnx: target.path = /tmp/$${TARGET}/bin
 else: unix:!android: target.path = /opt/$${TARGET}/bin
 !isEmpty(target.path): INSTALLS += target
+
+DISTFILES += \
+    android/AndroidManifest.xml \
+    android/build.gradle \
+    android/gradle.properties \
+    android/gradle/wrapper/gradle-wrapper.jar \
+    android/gradle/wrapper/gradle-wrapper.properties \
+    android/gradlew \
+    android/gradlew.bat \
+    android/res/values/libs.xml \
+    android/res/xml/qtprovider_paths.xml \
+    resource/Reset.png \
+    resource/Serial.png \
+    resource/Started.png \
+    resource/Trigger.png \
+    resource/close.png \
+    resource/open.png #\
+    #Android/src/usb/*.java \
+    #Android/src/com/hoho/android/usbserial/driver/*.java \
+    #Android/src/com/hoho/android/usbserial/util/*.java
+
+RESOURCES += \
+    pduresource.qrc
+
+#QT += androidextras
+#QT += core
+ANDROID_PACKAGE_SOURCE_DIR = $$PWD/android

File diff suppressed because it is too large
+ 1435 - 288
Qt/Android/SmartPDU_QT/SmartPDU_QT.pro.user


+ 248 - 256
Qt/Android/SmartPDU_QT/mainwidget.cpp

@@ -10,10 +10,13 @@ MainWidget::MainWidget(QWidget *parent)
 {
     ui->setupUi(this);
 
-    ui->serialCB->clear();
+    ui->serialCB_3->clear();
     m_USBCtrl.SerialPortInit();
     connect(Data_Ctrl::getData()->serialPort,SIGNAL(readyRead()),this,SLOT(manual_serialPortReadyRead()));/*手动连接槽函数*/
 
+    //InitSerial();
+
+
     InitUI();
     InitConnect();
 
@@ -25,13 +28,13 @@ MainWidget::MainWidget(QWidget *parent)
     });
 
     //QString currentPath = QDir::currentPath();
-    m_TotalCHNum=24;
-    m_CurPhase=1;
+    m_TotalCHNum=14;
     for (int i=0;i<64;i++) {
         m_PDUCHInfo[i].CHNum=i+1;
-        m_PDUCHInfo[i].CHName.sprintf("CH%d", i+1);
+        m_PDUCHInfo[i].CHName=QString("CH%1").arg(i+1);
+
+        m_chWidget[i].chid=i+1;
     }
-    InitCHTable(m_TotalCHNum,true);
 
     _timer_update_info = new QTimer(this);
     _timer_update_info->setInterval(1000);
@@ -51,7 +54,7 @@ void MainWidget::InitUI()
     //通过QSerialPortInfo查找可用串口
     foreach(const QSerialPortInfo &info, QSerialPortInfo::availablePorts())
     {
-        ui->serialCB->addItem(info.portName());
+        ui->serialCB_3->addItem(info.portName());
     }
     // 发送、接收计数清零
     sendNum = 0;
@@ -70,142 +73,58 @@ void MainWidget::InitUI()
     lblPortState->setMinimumSize(550, 20);
     setNumOnLabel(lblSendNum, "S: ", sendNum);
     setNumOnLabel(lblRecvNum, "R: ", recvNum);
+
     // 从右往左依次添加
-    ui->horizontalLayout_7->addWidget(lblPortState);
-    ui->horizontalLayout_7->addWidget(lblSendNum);
-    ui->horizontalLayout_7->addWidget(lblRecvNum);
+    ui->horizontalLayout_15->addWidget(lblPortState);
+    ui->horizontalLayout_15->addWidget(lblSendNum);
+    ui->horizontalLayout_15->addWidget(lblRecvNum);
 
-    ui->pushButton_L1->setIcon(QIcon("resource/Started.png"));
-    ui->pushButton_L2->setIcon(QIcon("resource/Reset.png"));
-    ui->pushButton_L3->setIcon(QIcon("resource/Reset.png"));
+    ui->pb_Debug->setIcon(QIcon(":/resource/Serial.png"));
 
-    ui->pushButton_ALLOPEN->setIcon(QIcon("resource/open.png"));
-    ui->pushButton_ALLCLOSE->setIcon(QIcon("resource/close.png"));
-}
-void MainWidget::InitCHTable(int CHNum,bool initFlag)
-{
-    if(CHNum>64) return;
+    ui->label_INT->setStyleSheet("color: rgb(0, 218, 205);");
+    ui->label_26->setStyleSheet("color: rgb(0, 218, 205);");
+    ui->label_OUTT->setStyleSheet("color: orange;");
+    ui->label_29->setStyleSheet("color: orange;");
+    // 创建一个 QWidget,并添加一些内容
 
-    if(initFlag)
-    {
-        ui->tableWidget_CHInfo->setColumnCount(10);
-        ui->tableWidget_CHInfo->setRowCount(CHNum);
-        QStringList pTableHeadList;
-        pTableHeadList<< "通道" << "名称" << "相位" << "电压(V)" << "电流(A)"<< "功率(W)" << "功率因数" << "耗电量(kWh)" << "状态" << "操作";
-        ui->tableWidget_CHInfo->setHorizontalHeaderLabels(pTableHeadList);
-        ui->tableWidget_CHInfo->setEditTriggers(QAbstractItemView::NoEditTriggers);
-        ui->tableWidget_CHInfo->setSelectionBehavior(QAbstractItemView::SelectRows);
-        ui->tableWidget_CHInfo->setSelectionMode(QAbstractItemView::SingleSelection);
-        ui->tableWidget_CHInfo->verticalHeader()->hide();
-        ui->tableWidget_CHInfo->setFont(QFont("Helvetica"));
-        ui->tableWidget_CHInfo->setColumnWidth(0, 60);
-        ui->tableWidget_CHInfo->setColumnWidth(1, 100);
-        ui->tableWidget_CHInfo->setColumnWidth(2, 100);
-        ui->tableWidget_CHInfo->setColumnWidth(3, 100);
-        ui->tableWidget_CHInfo->setColumnWidth(4, 100);
-        ui->tableWidget_CHInfo->setColumnWidth(5, 100);
-        ui->tableWidget_CHInfo->setColumnWidth(6, 100);
-        ui->tableWidget_CHInfo->setColumnWidth(7, 100);
-        ui->tableWidget_CHInfo->setColumnWidth(8, 80);
-        ui->tableWidget_CHInfo->setColumnWidth(9, 80);
-    }
+    ui->gridLayout->setContentsMargins(1, 1, 1, 1);
+     ui->gridLayout->setHorizontalSpacing(20);
+     ui->gridLayout->setVerticalSpacing(8);
+     m_TotalCHNum=14;
+     for (int i=0;i<m_TotalCHNum;i++) {
+        ui->gridLayout->addWidget(&m_chWidget[i], i%((m_TotalCHNum+1)/2), i/((m_TotalCHNum+1)/2));
 
-    ui->tableWidget_CHInfo->clearContents();
-    for (int i = 0; i < CHNum;i++)
-    {
-        ui->tableWidget_CHInfo->setRowHeight(i, 50);
-
-        QString chid;
-        chid.sprintf("%d", m_PDUCHInfo[i].CHNum);
-        QTableWidgetItem *newItem0 = new QTableWidgetItem(chid);
-        newItem0->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
-        ui->tableWidget_CHInfo->setItem(i, 0, newItem0);
-
-        QTableWidgetItem *newItem1 = new QTableWidgetItem(m_PDUCHInfo[i].CHName);
-        newItem1->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
-        ui->tableWidget_CHInfo->setItem(i, 1, newItem1);
-
-        QTableWidgetItem *newItem3;
-        if (0 == m_PDUCHInfo[i].CHPhase)
-            newItem3 = new QTableWidgetItem("L1");
-        else if (1 == m_PDUCHInfo[i].CHPhase)
-            newItem3 = new QTableWidgetItem("L2");
-        else if (2 == m_PDUCHInfo[i].CHPhase)
-            newItem3 = new QTableWidgetItem("L3");
-        else newItem3 = new QTableWidgetItem("Null");
-        newItem3->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
-        ui->tableWidget_CHInfo->setItem(i, 2, newItem3);
-
-        QString chV;
-        chV.sprintf("%0.3f", m_PDUCHInfo[i].CHVoltage);
-        QTableWidgetItem *newItem4 = new QTableWidgetItem(chV);
-        newItem4->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
-        ui->tableWidget_CHInfo->setItem(i, 3, newItem4);
-
-        QString chI;
-        chI.sprintf("%0.3f", m_PDUCHInfo[i].CHCurrent);
-        QTableWidgetItem *newItem5 = new QTableWidgetItem(chI);
-        newItem5->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
-        ui->tableWidget_CHInfo->setItem(i, 4, newItem5);
-
-        QString chP;
-        chP.sprintf("%0.3f", m_PDUCHInfo[i].CHPower);
-        QTableWidgetItem *newItem6 = new QTableWidgetItem(chP);
-        newItem6->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
-        ui->tableWidget_CHInfo->setItem(i, 5, newItem6);
-
-        QString chF;
-        chF.sprintf("%0.3f", m_PDUCHInfo[i].CHFactor);
-        QTableWidgetItem *newItem7 = new QTableWidgetItem(chF);
-        newItem7->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
-        ui->tableWidget_CHInfo->setItem(i, 6, newItem7);
-
-        QString chC;
-        chC.sprintf("%0.3f", m_PDUCHInfo[i].CHConsumption);
-        QTableWidgetItem *newItem8 = new QTableWidgetItem(chC);
-        newItem8->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
-        ui->tableWidget_CHInfo->setItem(i, 7, newItem8);
-
-        QTableWidgetItem *newItem9;
-        if (m_PDUCHInfo[i].CHStatus)
-        {
-            newItem9=new QTableWidgetItem(QIcon("resource/open.png"), "接通");
-            newItem9->setData(Qt::BackgroundRole, QBrush(QColor(0, 255 , 0, 60)));
-        }
-        else
-        {
-            newItem9 = new QTableWidgetItem(QIcon("resource/close.png"), "断开");
-            newItem9->setData(Qt::BackgroundRole, QBrush(QColor(255, 69,0, 60)));
-        }
-        newItem9->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
-        ui->tableWidget_CHInfo->setItem(i, 8, newItem9);
-
-        QPushButton* buttonoper;
-        if (m_PDUCHInfo[i].CHStatus)
-            buttonoper=new QPushButton(QStringLiteral("OFF"), ui->tableWidget_CHInfo);
-        else buttonoper=new QPushButton(QStringLiteral("ON"), ui->tableWidget_CHInfo);
-        buttonoper->setFixedSize(60, 23);
-        auto cellWidget = new QWidget(this);
-        auto layout = new QHBoxLayout(cellWidget);
-        layout ->addWidget(buttonoper);
-        cellWidget->setLayout(layout);
-        ui->tableWidget_CHInfo->setCellWidget(i, 9, cellWidget);
-    }
+     }
+     QString styleSheet = "QWidget { background-color: #rgb(11, 17, 45); }";
+     //ui->MainWidget->setStyleSheet(styleSheet);
 }
 
 
-
-
 void MainWidget::InitConnect()
 {
     connect(ui->pb_Debug,SIGNAL(clicked()),this,SLOT(slot_changeDebugMode()));
-    connect(ui->Button_checkserial,SIGNAL(clicked()),this,SLOT(on_Button_checkserial_clicked()));
-    connect(ui->Button_openserial,SIGNAL(clicked()),this,SLOT(on_Button_openserial_clicked()));
-    connect(ui->Button_clearrecive,SIGNAL(clicked()),this,SLOT(on_Button_clearrecive_clicked()));
-    connect(ui->Button_tx,SIGNAL(clicked()),this,SLOT(on_Button_tx_clicked()));
-    connect(ui->Button_cleartx,SIGNAL(clicked()),this,SLOT(on_Button_cleartx_clicked()));
+    connect(ui->Button_checkserial_3,SIGNAL(clicked()),this,SLOT(on_Button_checkserial_clicked()));
+    connect(ui->Button_openserial_3,SIGNAL(clicked()),this,SLOT(on_Button_openserial_clicked()));
+    connect(ui->Button_clearrecive_3,SIGNAL(clicked()),this,SLOT(on_Button_clearrecive_clicked()));
+    connect(ui->Button_tx_4,SIGNAL(clicked()),this,SLOT(on_Button_tx_clicked()));
+    connect(ui->Button_cleartx_4,SIGNAL(clicked()),this,SLOT(on_Button_cleartx_clicked()));
+}
+
+bool MainWidget::InitSerial()
+{
+    /*
+    QAndroidJniObject javaString = QAndroidJniObject::fromString("ttys1");
+    jboolean res = QAndroidJniObject::callStaticMethod<jboolean>(
+                                       "usb/USBListActivity",
+                                       "OpenSerial",
+                                       "(Ljava/lang/String;)Z",
+                                       javaString.object<jstring>());
+
+*/
 }
 
+
+
 void MainWidget::manual_serialPortReadyRead()
 {
     QByteArray recBuf = Data_Ctrl::getData()->serialPort->readAll();;
@@ -216,8 +135,8 @@ void MainWidget::manual_serialPortReadyRead()
      // 状态栏显示计数值
      setNumOnLabel(lblRecvNum, "R: ", recvNum);
 
-     if(ui->check_hex_recive->checkState() == false){
-         if(ui->check_timestamp->checkState() == Qt::Checked){
+     if(ui->check_hex_recive_3->checkState() == false){
+         if(ui->check_timestamp_3->checkState() == Qt::Checked){
              QDateTime nowtime = QDateTime::currentDateTime();
              str_rev = "[" + nowtime.toString("yyyy-MM-dd hh:mm:ss") + "] ";
              str_rev += QString(recBuf).append("\r\n");
@@ -226,7 +145,7 @@ void MainWidget::manual_serialPortReadyRead()
              // 在当前位置插入文本,不会发生换行。如果没有移动光标到文件结尾,会导致文件超出当前界面显示范围,界面也不会向下滚动。
              //ui->recvEdit->appendPlainText(buf);
 
-             if(ui->check_changeline->checkState() == Qt::Checked){
+             if(ui->check_changeline_3->checkState() == Qt::Checked){
                  str_rev = QString(recBuf).append("\r\n");
              }
              else
@@ -245,7 +164,7 @@ void MainWidget::manual_serialPortReadyRead()
              str2 += str1.mid (i,2);
              str2 += " ";
          }
-         if(ui->check_timestamp->checkState() == Qt::Checked)
+         if(ui->check_timestamp_3->checkState() == Qt::Checked)
          {
              QDateTime nowtime = QDateTime::currentDateTime();
              str_rev = "[" + nowtime.toString("yyyy-MM-dd hh:mm:ss") + "] ";
@@ -253,77 +172,77 @@ void MainWidget::manual_serialPortReadyRead()
          }
          else
          {
-             if(ui->check_changeline->checkState() == Qt::Checked)
+             if(ui->check_changeline_3->checkState() == Qt::Checked)
                  str_rev += str2.append("\r\n");
              else
                  str_rev = str2;
 
          }
      }
-     ui->recive_Edit->insertPlainText(str_rev);
-     ui->recive_Edit->moveCursor(QTextCursor::End);
+     ui->recive_Edit_4->insertPlainText(str_rev);
+     ui->recive_Edit_4->moveCursor(QTextCursor::End);
 }
 
 void MainWidget::on_Button_openserial_clicked()
 {
 
-    if(ui->baudrate_CB->currentText()=="1200")
+    if(ui->baudrate_CB_3->currentText()=="1200")
         Data_Ctrl::getData()->baudRate=QSerialPort::Baud1200;
-    else if(ui->baudrate_CB->currentText()=="2400")
+    else if(ui->baudrate_CB_3->currentText()=="2400")
         Data_Ctrl::getData()->baudRate=QSerialPort::Baud2400;
-    else if(ui->baudrate_CB->currentText()=="4800")
+    else if(ui->baudrate_CB_3->currentText()=="4800")
         Data_Ctrl::getData()->baudRate=QSerialPort::Baud4800;
-    else if(ui->baudrate_CB->currentText()=="9600")
+    else if(ui->baudrate_CB_3->currentText()=="9600")
         Data_Ctrl::getData()->baudRate=QSerialPort::Baud9600;
-    else if(ui->baudrate_CB->currentText()=="19200")
+    else if(ui->baudrate_CB_3->currentText()=="19200")
         Data_Ctrl::getData()->baudRate=QSerialPort::Baud19200;
-    else if(ui->baudrate_CB->currentText()=="38400")
+    else if(ui->baudrate_CB_3->currentText()=="38400")
         Data_Ctrl::getData()->baudRate=QSerialPort::Baud38400;
-    else if(ui->baudrate_CB->currentText()=="57600")
+    else if(ui->baudrate_CB_3->currentText()=="57600")
         Data_Ctrl::getData()->baudRate=QSerialPort::Baud57600;
-    else if(ui->baudrate_CB->currentText()=="115200")
+    else if(ui->baudrate_CB_3->currentText()=="115200")
         Data_Ctrl::getData()->baudRate=QSerialPort::Baud115200;
 
     // 获取串口数据位
-    if(ui->databit_CB->currentText()=="8")
+    if(ui->databit_CB_3->currentText()=="8")
         Data_Ctrl::getData()->dataBits=QSerialPort::Data5;
-    else if(ui->databit_CB->currentText()=="7")
+    else if(ui->databit_CB_3->currentText()=="7")
         Data_Ctrl::getData()->dataBits=QSerialPort::Data6;
-    else if(ui->databit_CB->currentText()=="6")
+    else if(ui->databit_CB_3->currentText()=="6")
         Data_Ctrl::getData()->dataBits=QSerialPort::Data7;
-    else if(ui->databit_CB->currentText()=="5")
+    else if(ui->databit_CB_3->currentText()=="5")
         Data_Ctrl::getData()->dataBits=QSerialPort::Data8;
 
     // 获取串口停止位
-    if(ui->stopbit_CB->currentText()=="1")
+    if(ui->stopbit_CB_3->currentText()=="1")
         Data_Ctrl::getData()->stopBits=QSerialPort::OneStop;
-    else if(ui->stopbit_CB->currentText()=="1.5")
+    else if(ui->stopbit_CB_3->currentText()=="1.5")
         Data_Ctrl::getData()->stopBits=QSerialPort::OneAndHalfStop;
-    else if(ui->stopbit_CB->currentText()=="2")
+    else if(ui->stopbit_CB_3->currentText()=="2")
         Data_Ctrl::getData()->stopBits=QSerialPort::TwoStop;
 
     // 获取串口奇偶校验位
-    if(ui->checkbit_CB->currentText() == "None"){
+    if(ui->checkbit_CB_3->currentText() == "None"){
         Data_Ctrl::getData()->checkBits = QSerialPort::NoParity;
-    }else if(ui->checkbit_CB->currentText() == "Odd"){
+    }else if(ui->checkbit_CB_3->currentText() == "Odd"){
         Data_Ctrl::getData()->checkBits = QSerialPort::OddParity;
-    }else if(ui->checkbit_CB->currentText() == "Even"){
+    }else if(ui->checkbit_CB_3->currentText() == "Even"){
         Data_Ctrl::getData()->checkBits = QSerialPort::EvenParity;
     }
 
     // 初始化串口属性,设置 端口号、波特率、数据位、停止位、奇偶校验位数
-    Data_Ctrl::getData()->serialPort->setPortName(ui->serialCB->currentText());
+    Data_Ctrl::getData()->serialPort->setPortName(ui->serialCB_3->currentText());
 
 
 
     // 根据初始化好的串口属性,打开串口
     // 如果打开成功,反转打开按钮显示和功能。打开失败,无变化,并且弹出错误对话框。
-    if(ui->Button_openserial->text() == "打开串口"){
+    if(ui->Button_openserial_3->text() == "打开串口"){
         if(m_USBCtrl.SeralPortCtrl(SeralCtrlType::Seral_Open)){
             //QMessageBox::
-            ui->Button_openserial->setText("关闭串口");
+            ui->Button_openserial_3->setText("关闭串口");
             // 让端口号下拉框不可选,避免误操作(选择功能不可用,控件背景为灰色)
-            ui->serialCB->setEnabled(false);
+            ui->serialCB_3->setEnabled(false);
         }else{
             QMessageBox::critical(this, "错误提示", "串口打开失败!!!\r\n该串口可能被占用\r\n请选择正确的串口");
         }
@@ -334,9 +253,9 @@ void MainWidget::on_Button_openserial_clicked()
         lblPortState->setStyleSheet("color:green");
     }else{
         m_USBCtrl.SeralPortCtrl(SeralCtrlType::Seral_Close);
-        ui->Button_openserial->setText("打开串口");
+        ui->Button_openserial_3->setText("打开串口");
         // 端口号下拉框恢复可选,避免误操作
-        ui->serialCB->setEnabled(true);
+        ui->serialCB_3->setEnabled(true);
         //statusBar 状态栏显示端口状态
         QString sm = "%1 CLOSED";
         QString status = sm.arg(Data_Ctrl::getData()->serialPort->portName());
@@ -350,15 +269,15 @@ void MainWidget::on_Button_tx_clicked()
     QByteArray array;
 
     //Hex复选框
-    if(ui->check_hexsend->checkState() == Qt::Checked){
+    if(ui->check_hexsend_4->checkState() == Qt::Checked){
         //array = QString2Hex(data);  //HEX 16进制
-        array = QByteArray::fromHex(ui->send_Edit->toPlainText().toUtf8()).data();
+        array = QByteArray::fromHex(ui->send_Edit_3->toPlainText().toUtf8()).data();
     }else{
         //array = data.toLatin1();    //ASCII
-        array = ui->send_Edit->toPlainText().toLocal8Bit().data();
+        array = ui->send_Edit_3->toPlainText().toLocal8Bit().data();
     }
 
-    if(ui->check_sendnewline->checkState() == Qt::Checked){
+    if(ui->check_sendnewline_4->checkState() == Qt::Checked){
         array.append("\r\n");
     }
     // 如发送成功,会返回发送的字节长度。失败,返回-1。
@@ -371,11 +290,22 @@ void MainWidget::on_Button_tx_clicked()
         // 状态栏显示计数值
         setNumOnLabel(lblSendNum, "S: ", sendNum);
     }
+    else
+    {
+        QMessageBox::StandardButton confimBtn = QMessageBox::question(this, "确认", " 串口信息发送失败!", QMessageBox::Ok | QMessageBox::Cancel);
+        if (confimBtn == QMessageBox::Cancel) {
+            return;
+        }
+        else
+        {
+            return;
+        }
+    }
 }
 
 void MainWidget::on_Button_clearrecive_clicked()
 {
-    ui->recive_Edit->clear();
+    ui->recive_Edit_4->clear();
     // 清除发送、接收字节计数
     sendNum = 0;
     recvNum = 0;
@@ -386,7 +316,7 @@ void MainWidget::on_Button_clearrecive_clicked()
 
 void MainWidget::on_Button_cleartx_clicked()
 {
-    ui->recive_Edit->clear();
+    ui->recive_Edit_4->clear();
     // 清除发送字节计数
     sendNum = 0;
     // 状态栏显示计数值
@@ -399,15 +329,15 @@ void MainWidget::on_check_autosend_stateChanged(int arg1)
      if(arg1 == 0){
          timSend->stop();
          // 时间输入框恢复可选
-         ui->spin_sendtime->setEnabled(true);
+         ui->spin_sendtime_4->setEnabled(true);
      }else{
          // 对输入的值做限幅,小于10ms会弹出对话框提示
-         if(ui->spin_sendtime->text().toInt() >= 10){
-             timSend->start(ui->spin_sendtime->text().toInt());// 设置定时时长,重新计数
+         if(ui->spin_sendtime_4->text().toInt() >= 10){
+             timSend->start(ui->spin_sendtime_4->text().toInt());// 设置定时时长,重新计数
              // 让时间输入框不可选,避免误操作(输入功能不可用,控件背景为灰色)
-             ui->spin_sendtime->setEnabled(false);
+             ui->spin_sendtime_4->setEnabled(false);
          }else{
-             ui->check_autosend->setCheckState(Qt::Unchecked);
+             ui->check_autosend_4->setCheckState(Qt::Unchecked);
              QMessageBox::critical(this, "错误提示", "定时发送的最小间隔为 10ms\r\n请确保输入的值 >=10");
          }
      }
@@ -415,23 +345,75 @@ void MainWidget::on_check_autosend_stateChanged(int arg1)
 
 void MainWidget::on_Button_checkserial_clicked()
 {
-    ui->serialCB->clear();
+    ui->serialCB_3->clear();
     //通过QSerialPortInfo查找可用串口
-    foreach(const QSerialPortInfo &info, QSerialPortInfo::availablePorts())
+    //foreach(const QSerialPortInfo &info, QSerialPortInfo::availablePorts())
+    //{
+    //    ui->serialCB_3->addItem(info.portName());
+   // }
+    QJniObject usbService = QJniObject::getStaticObjectField("android/content/Context",
+                                                            "USB_SERVICE",
+                                                            "Ljava/lang/String;");
+    if (!usbService.isValid())
     {
-        ui->serialCB->addItem(info.portName());
+        //logger("fail to get usb service");
+        return;
     }
+
+    QJniObject appContext = QJniObject(QNativeInterface::QAndroidApplication::context());
+    QJniObject activity = QJniObject(appContext);
+
+    QJniObject usbManager = activity.callObjectMethod("getSystemService",
+                                                      "(Ljava/lang/String;)Ljava/lang/Object;",
+                                                      usbService.object<jstring>());
+    if (!usbManager.isValid())
+    {
+        //logger("fail to get usb manager");
+        return;
+    }
+
+    QJniObject usbDeviceListHashMap = usbManager.callObjectMethod("getDeviceList",
+                                                           "()Ljava/util/HashMap;");
+    QJniObject devListKeySet = usbDeviceListHashMap.callObjectMethod("keySet",
+                                                       "()Ljava/util/Set;");
+    QJniObject devListIter = devListKeySet.callObjectMethod("iterator",
+                                                       "()Ljava/util/Iterator;");
+    jint devListSize = usbDeviceListHashMap.callMethod<jint>("size", "()I");
+
+    QJniObject usbDevObj;
+    QJniObject usbDevObjIter;
+    int vid = 0, pid = 0;
+    QString devName;
+    for (int i = 0; i < devListSize; ++i)
+    {
+        usbDevObjIter = devListIter.callObjectMethod("next",
+                                            "()Ljava/lang/Object;");
+        usbDevObj = usbDeviceListHashMap.callObjectMethod("get",
+                                                   "(Ljava/lang/Object;)Ljava/lang/Object;",
+                                                   usbDevObjIter.object());
+        vid = usbDevObj.callMethod<jint>("getVendorId", "()I");
+        pid = usbDevObj.callMethod<jint>("getProductId", "()I");
+        //QAndroidJniObject str((usbDevObj.callMethod<jstring>("getDeviceName", "()Ljava/lang/String;"));
+        QJniObject str( usbDevObj.callObjectMethod(
+                                   "getDeviceName",
+                                   "()Ljava/lang/String;"
+                               ).object<jstring>());
+       devName = str.toString();
+
+        ui->serialCB_3->addItem(devName);
+    }
+
 }
 
 void MainWidget::slot_changeDebugMode()
 {
-    int nIndex=ui->stackedWidget->currentIndex();
-    if(nIndex<2)
+    int nIndex=ui->stackedWidget_3->currentIndex();
+    if(nIndex<1)
     {
-        ui->stackedWidget->setCurrentIndex(2);
+        ui->stackedWidget_3->setCurrentIndex(1);
     }else
     {
-        ui->stackedWidget->setCurrentIndex(1);
+        ui->stackedWidget_3->setCurrentIndex(0);
     }
 }
 
@@ -439,99 +421,101 @@ void MainWidget::setNumOnLabel(QLabel *lbl, QString strS, long num)
 {
     // 标签显示
     QString strN;
-    strN.sprintf("%ld", num);
+    strN=QString("CH%1").arg(num);
     QString str = strS + strN;
     lbl->setText(str);
 }
 
 
-void MainWidget::on_pushButton_L1_clicked()
-{
-    m_CurPhase=1;
-    ui->pushButton_L1->setIcon(QIcon("resource/Started.png"));
-    ui->pushButton_L2->setIcon(QIcon("resource/Reset.png"));
-    ui->pushButton_L3->setIcon(QIcon("resource/Reset.png"));
-}
-
-void MainWidget::on_pushButton_L2_clicked()
+void MainWidget::UpdateStatusInfo()
 {
-    m_CurPhase=2;
-    ui->pushButton_L1->setIcon(QIcon("resource/Reset.png"));
-    ui->pushButton_L2->setIcon(QIcon("resource/Started.png"));
-    ui->pushButton_L3->setIcon(QIcon("resource/Reset.png"));
-}
 
-void MainWidget::on_pushButton_L3_clicked()
-{
-    m_CurPhase=3;
-    ui->pushButton_L1->setIcon(QIcon("resource/Reset.png"));
-    ui->pushButton_L2->setIcon(QIcon("resource/Reset.png"));
-    ui->pushButton_L3->setIcon(QIcon("resource/Started.png"));
-}
+    QString strTemp;
+    //更新传感器及日期时间
+    m_PDUAllInfo.Sensor_Temperature=24.5;
+    m_PDUAllInfo.Sensor_Humidity=66.72;
+    m_PDUAllInfo.Sensor_INTemperature=82.33;
+    m_PDUAllInfo.Sensor_OUTTemperature=53.89;
 
-void MainWidget::on_pushButton_ALLOPEN_clicked()
-{
-    QMessageBox::StandardButton confimBtn = QMessageBox::question(this, "确认", "是否打开全部通道?", QMessageBox::Ok | QMessageBox::Cancel);
-    if (confimBtn == QMessageBox::Cancel) {
-        return;
-    }
-    else
+    strTemp=QString::number(m_PDUAllInfo.Sensor_Temperature, 'f', 2);
+    ui->label_temperature->setText(strTemp);
+    strTemp=QString::number(m_PDUAllInfo.Sensor_Humidity, 'f', 2);
+    ui->label_humidity->setText(strTemp);
+    if(!m_PDUAllInfo.Sensor_WaterImmersion)
     {
-        return;
-    }
-}
-
-void MainWidget::on_pushButton_ALLCLOSE_clicked()
-{
-    QMessageBox::StandardButton confimBtn = QMessageBox::question(this, "确认", "是否关闭全部通道?", QMessageBox::Ok | QMessageBox::Cancel);
-    if (confimBtn == QMessageBox::Cancel) {
-        return;
+        ui->label_water->setText("未浸入");
+        ui->label_water->setStyleSheet("color: rgb(10, 197, 50);");
     }
     else
     {
-        return;
+        ui->label_water->setText("浸入");
+        // 切换颜色
+        QColor currentColor = ui->label_water->palette().color(QPalette::WindowText);
+        if (currentColor == Qt::white) {
+            ui->label_water->setStyleSheet("color: red;");
+        } else {
+            ui->label_water->setStyleSheet("color: white;");
+        }
     }
-}
-void MainWidget::UpdateStatusInfo()
-{
-    QString strTemp;
-    //更新传感器
-    strTemp.sprintf("%0.2f", m_PDUAllInfo.Sensor_Temperature);
-    ui->label_temperature->setText(strTemp);
-    strTemp.sprintf("%0.2f", m_PDUAllInfo.Sensor_Humidity);
-    ui->label_humidity->setText(strTemp);
-    strTemp.sprintf("%0.2f", m_PDUAllInfo.Sensor_WaterImmersion);//水浸温度
-    //ui->label_temperature->setText(strTemp);
-    strTemp.sprintf("%0.2f", m_PDUAllInfo.Sensor_INTemperature);//进液温度
-    //ui->label_humidity->setText(strTemp);
-    strTemp.sprintf("%0.2f", m_PDUAllInfo.Sensor_OUTTemperature);//出液温度
-   // ui->label_humidity->setText(strTemp);
 
-    //更新总体电源状态
-    if(1==m_CurPhase)
-    {
-        strTemp.sprintf("%0.3f", m_PDUAllInfo.AllPower_L1);
-        ui->lineEdit_TotalPower->setText(strTemp);
-        strTemp.sprintf("%0.3f", m_PDUAllInfo.AllConsumption_L1);
-        ui->lineEdit_TotalConsumption->setText(strTemp);
+    strTemp=QString::number(m_PDUAllInfo.Sensor_INTemperature, 'f', 2);//进液温度
+    ui->label_INT->setText(strTemp);
+    strTemp=QString::number(m_PDUAllInfo.Sensor_OUTTemperature, 'f', 2);//出液温度
+    ui->label_OUTT->setText(strTemp);
 
-    }
-    else if(2==m_CurPhase)
-    {
-        strTemp.sprintf("%0.3f", m_PDUAllInfo.AllPower_L2);
-        ui->lineEdit_TotalPower->setText(strTemp);
-        strTemp.sprintf("%0.3f", m_PDUAllInfo.AllConsumption_L2);
-        ui->lineEdit_TotalConsumption->setText(strTemp);
+    QDateTime currentDateTime = QDateTime::currentDateTime();
+    QDate currentDate = currentDateTime.date();
+    QTime currentTime = currentDateTime.time();
 
-    }
-    else if(3==m_CurPhase)
-    {
-        strTemp.sprintf("%0.3f", m_PDUAllInfo.AllPower_L3);
-        ui->lineEdit_TotalPower->setText(strTemp);
-        strTemp.sprintf("%0.3f", m_PDUAllInfo.AllConsumption_L3);
-        ui->lineEdit_TotalConsumption->setText(strTemp);
+    // 以字符串形式显示当前日期和时间
+    QString dateString = currentDate.toString("yyyy-MM-dd");
+    QString timeString = currentTime.toString("HH:mm:ss");
+    ui->label_Date->setText(dateString);
+    ui->label_Time->setText(timeString);
+
+
+    //更新总体电源状态
+    m_PDUAllInfo.AllVoltage_L1+=0.2;
+    m_PDUAllInfo.AllVoltage_L2+=0.6;
+    m_PDUAllInfo.AllVoltage_L3+=0.3;
+    m_PDUAllInfo.AllCurrent_L1+=0.1;
+    m_PDUAllInfo.AllCurrent_L2+=0.2;
+    m_PDUAllInfo.AllCurrent_L3+=0.3;
+    m_PDUAllInfo.AllPower_L1+=0.01;
+    m_PDUAllInfo.AllPower_L2+=0.02;
+    m_PDUAllInfo.AllPower_L3+=0.03;
+    m_PDUAllInfo.AllConsumption_L1+=0.05;
+    m_PDUAllInfo.AllConsumption_L2+=0.09;
+    m_PDUAllInfo.AllConsumption_L3+=0.03;
+
+
+    strTemp=QString::number(m_PDUAllInfo.AllVoltage_L1, 'f', 2);
+    ui->label_V1->setText(strTemp);
+    strTemp=QString::number(m_PDUAllInfo.AllCurrent_L1, 'f', 2);
+    ui->label_I1->setText(strTemp);
+    strTemp=QString::number(m_PDUAllInfo.AllPower_L1, 'f', 2);
+    //ui->label_P1->setText(strTemp);
+    strTemp=QString::number(m_PDUAllInfo.AllConsumption_L1, 'f', 2);
+    //ui->label_C1->setText(strTemp);
+
+    strTemp=QString::number(m_PDUAllInfo.AllVoltage_L2, 'f', 2);
+    ui->label_V2->setText(strTemp);
+    strTemp=QString::number(m_PDUAllInfo.AllCurrent_L2, 'f', 2);
+    ui->label_I2->setText(strTemp);
+    strTemp=QString::number(m_PDUAllInfo.AllPower_L2, 'f', 2);
+    //ui->label_P2->setText(strTemp);
+    strTemp=QString::number(m_PDUAllInfo.AllConsumption_L2, 'f', 2);
+    //ui->label_C2->setText(strTemp);
+
+    strTemp=QString::number(m_PDUAllInfo.AllVoltage_L3, 'f', 2);
+    ui->label_V3->setText(strTemp);
+    strTemp=QString::number(m_PDUAllInfo.AllCurrent_L3, 'f', 2);
+    ui->label_I3->setText(strTemp);
+    strTemp=QString::number(m_PDUAllInfo.AllPower_L3, 'f', 2);
+    //ui->label_P3->setText(strTemp);
+    strTemp=QString::number(m_PDUAllInfo.AllConsumption_L3, 'f', 2);
+    //ui->label_C3->setText(strTemp);
 
-    }
 
     //更新通道信息
     for (int i=0;i<64;i++) {
@@ -542,6 +526,14 @@ void MainWidget::UpdateStatusInfo()
         m_PDUCHInfo[i].CHFactor=0.983;
         if(i%2==0)m_PDUCHInfo[i].CHStatus=true;
     }
-    InitCHTable(m_TotalCHNum,false);
-}
 
+
+    for (int i=0;i<m_TotalCHNum;i++) {
+       m_chWidget[i].chid=i+1;
+       m_chWidget[i].chV=m_PDUCHInfo[i].CHVoltage;
+       m_chWidget[i].chI=m_PDUCHInfo[i].CHCurrent;
+       m_chWidget[i].chStatus=m_PDUCHInfo[i].CHStatus;
+       m_chWidget[i].UpdateStatusInfo();
+    }
+
+}

+ 5 - 14
Qt/Android/SmartPDU_QT/mainwidget.h

@@ -5,6 +5,8 @@
 #include <QWidget>
 #include <QTimer>
 #include "USB485_Ctrl.h"
+#include "widget.h"
+#include <QJniObject>
 
 QT_BEGIN_NAMESPACE
 namespace Ui { class MainWidget; }
@@ -32,7 +34,7 @@ struct PDUAllInfo
 
     float Sensor_Temperature=0;
     float Sensor_Humidity=0;
-    float Sensor_WaterImmersion=0;
+    bool Sensor_WaterImmersion=true;
     float Sensor_INTemperature=0;
     float Sensor_OUTTemperature=0;
 };
@@ -60,7 +62,7 @@ public:
 
     void InitUI();
     void InitConnect();
-    void InitCHTable(int CHNum,bool initFlag);
+    bool InitSerial();
 private slots:
     /*手动连接槽函数*/
     void manual_serialPortReadyRead();
@@ -79,17 +81,6 @@ private slots:
     void on_Button_checkserial_clicked();
 
     void slot_changeDebugMode();
-    void on_pushButton_6_clicked();
-
-    void on_pushButton_L1_clicked();
-
-    void on_pushButton_L2_clicked();
-
-    void on_pushButton_L3_clicked();
-
-    void on_pushButton_ALLOPEN_clicked();
-
-    void on_pushButton_ALLCLOSE_clicked();
 
     void UpdateStatusInfo();
 
@@ -112,10 +103,10 @@ private:
     Usb485_Ctrl m_USBCtrl;
 
     int m_TotalCHNum;
-    int m_CurPhase;
 
     PDUAllInfo m_PDUAllInfo;
     PDUCHInfo m_PDUCHInfo[64];
 
+    Widget m_chWidget[64];
 };
 #endif // MAINWIDGET_H

File diff suppressed because it is too large
+ 1706 - 705
Qt/Android/SmartPDU_QT/mainwidget.ui


+ 10 - 0
Qt/Android/SmartPDU_QT/pduresource.qrc

@@ -0,0 +1,10 @@
+<RCC>
+    <qresource prefix="/">
+        <file>resource/close.png</file>
+        <file>resource/open.png</file>
+        <file>resource/Reset.png</file>
+        <file>resource/Serial.png</file>
+        <file>resource/Started.png</file>
+        <file>resource/Trigger.png</file>
+    </qresource>
+</RCC>

BIN
Qt/Android/SmartPDU_QT/resource/Serial.png


+ 85 - 0
Qt/Android/SmartPDU_QT/widget.cpp

@@ -0,0 +1,85 @@
+#include "widget.h"
+#include "ui_widget.h"
+
+#include <QPainter>
+#include <QTimer>
+#include <QtMath>
+
+Widget::Widget(QWidget *parent)
+    : QWidget(parent)
+    , ui(new Ui::Widget)
+{
+    setWindowFlags(Qt::CustomizeWindowHint|Qt::FramelessWindowHint);
+    ui->setupUi(this);
+    setFixedSize(480,160);
+
+    ui->frame_ch->setFrameShadow(QFrame::Plain); // 设置边框阴影为无(或根据需要设置为其他值)
+    ui->frame_ch->setLineWidth(2); // 设置边框宽度
+
+    QPainter painter(this);
+    initCanvas(painter);
+
+}
+
+Widget::~Widget()
+{
+    delete ui;
+}
+
+
+void Widget::initCanvas(QPainter& painter)
+{
+    //抗锯齿
+    painter.setRenderHint(QPainter::Antialiasing,true);
+    //底色设置成黑色
+    painter.setBrush(Qt::gray);
+    painter.drawRect(rect());
+}
+
+void Widget::UpdateStatusInfo()
+{
+    QString strTemp;
+    //更新传感器及日期时间
+    strTemp=QString("%1").arg(chid);
+    ui->label_chid->setText(strTemp);
+    if(chStatus)
+    {
+        ui->pushButton_ch->setIcon(QIcon(":/resource/open.png"));
+        ui->label_chid->setStyleSheet("color: rgb(10, 197, 50);border: none;");
+        ui->label_chV->setStyleSheet("color: rgb(10, 197, 50);border: none;");
+        ui->label_chI->setStyleSheet("color: rgb(10, 197, 50);border: none;");
+        ui->label_2->setStyleSheet("color: rgb(10, 197, 50);border: none;");
+        ui->label_4->setStyleSheet("color: rgb(10, 197, 50);border: none;");
+        ui->label_5->setStyleSheet("color: rgb(10, 197, 50);border: none;");
+        ui->label_7->setStyleSheet("color: rgb(10, 197, 50);border: none;");
+
+        QPalette palette = ui->frame_ch->palette();
+        palette.setColor(QPalette::Window, QColor(0, 255, 0));
+        ui->frame_ch->setStyleSheet("QFrame { border: 2px solid rgb(10, 197, 50); border-radius: 0px; }");
+    }
+    else
+    {
+        ui->pushButton_ch->setIcon(QIcon(":/resource/close.png"));
+        ui->label_chid->setStyleSheet("color: red;border: none;");
+        ui->label_chV->setStyleSheet("color: red;border: none;");
+        ui->label_chI->setStyleSheet("color: red;border: none;");
+        ui->label_2->setStyleSheet("color: red;border: none;");
+        ui->label_4->setStyleSheet("color: red;border: none;");
+        ui->label_5->setStyleSheet("color: red;border: none;");
+        ui->label_7->setStyleSheet("color: red;border: none;");
+
+        QPalette palette = ui->frame_ch->palette();
+        palette.setColor(QPalette::Window, QColor(255, 0, 0));
+        ui->frame_ch->setStyleSheet("QFrame { border: 2px solid red; border-radius: 0px; }");
+    }
+
+    strTemp=QString::number(chV, 'f', 2);
+    ui->label_chV->setText(strTemp);
+    strTemp=QString::number(chI, 'f', 2);
+    ui->label_chI->setText(strTemp);
+
+
+
+}
+
+

+ 32 - 0
Qt/Android/SmartPDU_QT/widget.h

@@ -0,0 +1,32 @@
+#ifndef WIDGET_H
+#define WIDGET_H
+
+#include <QWidget>
+
+QT_BEGIN_NAMESPACE
+namespace Ui { class Widget; }
+QT_END_NAMESPACE
+
+class Widget : public QWidget
+{
+    Q_OBJECT
+
+public:
+    Widget(QWidget *parent = nullptr);
+    ~Widget();
+private:
+    Ui::Widget *ui;
+    QTimer *timer;
+public:
+    void initCanvas(QPainter& painter);
+    void UpdateStatusInfo();
+
+    int chid=0;
+    float chV=0;
+    float chI=0;
+    bool chStatus=false;
+};
+#endif // WIDGET_H
+
+
+

+ 325 - 0
Qt/Android/SmartPDU_QT/widget.ui

@@ -0,0 +1,325 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ui version="4.0">
+ <class>Widget</class>
+ <widget class="QWidget" name="Widget">
+  <property name="geometry">
+   <rect>
+    <x>0</x>
+    <y>0</y>
+    <width>500</width>
+    <height>180</height>
+   </rect>
+  </property>
+  <property name="windowTitle">
+   <string>汽车仪表盘</string>
+  </property>
+  <layout class="QHBoxLayout" name="horizontalLayout_4">
+   <property name="spacing">
+    <number>0</number>
+   </property>
+   <property name="leftMargin">
+    <number>0</number>
+   </property>
+   <property name="topMargin">
+    <number>0</number>
+   </property>
+   <property name="rightMargin">
+    <number>0</number>
+   </property>
+   <property name="bottomMargin">
+    <number>0</number>
+   </property>
+   <item>
+    <widget class="QFrame" name="frame_ch">
+     <property name="frameShape">
+      <enum>QFrame::StyledPanel</enum>
+     </property>
+     <property name="frameShadow">
+      <enum>QFrame::Raised</enum>
+     </property>
+     <layout class="QHBoxLayout" name="horizontalLayout_3">
+      <item>
+       <spacer name="horizontalSpacer_5">
+        <property name="orientation">
+         <enum>Qt::Horizontal</enum>
+        </property>
+        <property name="sizeHint" stdset="0">
+         <size>
+          <width>40</width>
+          <height>20</height>
+         </size>
+        </property>
+       </spacer>
+      </item>
+      <item>
+       <widget class="QPushButton" name="pushButton_ch">
+        <property name="minimumSize">
+         <size>
+          <width>20</width>
+          <height>20</height>
+         </size>
+        </property>
+        <property name="maximumSize">
+         <size>
+          <width>16777194</width>
+          <height>16777215</height>
+         </size>
+        </property>
+        <property name="text">
+         <string/>
+        </property>
+        <property name="flat">
+         <bool>true</bool>
+        </property>
+       </widget>
+      </item>
+      <item>
+       <widget class="QLabel" name="label_chid">
+        <property name="font">
+         <font>
+          <pointsize>46</pointsize>
+          <weight>75</weight>
+          <bold>true</bold>
+         </font>
+        </property>
+        <property name="text">
+         <string>0</string>
+        </property>
+        <property name="alignment">
+         <set>Qt::AlignCenter</set>
+        </property>
+       </widget>
+      </item>
+      <item>
+       <spacer name="horizontalSpacer_6">
+        <property name="orientation">
+         <enum>Qt::Horizontal</enum>
+        </property>
+        <property name="sizeHint" stdset="0">
+         <size>
+          <width>54</width>
+          <height>17</height>
+         </size>
+        </property>
+       </spacer>
+      </item>
+      <item>
+       <layout class="QVBoxLayout" name="verticalLayout">
+        <item>
+         <spacer name="verticalSpacer">
+          <property name="orientation">
+           <enum>Qt::Vertical</enum>
+          </property>
+          <property name="sizeHint" stdset="0">
+           <size>
+            <width>20</width>
+            <height>40</height>
+           </size>
+          </property>
+         </spacer>
+        </item>
+        <item>
+         <layout class="QHBoxLayout" name="horizontalLayout">
+          <item>
+           <widget class="QLabel" name="label_2">
+            <property name="font">
+             <font>
+              <family>微软雅黑</family>
+              <pointsize>22</pointsize>
+             </font>
+            </property>
+            <property name="text">
+             <string>电压:</string>
+            </property>
+            <property name="alignment">
+             <set>Qt::AlignCenter</set>
+            </property>
+           </widget>
+          </item>
+          <item>
+           <spacer name="horizontalSpacer_2">
+            <property name="orientation">
+             <enum>Qt::Horizontal</enum>
+            </property>
+            <property name="sizeHint" stdset="0">
+             <size>
+              <width>40</width>
+              <height>20</height>
+             </size>
+            </property>
+           </spacer>
+          </item>
+          <item>
+           <widget class="QLabel" name="label_chV">
+            <property name="font">
+             <font>
+              <family>微软雅黑</family>
+              <pointsize>22</pointsize>
+             </font>
+            </property>
+            <property name="text">
+             <string>0</string>
+            </property>
+            <property name="alignment">
+             <set>Qt::AlignCenter</set>
+            </property>
+           </widget>
+          </item>
+          <item>
+           <spacer name="horizontalSpacer">
+            <property name="orientation">
+             <enum>Qt::Horizontal</enum>
+            </property>
+            <property name="sizeHint" stdset="0">
+             <size>
+              <width>40</width>
+              <height>20</height>
+             </size>
+            </property>
+           </spacer>
+          </item>
+          <item>
+           <widget class="QLabel" name="label_4">
+            <property name="font">
+             <font>
+              <family>微软雅黑</family>
+              <pointsize>22</pointsize>
+             </font>
+            </property>
+            <property name="text">
+             <string>V</string>
+            </property>
+            <property name="alignment">
+             <set>Qt::AlignCenter</set>
+            </property>
+           </widget>
+          </item>
+         </layout>
+        </item>
+        <item>
+         <spacer name="verticalSpacer_2">
+          <property name="orientation">
+           <enum>Qt::Vertical</enum>
+          </property>
+          <property name="sizeHint" stdset="0">
+           <size>
+            <width>20</width>
+            <height>13</height>
+           </size>
+          </property>
+         </spacer>
+        </item>
+        <item>
+         <layout class="QHBoxLayout" name="horizontalLayout_2">
+          <item>
+           <widget class="QLabel" name="label_7">
+            <property name="font">
+             <font>
+              <family>微软雅黑</family>
+              <pointsize>22</pointsize>
+             </font>
+            </property>
+            <property name="text">
+             <string>电流:</string>
+            </property>
+            <property name="alignment">
+             <set>Qt::AlignCenter</set>
+            </property>
+           </widget>
+          </item>
+          <item>
+           <spacer name="horizontalSpacer_3">
+            <property name="orientation">
+             <enum>Qt::Horizontal</enum>
+            </property>
+            <property name="sizeHint" stdset="0">
+             <size>
+              <width>40</width>
+              <height>20</height>
+             </size>
+            </property>
+           </spacer>
+          </item>
+          <item>
+           <widget class="QLabel" name="label_chI">
+            <property name="font">
+             <font>
+              <family>微软雅黑</family>
+              <pointsize>22</pointsize>
+             </font>
+            </property>
+            <property name="text">
+             <string>0</string>
+            </property>
+            <property name="alignment">
+             <set>Qt::AlignCenter</set>
+            </property>
+           </widget>
+          </item>
+          <item>
+           <spacer name="horizontalSpacer_4">
+            <property name="orientation">
+             <enum>Qt::Horizontal</enum>
+            </property>
+            <property name="sizeHint" stdset="0">
+             <size>
+              <width>40</width>
+              <height>20</height>
+             </size>
+            </property>
+           </spacer>
+          </item>
+          <item>
+           <widget class="QLabel" name="label_5">
+            <property name="font">
+             <font>
+              <family>微软雅黑</family>
+              <pointsize>22</pointsize>
+             </font>
+            </property>
+            <property name="text">
+             <string>A</string>
+            </property>
+            <property name="alignment">
+             <set>Qt::AlignCenter</set>
+            </property>
+           </widget>
+          </item>
+         </layout>
+        </item>
+        <item>
+         <spacer name="verticalSpacer_3">
+          <property name="orientation">
+           <enum>Qt::Vertical</enum>
+          </property>
+          <property name="sizeHint" stdset="0">
+           <size>
+            <width>20</width>
+            <height>40</height>
+           </size>
+          </property>
+         </spacer>
+        </item>
+       </layout>
+      </item>
+      <item>
+       <spacer name="horizontalSpacer_7">
+        <property name="orientation">
+         <enum>Qt::Horizontal</enum>
+        </property>
+        <property name="sizeHint" stdset="0">
+         <size>
+          <width>59</width>
+          <height>17</height>
+         </size>
+        </property>
+       </spacer>
+      </item>
+     </layout>
+    </widget>
+   </item>
+  </layout>
+ </widget>
+ <resources/>
+ <connections/>
+</ui>