当前位置:   article > 正文

第二章:调用api发送和接收_设备是否发出或接收 api 调用?

设备是否发出或接收 api 调用?

在这里插入图片描述

  • 操作类

import cn.yumakeji.lib_serialportapi.SerialPort;
import cn.yumakeji.lib_serialportapi.callback.SerialCallBack;
import cn.yumakeji.lib_serialportapi.utils.ByteUtil;
import cn.yumakeji.lib_serialportapi.utils.LogUtil;

/**
 * 数据操作封装
 */
public class SerialPortUtil {

    public static String TAG = "serial_port";
    /**
     * 标记当前串口状态(true:打开,false:关闭)
     **/
    public boolean isFlagSerial = false;

    public SerialPort serialPort = null;
    public InputStream inputStream = null;
    public OutputStream outputStream = null;
    public Thread receiveThread = null;

    private SerialPortUtil() {
    }

    public static SerialPortUtil getInstance() {
        return SingletonHolder.sInstance;
    }

    //静态内部类
    private static class SingletonHolder {
        private static final SerialPortUtil sInstance = new SerialPortUtil();
    }

    /**
     * 打开串口
     * <p>
     * 串口有五个重要的参数:串口设备名,波特率,检验位,数据位,停止位
     * 其中检验位一般默认位NONE,数据位一般默认为8,停止位默认为1
     *
     * @param device   串口设备的绝对路径
     * @param baudrate 波特率
     * @param flags    校验位
     * @return
     */
    public boolean open(File device, int baudrate, int flags) {
        boolean isopen = false;
        if (isFlagSerial) {
            LogUtil.e(TAG, "串口已经打开,打开失败");
            return false;
        }
        try {
            serialPort = new SerialPort(device, baudrate, flags);
            inputStream = serialPort.getInputStream();
            outputStream = serialPort.getOutputStream();
            receive();
            isopen = true;
            isFlagSerial = true;
        } catch (Exception e) {
            e.printStackTrace();
            isopen = false;
        }
        return isopen;
    }

    /**
     * 打开串口
     *
     * @param device   串口设备文件
     * @param baudRate 波特率
     * @param parity   奇偶校验,0 None(默认); 1 Odd; 2 Even
     * @param dataBits 数据位,5 ~ 8  (默认8)
     * @param stopBit  停止位,1 或 2  (默认 1)
     * @param flags    标记 0(默认)
     * @return
     */
    public boolean open(File device, int baudRate, int parity, int dataBits,
                        int stopBit, int flags) {
        boolean isopen = false;
        if (isFlagSerial) {
            LogUtil.e(TAG, "串口已经打开,打开失败");
            return false;
        }
        try {
            serialPort = new SerialPort(device, baudRate, parity, dataBits, stopBit, flags);
            inputStream = serialPort.getInputStream();
            outputStream = serialPort.getOutputStream();
            receive();
            isopen = true;
            isFlagSerial = true;
        } catch (Exception e) {
            e.printStackTrace();
            isopen = false;
        }
        return isopen;
    }

    /**
     * 关闭串口
     */
    public boolean close() {
        if (!isFlagSerial) {
            LogUtil.e(TAG, "串口关闭失败");
            return false;
        }
        boolean isClose = false;
        LogUtil.e(TAG, "关闭串口");
        try {
            if (inputStream != null) {
                inputStream.close();
            }
            if (outputStream != null) {
                outputStream.close();
            }
            if (serialPort != null) {
                serialPort.close();
            }
            isClose = true;
            isFlagSerial = false;//关闭串口时,连接状态标记为false
        } catch (IOException e) {
            e.printStackTrace();
            isClose = false;
        }
        return isClose;
    }

    /**
     * 发送16进制,串口指令
     */
    public void sendHexString(String data) {
        if (!isFlagSerial) {
            LogUtil.e(TAG, "串口未打开,发送失败" + data);
            return;
        }
        try {
            outputStream.write(ByteUtil.hex2byte(data));
            outputStream.flush();
            LogUtil.e(TAG, "sendSerialData:" + data);
        } catch (IOException e) {
            e.printStackTrace();
            LogUtil.e(TAG, "发送指令出现异常");
        }
    }

    /**
     * 发送ASCII,串口指令
     */
    public void sendAsciiString(String data) {
        if (!isFlagSerial) {
            LogUtil.e(TAG, "串口未打开,发送失败" + data);
            return;
        }
        try {
            outputStream.write(data.getBytes("gbk"));
            outputStream.flush();
            LogUtil.e(TAG, "sendSerialData:" + data);
        } catch (IOException e) {
            e.printStackTrace();
            LogUtil.e(TAG, "发送指令出现异常");
        }
    }

