QGroundControl
Ground Control Station for MAVLink Drones
Loading...
Searching...
No Matches
AndroidSerialJni.cc
Go to the documentation of this file.
1#include "AndroidSerialJni.h"
2
3#include <algorithm>
4#include <atomic>
5#include <iterator>
6#include <limits>
7#include <optional>
8#include <type_traits>
9
10#include <QtCore/QCoreApplication>
11#include <QtCore/QJniEnvironment>
12#include <QtCore/QJniObject>
13#include <QtCore/QStringList>
14#include <QtCore/QtJniTypes>
15
16#include "AndroidInterface.h"
17#include "JavaBinding.h"
18#include "QGCLoggingCategory.h"
19
20// The Java class of a port that availablePorts() lists, for the signature below.
21Q_DECLARE_JNI_CLASS(QGCUsbSerialPortInfo, "org/mavlink/qgroundcontrol/serial/QGCUsbSerialPortInfo")
22
23namespace AndroidSerial {
24
25// ----------------------------------------------------------------------------
26// JNI method ID cache
27// ----------------------------------------------------------------------------
28
29// Each method and field is declared under its own name.
31{
60};
61
63// Set once, by setNativeMethods(), and only after s_methods is filled: a non-null load also means that the method
64// IDs are ready.
65static std::atomic<jclass> s_serialManagerClass{nullptr};
66
67static void cacheMethodIds(JNIEnv* env, jclass javaClass)
68{
69 int missing = 0;
70 for (JavaBinding<jmethodID>* method = s_javaMethods.first; method; method = method->next) {
71 method->id = env->GetStaticMethodID(javaClass, method->name, method->signature);
72 if (!method->id) {
73 // Leave it null so only the calls that need this method fail, not the whole serial backend.
74 qCCritical(AndroidSerialLog) << "Java method not found:" << method->name << method->signature;
75 (void) QJniEnvironment::checkAndClearExceptions(env);
76 ++missing;
77 }
78 }
79
80 qCDebug(AndroidSerialLog) << "Cached JNI method IDs," << missing << "missing";
81}
82
94
96
97static void cachePortInfoFieldIds(QJniEnvironment& env)
98{
99 // Qt keeps the class it finds referenced, so the field IDs stay valid.
100 const jclass portInfoClass = env.findClass<QtJniTypes::QGCUsbSerialPortInfo>();
101 if (!portInfoClass) {
102 qCCritical(AndroidSerialLog) << "Class Not Found:"
103 << QtJniTypes::Traits<QtJniTypes::QGCUsbSerialPortInfo>::className().data();
104 return;
105 }
106
107 for (JavaBinding<jfieldID>* field = s_javaFields.first; field; field = field->next) {
108 field->id = env->GetFieldID(portInfoClass, field->name, field->signature);
109 if (!field->id) {
110 // Leave it null so the port list only lacks this field.
111 qCCritical(AndroidSerialLog) << "Java field not found:" << field->name << field->signature;
112 (void) env.checkAndClearExceptions();
113 }
114 }
115}
116
117// ----------------------------------------------------------------------------
118// Class resolution
119// ----------------------------------------------------------------------------
120
123{
124 return s_serialManagerClass.load(std::memory_order_acquire);
125}
126
129static bool resolveSerialManagerClass(QJniEnvironment& env)
130{
131 // Qt keeps the class it finds referenced, so the class and its method IDs stay valid.
132 const jclass serialManagerClass = env.findClass(kJniUsbSerialManagerClassName);
133 if (!serialManagerClass) {
134 return false;
135 }
136
137 cacheMethodIds(env.jniEnv(), serialManagerClass);
139 (void) env.checkAndClearExceptions();
140 s_serialManagerClass.store(serialManagerClass, std::memory_order_release);
141 return true;
142}
143
144// ----------------------------------------------------------------------------
145// Native method registration
146// ----------------------------------------------------------------------------
147
148// The JNI callbacks, defined below, each with the native method of QGCUsbSerialManager.java that it is registered
149// as. Qt derives the JNI signature to register it under from the function's own types; one written by hand
150// that disagreed with them would compile, and corrupt the arguments of every call. Qt's macros for a function of
151// a scope are used because its plain ones take only a function of the global namespace.
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)
160
162{
163 qCDebug(AndroidSerialLog) << "Registering Native Functions";
164
165 const JNINativeMethod javaMethods[]{
166 Q_JNI_NATIVE_SCOPED_METHOD(jniDeviceNewData, AndroidSerial),
167 Q_JNI_NATIVE_SCOPED_METHOD(jniDeviceBytesWritten, AndroidSerial),
168 Q_JNI_NATIVE_SCOPED_METHOD(jniDeviceResourceError, AndroidSerial),
169 Q_JNI_NATIVE_SCOPED_METHOD(jniDevicesChanged, AndroidSerial),
170 };
171
172 QJniEnvironment env;
173 if (!env.isValid()) {
174 qCWarning(AndroidSerialLog) << "Invalid QJniEnvironment";
175 return false;
176 }
177
178 if (!env.registerNativeMethods(kJniUsbSerialManagerClassName, javaMethods, std::size(javaMethods))) {
179 qCWarning(AndroidSerialLog) << "Failed to register native methods for" << kJniUsbSerialManagerClassName;
180 return false;
181 }
182
183 if (!resolveSerialManagerClass(env)) {
184 qCWarning(AndroidSerialLog) << "Failed to resolve" << kJniUsbSerialManagerClassName;
185 return false;
186 }
187
188 qCDebug(AndroidSerialLog) << "Native Functions Registered Successfully";
189 return true;
190}
191
192// ----------------------------------------------------------------------------
193// JNI callbacks (called from Java threads)
194// ----------------------------------------------------------------------------
195
196// The first length bytes of data are the input. The array is the buffer of Java's read thread, which the next read
197// overwrites, so the bytes are copied before this returns. Returns whether the port has room for more input: if
198// not, Java's read thread waits until the port starts reading again. Input that reaches no port holds nothing back.
199static jboolean jniDeviceNewData(JNIEnv* env, jclass, jlong token, jbyteArray data, jint length)
200{
201 // As much as Java's read thread reads at once, READ_BUF_SIZE in QGCUsbSerialReader.java.
202 constexpr jsize kMaxNativePayloadBytes = 2048;
203
204 if (token == 0) {
205 qCWarning(AndroidSerialLog) << "nativeDeviceNewData called with token=0";
206 return JNI_TRUE;
207 }
208
209 if (!data) {
210 qCWarning(AndroidSerialLog) << "nativeDeviceNewData called with null data";
211 return JNI_TRUE;
212 }
213
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";
218 return JNI_TRUE;
219 }
220
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";
225 }
226
227 // On the stack, since this runs for every read. The stack of a Java thread has room for it.
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";
232 return JNI_TRUE;
233 }
234
235 return deliverNewData(token, payload, static_cast<int>(cappedLen)) ? JNI_TRUE : JNI_FALSE;
236}
237
238static void jniDeviceBytesWritten(JNIEnv*, jclass, jlong token, jint count)
239{
240 if (count <= 0) {
241 qCWarning(AndroidSerialLog) << "nativeDeviceBytesWritten called with count" << count;
242 return;
243 }
244
245 deliverBytesWritten(token, count);
246}
247
248// The port can no longer transfer data. The reason is a QGCUsbSerialResourceError of Java.
249static void jniDeviceResourceError(JNIEnv*, jclass, jlong token, jint reason, jstring detail)
250{
251 if (token == 0) {
252 qCWarning(AndroidSerialLog) << "nativeDeviceResourceError called with token=0";
253 return;
254 }
255
256 // Java passes an empty detail, not null, where it has none. The port is told of its loss either way.
257 const QString errorDetail = detail ? QJniObject(detail).toString() : QString();
258 // The port that the error belongs to warns of it, and so did Java.
259 qCDebug(AndroidSerialLog) << "nativeDeviceResourceError:" << reason << errorDetail;
260
261 // A reason that ResourceErrorReason does not list still reaches the port, which has a text for it.
262 deliverResourceError(token, static_cast<ResourceErrorReason>(reason), errorDetail);
263}
264
265DeviceWatcher::DeviceWatcher()
266{
267 // The first to ask for the watcher may be the Android thread that reports a change, which would otherwise
268 // own it and may end long before the application does.
269 if (const QCoreApplication* const application = QCoreApplication::instance()) {
270 moveToThread(application->thread());
271 }
272}
273
275{
276 static DeviceWatcher watcher;
277 return &watcher;
278}
279
280static void jniDevicesChanged(JNIEnv*, jclass)
281{
282 qCDebug(AndroidSerialLog) << "USB serial devices changed";
283
284 DeviceWatcher* const watcher = DeviceWatcher::instance();
285 emit watcher->devicesChanged();
286}
287
288// ----------------------------------------------------------------------------
289// Calling Java
290// ----------------------------------------------------------------------------
291
292// What the exception that ended this thread's last call into Java says of itself, and nothing once a call has
293// returned. Java keeps the detail of a failure only where it catches the failure.
294static thread_local QString t_exceptionDetail;
295
298static bool javaThrew(QJniEnvironment& env, const char* methodName)
299{
300 t_exceptionDetail.clear();
301 if (!env->ExceptionCheck()) {
302 return false;
303 }
304
305 const AndroidInterface::JniLocalRef<jthrowable> exception(env.jniEnv(), env->ExceptionOccurred());
306 // Logs the exception with its stack trace. Java can be asked for its text only once it is cleared.
307 (void) env.checkAndClearExceptions();
308 if (exception.get()) {
309 t_exceptionDetail = QJniObject(exception.get()).toString();
310 }
311 qCWarning(AndroidSerialLog) << "Exception occurred while calling" << methodName;
312 return true;
313}
314
316static jclass findJavaMethod(QJniEnvironment& env, const JavaBinding<jmethodID>& method)
317{
318 if (!env.isValid()) {
319 qCWarning(AndroidSerialLog) << "Invalid QJniEnvironment in" << method.name;
320 return nullptr;
321 }
322
323 const jclass cls = getSerialManagerClass();
324 if (!cls) {
325 qCWarning(AndroidSerialLog) << "getSerialManagerClass returned null in" << method.name;
326 return nullptr;
327 }
328
329 if (!method.id) {
330 qCWarning(AndroidSerialLog) << "Java method unavailable in" << method.name;
331 return nullptr;
332 }
333
334 return cls;
335}
336
339template <typename Ret, typename... Args>
340static Ret callJava(QJniEnvironment& env, const JavaMethod<Ret, Args...>& method, std::type_identity_t<Ret> fallback,
341 Args... args)
342{
343 static_assert(std::is_same_v<Ret, jint> || std::is_same_v<Ret, jlong> || std::is_same_v<Ret, jboolean>);
344
345 const jclass cls = findJavaMethod(env, method);
346 if (!cls) {
347 return fallback;
348 }
349
350 const Ret result = method.call(env.jniEnv(), cls, args...);
351 if (javaThrew(env, method.name)) {
352 return fallback;
353 }
354
355 return result;
356}
357
360template <typename Ret, typename... Args>
361static auto callJavaObject(QJniEnvironment& env, const JavaMethod<Ret, Args...>& method, Args... args)
362{
363 AndroidInterface::JniLocalRef<typename JavaMethod<Ret, Args...>::Returned> result(env.jniEnv());
364
365 const jclass cls = findJavaMethod(env, method);
366 if (!cls) {
367 return result;
368 }
369
370 result.reset(method.call(env.jniEnv(), cls, args...));
371 if (javaThrew(env, method.name)) {
372 result.reset();
373 } else if (!result.get()) {
374 qCWarning(AndroidSerialLog) << method.name << "returned null";
375 }
376
377 return result;
378}
379
381template <typename... Args>
382static Result callJavaCommand(const JavaMethod<jint, Args...>& method, Args... args)
383{
384 QJniEnvironment env;
385 const jint result = callJava(env, method, static_cast<jint>(Result::Failed), args...);
386 // The results are the values from Ok down to the last that Result lists.
387 if (result > static_cast<jint>(Result::Ok) || result < static_cast<jint>(Result::AmbiguousName)) {
388 qCWarning(AndroidSerialLog) << method.name << "returned" << result << "which is not a result";
389 return Result::Failed;
390 }
391
392 return static_cast<Result>(result);
393}
394
395static jboolean toJava(bool value)
396{
397 return value ? JNI_TRUE : JNI_FALSE;
398}
399
402static jint toJava(std::chrono::milliseconds timeout)
403{
404 if (timeout < std::chrono::milliseconds::zero()) {
405 return 1;
406 }
407
408 return static_cast<jint>(
409 (std::min<std::chrono::milliseconds::rep>) (timeout.count(), (std::numeric_limits<jint>::max)()));
410}
411
412static bool callJavaBool(const JavaMethod<jboolean, jlong>& method, PortHandle handle)
413{
414 QJniEnvironment env;
415 return callJava(env, method, JNI_FALSE, static_cast<jlong>(handle)) == JNI_TRUE;
416}
417
418static bool callJavaBool(const JavaMethod<jboolean, jstring>& method, const QString& portName)
419{
420 const QJniObject jname = QJniObject::fromString(portName);
421 if (!jname.isValid()) {
422 qCWarning(AndroidSerialLog) << "Invalid QJniObject for portName in" << method.name;
423 return false;
424 }
425
426 QJniEnvironment env;
427 return callJava(env, method, JNI_FALSE, jname.object<jstring>()) == JNI_TRUE;
428}
429
430static QList<int> callJavaIntArray(const JavaMethod<jintArray, jlong>& method, PortHandle handle)
431{
432 // A Java int is a C++ int on Android, so the array is copied straight into the list.
433 static_assert(std::is_same_v<jint, int>);
434 QList<int> ints;
435
436 QJniEnvironment env;
437 const auto jarray = callJavaObject(env, method, static_cast<jlong>(handle));
438 if (!jarray.get()) {
439 return ints;
440 }
441
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;
446 ints.clear();
447 }
448
449 return ints;
450}
451
452static AndroidInterface::JniLocalRef<jbyteArray> toJavaBytes(QJniEnvironment& env, const char* data, int length,
453 const char* caller)
454{
456 if (!env.isValid()) {
457 qCWarning(AndroidSerialLog) << "Invalid QJniEnvironment in" << caller;
458 return jarray;
459 }
460
461 jarray.reset(env->NewByteArray(static_cast<jsize>(length)));
462 if (!jarray.get()) {
463 qCWarning(AndroidSerialLog) << "Failed to create jbyteArray in" << caller;
464 (void) env.checkAndClearExceptions();
465 return jarray;
466 }
467
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;
471 jarray.reset();
472 }
473
474 return jarray;
475}
476
477// ----------------------------------------------------------------------------
478// Devices
479// ----------------------------------------------------------------------------
480
481static QString stringField(JNIEnv* env, jobject object, const JavaField<jstring>& field)
482{
483 QString string;
484 if (!field.id) {
485 return string;
486 }
487
489 static_cast<jstring>(env->GetObjectField(object, field.id)));
490 if (value.get()) {
491 string.resize(env->GetStringLength(value.get()));
492 env->GetStringRegion(value.get(), 0, static_cast<jsize>(string.size()),
493 reinterpret_cast<jchar*>(string.data()));
494 }
495
496 return string;
497}
498
499static quint16 usbIdField(JNIEnv* env, jobject object, const JavaField<jint>& field)
500{
501 return field.id ? static_cast<quint16>(env->GetIntField(object, field.id)) : 0;
502}
503
504QList<QSerialPortInfo> availablePorts()
505{
506 const auto& method = s_methods.availablePorts;
507 QList<QSerialPortInfo> serialPortInfoList;
508
509 QJniEnvironment env;
510 const auto portInfos = callJavaObject(env, method);
511 if (!portInfos.get()) {
512 return serialPortInfoList;
513 }
514
515 const jsize count = env->GetArrayLength(portInfos.get());
516 for (jsize i = 0; i < count; ++i) {
517 const AndroidInterface::JniLocalRef<jobject> portInfo(env.jniEnv(),
518 env->GetObjectArrayElement(portInfos.get(), i));
519 if (!portInfo.get()) {
520 qCWarning(AndroidSerialLog) << method.name << "returned null at index" << i;
521 continue;
522 }
523
525 info.systemLocation = stringField(env.jniEnv(), portInfo.get(), s_portInfoFields.name);
526 if (info.systemLocation.isEmpty()) {
527 qCWarning(AndroidSerialLog) << method.name << "returned a port without a name at index" << i;
528 continue;
529 }
531 info.stableName = stringField(env.jniEnv(), portInfo.get(), s_portInfoFields.stableName);
532 info.description = stringField(env.jniEnv(), portInfo.get(), s_portInfoFields.productName);
533 info.manufacturer = stringField(env.jniEnv(), portInfo.get(), s_portInfoFields.manufacturerName);
534 info.serialNumber = stringField(env.jniEnv(), portInfo.get(), s_portInfoFields.serialNumber);
535 info.vendorIdentifier = usbIdField(env.jniEnv(), portInfo.get(), s_portInfoFields.vendorId);
536 info.hasVendorIdentifier = (info.vendorIdentifier != 0);
537 info.productIdentifier = usbIdField(env.jniEnv(), portInfo.get(), s_portInfoFields.productId);
538 info.hasProductIdentifier = (info.productIdentifier != 0);
539 // A port whose driver cannot be asked is taken for one that has it, as a port of any other platform is.
540 const JavaField<jboolean>& flowControlField = s_portInfoFields.hardwareFlowControl;
542 !flowControlField.id || (env->GetBooleanField(portInfo.get(), flowControlField.id) == JNI_TRUE);
543
544 serialPortInfoList.append(QSerialPortInfo(info));
545 }
546
547 (void) env.checkAndClearExceptions();
548
549 return serialPortInfoList;
550}
551
552QList<QSerialPortInfo> portsAwaitingPermission()
553{
554 QList<QSerialPortInfo> ports = availablePorts();
555 // Java gives a port its stable name once QGC may open its device.
556 ports.removeIf([](const QSerialPortInfo& port) { return !port.stableName().isEmpty(); });
557 return ports;
558}
559
560bool hasPermission(const QString& portName)
561{
562 return callJavaBool(s_methods.hasPermission, portName);
563}
564
565bool requestPermission(const QString& portName)
566{
567 return callJavaBool(s_methods.requestPermission, portName);
568}
569
570bool isPermissionDenied(const QString& portName)
571{
572 return callJavaBool(s_methods.isPermissionDenied, portName);
573}
574
575bool isPortNameValid(const QString& portName)
576{
577 return callJavaBool(s_methods.isPortNameValid, portName);
578}
579
580bool isPortOpen(const QString& portName)
581{
582 return getPortHandle(portName) != kNoPort;
583}
584
585PortHandle getPortHandle(const QString& portName)
586{
587 const QJniObject name = QJniObject::fromString(portName);
588 if (!name.isValid()) {
589 qCWarning(AndroidSerialLog) << "Invalid QJniObject for portName in getPortHandle";
590 return kNoPort;
591 }
592
593 QJniEnvironment env;
594 return callJava(env, s_methods.getPortHandle, static_cast<jlong>(kNoPort), name.object<jstring>());
595}
596
597// ----------------------------------------------------------------------------
598// Failure detail
599// ----------------------------------------------------------------------------
600
602{
603 // An exception ended the call, so Java has kept no detail of its failure.
604 if (!t_exceptionDetail.isEmpty()) {
605 return t_exceptionDetail;
606 }
607
608 QJniEnvironment env;
609 const auto detail = callJavaObject(env, s_methods.getLastErrorDetail);
610 return detail.get() ? QJniObject(detail.get()).toString() : QString();
611}
612
613// ----------------------------------------------------------------------------
614// Open / close
615// ----------------------------------------------------------------------------
616
617int open(const QString& portName, PortHandle handle)
618{
619 constexpr jint kFailed = static_cast<jint>(Result::Failed);
620 if (handle == kNoPort) {
621 qCWarning(AndroidSerialLog) << "open called without a handle from registerPort";
622 return kFailed;
623 }
624
625 const QJniObject name = QJniObject::fromString(portName);
626 if (!name.isValid()) {
627 qCWarning(AndroidSerialLog) << "Invalid QJniObject for portName in open";
628 return kFailed;
629 }
630
631 QJniEnvironment env;
632 return callJava(env, s_methods.open, kFailed, name.object<jstring>(), static_cast<jlong>(handle));
633}
634
636{
637 return callJavaCommand(s_methods.close, static_cast<jlong>(handle));
638}
639
640// ----------------------------------------------------------------------------
641// Reading
642// ----------------------------------------------------------------------------
643
645{
646 return callJavaCommand(s_methods.startReading, static_cast<jlong>(handle));
647}
648
650{
651 return callJavaCommand(s_methods.stopReading, static_cast<jlong>(handle));
652}
653
655{
656 return callJavaBool(s_methods.isReading, handle);
657}
658
659QByteArray read(PortHandle handle, int length, std::chrono::milliseconds timeout)
660{
661 QByteArray data;
662
663 QJniEnvironment env;
664 const auto jarray =
665 callJavaObject(env, s_methods.read, static_cast<jlong>(handle), static_cast<jint>(length), toJava(timeout));
666 if (!jarray.get()) {
667 return data;
668 }
669
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";
674 data.clear();
675 }
676
677 return data;
678}
679
680// ----------------------------------------------------------------------------
681// Writing
682// ----------------------------------------------------------------------------
683
686template <typename... Args>
688 const char* data, int length, Args... args)
689{
690 if (!data || length <= 0) {
691 qCWarning(AndroidSerialLog) << "Invalid data or length in" << method.name;
692 return static_cast<int>(Result::Failed);
693 }
694
695 QJniEnvironment env;
696 const auto jarray = toJavaBytes(env, data, length, method.name);
697 if (!jarray.get()) {
698 return static_cast<int>(Result::Failed);
699 }
700
701 return callJava(env, method, static_cast<jint>(Result::Failed), static_cast<jlong>(handle), jarray.get(),
702 static_cast<jint>(length), args...);
703}
704
705int write(PortHandle handle, const char* data, int length, std::chrono::milliseconds timeout)
706{
707 const int written = writeWithProgress(handle, data, length, timeout);
708 return (written == length || written < 0) ? written : static_cast<int>(Result::Failed);
709}
710
711int writeWithProgress(PortHandle handle, const char* data, int length, std::chrono::milliseconds timeout)
712{
713 return callJavaWrite(s_methods.writeWithProgress, handle, data, length, toJava(timeout));
714}
715
716int writeAsync(PortHandle handle, const char* data, int length)
717{
718 return callJavaWrite(s_methods.writeAsync, handle, data, length);
719}
720
721// ----------------------------------------------------------------------------
722// Port settings
723// ----------------------------------------------------------------------------
724
725// Java takes the constants of usb-serial-for-android's UsbSerialPort, and names a value of one of its enums by
726// the code that QGCUsbSerialManager.java gives it. The functions below return nothing for a value that
727// QSerialPort's enum does not list.
728
729static std::optional<jint> toJavaDataBits(QSerialPort::DataBits dataBits)
730{
731 switch (dataBits) {
736 return static_cast<jint>(dataBits);
737 }
738
739 return std::nullopt;
740}
741
742static std::optional<jint> toJavaStopBits(QSerialPort::StopBits stopBits)
743{
744 switch (stopBits) {
746 return 1;
748 return 3;
750 return 2;
751 }
752
753 return std::nullopt;
754}
755
756static std::optional<jint> toJavaParity(QSerialPort::Parity parity)
757{
758 switch (parity) {
760 return 0;
762 return 1;
764 return 2;
766 return 3;
768 return 4;
769 }
770
771 return std::nullopt;
772}
773
774static std::optional<FlowControl> toJavaFlowControl(QSerialPort::FlowControl flowControl)
775{
776 switch (flowControl) {
778 return FlowControl::None;
780 return FlowControl::RtsCts;
783 }
784
785 return std::nullopt;
786}
787
788static std::optional<FlowControl> fromJavaFlowControl(jint code)
789{
790 if (code < static_cast<jint>(FlowControl::None) || code > static_cast<jint>(FlowControl::XonXoffInline)) {
791 qCWarning(AndroidSerialLog) << "Unknown flow control code:" << code;
792 return std::nullopt;
793 }
794
795 return static_cast<FlowControl>(code);
796}
797
799 QSerialPort::Parity parity)
800{
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;
806 return Result::Unsupported;
807 }
808
809 return callJavaCommand(s_methods.setParameters, static_cast<jlong>(handle), static_cast<jint>(baudRate),
810 *javaDataBits, *javaStopBits, *javaParity);
811}
812
814{
815 QJniEnvironment env;
816 const jint code =
817 callJava(env, s_methods.getFlowControl, static_cast<jint>(FlowControl::None), static_cast<jlong>(handle));
818 return fromJavaFlowControl(code).value_or(FlowControl::None);
819}
820
822{
823 const std::optional<FlowControl> javaFlowControl = toJavaFlowControl(flowControl);
824 if (!javaFlowControl) {
825 qCWarning(AndroidSerialLog) << "Invalid flow control:" << flowControl;
826 return Result::Unsupported;
827 }
828
829 return callJavaCommand(s_methods.setFlowControl, static_cast<jlong>(handle), static_cast<jint>(*javaFlowControl));
830}
831
832QList<FlowControl> getSupportedFlowControl(PortHandle handle)
833{
834 QList<FlowControl> supported;
835
836 const QList<int> codes = callJavaIntArray(s_methods.getSupportedFlowControl, handle);
837 for (const int code : codes) {
838 if (const std::optional<FlowControl> flowControl = fromJavaFlowControl(code)) {
839 supported.append(*flowControl);
840 }
841 }
842
843 return supported;
844}
845
846bool getXon(PortHandle handle)
847{
848 return callJavaBool(s_methods.getXon, handle);
849}
850
851Result setLatencyTimer(PortHandle handle, int milliseconds)
852{
853 return callJavaCommand(s_methods.setLatencyTimer, static_cast<jlong>(handle), static_cast<jint>(milliseconds));
854}
855
856Result setBreak(PortHandle handle, bool set)
857{
858 return callJavaCommand(s_methods.setBreak, static_cast<jlong>(handle), toJava(set));
859}
860
861Result purgeBuffers(PortHandle handle, QSerialPort::Directions directions)
862{
863 return callJavaCommand(s_methods.purgeBuffers, static_cast<jlong>(handle),
864 toJava(directions.testFlag(QSerialPort::Input)),
865 toJava(directions.testFlag(QSerialPort::Output)));
866}
867
868// ----------------------------------------------------------------------------
869// Control lines
870// ----------------------------------------------------------------------------
871
873{
874 return callJavaCommand(s_methods.setDataTerminalReady, static_cast<jlong>(handle), toJava(set));
875}
876
878{
879 return callJavaCommand(s_methods.setRequestToSend, static_cast<jlong>(handle), toJava(set));
880}
881
882static QSerialPort::PinoutSignals callJavaControlLines(const JavaMethod<jintArray, jlong>& method, PortHandle handle)
883{
884 // By the code that controlLineCode() in QGCUsbSerialManager.java gives each line.
885 static constexpr QSerialPort::PinoutSignal kSignals[] = {
888 };
889
890 QSerialPort::PinoutSignals data = QSerialPort::PinoutSignals();
891
892 const QList<int> lines = callJavaIntArray(method, handle);
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;
896 continue;
897 }
898 data |= kSignals[line];
899 }
900
901 return data;
902}
903
904QSerialPort::PinoutSignals getControlLines(PortHandle handle)
905{
906 return callJavaControlLines(s_methods.getControlLines, handle);
907}
908
910{
911 return getControlLines(handle).testFlag(line);
912}
913
914QSerialPort::PinoutSignals getSupportedControlLines(PortHandle handle)
915{
916 return callJavaControlLines(s_methods.getSupportedControlLines, handle);
917}
918
920{
921 return getSupportedControlLines(handle).testFlag(line);
922}
923
924// ----------------------------------------------------------------------------
925// Self-test support
926// ----------------------------------------------------------------------------
927
928Result echoToCallbacks(PortHandle handle, const char* data, int length, int deliveredLength, int written,
929 ResourceErrorReason reason, const QString& detail)
930{
931 QJniEnvironment env;
932 const auto javaData = toJavaBytes(env, data, length, "echoToCallbacks");
933 const QJniObject javaDetail = QJniObject::fromString(detail);
934 if (!javaData.get() || !javaDetail.isValid()) {
935 return Result::Failed;
936 }
937
938 return callJavaCommand(s_methods.echoToCallbacks, static_cast<jlong>(handle), javaData.get(),
939 static_cast<jint>(deliveredLength), static_cast<jint>(written), static_cast<jint>(reason),
940 javaDetail.object<jstring>());
941}
942
944template <typename Id>
945static void appendUnbound(QStringList& names, const char* kind, const JavaBindingList<Id>& bindings)
946{
947 for (const JavaBinding<Id>* binding = bindings.first; binding; binding = binding->next) {
948 if (!binding->id) {
949 names.append(QStringLiteral("%1 %2 %3")
950 .arg(QLatin1StringView(kind), QLatin1StringView(binding->name),
951 QLatin1StringView(binding->signature)));
952 }
953 }
954}
955
956QStringList unboundJavaNames()
957{
958 QStringList names;
959 if (!getSerialManagerClass()) {
960 names.append(QStringLiteral("class %1").arg(QLatin1StringView(kJniUsbSerialManagerClassName)));
961 return names;
962 }
963
964 appendUnbound(names, "method", s_javaMethods);
965 appendUnbound(names, "field", s_javaFields);
966 return names;
967}
968
969} // namespace AndroidSerial
static DeviceWatcher * instance()
static QString portNameFromSystemLocation(const QString &systemLocation)
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
Definition JavaBinding.h:48
JavaBindingList< jfieldID > s_javaFields
Definition JavaBinding.h:49
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.
Definition JavaBinding.h:20
JavaBinding< Id > * first
Definition JavaBinding.h:21
const char *const name
Definition JavaBinding.h:40
A field of QGCUsbSerialPortInfo.java, declared by its JNI type, from which its signature is derived.
Definition JavaBinding.h:88
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.
Definition JavaBinding.h:67
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< jboolean > hardwareFlowControl
JavaField< jstring > manufacturerName
What is known of a port.