├── .gradle ├── 7.3.3 │ ├── gc.properties │ ├── fileChanges │ │ └── last-build.bin │ ├── dependencies-accessors │ │ ├── gc.properties │ │ └── dependencies-accessors.lock │ ├── checksums │ │ ├── checksums.lock │ │ ├── md5-checksums.bin │ │ ├── sha1-checksums.bin │ │ ├── sha256-checksums.bin │ │ └── sha512-checksums.bin │ ├── fileHashes │ │ ├── fileHashes.bin │ │ ├── fileHashes.lock │ │ └── resourceHashesCache.bin │ └── executionHistory │ │ ├── executionHistory.bin │ │ └── executionHistory.lock ├── vcs-1 │ └── gc.properties ├── buildOutputCleanup │ ├── cache.properties │ ├── outputFiles.bin │ └── buildOutputCleanup.lock ├── file-system.probe └── checksums │ ├── checksums.lock │ ├── md5-checksums.bin │ ├── sha1-checksums.bin │ ├── sha256-checksums.bin │ └── sha512-checksums.bin ├── jitpack.yml ├── settings.gradle ├── app ├── src │ └── main │ │ ├── res │ │ ├── values │ │ │ ├── strings.xml │ │ │ ├── colors.xml │ │ │ └── themes.xml │ │ ├── mipmap-hdpi │ │ │ ├── ic_launcher.webp │ │ │ └── ic_launcher_round.webp │ │ ├── mipmap-mdpi │ │ │ ├── ic_launcher.webp │ │ │ └── ic_launcher_round.webp │ │ ├── mipmap-xhdpi │ │ │ ├── ic_launcher.webp │ │ │ └── ic_launcher_round.webp │ │ ├── mipmap-xxhdpi │ │ │ ├── ic_launcher.webp │ │ │ └── ic_launcher_round.webp │ │ ├── mipmap-xxxhdpi │ │ │ ├── ic_launcher.webp │ │ │ └── ic_launcher_round.webp │ │ ├── mipmap-anydpi-v26 │ │ │ ├── ic_launcher.xml │ │ │ └── ic_launcher_round.xml │ │ ├── xml │ │ │ ├── backup_rules.xml │ │ │ └── data_extraction_rules.xml │ │ ├── values-night │ │ │ └── themes.xml │ │ ├── drawable-v24 │ │ │ └── ic_launcher_foreground.xml │ │ ├── layout │ │ │ └── activity_main.xml │ │ └── drawable │ │ │ └── ic_launcher_background.xml │ │ ├── AndroidManifest.xml │ │ └── java │ │ ├── ink │ │ └── itwo │ │ │ └── lib │ │ │ └── modbus │ │ │ └── MainActivity.kt │ │ └── android_serialport_api │ │ └── SerialPort.java ├── libs │ ├── x86 │ │ └── libserial_port.so │ ├── x86_64 │ │ └── libserial_port.so │ ├── arm64-v8a │ │ └── libserial_port.so │ └── armeabi-v7a │ │ └── libserial_port.so └── build.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── modbus ├── src │ └── main │ │ ├── AndroidManifest.xml │ │ └── java │ │ └── ink │ │ └── itwo │ │ └── lib │ │ └── modbus │ │ ├── Ext.kt │ │ └── ModbusMaster.kt └── build.gradle ├── .gitignore ├── gradle.properties ├── gradlew.bat ├── README.md └── gradlew /.gradle/7.3.3/gc.properties: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.gradle/vcs-1/gc.properties: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /jitpack.yml: -------------------------------------------------------------------------------- 1 | jdk: 2 | - openjdk11 -------------------------------------------------------------------------------- /.gradle/7.3.3/fileChanges/last-build.bin: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.gradle/7.3.3/dependencies-accessors/gc.properties: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | 2 | rootProject.name = "modbus" 3 | include ':app' 4 | include ':modbus' 5 | -------------------------------------------------------------------------------- /.gradle/buildOutputCleanup/cache.properties: -------------------------------------------------------------------------------- 1 | #Tue May 23 10:41:53 CST 2023 2 | gradle.version=7.3.3 3 | -------------------------------------------------------------------------------- /.gradle/file-system.probe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hzlaoliu/modbus-master-kt/HEAD/.gradle/file-system.probe -------------------------------------------------------------------------------- /app/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | modbus 3 | -------------------------------------------------------------------------------- /app/libs/x86/libserial_port.so: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hzlaoliu/modbus-master-kt/HEAD/app/libs/x86/libserial_port.so -------------------------------------------------------------------------------- /.gradle/checksums/checksums.lock: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hzlaoliu/modbus-master-kt/HEAD/.gradle/checksums/checksums.lock -------------------------------------------------------------------------------- /app/libs/x86_64/libserial_port.so: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hzlaoliu/modbus-master-kt/HEAD/app/libs/x86_64/libserial_port.so -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hzlaoliu/modbus-master-kt/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /.gradle/checksums/md5-checksums.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hzlaoliu/modbus-master-kt/HEAD/.gradle/checksums/md5-checksums.bin -------------------------------------------------------------------------------- /.gradle/checksums/sha1-checksums.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hzlaoliu/modbus-master-kt/HEAD/.gradle/checksums/sha1-checksums.bin -------------------------------------------------------------------------------- /app/libs/arm64-v8a/libserial_port.so: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hzlaoliu/modbus-master-kt/HEAD/app/libs/arm64-v8a/libserial_port.so -------------------------------------------------------------------------------- /.gradle/7.3.3/checksums/checksums.lock: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hzlaoliu/modbus-master-kt/HEAD/.gradle/7.3.3/checksums/checksums.lock -------------------------------------------------------------------------------- /.gradle/checksums/sha256-checksums.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hzlaoliu/modbus-master-kt/HEAD/.gradle/checksums/sha256-checksums.bin -------------------------------------------------------------------------------- /.gradle/checksums/sha512-checksums.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hzlaoliu/modbus-master-kt/HEAD/.gradle/checksums/sha512-checksums.bin -------------------------------------------------------------------------------- /app/libs/armeabi-v7a/libserial_port.so: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hzlaoliu/modbus-master-kt/HEAD/app/libs/armeabi-v7a/libserial_port.so -------------------------------------------------------------------------------- /.gradle/7.3.3/checksums/md5-checksums.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hzlaoliu/modbus-master-kt/HEAD/.gradle/7.3.3/checksums/md5-checksums.bin -------------------------------------------------------------------------------- /.gradle/7.3.3/fileHashes/fileHashes.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hzlaoliu/modbus-master-kt/HEAD/.gradle/7.3.3/fileHashes/fileHashes.bin -------------------------------------------------------------------------------- /.gradle/7.3.3/fileHashes/fileHashes.lock: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hzlaoliu/modbus-master-kt/HEAD/.gradle/7.3.3/fileHashes/fileHashes.lock -------------------------------------------------------------------------------- /.gradle/7.3.3/checksums/sha1-checksums.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hzlaoliu/modbus-master-kt/HEAD/.gradle/7.3.3/checksums/sha1-checksums.bin -------------------------------------------------------------------------------- /.gradle/buildOutputCleanup/outputFiles.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hzlaoliu/modbus-master-kt/HEAD/.gradle/buildOutputCleanup/outputFiles.bin -------------------------------------------------------------------------------- /.gradle/7.3.3/checksums/sha256-checksums.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hzlaoliu/modbus-master-kt/HEAD/.gradle/7.3.3/checksums/sha256-checksums.bin -------------------------------------------------------------------------------- /.gradle/7.3.3/checksums/sha512-checksums.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hzlaoliu/modbus-master-kt/HEAD/.gradle/7.3.3/checksums/sha512-checksums.bin -------------------------------------------------------------------------------- /app/src/main/res/mipmap-hdpi/ic_launcher.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hzlaoliu/modbus-master-kt/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher.webp -------------------------------------------------------------------------------- /app/src/main/res/mipmap-mdpi/ic_launcher.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hzlaoliu/modbus-master-kt/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher.webp -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xhdpi/ic_launcher.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hzlaoliu/modbus-master-kt/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher.webp -------------------------------------------------------------------------------- /.gradle/7.3.3/fileHashes/resourceHashesCache.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hzlaoliu/modbus-master-kt/HEAD/.gradle/7.3.3/fileHashes/resourceHashesCache.bin -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxhdpi/ic_launcher.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hzlaoliu/modbus-master-kt/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hzlaoliu/modbus-master-kt/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp -------------------------------------------------------------------------------- /.gradle/7.3.3/executionHistory/executionHistory.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hzlaoliu/modbus-master-kt/HEAD/.gradle/7.3.3/executionHistory/executionHistory.bin -------------------------------------------------------------------------------- /.gradle/buildOutputCleanup/buildOutputCleanup.lock: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hzlaoliu/modbus-master-kt/HEAD/.gradle/buildOutputCleanup/buildOutputCleanup.lock -------------------------------------------------------------------------------- /app/src/main/res/mipmap-hdpi/ic_launcher_round.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hzlaoliu/modbus-master-kt/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp -------------------------------------------------------------------------------- /app/src/main/res/mipmap-mdpi/ic_launcher_round.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hzlaoliu/modbus-master-kt/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp -------------------------------------------------------------------------------- /.gradle/7.3.3/executionHistory/executionHistory.lock: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hzlaoliu/modbus-master-kt/HEAD/.gradle/7.3.3/executionHistory/executionHistory.lock -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hzlaoliu/modbus-master-kt/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hzlaoliu/modbus-master-kt/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hzlaoliu/modbus-master-kt/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp -------------------------------------------------------------------------------- /.gradle/7.3.3/dependencies-accessors/dependencies-accessors.lock: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hzlaoliu/modbus-master-kt/HEAD/.gradle/7.3.3/dependencies-accessors/dependencies-accessors.lock -------------------------------------------------------------------------------- /modbus/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Thu Apr 27 16:24:32 CST 2023 2 | distributionBase=GRADLE_USER_HOME 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.3.3-bin.zip 4 | distributionPath=wrapper/dists 5 | zipStorePath=wrapper/dists 6 | zipStoreBase=GRADLE_USER_HOME 7 | -------------------------------------------------------------------------------- /app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | /local.properties 3 | /.idea/caches 4 | /.idea/libraries 5 | /.idea/modules.xml 6 | /.idea/workspace.xml 7 | /.idea/navEditor.xml 8 | /.idea/assetWizardSettings.xml 9 | .DS_Store 10 | /build 11 | /captures 12 | .externalNativeBuild 13 | .cxx 14 | local.properties 15 | .idea 16 | modbus/consumer-rules.pro 17 | modbus/proguard-rules.pro 18 | app/proguard-rules.pro 19 | build/ 20 | modbus/build -------------------------------------------------------------------------------- /app/src/main/res/values/colors.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | #FFBB86FC 4 | #FF6200EE 5 | #FF3700B3 6 | #FF03DAC5 7 | #FF018786 8 | #FF000000 9 | #FFFFFFFF 10 | -------------------------------------------------------------------------------- /app/src/main/res/xml/backup_rules.xml: -------------------------------------------------------------------------------- 1 | 8 | 9 | 13 | -------------------------------------------------------------------------------- /app/src/main/res/xml/data_extraction_rules.xml: -------------------------------------------------------------------------------- 1 | 6 | 7 | 8 | 12 | 13 | 19 | -------------------------------------------------------------------------------- /app/src/main/res/values/themes.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 16 | -------------------------------------------------------------------------------- /app/src/main/res/values-night/themes.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 16 | -------------------------------------------------------------------------------- /app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 16 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /app/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'com.android.application' 3 | id 'org.jetbrains.kotlin.android' 4 | } 5 | 6 | android { 7 | compileSdk 31 8 | 9 | defaultConfig { 10 | applicationId "ink.itwo.lib.modbus" 11 | minSdk 21 12 | targetSdk 31 13 | versionCode 1 14 | versionName "1.0" 15 | 16 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" 17 | } 18 | 19 | buildTypes { 20 | release { 21 | minifyEnabled false 22 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' 23 | } 24 | } 25 | compileOptions { 26 | sourceCompatibility JavaVersion.VERSION_1_8 27 | targetCompatibility JavaVersion.VERSION_1_8 28 | } 29 | kotlinOptions { 30 | jvmTarget = '1.8' 31 | } 32 | } 33 | 34 | dependencies { 35 | 36 | implementation 'androidx.core:core-ktx:1.6.0' 37 | implementation 'androidx.appcompat:appcompat:1.3.0' 38 | implementation 'com.google.android.material:material:1.3.0' 39 | implementation 'androidx.constraintlayout:constraintlayout:2.0.4' 40 | implementation "androidx.lifecycle:lifecycle-runtime-ktx:$rootProject.lifecycle_version" 41 | api project(':modbus') 42 | } -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | # Project-wide Gradle settings. 2 | # IDE (e.g. Android Studio) users: 3 | # Gradle settings configured through the IDE *will override* 4 | # any settings specified in this file. 5 | # For more details on how to configure your build environment visit 6 | # http://www.gradle.org/docs/current/userguide/build_environment.html 7 | # Specifies the JVM arguments used for the daemon process. 8 | # The setting is particularly useful for tweaking memory settings. 9 | org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8 10 | # When configured, Gradle will run in incubating parallel mode. 11 | # This option should only be used with decoupled projects. More details, visit 12 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 13 | # org.gradle.parallel=true 14 | # AndroidX package structure to make it clearer which packages are bundled with the 15 | # Android operating system, and which are packaged with your app"s APK 16 | # https://developer.android.com/topic/libraries/support-library/androidx-rn 17 | android.useAndroidX=true 18 | # Kotlin code style for this project: "official" or "obsolete": 19 | kotlin.code.style=official 20 | # Enables namespacing of each library's R class so that its R class includes only the 21 | # resources declared in the library itself and none from the library's dependencies, 22 | # thereby reducing the size of the R class for that library 23 | android.nonTransitiveRClass=true -------------------------------------------------------------------------------- /modbus/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'com.android.library' 3 | id 'org.jetbrains.kotlin.android' 4 | id 'maven-publish' 5 | } 6 | 7 | android { 8 | compileSdk 31 9 | 10 | defaultConfig { 11 | minSdk 21 12 | targetSdk 31 13 | 14 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" 15 | consumerProguardFiles "consumer-rules.pro" 16 | } 17 | 18 | buildTypes { 19 | release { 20 | minifyEnabled false 21 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' 22 | } 23 | } 24 | compileOptions { 25 | sourceCompatibility JavaVersion.VERSION_1_8 26 | targetCompatibility JavaVersion.VERSION_1_8 27 | } 28 | kotlinOptions { 29 | jvmTarget = '1.8' 30 | } 31 | } 32 | 33 | dependencies { 34 | 35 | // implementation 'androidx.core:core-ktx:1.6.0' 36 | // implementation 'androidx.appcompat:appcompat:1.3.0' 37 | // implementation 'com.google.android.material:material:1.3.0' 38 | // implementation 'androidx.constraintlayout:constraintlayout:2.0.4' 39 | compileOnly "org.jetbrains.kotlinx:kotlinx-coroutines-core:$rootProject.kotlin_version" 40 | compileOnly "org.jetbrains.kotlinx:kotlinx-coroutines-android:$rootProject.kotlin_version" 41 | // implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" 42 | } 43 | 44 | afterEvaluate { 45 | publishing { 46 | publications { 47 | // Creates a Maven publication called "release". 48 | release(MavenPublication) { 49 | from components.release 50 | groupId = 'com.github.hzlaoliu' 51 | artifactId = 'modbus' 52 | version = '0.0.5' 53 | } 54 | } 55 | } 56 | } -------------------------------------------------------------------------------- /app/src/main/res/drawable-v24/ic_launcher_foreground.xml: -------------------------------------------------------------------------------- 1 | 7 | 8 | 9 | 15 | 18 | 21 | 22 | 23 | 24 | 30 | -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 2 | 9 | 10 | 21 | 22 | 33 | 44 | 45 | -------------------------------------------------------------------------------- /app/src/main/java/ink/itwo/lib/modbus/MainActivity.kt: -------------------------------------------------------------------------------- 1 | package ink.itwo.lib.modbus 2 | 3 | import android.os.Bundle 4 | import android.util.Log 5 | import android.view.View 6 | import android_serialport_api.SerialPort 7 | import androidx.appcompat.app.AppCompatActivity 8 | import androidx.lifecycle.lifecycleScope 9 | import kotlinx.coroutines.Dispatchers 10 | import kotlinx.coroutines.async 11 | import kotlinx.coroutines.launch 12 | import java.io.File 13 | 14 | class MainActivity : AppCompatActivity() { 15 | private var modeBus: ModbusMaster? = null 16 | override fun onCreate(savedInstanceState: Bundle?) { 17 | super.onCreate(savedInstanceState) 18 | setContentView(R.layout.activity_main) 19 | 20 | lifecycleScope.async(Dispatchers.IO) { 21 | //RTU模式 22 | val serialPort = SerialPort(File("/dev/ttyS1"), 115200, 1, 8, 0, 0, 0) 23 | modeBus = ModbusMaster.init(ModBusMaserConfig(ModBusMode.RTU), serialPort.inputStream, serialPort.outputStream) 24 | modeBus?.onReceive() 25 | 26 | //TCP模式 27 | // val socket = Socket("192.168.0.1", 5020) 28 | // modeBus = ModbusMaster.init(ModBusMaserConfig(ModBusMode.TCP), socket.getInputStream(), socket.getOutputStream()) 29 | // modeBus?.onReceive() 30 | } 31 | findViewById(R.id.tv_read_01)?.setOnClickListener { 32 | lifecycleScope.launch(Dispatchers.IO) { 33 | //读取从站 =1 的线圈,从0开始读取100个 34 | val response = modeBus?.read(ModbusMaster.createRequestRead01(1, 0, 100)) 35 | Log.d("TAG", "返回的原始数据 ${response?.raw}") 36 | Log.d("TAG", "返回的 BooleanArray 类型的 result ${response?.result}") 37 | } 38 | } 39 | 40 | findViewById(R.id.tv_read_03)?.setOnClickListener { 41 | lifecycleScope.launch(Dispatchers.IO) { 42 | //读取从站 =1 的保持寄存器,从0开始读20个 43 | val response = modeBus?.read(ModbusMaster.createRequestRead03(1, 0, 20)) 44 | Log.d("TAG", "返回的原始数据 ${response?.raw}") 45 | Log.d("TAG", "返回的 ShortArray 类型的 result ${response?.result}") 46 | } 47 | } 48 | 49 | 50 | findViewById(R.id.tv_write_10)?.setOnClickListener { 51 | lifecycleScope.launch(Dispatchers.IO) { 52 | //写从站 =1 的多个寄存器,从200开始写入 [98,25,33] 这三个数据 53 | val response = modeBus?.write(ModbusMaster.createRequestWrite10(1, 200, shortArrayOf(98, 25, 33))) 54 | Log.d("TAG", "返回的原始数据 ${response?.raw}") 55 | Log.d("TAG", "返回的 ByteArray 类型的 pdu ${response?.pdu}") 56 | } 57 | } 58 | 59 | } 60 | } 61 | 62 | 63 | -------------------------------------------------------------------------------- /app/src/main/java/android_serialport_api/SerialPort.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2009 Cedric Priscal 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package android_serialport_api; 17 | 18 | import android.util.Log; 19 | 20 | import java.io.File; 21 | import java.io.FileDescriptor; 22 | import java.io.FileInputStream; 23 | import java.io.FileOutputStream; 24 | import java.io.IOException; 25 | import java.io.InputStream; 26 | import java.io.OutputStream; 27 | 28 | import androidx.annotation.NonNull; 29 | 30 | public final class SerialPort { 31 | 32 | private static final String TAG = "SerialPort"; 33 | 34 | private final FileDescriptor mFd; 35 | 36 | private final FileInputStream mFileInputStream; 37 | 38 | private final FileOutputStream mFileOutputStream; 39 | 40 | public SerialPort(@NonNull File path, int baudRate, int stopBits, int dataBits, int parity, int flowCon, int flags) throws SecurityException, IOException { 41 | 42 | if (!path.canRead() || !path.canWrite()) { 43 | try { 44 | // 获取ROOT权限 45 | Process su = Runtime.getRuntime().exec("/system/bin/su"); 46 | String cmd = "chmod 666 " + path.getAbsolutePath() + "\n" + "exit\n"; 47 | su.getOutputStream().write(cmd.getBytes()); 48 | if ((su.waitFor() != 0) || !path.canRead() || !path.canWrite()) { 49 | Log.e(TAG, "获取指定串口的读写权限异常"); 50 | throw new SecurityException(); 51 | } 52 | } catch (Exception e) { 53 | throw new SecurityException(); 54 | } 55 | } 56 | 57 | mFd = open(path.getAbsolutePath(), baudRate, stopBits, dataBits, parity, flowCon, flags); 58 | if (null == mFd) { 59 | Log.e(TAG, "native open returns null"); 60 | throw new IOException(); 61 | } 62 | mFileInputStream = new FileInputStream(mFd); 63 | mFileOutputStream = new FileOutputStream(mFd); 64 | } 65 | 66 | public InputStream getInputStream() { 67 | return mFileInputStream; 68 | } 69 | 70 | 71 | public OutputStream getOutputStream() { 72 | return mFileOutputStream; 73 | } 74 | 75 | 76 | private native static FileDescriptor open(@NonNull String path, int baudRate, int stopBits, 77 | int dataBits, int parity, int flowCon, int flags); 78 | 79 | public native void close(); 80 | 81 | static { 82 | System.loadLibrary("serial_port"); 83 | } 84 | } -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if "%ERRORLEVEL%"=="0" goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 84 | exit /b 1 85 | 86 | :mainEnd 87 | if "%OS%"=="Windows_NT" endlocal 88 | 89 | :omega 90 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ModbusMaster-KT 框架 2 | 3 | ModbusMaster-KT 框架是一个使用 Kotlin 编写的开源项目,用于实现 Modbus 主站(Master)功能。该框架提供了一组易于使用的 API,帮助开发者快速集成 Modbus 通信功能到他们的应用程序中。 4 | 5 | ## 特性 6 | 7 | - 支持 Modbus TCP 和 Modbus RTU 通信协议。 8 | - 提供了灵活的数据读写接口,包括读取和写入线圈、输入状态、保持寄存器和输入寄存器等功能。 9 | - 支持自定义寄存器地址、数据类型和数据长度。 10 | - 提供了异常处理机制,用于处理 Modbus 从站返回的错误信息。 11 | - 支持多线程操作,可同时处理多个 Modbus 请求。 12 | - 简化了 Modbus 通信的实现细节,减少了开发时间和复杂性。 13 | 14 | ## 安装 15 | 16 | 你可以通过以下方式获取该框架: 17 | 18 | - 下载源代码并手动集成到你的项目中。 19 | - 使用 Maven 或 Gradle 等构建工具,将该框架添加为依赖项。 20 | 21 | ```groovy 22 | allprojects { 23 | repositories { 24 | maven { url 'https://jitpack.io' } 25 | } 26 | } 27 | 28 | dependencies { 29 | implementation 'com.github.hzlaoliu:modbus:1.0.0' 30 | } 31 | ``` 32 | 33 | ## 使用示例 34 | 35 | 下面是一个简单的示例代码,展示了如何使用 Modbus Master 框架进行数据读取: 36 | 37 | #### 初始化 38 | 39 | * 该框架只做 modbus 的数据协议处理,不做链路层的链接。需要自行链接,并用 `inputStream` 和 `outputStream` 初始化框架 40 | 41 | ```kotlin 42 | //RTU模式 43 | val serialPort = SerialPort(File("/dev/ttyS1"), 115200, 1, 8, 0, 0, 0) 44 | modeBus = ModbusMaster.init(ModBusMaserConfig(ModBusMode.RTU), serialPort.inputStream, serialPort.outputStream) 45 | modeBus?.onReceive() 46 | 47 | //TCP模式 48 | val socket = Socket("192.168.0.1", 5020) 49 | modeBus = ModbusMaster.init(ModBusMaserConfig(ModBusMode.TCP), socket.getInputStream(), socket.getOutputStream()) 50 | modeBus?.onReceive() 51 | ``` 52 | 53 | #### 支持的读写 54 | 55 | ```kotlin 56 | /** 读 0x01 ,线圈*/ 57 | fun createRequestRead01(slaveId: Byte, start: Int, num: Int): ReadCoilsRequest = ReadCoilsRequest(slaveId, start, num) 58 | 59 | /** 读 0x02 ,离散寄存器*/ 60 | fun createRequestRead02(slaveId: Byte, start: Int, num: Int): ReadDiscreteRequest = ReadDiscreteRequest(slaveId, start, num) 61 | 62 | /** 读 0x03 ,保持寄存器*/ 63 | fun createRequestRead03(slaveId: Byte, start: Int, num: Int): ReadHoldRegisterRequest = ReadHoldRegisterRequest(slaveId, start, num) 64 | 65 | /** 读 0x04 ,输入寄存器*/ 66 | fun createRequestRead04(slaveId: Byte, start: Int, num: Int): ReadInputRegisterRequest = ReadInputRegisterRequest(slaveId, start, num) 67 | 68 | /** 写 0x05 ,单个线圈*/ 69 | fun createRequestWrite05(slaveId: Byte, start: Int, value: Boolean): WriteCoilOneRequest = WriteCoilOneRequest(slaveId, start, value) 70 | 71 | /** 写 0x06,单个寄存器*/ 72 | fun createRequestWrite06(slaveId: Byte, start: Int, value: Short): WriteRegisterOneRequest = WriteRegisterOneRequest(slaveId, start, value) 73 | 74 | /** 写 0x10 ,多个寄存器*/ 75 | fun createRequestWrite10(slaveId: Byte, start: Int, values: ShortArray): WriteRegistersRequest = WriteRegistersRequest(slaveId, start, values) 76 | 77 | /** 写 0x0f ,多个线圈*/ 78 | fun createRequestWrite0f(slaveId: Byte, start: Int, values: BooleanArray): WriteCoilsRequest = WriteCoilsRequest(slaveId, start, values) 79 | ``` 80 | 81 | #### 读示例 82 | 83 | ```kotlin 84 | lifecycleScope.launch(Dispatchers.IO) { 85 | //读取从站 =1 的线圈,从0开始读取100个 86 | val response = modeBus?.read(ModbusMaster.createRequestRead01(1, 0, 100)) 87 | Log.d("TAG", "返回的原始数据 ${response?.raw}") 88 | Log.d("TAG", "返回的 BooleanArray 类型的 result ${response?.result}") 89 | } 90 | 91 | lifecycleScope.launch(Dispatchers.IO) { 92 | //读取从站 =1 的保持寄存器,从0开始读20个 93 | val response = modeBus?.read(ModbusMaster.createRequestRead03(1, 0, 20)) 94 | Log.d("TAG", "返回的原始数据 ${response?.raw}") 95 | Log.d("TAG", "返回的 ShortArray 类型的 result ${response?.result}") 96 | } 97 | ``` 98 | 99 | #### 写示例 100 | 101 | ```kotlin 102 | lifecycleScope.launch(Dispatchers.IO) { 103 | //写从站 =1 的多个寄存器,从200开始写入 [98,25,33] 这三个数据 104 | val response = modeBus?.write(ModbusMaster.createRequestWrite10(1, 200, shortArrayOf(98, 25, 33))) 105 | Log.d("TAG", "返回的原始数据 ${response?.raw}") 106 | Log.d("TAG", "返回的 ByteArray 类型的 pdu ${response?.pdu}") 107 | } 108 | ``` 109 | 110 | ## 贡献 111 | 112 | 欢迎对该项目进行贡献!如果你发现了 Bug、有新的功能建议或者愿意改进现有功能,请提交 Issue 或 Pull Request。任何形式的贡献都将不胜感激。 113 | 114 | ## 许可证 115 | 116 | 该项目采用 MIT 许可证进行许可。 -------------------------------------------------------------------------------- /app/src/main/res/drawable/ic_launcher_background.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 10 | 15 | 20 | 25 | 30 | 35 | 40 | 45 | 50 | 55 | 60 | 65 | 70 | 75 | 80 | 85 | 90 | 95 | 100 | 105 | 110 | 115 | 120 | 125 | 130 | 135 | 140 | 145 | 150 | 155 | 160 | 165 | 170 | 171 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | # 4 | # Copyright 2015 the original author or authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | ## 21 | ## Gradle start up script for UN*X 22 | ## 23 | ############################################################################## 24 | 25 | # Attempt to set APP_HOME 26 | # Resolve links: $0 may be a link 27 | PRG="$0" 28 | # Need this for relative symlinks. 29 | while [ -h "$PRG" ] ; do 30 | ls=`ls -ld "$PRG"` 31 | link=`expr "$ls" : '.*-> \(.*\)$'` 32 | if expr "$link" : '/.*' > /dev/null; then 33 | PRG="$link" 34 | else 35 | PRG=`dirname "$PRG"`"/$link" 36 | fi 37 | done 38 | SAVED="`pwd`" 39 | cd "`dirname \"$PRG\"`/" >/dev/null 40 | APP_HOME="`pwd -P`" 41 | cd "$SAVED" >/dev/null 42 | 43 | APP_NAME="Gradle" 44 | APP_BASE_NAME=`basename "$0"` 45 | 46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 48 | 49 | # Use the maximum available, or set MAX_FD != -1 to use that value. 50 | MAX_FD="maximum" 51 | 52 | warn () { 53 | echo "$*" 54 | } 55 | 56 | die () { 57 | echo 58 | echo "$*" 59 | echo 60 | exit 1 61 | } 62 | 63 | # OS specific support (must be 'true' or 'false'). 64 | cygwin=false 65 | msys=false 66 | darwin=false 67 | nonstop=false 68 | case "`uname`" in 69 | CYGWIN* ) 70 | cygwin=true 71 | ;; 72 | Darwin* ) 73 | darwin=true 74 | ;; 75 | MINGW* ) 76 | msys=true 77 | ;; 78 | NONSTOP* ) 79 | nonstop=true 80 | ;; 81 | esac 82 | 83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 84 | 85 | 86 | # Determine the Java command to use to start the JVM. 87 | if [ -n "$JAVA_HOME" ] ; then 88 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 89 | # IBM's JDK on AIX uses strange locations for the executables 90 | JAVACMD="$JAVA_HOME/jre/sh/java" 91 | else 92 | JAVACMD="$JAVA_HOME/bin/java" 93 | fi 94 | if [ ! -x "$JAVACMD" ] ; then 95 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 96 | 97 | Please set the JAVA_HOME variable in your environment to match the 98 | location of your Java installation." 99 | fi 100 | else 101 | JAVACMD="java" 102 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 103 | 104 | Please set the JAVA_HOME variable in your environment to match the 105 | location of your Java installation." 106 | fi 107 | 108 | # Increase the maximum file descriptors if we can. 109 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 110 | MAX_FD_LIMIT=`ulimit -H -n` 111 | if [ $? -eq 0 ] ; then 112 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 113 | MAX_FD="$MAX_FD_LIMIT" 114 | fi 115 | ulimit -n $MAX_FD 116 | if [ $? -ne 0 ] ; then 117 | warn "Could not set maximum file descriptor limit: $MAX_FD" 118 | fi 119 | else 120 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 121 | fi 122 | fi 123 | 124 | # For Darwin, add options to specify how the application appears in the dock 125 | if $darwin; then 126 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 127 | fi 128 | 129 | # For Cygwin or MSYS, switch paths to Windows format before running java 130 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then 131 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 132 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 133 | 134 | JAVACMD=`cygpath --unix "$JAVACMD"` 135 | 136 | # We build the pattern for arguments to be converted via cygpath 137 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 138 | SEP="" 139 | for dir in $ROOTDIRSRAW ; do 140 | ROOTDIRS="$ROOTDIRS$SEP$dir" 141 | SEP="|" 142 | done 143 | OURCYGPATTERN="(^($ROOTDIRS))" 144 | # Add a user-defined pattern to the cygpath arguments 145 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 146 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 147 | fi 148 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 149 | i=0 150 | for arg in "$@" ; do 151 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 152 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 153 | 154 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 155 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 156 | else 157 | eval `echo args$i`="\"$arg\"" 158 | fi 159 | i=`expr $i + 1` 160 | done 161 | case $i in 162 | 0) set -- ;; 163 | 1) set -- "$args0" ;; 164 | 2) set -- "$args0" "$args1" ;; 165 | 3) set -- "$args0" "$args1" "$args2" ;; 166 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;; 167 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 168 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 169 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 170 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 171 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 172 | esac 173 | fi 174 | 175 | # Escape application args 176 | save () { 177 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 178 | echo " " 179 | } 180 | APP_ARGS=`save "$@"` 181 | 182 | # Collect all arguments for the java command, following the shell quoting and substitution rules 183 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 184 | 185 | exec "$JAVACMD" "$@" 186 | -------------------------------------------------------------------------------- /modbus/src/main/java/ink/itwo/lib/modbus/Ext.kt: -------------------------------------------------------------------------------- 1 | package ink.itwo.lib.modbus 2 | 3 | import kotlin.experimental.and 4 | import kotlin.experimental.or 5 | 6 | 7 | enum class ModBusMode { RTU, TCP } 8 | 9 | data class ModBusMaserConfig( 10 | val model: ModBusMode, 11 | val timeout: Long = 100, 12 | val retryTime: Long = 0, 13 | val loggerPrefix: String = "Modbus ", 14 | val logger: ((String) -> Unit)? = null, 15 | val fold: (suspend (ByteArray) -> ByteArray?)? = null, 16 | ) 17 | 18 | 19 | private object ModBusFunCode { 20 | 21 | /** 读 0x01 ,线圈*/ 22 | const val ReadCoils: Byte = 0x01 23 | 24 | /** 读 0x02 ,离散寄存器*/ 25 | const val ReadDiscrete: Byte = 0x02 26 | 27 | /** 读 0x03 ,保持寄存器*/ 28 | const val ReadHoldRegister: Byte = 0x03 29 | 30 | /** 读 0x04 ,输入寄存器*/ 31 | const val ReadInputRegister: Byte = 0x04 32 | 33 | /** 写 0x05 ,单个线圈*/ 34 | const val WriteCoilOne: Byte = 0x05 35 | 36 | /** 写 0x06,单个寄存器*/ 37 | const val WriteRegisterOne: Byte = 0x06 38 | 39 | /** 写 0x10 ,多个寄存器*/ 40 | const val WriteRegisters: Byte = 0x10 41 | 42 | /** 写 0x0f ,多个线圈*/ 43 | const val WriteCoils: Byte = 0x0f 44 | 45 | /** 读 0x14 ,文件记录*/ 46 | const val ReadFile: Byte = 0x14 47 | 48 | /** 写 0x15 ,文件记录*/ 49 | const val WriteFile: Byte = 0x015 50 | } 51 | 52 | interface Request { 53 | val slaveId: Byte 54 | val funCode: Byte 55 | } 56 | 57 | interface ReadRequest : Request { 58 | val start: Int 59 | val num: Int 60 | } 61 | 62 | interface Response { 63 | var raw: ByteArray? 64 | var pdu: ByteArray? 65 | } 66 | 67 | interface ReadCoilRequest : ReadRequest 68 | 69 | interface ReadRegisterRequest : ReadRequest 70 | 71 | interface WriteRequest : Request 72 | 73 | class CoilResponse(override var raw: ByteArray?, override var pdu: ByteArray? = null, var result: BooleanArray? = null) : Response 74 | 75 | 76 | class RegisterResponse(override var raw: ByteArray?, override var pdu: ByteArray? = null, var result: ShortArray? = null) : Response 77 | 78 | class WriteResponse(override var raw: ByteArray?, override var pdu: ByteArray? = null) : Response 79 | 80 | class ReadCoilsRequest(override val slaveId: Byte, override val start: Int, override val num: Int) : ReadCoilRequest { 81 | override val funCode = ModBusFunCode.ReadCoils 82 | } 83 | 84 | class ReadDiscreteRequest(override val slaveId: Byte, override val start: Int, override val num: Int) : ReadCoilRequest { 85 | override val funCode = ModBusFunCode.ReadDiscrete 86 | } 87 | 88 | class ReadHoldRegisterRequest(override val slaveId: Byte, override val start: Int, override val num: Int) : ReadRegisterRequest { 89 | override val funCode = ModBusFunCode.ReadHoldRegister 90 | } 91 | 92 | class ReadInputRegisterRequest(override val slaveId: Byte, override val start: Int, override val num: Int) : ReadRegisterRequest { 93 | override val funCode = ModBusFunCode.ReadInputRegister 94 | } 95 | 96 | 97 | class WriteCoilOneRequest(override val slaveId: Byte, val start: Int, val value: Boolean) : WriteRequest { 98 | override val funCode = ModBusFunCode.WriteCoilOne 99 | } 100 | 101 | class WriteRegisterOneRequest(override val slaveId: Byte, val start: Int, val value: Short) : WriteRequest { 102 | override val funCode = ModBusFunCode.WriteRegisterOne 103 | } 104 | 105 | class WriteRegistersRequest(override val slaveId: Byte, val start: Int, val values: ShortArray) : WriteRequest { 106 | override val funCode = ModBusFunCode.WriteRegisters 107 | } 108 | 109 | class WriteCoilsRequest(override val slaveId: Byte, val start: Int, val values: BooleanArray) : WriteRequest { 110 | override val funCode = ModBusFunCode.WriteCoils 111 | } 112 | 113 | 114 | internal val Request.pdu: ByteArray 115 | get() { 116 | return when (this) { 117 | // code 1 start 2 num 2 118 | is ReadRequest -> byteArrayOf(funCode).plus(start.toByte2).plus(num.toByte2) 119 | // code 1 start 2 value 2 (0xFF00 = on 0x0000 = off) 120 | is WriteCoilOneRequest -> byteArrayOf(funCode).plus(start.toByte2).plus(if (value) (0xFF).toByte() else 0x00).plus(0x00) 121 | // code 1 start 2 value 2 122 | is WriteRegisterOneRequest -> byteArrayOf(funCode).plus(start.toByte2).plus(value.toInt().toByte2) 123 | // code 1 start 2 寄存器数量 2 字节数 1 寄存器值 N*2 124 | is WriteRegistersRequest -> { 125 | val funCodeByte = byteArrayOf(funCode) 126 | val startBytes = start.toByte2 127 | val numBytes = values.size.toByte2 128 | val countBytes = (values.size * 2).toByte() 129 | val valueBytes = values.toByteArray 130 | return funCodeByte.plus(startBytes).plus(numBytes).plus(countBytes).plus(valueBytes) 131 | } 132 | // code 1 start 2 输出数量 2 字节数 1 写入值 N*1 133 | is WriteCoilsRequest -> { 134 | val funCodeByte = byteArrayOf(funCode) 135 | val startBytes = start.toByte2 136 | val numBytes = values.size.toByte2 137 | val valueBytes = values.toByteArrayFill0 138 | val countBytes = (valueBytes.size).toByte() 139 | return funCodeByte.plus(startBytes).plus(numBytes).plus(countBytes).plus(valueBytes) 140 | } 141 | else -> byteArrayOf() 142 | } 143 | } 144 | internal val Request.adu: ByteArray 145 | get() = byteArrayOf(slaveId).plus(pdu).plusCrc16 146 | 147 | internal fun Response.parse() { 148 | when (this) { 149 | is CoilResponse -> { 150 | pdu = raw?.elementAtOrNull(2)?.let { raw?.sliceArray(1..2 + it) } 151 | result = raw?.elementAtOrNull(2)?.let { raw?.sliceArray(3..2 + it) }?.toBooleanArray 152 | } 153 | is RegisterResponse -> { 154 | pdu = raw?.elementAtOrNull(2)?.let { raw?.sliceArray(1..2 + it) } 155 | result = raw?.elementAtOrNull(2)?.let { raw?.sliceArray(3..2 + it) }?.toShortArray 156 | } 157 | is WriteResponse -> { 158 | pdu = raw?.elementAtOrNull(2)?.let { raw?.sliceArray(1..2 + it) } 159 | } 160 | } 161 | } 162 | 163 | internal fun Response.parseTcp() { 164 | //000d 0000 0009 01 10 0304 0001 02 000d 165 | when (this) { 166 | is CoilResponse -> { 167 | pdu = raw?.sliceArray(6 until (raw?.size ?: 6)) 168 | result = raw?.elementAtOrNull(2)?.let { raw?.sliceArray(3..2 + it) }?.toBooleanArray 169 | result = raw?.sliceArray(8 until (raw?.size ?: 8))?.toBooleanArray 170 | } 171 | is RegisterResponse -> { 172 | pdu = raw?.sliceArray(6 until (raw?.size ?: 6)) 173 | result = raw?.sliceArray(8 until (raw?.size ?: 8))?.toShortArray 174 | } 175 | is WriteResponse -> { 176 | pdu = raw?.sliceArray(6 until (raw?.size ?: 6)) 177 | } 178 | } 179 | } 180 | 181 | 182 | internal val Int.toByte2: ByteArray 183 | get() = byteArrayOf(this.shr(8).and(0xFF).toByte(), this.and(0xFF).toByte()) 184 | internal val ByteArray.crc16: ByteArray 185 | get() = getCrc16Str(this, false) 186 | private val ByteArray.plusCrc16: ByteArray 187 | get() = this.plus(this.crc16) 188 | private val ShortArray.toByteArray: ByteArray 189 | get() { 190 | val byteArray = ByteArray(this.size * 2) 191 | forEachIndexed { index, sh -> 192 | byteArray[(index * 2)] = sh.toInt().shr(8).and(0xFF).toByte() 193 | byteArray[(index * 2) + 1] = sh.and(0xFF).toByte() 194 | } 195 | return byteArray 196 | } 197 | internal val ByteArray.toInt2: Int 198 | get() { 199 | return (this[1].toInt() and 0xFF) shl 8 or (this[0].toInt() and 0xFF) 200 | } 201 | 202 | /** BooleanArray 按8位一组转成ByteArray,不足8位补0*/ 203 | private val BooleanArray.toByteArrayFill0: ByteArray 204 | get() { 205 | val result = ByteArray((size / 8) + if (size % 8 != 0) 1 else 0) 206 | for (i in indices) { 207 | if (this[i]) { 208 | result[i / 8] = result[i / 8] or (1 shl (i % 8)).toByte() 209 | } 210 | } 211 | return result 212 | } 213 | 214 | /** 将 byteArray 转成 booleanArray*/ 215 | internal val ByteArray.toBooleanArray: BooleanArray 216 | get() { 217 | val result = BooleanArray(size * 8) 218 | for (i in indices) { 219 | for (j in 0 until 8) { 220 | result[i * 8 + j] = (this[i].toInt() shr j) and 0x1 == 1 221 | } 222 | } 223 | return result 224 | } 225 | internal val ByteArray.toShortArray: ShortArray 226 | get() { 227 | val result = ShortArray(size / 2) 228 | for (i in 0 until size step 2) { 229 | result[i / 2] = ((this[i].toInt() and 0xFF) shl 8 or (this[i + 1].toInt() and 0xFF)).toShort() 230 | } 231 | return result 232 | } 233 | 234 | 235 | private val UByte.toRadix16: String 236 | get() = if (toString(16).length < 2) "0${toString(16)}" else toString(16) 237 | private val ByteArray.toRadix16: String 238 | get() = joinToString(separator = "") { it.toUByte().toRadix16 } 239 | internal val ByteArray.toRadix16Separator: String 240 | get() = joinToString(separator = " ") { it.toUByte().toRadix16 } 241 | 242 | 243 | private fun getCrc16Str(arrBuff: ByteArray, littleEndian: Boolean = true): ByteArray { 244 | val len = arrBuff.size 245 | var crc = 0xFFFF 246 | for (i in 0 until len) { 247 | crc = ((crc and 0xFF00) or (crc and 0x00FF) xor (arrBuff[i].toInt() and 0xFF)) 248 | for (j in 0 until 8) { 249 | if ((crc and 0x0001) > 0) { 250 | crc = crc.shr(1) 251 | crc = crc xor 0xA001 252 | } else { 253 | crc = crc.shr(1) 254 | } 255 | } 256 | } 257 | val result = ByteArray(2) 258 | result[if (littleEndian) 0 else 1] = (crc.shr(8) and 0xFF).toByte() 259 | result[if (littleEndian) 1 else 0] = (crc and 0xFF).toByte() 260 | return result 261 | } 262 | 263 | internal fun ByteArray.sliceArray(indices: IntRange): ByteArray? { 264 | if (this.size <= indices.last) return null 265 | if (indices.isEmpty()) return null 266 | return copyOfRange(indices.first, indices.last + 1) 267 | } 268 | -------------------------------------------------------------------------------- /modbus/src/main/java/ink/itwo/lib/modbus/ModbusMaster.kt: -------------------------------------------------------------------------------- 1 | package ink.itwo.lib.modbus 2 | 3 | import kotlinx.coroutines.delay 4 | import kotlinx.coroutines.sync.Mutex 5 | import kotlinx.coroutines.sync.withLock 6 | import java.io.InputStream 7 | import java.io.OutputStream 8 | 9 | /** Created by wang on 2023/4/27. */ 10 | interface ModbusMaster { 11 | companion object { 12 | fun init(config: ModBusMaserConfig, input: InputStream, output: OutputStream): ModbusMaster { 13 | return when (config.model) { 14 | ModBusMode.RTU -> ModbusRtu(config, input, output) 15 | ModBusMode.TCP -> ModbusTCP(config, input, output) 16 | } 17 | } 18 | 19 | /** 读 0x01 ,线圈*/ 20 | fun createRequestRead01(slaveId: Byte, start: Int, num: Int): ReadCoilsRequest = ReadCoilsRequest(slaveId, start, num) 21 | 22 | /** 读 0x02 ,离散寄存器*/ 23 | fun createRequestRead02(slaveId: Byte, start: Int, num: Int): ReadDiscreteRequest = ReadDiscreteRequest(slaveId, start, num) 24 | 25 | /** 读 0x03 ,保持寄存器*/ 26 | fun createRequestRead03(slaveId: Byte, start: Int, num: Int): ReadHoldRegisterRequest = ReadHoldRegisterRequest(slaveId, start, num) 27 | 28 | /** 读 0x04 ,输入寄存器*/ 29 | fun createRequestRead04(slaveId: Byte, start: Int, num: Int): ReadInputRegisterRequest = ReadInputRegisterRequest(slaveId, start, num) 30 | 31 | /** 写 0x05 ,单个线圈*/ 32 | fun createRequestWrite05(slaveId: Byte, start: Int, value: Boolean): WriteCoilOneRequest = WriteCoilOneRequest(slaveId, start, value) 33 | 34 | /** 写 0x06,单个寄存器*/ 35 | fun createRequestWrite06(slaveId: Byte, start: Int, value: Short): WriteRegisterOneRequest = WriteRegisterOneRequest(slaveId, start, value) 36 | 37 | /** 写 0x10 ,多个寄存器*/ 38 | fun createRequestWrite10(slaveId: Byte, start: Int, values: ShortArray): WriteRegistersRequest = WriteRegistersRequest(slaveId, start, values) 39 | 40 | /** 写 0x0f ,多个线圈*/ 41 | fun createRequestWrite0f(slaveId: Byte, start: Int, values: BooleanArray): WriteCoilsRequest = WriteCoilsRequest(slaveId, start, values) 42 | } 43 | 44 | suspend fun onReceive() 45 | suspend fun read(request: ReadCoilRequest): CoilResponse 46 | suspend fun read(request: ReadRegisterRequest): RegisterResponse 47 | suspend fun write(request: WriteRequest): WriteResponse 48 | fun close() 49 | } 50 | 51 | abstract class ModbusMasterAbs(protected val config: ModBusMaserConfig, private val input: InputStream, private val output: OutputStream) : ModbusMaster { 52 | private var flag = true 53 | private var lastBuffer: ByteArray? = null 54 | private var foldBuffer = byteArrayOf() 55 | private var transmitting = true 56 | private val byte0: Byte = 0 57 | private val mutex by lazy { Mutex() } 58 | override suspend fun onReceive() { 59 | while (flag) { 60 | try { 61 | val byteArray = ByteArray(1024) 62 | val size = input.read(byteArray) 63 | val bytes = byteArray.copyOf(size) 64 | if (config.fold == null) { 65 | lastBuffer = bytes 66 | } else { 67 | lastBuffer = config.fold.invoke(bytes) 68 | } 69 | config.logger?.invoke("${config.loggerPrefix} rx : ${bytes.toRadix16Separator} lastBuffer ${lastBuffer?.toRadix16Separator}") 70 | // fold(bytes) 71 | } catch (e: Exception) { 72 | config.logger?.invoke("${config.loggerPrefix} rx : ${e.message} err Exception") 73 | } finally { 74 | } 75 | } 76 | } 77 | 78 | private suspend fun fold(byteArray: ByteArray) { 79 | mutex.withLock { 80 | foldBuffer = foldBuffer.plus(byteArray) 81 | val crc16 = foldBuffer.crc16 82 | // config.logger?.invoke("${config.loggerPrefix} fold : \n foldBuffer ${foldBuffer.toRadix16Separator} \n byteArray ${byteArray.toRadix16Separator} \n lastBuffer ${lastBuffer?.toRadix16Separator} crc16 ${crc16.toRadix16Separator}") 83 | if (crc16.size == 2 && crc16.firstOrNull() == byte0 && crc16.lastOrNull() == byte0) { 84 | lastBuffer = foldBuffer.copyOf() 85 | foldBuffer = byteArrayOf() 86 | config.logger?.invoke("${config.loggerPrefix} rx :${lastBuffer?.toRadix16Separator}") 87 | transmitting = true 88 | } 89 | } 90 | } 91 | 92 | protected suspend fun publish(byteArray: ByteArray): ByteArray? { 93 | try { 94 | if (!transmitting) { 95 | config.logger?.invoke("${config.loggerPrefix} tx transmitting = $transmitting") 96 | return null 97 | } 98 | transmitting = true 99 | config.logger?.invoke("${config.loggerPrefix} tx ${byteArray.toRadix16Separator}") 100 | output.write(byteArray) 101 | output.flush() 102 | transmitting = false 103 | } catch (e: Exception) { 104 | e.printStackTrace() 105 | return null 106 | } 107 | val onResult = onResult(byteArray) 108 | transmitting = true 109 | return onResult 110 | } 111 | 112 | private suspend fun onResult(txArray: ByteArray): ByteArray? { 113 | delay(config.timeout) 114 | var check = lastBuffer?.let { checkResult(txArray, it) } 115 | if (check == true) { 116 | val bytes = lastBuffer?.copyOf() 117 | lastBuffer = null 118 | return bytes 119 | } 120 | if (config.retryTime == 0L) { 121 | config.logger?.invoke("${config.loggerPrefix} tx ${txArray.toRadix16Separator} lastReceive ${lastBuffer?.toRadix16Separator} err timeout ") 122 | val bytes = lastBuffer?.copyOf() 123 | lastBuffer = null 124 | return bytes 125 | } 126 | delay(config.retryTime) 127 | check = lastBuffer?.let { checkResult(txArray, it) } 128 | if (check != true) { 129 | config.logger?.invoke("${config.loggerPrefix} tx ${txArray.toRadix16Separator} lastReceive ${lastBuffer?.toRadix16Separator} err timeout ") 130 | val bytes = lastBuffer?.copyOf() 131 | lastBuffer = null 132 | return bytes 133 | } 134 | val bytes = lastBuffer?.copyOf() 135 | lastBuffer = null 136 | return bytes 137 | } 138 | 139 | override fun close() { 140 | flag = false 141 | } 142 | 143 | protected abstract fun checkResult(src: ByteArray, receive: ByteArray): Boolean 144 | } 145 | 146 | 147 | class ModbusRtu(config: ModBusMaserConfig, input: InputStream, output: OutputStream) : ModbusMasterAbs(config, input, output) { 148 | 149 | 150 | override suspend fun read(request: ReadCoilRequest): CoilResponse { 151 | val bytes = publish(request.adu) 152 | return CoilResponse(bytes).apply { parse() } 153 | } 154 | 155 | override suspend fun read(request: ReadRegisterRequest): RegisterResponse { 156 | val bytes = publish(request.adu) 157 | return RegisterResponse(bytes).apply { parse() } 158 | } 159 | 160 | override suspend fun write(request: WriteRequest): WriteResponse { 161 | val bytes = publish(request.adu) 162 | return WriteResponse(bytes).apply { parse() } 163 | } 164 | 165 | override fun checkResult(src: ByteArray, receive: ByteArray): Boolean { 166 | if (receive.isEmpty() || receive.size < 5) { 167 | config.logger?.invoke("${config.loggerPrefix} tx: ${src.toRadix16Separator} receive: ${receive.toRadix16Separator} err size < 6 ") 168 | return false 169 | } 170 | val crc16 = receive.crc16 171 | if (crc16.size != 2 || crc16.firstOrNull()?.toInt() != 0 || crc16.lastOrNull()?.toInt() != 0) { 172 | config.logger?.invoke("${config.loggerPrefix} tx:${src.toRadix16Separator} rx: ${receive.toRadix16Separator} err CRC ") 173 | return false 174 | } 175 | if (src.elementAtOrNull(1) != receive.elementAtOrNull(1) || src.elementAtOrNull(0) != receive.elementAtOrNull(0)) { 176 | config.logger?.invoke("${config.loggerPrefix} tx:${src.toRadix16Separator} rx: ${receive.toRadix16Separator} err fun code diff ") 177 | return false 178 | } 179 | return true 180 | } 181 | } 182 | 183 | class ModbusTCP(config: ModBusMaserConfig, input: InputStream, output: OutputStream) : ModbusMasterAbs(config, input, output) { 184 | private var serialNum: Int = 0x00 185 | private val protocolId by lazy { byteArrayOf(0x00, 0x00) } 186 | private val byte0: Byte = 0 187 | 188 | 189 | //传输标识符:用于标识应用数据单元,即请求和应答之间的配对;客户端对该部分进行初始化, x2 190 | //协议标识符:系统间的协议标识,0=Modbus; x2 191 | //长度:接下来要发送的数据长度,即:单元标识符+PDU的总长度,以字节为单位; x2 192 | //单元标识符:用于系统间的站寻址,比如在以太网+串行链路的网络中,远程站的地址; x1 193 | //0032 0000 0006 01 03 00c8 0011 194 | override suspend fun read(request: ReadCoilRequest): CoilResponse { 195 | val byteArray = createRequestByteArray(request) 196 | val bytes = publish(byteArray) 197 | return CoilResponse(bytes).apply { parseTcp() } 198 | } 199 | 200 | 201 | override suspend fun read(request: ReadRegisterRequest): RegisterResponse { 202 | val byteArray = createRequestByteArray(request) 203 | val bytes = publish(byteArray) 204 | return RegisterResponse(bytes).apply { parseTcp() } 205 | } 206 | 207 | //000d 0000 0009 01 10 0304 0001 02 000d 208 | override suspend fun write(request: WriteRequest): WriteResponse { 209 | val byteArray = createRequestByteArray(request) 210 | val bytes = publish(byteArray) 211 | return WriteResponse(bytes).apply { parseTcp() } 212 | } 213 | 214 | override fun checkResult(src: ByteArray, receive: ByteArray): Boolean { 215 | if (receive.isEmpty() || receive.size < 8) { 216 | config.logger?.invoke("${config.loggerPrefix} err size < 8 tx: ${src.toRadix16Separator} receive: ${receive.toRadix16Separator}") 217 | return false 218 | } 219 | 220 | if (receive.elementAtOrNull(2) != byte0 || receive.elementAtOrNull(3) != byte0) { 221 | config.logger?.invoke("${config.loggerPrefix} err receive protocol fail tx: ${src.toRadix16Separator} receive: ${receive.toRadix16Separator}") 222 | return false 223 | } 224 | val size = receive.sliceArray(4..5)?.toInt2 ?: 0 225 | if (size == 0 || size + 6 != receive.size) { 226 | config.logger?.invoke("${config.loggerPrefix} err receive size fail tx: ${src.toRadix16Separator} receive: ${receive.toRadix16Separator}") 227 | return false 228 | } 229 | 230 | if (src.elementAtOrNull(6) != receive.elementAtOrNull(6)) { 231 | config.logger?.invoke("${config.loggerPrefix} err fun code diff tx:${src.toRadix16Separator} rx: ${receive.toRadix16Separator}") 232 | return false 233 | } 234 | return true 235 | } 236 | 237 | 238 | private fun createRequestByteArray(request: Request): ByteArray { 239 | val transactionId = serialNum++.toByte2 240 | val pdu = byteArrayOf(request.slaveId).plus(request.pdu) 241 | val pduSize = pdu.size.toByte2 242 | return transactionId.plus(protocolId).plus(pduSize).plus(pdu) 243 | } 244 | } --------------------------------------------------------------------------------