-void main_loop(char *script_cmds_file, char* script_cmd, bool usb_present, serial_port* sp) {
- receiver_arg conn;
- char *cmd = NULL;
- pthread_t reader_thread;
- bool execCommand = (script_cmd != NULL);
- bool stdinOnPipe = !isatty(STDIN_FILENO);
+// a global mutex to prevent interlaced printing from different threads
+pthread_mutex_t print_lock;
+
+static serial_port sp;
+static UsbCommand txcmd;
+volatile static bool txcmd_pending = false;
+
+void SendCommand(UsbCommand *c) {
+ #if 0
+ printf("Sending %d bytes\n", sizeof(UsbCommand));
+ #endif
+
+ if (offline) {
+ PrintAndLog("Sending bytes to proxmark failed - offline");
+ return;
+ }
+ /**
+ The while-loop below causes hangups at times, when the pm3 unit is unresponsive
+ or disconnected. The main console thread is alive, but comm thread just spins here.
+ Not good.../holiman
+ **/
+ while(txcmd_pending);
+ txcmd = *c;
+ txcmd_pending = true;
+}
+
+struct receiver_arg {
+ int run;
+};
+
+byte_t rx[sizeof(UsbCommand)];
+byte_t* prx = rx;
+
+
+static void
+#ifdef __has_attribute
+#if __has_attribute(force_align_arg_pointer)
+__attribute__((force_align_arg_pointer))
+#endif
+#endif
+*uart_receiver(void *targ) {
+ struct receiver_arg *arg = (struct receiver_arg*)targ;
+ size_t rxlen;
+
+ while (arg->run) {
+ rxlen = 0;
+ if (uart_receive(sp, prx, sizeof(UsbCommand) - (prx-rx), &rxlen) && rxlen) {
+ prx += rxlen;
+ if (prx-rx < sizeof(UsbCommand)) {
+ continue;
+ }
+ UsbCommandReceived((UsbCommand*)rx);
+ }
+ prx = rx;