├── app
├── .gitignore
├── src
│ ├── main
│ │ ├── res
│ │ │ ├── values
│ │ │ │ ├── strings.xml
│ │ │ │ ├── colors.xml
│ │ │ │ └── styles.xml
│ │ │ ├── mipmap-hdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-mdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-xhdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-xxhdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-xxxhdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-anydpi-v26
│ │ │ │ ├── ic_launcher.xml
│ │ │ │ └── ic_launcher_round.xml
│ │ │ ├── layout
│ │ │ │ └── activity_main.xml
│ │ │ ├── drawable-v24
│ │ │ │ └── ic_launcher_foreground.xml
│ │ │ └── drawable
│ │ │ │ └── ic_launcher_background.xml
│ │ ├── java
│ │ │ └── cn
│ │ │ │ └── seeyou
│ │ │ │ └── serialport
│ │ │ │ ├── comm
│ │ │ │ ├── maker
│ │ │ │ │ ├── MakerManager.java
│ │ │ │ │ ├── DatasMaker.java
│ │ │ │ │ └── ProtocolMaker.java
│ │ │ │ ├── handler
│ │ │ │ │ ├── CmdHandler.java
│ │ │ │ │ ├── CmdHandlerManager.java
│ │ │ │ │ └── ProtocolHandler.java
│ │ │ │ ├── agreement
│ │ │ │ │ ├── HandlerConfig.java
│ │ │ │ │ └── ProtocolDefine.java
│ │ │ │ └── manager
│ │ │ │ │ ├── CommManager.java
│ │ │ │ │ └── SystemManager.java
│ │ │ │ └── MainActivity.java
│ │ └── AndroidManifest.xml
│ ├── test
│ │ └── java
│ │ │ └── cn
│ │ │ └── seeyou
│ │ │ └── serialport
│ │ │ └── ExampleUnitTest.java
│ └── androidTest
│ │ └── java
│ │ └── cn
│ │ └── seeyou
│ │ └── serialport
│ │ └── ExampleInstrumentedTest.java
├── proguard-rules.pro
└── build.gradle
├── commlibrary
├── .gitignore
├── src
│ └── main
│ │ ├── res
│ │ └── values
│ │ │ └── strings.xml
│ │ ├── AndroidManifest.xml
│ │ └── java
│ │ └── com
│ │ └── seeyou
│ │ └── comm
│ │ └── framework
│ │ ├── commframe
│ │ ├── ICMDHandler.java
│ │ ├── makermanager
│ │ │ ├── IMaker.java
│ │ │ ├── MakerItem.java
│ │ │ └── MakerManagerBase.java
│ │ ├── IReadwriter.java
│ │ ├── IProtocolHandler.java
│ │ ├── cmdmanager
│ │ │ ├── HandlerItem.java
│ │ │ └── SIDHandlerManagerBase.java
│ │ ├── CommManagerBase.java
│ │ ├── DefaultProtocolHandler.java
│ │ ├── CommConfiguration.java
│ │ ├── KAChecker.java
│ │ ├── UartReadwriter.java
│ │ ├── LoopBuffer.java
│ │ └── BaseProtocolHandler.java
│ │ └── utils
│ │ ├── ICrcTools.java
│ │ ├── CRCToolsB.java
│ │ ├── FormatUtil.java
│ │ ├── CRCToolsA.java
│ │ ├── ConvertTypeUtils.java
│ │ └── ByteConverter.java
├── libs
│ └── android_hardware.jar
├── proguard-rules.pro
└── build.gradle
├── settings.gradle
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── .idea
├── vcs.xml
├── misc.xml
├── runConfigurations.xml
├── gradle.xml
└── codeStyles
│ └── Project.xml
├── .gitignore
├── README.md
├── gradle.properties
├── gradlew.bat
└── gradlew
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/commlibrary/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':app', ':commlibrary'
2 | rootProject.name='SerialPortDataparsing'
3 |
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | SerialPortDataparsing
3 |
4 |
--------------------------------------------------------------------------------
/commlibrary/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | CommLibrary
3 |
4 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/savasee/SerialPortDataparsing/HEAD/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/commlibrary/libs/android_hardware.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/savasee/SerialPortDataparsing/HEAD/commlibrary/libs/android_hardware.jar
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/savasee/SerialPortDataparsing/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/savasee/SerialPortDataparsing/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/commlibrary/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
3 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/savasee/SerialPortDataparsing/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/savasee/SerialPortDataparsing/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/savasee/SerialPortDataparsing/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/savasee/SerialPortDataparsing/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/savasee/SerialPortDataparsing/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/savasee/SerialPortDataparsing/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/savasee/SerialPortDataparsing/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/savasee/SerialPortDataparsing/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/commlibrary/src/main/java/com/seeyou/comm/framework/commframe/ICMDHandler.java:
--------------------------------------------------------------------------------
1 | package com.seeyou.comm.framework.commframe;
2 |
3 |
4 | public interface ICMDHandler {
5 | public void handle(byte[] bytes, byte packageid);
6 | }
7 |
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #008577
4 | #00574B
5 | #D81B60
6 |
7 |
--------------------------------------------------------------------------------
/commlibrary/src/main/java/com/seeyou/comm/framework/utils/ICrcTools.java:
--------------------------------------------------------------------------------
1 | package com.seeyou.comm.framework.utils;
2 |
3 | /**
4 | * Create by seeyou
5 | * seeyou1052@foxmail.com
6 | */
7 | public interface ICrcTools {
8 | int handle(byte[] dat, int len);
9 | }
10 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .gradle
3 | /local.properties
4 | /.idea/caches
5 | /.idea/libraries
6 | /.idea/modules.xml
7 | /.idea/workspace.xml
8 | /.idea/navEditor.xml
9 | /.idea/assetWizardSettings.xml
10 | .DS_Store
11 | /build
12 | /captures
13 | .externalNativeBuild
14 | .cxx
15 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # SerialPortDataparsing
2 | 基于串口通讯的通讯层框架,封装了数据缓冲池和数据解析等,可更改拓展于蓝牙,wifi通讯等
3 |
4 | #用法
5 |
6 | 拷贝commlibrary
7 | 根据app源码参照
8 | 实现handler类 协议层类 maker发送数据层类 和manger类
9 | 因为协议的不同,故需要对协议的定义进行修改,通信原理不变
10 |
11 | #原理
12 |
13 | 定义LoopBuffer字节缓冲池,所有串口接收数据存入缓冲池中,按照数据协议包格式进行读取。
14 |
--------------------------------------------------------------------------------
/commlibrary/src/main/java/com/seeyou/comm/framework/commframe/makermanager/IMaker.java:
--------------------------------------------------------------------------------
1 | package com.seeyou.comm.framework.commframe.makermanager;
2 |
3 | /**
4 | * Create by seeyou
5 | * seeyou1052@foxmail.com
6 | */
7 | public interface IMaker {
8 | public Object make();
9 | }
10 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Thu Mar 19 13:43:31 CST 2020
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | distributionUrl=https\://services.gradle.org/distributions/gradle-5.4.1-all.zip
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 |
--------------------------------------------------------------------------------
/commlibrary/src/main/java/com/seeyou/comm/framework/commframe/IReadwriter.java:
--------------------------------------------------------------------------------
1 | package com.seeyou.comm.framework.commframe;
2 |
3 | import java.nio.ByteBuffer;
4 |
5 | public interface IReadwriter {
6 | void start(String uartPath, int port, int baudrate);
7 | void stop();
8 | ByteBuffer read(byte[] bytes);
9 | void sendData(byte[] bytes);
10 | }
11 |
--------------------------------------------------------------------------------
/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/app/src/test/java/cn/seeyou/serialport/ExampleUnitTest.java:
--------------------------------------------------------------------------------
1 | package cn.seeyou.serialport;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.junit.Assert.*;
6 |
7 | /**
8 | * Example local unit test, which will execute on the development machine (host).
9 | *
10 | * @see Testing documentation
11 | */
12 | public class ExampleUnitTest {
13 | @Test
14 | public void addition_isCorrect() {
15 | assertEquals(4, 2 + 2);
16 | }
17 | }
--------------------------------------------------------------------------------
/.idea/runConfigurations.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
11 |
12 |
--------------------------------------------------------------------------------
/app/src/main/java/cn/seeyou/serialport/comm/maker/MakerManager.java:
--------------------------------------------------------------------------------
1 | package cn.seeyou.serialport.comm.maker;
2 |
3 | import android.content.Context;
4 | import com.seeyou.comm.framework.commframe.makermanager.MakerManagerBase;
5 |
6 | import cn.seeyou.serialport.comm.agreement.HandlerConfig;
7 |
8 | /**
9 | * Create by seeyou
10 | * on 2019/10/7
11 | */
12 | public class MakerManager extends MakerManagerBase {
13 | public MakerManager(Context context){
14 | super(context);
15 | initMakerList();
16 | }
17 |
18 | private void initMakerList(){
19 | addItem(HandlerConfig.HEART_BEAT_PKG.getCmd(),
20 | new DatasMaker());
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/.idea/gradle.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
--------------------------------------------------------------------------------
/app/src/main/java/cn/seeyou/serialport/comm/handler/CmdHandler.java:
--------------------------------------------------------------------------------
1 | package cn.seeyou.serialport.comm.handler;
2 |
3 | import android.content.Context;
4 |
5 | import com.seeyou.comm.framework.commframe.ICMDHandler;
6 |
7 | import cn.seeyou.serialport.comm.manager.CommManager;
8 |
9 | /**
10 | * Create by seeyou
11 | */
12 | public class CmdHandler implements ICMDHandler {
13 |
14 | private Context mContext;
15 | public CmdHandler(Context context, CommManager manager){
16 | this.mContext = context;
17 | }
18 | @Override
19 | public void handle(byte[] bytes, byte packageid) {
20 | parseProtocol(bytes);
21 | }
22 | //数据解析
23 | public void parseProtocol(byte[] datas){
24 |
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/app/src/main/java/cn/seeyou/serialport/comm/maker/DatasMaker.java:
--------------------------------------------------------------------------------
1 | package cn.seeyou.serialport.comm.maker;
2 |
3 |
4 |
5 | import java.util.HashMap;
6 | import java.util.Map;
7 |
8 | /**
9 | * Create by seeyou
10 | * on 2019/10/7
11 | */
12 | public class DatasMaker extends ProtocolMaker {
13 | private byte cmd;
14 | private byte[] data;
15 | public DatasMaker(){
16 |
17 | }
18 |
19 | @Override
20 | public byte[] createData() {
21 | return data;
22 | }
23 |
24 | @Override
25 | public byte createCmd() {
26 | return cmd;
27 | }
28 | public void SetCmd(byte Ncmd){
29 | cmd = Ncmd;
30 | }
31 | public void SetData(byte[] Ndata){
32 | data = Ndata;
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/commlibrary/src/main/java/com/seeyou/comm/framework/commframe/IProtocolHandler.java:
--------------------------------------------------------------------------------
1 | package com.seeyou.comm.framework.commframe;
2 |
3 | public interface IProtocolHandler {
4 | public void parseCmdPkg(byte[] src, int pkglen);
5 | public int getMinFrameLength();
6 | public boolean checkCommFrameHead(byte[] src, int startIndex);
7 | public boolean checkFrameCrc(byte[] pkgData, int crcFramelen);
8 | public boolean checkFrameTail(byte[] src, int startIndex, int pkglen);
9 | public boolean checkPkgLength(byte[] src, int startIndex);
10 | public boolean checkFrameSourceAdd(byte[] src, int startIndex);
11 | public boolean checkFrameTarget(byte[] src, int startIndex);
12 | public int getPkgLength(byte[] src, int startIndex);
13 | public int getPkgLengthNot(byte[] src, int startIndex);
14 | }
15 |
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
--------------------------------------------------------------------------------
/app/src/main/java/cn/seeyou/serialport/comm/agreement/HandlerConfig.java:
--------------------------------------------------------------------------------
1 | package cn.seeyou.serialport.comm.agreement;
2 |
3 | import com.seeyou.comm.framework.commframe.ICMDHandler;
4 |
5 | import cn.seeyou.serialport.comm.handler.CmdHandler;
6 |
7 | /**
8 | * Create by seeyou
9 | */
10 | public enum HandlerConfig {
11 | //handler这里注册
12 | HEART_BEAT_PKG(ProtocolDefine.FID.FID_BASE_ID, CmdHandler.class);
13 |
14 | private byte mFid;
15 | private String mClassName;
16 | HandlerConfig(byte fidCmd, Class clz){
17 | this.mFid = fidCmd;
18 | this.mClassName = clz.getName();
19 | }
20 |
21 | public String getClassName(){
22 | return this.mClassName;
23 | }
24 |
25 | public int getCmd(){
26 | return (this.mFid & 0xff);
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/commlibrary/src/main/java/com/seeyou/comm/framework/commframe/makermanager/MakerItem.java:
--------------------------------------------------------------------------------
1 | package com.seeyou.comm.framework.commframe.makermanager;
2 |
3 | /**
4 | * Create by seeyou
5 | * seeyou1052@foxmail.com
6 | */
7 | public class MakerItem {
8 | int mId;
9 | int mFid;
10 | int mSid;
11 | IMaker mMaker;
12 |
13 | public void setId(int id){
14 | this.mId = id;
15 | }
16 | public int getId(){
17 | return this.mId;
18 | }
19 | public void setFid(int fid){
20 | this.mFid = fid;
21 | }
22 | public int getFid(){
23 | return this.mFid;
24 | }
25 | public void setSid(int sid){
26 | this.mSid = sid;
27 | }
28 | public int getSid(){
29 | return this.mSid;
30 | }
31 |
32 | public void setMaker(IMaker maker){
33 | this.mMaker = maker;
34 | }
35 | public IMaker getMaker(){
36 | return mMaker;
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
22 |
--------------------------------------------------------------------------------
/commlibrary/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
22 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
9 |
17 |
18 |
--------------------------------------------------------------------------------
/app/src/main/java/cn/seeyou/serialport/comm/manager/CommManager.java:
--------------------------------------------------------------------------------
1 | package cn.seeyou.serialport.comm.manager;
2 |
3 | import android.content.Context;
4 |
5 | import com.seeyou.comm.framework.commframe.CommManagerBase;
6 |
7 |
8 | /**
9 | * Create by seeyou
10 | * on 2019/10/7
11 | */
12 | public class CommManager extends CommManagerBase {
13 | private static volatile CommManager ourInstance = null;
14 |
15 | public static CommManager getInstance(Context context) {
16 | if ( null == ourInstance ) {
17 | synchronized (CommManager.class) {
18 | if (null == ourInstance ) {
19 | ourInstance = new CommManager(context);
20 | }
21 | }
22 | }
23 | return ourInstance;
24 | }
25 |
26 | protected CommManager(Context context) {
27 | super(context);
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/commlibrary/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.library'
2 |
3 | android {
4 | compileSdkVersion 23
5 | buildToolsVersion "29.0.1"
6 |
7 | defaultConfig {
8 | minSdkVersion 15
9 | targetSdkVersion 23
10 | versionCode 1
11 | versionName "1.0"
12 |
13 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
14 |
15 | }
16 |
17 | buildTypes {
18 | release {
19 | minifyEnabled false
20 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
21 | }
22 | }
23 |
24 | }
25 |
26 | dependencies {
27 | implementation fileTree(include: ['*.jar'], dir: 'libs')
28 | implementation 'cn.shorr:ez-serialport:0.1.0'
29 | implementation 'com.android.support:appcompat-v7:23.+'
30 | implementation files('libs/android_hardware.jar')
31 | }
32 |
--------------------------------------------------------------------------------
/commlibrary/src/main/java/com/seeyou/comm/framework/utils/CRCToolsB.java:
--------------------------------------------------------------------------------
1 | package com.seeyou.comm.framework.utils;
2 |
3 | /**
4 | * Create by seeyou
5 | * seeyou1052@foxmail.com
6 | */
7 | public class CRCToolsB implements ICrcTools {
8 | @Override
9 | public int handle(byte[] dat, int len) {
10 | // TODO Auto-generated method stub
11 | int shift, val;
12 | int i,j;
13 | shift = 0xffff;
14 | for (i = 0; i < len; i++)
15 | {
16 | val = dat[i]<<8;
17 | for ( j = 0; j < 8; j++)
18 | {
19 | if ((short)(shift ^ val)<0)
20 | shift = (shift << 1)^ 0x8005;
21 | else
22 | shift <<= 1;
23 | val <<= 1;
24 | }
25 | }
26 | return shift;
27 | }
28 |
29 |
30 | }
31 |
--------------------------------------------------------------------------------
/app/src/androidTest/java/cn/seeyou/serialport/ExampleInstrumentedTest.java:
--------------------------------------------------------------------------------
1 | package cn.seeyou.serialport;
2 |
3 | import android.content.Context;
4 |
5 | import androidx.test.platform.app.InstrumentationRegistry;
6 | import androidx.test.ext.junit.runners.AndroidJUnit4;
7 |
8 | import org.junit.Test;
9 | import org.junit.runner.RunWith;
10 |
11 | import static org.junit.Assert.*;
12 |
13 | /**
14 | * Instrumented test, which will execute on an Android device.
15 | *
16 | * @see Testing documentation
17 | */
18 | @RunWith(AndroidJUnit4.class)
19 | public class ExampleInstrumentedTest {
20 | @Test
21 | public void useAppContext() {
22 | // Context of the app under test.
23 | Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
24 |
25 | assertEquals("cn.seeyou.serialport", appContext.getPackageName());
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/commlibrary/src/main/java/com/seeyou/comm/framework/commframe/cmdmanager/HandlerItem.java:
--------------------------------------------------------------------------------
1 | package com.seeyou.comm.framework.commframe.cmdmanager;
2 |
3 |
4 | import com.seeyou.comm.framework.commframe.ICMDHandler;
5 |
6 | /**
7 | * Create by seeyou
8 | * seeyou1052@foxmail.com
9 | */
10 | public class HandlerItem {
11 | int mCmd;
12 | int mFid;
13 | int mSid;
14 | ICMDHandler mHandler;
15 |
16 | public void setCmd(int id){
17 | this.mCmd = id;
18 | }
19 | public int getCmd(){
20 | return this.mCmd;
21 | }
22 |
23 | public void setFID(int fid){
24 | this.mFid = fid;
25 | }
26 | public int getFId(){
27 | return this.mFid;
28 | }
29 |
30 | public void setSID(int sid){
31 | this.mSid = sid;
32 | }
33 | public int getSId(){
34 | return this.mSid;
35 | }
36 |
37 | public void setHandler(ICMDHandler mHandler){
38 | this.mHandler = mHandler;
39 | }
40 | public ICMDHandler getHandler(){
41 | return mHandler;
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/app/src/main/java/cn/seeyou/serialport/MainActivity.java:
--------------------------------------------------------------------------------
1 | package cn.seeyou.serialport;
2 |
3 | import androidx.appcompat.app.AppCompatActivity;
4 |
5 | import android.os.Bundle;
6 |
7 | import cn.seeyou.serialport.comm.maker.DatasMaker;
8 | import cn.seeyou.serialport.comm.manager.CommManager;
9 | import cn.seeyou.serialport.comm.manager.SystemManager;
10 |
11 | public class MainActivity extends AppCompatActivity {
12 |
13 | @Override
14 | protected void onCreate(Bundle savedInstanceState) {
15 | super.onCreate(savedInstanceState);
16 | setContentView(R.layout.activity_main);
17 | //初始化串口配置
18 | SystemManager.getInstance(this).init();
19 | SendDatas();
20 | }
21 |
22 | /**
23 | * 打包发送串口数据
24 | */
25 | public void SendDatas(){
26 | DatasMaker maker = new DatasMaker();
27 | maker.SetCmd((byte) 0xff);
28 | maker.SetData(new byte[5]);
29 | CommManager.getInstance(this).sendDirect((byte[]) maker.make());
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 |
3 | android {
4 | compileSdkVersion 29
5 | buildToolsVersion "29.0.3"
6 | defaultConfig {
7 | applicationId "cn.seeyou.serialport"
8 | minSdkVersion 15
9 | targetSdkVersion 29
10 | versionCode 1
11 | versionName "1.0"
12 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
13 | }
14 | buildTypes {
15 | release {
16 | minifyEnabled false
17 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
18 | }
19 | }
20 | }
21 |
22 | dependencies {
23 | implementation fileTree(dir: 'libs', include: ['*.jar'])
24 | implementation 'androidx.appcompat:appcompat:1.0.2'
25 | implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
26 | testImplementation 'junit:junit:4.12'
27 | androidTestImplementation 'androidx.test:runner:1.1.1'
28 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'
29 | implementation project(':commlibrary')
30 | }
31 |
--------------------------------------------------------------------------------
/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=-Xmx1536m
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 | # Automatically convert third-party libraries to use AndroidX
19 | android.enableJetifier=true
20 |
21 |
--------------------------------------------------------------------------------
/commlibrary/src/main/java/com/seeyou/comm/framework/commframe/CommManagerBase.java:
--------------------------------------------------------------------------------
1 | package com.seeyou.comm.framework.commframe;
2 |
3 | import android.content.Context;
4 | import android.util.Log;
5 |
6 | /**
7 | * 基础通信框架
8 | * */
9 | public class CommManagerBase {
10 |
11 | private static final String TAG = "CommManagerBase";
12 |
13 | private IReadwriter mUartReadwriter;
14 | private final Context mContext;
15 |
16 |
17 | private LoopBuffer mRecLoopBuffer = null;
18 | private BaseProtocolHandler mProtocolHandler = null; //
19 | public void init(CommConfiguration config){
20 | mRecLoopBuffer.init(config.getFramelength());
21 | mProtocolHandler.init(config.getProtocolHandler());
22 | mUartReadwriter.start(config.getDevicePath(), config.getDevicePort(), config.getBaudrate());
23 | mProtocolHandler.start();
24 |
25 | Log.i(TAG, "init() end");
26 | }
27 |
28 | /**
29 | * @param
30 | * @explain
31 | */
32 | protected CommManagerBase(Context context) {
33 | mContext = context;
34 | mRecLoopBuffer = new LoopBuffer();
35 | mUartReadwriter = new UartReadwriter(mContext, mRecLoopBuffer);
36 |
37 |
38 | mProtocolHandler = new BaseProtocolHandler(mRecLoopBuffer);
39 |
40 | }
41 |
42 | public void sendDirect(byte[] directDatas) {
43 | mUartReadwriter.sendData(directDatas);
44 | }
45 |
46 | }
47 |
--------------------------------------------------------------------------------
/commlibrary/src/main/java/com/seeyou/comm/framework/commframe/makermanager/MakerManagerBase.java:
--------------------------------------------------------------------------------
1 | package com.seeyou.comm.framework.commframe.makermanager;
2 |
3 | import java.util.ArrayList;
4 | import java.util.Iterator;
5 | import java.util.List;
6 | import android.content.Context;
7 | /**
8 | * Create by seeyou
9 | * seeyou1052@foxmail.com
10 | */
11 | public class MakerManagerBase {
12 | private List sendCmdMakerList;
13 | protected Context mContext;
14 |
15 | protected MakerManagerBase(Context context){
16 | this.mContext = context;
17 | sendCmdMakerList = new ArrayList();
18 | }
19 |
20 |
21 |
22 | protected void addItem(int fid, int sid, IMaker maker){
23 | MakerItem item = new MakerItem();
24 | item.setFid(fid);
25 | item.setSid(sid);
26 | item.setMaker(maker);
27 | sendCmdMakerList.add(item);
28 | }
29 | protected void addItem(int cmd, IMaker maker){
30 | MakerItem item = new MakerItem();
31 | item.setFid(cmd);
32 | item.setMaker(maker);
33 | sendCmdMakerList.add(item);
34 | }
35 |
36 | public IMaker getMaker(int fid, int sid){
37 | Iterator sListIterator = sendCmdMakerList.iterator();
38 | while (sListIterator.hasNext()){
39 | MakerItem item = (MakerItem) sListIterator.next();
40 |
41 | if ((fid == item.getFid())
42 | && (sid == item.getSid())){
43 | return item.getMaker();
44 | }
45 | }
46 | return null;
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/commlibrary/src/main/java/com/seeyou/comm/framework/utils/FormatUtil.java:
--------------------------------------------------------------------------------
1 | package com.seeyou.comm.framework.utils;
2 |
3 | /**
4 | * Create by seeyou
5 | * seeyou1052@foxmail.com
6 | */
7 | public class FormatUtil {
8 | /**
9 | * 16进制字符串转换为byte[]
10 | *
11 | * @param hexString
12 | * @return
13 | */
14 | public static byte[] hexStringToBytes(String hexString) {
15 | if (hexString == null || hexString.equals("")) {
16 | return null;
17 | }
18 | hexString = hexString.toUpperCase().replace(" ", "");
19 | int length = hexString.length() / 2;
20 | char[] hexChars = hexString.toCharArray();
21 | byte[] d = new byte[length];
22 | for (int i = 0; i < length; i++) {
23 | int pos = i * 2;
24 | d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
25 | }
26 | return d;
27 | }
28 | /*
29 | * 十六进制转字符
30 | */
31 | public static String bytesToHexString(byte[] src){
32 | StringBuilder StringBuilder = new StringBuilder("");
33 | if (src == null || src.length <= 0) {
34 | return null;
35 | }
36 |
37 | for (int i = 0; i < src.length; i++) {
38 | int v = src[i] & 0xFF;
39 | String hv = Integer.toHexString(v);
40 | if (hv.length() < 2) {
41 | StringBuilder.append(0);
42 | }
43 |
44 | StringBuilder.append(hv);
45 | }
46 |
47 | return StringBuilder.toString();
48 | }
49 | private static byte charToByte(char c) {
50 | return (byte) "0123456789ABCDEF".indexOf(c);
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/commlibrary/src/main/java/com/seeyou/comm/framework/commframe/DefaultProtocolHandler.java:
--------------------------------------------------------------------------------
1 | package com.seeyou.comm.framework.commframe;
2 |
3 |
4 | public class DefaultProtocolHandler implements IProtocolHandler{
5 |
6 | @Override
7 | public void parseCmdPkg(byte[] src, int pkglen) {
8 | // TODO Auto-generated method stub
9 |
10 | }
11 |
12 | @Override
13 | public int getMinFrameLength() {
14 | // TODO Auto-generated method stub
15 | return 0;
16 | }
17 |
18 | @Override
19 | public boolean checkCommFrameHead(byte[] src, int startIndex) {
20 | // TODO Auto-generated method stub
21 | return false;
22 | }
23 |
24 | @Override
25 | public boolean checkFrameCrc(byte[] pkgData, int crcFramelen) {
26 | // TODO Auto-generated method stub
27 | return false;
28 | }
29 |
30 | @Override
31 | public boolean checkFrameTail(byte[] src, int startIndex, int pkglen) {
32 | // TODO Auto-generated method stub
33 | return false;
34 | }
35 |
36 | @Override
37 | public boolean checkPkgLength(byte[] src, int startIndex) {
38 | // TODO Auto-generated method stub
39 | return false;
40 | }
41 |
42 | @Override
43 | public boolean checkFrameSourceAdd(byte[] src, int startIndex) {
44 | // TODO Auto-generated method stub
45 | return false;
46 | }
47 |
48 | @Override
49 | public boolean checkFrameTarget(byte[] src, int startIndex) {
50 | // TODO Auto-generated method stub
51 | return false;
52 | }
53 |
54 | @Override
55 | public int getPkgLength(byte[] src, int startIndex) {
56 | // TODO Auto-generated method stub
57 | return 0;
58 | }
59 |
60 | @Override
61 | public int getPkgLengthNot(byte[] src, int startIndex) {
62 | // TODO Auto-generated method stub
63 | return 0;
64 | }
65 |
66 | }
67 |
--------------------------------------------------------------------------------
/commlibrary/src/main/java/com/seeyou/comm/framework/commframe/CommConfiguration.java:
--------------------------------------------------------------------------------
1 | package com.seeyou.comm.framework.commframe;
2 |
3 |
4 | import com.seeyou.comm.framework.commframe.makermanager.MakerManagerBase;
5 | /**
6 | * Create by seeyou
7 | * seeyou1052@foxmail.com
8 | */
9 | public class CommConfiguration {
10 | private int mPort;
11 | private int mBaudrate;
12 | private String mPath;
13 | // private ICMDHandler mCmdHandler;
14 | private MakerManagerBase mCmdMaker;
15 | private int mFramelength;
16 | private int mRwCacheLength;
17 | private IProtocolHandler mProtocolHandler;
18 |
19 | public MakerManagerBase getCmdMaker() {
20 | return mCmdMaker;
21 | }
22 |
23 | public void setCmdMaker(MakerManagerBase maker) {
24 | this.mCmdMaker = maker;
25 | }
26 |
27 | public int getDevicePort() {
28 | return mPort;
29 | }
30 |
31 | public void setDevicePort(int mPort) {
32 | this.mPort = mPort;
33 | }
34 | public int getBaudrate() {
35 | return mBaudrate;
36 | }
37 | public void setBaudrate(int mBaudrate) {
38 | this.mBaudrate = mBaudrate;
39 | }
40 | public String getDevicePath() {
41 | return mPath;
42 | }
43 | public void setDevicePath(String mPath) {
44 | this.mPath = mPath;
45 | }
46 |
47 | public int getFramelength() {
48 | return mFramelength;
49 | }
50 | public void setFramelength(int mFramelength) {
51 | this.mFramelength = mFramelength;
52 | }
53 |
54 | public int getCacheLength() {
55 | return mRwCacheLength;
56 | }
57 | public void setCacheLength(int len) {
58 | this.mRwCacheLength = len;
59 | }
60 |
61 | public IProtocolHandler getProtocolHandler() {
62 | return mProtocolHandler;
63 | }
64 | public void setProtocolHandler(IProtocolHandler handler) {
65 | this.mProtocolHandler = handler;
66 | }
67 | }
68 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable-v24/ic_launcher_foreground.xml:
--------------------------------------------------------------------------------
1 |
7 |
12 |
13 |
19 |
22 |
25 |
26 |
27 |
28 |
34 |
35 |
--------------------------------------------------------------------------------
/commlibrary/src/main/java/com/seeyou/comm/framework/commframe/KAChecker.java:
--------------------------------------------------------------------------------
1 | package com.seeyou.comm.framework.commframe;
2 |
3 | public class KAChecker extends Thread {
4 | private long katime = (15*1000); //心跳检测时间为15秒
5 | private boolean mIsRunning = false;
6 | private long lastkatimestamp = 0;
7 | @Override
8 | public void run() {
9 | while( mIsRunning ) {
10 | try {
11 | if ( getLastkatimestamp() == 0 ) {
12 | setLastkatimestamp( System.currentTimeMillis() );
13 | try {
14 | Thread.sleep(katime);
15 | } catch (InterruptedException e) {
16 | e.printStackTrace();
17 | }
18 | continue;
19 | }
20 |
21 | if ( kaTimeout() ) {
22 | mIsRunning = false;
23 | break;
24 |
25 | } else{
26 | try {
27 | Thread.sleep(katime);
28 | } catch (InterruptedException e) {
29 | e.printStackTrace();
30 | }
31 | }
32 |
33 | } catch(Exception ex) {
34 | ex.printStackTrace();
35 | }
36 | }
37 | //stopCommProcess();
38 | }
39 |
40 | /**
41 | * @return
42 | * @exception心跳超时
43 | */
44 | public boolean kaTimeout() {
45 | try {
46 | if ( mIsRunning == false ) {
47 | throw new Exception("user interrupt");
48 | }
49 | if( ( System.currentTimeMillis() - getLastkatimestamp() )> ( katime*3L) ) {
50 | return true;
51 | }
52 | } catch(Exception ex){
53 | ex.printStackTrace();
54 | }
55 | return false;
56 | }
57 |
58 | public void startWork() {
59 | try {
60 | mIsRunning = true;
61 | this.start();
62 | } catch ( Exception ex) {
63 | ex.printStackTrace();
64 | }
65 | }
66 |
67 | public void stopWork() {
68 | try {
69 | if ( mIsRunning ) {
70 | mIsRunning = false;
71 | this.interrupt();
72 | }
73 | } catch(Exception ex) {
74 | ex.printStackTrace();
75 | }
76 | }
77 |
78 | private long getLastkatimestamp() {
79 | return lastkatimestamp;
80 | }
81 |
82 | private void setLastkatimestamp(long lastkatimestamp) {
83 | this.lastkatimestamp = lastkatimestamp;
84 | }
85 | }
86 |
--------------------------------------------------------------------------------
/commlibrary/src/main/java/com/seeyou/comm/framework/commframe/cmdmanager/SIDHandlerManagerBase.java:
--------------------------------------------------------------------------------
1 | package com.seeyou.comm.framework.commframe.cmdmanager;
2 |
3 | import java.util.ArrayList;
4 | import java.util.Iterator;
5 | import java.util.List;
6 | import android.content.Context;
7 |
8 | import com.seeyou.comm.framework.commframe.ICMDHandler;
9 |
10 | /**
11 | * Create by seeyou
12 | * seeyou1052@foxmail.com
13 | */
14 | public class SIDHandlerManagerBase{
15 | private final static byte FID_DEFAULT_CMD = (byte)(0xFF); //
16 | protected Context mContext;
17 | private List mList;
18 |
19 | protected SIDHandlerManagerBase(Context context){
20 | this.mContext = context;
21 | mList = new ArrayList();
22 | }
23 |
24 | protected void addItem(int fid, int sid, ICMDHandler handler){
25 | HandlerItem item = new HandlerItem();
26 | //item.setID(id);
27 | item.setFID(fid);
28 | item.setSID(sid);
29 | item.setHandler(handler);
30 | mList.add(item);
31 | }
32 |
33 | protected void addItem(int cmd, ICMDHandler handler){
34 | HandlerItem item = new HandlerItem();
35 | //item.setID(id);
36 | item.setCmd(cmd);
37 | item.setHandler(handler);
38 | mList.add(item);
39 | }
40 |
41 | public ICMDHandler getHandler(int fid, int sid){
42 | ICMDHandler handler = searchHandler(fid, sid);
43 | if(handler == null){
44 | handler = loadDefaultCmdHandler(fid, sid);
45 | }
46 |
47 | return handler;
48 | }
49 |
50 | private ICMDHandler searchHandler(int fid, int sid){
51 | Iterator sListIterator = mList.iterator();
52 | while (sListIterator.hasNext()){
53 | HandlerItem item = (HandlerItem) sListIterator.next();
54 | int cmd = ((fid&0xff)<<8) + (sid&0xff);
55 | if(cmd == item.getCmd()){
56 | return item.getHandler();
57 | }
58 | // if ((fid == item.getFId()) && (sid == item.getSId())){
59 | // return item.getHandler();
60 | // }
61 | }
62 | return null;
63 | }
64 |
65 | private ICMDHandler loadDefaultCmdHandler(int fid, int sid){
66 | return searchHandler(FID_DEFAULT_CMD, FID_DEFAULT_CMD);
67 | }
68 | }
69 |
--------------------------------------------------------------------------------
/app/src/main/java/cn/seeyou/serialport/comm/manager/SystemManager.java:
--------------------------------------------------------------------------------
1 | package cn.seeyou.serialport.comm.manager;
2 |
3 | import android.content.Context;
4 |
5 | import com.seeyou.comm.framework.commframe.CommConfiguration;
6 | import com.seeyou.comm.framework.utils.CRCToolsA;
7 |
8 | import cn.seeyou.serialport.comm.agreement.ProtocolDefine;
9 | import cn.seeyou.serialport.comm.handler.CmdHandlerManager;
10 | import cn.seeyou.serialport.comm.handler.ProtocolHandler;
11 | import cn.seeyou.serialport.comm.maker.MakerManager;
12 |
13 | /**
14 | * Create by seeyou
15 | */
16 | public class SystemManager {
17 | private final static String TAG = "SystemManager";
18 |
19 | private Context mContext;
20 |
21 | private CommManager mCommManager = null;
22 |
23 | private static volatile SystemManager mInstance = null;
24 |
25 | public static SystemManager getInstance(Context context) {
26 | if (null == mInstance) {
27 | synchronized (SystemManager.class) {
28 | if (null == mInstance) {
29 | mInstance = new SystemManager(context);
30 | }
31 | }
32 | }
33 | return mInstance;
34 | }
35 |
36 | private SystemManager(Context context) {
37 | this.mContext = context;
38 | }
39 |
40 | /**
41 | * @exception初始化数据
42 | */
43 | public void init() {
44 | initInfrareUart();
45 | return;
46 | }
47 |
48 | /**
49 | * 初始化串口配置
50 | */
51 | public void initInfrareUart() {
52 | mCommManager = CommManager.getInstance(mContext);
53 | CommConfiguration config = new CommConfiguration();
54 | config.setBaudrate(ProtocolDefine.UartConstant.UART_MCU_BAUDRATE);
55 | config.setDevicePath(ProtocolDefine.UartConstant.UART_NAME);
56 | config.setDevicePort(ProtocolDefine.UartConstant.UART_PORT_MCU);
57 | config.setFramelength(ProtocolDefine.FRAME.FRAME_MC_lENGTH);
58 | config.setCacheLength(ProtocolDefine.FRAME.FRAME_MC_LENGTH_CACHE_MCUUART);
59 | config.setProtocolHandler(new ProtocolHandler(
60 | new CmdHandlerManager(mContext, mCommManager),
61 | new CRCToolsA()));
62 | config.setCmdMaker(new MakerManager(mContext));
63 | mCommManager.init(config);
64 | }
65 | }
66 |
--------------------------------------------------------------------------------
/app/src/main/java/cn/seeyou/serialport/comm/agreement/ProtocolDefine.java:
--------------------------------------------------------------------------------
1 | package cn.seeyou.serialport.comm.agreement;
2 |
3 | /**
4 | * Create by seeyou
5 | */
6 | public class ProtocolDefine {
7 | public class FRAME {
8 | //数据包信息定义
9 | public static final byte FRAME_MC_HEAD = (byte) 0x7e; //Head域 包头标志1
10 | public static final byte FRAME_MC_TAIL = (byte) 0x0d; //Tail域 包尾
11 | public static final int FRAME_MC_lENGTH = 1036; //Length域 通信协议包长度
12 | public static final int FRAME_MC_lENGTH_HEAD = 1; //包头长度
13 | public static final int FRAME_MC_lENGTH_TAIL = 3; //包尾长度
14 |
15 | public static final int FRAME_MC_LENGTH_READ_HEAD = 3; //读取包的前三个字节,包头(byte)+长度(short)
16 | public static final int FRAME_MC_LENGTH_CACHE_MCUUART = 1036; //初始化mcu uart缓存数据大小
17 |
18 | public static final int MIN_PACKAGE_LENGTH = 12; //最小包长度
19 | public static final int MAX_PACKAGE_LENGTH = 1036; //最大包长度
20 | public static final int FRAME_NOTUSE_LENTH = 8;//头和lenth和lenth取非和crc和tail的总长度
21 |
22 | public static final int FRAME_MC_HEAD_INDEX = 0; //包头字节
23 | public static final int FRAME_MC_LEN_H_INDEX = 1; //
24 | public static final int FRAME_MC_LEN_L_INDEX = 2; //
25 | public static final int FRAME_MC_NOTLEN_H_INDEX = 3; //
26 | public static final int FRAME_MC_NOTLEN_L_INDEX = 4; //
27 | public static final int FRAME_MC_SRCADDR_INDEX = 5; //
28 | public static final int FRAME_MC_TAGADDR_INDEX = 6; //
29 | public static final int FRAME_MC_PKGID_INDEX = 7; //
30 | public static final int FRAME_MC_CMD_INDEX = 8; // 之前为FID(修改成CMD)
31 | public static final int FRAME_MC_DATA_INDEX = 9; //之前为SID(修改成DATA)
32 |
33 | public static final byte COMMINUCATION_SRC_ADDR = 0x01;
34 | public static final byte COMMINUCAITON_TAR_ADDR = 0x02;
35 | public static final byte COMMINUCATION_BROADCAST_ADDR = (byte) 0xFF;
36 | }
37 |
38 | public class FID {
39 | //FID功能ID声明
40 | public final static byte FID_BASE_ID = (byte) 0xA0;//注册Handler指定标识
41 | }
42 | public class UartConstant {
43 | public final static String UART_NAME = "/dev/ttyUSB";
44 | public final static int UART_PORT_MCU = 3;
45 | public final static int UART_MCU_BAUDRATE = 115200; //115200
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/commlibrary/src/main/java/com/seeyou/comm/framework/commframe/UartReadwriter.java:
--------------------------------------------------------------------------------
1 | package com.seeyou.comm.framework.commframe;
2 | import java.nio.ByteBuffer;
3 | import java.util.LinkedList;
4 | import java.util.Queue;
5 |
6 | import android.content.Context;
7 | import android.util.Log;
8 |
9 |
10 | import cn.shorr.serialport.SerialPortConfig;
11 | import cn.shorr.serialport.SerialPortUtil;
12 | import cn.shorr.serialport.SerialRead;
13 | import cn.shorr.serialport.SerialWrite;
14 |
15 | /**
16 | * Create by seeyou
17 | * seeyou1052@foxmail.com
18 | */
19 | public class UartReadwriter implements IReadwriter, SerialRead.ReadDataListener,SerialWrite.WriteDataListener {
20 |
21 | private static final String TAG = "UartReadwriter";
22 |
23 | private SerialPortUtil serialPortUtil;
24 | private SerialRead serialRead; //串口读取数据服务
25 | private SerialWrite serialWrite;
26 | private Context mContext;
27 | private LoopBuffer mLoopBuffer;
28 |
29 | public UartReadwriter(Context mContext, LoopBuffer loopBuffer){
30 | this.mContext = mContext;
31 | this.mLoopBuffer = loopBuffer;
32 | }
33 |
34 | @Override
35 | public void start(String uartPath, int port, int baudrate) {
36 | //配置串口参数
37 | serialPortUtil = new SerialPortUtil(mContext, new SerialPortConfig(uartPath+port, baudrate));
38 | //设置为调试模式,打印收发数据
39 | serialPortUtil.setDebug(true);
40 | //绑定串口服务
41 | serialPortUtil.bindService();
42 | serialRead = new SerialRead(mContext);
43 | serialWrite = new SerialWrite(mContext);
44 | serialRead.registerListener(0/*默认为0,此参数可省略*/, this);
45 | }
46 |
47 | @Override
48 | public void onReadData(byte[] data) {
49 | //Log.e(TAG, "收到数据11:"+ FormatUtil.bytesToHexString(data));
50 | mLoopBuffer.pushData(data, 0 , data.length);
51 | }
52 |
53 | /**
54 | * @exception销毁释放串口
55 | */
56 | @Override
57 | public void stop() {
58 | serialRead.unRegisterListener();
59 | serialPortUtil.unBindService();
60 | }
61 |
62 | @Override
63 | public ByteBuffer read(byte[] bytes) {
64 | ByteBuffer buf = ByteBuffer.wrap(bytes);
65 | ByteBuffer.wrap(bytes,0,bytes.length);
66 | return buf;
67 | }
68 |
69 | /**
70 | * 发送串口数据
71 | * @param bytes
72 | */
73 | @Override
74 | public void sendData(byte[] bytes) {
75 | serialWrite.sendData(mContext, 0 , bytes);
76 | }
77 |
78 | @Override
79 | public void onWriteData(byte[] data) {
80 |
81 | }
82 | }
83 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | set DIRNAME=%~dp0
12 | if "%DIRNAME%" == "" set DIRNAME=.
13 | set APP_BASE_NAME=%~n0
14 | set APP_HOME=%DIRNAME%
15 |
16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
17 | set DEFAULT_JVM_OPTS=
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windows variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 |
53 | :win9xME_args
54 | @rem Slurp the command line arguments.
55 | set CMD_LINE_ARGS=
56 | set _SKIP=2
57 |
58 | :win9xME_args_slurp
59 | if "x%~1" == "x" goto execute
60 |
61 | set CMD_LINE_ARGS=%*
62 |
63 | :execute
64 | @rem Setup the command line
65 |
66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
67 |
68 | @rem Execute Gradle
69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
70 |
71 | :end
72 | @rem End local scope for the variables with windows NT shell
73 | if "%ERRORLEVEL%"=="0" goto mainEnd
74 |
75 | :fail
76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
77 | rem the _cmd.exe /c_ return code!
78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
79 | exit /b 1
80 |
81 | :mainEnd
82 | if "%OS%"=="Windows_NT" endlocal
83 |
84 | :omega
85 |
--------------------------------------------------------------------------------
/app/src/main/java/cn/seeyou/serialport/comm/handler/CmdHandlerManager.java:
--------------------------------------------------------------------------------
1 | package cn.seeyou.serialport.comm.handler;
2 |
3 | import android.content.Context;
4 | import android.util.Log;
5 |
6 | import com.seeyou.comm.framework.commframe.ICMDHandler;
7 | import com.seeyou.comm.framework.commframe.cmdmanager.SIDHandlerManagerBase;
8 |
9 | import java.lang.reflect.Constructor;
10 | import java.util.EnumSet;
11 |
12 | import cn.seeyou.serialport.comm.agreement.HandlerConfig;
13 | import cn.seeyou.serialport.comm.manager.CommManager;
14 |
15 | /**
16 | * Create by seeyou
17 | */
18 | public class CmdHandlerManager extends SIDHandlerManagerBase implements ICMDHandler {
19 | private final static String TAG = "CmdHandlerManager";
20 |
21 | private CommManager mCommManagerr;
22 |
23 | public CmdHandlerManager(Context mContext, CommManager commManagerr){
24 | super(mContext);
25 | this.mCommManagerr = commManagerr;
26 | initCmdHandler();
27 | }
28 | private void initCmdHandler(){
29 | Class[] parameterTypes = {Context.class, CommManager.class};
30 |
31 | EnumSet cmdConfig = EnumSet.allOf(HandlerConfig.class);
32 | for(HandlerConfig item : cmdConfig){
33 | Constructor con = null;
34 | Class clz = null;
35 | try {
36 | clz = (Class) Class.forName(item.getClassName());
37 | con = clz.getConstructor(parameterTypes);
38 | addItem(item.getCmd(), (ICMDHandler) con.newInstance(mContext, mCommManagerr));
39 | } catch (Exception e) {
40 | e.printStackTrace();
41 | }
42 | }
43 | return;
44 | }
45 | //获取指定handler
46 | @Override
47 | public void handle(byte[] bytes, byte packageid) {
48 | ICMDHandler CmdHandler = getHandler(bytes[0], bytes[1]);
49 | //数据数组无Handler指定标识 则可任意规定一个
50 | //ICMDHandler CmdHandler = getHandler(00, 0xA0);
51 | handlerProcessor(CmdHandler,bytes,packageid);
52 | return;
53 | }
54 |
55 | /**
56 | * @param handler
57 | * @param bytes
58 | * @param packageid
59 | * @exception命令处理handler
60 | */
61 | private synchronized void handlerProcessor(final ICMDHandler handler, final byte[] bytes, final byte packageid){
62 | try{
63 | if ( null == handler ) {
64 | Log.e(TAG,"evevatorhandle function in getHandler bytes[0]:" + Integer.toHexString(bytes[0])
65 | + " ,bytes[1]:" + Integer.toHexString(bytes[1]));
66 | return ;
67 | }
68 | handler.handle(bytes, packageid);
69 |
70 | } catch(Exception ex){
71 | ex.printStackTrace();
72 | }
73 | return;
74 | }
75 |
76 | }
77 |
--------------------------------------------------------------------------------
/app/src/main/java/cn/seeyou/serialport/comm/maker/ProtocolMaker.java:
--------------------------------------------------------------------------------
1 | package cn.seeyou.serialport.comm.maker;
2 |
3 | import com.seeyou.comm.framework.commframe.makermanager.IMaker;
4 | import com.seeyou.comm.framework.utils.ByteConverter;
5 | import com.seeyou.comm.framework.utils.CRCToolsA;
6 | import com.seeyou.comm.framework.utils.ICrcTools;
7 |
8 | import cn.seeyou.serialport.comm.agreement.ProtocolDefine;
9 |
10 | /**
11 | * Create by seeyou
12 | */
13 | public abstract class ProtocolMaker implements IMaker {
14 | private static byte bPackageid = (byte)0x00;
15 | private ICrcTools createCrc;
16 |
17 | public abstract byte[] createData();
18 | public abstract byte createCmd();
19 |
20 | public ProtocolMaker(){
21 | createCrc = new CRCToolsA();
22 | }
23 |
24 | @Override
25 | public Object make() {
26 | // TODO Auto-generated method stub
27 | byte[] commPkg;
28 | byte[] commDat = createData();
29 | if(commDat != null){
30 | commPkg = new byte[commDat.length + ProtocolDefine.FRAME.MIN_PACKAGE_LENGTH ];
31 | }
32 | else {
33 | commPkg = new byte[ProtocolDefine.FRAME.MIN_PACKAGE_LENGTH ];
34 | }
35 | makeHead(commPkg);
36 | makeCmd(commPkg, createCmd());
37 | makeData(commDat,commPkg);
38 | makeCrcAndTail(commPkg);
39 | return commPkg;
40 | }
41 |
42 |
43 |
44 |
45 | private void makeHead(byte[] pkg) {
46 | short iFrameDataLen = (short)pkg.length;
47 | byte[] bFrameHeadDataLen = ByteConverter.shortToBytes(iFrameDataLen);
48 | pkg[ProtocolDefine.FRAME.FRAME_MC_HEAD_INDEX] = ProtocolDefine.FRAME.FRAME_MC_HEAD;
49 | pkg[ProtocolDefine.FRAME.FRAME_MC_LEN_H_INDEX] = bFrameHeadDataLen[1];
50 | pkg[ProtocolDefine.FRAME.FRAME_MC_LEN_L_INDEX] = bFrameHeadDataLen[0];
51 | pkg[ProtocolDefine.FRAME.FRAME_MC_NOTLEN_H_INDEX] = (byte)(~bFrameHeadDataLen[1]);
52 | pkg[ProtocolDefine.FRAME.FRAME_MC_NOTLEN_L_INDEX] = (byte)(~bFrameHeadDataLen[0]);
53 | pkg[ProtocolDefine.FRAME.FRAME_MC_SRCADDR_INDEX] = (byte)ProtocolDefine.FRAME.COMMINUCAITON_TAR_ADDR; //源地址
54 | pkg[ProtocolDefine.FRAME.FRAME_MC_TAGADDR_INDEX] = (byte)ProtocolDefine.FRAME.COMMINUCATION_SRC_ADDR; //目的地址
55 | pkg[ProtocolDefine.FRAME.FRAME_MC_PKGID_INDEX] = getPackgeId(); //包id
56 | }
57 | private void makeCmd(byte[] pkg, byte cmd){
58 | pkg[ProtocolDefine.FRAME.FRAME_MC_CMD_INDEX] = cmd;
59 | }
60 | private void makeData(byte[] src,byte[] pkg){
61 | System.arraycopy(src,0 , pkg, ProtocolDefine.FRAME.FRAME_MC_DATA_INDEX, src.length);
62 | }
63 |
64 | private void makeCrcAndTail(byte[] pkg){
65 | int crcLength = pkg.length - 3;
66 | int sCRCData = (createCrc.handle(pkg, crcLength));
67 | byte[] bCRCData = ByteConverter.shortToBytesBig((short)sCRCData);
68 | pkg[crcLength] = bCRCData[0];
69 | pkg[crcLength+1] = bCRCData[1];
70 | pkg[crcLength+2] = ProtocolDefine.FRAME.FRAME_MC_TAIL;
71 | }
72 |
73 | private static byte getPackgeId(){
74 | return bPackageid++;
75 | }
76 | }
77 |
--------------------------------------------------------------------------------
/commlibrary/src/main/java/com/seeyou/comm/framework/commframe/LoopBuffer.java:
--------------------------------------------------------------------------------
1 | package com.seeyou.comm.framework.commframe;
2 |
3 | /**
4 | * @Description.循环buffer处理
5 | */
6 | public class LoopBuffer{
7 | private static final String TAG = "CommLoopBufferBase";
8 |
9 | private byte[] mBuffer = null; //数据缓存buffer
10 | private int mRdIndex = 0; //读数据数组下标
11 | private int mWrIndex = 0; //写数据数组下标
12 | private int mBufferLen;
13 | private int mDataLen = 0;
14 |
15 | public void init(int len) {
16 | this.mBufferLen = len;
17 | if ( null == mBuffer ) {
18 | mBuffer = new byte[mBufferLen];
19 | mBuffer[0] = (byte)(0x00);
20 | }
21 | mRdIndex = 0;
22 | mWrIndex = 0;
23 | }
24 |
25 | public int getBufferLength(){
26 | return this.mBufferLen;
27 | }
28 |
29 | public synchronized int getCurrentRd(){
30 | return this.mRdIndex;
31 | }
32 | public synchronized byte[] getBuffer(){
33 | return this.mBuffer;
34 | }
35 | /*
36 | * 返回缓冲区有效数据长度
37 | * */
38 | public int getDataLen(){
39 | return this.mDataLen;
40 | }
41 | /*
42 | * 返回缓冲区剩余字节长度
43 | * */
44 | public int getSpaceLen(){
45 | return mBufferLen-mDataLen;
46 | }
47 |
48 | public synchronized void incDataLength(){
49 | if(mDataLen < mBufferLen){
50 | mDataLen += 1;
51 | }
52 | }
53 |
54 | public void incDataLength(int len) {
55 | for (int i = 0; i < len; i++){
56 | incDataLength();
57 | }
58 | }
59 |
60 | public synchronized void decDataLength(){
61 | if(mDataLen > 0){
62 | mDataLen -= 1;
63 | }
64 | }
65 |
66 | public void decDataLength(int len) {
67 | for (int i = 0; i < len; i++){
68 | decDataLength();
69 | }
70 | }
71 |
72 | public synchronized void incRdIndex(int len){
73 | if (mRdIndex + len < mBufferLen){
74 | mRdIndex += len;
75 | } else {
76 | mRdIndex = mRdIndex + len - mBufferLen;
77 | }
78 | }
79 |
80 | private synchronized void incWrIndex(int len){
81 | if (mWrIndex + len < mBufferLen){
82 | mWrIndex += len;
83 | }else{
84 | mWrIndex = mWrIndex + len - mBufferLen;
85 | }
86 | }
87 |
88 | /**
89 | * 写数据到缓冲区,返回成功写入数据长度
90 | * */
91 | public int pushData(byte[] src, int idx, int len){
92 | int length = getSpaceLen();
93 |
94 | if(length < len){
95 | return pushNByte(src, idx, length);
96 | } else {
97 | return pushNByte(src, idx, len);
98 | }
99 | }
100 |
101 | /**
102 | * 写数据到缓冲区
103 | * 写之前需要调用getDataLen()方法确认空间足够
104 | * */
105 | public int pushNByte(byte[] src, int idx, int len) {
106 | for (int i = 0; i < len; i++){
107 | this.mBuffer[mWrIndex] = src[idx + i];
108 | incWrIndex(1);
109 | incDataLength(1);
110 | }
111 | return len;
112 | }
113 |
114 | public int pullData(byte[] bytes, int len){
115 | int dataLen = getDataLen();
116 | if(dataLen < len){
117 | return pullNByte(bytes, dataLen);
118 | } else {
119 | return pullNByte(bytes, len);
120 | }
121 | }
122 |
123 | public int pullNByte(byte[] bytes, int len){
124 | for(int i = 0; i < len; i++){
125 | bytes[i] = this.mBuffer[mRdIndex];
126 | incRdIndex(1);
127 | decDataLength(1);
128 | }
129 | return len;
130 | }
131 |
132 |
133 |
134 |
135 |
136 |
137 | }
138 |
--------------------------------------------------------------------------------
/commlibrary/src/main/java/com/seeyou/comm/framework/commframe/BaseProtocolHandler.java:
--------------------------------------------------------------------------------
1 | package com.seeyou.comm.framework.commframe;
2 |
3 | /**
4 | * Create by seeyou
5 | * seeyou1052@foxmail.com
6 | */
7 | public class BaseProtocolHandler {
8 | private static final String TAG = "ProtocolHandlerBase";
9 | private Thread mThread = null;
10 | private boolean isRunning;
11 | protected LoopBuffer mLoopBuffer;
12 | private IProtocolHandler mProtocolHandler;
13 |
14 | public BaseProtocolHandler(LoopBuffer buffer){
15 | isRunning = false;
16 | mLoopBuffer = buffer;
17 | mProtocolHandler = new DefaultProtocolHandler();
18 | }
19 | public void init(IProtocolHandler handler){
20 | mProtocolHandler = handler;
21 | }
22 | public void start() {
23 | isRunning = true;
24 | mThread = new Thread(new ProtocolHandlerRunable());
25 | mThread.start();
26 | }
27 |
28 | public void stop() {
29 | isRunning = false;
30 | if (null != mThread) {
31 | mThread.interrupt();
32 | mThread = null;
33 | }
34 | }
35 |
36 | protected class ProtocolHandlerRunable implements Runnable{
37 |
38 | @Override
39 | public void run() {
40 | // TODO Auto-generated method stub
41 | while (isRunning) {
42 | handleComm();
43 | try {
44 | Thread.sleep(2);
45 | } catch (InterruptedException ex) {
46 | ex.printStackTrace();
47 | }
48 | }
49 | }
50 | }
51 |
52 | protected void handleComm(){
53 | int frameStartIndex;
54 | byte[] recBuffer = mLoopBuffer.getBuffer();
55 | int commFramePkgLen;
56 | while(mLoopBuffer.getDataLen() > mProtocolHandler.getMinFrameLength()){
57 | frameStartIndex = mLoopBuffer.getCurrentRd();
58 | if (!mProtocolHandler.checkCommFrameHead(recBuffer, frameStartIndex)) {
59 | //Log.e(TAG,"checkCommFrameHead 验证头部失败");
60 | mLoopBuffer.incRdIndex(1);
61 | mLoopBuffer.decDataLength(1);
62 | continue;
63 | }
64 |
65 | commFramePkgLen = mProtocolHandler.getPkgLength(recBuffer, frameStartIndex);
66 |
67 | if(!mProtocolHandler.checkPkgLength(recBuffer, frameStartIndex)){
68 | //Log.e(TAG,"checkPkgLength 验证包长失败");
69 | mLoopBuffer.incRdIndex(1);
70 | mLoopBuffer.decDataLength(1);
71 | continue;
72 | }
73 |
74 | if(commFramePkgLen > mLoopBuffer.getDataLen()){
75 | return;
76 | }
77 | if(commFramePkgLen < mProtocolHandler.getMinFrameLength()){
78 | mLoopBuffer.incRdIndex(1);
79 | mLoopBuffer.decDataLength(1);
80 | continue;
81 | }
82 |
83 | if(!mProtocolHandler.checkFrameTail(recBuffer, frameStartIndex, commFramePkgLen)){
84 | //Log.e(TAG,"checkFrameTail failed");
85 | mLoopBuffer.incRdIndex(1);
86 | mLoopBuffer.decDataLength(1);
87 | continue;
88 | }
89 |
90 | // 有效包,读出解析
91 | byte[] readOutPkg = new byte[commFramePkgLen];
92 | mLoopBuffer.pullNByte(readOutPkg, commFramePkgLen);
93 | // Log.i(getClass().getName(), " handleComm() bytes:"+Arrays.toString(readOutPkg));
94 | // Log.i(getClass().getName(), " handleComm() commFramePkgLen:"+commFramePkgLen);
95 | if(!mProtocolHandler.checkPkgLength(recBuffer, frameStartIndex)){
96 | //Log.e(TAG,"checkPkgLength failed");
97 | return;
98 | }
99 |
100 | if(!mProtocolHandler.checkFrameCrc(readOutPkg, commFramePkgLen-3)){
101 | //Log.e(TAG,"checkFrameCrc failed");
102 | return;
103 | }
104 |
105 | mProtocolHandler.parseCmdPkg(readOutPkg, commFramePkgLen);
106 | }
107 | }
108 |
109 |
110 | }
111 |
--------------------------------------------------------------------------------
/commlibrary/src/main/java/com/seeyou/comm/framework/utils/CRCToolsA.java:
--------------------------------------------------------------------------------
1 | package com.seeyou.comm.framework.utils;
2 |
3 |
4 | /**
5 | * Create by seeyou
6 | * seeyou1052@foxmail.com
7 | */
8 | public class CRCToolsA implements ICrcTools {
9 |
10 | public int handle(byte[] dat, int len) {
11 | // TODO Auto-generated method stub
12 | return g_Can_C_Crc16CheckFromTable(dat, len);
13 | }
14 |
15 |
16 | /*! \brief FUNCTION: g_Can_C_Crc16Check
17 | *
18 | * DESCRIPTION: calc CAN NP3D protocol crc16 check from table
19 | *
20 | * PARAMETERS: [I]: pDatapFrame the data be checkSum
21 | * [I]: frame_len, the length of data be checkSum
22 | *
23 | * RETURN: the checkSum value
24 | *
25 | * NOTES: None
26 | ***************************************************************************/
27 | public int g_Can_C_Crc16CheckFromTable(byte[] pszBuf, int unLength)
28 | {
29 | //MODBUS CRC-16表 8005 逆序
30 |
31 | return GetCrc_16(pszBuf, unLength, 0xFFFF, g_McRctable_16);
32 | }
33 |
34 | static int GetCrc_16(byte[] pData, int nLength, int init, int[] ptable)
35 | {
36 | int cRc_16 = init;
37 | int temp;
38 | int i = 0;
39 | while(nLength-- > 0)
40 | {
41 | temp = cRc_16 >> 8;
42 | cRc_16 = (cRc_16 << 8) ^ ptable[(temp ^ (int)(pData[i++])) & 0xFF];
43 | }
44 |
45 | return cRc_16;
46 | }
47 |
48 |
49 |
50 |
51 | //逆序CRC计算
52 | private final int[] g_McRctable_16 = new int[]
53 | {
54 | 0x0000, 0x8005, 0x800F, 0x000A, 0x801B, 0x001E, 0x0014, 0x8011,
55 | 0x8033, 0x0036, 0x003C, 0x8039, 0x0028, 0x802D, 0x8027, 0x0022,
56 | 0x8063, 0x0066, 0x006C, 0x8069, 0x0078, 0x807D, 0x8077, 0x0072,
57 | 0x0050, 0x8055, 0x805F, 0x005A, 0x804B, 0x004E, 0x0044, 0x8041,
58 | 0x80C3, 0x00C6, 0x00CC, 0x80C9, 0x00D8, 0x80DD, 0x80D7, 0x00D2,
59 | 0x00F0, 0x80F5, 0x80FF, 0x00FA, 0x80EB, 0x00EE, 0x00E4, 0x80E1,
60 | 0x00A0, 0x80A5, 0x80AF, 0x00AA, 0x80BB, 0x00BE, 0x00B4, 0x80B1,
61 | 0x8093, 0x0096, 0x009C, 0x8099, 0x0088, 0x808D, 0x8087, 0x0082,
62 | 0x8183, 0x0186, 0x018C, 0x8189, 0x0198, 0x819D, 0x8197, 0x0192,
63 | 0x01B0, 0x81B5, 0x81BF, 0x01BA, 0x81AB, 0x01AE, 0x01A4, 0x81A1,
64 | 0x01E0, 0x81E5, 0x81EF, 0x01EA, 0x81FB, 0x01FE, 0x01F4, 0x81F1,
65 | 0x81D3, 0x01D6, 0x01DC, 0x81D9, 0x01C8, 0x81CD, 0x81C7, 0x01C2,
66 | 0x0140, 0x8145, 0x814F, 0x014A, 0x815B, 0x015E, 0x0154, 0x8151,
67 | 0x8173, 0x0176, 0x017C, 0x8179, 0x0168, 0x816D, 0x8167, 0x0162,
68 | 0x8123, 0x0126, 0x012C, 0x8129, 0x0138, 0x813D, 0x8137, 0x0132,
69 | 0x0110, 0x8115, 0x811F, 0x011A, 0x810B, 0x010E, 0x0104, 0x8101,
70 | 0x8303, 0x0306, 0x030C, 0x8309, 0x0318, 0x831D, 0x8317, 0x0312,
71 | 0x0330, 0x8335, 0x833F, 0x033A, 0x832B, 0x032E, 0x0324, 0x8321,
72 | 0x0360, 0x8365, 0x836F, 0x036A, 0x837B, 0x037E, 0x0374, 0x8371,
73 | 0x8353, 0x0356, 0x035C, 0x8359, 0x0348, 0x834D, 0x8347, 0x0342,
74 | 0x03C0, 0x83C5, 0x83CF, 0x03CA, 0x83DB, 0x03DE, 0x03D4, 0x83D1,
75 | 0x83F3, 0x03F6, 0x03FC, 0x83F9, 0x03E8, 0x83ED, 0x83E7, 0x03E2,
76 | 0x83A3, 0x03A6, 0x03AC, 0x83A9, 0x03B8, 0x83BD, 0x83B7, 0x03B2,
77 | 0x0390, 0x8395, 0x839F, 0x039A, 0x838B, 0x038E, 0x0384, 0x8381,
78 | 0x0280, 0x8285, 0x828F, 0x028A, 0x829B, 0x029E, 0x0294, 0x8291,
79 | 0x82B3, 0x02B6, 0x02BC, 0x82B9, 0x02A8, 0x82AD, 0x82A7, 0x02A2,
80 | 0x82E3, 0x02E6, 0x02EC, 0x82E9, 0x02F8, 0x82FD, 0x82F7, 0x02F2,
81 | 0x02D0, 0x82D5, 0x82DF, 0x02DA, 0x82CB, 0x02CE, 0x02C4, 0x82C1,
82 | 0x8243, 0x0246, 0x024C, 0x8249, 0x0258, 0x825D, 0x8257, 0x0252,
83 | 0x0270, 0x8275, 0x827F, 0x027A, 0x826B, 0x026E, 0x0264, 0x8261,
84 | 0x0220, 0x8225, 0x822F, 0x022A, 0x823B, 0x023E, 0x0234, 0x8231,
85 | 0x8213, 0x0216, 0x021C, 0x8219, 0x0208, 0x820D, 0x8207, 0x0202,
86 |
87 | };
88 | }
89 |
--------------------------------------------------------------------------------
/.idea/codeStyles/Project.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 | xmlns:android
14 |
15 | ^$
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 | xmlns:.*
25 |
26 | ^$
27 |
28 |
29 | BY_NAME
30 |
31 |
32 |
33 |
34 |
35 |
36 | .*:id
37 |
38 | http://schemas.android.com/apk/res/android
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 | .*:name
48 |
49 | http://schemas.android.com/apk/res/android
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 | name
59 |
60 | ^$
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 | style
70 |
71 | ^$
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 | .*
81 |
82 | ^$
83 |
84 |
85 | BY_NAME
86 |
87 |
88 |
89 |
90 |
91 |
92 | .*
93 |
94 | http://schemas.android.com/apk/res/android
95 |
96 |
97 | ANDROID_ATTRIBUTE_ORDER
98 |
99 |
100 |
101 |
102 |
103 |
104 | .*
105 |
106 | .*
107 |
108 |
109 | BY_NAME
110 |
111 |
112 |
113 |
114 |
115 |
116 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Attempt to set APP_HOME
10 | # Resolve links: $0 may be a link
11 | PRG="$0"
12 | # Need this for relative symlinks.
13 | while [ -h "$PRG" ] ; do
14 | ls=`ls -ld "$PRG"`
15 | link=`expr "$ls" : '.*-> \(.*\)$'`
16 | if expr "$link" : '/.*' > /dev/null; then
17 | PRG="$link"
18 | else
19 | PRG=`dirname "$PRG"`"/$link"
20 | fi
21 | done
22 | SAVED="`pwd`"
23 | cd "`dirname \"$PRG\"`/" >/dev/null
24 | APP_HOME="`pwd -P`"
25 | cd "$SAVED" >/dev/null
26 |
27 | APP_NAME="Gradle"
28 | APP_BASE_NAME=`basename "$0"`
29 |
30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
31 | DEFAULT_JVM_OPTS=""
32 |
33 | # Use the maximum available, or set MAX_FD != -1 to use that value.
34 | MAX_FD="maximum"
35 |
36 | warn () {
37 | echo "$*"
38 | }
39 |
40 | die () {
41 | echo
42 | echo "$*"
43 | echo
44 | exit 1
45 | }
46 |
47 | # OS specific support (must be 'true' or 'false').
48 | cygwin=false
49 | msys=false
50 | darwin=false
51 | nonstop=false
52 | case "`uname`" in
53 | CYGWIN* )
54 | cygwin=true
55 | ;;
56 | Darwin* )
57 | darwin=true
58 | ;;
59 | MINGW* )
60 | msys=true
61 | ;;
62 | NONSTOP* )
63 | nonstop=true
64 | ;;
65 | esac
66 |
67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
68 |
69 | # Determine the Java command to use to start the JVM.
70 | if [ -n "$JAVA_HOME" ] ; then
71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
72 | # IBM's JDK on AIX uses strange locations for the executables
73 | JAVACMD="$JAVA_HOME/jre/sh/java"
74 | else
75 | JAVACMD="$JAVA_HOME/bin/java"
76 | fi
77 | if [ ! -x "$JAVACMD" ] ; then
78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
79 |
80 | Please set the JAVA_HOME variable in your environment to match the
81 | location of your Java installation."
82 | fi
83 | else
84 | JAVACMD="java"
85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
86 |
87 | Please set the JAVA_HOME variable in your environment to match the
88 | location of your Java installation."
89 | fi
90 |
91 | # Increase the maximum file descriptors if we can.
92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
93 | MAX_FD_LIMIT=`ulimit -H -n`
94 | if [ $? -eq 0 ] ; then
95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
96 | MAX_FD="$MAX_FD_LIMIT"
97 | fi
98 | ulimit -n $MAX_FD
99 | if [ $? -ne 0 ] ; then
100 | warn "Could not set maximum file descriptor limit: $MAX_FD"
101 | fi
102 | else
103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
104 | fi
105 | fi
106 |
107 | # For Darwin, add options to specify how the application appears in the dock
108 | if $darwin; then
109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
110 | fi
111 |
112 | # For Cygwin, switch paths to Windows format before running java
113 | if $cygwin ; then
114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
116 | JAVACMD=`cygpath --unix "$JAVACMD"`
117 |
118 | # We build the pattern for arguments to be converted via cygpath
119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
120 | SEP=""
121 | for dir in $ROOTDIRSRAW ; do
122 | ROOTDIRS="$ROOTDIRS$SEP$dir"
123 | SEP="|"
124 | done
125 | OURCYGPATTERN="(^($ROOTDIRS))"
126 | # Add a user-defined pattern to the cygpath arguments
127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
129 | fi
130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
131 | i=0
132 | for arg in "$@" ; do
133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
135 |
136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
138 | else
139 | eval `echo args$i`="\"$arg\""
140 | fi
141 | i=$((i+1))
142 | done
143 | case $i in
144 | (0) set -- ;;
145 | (1) set -- "$args0" ;;
146 | (2) set -- "$args0" "$args1" ;;
147 | (3) set -- "$args0" "$args1" "$args2" ;;
148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
154 | esac
155 | fi
156 |
157 | # Escape application args
158 | save () {
159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
160 | echo " "
161 | }
162 | APP_ARGS=$(save "$@")
163 |
164 | # Collect all arguments for the java command, following the shell quoting and substitution rules
165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
166 |
167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
169 | cd "$(dirname "$0")"
170 | fi
171 |
172 | exec "$JAVACMD" "$@"
173 |
--------------------------------------------------------------------------------
/app/src/main/java/cn/seeyou/serialport/comm/handler/ProtocolHandler.java:
--------------------------------------------------------------------------------
1 | package cn.seeyou.serialport.comm.handler;
2 |
3 | import android.content.Context;
4 |
5 | import com.seeyou.comm.framework.commframe.ICMDHandler;
6 | import com.seeyou.comm.framework.commframe.IProtocolHandler;
7 | import com.seeyou.comm.framework.commframe.KAChecker;
8 | import com.seeyou.comm.framework.utils.ICrcTools;
9 |
10 | import cn.seeyou.serialport.comm.agreement.ProtocolDefine;
11 |
12 | /**
13 | * Create by seeyou
14 | */
15 | public class ProtocolHandler implements IProtocolHandler {
16 | private static final String TAG = "ProtocolHandler";
17 | private ICrcTools crcCreater;
18 |
19 | private ICMDHandler mCmdManager = null;
20 | private KAChecker mKAChecker = null;
21 | private Context context;
22 |
23 | public ProtocolHandler(ICMDHandler manager, ICrcTools crcTools) {
24 | mCmdManager = manager;
25 | crcCreater = crcTools;
26 | }
27 | public ProtocolHandler(Context context, ICrcTools crcTools) {
28 | crcCreater = crcTools;
29 | this.context = context;
30 | }
31 | public boolean checkHead(byte[] src, int pkglen){
32 | int head = byteToInt(src[0]);
33 | return head == byteToInt(ProtocolDefine.FRAME.FRAME_MC_HEAD);
34 | }
35 |
36 | public boolean checkTail(byte[] src, int pkglen){
37 | int length = (int)getShort(byteToInt(src[1]), byteToInt(src[2]));
38 | int tail = byteToInt(src[length-1]);
39 | return tail == byteToInt(ProtocolDefine.FRAME.FRAME_MC_TAIL);
40 | }
41 |
42 | public boolean checkLength(byte[] src){
43 | int length = (int)getShort(byteToInt(src[1]), byteToInt(src[2]));
44 | return length >=12 && length <= 1036;
45 | }
46 |
47 |
48 | public void parseCmdPkg(byte[] src, int pkglen){
49 | int cmdPkgLen = pkglen- ProtocolDefine.FRAME.FRAME_NOTUSE_LENTH ;//减去(头+lenth+lenth取非+Crc+tail)长度 得到从src开始到data结束
50 | byte cmdPkg[] = new byte[cmdPkgLen];
51 | byte pkgId = src[ProtocolDefine.FRAME.FRAME_MC_PKGID_INDEX];
52 | System.arraycopy(src,
53 | ProtocolDefine.FRAME.FRAME_MC_SRCADDR_INDEX,
54 | cmdPkg,
55 | 0,
56 | cmdPkgLen);
57 | mCmdManager.handle(cmdPkg, pkgId);
58 | }
59 |
60 | public boolean checkFrameCrc(byte[] pkgData, int crcFramelen){
61 | int sumCrc = crcCreater.handle(pkgData, crcFramelen) & 0xffff;
62 |
63 | int crc = (pkgData[(crcFramelen+1) % ProtocolDefine.FRAME.FRAME_MC_lENGTH]&0xFF)
64 | | ((pkgData[crcFramelen % ProtocolDefine.FRAME.FRAME_MC_lENGTH] << 8 )&0xFF00);
65 | return sumCrc == crc;
66 | }
67 |
68 | public boolean checkFrameTail(byte[] src, int startIndex, int pkglen){
69 | int tailIndex = (startIndex + pkglen-1) % ProtocolDefine.FRAME.FRAME_MC_lENGTH;
70 | return src[tailIndex] == ProtocolDefine.FRAME.FRAME_MC_TAIL;
71 | }
72 |
73 | public boolean checkCommFrameHead(byte[] src, int startIndex){
74 | int headIndex = (startIndex + ProtocolDefine.FRAME.FRAME_MC_HEAD_INDEX) % ProtocolDefine.FRAME.FRAME_MC_lENGTH;
75 | // boolean ret;
76 | // ret = (src[headIndex] == ProtocolDefine.FRAME.FRAME_MC_HEAD);
77 | // Log.e("ret:",""+ ret);
78 | return (src[headIndex] == ProtocolDefine.FRAME.FRAME_MC_HEAD);
79 | // {
80 | // return true;
81 | // }
82 | // else {
83 | // return false;
84 | // }
85 | }
86 |
87 | public boolean checkPkgLength(byte[] src, int startIndex){
88 | int pkgLen = getPkgLength(src, startIndex);
89 | int pkgNotLen = getPkgLengthNot(src, startIndex);
90 | return (((~pkgLen)&0xffff) == ((pkgNotLen)&0xffff));
91 | }
92 |
93 | //验证src
94 | public boolean checkFrameSourceAdd(byte[] src, int startIndex){
95 | byte source = src[(startIndex + ProtocolDefine.FRAME.FRAME_MC_SRCADDR_INDEX)%ProtocolDefine.FRAME.FRAME_MC_lENGTH];
96 | return ProtocolDefine.FRAME.COMMINUCATION_SRC_ADDR == source;
97 | }
98 |
99 | //验证target
100 | public boolean checkFrameTarget(byte[] src, int startIndex){
101 | byte target = src[(startIndex + ProtocolDefine.FRAME.FRAME_MC_TAGADDR_INDEX)%ProtocolDefine.FRAME.FRAME_MC_lENGTH];
102 | if(target == ProtocolDefine.FRAME.COMMINUCATION_BROADCAST_ADDR){
103 | return true;
104 | } else {
105 | return ProtocolDefine.FRAME.COMMINUCAITON_TAR_ADDR == target;
106 | }
107 | }
108 |
109 | //获取pkg
110 | public int getPkgLength(byte[] src, int startIndex){
111 | byte lenH = src[(startIndex+ProtocolDefine.FRAME.FRAME_MC_LEN_H_INDEX)%ProtocolDefine.FRAME.FRAME_MC_lENGTH];
112 | byte lenL = src[(startIndex+ProtocolDefine.FRAME.FRAME_MC_LEN_L_INDEX)%ProtocolDefine.FRAME.FRAME_MC_lENGTH];
113 |
114 | int length = ((lenL & 0xFF)
115 | | ((lenH<<8) & 0xFF00));
116 | return length;
117 | }
118 |
119 | //获取LengthNot域
120 | public int getPkgLengthNot(byte[] src, int startIndex){
121 | byte lenH = src[(startIndex+ProtocolDefine.FRAME.FRAME_MC_NOTLEN_H_INDEX)%ProtocolDefine.FRAME.FRAME_MC_lENGTH];
122 | byte lenL = src[(startIndex+ProtocolDefine.FRAME.FRAME_MC_NOTLEN_L_INDEX)%ProtocolDefine.FRAME.FRAME_MC_lENGTH];
123 | int length = ((lenL & 0xFF)
124 | | ((lenH<<8) & 0xFF00));
125 | return length;
126 | }
127 |
128 | //获取包最小长度
129 | public int getMinFrameLength() {
130 | return ProtocolDefine.FRAME.MIN_PACKAGE_LENGTH;
131 | }
132 | //获取最大包长度
133 | public int getMaxFrameLength(){
134 | return ProtocolDefine.FRAME.MAX_PACKAGE_LENGTH;
135 | }
136 |
137 | private static int byteToInt(byte b) {
138 | //Java 总是把 byte 当做有符处理;我们可以通过将其和 0xFF 进行二进制与得到它的无符值
139 | return b & 0xFF;
140 | }
141 |
142 | private static short getShort(byte byte1,byte byte2) {
143 | short sho= (short)(byte2 | (((short)byte1) << 8));
144 | return sho;
145 | }
146 |
147 | private static short getShort(int byte1,int byte2) {
148 | short sho= (short)(byte2 | (((short)byte1) << 8));
149 | return sho;
150 | }
151 |
152 | }
153 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/commlibrary/src/main/java/com/seeyou/comm/framework/utils/ConvertTypeUtils.java:
--------------------------------------------------------------------------------
1 | package com.seeyou.comm.framework.utils;
2 |
3 | /**
4 | * Create by seeyou
5 | * seeyou1052@foxmail.com
6 | */
7 | public class ConvertTypeUtils {
8 |
9 | /**
10 | * 将int数值转换为占四个字节的byte数组,本方法适用于(低位在前,高位在后)的顺序。
11 | * @param value
12 | * 要转换的int值
13 | * @return byte数组
14 | */
15 | public static byte[] intToBytesLitter(int value) {
16 | byte[] byte_src = new byte[4];
17 | byte_src[3] = (byte) ((value & 0xFF000000)>>24);
18 | byte_src[2] = (byte) ((value & 0x00FF0000)>>16);
19 | byte_src[1] = (byte) ((value & 0x0000FF00)>>8);
20 | byte_src[0] = (byte) ((value & 0x000000FF));
21 | return byte_src;
22 | }
23 |
24 | /**
25 | * 将int数值转换为占四个字节的byte数组,本方法适用于(低位在前,高位在后)的顺序。
26 | * @param value
27 | * 要转换的int值
28 | * @return byte数组
29 | */
30 | public static byte[] intToBytesLitters(int value,byte[] bytes,int offset) {
31 | bytes[3+offset] = (byte) ((value & 0xFF000000)>>24);
32 | bytes[2+offset] = (byte) ((value & 0x00FF0000)>>16);
33 | bytes[1+offset] = (byte) ((value & 0x0000FF00)>>8);
34 | bytes[0+offset] = (byte) ((value & 0x000000FF));
35 | return bytes;
36 | }
37 |
38 |
39 | /**
40 | * 将int数值转换为占四个字节的byte数组,本方法适用于(高位在前,低位在后)的顺序。
41 | * @param value
42 | * 要转换的int值
43 | * @return byte数组
44 | */
45 | public static byte[] intToBytesBigs(int value,byte[] bytes,int offset) {
46 | bytes[3+offset] = (byte) ((value & 0xFF000000)>>24);
47 | bytes[2+offset] = (byte) ((value & 0x00FF0000)>>16);
48 | bytes[1+offset] = (byte) ((value & 0x0000FF00)>>8);
49 | bytes[0+offset] = (byte) ((value & 0x000000FF));
50 | return bytes;
51 | }
52 |
53 | /**
54 | * 将int数值转换为占四个字节的byte数组,本方法适用于(高位在前,低位在后)的顺序。
55 | * @param value
56 | * 要转换的int值
57 | * @return byte数组
58 | */
59 | public static byte[] intToBytesBig(int value) {
60 | byte[] byte_src = new byte[4];
61 | byte_src[0] = (byte) ((value & 0xFF000000)>>24);
62 | byte_src[1] = (byte) ((value & 0x00FF0000)>>16);
63 | byte_src[2] = (byte) ((value & 0x0000FF00)>>8);
64 | byte_src[3] = (byte) ((value & 0x000000FF));
65 | return byte_src;
66 | }
67 |
68 | /**
69 | * 将int数值转换为占四个字节的byte数组,本方法适用于(高位在前,低位在后)的顺序。
70 | * @param value
71 | * 要转换的int值
72 | * @return byte数组
73 | */
74 | public static byte[] intToBytesBig(int value,byte[] bytes, int offset) {
75 | bytes[offset+0] = (byte) ((value & 0xFF000000)>>24);
76 | bytes[offset+1] = (byte) ((value & 0x00FF0000)>>16);
77 | bytes[offset+2] = (byte) ((value & 0x0000FF00)>>8);
78 | bytes[offset+3] = (byte) ((value & 0x000000FF));
79 | return bytes;
80 | }
81 |
82 | /**
83 | * byte数组中取int数值,本方法适用于(低位在前,高位在后)的顺序。
84 | *
85 | * @param ary
86 | * byte数组
87 | * @param offset
88 | * 从数组的第offset位开始
89 | * @return int数值
90 | */
91 | public static int bytesToIntLitter(byte[] ary, int offset) {
92 | int value;
93 | value = (int) ((ary[offset]&0xFF)
94 | | ((ary[offset+1]<<8) & 0xFF00)
95 | | ((ary[offset+2]<<16)& 0xFF0000)
96 | | ((ary[offset+3]<<24) & 0xFF000000));
97 | return value;
98 | }
99 |
100 | /**
101 | * byte数组中取int数值,本方法适用于(高位在前,低位在后)的顺序。
102 | *
103 | * @param ary
104 | * byte数组
105 | * @param offset
106 | * 从数组的第offset位开始
107 | * @return int数值
108 | */
109 | public static int bytesToIntBig(byte[] ary, int offset){
110 | int value;
111 | value = (int) ((ary[offset+3]&0xFF)
112 | | ((ary[offset+2]<<8) & 0xFF00)
113 | | ((ary[offset+1]<<16)& 0xFF0000)
114 | | ((ary[offset+0]<<24) & 0xFF000000));
115 | return value;
116 | }
117 |
118 | /**
119 | * @param ary
120 | * @param offset
121 | * @return
122 | */
123 | public static int bytesToIntBigPluse(byte[] ary, int offset) {
124 | int value;
125 | value = (int) ((ary[offset+2]&0xFF)
126 | | ((ary[offset+3]<<8) & 0xFF00)
127 | | ((ary[offset+0]<<16)& 0xFF0000)
128 | | ((ary[offset+1]<<24) & 0xFF000000));
129 | return value;
130 | }
131 |
132 | /**
133 | * @param ary
134 | * @param offset
135 | * @return 4个字节数组转long型
136 | */
137 | public static long bytesToLongLitter(byte[] ary, int offset) {
138 | long value;
139 | value = (long) ((ary[offset]&0x0FF)
140 | | ((ary[offset+1]<<8) & 0x0FF00)
141 | | ((ary[offset+2]<<16)& 0x0FF0000)
142 | | ((ary[offset+3]<<24) & 0x0FF000000));
143 | return value;
144 | }
145 |
146 | /**
147 | * @param ary
148 | * @param offset
149 | * @return 4个字节数组转long型
150 | */
151 | public static long bytesToLongBit(byte[] ary, int offset) {
152 | long value ;
153 | value = (long) ((ary[offset+3]&0x0FF)
154 | | ((ary[offset+2]<<8) & 0x0FF00)
155 | | ((ary[offset+1]<<16)& 0x0FF0000)
156 | | ((ary[offset+0]<<24) & 0x0FF000000));
157 | return value;
158 | }
159 |
160 |
161 | /**
162 | * @param
163 | * @return int
164 | */
165 | public static int byteArrayToInt(byte[] b) {
166 | byte[] a = new byte[4];
167 | int i = a.length - 1,j = b.length - 1;
168 | for (; i >= 0 ; i--,j--) {//从b的尾部(即int值的低位)开始copy数据
169 | if(j >= 0)
170 | a[i] = b[j];
171 | else
172 | a[i] = 0;//如果b.length不足4,则将高位补0
173 | }
174 | int v0 = (a[0] & 0xff) << 24;//&0xff将byte值无差异转成int,避免Java自动类型提升后,会保留高位的符号位
175 | int v1 = (a[1] & 0xff) << 16;
176 | int v2 = (a[2] & 0xff) << 8;
177 | int v3 = (a[3] & 0xff) ;
178 | return v0 + v1 + v2 + v3;
179 | }
180 |
181 |
182 | /**
183 | * @param ary
184 | * @param offset
185 | * @return byte数组转long类型
186 | */
187 | public static int bytesToIntLowerbyte(byte[] ary, int offset) {
188 | int value = 0;
189 | int s1 = ary[1+offset] & 0x0ff;// 最低位
190 | int s3 = ary[3+offset] & 0x0ff;
191 | int s5 = ary[5+offset] & 0x0ff;// 最低位
192 | int s7 = ary[7+offset] & 0x0ff;
193 |
194 | // s7不变
195 | s5 <<= 8 * 1;
196 | s3 <<= 8 * 2;
197 | s1 <<= 8 * 3;
198 | value = (s1 | s3 | s5 | s7) ;
199 | return value;
200 | }
201 |
202 | /**
203 | * 将short数值转换为占2个字节的byte数组,本方法适用于(低位在前,高位在后)的顺序。
204 | * @param value 要转换的short值
205 | * @return byte数组
206 | */
207 | public static byte[] shortToBytes(short value) {
208 | byte[] byte_src = new byte[2];
209 | byte_src[1] = (byte) ((value & 0xFF00)>>8);
210 | byte_src[0] = (byte) ((value & 0x00FF));
211 | return byte_src;
212 | }
213 |
214 | /**
215 | * 将short数值转换为占四个字节的byte数组,本方法适用于(高位在前,低位在后)的顺序。
216 | * @param value 要转换的short值
217 | * @return byte数组
218 | */
219 | public static byte[] shortToBytesBig(short value) {
220 | byte[] byte_src = new byte[2];
221 | byte_src[0] = (byte) ((value & 0xFF00)>>8);
222 | byte_src[1] = (byte) ((value & 0x00FF));
223 | return byte_src;
224 | }
225 |
226 | /**
227 | * 将short数值转换为占四个字节的byte数组,本方法适用于(高位在前,低位在后)的顺序。
228 | * @param value 要转换的short值
229 | * @return byte数组
230 | */
231 | public static byte[] shortToBytesBig(short value,byte[] bytes,int offset) {
232 | bytes[offset] = (byte) ((value & 0xFF00)>>8);
233 | bytes[offset+1] = (byte) ((value & 0x00FF));
234 | return bytes;
235 | }
236 |
237 | /**
238 | * 将short数值转换为占四个字节的byte数组,本方法适用于(低位在前,高位在后)的顺序。
239 | * @param value 要转换的short值
240 | * @return byte数组
241 | */
242 | public static byte[] shortToBytesLiter(short value,byte[] bytes,int offset) {
243 | bytes[offset] = (byte) ((value & 0x00FF));
244 | bytes[offset+1] = (byte) ((value & 0xFF00)>>8);
245 | return bytes;
246 | }
247 |
248 | /**
249 | * byte数组中取int数值,本方法适用于(低位在前,高位在后)的顺序。
250 | * 小端
251 | * @param ary
252 | * byte数组
253 | * @param offset
254 | * 从数组的第offset位开始
255 | * @return int数值
256 | */
257 | public static short bytesToShortLiterEnd(byte[] ary, int offset) {
258 | short value;
259 | value = (short) ((ary[offset]&0xFF)
260 | | ((ary[offset+1]<<8) & 0xFF00));
261 | return value;
262 | }
263 |
264 | /**
265 | * byte数组中取int数值,本方法适用于(低位在前,高位在后)的顺序。
266 | * 小端
267 | * @param ary
268 | * byte数组
269 | * @param offset
270 | * 从数组的第offset位开始
271 | * @return int数值
272 | */
273 | public static int doubleBytesToIntLiterEnd(byte[] ary, int offset) {
274 | int value;
275 | value = (int) ((ary[offset]&0xFF)
276 | | ((ary[offset+1]<<8) & 0xFF00)
277 | | 0x00000000 );
278 | return value;
279 | }
280 |
281 | /**
282 | * byte字节型转换为int型
283 | * 小端
284 | * @param ary
285 | * byte
286 | * @return int数值
287 | */
288 | public static int byteToInt(byte ary) {
289 | int value;
290 | value = (int) ( (ary & 0xFF)
291 | | 0x00000000 );
292 | return value;
293 | }
294 |
295 | /**
296 | * byte数组中取int数值,本方法适用于(高位在前,低位在后)的顺序。
297 | * 大端
298 | * @param ary
299 | * byte数组
300 | * @param offset
301 | * 从数组的第offset位开始
302 | * @return int数值
303 | */
304 | public static int bytesToShortBigEnd(byte[] ary, int offset) {
305 | int value;
306 | value = (short) ((ary[offset+1]&0x0FF)
307 | | ((ary[offset]<<8) & 0x0FF00));
308 | return value;
309 | }
310 |
311 | public static byte[] subBytes(byte[] src, int begin, int count) {
312 | byte[] bs = new byte[count];
313 | for (int i = begin; i < begin+count; i++) bs[i-begin] = src[i];
314 | return bs;
315 | }
316 |
317 | /**
318 | * @param b byte字节数
319 | * @explain 把byte转为字符串的bit
320 | */
321 | public static String byteToBit(byte b) {
322 | return ""
323 | + (byte) ((b >> 7) & 0x1) + (byte) ((b >> 6) & 0x1)
324 | + (byte) ((b >> 5) & 0x1) + (byte) ((b >> 4) & 0x1)
325 | + (byte) ((b >> 3) & 0x1) + (byte) ((b >> 2) & 0x1)
326 | + (byte) ((b >> 1) & 0x1) + (byte) ((b >> 0) & 0x1);
327 | }
328 |
329 | /**
330 | * @param data
331 | * @return 返回无符号byte型数据
332 | */
333 | public static byte getUnsignedByteFromInt (int data) {
334 | String strData = Integer.toHexString(data);
335 | byte bytedata = Integer.valueOf(strData, 16).byteValue();
336 | return bytedata;
337 | }
338 |
339 | /**
340 | * @param data
341 | * @return 返回无符号short型数据
342 | */
343 | public static short getUnsignedShortByteInt(int data) {
344 | String strData = Integer.toHexString(data);
345 | short shortData = Integer.valueOf(strData, 16).shortValue();
346 | return shortData;
347 | }
348 |
349 | /**
350 | * @param data
351 | * @return //将data字节型数据转换为0~255 (0xFF 即BYTE)。
352 | */
353 | public static int getUnsignedByteFromByte (byte data) {
354 | return data&0x0FF;
355 | }
356 |
357 | /**
358 | * @param data
359 | * @return //将data字节型数据转换为0~65535 (0xFFFF 即 WORD)。
360 | */
361 | public static int getUnsignedShort (short data) {
362 | return (data&0x0FFFF);
363 | }
364 |
365 | /**
366 | * @param data
367 | * @return 将int数据转换为0~4294967295 (0xFFFFFFFF即DWORD)。
368 | */
369 | public static long getUnsignedInteger (int data) {
370 | return (data&0x0FFFFFFFFl);
371 | }
372 |
373 | }
--------------------------------------------------------------------------------
/commlibrary/src/main/java/com/seeyou/comm/framework/utils/ByteConverter.java:
--------------------------------------------------------------------------------
1 | package com.seeyou.comm.framework.utils;
2 |
3 | /**
4 | * Created by seeyou
5 | */
6 |
7 | public class ByteConverter {
8 | /**
9 | * 将int数值转换为占四个字节的byte数组,本方法适用于(低位在前,高位在后)的顺序。
10 | *
11 | * @param value 要转换的int值
12 | * @return byte数组
13 | */
14 | public static byte[] intToBytesLitter(int value) {
15 | byte[] byte_src = new byte[4];
16 | byte_src[3] = (byte) ((value & 0xFF000000) >> 24);
17 | byte_src[2] = (byte) ((value & 0x00FF0000) >> 16);
18 | byte_src[1] = (byte) ((value & 0x0000FF00) >> 8);
19 | byte_src[0] = (byte) ((value & 0x000000FF));
20 | return byte_src;
21 | }
22 |
23 | /**
24 | * 将int数值转换为占四个字节的byte数组,本方法适用于(低位在前,高位在后)的顺序。
25 | *
26 | * @param value 要转换的int值
27 | * @return byte数组
28 | */
29 | public static byte[] intToBytesLitters(int value, byte[] bytes, int offset) {
30 | bytes[3 + offset] = (byte) ((value & 0xFF000000) >> 24);
31 | bytes[2 + offset] = (byte) ((value & 0x00FF0000) >> 16);
32 | bytes[1 + offset] = (byte) ((value & 0x0000FF00) >> 8);
33 | bytes[0 + offset] = (byte) ((value & 0x000000FF));
34 | return bytes;
35 | }
36 |
37 |
38 | /**
39 | * 将int数值转换为占四个字节的byte数组,本方法适用于(高位在前,低位在后)的顺序。
40 | *
41 | * @param value 要转换的int值
42 | * @return byte数组
43 | */
44 | public static byte[] intToBytesBigs(int value, byte[] bytes, int offset) {
45 | bytes[3 + offset] = (byte) ((value & 0xFF000000) >> 24);
46 | bytes[2 + offset] = (byte) ((value & 0x00FF0000) >> 16);
47 | bytes[1 + offset] = (byte) ((value & 0x0000FF00) >> 8);
48 | bytes[0 + offset] = (byte) ((value & 0x000000FF));
49 | return bytes;
50 | }
51 |
52 | /**
53 | * 将int数值转换为占四个字节的byte数组,本方法适用于(高位在前,低位在后)的顺序。
54 | *
55 | * @param value 要转换的int值
56 | * @return byte数组
57 | */
58 | public static byte[] intToBytesBig(int value) {
59 | byte[] byte_src = new byte[4];
60 | byte_src[0] = (byte) ((value & 0xFF000000) >> 24);
61 | byte_src[1] = (byte) ((value & 0x00FF0000) >> 16);
62 | byte_src[2] = (byte) ((value & 0x0000FF00) >> 8);
63 | byte_src[3] = (byte) ((value & 0x000000FF));
64 | return byte_src;
65 | }
66 |
67 | /**
68 | * 将int数值转换为占四个字节的byte数组,本方法适用于(高位在前,低位在后)的顺序。
69 | *
70 | * @param value 要转换的int值
71 | * @return byte数组
72 | */
73 | public static byte[] intToBytesBig(int value, byte[] bytes, int offset) {
74 | bytes[offset + 0] = (byte) ((value & 0xFF000000) >> 24);
75 | bytes[offset + 1] = (byte) ((value & 0x00FF0000) >> 16);
76 | bytes[offset + 2] = (byte) ((value & 0x0000FF00) >> 8);
77 | bytes[offset + 3] = (byte) ((value & 0x000000FF));
78 | return bytes;
79 | }
80 |
81 | /**
82 | * byte数组中取int数值,本方法适用于(低位在前,高位在后)的顺序。
83 | *
84 | * @param ary byte数组
85 | * @param offset 从数组的第offset位开始
86 | * @return int数值
87 | */
88 | public static int bytesToIntLitter(byte[] ary, int offset) {
89 | int value;
90 | value = (int) ((ary[offset] & 0xFF)
91 | | ((ary[offset + 1] << 8) & 0xFF00)
92 | | ((ary[offset + 2] << 16) & 0xFF0000)
93 | | ((ary[offset + 3] << 24) & 0xFF000000));
94 | return value;
95 | }
96 |
97 | /**
98 | * byte数组中取int数值,本方法适用于(高位在前,低位在后)的顺序。
99 | *
100 | * @param ary byte数组
101 | * @param offset 从数组的第offset位开始
102 | * @return int数值
103 | */
104 | public static int bytesToIntBig(byte[] ary, int offset) {
105 | int value;
106 | value = (int) ((ary[offset + 3] & 0xFF)
107 | | ((ary[offset + 2] << 8) & 0xFF00)
108 | | ((ary[offset + 1] << 16) & 0xFF0000)
109 | | ((ary[offset + 0] << 24) & 0xFF000000));
110 | return value;
111 | }
112 |
113 | /**
114 | * @param ary
115 | * @param offset
116 | * @return
117 | */
118 | public static int bytesToIntBigPluse(byte[] ary, int offset) {
119 | int value;
120 | value = (int) ((ary[offset + 2] & 0xFF)
121 | | ((ary[offset + 3] << 8) & 0xFF00)
122 | | ((ary[offset + 0] << 16) & 0xFF0000)
123 | | ((ary[offset + 1] << 24) & 0xFF000000));
124 | return value;
125 | }
126 |
127 | /**
128 | * @param ary
129 | * @param offset
130 | * @return 4个字节数组转long型
131 | */
132 | public static long bytesToLongLitter(byte[] ary, int offset) {
133 | long value;
134 | value = (long) ((ary[offset] & 0x0FF)
135 | | ((ary[offset + 1] << 8) & 0x0FF00)
136 | | ((ary[offset + 2] << 16) & 0x0FF0000)
137 | | ((ary[offset + 3] << 24) & 0x0FF000000));
138 | return value;
139 | }
140 |
141 | /**
142 | * @param ary
143 | * @param offset
144 | * @return 4个字节数组转long型
145 | */
146 | public static long bytesToLongBit(byte[] ary, int offset) {
147 | long value;
148 | value = (long) ((ary[offset + 3] & 0x0FF)
149 | | ((ary[offset + 2] << 8) & 0x0FF00)
150 | | ((ary[offset + 1] << 16) & 0x0FF0000)
151 | | ((ary[offset + 0] << 24) & 0x0FF000000));
152 | return value;
153 | }
154 |
155 |
156 | /**
157 | * @param b
158 | * @return int
159 | */
160 | public static int byteArrayToInt(byte[] b) {
161 | byte[] a = new byte[4];
162 | int i = a.length - 1, j = b.length - 1;
163 | for (; i >= 0; i--, j--) {//从b的尾部(即int值的低位)开始copy数据
164 | if (j >= 0)
165 | a[i] = b[j];
166 | else
167 | a[i] = 0;//如果b.length不足4,则将高位补0
168 | }
169 | int v0 = (a[0] & 0xff) << 24;//&0xff将byte值无差异转成int,避免Java自动类型提升后,会保留高位的符号位
170 | int v1 = (a[1] & 0xff) << 16;
171 | int v2 = (a[2] & 0xff) << 8;
172 | int v3 = (a[3] & 0xff);
173 | return v0 + v1 + v2 + v3;
174 | }
175 |
176 |
177 | /**
178 | * @param ary
179 | * @param offset
180 | * @return byte数组转long类型
181 | */
182 | public static int bytesToIntLowerbyte(byte[] ary, int offset) {
183 | int value = 0;
184 | int s1 = ary[1 + offset] & 0x0ff;// 最低位
185 | int s3 = ary[3 + offset] & 0x0ff;
186 | int s5 = ary[5 + offset] & 0x0ff;// 最低位
187 | int s7 = ary[7 + offset] & 0x0ff;
188 |
189 | // s7不变
190 | s5 <<= 8 * 1;
191 | s3 <<= 8 * 2;
192 | s1 <<= 8 * 3;
193 | value = (s1 | s3 | s5 | s7);
194 | return value;
195 | }
196 |
197 | /**
198 | * 将short数值转换为占2个字节的byte数组,本方法适用于(低位在前,高位在后)的顺序。
199 | *
200 | * @param value 要转换的short值
201 | * @return byte数组
202 | */
203 | public static byte[] shortToBytes(short value) {
204 | byte[] byte_src = new byte[2];
205 | byte_src[1] = (byte) ((value & 0xFF00) >> 8);
206 | byte_src[0] = (byte) ((value & 0x00FF));
207 | return byte_src;
208 | }
209 |
210 | /**
211 | * 将short数值转换为占四个字节的byte数组,本方法适用于(高位在前,低位在后)的顺序。
212 | *
213 | * @param value 要转换的short值
214 | * @return byte数组
215 | */
216 | public static byte[] shortToBytesBig(short value) {
217 | byte[] byte_src = new byte[2];
218 | byte_src[0] = (byte) ((value & 0xFF00) >> 8);
219 | byte_src[1] = (byte) ((value & 0x00FF));
220 | return byte_src;
221 | }
222 |
223 | /**
224 | * 将short数值转换为占四个字节的byte数组,本方法适用于(高位在前,低位在后)的顺序。
225 | *
226 | * @param value 要转换的short值
227 | * @return byte数组
228 | */
229 | public static byte[] shortToBytesBig(short value, byte[] bytes, int offset) {
230 | bytes[offset] = (byte) ((value & 0xFF00) >> 8);
231 | bytes[offset + 1] = (byte) ((value & 0x00FF));
232 | return bytes;
233 | }
234 |
235 | /**
236 | * 将short数值转换为占四个字节的byte数组,本方法适用于(低位在前,高位在后)的顺序。
237 | *
238 | * @param value 要转换的short值
239 | * @return byte数组
240 | */
241 | public static byte[] shortToBytesLiter(short value, byte[] bytes, int offset) {
242 | bytes[offset] = (byte) ((value & 0x00FF));
243 | bytes[offset + 1] = (byte) ((value & 0xFF00) >> 8);
244 | return bytes;
245 | }
246 |
247 | /**
248 | * byte数组中取int数值,本方法适用于(低位在前,高位在后)的顺序。
249 | * 小端
250 | *
251 | * @param ary byte数组
252 | * @param offset 从数组的第offset位开始
253 | * @return int数值
254 | */
255 | public static short bytesToShortLiterEnd(byte[] ary, int offset) {
256 | short value;
257 | value = (short) ((ary[offset] & 0xFF)
258 | | ((ary[offset + 1] << 8) & 0xFF00));
259 | return value;
260 | }
261 |
262 | /**
263 | * byte数组中取int数值,本方法适用于(低位在前,高位在后)的顺序。
264 | * 小端
265 | *
266 | * @param ary byte数组
267 | * @param offset 从数组的第offset位开始
268 | * @return int数值
269 | */
270 | public static int doubleBytesToIntLiterEnd(byte[] ary, int offset) {
271 | int value;
272 | value = (int) ((ary[offset] & 0xFF)
273 | | ((ary[offset + 1] << 8) & 0xFF00)
274 | | 0x00000000);
275 | return value;
276 | }
277 |
278 | /**
279 | * byte字节型转换为int型
280 | * 小端
281 | *
282 | * @param ary byte
283 | * @return int数值
284 | */
285 | public static int byteToInt(byte ary) {
286 | int value;
287 | value = (int) ((ary & 0xFF)
288 | | 0x00000000);
289 | return value;
290 | }
291 |
292 | /**
293 | * byte数组中取int数值,本方法适用于(高位在前,低位在后)的顺序。
294 | * 大端
295 | *
296 | * @param ary byte数组
297 | * @param offset 从数组的第offset位开始
298 | * @return int数值
299 | */
300 | public static int bytesToShortBigEnd(byte[] ary, int offset) {
301 | int value;
302 | value = (short) ((ary[offset + 1] & 0x0FF)
303 | | ((ary[offset] << 8) & 0x0FF00));
304 | return value;
305 | }
306 |
307 | public static byte[] subBytes(byte[] src, int begin, int count) {
308 | byte[] bs = new byte[count];
309 | for (int i = begin; i < begin + count; i++) bs[i - begin] = src[i];
310 | return bs;
311 | }
312 |
313 | /**
314 | * @param b byte字节数
315 | * @explain 把byte转为字符串的bit
316 | */
317 | public static String byteToBit(byte b) {
318 | return ""
319 | + (byte) ((b >> 7) & 0x1) + (byte) ((b >> 6) & 0x1)
320 | + (byte) ((b >> 5) & 0x1) + (byte) ((b >> 4) & 0x1)
321 | + (byte) ((b >> 3) & 0x1) + (byte) ((b >> 2) & 0x1)
322 | + (byte) ((b >> 1) & 0x1) + (byte) ((b >> 0) & 0x1);
323 | }
324 |
325 | /**
326 | * @param data
327 | * @return 返回无符号byte型数据
328 | */
329 | public static byte getUnsignedByteFromInt(int data) {
330 | String strData = Integer.toHexString(data);
331 | byte bytedata = Integer.valueOf(strData, 16).byteValue();
332 | return bytedata;
333 | }
334 |
335 | /**
336 | * @param data
337 | * @return 返回无符号short型数据
338 | */
339 | public static short getUnsignedShortByteInt(int data) {
340 | String strData = Integer.toHexString(data);
341 | short shortData = Integer.valueOf(strData, 16).shortValue();
342 | return shortData;
343 | }
344 |
345 | /**
346 | * @param data
347 | * @return //将data字节型数据转换为0~255 (0xFF 即BYTE)。
348 | */
349 | public static int getUnsignedByteFromByte(byte data) {
350 | return data & 0x0FF;
351 | }
352 |
353 | /**
354 | * @param data
355 | * @return //将data字节型数据转换为0~65535 (0xFFFF 即 WORD)。
356 | */
357 | public static int getUnsignedShort(short data) {
358 | return (data & 0x0FFFF);
359 | }
360 |
361 | /**
362 | * @param data
363 | * @return 将int数据转换为0~4294967295 (0xFFFFFFFF即DWORD)。
364 | */
365 | public static long getUnsignedInteger(int data) {
366 | return (data & 0x0FFFFFFFFl);
367 | }
368 |
369 | }
370 |
--------------------------------------------------------------------------------