Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
194 views
in Technique[技术] by (71.8m points)

C# pass data between functions

I'm trying to write a code that will write the data coming from an external device (USB) to a file. I have a function that receives data in a separate task ReadAvailable and I don't know how to pass this data in a correct way to the SaveRxDataToFile function. The write function must also know how much data it is adding each time to the file in order to know when to end the write. (I'm learning and maybe it's something simple, but I'm a little lost)

Could you please help?

Here is the code:

using FTD2XX_NET;
using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.IO;


namespace Engine
{
    public class FtdiFifo
    {

        private FTDI ftHandle = new FTDI();
        private FTDI.FT_DEVICE_INFO_NODE[] deviceInfos = new FTDI.FT_DEVICE_INFO_NODE[2];

        public byte[] RxDataBuffer { get; set; } = new byte[65536];

        public List<string> serialNumbers { get; set; }

        public FtdiFifo()
        {
            System.Diagnostics.Debug.WriteLine("This is a new FtdiFifo object.");
            serialNumbers = new List<string>();

        }

        public void IdentifyDevice()
        {
            FTDI.FT_STATUS ftdiStatus;
            uint ftdiDeviceCount = 0;
            serialNumbers.Clear();

            ftdiStatus = ftHandle.GetNumberOfDevices(ref ftdiDeviceCount);
            if (ftdiDeviceCount > 0)
            {
                System.Diagnostics.Debug.WriteLine("Number of FTDI devices: " + ftdiDeviceCount.ToString());
            }
            else if (ftdiDeviceCount == 0) // If no devices available, return
            {
                System.Diagnostics.Debug.WriteLine("No FTDI device detected (" + ftdiStatus.ToString() + ")");
                return;
            }


            ftdiStatus = ftHandle.GetDeviceList(deviceInfos);
            if (ftdiStatus == FTDI.FT_STATUS.FT_OK)
            {
                for (UInt32 i = 0; i < ftdiDeviceCount; i++)
                {
                    System.Diagnostics.Debug.WriteLine("Device Index: " + i.ToString());
                    System.Diagnostics.Debug.WriteLine("Flags: " + String.Format("{0:x}", deviceInfos[i].Flags));
                    System.Diagnostics.Debug.WriteLine("Type: " + deviceInfos[i].Type.ToString());
                    System.Diagnostics.Debug.WriteLine("ID: " + String.Format("{0:x}", deviceInfos[i].ID));
                    System.Diagnostics.Debug.WriteLine("Location ID: " + String.Format("{0:x}", deviceInfos[i].LocId));
                    System.Diagnostics.Debug.WriteLine("Serial Number: " + deviceInfos[i].SerialNumber.ToString());
                    System.Diagnostics.Debug.WriteLine("Description: " + deviceInfos[i].Description.ToString());
                    System.Diagnostics.Debug.WriteLine("");

                    serialNumbers.Add(deviceInfos[i].SerialNumber.ToString());
                }
            }

            return;
        }



        public void SetFifoMode()
        {
            FTDI.FT_STATUS ftStatus;
            ftStatus = ftHandle.OpenBySerialNumber(serialNumbers[1]);
            if (ftStatus != FTDI.FT_STATUS.FT_OK)
            {
                System.Diagnostics.Debug.WriteLine("Cannot open device");
                return;
            }

            ftStatus = ftHandle.SetTimeouts(5000, 5000);

            System.Threading.Thread.Sleep(100);
            ftStatus = ftHandle.SetBitMode(0xff, 0x00);
            if (ftStatus != FTDI.FT_STATUS.FT_OK)
            {
                System.Diagnostics.Debug.WriteLine("Cannot set bit mode");
                return;
            }

            System.Threading.Thread.Sleep(100);
            ftStatus = ftHandle.SetBitMode(0xff, 0x40);
            if (ftStatus != FTDI.FT_STATUS.FT_OK)
            {
                System.Diagnostics.Debug.WriteLine("Cannot set ftStatus");
                return;
            }

            System.Threading.Thread.Sleep(100);
            ftStatus = ftHandle.SetLatency(2);
            if (ftStatus != FTDI.FT_STATUS.FT_OK)
            {
                System.Diagnostics.Debug.WriteLine("Cannot set latency");
                return;
            }

            System.Threading.Thread.Sleep(100);
            ftStatus = ftHandle.InTransferSize(0x10000);
            if (ftStatus != FTDI.FT_STATUS.FT_OK)
            {
                System.Diagnostics.Debug.WriteLine("Cannot set In transfer size");
                return;
            }

            System.Threading.Thread.Sleep(100);
            ftStatus = ftHandle.SetFlowControl(FTDI.FT_FLOW_CONTROL.FT_FLOW_RTS_CTS, 0, 0);
            if (ftStatus != FTDI.FT_STATUS.FT_OK)
            {
                System.Diagnostics.Debug.WriteLine("Cannot set flow control");
                return;
            }

            System.Threading.Thread.Sleep(100);
            ftStatus = ftHandle.Purge(FTDI.FT_PURGE.FT_PURGE_RX);
            if (ftStatus != FTDI.FT_STATUS.FT_OK)
            {
                System.Diagnostics.Debug.WriteLine("Cannot purge FTDI");
                return;
            }

            System.Diagnostics.Debug.WriteLine("Synchronous FIFO mode enabled for " + serialNumbers[1]);


            // Create a task and supply a user delegate by using a lambda expression.
            Task taskA = new Task(() => ReceiveLoop());
            // Start the task.
            taskA.Start();

            System.Diagnostics.Debug.WriteLine("ReceiveLoop enabled");
        }


        public bool IsDeviceAllowed(string allowedDevice)
        {
            foreach (string device in serialNumbers)
            {
                if (device == allowedDevice)
                {
                    System.Diagnostics.Debug.WriteLine("Allowed device");
                    return true;
                }
            }

            System.Diagnostics.Debug.WriteLine("No allowed device");
            return false;
        }



        void ReadAvailable()
        {
            FTDI.FT_STATUS ftStatus;
            UInt32 numBytesAvailable = 0;

            ftStatus = ftHandle.GetRxBytesAvailable(ref numBytesAvailable);
            System.Diagnostics.Debug.WriteLine(ftStatus + "  bytes available: " + numBytesAvailable.ToString());

            if (numBytesAvailable < 1)
            {
                System.Diagnostics.Debug.WriteLine("NO_READ_DATA_AVAILABLE
");
                return;
            }

            byte[] bytes = new byte[numBytesAvailable];
            UInt32 numBytesRead = 0;
            ftHandle.Read(bytes, numBytesAvailable, ref numBytesRead);
            if (numBytesAvailable != numBytesRead)
                System.Diagnostics.Debug.WriteLine("Something bad happened");

            System.Diagnostics.Debug.WriteLine("Dec: " + String.Join(" ", bytes) + "
Hex: " + BitConverter.ToString(bytes).Replace("-", string.Empty) + "
Text: " + Encoding.Default.GetString(bytes) + "
");

        }

        public void ReceiveLoop()
        {
            var receivedDataEvent = new AutoResetEvent(false);
            ftHandle.SetEventNotification(FTDI.FT_EVENTS.FT_EVENT_RXCHAR, receivedDataEvent);

            //var cancellation = new CancellationTokenSource();  // should be declared in a broader scope
            //while (!_cancellation.IsCancellationRequested)
            while (true)
            {
                receivedDataEvent.WaitOne();
                ReadAvailable();
            }
        }


        public void SaveRxDataToFile(byte[] rxData)
        {

            String filename = DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss_readout") + ".bin";

            const int dataLengthTotal = 1024000;
            int dataLength = 0;
            do
            {

                using (var fileStream = new FileStream(filename, FileMode.Append, FileAccess.Write, FileShare.Write))
                {
                    fileStream.Write(rxData, dataLength, rxData.Length);
                }
                dataLength += rxData.Length;

            } while (dataLength < dataLengthTotal);



        }
    }
}
question from:https://stackoverflow.com/questions/65672044/c-sharp-pass-data-between-functions

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...