10#include <QtCore/QCoreApplication>
11#include <QtCore/QJniEnvironment>
12#include <QtCore/QJniObject>
13#include <QtCore/QStringList>
14#include <QtCore/QtJniTypes>
21Q_DECLARE_JNI_CLASS(QGCUsbSerialPortInfo,
"org/mavlink/qgroundcontrol/serial/QGCUsbSerialPortInfo")
71 method->id = env->GetStaticMethodID(javaClass, method->name, method->signature);
74 qCCritical(AndroidSerialLog) <<
"Java method not found:" << method->name << method->signature;
75 (void) QJniEnvironment::checkAndClearExceptions(env);
80 qCDebug(AndroidSerialLog) <<
"Cached JNI method IDs," << missing <<
"missing";
100 const jclass portInfoClass = env.findClass<QtJniTypes::QGCUsbSerialPortInfo>();
101 if (!portInfoClass) {
102 qCCritical(AndroidSerialLog) <<
"Class Not Found:"
103 << QtJniTypes::Traits<QtJniTypes::QGCUsbSerialPortInfo>::className().data();
108 field->id = env->GetFieldID(portInfoClass, field->name, field->signature);
111 qCCritical(AndroidSerialLog) <<
"Java field not found:" << field->name << field->signature;
112 (void) env.checkAndClearExceptions();
133 if (!serialManagerClass) {
139 (void) env.checkAndClearExceptions();
152static jboolean jniDeviceNewData(JNIEnv* env, jclass javaClass, jlong token, jbyteArray data, jint length);
153static void jniDeviceBytesWritten(JNIEnv* env, jclass javaClass, jlong token, jint count);
154static void jniDeviceResourceError(JNIEnv* env, jclass javaClass, jlong token, jint reason, jstring detail);
155static void jniDevicesChanged(JNIEnv* env, jclass javaClass);
156Q_DECLARE_JNI_NATIVE_METHOD_IN_CURRENT_SCOPE(jniDeviceNewData, nativeDeviceNewData)
157Q_DECLARE_JNI_NATIVE_METHOD_IN_CURRENT_SCOPE(jniDeviceBytesWritten, nativeDeviceBytesWritten)
158Q_DECLARE_JNI_NATIVE_METHOD_IN_CURRENT_SCOPE(jniDeviceResourceError, nativeDeviceResourceError)
159Q_DECLARE_JNI_NATIVE_METHOD_IN_CURRENT_SCOPE(jniDevicesChanged, nativeDevicesChanged)
163 qCDebug(AndroidSerialLog) <<
"Registering Native Functions";
165 const JNINativeMethod javaMethods[]{
173 if (!env.isValid()) {
174 qCWarning(AndroidSerialLog) <<
"Invalid QJniEnvironment";
188 qCDebug(AndroidSerialLog) <<
"Native Functions Registered Successfully";
199static jboolean
jniDeviceNewData(JNIEnv* env, jclass, jlong token, jbyteArray data, jint length)
202 constexpr jsize kMaxNativePayloadBytes = 2048;
205 qCWarning(AndroidSerialLog) <<
"nativeDeviceNewData called with token=0";
210 qCWarning(AndroidSerialLog) <<
"nativeDeviceNewData called with null data";
214 const jsize arrayLen = env->GetArrayLength(data);
215 if (length <= 0 || length > arrayLen) {
216 qCWarning(AndroidSerialLog) <<
"nativeDeviceNewData called with length" << length <<
"for an array of"
217 << arrayLen <<
"bytes";
221 const jsize cappedLen = (length > kMaxNativePayloadBytes) ? kMaxNativePayloadBytes : length;
222 if (cappedLen != length) {
223 qCWarning(AndroidSerialLog) <<
"nativeDeviceNewData payload exceeds limit, truncating from" << length <<
"to"
224 << cappedLen <<
"bytes";
228 char payload[kMaxNativePayloadBytes];
229 env->GetByteArrayRegion(data, 0, cappedLen,
reinterpret_cast<jbyte*
>(payload));
230 if (QJniEnvironment::checkAndClearExceptions(env)) {
231 qCWarning(AndroidSerialLog) <<
"nativeDeviceNewData failed to copy JNI byte array";
235 return deliverNewData(token, payload,
static_cast<int>(cappedLen)) ? JNI_TRUE : JNI_FALSE;
241 qCWarning(AndroidSerialLog) <<
"nativeDeviceBytesWritten called with count" << count;
252 qCWarning(AndroidSerialLog) <<
"nativeDeviceResourceError called with token=0";
257 const QString errorDetail = detail ? QJniObject(detail).toString() : QString();
259 qCDebug(AndroidSerialLog) <<
"nativeDeviceResourceError:" << reason << errorDetail;
265DeviceWatcher::DeviceWatcher()
269 if (
const QCoreApplication*
const application = QCoreApplication::instance()) {
270 moveToThread(application->thread());
276 static DeviceWatcher watcher;
282 qCDebug(AndroidSerialLog) <<
"USB serial devices changed";
298static bool javaThrew(QJniEnvironment& env,
const char* methodName)
301 if (!env->ExceptionCheck()) {
307 (void) env.checkAndClearExceptions();
308 if (exception.
get()) {
311 qCWarning(AndroidSerialLog) <<
"Exception occurred while calling" << methodName;
318 if (!env.isValid()) {
319 qCWarning(AndroidSerialLog) <<
"Invalid QJniEnvironment in" << method.
name;
325 qCWarning(AndroidSerialLog) <<
"getSerialManagerClass returned null in" << method.
name;
330 qCWarning(AndroidSerialLog) <<
"Java method unavailable in" << method.
name;
339template <
typename Ret,
typename... Args>
343 static_assert(std::is_same_v<Ret, jint> || std::is_same_v<Ret, jlong> || std::is_same_v<Ret, jboolean>);
350 const Ret result = method.
call(env.jniEnv(), cls, args...);
360template <
typename Ret,
typename... Args>
370 result.reset(method.
call(env.jniEnv(), cls, args...));
373 }
else if (!result.get()) {
374 qCWarning(AndroidSerialLog) << method.
name <<
"returned null";
381template <
typename... Args>
388 qCWarning(AndroidSerialLog) << method.
name <<
"returned" << result <<
"which is not a result";
392 return static_cast<Result>(result);
397 return value ? JNI_TRUE : JNI_FALSE;
402static jint
toJava(std::chrono::milliseconds timeout)
404 if (timeout < std::chrono::milliseconds::zero()) {
408 return static_cast<jint
>(
409 (std::min<std::chrono::milliseconds::rep>) (timeout.count(), (std::numeric_limits<jint>::max)()));
415 return callJava(env, method, JNI_FALSE,
static_cast<jlong
>(handle)) == JNI_TRUE;
420 const QJniObject jname = QJniObject::fromString(portName);
421 if (!jname.isValid()) {
422 qCWarning(AndroidSerialLog) <<
"Invalid QJniObject for portName in" << method.
name;
427 return callJava(env, method, JNI_FALSE, jname.object<jstring>()) == JNI_TRUE;
433 static_assert(std::is_same_v<jint, int>);
437 const auto jarray =
callJavaObject(env, method,
static_cast<jlong
>(handle));
442 ints.resize(env->GetArrayLength(jarray.get()));
443 env->GetIntArrayRegion(jarray.get(), 0,
static_cast<jsize
>(ints.size()), ints.data());
444 if (env.checkAndClearExceptions()) {
445 qCWarning(AndroidSerialLog) <<
"Failed to read the int array from" << method.
name;
456 if (!env.isValid()) {
457 qCWarning(AndroidSerialLog) <<
"Invalid QJniEnvironment in" << caller;
461 jarray.
reset(env->NewByteArray(
static_cast<jsize
>(length)));
463 qCWarning(AndroidSerialLog) <<
"Failed to create jbyteArray in" << caller;
464 (void) env.checkAndClearExceptions();
468 env->SetByteArrayRegion(jarray.
get(), 0,
static_cast<jsize
>(length),
reinterpret_cast<const jbyte*
>(data));
469 if (env.checkAndClearExceptions()) {
470 qCWarning(AndroidSerialLog) <<
"Exception occurred while setting byte array region in" << caller;
489 static_cast<jstring
>(env->GetObjectField(
object, field.
id)));
491 string.resize(env->GetStringLength(value.
get()));
492 env->GetStringRegion(value.
get(), 0,
static_cast<jsize
>(
string.size()),
493 reinterpret_cast<jchar*
>(
string.data()));
501 return field.
id ?
static_cast<quint16
>(env->GetIntField(
object, field.
id)) : 0;
506 const auto& method =
s_methods.availablePorts;
507 QList<QSerialPortInfo> serialPortInfoList;
511 if (!portInfos.get()) {
512 return serialPortInfoList;
515 const jsize count = env->GetArrayLength(portInfos.get());
516 for (jsize i = 0; i < count; ++i) {
518 env->GetObjectArrayElement(portInfos.get(), i));
519 if (!portInfo.
get()) {
520 qCWarning(AndroidSerialLog) << method.name <<
"returned null at index" << i;
527 qCWarning(AndroidSerialLog) << method.name <<
"returned a port without a name at index" << i;
542 !flowControlField.
id || (env->GetBooleanField(portInfo.
get(), flowControlField.
id) == JNI_TRUE);
547 (void) env.checkAndClearExceptions();
549 return serialPortInfoList;
556 ports.removeIf([](
const QSerialPortInfo& port) {
return !port.stableName().isEmpty(); });
587 const QJniObject name = QJniObject::fromString(portName);
588 if (!name.isValid()) {
589 qCWarning(AndroidSerialLog) <<
"Invalid QJniObject for portName in getPortHandle";
610 return detail.get() ? QJniObject(detail.get()).toString() : QString();
621 qCWarning(AndroidSerialLog) <<
"open called without a handle from registerPort";
625 const QJniObject name = QJniObject::fromString(portName);
626 if (!name.isValid()) {
627 qCWarning(AndroidSerialLog) <<
"Invalid QJniObject for portName in open";
632 return callJava(env,
s_methods.open, kFailed, name.object<jstring>(),
static_cast<jlong
>(handle));
670 data.resize(env->GetArrayLength(jarray.get()));
671 env->GetByteArrayRegion(jarray.get(), 0,
static_cast<jsize
>(data.size()),
reinterpret_cast<jbyte*
>(data.data()));
672 if (env.checkAndClearExceptions()) {
673 qCWarning(AndroidSerialLog) <<
"Failed to copy the bytes from read";
686template <
typename... Args>
688 const char* data,
int length, Args... args)
690 if (!data || length <= 0) {
691 qCWarning(AndroidSerialLog) <<
"Invalid data or length in" << method.
name;
702 static_cast<jint
>(length), args...);
705int write(
PortHandle handle,
const char* data,
int length, std::chrono::milliseconds timeout)
708 return (written == length || written < 0) ? written :
static_cast<int>(
Result::Failed);
736 return static_cast<jint
>(dataBits);
776 switch (flowControl) {
791 qCWarning(AndroidSerialLog) <<
"Unknown flow control code:" << code;
801 const std::optional<jint> javaDataBits =
toJavaDataBits(dataBits);
802 const std::optional<jint> javaStopBits =
toJavaStopBits(stopBits);
803 const std::optional<jint> javaParity =
toJavaParity(parity);
804 if (!javaDataBits || !javaStopBits || !javaParity) {
805 qCWarning(AndroidSerialLog) <<
"Invalid serial parameters:" << dataBits << stopBits << parity;
810 *javaDataBits, *javaStopBits, *javaParity);
823 const std::optional<FlowControl> javaFlowControl =
toJavaFlowControl(flowControl);
824 if (!javaFlowControl) {
825 qCWarning(AndroidSerialLog) <<
"Invalid flow control:" << flowControl;
834 QList<FlowControl> supported;
837 for (
const int code : codes) {
839 supported.append(*flowControl);
890 QSerialPort::PinoutSignals data = QSerialPort::PinoutSignals();
893 for (
const int line : lines) {
894 if (line < 0 || line >=
static_cast<int>(std::size(kSignals))) {
895 qCWarning(AndroidSerialLog) <<
"Unknown control line code:" << line;
898 data |= kSignals[line];
932 const auto javaData =
toJavaBytes(env, data, length,
"echoToCallbacks");
933 const QJniObject javaDetail = QJniObject::fromString(detail);
934 if (!javaData.get() || !javaDetail.isValid()) {
939 static_cast<jint
>(deliveredLength),
static_cast<jint
>(written),
static_cast<jint
>(reason),
940 javaDetail.object<jstring>());
944template <
typename Id>
949 names.append(QStringLiteral(
"%1 %2 %3")
950 .arg(QLatin1StringView(kind), QLatin1StringView(binding->name),
951 QLatin1StringView(binding->signature)));
void reset(T ref=nullptr)
static DeviceWatcher * instance()
static QString portNameFromSystemLocation(const QString &systemLocation)
@ DataTerminalReadySignal
@ DataCarrierDetectSignal
bool getXon(PortHandle handle)
Under XON/XOFF flow control, false while the device has paused transmission.
bool isReading(PortHandle handle)
static jclass getSerialManagerClass()
The serial manager class, or null until setNativeMethods() has found it.
static JniPortInfoFields s_portInfoFields
Result echoToCallbacks(PortHandle handle, const char *data, int length, int deliveredLength, int written, ResourceErrorReason reason, const QString &detail)
static void cachePortInfoFieldIds(QJniEnvironment &env)
void deliverBytesWritten(PortHandle handle, int count)
qint64 PortHandle
Names an open port in every call to Java and in Java's callbacks. registerPort() makes one.
bool isControlLineSupported(PortHandle handle, QSerialPort::PinoutSignal line)
Whether the port has this one of the control lines.
QString getLastErrorDetail()
Result setLatencyTimer(PortHandle handle, int milliseconds)
Sets how long an FTDI chip holds back a partly filled packet, 1 to 255 ms. No other chip supports it.
bool deliverNewData(PortHandle handle, const char *bytes, int length)
FlowControl getFlowControl(PortHandle handle)
None also if the port cannot be asked.
void deliverResourceError(PortHandle handle, ResourceErrorReason reason, const QString &detail)
Result stopReading(PortHandle handle)
Stops delivering the port's input until startReading(); what arrives meanwhile is dropped.
constexpr const char * kJniUsbSerialManagerClassName
static bool resolveSerialManagerClass(QJniEnvironment &env)
static void appendUnbound(QStringList &names, const char *kind, const JavaBindingList< Id > &bindings)
Adds each method or field of the list that JNI did not find in Java to the names.
QByteArray read(PortHandle handle, int length, std::chrono::milliseconds timeout)
static Ret callJava(QJniEnvironment &env, const JavaMethod< Ret, Args... > &method, std::type_identity_t< Ret > fallback, Args... args)
constexpr PortHandle kNoPort
static QString t_exceptionDetail
Result setDataTerminalReady(PortHandle handle, bool set)
Result setRequestToSend(PortHandle handle, bool set)
static JniMethodCache s_methods
static void jniDeviceBytesWritten(JNIEnv *env, jclass javaClass, jlong token, jint count)
static jboolean jniDeviceNewData(JNIEnv *env, jclass javaClass, jlong token, jbyteArray data, jint length)
PortHandle getPortHandle(const QString &portName)
The handle of the open port with this name, or kNoPort.
static jboolean toJava(bool value)
int write(PortHandle handle, const char *data, int length, std::chrono::milliseconds timeout)
Returns length, or a Result: Failed if the write timed out, otherwise what writeWithProgress() report...
bool hasPermission(const QString &portName)
Whether QGC may open the device of this port.
bool isControlLineActive(PortHandle handle, QSerialPort::PinoutSignal line)
Whether this one of the control lines is active.
Result startReading(PortHandle handle)
QList< QSerialPortInfo > portsAwaitingPermission()
The ports of attached devices that still need USB permission.
bool isPortOpen(const QString &portName)
QSerialPort::PinoutSignals getControlLines(PortHandle handle)
The control lines that are active.
static int callJavaWrite(const JavaMethod< jint, jlong, jbyteArray, jint, Args... > &method, PortHandle handle, const char *data, int length, Args... args)
static bool javaThrew(QJniEnvironment &env, const char *methodName)
Result purgeBuffers(PortHandle handle, QSerialPort::Directions directions)
QSerialPort::PinoutSignals getSupportedControlLines(PortHandle handle)
The control lines the port has at all. None also if the port cannot be asked.
static QString stringField(JNIEnv *env, jobject object, const JavaField< jstring > &field)
static void jniDevicesChanged(JNIEnv *env, jclass javaClass)
static std::atomic< jclass > s_serialManagerClass
static quint16 usbIdField(JNIEnv *env, jobject object, const JavaField< jint > &field)
JavaBindingList< jmethodID > s_javaMethods
JavaBindingList< jfieldID > s_javaFields
static void cacheMethodIds(JNIEnv *env, jclass javaClass)
static bool callJavaBool(const JavaMethod< jboolean, jlong > &method, PortHandle handle)
QStringList unboundJavaNames()
Result setFlowControl(PortHandle handle, QSerialPort::FlowControl flowControl)
Result setBreak(PortHandle handle, bool set)
static std::optional< FlowControl > toJavaFlowControl(QSerialPort::FlowControl flowControl)
static std::optional< FlowControl > fromJavaFlowControl(jint code)
static std::optional< jint > toJavaDataBits(QSerialPort::DataBits dataBits)
static QSerialPort::PinoutSignals callJavaControlLines(const JavaMethod< jintArray, jlong > &method, PortHandle handle)
static std::optional< jint > toJavaStopBits(QSerialPort::StopBits stopBits)
static AndroidInterface::JniLocalRef< jbyteArray > toJavaBytes(QJniEnvironment &env, const char *data, int length, const char *caller)
QList< QSerialPortInfo > availablePorts()
bool isPermissionDenied(const QString &portName)
int writeWithProgress(PortHandle handle, const char *data, int length, std::chrono::milliseconds timeout)
Result close(PortHandle handle)
static void jniDeviceResourceError(JNIEnv *env, jclass javaClass, jlong token, jint reason, jstring detail)
bool isPortNameValid(const QString &portName)
Whether an attached device has a port with this name.
ResourceErrorReason
Why a port can no longer transfer data. QGCUsbSerialResourceError.java lists the same values.
static QList< int > callJavaIntArray(const JavaMethod< jintArray, jlong > &method, PortHandle handle)
int open(const QString &portName, PortHandle handle)
bool requestPermission(const QString &portName)
Result setParameters(PortHandle handle, qint32 baudRate, QSerialPort::DataBits dataBits, QSerialPort::StopBits stopBits, QSerialPort::Parity parity)
static Result callJavaCommand(const JavaMethod< jint, Args... > &method, Args... args)
Calls a static Java method that returns a QGCUsbSerialResult.
@ AmbiguousName
Opening: several attached devices share this stable name, so it opens none.
@ Unsupported
The port or its driver cannot do this.
@ Failed
The call could not be made, or failed for a reason not listed here.
static auto callJavaObject(QJniEnvironment &env, const JavaMethod< Ret, Args... > &method, Args... args)
QList< FlowControl > getSupportedFlowControl(PortHandle handle)
The flow control the port's driver has.
static jclass findJavaMethod(QJniEnvironment &env, const JavaBinding< jmethodID > &method)
Returns the serial manager class, or null after a warning if it or the method is unavailable.
static std::optional< jint > toJavaParity(QSerialPort::Parity parity)
int writeAsync(PortHandle handle, const char *data, int length)
The Java methods or fields that C++ binds, in the order in which they are declared.
JavaBinding< Id > * first
A field of QGCUsbSerialPortInfo.java, declared by its JNI type, from which its signature is derived.
Returned call(JNIEnv *env, jclass javaClass, Args... args) const
Calls the method, which the caller has found available. The caller then checks whether Java threw.
JavaMethod< jint, jlong, jboolean > setRequestToSend
JavaMethod< jint, jlong, jboolean > setBreak
JavaMethod< jint, jlong > getFlowControl
JavaMethod< jint, jlong, jint, jint, jint, jint > setParameters
JavaMethod< jboolean, jstring > hasPermission
JavaMethod< jint, jlong > stopReading
JavaMethod< jintArray, jlong > getControlLines
JavaMethod< jbyteArray, jlong, jint, jint > read
JavaMethod< jboolean, jlong > isReading
JavaMethod< jint, jlong, jbyteArray, jint > writeAsync
JavaMethod< jboolean, jstring > requestPermission
JavaMethod< jstring > getLastErrorDetail
JavaMethod< jboolean, jlong > getXon
JavaMethod< jint, jlong, jbyteArray, jint, jint, jint, jstring > echoToCallbacks
JavaMethod< jintArray, jlong > getSupportedControlLines
JavaMethod< QtJniTypes::QGCUsbSerialPortInfo[]> availablePorts
JavaMethod< jboolean, jstring > isPermissionDenied
JavaMethod< jlong, jstring > getPortHandle
JavaMethod< jint, jlong > close
JavaMethod< jint, jlong > startReading
JavaMethod< jint, jstring, jlong > open
JavaMethod< jint, jlong, jbyteArray, jint, jint > writeWithProgress
JavaMethod< jint, jlong, jboolean > setDataTerminalReady
JavaMethod< jboolean, jstring > isPortNameValid
JavaMethod< jint, jlong, jint > setLatencyTimer
JavaMethod< jint, jlong, jint > setFlowControl
JavaMethod< jintArray, jlong > getSupportedFlowControl
JavaMethod< jint, jlong, jboolean, jboolean > purgeBuffers
JavaField< jstring > stableName
JavaField< jstring > name
JavaField< jint > productId
JavaField< jint > vendorId
JavaField< jboolean > hardwareFlowControl
JavaField< jstring > serialNumber
JavaField< jstring > productName
JavaField< jstring > manufacturerName
quint16 productIdentifier
bool hasHardwareFlowControl
bool hasProductIdentifier