Network debugging assistant: Android APP integrates TCP, UDP, classic Bluetooth and low-power Bluetooth debugging demo

Posted by rowman on Tue, 08 Mar 2022 00:18:17 +0100

1. Preface

I finally don't need to debug a hardware device and install an APP. If I download someone else's network debugging assistant in the APP store and have advertisements, I might as well write a relatively complete network debugging assistant directly. At present, the supported functions include tcp client and server, udp, low-power Bluetooth client and server, classic Bluetooth client and server. Low power Bluetooth can dynamically obtain the UUID of the server.

2. Implementation method

How do I implement debugging assistants? In fact, it is to download other people's apps to test first. For example, if I do tcp client first, I will use my client to test with the server opened by the downloaded APP. If the test is successful, write down one, and so on. I remember when I was a junior, a senior brother said that our class's network knowledge was too poor. It was really, really bad. I also started to learn more about the Internet of things before graduating from my senior year. Like Bluetooth, I used to look very scared and feel it would be very difficult. It seems that there is a wall in my heart and Bluetooth will never enter my heart. But now I want to learn them thoroughly and put them in my bowl, because I want to master more knowledge in order to become a better myself and no longer escape. Well, I talk too much. Let's take a look at the demo diagram first.

3.APP renderings

4. Deficiencies

The interface is simple without too many complex UIs. It mainly realizes the corresponding functions
It will be maintained slowly in the future, hee hee

5. Implementation idea of each debugging tool

Because there are too many codes, they are not displayed one by one.

(1) tcp client

1. Create Socket
2. Open the input / output stream connected to the Socket with the corresponding ip address and port number.
3. Read / write the Socket according to the protocol.
4. Close the I / O stream and the Socket.
However, in Android, when it comes to time-consuming operations such as network connection, you can't put them in the UI main thread. You need to add sub threads to make network connection in the sub threads, which involves the communication between Android threads, which is realized with Handle.

(2) tcp server

1. Create a server socket service. Through the ServerSocket object.
2. The server must provide an external port, otherwise the client cannot connect.
3. Get the connected client object.
4. Get the socket stream through the client object, read the data sent by the client and print it on the console.
5. Close resources: close the client and the server.

I don't know why. When the client disconnects, the server doesn't know that the client is disconnected, that is, it can't get the disconnection request from the client. So I wrote that when the client sends "close", the server disconnects the client. In addition, the client also sends "close" when requesting disconnection.


1. Establish the IP address and port number of the connection. The IP is the address you want to send, and the port number should choose the idle port, which is the port number from 8000 to 9000.
2. Establish datagram socket, sendsocket / receivesocket to send and receive data packets.
3. Create datagram packet sendpackage / receivepackage to package the contents sent or received.
4. Through sendsocket Send (sendpackage) or receivesocket UDP based Socket receive communication is completed.

Two threads are required for sending and receiving.
This implementation mainly refers to Android UDP communication summary (finally got up from the pit)

This article.

(4) Low power Bluetooth client

1. Permission problem: first judge whether the mobile phone meets Android 4 3 or above, and then judge whether the mobile phone turns on Bluetooth.
2. Search Bluetooth: search Bluetooth, call back the interface to view the relevant information of the device, and stop scanning for a certain time.
3. connect Bluetooth: first get the mac address of the ble device, then call the connect() method to connect.
4. Obtain features: after the Bluetooth connection is successful, you need to obtain the service features of Bluetooth, and then turn on the receiving settings.
5. Send message: the writeCharacteristic() method sends data to the device.
6. Receive message: receive the message received by Bluetooth through onCharacteristicRead() method in Bluetooth callback interface.
7. Connect and disconnect resources.

Classic Bluetooth cannot be found in low-power Bluetooth. I can't find it when I use hc-06 module as the server. I can find it when I change to classic Bluetooth.
Here is the method of dynamically obtaining the service UUID of the server. In the rewriting method onServicesDiscovered():

        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
            super.onServicesDiscovered(gatt, status);

            List<BluetoothGattService> gattServiceList = gatt.getServices();
            Log.e("ard", "Bluetooth module service open status:" + status + ",GATT: " + gatt.hashCode() + ",Number of services:" + gattServiceList.size());

            // Traversal Service
            for (int i = 0; i < gattServiceList.size(); i++) {
                BluetoothGattService gattService = gattServiceList.get(i);
                String serviceUUID = gattService.getUuid().toString();
                List<BluetoothGattCharacteristic> characteristicList = gattService.getCharacteristics();
                Log.i("ard", "service UUID: " + serviceUUID + ",Number of feature codes below: " + (null == characteristicList ? 0 : characteristicList.size()));

                // Traverse Characteristic
                for (int j = 0; j < characteristicList.size(); j++) {
                    BluetoothGattCharacteristic characteristic = characteristicList.get(j);
                    boolean b= bluetoothGatt.setCharacteristicNotification(characteristic, true); // Set the callback message that can be received
                    Log.e(TAG, "Open notification"+b );
                    String characteristicUUID = characteristic.getUuid().toString();
                    int properties = characteristic.getProperties();
                    Log.i("ard", "\t Signature code UUID: " + characteristicUUID + ",Properties:" + properties);

                    // This feature code is sent by the mobile phone to Bluetooth. According to different Bluetooth module models, the feature codes uuid are also different. You can try them all
                    characteristic2 = characteristic; // Set as the global target Bluetooth module to write data to the controller

                    // ---The following if blocks have no substantive operations---
                    if ((properties | BluetoothGattCharacteristic.PROPERTY_NOTIFY) > 0) { // Characteristic can receive callback messages
                        List<BluetoothGattDescriptor> descriptorList = characteristic.getDescriptors();
                        if (null != descriptorList && descriptorList.size() > 0) {

                            // Traversal Descriptor
                            for (int k = 0; k < descriptorList.size(); k++) {
                                BluetoothGattDescriptor descriptor = descriptorList.get(k);
                                UUID descriptorUUID = descriptor.getUuid();
                                byte[] descriptorValue = descriptor.getValue();
                                Log.i("ard", "\t\t descriptor  UUID: " + descriptorUUID + "," + String.valueOf(descriptorValue));

(5) Low power Bluetooth server (peripheral mode)

1. Set broadcast and initialize broadcast data
2. Start broadcasting
3. Configure Services and Characteristic
4.Server callback and operation

(6) Classic Bluetooth client

1. First turn on Bluetooth and set Bluetooth visible
2. Search for available devices
3. Pairing and connection (via UUID)
4. Create a Bluetooth socket and obtain the input / output stream
5. Read and write data, receive and send with outputstream and inputstream

(7) Classic Bluetooth server

1. First turn on Bluetooth and set Bluetooth visible
2. The server socket on the server side is waiting to receive the connection from the client. If there is no connection, it is blocked. Therefore, the code waiting for connection should be placed in the sub thread
3. After receiving the connection, the server returns a socket to manage the conversation, and uses outputstream and inputstream to receive and send

Note: the UUID s of the client and server should be consistent, otherwise the connection cannot be made.

6. Source code

Code cloud:

(7) References:

Android realizes communication between devices through Bluetooth (BLE low-power Bluetooth) | client | server

Topics: Android bluetooth udp TCPIP