Reading time: 10 minutes
Original address: juejin.cn/post/684490…
Original author: YKamh
Technical preparation: Java basics
Nowadays, our life is filled with all kinds of smart devices, which make our life convenient. This is the era of the Internet of Things. Android serial programming is a must-have skill if we’re going to develop smart devices.
Before getting involved in Android development, I thought Android development was all about writing mobile apps. With more and more projects, GRADUALLY began to contact the Android application combined with control hardware equipment project, application control lock, printer, scanner and so on, which is to use the knowledge of Android serial programming.
STEP1
Google’s Open source serialPort API is used in Android serial programming
Download link:
Github.com/cepr/androi…
After downloading the required resources on GitHub, you can place them in the directory structure shown below
The SerialPort class package name must be Android_serialport_API. If you want to change this package name, you need to regenerate the corresponding so library.
The open() and close() methods in the serialport.java file are red but we don’t have to worry about them.
STEP2
Add the following sentence under the buildTypes node in the project gradle file
STEP3
Write package serial port tools, mainly divided into the following steps to open the serial port:
-
Set the port number and baud rate
-
To obtain the input and output streams of the open serial port for sending and receiving serial port data
-
Open the thread reading serial port information (receiving serial port information is often time-consuming operation, so open the thread to wait)
-
Bind serial port return listener
-
Path: port number, be sure to write in this format, depending on the hardware might use /dev/ttys2, /dev/ttys1, etc.
-
Baudrate: indicates the baudrate
-
SerialPortStatus: indicates the serialPortStatus
-
Data_ : sent serial port data
-
ThreadStatus: terminates the thread flag (Volatile is more appropriate)
-
MSerialPort: API provided by Google
-
MInputStream: serial port input stream
-
MOutputStream: serial port output stream
/** ** Open the serial port * @returnSerialPort serialPort object */ public serialPortopenSerialPort()
{
try {
mSerialPort = new SerialPort(new File(path), baudrate, 0);
this.serialPortStatus = true;
threadStatus = false; / / access to open the serial port of the input and output flow, so that the serial data transceiver mInputStream = mSerialPort. GetInputStream (); mOutputStream = mSerialPort.getOutputStream(); new ReadThread().start(); } catch (IOException e){log.e (TAG,"OpenSerialPort: Abnormal opening of the serial port:" + e.toString());
return mSerialPort;
}
Log.d(TAG, "OpenSerialPort: openSerialPort");
return mSerialPort;
}
Copy the code
The open serial port method mainly completes the use of Google API construction method to pass in the port number and baud rate, get the input and output stream, open the listener thread.
/** ** Disable the serial port */ public voidcloseSerialPort()
{
try {
if(mInputStream ! = null) { mInputStream.close(); }if(mOutputStream ! = null) { mOutputStream.close(); } this.threadStatus =true;
this.serialPortStatus = false;
mSerialPort.close();
} catch (IOException e){
Log.e(TAG, "CloseSerialPort: Failed to close the serial port" + e.toString());
return;
}
Log.d(TAG, "CloseSerialPort: Serial port closed successfully");
}
Copy the code
Close the serial port method is mainly completed to close the input and output stream, call Google API to close the serial port method and use the flag bit method to safely close the listener thread.
public void sendSerialPort(String data)
{
Log.d(TAG, "SendSerialPort: Send data" + data);
try {
byte[]
sendData = data.getBytes("gb2312");
this.data_ = new String(sendData);
if (sendData.length > 0) {
mOutputStream.write(sendData);
mOutputStream.write('\n');
mOutputStream.flush();
Log.d(TAG, "SendSerialPort: Sending serial port data succeeded");
}
} catch (IOException e)
{
Log.e(TAG, "SendSerialPort: Serial port failed to send data"+ e.toString()); }}Copy the code
Send method, this method is only for the printer operation instance to achieve, in the red box we want to send the string into gb2312 byte array sent out.
In serial communication, all instructions are sent as byte arrays. You can improve on the author’s simple utility class to make it more generic.
class ReadThread extends Thread {
@Override
public void run() { super.run(); // Determine if the thread is safe to proceed, and terminate the thread safelywhile(! threadStatus){ Log.d(TAG,"Enter thread run");
byte[] buffer = new byte[64];
int size;
try {
size = mInputStream.read(buffer);
if (size > 0) {
Log.d(TAG, "Run: Received data size:" + size);
onDataReceiveListener.onDataReceive(buffer, size);
}
} catch (IOException e){
Log.e(TAG, "Run: Data read exception"+ e.toString()); }}}}Copy the code
In the try block, the inputStream.read () method is a blocking operation that can be used to close the thread quickly, depending on the project’s needs, without having to wait for the next loop with a flag bit.
The try block also calls methods on the onDataReceive() custom interface to return data that the thread is listening to.
public OnDataReceiveListener onDataReceiveListener = null;
public static interface OnDataReceiveListener
{
void onDataReceive(byte[] buffer, int size);
}
public void setOnDataReceiveListener(OnDataReceiveListener listener)
{
this.onDataReceiveListener = listener;
}
Copy the code
There is also an OnDataReceiveListener variable in the utility class that is used to set up the listening interface for external callers.
Note that the buffer in the onDataReceive() method is converted to a byte array, and the received information is also a byte array, so you can convert the byte array to a string and so on.
Methods for converting byte arrays to strings and strings to hexadecimal byte arrays are provided below.
Complete code:
Github.com/YKamh/Seria…
PS: The Demo simply implemented basic serial programming functions, and did not optimize the details.
conclusion
Facing the trend of the Internet of Things era, Android serial programming should be necessary. In the above knowledge points, the core code of which is still Java foundation, also reflects the importance of Java foundation.
When the author contacted the project combining hardware, he felt as if he had discovered a new continent. Serial programming was more interesting, without the boring of developing pure applications.
I hope we can work together and grow up together!
—– End —–
More oliver
Please scan the qr code below
Welcome to pay attention ~