private async Task SendTxData() { logger.Info(">SendTx Ready:" + Name); FTDI.FT_STATUS ftStatus = FTDI.FT_STATUS.FT_OTHER_ERROR; USBMsg msg = null; UInt32 numBytesWritten = 0; while (!cts.IsCancellationRequested) { if ((pendMsgs.Count > 0) && ((avl - sentMsgs.Count) > 10)) { pendMsgs.TryTake(out msg); msg.seq = ++nxtseq; sentMsgs.Enqueue(msg); string hex = "Send: " + Name + ": "; int siz = msg.size; for (int ptr = 0; ptr < siz; ptr++) { hex += " " + msg.msg[ptr].ToString("x2"); } logger.Info(hex); ftStatus = myFtdiDevice.Write(msg.msg, msg.size, ref numBytesWritten); if (ftStatus != FTDI.FT_STATUS.FT_OK) { logger.Error("<failure: " + Name + ":" + ftStatus.ToString()); } else { logger.Info(string.Format("< {0:x2}", msg.seq)); } } else { await Task.Delay(5); } } logger.Info(">SendTx Closed:" + Name); tkn.ThrowIfCancellationRequested(); }
private async Task ShowRxData() { logger.Info(">ShowRx Ready: " + Name); FTDI.FT_STATUS ftStatus = FTDI.FT_STATUS.FT_OTHER_ERROR; UInt32 numBytesAvailable = 0; byte[] resp = new byte[4]; byte cod = 0; byte seq = 0; byte cnt = 0; byte chk = 0; USBMsg msg = null; UInt32 numBytesRead = 0; try { ManualResetEventSlim hdl = new ManualResetEventSlim(false); while (!cts.IsCancellationRequested) { ftStatus = myFtdiDevice.GetRxBytesAvailable(ref numBytesAvailable); if (ftStatus != FTDI.FT_STATUS.FT_OK) { // Wait for a key press logger.Error("Failed to get number of bytes available to read:" + Name + " (error " + ftStatus.ToString() + ")"); throw new InvalidOperationException("Failed to get number of bytes available to read"); } if (numBytesAvailable > 3) { ftStatus = myFtdiDevice.Read(resp, numBytesAvailable, ref numBytesRead); if (ftStatus != FTDI.FT_STATUS.FT_OK) { // Wait for a key press logger.Error("Failed to read data:" + Name + " (error " + ftStatus.ToString() + ")"); } cod = resp[0]; seq = resp[1]; cnt = resp[2]; chk = resp[3]; logger.Info(string.Format("Recv: {4}: {0:x2} {1:x2} {2:x2} {3:x2}", cod, seq, cnt, chk, Name)); switch (cod) { case 0x80: if (sentMsgs.TryPeek(out msg)) { if (msg.seq == seq) { if (sentMsgs.TryDequeue(out msg)) { bufrPool.Add(msg); } } } avl = cnt; if (avl > maxavl) { maxavl = avl; } break; case 0x90: avl = cnt; if (avl > maxavl) { maxavl = avl; } break; default: logger.Error(string.Format(">Invalid resp: {4}: {0:x2} {1:x2} {2:x2} {3:x2}", cod, seq, cnt, chk, Name)); break; } } else { //using (EventWaitHandle hdl = new EventWaitHandle(false, EventResetMode.ManualReset)) //{ // myFtdiDevice.SetEventNotification(0, hdl); // hdl.WaitOne(500); //} hdl.Reset(); //myFtdiDevice.SetEventNotification(FTD2XX_NET.FTDI.FT_EVENTS.FT_EVENT_RXCHAR, hdl.WaitHandle); hdl.Wait(-1, tkn); //WaitHandle.WaitAny(new WaitHandle[] { hdl.WaitHandle, tkn.WaitHandle }, -1); await hdl.WaitHandle.WaitOneAsync(tkn); } } } finally { } tkn.ThrowIfCancellationRequested(); }