We need to use Type-C to connect an Android app on a phone to a drone for communication.
We use MAVSDK Android to connect via Type-C, but we encountered an issue where serial access fails due to a lack of Linux file permissions. We are not root users and cannot gain root access. However, we noticed that the Android version of QGC also operates as a regular user but is able to establish a connection.
Through investigation, I found there are two possible approaches:
-
1、Using one java thread reading from serial using Android SDK api, forwarding to mavsdk server on like UDP:14550, and the other tread receiving data from mavsdk server UDP:14550, sending to serial (through Android SDK)
-
2、Using divyanshupundir 's andriod-serial git branch, compile by myself… Using the new fileDiscripitor interface to read and write by madsdk server directly…
I tried both… Seems not working neither… Am I wrong somewhere?
Below are codes of approach 1:
private void startForwardThreads() {
stopForwardThreads(); // 确保在启动新线程前停止旧线程
running.set(true);
// 启动 UDP→serial 的线程
executor.execute(() -> {
byte[] buffer = new byte[READ_BUFFER_SIZE];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
Log.i(TAG, "UDP→串口 线程启动");
while (running.get()) {
try {
if (udpSocket == null || udpSocket.isClosed()) {
Log.w(TAG, "UDP Socket 未初始化或已关闭,等待重新初始化...");
try {
Thread.sleep(1000); // 避免高频错误
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
break;
}
continue;
}
udpSocket.receive(packet);
int len = packet.getLength();
if (len > 0) {
Log.i(TAG, "从 UDP 接收到消息: " + bytesToHex(packet.getData(), len));
writeToSerial(packet.getData(), len);
}
packet.setLength(buffer.length);
} catch (IOException e) {
if (running.get()) {
Log.w(TAG, "UDP 接收错误: " + e.getMessage());
}
try {
Thread.sleep(1000); // 避免高频错误
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
break;
}
}
}
Log.i(TAG, "UDP→串口 线程已停止");
});
// 启动 serial→UDP 的线程
executor.execute(() -> {
byte[] buffer = new byte[READ_BUFFER_SIZE];
int readFailCount = 0;
Log.i(TAG, "串口→UDP 线程启动");
while (running.get()) {
try {
int len = serialPort.read(buffer, READ_WAIT_MILLIS);
if (len > 0) {
readFailCount = 0;
forwardToUDP(buffer, len);
}
} catch (IOException e) {
readFailCount++;
Log.w(TAG, "串口读取失败,当前重试次数:" + readFailCount);
if (readFailCount >= MAX_READ_FAILS) {
handleConnectionLoss();
break;
}
try {
Thread.sleep(2000);
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
break;
}
}
}
Log.i(TAG, "串口→UDP 线程已停止");
});
}
Approach 2 LOG: