From e6c5a02c50bbba4df47c362a61694287182c9399 Mon Sep 17 00:00:00 2001 From: xiaowusky Date: Tue, 21 Nov 2023 14:38:35 +0800 Subject: [PATCH] =?UTF-8?q?desc:=E6=95=B0=E6=8D=AE=E6=A0=87=E5=AE=9A?= =?UTF-8?q?=E5=91=BD=E4=BB=A4=E5=B0=81=E8=A3=85?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../watcher/port/cmd/CalibrationCmd.kt | 55 +++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 app/src/main/java/com/yinuo/safetywatcher/watcher/port/cmd/CalibrationCmd.kt diff --git a/app/src/main/java/com/yinuo/safetywatcher/watcher/port/cmd/CalibrationCmd.kt b/app/src/main/java/com/yinuo/safetywatcher/watcher/port/cmd/CalibrationCmd.kt new file mode 100644 index 0000000..4adbe76 --- /dev/null +++ b/app/src/main/java/com/yinuo/safetywatcher/watcher/port/cmd/CalibrationCmd.kt @@ -0,0 +1,55 @@ +package com.yinuo.safetywatcher.watcher.port.cmd + +/** + * 校准命令 + * @param index 传感器编号 00 01 02 03 + * @param target 目标值 + */ +class CalibrationCmd(private val index: Int, private val target: Int) { + val ZERO = 0x87.toByte() + val SPAN = 0x88.toByte() + + fun buildZeroCmd(): ByteArray { + return build(ZERO) + } + + fun buildSPANCmd(): ByteArray { + return build(SPAN) + } + + private fun build(cmd: Byte): ByteArray { + var highBit: Byte = 0x00 + var lowBit: Byte = 0x00 + if (index != 0) { + highBit = (target shr 8 and FF).toByte() + lowBit = (target and FF).toByte() + } + return byteArrayOf( + 0xFF.toByte(), + index.toByte(), + cmd, + highBit, + lowBit, + 0x00, + 0x00, + 0x00 + ).calibrationSum() + } +} + +private fun ByteArray.calibrationSum(): ByteArray { + return this.plus(getCheckSum(this)) +} + +fun getCheckSum(packet: ByteArray): Byte { + var checksum = 0 + for (i in packet.indices) { + if (i in 1..7) { + checksum += packet[i] + } + } + checksum = 0xffff - checksum + checksum += 1 + return checksum.toByte() +} +