+
+bool OpenProxmark(void *port, bool wait_for_port, int timeout, bool flash_mode) {
+ char *portname = (char *)port;
+ if (!wait_for_port) {
+ sp = uart_open(portname);
+ } else {
+ printf("Waiting for Proxmark to appear on %s ", portname);
+ fflush(stdout);
+ int openCount = 0;
+ do {
+ sp = uart_open(portname);
+ msleep(1000);
+ printf(".");
+ fflush(stdout);
+ } while(++openCount < timeout && (sp == INVALID_SERIAL_PORT || sp == CLAIMED_SERIAL_PORT));
+ printf("\n");
+ }
+
+ // check result of uart opening
+ if (sp == INVALID_SERIAL_PORT) {
+ printf("ERROR: invalid serial port\n");
+ sp = NULL;
+ serial_port_name = NULL;
+ return false;
+ } else if (sp == CLAIMED_SERIAL_PORT) {
+ printf("ERROR: serial port is claimed by another process\n");
+ sp = NULL;
+ serial_port_name = NULL;
+ return false;
+ } else {
+ // start the USB communication thread
+ serial_port_name = portname;
+ conn.run = true;
+ conn.block_after_ACK = flash_mode;
+ pthread_create(&USB_communication_thread, NULL, &uart_communication, &conn);
+ return true;
+ }
+}
+
+
+void CloseProxmark(void) {
+ conn.run = false;
+
+#ifdef __BIONIC__
+ // In Android O and later, if an invalid pthread_t is passed to pthread_join, it calls fatal().
+ // https://github.com/aosp-mirror/platform_bionic/blob/ed16b344e75f422fb36fbfd91fb30de339475880/libc/bionic/pthread_internal.cpp#L116-L128
+ //
+ // In Bionic libc, pthread_t is an integer.
+
+ if (USB_communication_thread != 0) {
+ pthread_join(USB_communication_thread, NULL);
+ }
+#else
+ // pthread_t is a struct on other libc, treat as an opaque memory reference
+ pthread_join(USB_communication_thread, NULL);
+#endif
+
+ if (sp) {
+ uart_close(sp);
+ }
+
+#if defined(__linux__) && !defined(NO_UNLINK)
+ // Fix for linux, it seems that it is extremely slow to release the serial port file descriptor /dev/*
+ //
+ // This may be disabled at compile-time with -DNO_UNLINK (used for a JNI-based serial port on Android).
+ if (serial_port_name) {
+ unlink(serial_port_name);
+ }
+#endif
+
+ // Clean up our state
+ sp = NULL;
+ serial_port_name = NULL;
+#ifdef __BIONIC__
+ memset(&USB_communication_thread, 0, sizeof(pthread_t));
+#endif
+}
+
+