Browse Source

优化串口模块

王育民 6 years ago
parent
commit
2e7478639f

+ 4 - 3
app/build.gradle

@@ -44,9 +44,10 @@ android {
 dependencies {
     implementation fileTree(dir: 'libs', include: ['*.jar'])
     implementation 'com.android.support:appcompat-v7:28.0.0'
-    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
-    testImplementation 'junit:junit:4.12'
+    implementation 'com.android.support.constraint:constraint-layout:2.0.0-beta2'
+    testImplementation 'junit:junit:4.13-beta-3'
     androidTestImplementation 'com.android.support.test:runner:1.0.2'
     androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
-    implementation(name: 'serialport-release', ext: 'aar')
+    // implementation(name: 'serialport-release', ext: 'aar')
+    implementation project(path: ':serialport')
 }

+ 23 - 62
app/src/main/java/cn/minbb/serial/activities/MainActivity.java

@@ -9,6 +9,7 @@ import android.widget.TextView;
 import android.widget.Toast;
 
 import java.io.File;
+import java.nio.charset.Charset;
 
 import cn.minbb.serial.R;
 import cn.minbb.serialport.SerialPortManager;
@@ -23,7 +24,6 @@ public class MainActivity extends AppCompatActivity {
     private EditText editText;
     private TextView textView;
     private SerialPortManager serialPortManager;
-    private static String data;
 
     @Override
     protected void onCreate(Bundle savedInstanceState) {
@@ -36,25 +36,6 @@ public class MainActivity extends AppCompatActivity {
         editText = findViewById(R.id.edit_text);
         textView = findViewById(R.id.text_view);
 
-//        serialPortUtil = new SerialPortUtil(getApplicationContext());
-//        serialPortUtil.setOnDataReceiveListener(new SerialPortUtil.OnDataReceiveListener() {
-//            @Override
-//            public void onDataReceive(final String data, final int size) {
-//                runOnUiThread(new Runnable() {
-//                    @Override
-//                    public void run() {
-//                        setText(data, size);
-//                        try {
-//                            serialPortUtil.sendSerialPort(data.getBytes(Charset.forName("UTF-8")));
-//                        } catch (IOException e) {
-//                            e.printStackTrace();
-//                            Toast.makeText(getApplicationContext(), "发送失败 = " + e.getMessage(), Toast.LENGTH_SHORT).show();
-//                        }
-//                    }
-//                });
-//            }
-//        });
-
         serialPortManager = new SerialPortManager();
         serialPortManager.setOnOpenSerialPortListener(new OnOpenSerialPortListener() {
             @Override
@@ -70,20 +51,18 @@ public class MainActivity extends AppCompatActivity {
         serialPortManager.setOnSerialPortDataListener(new OnSerialPortDataListener() {
             @Override
             public void onDataReceived(byte[] bytes, String data) {
-                MainActivity.data = data;
-                runOnUiThread(new Runnable() {
-                    @Override
-                    public void run() {
-                        byte[] bytes = ByteUtil.addBytes(MainActivity.data.getBytes(), new byte[64]);
-//                        for (int i = bytes.length; i < 64; i++) {
-//                            bytes[i] = 0x0;
-//                        }
-                        setText(MainActivity.data, MainActivity.data.length());
-                        if (serialPortManager.sendBytes(bytes)) {
-                            Toast.makeText(getApplicationContext(), "发送成功 = " + MainActivity.data, Toast.LENGTH_SHORT).show();
+                runOnUiThread(() -> {
+                    byte[] bytes1 = ByteUtil.addBytes(data.getBytes(), new byte[64]);
+                    setText(data, data.length());
+                    try {
+                        if (serialPortManager.sendBytes(bytes1)) {
+                            Toast.makeText(getApplicationContext(), "发送成功 = " + data, Toast.LENGTH_SHORT).show();
                         } else {
                             Toast.makeText(getApplicationContext(), "发送失败", Toast.LENGTH_SHORT).show();
                         }
+                    } catch (Exception e) {
+                        e.printStackTrace();
+                        Toast.makeText(getApplicationContext(), "发送失败 " + e.getMessage(), Toast.LENGTH_SHORT).show();
                     }
                 });
             }
@@ -102,15 +81,7 @@ public class MainActivity extends AppCompatActivity {
     public void onClick(View view) {
         switch (view.getId()) {
             case R.id.open_serial_port:
-//                if (serialPortUtil.serialPortStatus) {
-//                    Toast.makeText(getApplicationContext(), "串口已经打开", Toast.LENGTH_SHORT).show();
-//                } else {
-//                    if (null != serialPortUtil.openSerialPort()) {
-//                        openSerial.setEnabled(false);
-//                        closeSerial.setEnabled(true);
-//                    }
-//                }
-                if (serialPortManager.openSerialPort(new File("/dev/ttyS1"), 115200)) {
+                if (serialPortManager.openSerialPort()) {
                     Toast.makeText(getApplicationContext(), "串口打开成功", Toast.LENGTH_SHORT).show();
                     openSerial.setEnabled(false);
                     closeSerial.setEnabled(true);
@@ -119,12 +90,7 @@ public class MainActivity extends AppCompatActivity {
                 }
                 break;
             case R.id.close_serial_port:
-//                if (serialPortUtil.serialPortStatus) {
-//                    serialPortUtil.closeSerialPort();
-//                    openSerial.setEnabled(true);
-//                    closeSerial.setEnabled(false);
-//                }
-//                Toast.makeText(getApplicationContext(), "串口已关闭", Toast.LENGTH_SHORT).show();
+                Toast.makeText(getApplicationContext(), "串口已关闭", Toast.LENGTH_SHORT).show();
                 serialPortManager.closeSerialPort();
                 openSerial.setEnabled(true);
                 closeSerial.setEnabled(false);
@@ -132,23 +98,18 @@ public class MainActivity extends AppCompatActivity {
             case R.id.send:
                 // byte[] reportID = {0x0};
                 // byte[] data = ByteUtil.addBytes(reportID, editText.getText().toString().getBytes());
-                boolean sendBytes = serialPortManager.sendBytes(editText.getText().toString().getBytes());
-                if (sendBytes) {
-                    Toast.makeText(getApplicationContext(), "发送成功", Toast.LENGTH_SHORT).show();
-                } else {
-                    Toast.makeText(getApplicationContext(), "发送失败", Toast.LENGTH_SHORT).show();
+                boolean sendBytes = false;
+                try {
+                    sendBytes = serialPortManager.sendBytes(editText.getText().toString().getBytes(Charset.forName("UTF-8")));
+                    if (sendBytes) {
+                        Toast.makeText(getApplicationContext(), "数据发送成功", Toast.LENGTH_SHORT).show();
+                    } else {
+                        Toast.makeText(getApplicationContext(), "数据发送失败", Toast.LENGTH_SHORT).show();
+                    }
+                } catch (Exception e) {
+                    e.printStackTrace();
+                    Toast.makeText(getApplicationContext(), "数据发送失败 " + e.getMessage(), Toast.LENGTH_SHORT).show();
                 }
-//                if (serialPortUtil.serialPortStatus) {
-//                    try {
-//                        serialPortUtil.sendSerialPort(editText.getText().toString());
-//                    } catch (IOException e) {
-//                        e.printStackTrace();
-//                        Log.e(TAG, "sendSerialPort: 串口数据发送失败:" + e.toString());
-//                        Toast.makeText(getApplicationContext(), "数据发送失败:" + e.toString(), Toast.LENGTH_SHORT).show();
-//                    }
-//                } else {
-//                    Toast.makeText(getApplicationContext(), "请先打开串口", Toast.LENGTH_SHORT).show();
-//                }
                 break;
             case R.id.clearSend:
                 editText.setText("");

+ 2 - 2
serialport/build.gradle

@@ -36,10 +36,10 @@ dependencies {
     implementation fileTree(dir: 'libs', include: ['*.jar'])
 
     implementation 'com.android.support:appcompat-v7:28.0.0'
-    testImplementation 'junit:junit:4.12'
+    testImplementation 'junit:junit:4.13-beta-3'
     androidTestImplementation 'com.android.support.test:runner:1.0.2'
     androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
-    androidTestImplementation('com.android.support.test.espresso:espresso-core:2.2.2', {
+    androidTestImplementation('com.android.support.test.espresso:espresso-core:3.0.2', {
         exclude group: 'com.android.support', module: 'support-annotations'
     })
 }

+ 9 - 5
serialport/src/main/java/cn/minbb/serialport/SerialPortManager.java

@@ -35,12 +35,15 @@ public class SerialPortManager extends SerialPort {
 
     /**
      * 打开串口
+     * <p>
+     * 串口设备
+     * 波特率
      *
-     * @param device   串口设备
-     * @param baudRate 波特率
      * @return 打开是否成功
      */
-    public boolean openSerialPort(File device, int baudRate) {
+    public boolean openSerialPort() {
+        File device = new File("/dev/ttyS1");
+        int baudRate = 115200;
         Log.i(TAG, "openSerialPort: " + String.format("打开串口 %s  波特率 %s", device.getPath(), baudRate));
         // 校验串口权限
         if (!device.canRead() || !device.canWrite()) {
@@ -237,14 +240,15 @@ public class SerialPortManager extends SerialPort {
      * @param sendBytes 发送数据
      * @return 发送是否成功
      */
-    public boolean sendBytes(byte[] sendBytes) {
+    public boolean sendBytes(byte[] sendBytes) throws Exception {
         if (null != mFd && null != mFileInputStream && null != mFileOutputStream) {
             if (null != mSendingHandler) {
                 Message message = Message.obtain();
                 message.obj = sendBytes;
                 return mSendingHandler.sendMessage(message);
             }
+            throw new RuntimeException("缺失发送处理器");
         }
-        return false;
+        throw new RuntimeException("数据流为空");
     }
 }