    /**
     * 接收串口数据的方法
     */
    public void receive() {
        if (receiveThread != null && !isFlagSerial) {
            return;
        }
        receiveThread = new Thread() {
            @Override
            public void run() {
                while (isFlagSerial) {
                    try {
                        byte[] readData = new byte[256];
                        if (inputStream == null) {
                            return;
                        }
                        int size = inputStream.read(readData);
                        if (size > 0 && isFlagSerial) {
//                            strData = ByteUtil.byteToStr(readData, size);
                            if (onDataReceiveListener != null) {
                                onDataReceiveListener.onSerialPortData(readData, size);
                            }
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        receiveThread.start();
    }

    private SerialCallBack onDataReceiveListener;

    public void setOnDataReceiveListener(SerialCallBack onDataReceiveListener) {
        this.onDataReceiveListener = onDataReceiveListener;
    }

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172
  • 173
  • 174
  • 175
  • 176
  • 177
  • 178
  • 179
  • 180
  • 181
  • 182
  • 183
  • 184
  • 185
  • 186
  • 187
  • 188
  • 189
  • 190
  • 191
  • 192
  • 193
  • 194
  • 195
  • 196
  • 197
  • 198
  • 199
  • 200
  • 201
  • 具体调用如下:

public class MainActivity extends AppCompatActivity implements SerialCallBack {

    private static final int REQUESE_CODE = 0xFFA;
    private CheckBox mCbHex;
    private CheckBox mCbAscii;

    @Override
    public void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        SerialPortUtil.getInstance().close();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        HxgPermissionHelper.requestPermissionsResult(this, requestCode, permissions);
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mCbHex = findViewById(R.id.cb_hex);
        mCbAscii = findViewById(R.id.cb_ascii);
        mCbHex.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    mCbAscii.setChecked(false);
                } else {
                    mCbAscii.setChecked(true);
                }
            }
        });
        mCbAscii.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    mCbHex.setChecked(false);
                } else {
                    mCbHex.setChecked(true);
                }
            }
        });
    }

    @Override
    public void onAttachedToWindow() {
        super.onAttachedToWindow();
        HxgPermissionHelper.with(this)
                .requestCode(REQUESE_CODE)
                .requestPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_EXTERNAL_STORAGE)
                .request();
        SerialPortUtil.getInstance().setOnDataReceiveListener(this);
    }

    @HxgPermissionSuccess(requestCode = REQUESE_CODE)
    private void success() {
        Toast.makeText(this, "权限获取成功", Toast.LENGTH_SHORT).show();
        LogUtil.d(AppUtils.isRooted() + "");
    }

    @HxgPermissionFail(requestCode = REQUESE_CODE)
    private void fail() {
        Toast.makeText(this, "权限获取失败", Toast.LENGTH_SHORT).show();
    }

    /**
     * 打开串口
     *
     * @param view
     */
    public void onOpenClick(View view) {
        boolean open = SerialPortUtil.getInstance().open(new File("/dev/ttyS0"), 38400, 0);
        if (open) {
            LogUtil.d("串口已经打开");
        } else {
            LogUtil.d("串口打开失败");
        }
    }

    /**
     * 发送数据
     *
     * @param view
     */
    public void onSendClick(View view) {
        String trim = ((EditText) findViewById(R.id.et_input)).getText().toString().trim();
        if (TextUtils.isEmpty(trim)) {
            Toast.makeText(AppGlobals.getApplication().getApplicationContext(), "请输入发送内容", Toast.LENGTH_LONG).show();
            return;
        }
        if (!mCbHex.isChecked() && !mCbAscii.isChecked()) {
            Toast.makeText(AppGlobals.getApplication().getApplicationContext(), "请选择数据类型", Toast.LENGTH_LONG).show();
            return;
        }
        if (mCbHex.isChecked()) {
            SerialPortUtil.getInstance().sendHexString(trim);
        }
        if (mCbAscii.isChecked()) {
            SerialPortUtil.getInstance().sendAsciiString(trim);
        }
    }

    /**
     * 关闭串口
     *
     * @param view
     */
    public void onCloseClick(View view) {
        boolean close = SerialPortUtil.getInstance().close();
        if (close) {
            LogUtil.d("串口已经关闭");
        }
    }

    /**
     * 获取串口数据
     *
     * @param view
     */
    public void onInfoClick(View view) {
        SerialPortFinder spf = new SerialPortFinder();
        if (spf.getAllDevices() != null && spf.getAllDevices().length > 0) {
            LogUtil.e(String.valueOf(Arrays.asList(spf.getAllDevicesPath())));
        }
        if (spf.getAllDevicesPath() != null && spf.getAllDevicesPath().length > 0) {
            LogUtil.e(String.valueOf(Arrays.asList(spf.getAllDevicesPath())));
        }
    }

    /**
     * 接收数据
     *
     * @param buffer
     * @param size
     */
    @Override
    public void onSerialPortData(final byte[] buffer, final int size) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (mCbHex.isChecked()) {
                    LogUtil.d(ByteUtil.byteToStr(buffer, size));
                    ((TextView) findViewById(R.id.tv_read_message)).setText(ByteUtil.byteToStr(buffer, size));
                }
                if (mCbAscii.isChecked()) {
                    try {
                        LogUtil.d(new String(buffer, 0, size,"gbk"));
//                        ((TextView) findViewById(R.id.tv_read_message)).setText(new String(buffer, 0, size));
                        ((TextView) findViewById(R.id.tv_read_message)).setText(new String(buffer, 0, size,"gbk"));
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                }

            }
        });

    }

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 权限
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_SUPERUSER"/>
  • 1
  • 2
  • 3

demo地址:https://gitee.com/huangxiaoguo/chuankouxuexi

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/从前慢现在也慢/article/detail/326592
推荐阅读
相关标签
  

闽ICP备14008679号