Welcome to SerialPort’s documentation!¶
Install¶
Edit the Build.gradle
file and add the following dependencies.
dependencies {
implementation 'cn.shanyaliux.serialport:serialport:4.2.0'
}
If you need to use 4.1.6
and below, do as follows:
Add
JitPack
repository Add theJitPack
repository to your build fileallprojects { repositories { ... maven { url 'https://jitpack.io' } } }
add dependencies
dependencies { implementation 'com.gitee.Shanya:SerialPortSample:4.1.6' //Chinese warehouse implementation 'com.github.Shanyaliux:SerialPortSample:4.1.6' //Foreign warehouse }
Basic usage (Kotlin)¶
Build SerialPort instance¶
val serialPort = SerialPortBuilder.build(this)
Search device¶
Use the method doDiscovery(context)
to search for devices:
serialPort.doDiscovery(this)
Use the methods getPairedDevicesListBD()
and getUnPairedDevicesListBD()
to get search results:
serialPort.getPairedDevicesListBD() //Get a list of paired devices
serialPort.getUnPairedDevicesListBD() //Get a list of unpaired devices
If the search is not over, the list of unpaired devices may be empty or incomplete.
Connect the device¶
Setting the correct UUID is an essential step in order to successfully connect the device and complete the communication.
Set legacy device UUID¶
Use the static method setLegacyUUID(uuid)
of SerialPort
to set the UUID of the legacy device:
SerialPort.setLegacyUUID("00001101-0000-1000-8000-00805F9B34FB")
For traditional devices generally, you can use the default UUID without setting UUID.
Set BLE device UUID¶
Use the static method setLegacyUUID(uuid)
of SerialPort
to set the UUID of the BLE device:
SerialPort.setBleUUID("0000ffe1-0000-1000-8000-00805f9b34fb")
In most cases, BLE devices need to set UUID. For specific UUID, you can check the manual or consult the seller.
In addition, you can also use the method printPossibleBleUUID()
to print out a feasible UUID, and try it yourself:
serialPort.printPossibleBleUUID()
Establish connection¶
Use the method openDiscoveryActivity()
to open the built-in search page and select a device to connect to:
serialPort.openDiscoveryActivity()
**What if you don’t want to use the built-in search page? **
You can set up a custom search page or connect directly using the device address. See Use a custom interface
Receive message¶
Use the method setReceivedDataCallback(receivedDataCallback)
to set up a received message listener:
serialPort.setReceivedDataCallback { data ->
}
In addition to this, you can also configure the listener when building the instance:
val serialPort = SerialPortBuilder
.setReceivedDataCallback { data ->
}
.build(this)
Send a message¶
Send a message using the method sendData(data)
:
serialPort.sendData("Hello World")
**At this point, you can quickly develop a serial port application that can complete basic sending and receiving data. Of course, SerialPort
has many more functions, please continue to read the documentation. **
Basic usage (Java)¶
Build SerialPort instance¶
SerialPort serialPort = SerialPortBuilder.INSTANCE.build(this);
Search device¶
Use the method doDiscovery(context)
to search for devices:
serialPort.doDiscovery(this);
Use the methods getPairedDevicesListBD()
and getUnPairedDevicesListBD()
to get search results:
serialPort.getPairedDevicesListBD(); //Get a list of paired devices
serialPort.getUnPairedDevicesListBD(); //Get a list of unpaired devices
If the search is not over, the list of unpaired devices may be empty or incomplete.
Connect the device¶
Setting the correct UUID is an essential step in order to successfully connect the device and complete the communication.
Set legacy device UUID¶
Use the static method setLegacyUUID(uuid)
of SerialPort
to set the UUID of the legacy device:
SerialPort.Companion.setLegacyUUID("00001101-0000-1000-8000-00805F9B34FB");
For traditional devices generally, you can use the default UUID without setting UUID.
Set BLE device UUID¶
Use the static method setLegacyUUID(uuid)
of SerialPort
to set the UUID of the BLE device:
SerialPort.Companion.setBleUUID("0000ffe1-0000-1000-8000-00805f9b34fb");
In most cases, BLE devices need to set UUID. For specific UUID, you can check the manual or consult the seller.
In addition, you can also use the method printPossibleBleUUID()
to print out a feasible UUID, and try it yourself:
serialPort.printPossibleBleUUID()
Establish connection¶
Use the method openDiscoveryActivity()
to open the built-in search page and select a device to connect to:
serialPort.openDiscoveryActivity();
**What if you don’t want to use the built-in search page? **
You can set up a custom search page or connect directly using the device address. See Use a custom interface
Receive message¶
Use the method setReceivedDataCallback(receivedDataCallback)
to set up a received message listener:
serialPort.setReceivedDataCallback( (data) -> {
return null;
});
In addition to this, you can also configure the listener when building the instance:
SerialPort serialPort = SerialPortBuilder.INSTANCE
.setReceivedDataCallback( (data) -> {
return null;
})
.build(this);
Send a message¶
Send a message using the method sendData(data)
:
serialPort.sendData("Hello World");
**At this point, you can quickly develop a serial port application that can complete basic sending and receiving data. Of course, SerialPort
has many more functions, please continue to read the documentation. **
Server¶
Now, an Android server can be built to implement Bluetooth communication between two Androids. (Currently only supports single device connection)
Build instance¶
val serialPortServer = SerialPortServerBuilder
.setServerName("SerialPortServer")
.setServerUUID("00001101-0000-1000-8000-00805F9B34FB")
.setServerReceivedDataCallback {
}
.setServerConnectStatusCallback { status, bluetoothDevice ->
}
.build(this)
setServerName
Set server namesetServerUUID
Set the UUID of the server, the UUID of the traditional device needs to be set to the same as this when the client connectssetServerReceivedDataCallback
The server receives message monitoringsetServerConnectStatusCallback
Server connection status monitoringstatus
Connection StatusbluetoothDevice
Connected device, null whenstatus
is false
Open server¶
Only after the service is opened, the client can connect to the server.
serialPortServer.openServer()
Close server¶
serialPortServer.closeServer()
Set the server discoverable state¶
By default, if the server is turned on, it will be automatically set to be discoverable, and if the server is turned off, it will be set to be invisible.
setServerDiscoverable(status)
status
is of typeBoolean
, indicating the discoverable status
Send¶
serialPortServer.sendData("Hello")
Configuration¶
Debug mode¶
When debugging the program, we can turn on the debugging mode, which will print a variety of log information, and turn off this switch when the APP is officially released to reduce resource overhead. The settings are as follows:
val serialPort = SerialPortBuilder
.isDebug(true)
.build(this)
Auto reconnect¶
Reconnect at startup¶
After this function is enabled, an automatic reconnection will be performed when the instance is constructed, and the reconnection object is the last successfully connected device. The settings are as follows:
val serialPort = SerialPortBuilder
.autoConnect(true)
.build(this)
Automatic reconnection at intervals¶
After this function is turned on, it will automatically reconnect once at intervals (the time can be set by yourself), and the reconnection object is the last successfully connected device. The settings are as follows:
val serialPort = SerialPortBuilder
//The second parameter is the interval time,
//if not specified, the default is 10000Ms
.setAutoReconnectAtIntervals(true, 10000)
.build(this)
Ignore unnamed devices¶
When this feature is turned on, devices with empty device names are automatically ignored when searching for devices. The settings are as follows:
val serialPort = SerialPortBuilder
.isIgnoreNoNameDevice(true)
.build(this)
For some Bluetooth devices, the device name may be empty when connecting for the first time. Please enable this function according to the situation.
Automatically open the search interface¶
After enabling this function, when sending data, if it finds that the device is not connected, it will automatically open the built-in search page. The settings are as follows:
val serialPort = SerialPortBuilder
.autoOpenDiscoveryActivity(true)
.build(this)
Automatic conversion of hexadecimal data¶
When this function is turned on, when the received data is in hexadecimal, it will be automatically converted into a string. The settings are as follows:
val serialPort = SerialPortBuilder
.autoHexStringToString(true)
.build(this)
Of course, you can also do the conversion manually using the method hexStringToString(hexString)
:
string = serialPort.hexStringToString(hexString)
Built-in search page to choose connection method¶
After enabling this function, when you click the device to connect on the built-in page, you can manually select the connection method. But please note that if your device does not support the connection method you selected, the connection will not be successful.
val serialPort = SerialPortBuilder
.setOpenConnectionTypeDialogFlag(true)
.build(this)
Configurator¶
Configurator You can pass the above multiple configurations into SerialPortBuilder
at one time.
val config = SerialPortConfig()
val serialPort = SerialPortBuilder
.setConfig(config)
.build(this)
The parameters that can be set by the configurator are shown in the following table (bold indicates the default value):
parameter name | value |
---|---|
debug | (bool) true / false |
UUID_LEGACY | (string) 00001101-0000-1000-8000-00805F9B34FB |
UUID_BLE | (string) 00001101-0000-1000-8000-00805F9B34FB |
UUID_BLE_READ | (string) none |
UUID_BLE_SEND | (string) none |
autoConnect | (bool) true / false |
autoReconnect | (bool) true / false |
reconnectAtIntervals | (int) 10000 |
autoOpenDiscoveryActivity | (bool) true / false |
autoHexStringToString | (bool) true / false |
readDataType | SerialPort.READ_STRING / SerialPort.READ_HEX |
sendDataType | SerialPort.SEND_STRING / SerialPort.SEND_HEX |
ignoreNoNameDevice | (bool) true / false |
openConnectionTypeDialogFlag | (bool) true / false |
Among them, please refer to the precautions for setting UUID: ble device set UUID
Set search duration¶
Use this method to configure how long to search for devices:
//The parameter is time, in milliseconds
val serialPort = SerialPortBuilder
.setDiscoveryTime(10000)
.build(this)
Discovery and connect¶
Built-in interface¶
In order to help develop serial communication applications more conveniently and quickly, we have integrated a necessary search and connection page internally. Use the method openDiscoveryActivity()
to open a built-in interface:
serialPort.openDiscoveryActivity()
Use a custom interface¶
Of course, in more cases our search and connection pages need to be more beautiful and customizable. Then, you can use the method serialPort.openDiscoveryActivity(intent)
to open a custom page:
//Here you can modify it to your custom Activity
val intent = Intent(this,DiscoveryActivity::class.java)
serialPort.openDiscoveryActivity(intent)
Search device¶
Start search¶
Use the method doDiscovery(context)
to start searching for devices:
serialPort.doDiscovery(this)
Stop searching¶
Use the method cancelDiscovery(context)
to start searching for devices:
serialPort.cancelDiscovery(this)
Monitor search status¶
Use the method setDiscoveryStatusWithTypeCallback(discoveryStatusWithTypeCallback)
or setDiscoveryStatusCallback(discoveryStatusCallback)
to set a search status listener:
//status is search status
serialPort.setDiscoveryStatusCallback{ status ->
}
//Search for listeners with status band type
//deviceType = SerialPort.DISCOVERY_BLE Search for BLE devices
//deviceType = SerialPort.DISCOVERY_LEGACY Search traditional types
//status is search status
serialPort.setDiscoveryStatusWithTypeCallback { deviceType, status ->
}
In addition to this, you can also configure the listener when building the instance:
//status is search status
val serialPort = SerialPortBuilder
.setDiscoveryStatusCallback { status ->
}
.build(this)
//Search for listeners with status band type
//deviceType = SerialPort.DISCOVERY_BLE Search for BLE devices
//deviceType = SerialPort.DISCOVERY_LEGACY Search traditional types
//status is search status
val serialPort = SerialPortBuilder
.setDiscoveryStatusWithTypeCallback { deviceType, status ->
}
.build(this)
Get search results¶
Use the methods getPairedDevicesListBD()
and getUnPairedDevicesListBD()
to get search results:
serialPort.getPairedDevicesListBD() //Get a list of paired devices
serialPort.getUnPairedDevicesListBD() //Get a list of unpaired devices
If the search does not end, the acquired list of unpaired devices may be empty or incomplete.
Connect the device¶
Setting the correct UUID is an essential step in order to successfully connect the device and complete the communication.
Traditional equipment¶
Set UUID¶
Use the static method setLegacyUUID(uuid)
of SerialPort
to set the UUID of the legacy device:
SerialPort.setLegacyUUID("00001101-0000-1000-8000-00805F9B34FB")
For traditional devices generally, you can use the default UUID without setting UUID.
Establish connection¶
Use the method connectLegacyDevice(address)
to establish a connection with a legacy device:
serialPort.connectLegacyDevice("98:D3:32:21:67:D0")
BLE device¶
Set UUID¶
Use the static method setBleUUID(uuid)
of SerialPort
to set the UUID of the BLE device, or use setBleSendUUID
and setBleReadUUID
to set the send and receive UUID independently:
SerialPort.setBleUUID("0000ffe1-0000-1000-8000-00805f9b34fb")
SerialPort.setBleReadUUID("0000ffe1-0000-1000-8000-00805f9b34fb")
SerialPort.setBleSendUUID("0000ffe1-0000-1000-8000-00805f9b34fb")
If the UUID is set independently, the one set independently shall prevail.
In most cases, BLE devices need to set UUID. For specific UUID, you can check the manual or consult the seller.
In addition, you can also use the method printPossibleBleUUID()
to print out the feasible UUID, see for details: print uuid and its attributes
Establish connection¶
Use the method connectBle(address)
to establish a connection to a legacy device:
serialPort.connectBle("98:D3:32:21:67:D0")
Disconnect¶
Use the method disconnect()
to establish a connection to a legacy device:
serialPort.disconnect()
Monitor connection status¶
Use the method setConnectionStatusCallback(connectionStatusCallback)
to set a connection status listener:
serialPort.setConnectStatusCallback { status, bluetoothDevice ->
}
In addition to this, you can also configure the listener when building the instance:
val serialPort = SerialPortBuilder
.setConnectionStatusCallback { status, bluetoothDevice ->
}
.build(this)
The bluetoothDevice
used here is the official class, which contains various information about the Bluetooth device. see details official documentation
In previous versions, a custom Device
class was used (deprecated), which contains: device name, device address, and device type. It is implemented as follows:
@Deprecated("This class is deprecated in version 4.0.0 and will directly use the official BluetoothDevice class instead")
data class Device(
val name:String,
val address:String,
val type:Int = 0
)
BLE can work callback¶
This callback is triggered after the BLE device is successfully connected and can work, and can be used to configure the automatic sending of messages after the connection is successful. The method of use is as follows:
serialPort.setBleCanWorkCallback {
}
In addition to this, you can also configure the listener when building the instance:
val serialPort = SerialPortBuilder
.setBleCanWorkCallback {
}
.build(this)
Received and send¶
Set data format¶
Use the methods setReadDataType(type)
and setSendDataType(type)
to format the technique data:
Set the received message format¶
//SerialPort.READ_HEX hex
//SerialPort.READ_STRING string
//If not set, the default string form
serialPort.setReadDataType(SerialPort.READ_HEX)
In addition to this, you can also set the received data format when building the instance:
//SerialPort.READ_HEX hex
//SerialPort.READ_STRING string
//If not set, the default string form
val serialPort = SerialPortBuilder
.setReadDataType(SerialPort.READ_HEX)
.build(this)
Set the send data format¶
//SerialPort.SEND_HEX hex
//SerialPort.SEND_STRING string
//If not set, the default string form
serialPort.setSendDataType(SerialPort.SEND_HEX )
In addition to this, you can also set the send data format when building the instance:
//SerialPort.SEND_HEX hex
//SerialPort.SEND_STRING string
//If not set, the default string form
val serialPort = SerialPortBuilder
.setSendDataType(SerialPort.SEND_HEX)
.build(this)
Currently, the data sending and receiving for BLE devices does not support the setting format, only the string format is supported. If you really need the hexadecimal data format, you can temporarily implement it by referring to the processing method of traditional equipment.
Reference code link: HexStringToString、StringToHex
Receive message¶
string and hex¶
Use the method setReceivedDataCallback(receivedDataCallback)
to set up a received message listener:
serialPort.setReceivedDataCallback { data ->
}
In addition to this, you can also configure the listener when building the instance:
val serialPort = SerialPortBuilder
.setReceivedDataCallback { data ->
}
.build(this)
Byte array¶
When receiving a message, you can also choose to obtain a byte array as follows:
serialPort.setReceivedBytesCallback { bytes ->
}
In addition to this, you can also configure the listener when building the instance:
val serialPort = SerialPortBuilder
.setReceivedBytesCallback { bytes ->
}
.build(this)
Toast¶
Configuration method¶
//whether to display
SerialPortToast.connectSucceeded.status = true
//prompt content (content is a string id)
SerialPortToast.connectSucceeded.content = R.string.connectSucceededToast
//Display duration Toast.LENGTH_SHORT or Toast.LENGTH_LONG
SerialPortToast.connectSucceeded.time = Toast.LENGTH_SHORT
Optional configuration items¶
item | describe | defaults |
---|---|---|
connectSucceeded | When the connection is successful | Connection succeeded |
connectFailed | When the connection fails | Connection failed |
disconnect | When disconnected | Disconnect |
connectFirst | Send data when no device is connected | Please connect the device first |
disconnectFirst | Perform the connect operation after the device is connected | Please disconnect first |
permission | Ask whether to enable location permission | Please enable location permission first |
hexTip | When sending hexadecimal, the data format is incorrect | Please keep two digits for each hexadecimal data entered, and the insufficient is 0 in the front |
openBluetoothSucceeded | When the bluetooth is turned on successfully | Bluetooth turned on successfully |
openBluetoothFailed | When turning on bluetooth fails | Failed to turn on bluetooth |
Tools¶
Print UUID and its attributes¶
If we don’t know the UUID of the current BLE device, we can call the function printPossibleBleUUID
to print out the optional UUID of the currently connected device
Where Properties
is a binary number, and the meaning of each bit is shown in the following table:
value (in hexadecimal) | mean |
---|---|
0x01 | broadcastable |
0x02 | readable |
0x04 | can be written without response |
0x08 | can be written |
0x10 | supports notification |
0x20 | supports indication |
0x40 | supports write with signature |
0x80 | has extended properties |
String2hex¶
/**
* Convert string to hexadecimal
* @param str String to convert
* @return hex array
*/
DataUtil.string2hex("Hello")
Bytes2string¶
/**
* The byte array is converted into a string according to the required encoding format
* @param bytes byte array to convert
* @param charsetName Required encoding format
* @return Converted string
*/
SerialPortTools.bytes2string(bytes, "GBK")
String2bytes¶
/**
* The string is converted into a byte array according to the required encoding format
* @param string String to convert
* @param charsetName Required encoding format
* @return Converted byte array
*/
SerialPortTools.bytes2string("Hello", "GBK")
Configuration¶
Debug mode¶
When debugging the program, we can turn on the debugging mode, which will print a variety of log information, and turn off this switch when the APP is officially released to reduce resource overhead. The settings are as follows:
SerialPort serialPort = SerialPortBuilder.INSTANCE
.isDebug(true)
.build(this);
Auto reconnect¶
Reconnect at startup¶
After this function is enabled, an automatic reconnection will be performed when the instance is constructed, and the reconnection object is the last successfully connected device. The settings are as follows:
SerialPort serialPort = SerialPortBuilder.INSTANCE
.autoConnect(true)
.build(this);
Automatic reconnection at intervals¶
After this function is turned on, it will automatically reconnect once at intervals (the time can be set by yourself), and the reconnection object is the last successfully connected device. The settings are as follows:
SerialPort serialPort = SerialPortBuilder.INSTANCE
//The second parameter is the interval time,
//if not specified, the default is 10000Ms
.setAutoReconnectAtIntervals(true, 10000)
.build(this);
Ignore unnamed devices¶
When this feature is turned on, devices with empty device names are automatically ignored when searching for devices. The settings are as follows:
SerialPort serialPort = SerialPortBuilder.INSTANCE
.isIgnoreNoNameDevice(true)
.build(this);
For some Bluetooth devices, the device name may be empty when connecting for the first time. Please enable this function according to the situation.
Automatically open the search interface¶
After enabling this function, when sending data, if it finds that the device is not connected, it will automatically open the built-in search page. The settings are as follows:
SerialPort serialPort = SerialPortBuilder.INSTANCE
.autoOpenDiscoveryActivity(true)
.build(this);
Automatic conversion of hexadecimal data¶
When this function is turned on, when the received data is in hexadecimal, it will be automatically converted into a string. The settings are as follows:
SerialPort serialPort = SerialPortBuilder.INSTANCE
.autoHexStringToString(true)
.build(this);
Of course, you can also do the conversion manually using the method hexStringToString(hexString)
:
string = serialPort.hexStringToString(hexString)
Built-in search page to choose connection method¶
After enabling this function, when you click the device to connect on the built-in page, you can manually select the connection method. But please note that if your device does not support the connection method you selected, the connection will not be successful.
SerialPort serialPort = SerialPortBuilder.INSTANCE
.setOpenConnectionTypeDialogFlag(true)
.build(this);
Configurator¶
Configurator You can pass the above multiple configurations into SerialPortBuilder
at one time.
SerialPortConfig config = new SerialPortConfig();
SerialPort serialPort = SerialPortBuilder.INSTANCE
.setConfig(config)
.build(this);
The parameters that can be set by the configurator are shown in the following table (bold indicates the default value):
parameter name | value |
---|---|
debug | (bool) true / false |
UUID_LEGACY | (string) 00001101-0000-1000-8000-00805F9B34FB |
UUID_BLE | (string) 00001101-0000-1000-8000-00805F9B34FB |
UUID_BLE_READ | (string) none |
UUID_BLE_SEND | (string) none |
autoConnect | (bool) true / false |
autoReconnect | (bool) true / false |
reconnectAtIntervals | (int) 10000 |
autoOpenDiscoveryActivity | (bool) true / false |
autoHexStringToString | (bool) true / false |
readDataType | SerialPort.READ_STRING / SerialPort.READ_HEX |
sendDataType | SerialPort.SEND_STRING / SerialPort.SEND_HEX |
ignoreNoNameDevice | (bool) true / false |
openConnectionTypeDialogFlag | (bool) true / false |
Among them, please refer to the precautions for setting UUID: ble device set UUID
Set search duration¶
Use this method to configure how long to search for devices:
//The parameter is time, in milliseconds
SerialPort serialPort = SerialPortBuilder.INSTANCE
.setDiscoveryTime(10000)
.build(this);
Discovery and connect¶
Built-in interface¶
In order to help develop serial communication applications more conveniently and quickly, we have integrated a necessary search and connection page internally. Use the method openDiscoveryActivity()
to open a built-in interface:
serialPort.openDiscoveryActivity();
Use a custom interface¶
Of course, in more cases our search and connection pages need to be more beautiful and customizable. Then, you can use the method serialPort.openDiscoveryActivity(intent)
to open a custom page:
//Here you can modify it to your custom Activity
Intent intent = new Intent(this, DiscoveryActivity.class);
serialPort.openDiscoveryActivity(intent);
Search device¶
Start search¶
Use the method doDiscovery(context)
to start searching for devices:
serialPort.doDiscovery(this);
Stop searching¶
Use the method cancelDiscovery(context)
to start searching for devices:
serialPort.cancelDiscovery(this);
Monitor search status¶
Use the method setDiscoveryStatusWithTypeCallback(discoveryStatusWithTypeCallback)
or setDiscoveryStatusCallback(discoveryStatusCallback)
to set a search status listener:
//status is search status
serialPort.setDiscoveryStatusCallback((status) ->{
return null;
});
//Search for listeners with status band type
//deviceType = SerialPort.DISCOVERY_BLE Search for BLE devices
//deviceType = SerialPort.DISCOVERY_LEGACY Search traditional types
//status is search status
serialPort.setDiscoveryStatusWithTypeCallback((deviceType, status) -> {
return null;
});
In addition to this, you can also configure the listener when building the instance:
//status is search status
SerialPort serialPort = SerialPortBuilder.INSTANCE
.setDiscoveryStatusCallback( (status) -> {
return null;
})
.build(this);
//Search for listeners with status band type
//deviceType = SerialPort.DISCOVERY_BLE Search for BLE devices
//deviceType = SerialPort.DISCOVERY_LEGACY Search traditional types
//status is search status
SerialPort serialPort = SerialPortBuilder.INSTANCE
.setDiscoveryStatusWithTypeCallback( (deviceType, status) -> {
return null;
})
.build(this);
Get search results¶
Use the methods getPairedDevicesListBD()
and getUnPairedDevicesListBD()
to get search results:
serialPort.getPairedDevicesListBD(); //Get a list of paired devices
serialPort.getUnPairedDevicesListBD(); //Get a list of unpaired devices
If the search does not end, the acquired list of unpaired devices may be empty or incomplete.
Connect the device¶
Setting the correct UUID is an essential step in order to successfully connect the device and complete the communication.
Traditional equipment¶
Set UUID¶
Use the static method setLegacyUUID(uuid)
of SerialPort
to set the UUID of the legacy device:
SerialPort.Companion.setLegacyUUID("00001101-0000-1000-8000-00805F9B34FB");
For traditional devices generally, you can use the default UUID without setting UUID.
Establish connection¶
Use the method connectLegacyDevice(address)
to establish a connection with a legacy device:
serialPort.connectLegacyDevice("98:D3:32:21:67:D0");
BLE device¶
Set UUID¶
Use the static method setBleUUID(uuid)
of SerialPort
to set the UUID of the BLE device, or use setBleSendUUID
and setBleReadUUID
to set the send and receive UUID independently:
SerialPort.Companion.setBleUUID("0000ffe1-0000-1000-8000-00805f9b34fb");
SerialPort.Companion.setBleReadUUID("0000ffe1-0000-1000-8000-00805f9b34fb");
SerialPort.Companion.setBleSendUUID("0000ffe1-0000-1000-8000-00805f9b34fb");
If the UUID is set independently, the one set independently shall prevail.
In most cases, BLE devices need to set UUID. For specific UUID, you can check the manual or consult the seller.
In addition, you can also use the method printPossibleBleUUID()
to print out the feasible UUID, see for details: print uuid and its attributes
Establish connection¶
Use the method connectBle(address)
to establish a connection to a legacy device:
serialPort.connectBle("98:D3:32:21:67:D0");
Disconnect¶
Use the method disconnect()
to establish a connection to a legacy device:
serialPort.disconnect();
Monitor connection status¶
Use the method setConnectionStatusCallback(connectionStatusCallback)
to set a connection status listener:
serialPort.setConnectionStatusCallback((status,bluetoothDevice)->{
return null;
});
In addition to this, you can also configure the listener when building the instance:
SerialPort serialPort = SerialPortBuilder.INSTANCE
.setConnectionStatusCallback( (status, bluetoothDevice) -> {
return null;
})
.build(this);
The bluetoothDevice
used here is the official class, which contains various information about the Bluetooth device. see details official documentation
In previous versions, a custom Device
class was used (deprecated), which contains: device name, device address, and device type. It is implemented as follows:
@Deprecated("This class is deprecated in version 4.0.0 and will directly use the official BluetoothDevice class instead")
data class Device(
val name:String,
val address:String,
val type:Int = 0
)
BLE can work callback¶
This callback is triggered after the BLE device is successfully connected and can work, and can be used to configure the automatic sending of messages after the connection is successful. The method of use is as follows:
serialPort.setBleCanWorkCallback( () -> {
return null;
});
In addition to this, you can also configure the listener when building the instance:
SerialPort serialPort = SerialPortBuilder.INSTANCE
.setBleCanWorkCallback( () -> {
return null;
})
.build(this);
Received and send¶
Set data format¶
Use the methods setReadDataType(type)
and setSendDataType(type)
to format the technique data:
Set the received message format¶
//SerialPort.READ_HEX hex
//SerialPort.READ_STRING string
//If not set, the default string form
serialPort.setReadDataType(SerialPort.READ_HEX);
In addition to this, you can also set the received data format when building the instance:
//SerialPort.READ_HEX hex
//SerialPort.READ_STRING string
//If not set, the default string form
SerialPort serialPort = SerialPortBuilder.INSTANCE
.setReadDataType(SerialPort.READ_HEX)
.build(this);
Set the send data format¶
//SerialPort.SEND_HEX hex
//SerialPort.SEND_STRING string
//If not set, the default string form
serialPort.setSendDataType(SerialPort.SEND_HEX);
In addition to this, you can also set the send data format when building the instance:
//SerialPort.SEND_HEX hex
//SerialPort.SEND_STRING string
//If not set, the default string form
SerialPort serialPort = SerialPortBuilder.INSTANCE
.setSendDataType(SerialPort.SEND_HEX)
.build(this);
Currently, the data sending and receiving for BLE devices does not support the setting format, only the string format is supported. If you really need the hexadecimal data format, you can temporarily implement it by referring to the processing method of traditional equipment.
Reference code link: HexStringToString、StringToHex
Receive message¶
String and hex¶
Use the method setReceivedDataCallback(receivedDataCallback)
to set up a received message listener:
serialPort.setReceivedDataCallback( (data) -> {
return null;
});
In addition to this, you can also configure the listener when building the instance:
SerialPort serialPort = SerialPortBuilder.INSTANCE
.setReceivedDataCallback( (data) -> {
return null;
})
.build(this);
Byte array¶
When receiving a message, you can also choose to obtain a byte array as follows:
serialPort.setReceivedBytesCallback( (bytes) -> {
return null;
});
In addition to this, you can also configure the listener when building the instance:
SerialPort serialPort = SerialPortBuilder.INSTANCE
.setReceivedBytesCallback( (bytes) -> {
return null;
})
.build(this);
Toast¶
Configuration method¶
//whether to display
SerialPortToast.INSTANCE.getConnectSucceeded().setStatus(true);
//prompt content (content is a string id)
SerialPortToast.INSTANCE.getConnectSucceeded().setContent(R.string.connectSucceededToast);
//Display duration Toast.LENGTH_SHORT or Toast.LENGTH_LONG
SerialPortToast.INSTANCE.getConnectSucceeded().setTime(Toast.LENGTH_SHORT);
Optional configuration items¶
item | describe | defaults |
---|---|---|
connectSucceeded | When the connection is successful | Connection succeeded |
connectFailed | When the connection fails | Connection failed |
disconnect | When disconnected | Disconnect |
connectFirst | Send data when no device is connected | Please connect the device first |
disconnectFirst | Perform the connect operation after the device is connected | Please disconnect first |
permission | Ask whether to enable location permission | Please enable location permission first |
hexTip | When sending hexadecimal, the data format is incorrect | Please keep two digits for each hexadecimal data entered, and the insufficient is 0 in the front |
openBluetoothSucceeded | When the bluetooth is turned on successfully | Bluetooth turned on successfully |
openBluetoothFailed | When turning on bluetooth fails | Failed to turn on bluetooth |
Tools¶
Print UUID and its attributes¶
If we don’t know the UUID of the current BLE device, we can call the function printPossibleBleUUID
to print out the optional UUID of the currently connected device
Where Properties
is a binary number, and the meaning of each bit is shown in the following table:
value (in hexadecimal) | mean |
---|---|
0x01 | broadcastable |
0x02 | readable |
0x04 | can be written without response |
0x08 | can be written |
0x10 | supports notification |
0x20 | supports indication |
0x40 | supports write with signature |
0x80 | has extended properties |
String2hex¶
/**
* Convert string to hexadecimal
* @param str String to convert
* @return hex array
*/
DataUtil.INSTANCE.string2hex("Hello");
Bytes2string¶
/**
* The byte array is converted into a string according to the required encoding format
* @param bytes byte array to convert
* @param charsetName Required encoding format
* @return Converted string
*/
SerialPortTools.bytes2string(bytes, "GBK");
String2bytes¶
/**
* The string is converted into a byte array according to the required encoding format
* @param string String to convert
* @param charsetName Required encoding format
* @return Converted byte array
*/
SerialPortTools.string2bytes("Hello", "GBK");
FREQUENTLY ASKED QUESTIONS¶
Feature support¶
Does it support BLE devices?¶
Certainly,SerialPort
fully supports BLE devices since version 4.0.0
.
Is there an automatic reconnection mechanism?¶
Yes, it can be set to reconnect at startup, or it can be automatically reconnected at intervals.See auto reconnect
Common problem¶
Why is the list of available devices for a custom page empty?¶
After Android 6.0, you must give the positioning permission to search for available devices.
Why does the BLE device connect successfully, but cannot send and receive messages, and sometimes an exception occurs?¶
After the BLE device is successfully connected, it is necessary to set the correct UUID for normal communication.For the specific setting method, see Set BLE device UUID
Changelog¶
4.2.0 was released in 7/6/2022:¶
[Fix] Some compilation warnings about bluetooth permissions
[Modify] Upgrade
Kotlin
andGradle
versions[Modify] Mark
ConnectionResultCallback
obsolete[Feature] Added Ble device to send byte array
[Feature] Added Ble device can work callback
[Feature] Added Server
4.1.9 was released in 9/5/2022:¶
[Fix] When the sendUUID is incorrect, it crashes
4.1.8 was released in 14/4/2022:¶
fix autoOpenDiscoveryActivity is always true
DiscoveryActivity add English
add setDiscoveryTime
Sponsor¶
SerialPort is an open source project licensed under the Apache-2.0 license. It is completely free to use, but your sponsorship can make SerialPort more healthy and stable.
If you recognize the author’s efforts or SerialPort really helped you, please go to Gitee and GitHub to click star to encourage it. In addition, if you have enough pockets, you can scan the following sponsorship code to become a SerialPort sponsor: