Ejemplo n.º 1
0
    private IEnumerator FreiburgPulse()
    {
        while (true)
        {
            yield return(new WaitForSeconds(Random.Range(TIME_BETWEEN_PULSES_MIN, TIME_BETWEEN_PULSES_MAX)));

            int claimInterfaceResult = MonoUsbApi.ClaimInterface(freiburgSyncboxDeviceHandle, FREIBURG_SYNCBOX_INTERFACE_NUMBER);
            int actual_length;
            int bulkTransferResult = MonoUsbApi.BulkTransfer(freiburgSyncboxDeviceHandle, FREIBURG_SYNCBOX_ENDPOINT, byte.MinValue, FREIBURG_SYNCBOX_PIN_COUNT / 8, out actual_length, FREIBURG_SYNCBOX_TIMEOUT_MS);
            if (bulkTransferResult == 0)
            {
                LogPulse();
            }
            Debug.Log("Sync pulse. " + actual_length.ToString() + " byte(s) written.");

            MonoUsbApi.ReleaseInterface(freiburgSyncboxDeviceHandle, FREIBURG_SYNCBOX_INTERFACE_NUMBER);

            if (claimInterfaceResult != 0 || bulkTransferResult != 0)
            {
                break;
            }
        }

        Debug.Log("Restarting sync session.");
        EndFreiburgSyncSession();
        BeginFreiburgSyncSession();
    }
Ejemplo n.º 2
0
        private int SendInternal(byte[] buffer)
        {
            var handle = getUsableAndOpenUsbHandle();

            if (handle == null)
            {
                throw new Exception("USB writer is null, you may have disconnected the device during previous function");
            }

            uint pack = (uint)buffer.Length + 2;

            byte[] packed = BitConverter.GetBytes(pack);
            var    ec     = MonoUsbApi.BulkTransfer(handle, WRITEPOINT, packed, packed.Length, out var _, 5000);

            if (ec != 0)
            {
                string err = MonoUsbSessionHandle.LastErrorString;
                CleanUpHandle(handle);
                throw new Exception(err);
            }
            ec = MonoUsbApi.BulkTransfer(handle, WRITEPOINT, buffer, buffer.Length, out var len, 5000);
            if (ec != 0)
            {
                string err = MonoUsbSessionHandle.LastErrorString;
                CleanUpHandle(handle);
                throw new Exception(err);
            }

            CleanUpHandle(handle);
            return(len);
        }
Ejemplo n.º 3
0
        private static void SendData(MonoUsbDeviceHandle rapidradio, int endpoint, byte[] data, int length, int timeout = 1000000)
        {
            Marshal.Copy(data, 0, _unmanagedWriteBuff, Math.Min(length, 32));

            int transferred;
            var r = MonoUsbApi.BulkTransfer(rapidradio,
                                            (byte)endpoint,
                                            _unmanagedWriteBuff,
                                            length,
                                            out transferred,
                                            timeout);

            if (r != (int)MonoUsbError.Success)
            {
                throw new Exception("Error while sending: " + GetErrorMessage(r));
            }
        }
Ejemplo n.º 4
0
        private int ReadInternal(byte[] buffer)
        {
            var handle = getUsableAndOpenUsbHandle();

            if (handle == null)
            {
                throw new Exception("USB writer is null, you may have disconnected the device during previous function");
            }

            byte[] sizeOfReturn = new byte[4];

            MonoUsbApi.BulkTransfer(handle, READPOINT, sizeOfReturn, 4, out var _, 5000);

            // read stack
            MonoUsbApi.BulkTransfer(handle, READPOINT, buffer, buffer.Length, out var len, 5000);
            CleanUpHandle(handle);
            return(len);
        }
Ejemplo n.º 5
0
        private static int ReadData(MonoUsbDeviceHandle rapidradio, int endpoint, byte[] data, int length, int timeout = 1)
        {
            int transferred;
            var r = MonoUsbApi.BulkTransfer(rapidradio,
                                            (byte)(endpoint + 0x80),
                                            _unmanagedReadBuff,
                                            length,
                                            out transferred,
                                            timeout);

            if (r != (int)MonoUsbError.Success && r != (int)MonoUsbError.ErrorTimeout)
            {
                throw new Exception("Error while reading: " + GetErrorMessage(r));
            }

            Marshal.Copy(_unmanagedReadBuff, data, 0, Math.Min(transferred, 32));

            return(transferred);
        }
Ejemplo n.º 6
0
        protected override void SpiWrite(byte[] txBuf, int length)
        {
            int sentLength = 0;

            while (sentLength < length)
            {
                int size = Math.Min(BUF_SIZE, length - sentLength);
                Buffer.BlockCopy(txBuf, sentLength, outData, 0, size);

                int transferred;
                MonoUsbApi.BulkTransfer(deviceHandle, 0x01, outData, size, out transferred, TIMEOUT);
                if (transferred > 0)
                {
                    MonoUsbApi.BulkTransfer(deviceHandle, 0x81, inData, size, out transferred, TIMEOUT);
                }

                sentLength += size;
            }
        }
Ejemplo n.º 7
0
        protected override void SpiRead(byte[] rxBuf, int length)
        {
            for (int i = 0; i < outData.Length; i++)
            {
                outData[i] = 0x4a;
            }

            int sentLength = 0;

            while (sentLength < length)
            {
                int size = Math.Min(BUF_SIZE, length - sentLength);

                int transferred;
                MonoUsbApi.BulkTransfer(deviceHandle, 0x01, outData, size, out transferred, TIMEOUT);
                if (transferred > 0)
                {
                    MonoUsbApi.BulkTransfer(deviceHandle, 0x81, inData, transferred, out transferred, TIMEOUT);
                }

                Buffer.BlockCopy(inData, 0, rxBuf, sentLength, size);
                sentLength += size;
            }
        }
Ejemplo n.º 8
0
        public static int Main(string[] args)
        {
            MonoUsbDeviceHandle device_handle = null;

            int r = 0;
            int transferred;

            byte[] testWriteData = new byte[TEST_WRITE_LEN];
            byte[] testReadData  = new byte[TEST_READ_LEN];

            if (args.Length > 0)
            {
                switch (args[0].ToLower())
                {
                case "sync":
                    TEST_MODE = TestMode.Sync;
                    break;

                case "async":
                    TEST_MODE = TestMode.Async;
                    break;
                }
            }

            fillTestData(testWriteData, TEST_WRITE_LEN);
            memset(testReadData, 0, TEST_READ_LEN);

            int loopCount = 0;

            do
            {
                try
                {
                    do
                    {
                        sessionHandle = new MonoUsbSessionHandle();
                        if (sessionHandle.IsInvalid)
                        {
                            throw new Exception("Invalid session handle.");
                        }

                        Console.WriteLine("Opening Device..");
                        device_handle = MonoUsbApi.OpenDeviceWithVidPid(sessionHandle, MY_VID, MY_PID);
                        if ((device_handle == null) || device_handle.IsInvalid)
                        {
                            break;
                        }

                        // If TEST_REST_DEVICE = True, reset the device and re-open
                        if (TEST_REST_DEVICE)
                        {
                            MonoUsbApi.ResetDevice(device_handle);
                            device_handle.Close();
                            device_handle = MonoUsbApi.OpenDeviceWithVidPid(sessionHandle, MY_VID, MY_PID);
                            if ((device_handle == null) || device_handle.IsInvalid)
                            {
                                break;
                            }
                        }

                        // Set configuration
                        Console.WriteLine("Set Config..");
                        r = MonoUsbApi.SetConfiguration(device_handle, MY_CONFIG);
                        if (r != 0)
                        {
                            break;
                        }

                        // Claim interface
                        Console.WriteLine("Set Interface..");
                        r = MonoUsbApi.ClaimInterface(device_handle, MY_INTERFACE);
                        if (r != 0)
                        {
                            break;
                        }

                        /////////////////////
                        // Write test data //
                        /////////////////////
                        int packetCount      = 0;
                        int transferredTotal = 0;
                        do
                        {
                            Console.WriteLine("Sending test data..");

                            // If the Async TEST_MODE enumeration is set, use
                            // the internal transfer function
                            if (TEST_MODE == TestMode.Async)
                            {
                                r = (int)doBulkAsyncTransfer(device_handle,
                                                             MY_EP_WRITE,
                                                             testWriteData,
                                                             TEST_WRITE_LEN,
                                                             out transferred,
                                                             MY_TIMEOUT);
                            }
                            else
                            {
                                // Use the sync bulk transfer API function
                                r = MonoUsbApi.BulkTransfer(device_handle,
                                                            MY_EP_WRITE,
                                                            testWriteData,
                                                            TEST_WRITE_LEN,
                                                            out transferred,
                                                            MY_TIMEOUT);
                            }
                            if (r == 0)
                            {
                                packetCount++;
                                transferredTotal += transferred;
                            }
                            // Keep writing data until an error occurs or
                            // 4 packets have been sent.
                        } while (r == 0 && packetCount < 5);


                        if (r == (int)MonoUsbError.ErrorTimeout)
                        {
                            // This is considered normal operation
                            Console.WriteLine("Write Timed Out. {0} packet(s) written ({1} bytes)", packetCount, transferredTotal);
                        }
                        else if (r != (int)MonoUsbError.ErrorTimeout && r != 0)
                        {
                            // An error, other than ErrorTimeout was received.
                            Console.WriteLine("Write failed:{0}", (MonoUsbError)r);
                            break;
                        }
                        ////////////////////
                        // Read test data //
                        ////////////////////
                        Console.WriteLine("Reading test data..");
                        packetCount      = 0;
                        transferredTotal = 0;
                        do
                        {
                            // If the Async TEST_MODE enumeration is set, use
                            // the internal transfer function
                            if (TEST_MODE == TestMode.Async)
                            {
                                r = (int)doBulkAsyncTransfer(device_handle,
                                                             MY_EP_READ,
                                                             testReadData,
                                                             TEST_READ_LEN,
                                                             out transferred,
                                                             MY_TIMEOUT);
                            }
                            else
                            {
                                // Use the sync bulk transfer API function
                                r = MonoUsbApi.BulkTransfer(device_handle,
                                                            MY_EP_READ,
                                                            testReadData,
                                                            TEST_READ_LEN,
                                                            out transferred,
                                                            MY_TIMEOUT);
                            }
                            if (r == (int)MonoUsbError.ErrorTimeout)
                            {
                                // This is considered normal operation
                                Console.WriteLine("Read Timed Out. {0} packet(s) read ({1} bytes)", packetCount, transferredTotal);
                            }
                            else if (r != 0)
                            {
                                // An error, other than ErrorTimeout was received.
                                Console.WriteLine("Read failed:{0}", (MonoUsbError)r);
                            }
                            else
                            {
                                transferredTotal += transferred;
                                packetCount++;

                                // Display test data.
                                Console.Write("Received: ");
                                Console.WriteLine(System.Text.Encoding.Default.GetString(testReadData, 0, transferred));
                            }
                            // Keep reading data until an error occurs, (ErrorTimeout)
                        } while (r == 0);
                    } while (false);
                }
                finally
                {
                    // Free and close resources
                    if (device_handle != null)
                    {
                        if (!device_handle.IsInvalid)
                        {
                            MonoUsbApi.ReleaseInterface(device_handle, MY_INTERFACE);
                            device_handle.Close();
                        }
                    }
                    if (sessionHandle != null)
                    {
                        sessionHandle.Close();
                        sessionHandle = null;
                    }
                }
                // Run the entire test TEST_LOOP_COUNT times.
            } while (++loopCount < TEST_LOOP_COUNT);

            Console.WriteLine("\nDone!  [Press any key to exit]");
            Console.ReadKey();

            return(r);
        }
Ejemplo n.º 9
0
        public BorIPDevice(CyUSBDevice usbDevice, MonoUsbProfile usbProfile, EDeviceType deviceType)
            : base(usbDevice, usbProfile, deviceType)
        {
            if (deviceType == EDeviceType.ADC)
            {
                byte[] response = ReceiveVendorResponse((byte)EVendorRequests.DeviceParam, 2);
                dataPortNo = (ushort)(response[0] + (response[1] << 8));
            }
            else
            {
                byte[] response = ReceiveVendorResponse((byte)EVendorRequests.DeviceParam, 4);
                dataPortNo    = (ushort)(response[0] + (response[1] << 8));
                ControlPortNo = (ushort)(response[2] + (response[3] << 8));
            }

            Console.WriteLine($"+ {this}");


            var ct = Cts.Token;

            Task.Run(() =>
            {
                TcpListener listener = BorIPCreateListener(BORIP_SERVERPORT);
                try
                {
                    listener.Start();
                    var addresses = Dns.GetHostAddresses(Dns.GetHostName())
                                    .Where(p => p.ToString().Contains('.'));
                    Console.WriteLine($"{BORIP_SERVERPORT}: {string.Join(" ", addresses)}");

                    CancellationTokenSource tcpCts = null;
                    while (!ct.IsCancellationRequested)
                    {
                        TcpClient client = listener.AcceptTcpClient();
                        Console.WriteLine($"{BORIP_SERVERPORT}: accepted");

                        if (tcpCts != null)
                        {
                            tcpCts.Cancel();
                        }

                        tcpCts    = new CancellationTokenSource();
                        var tcpCt = tcpCts.Token;
                        Task.Run(() =>
                        {
                            BorIPClient borIPClient = new BorIPClient(client);
                            borIPClients.Add(borIPClient);
                            try
                            {
                                using (NetworkStream ns = client.GetStream())
                                    using (StreamReader sr = new StreamReader(ns, Encoding.ASCII))
                                        using (StreamWriter sw = new StreamWriter(ns, Encoding.ASCII))
                                        {
                                            BorIPWriteLine(sw, "DEVICE -");

                                            while (!tcpCt.IsCancellationRequested)
                                            {
                                                string str = sr.ReadLine();
                                                if (string.IsNullOrWhiteSpace(str))
                                                {
                                                    return;                                     // keep alive
                                                }
                                                Console.WriteLine($"{BORIP_SERVERPORT}: [in] {str.Trim()}");

                                                BorIPProcessInput(borIPClient, sw, str);
                                            }
                                        }
                            }
                            catch (Exception)
                            {
                                // nothing to do
                            }
                            finally
                            {
                                borIPClients.Remove(borIPClient);
                                Console.WriteLine($"{BORIP_SERVERPORT}: closed");
                            }
                        }, tcpCt);
                    }
                }
                catch (SocketException ex) when(ex.ErrorCode == 10004)
                {
                    // nothing to do
                }
                catch (OperationCanceledException)
                {
                    // nothing to do
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"{BORIP_SERVERPORT}: {ex.Message}");
                }
                finally
                {
                    listener.Stop();
                    //Console.WriteLine($"{BORIP_PORTNO}: listener stopped");
                }
            }, ct);


            if (USBDevice != null)
            {
                endpoint2 = USBDevice.EndPointOf(0x82) as CyBulkEndPoint;
            }

            Task.Run(() =>
            {
                while (!ct.IsCancellationRequested)
                {
                    if (borIPClients.Count == 0 && (ControlPortNo > 0 && controlClients.Count == 0))
                    {
                        Thread.Sleep(100);
                        continue;
                    }

                    UdpClient udp = new UdpClient();
                    try
                    {
                        int maxPacketSize;
                        if (USBDevice != null)
                        {
                            maxPacketSize = endpoint2.MaxPktSize;
                        }
                        else
                        {
                            maxPacketSize = MonoUsbApi.GetMaxPacketSize(USBProfile.ProfileHandle, 0x82);
                        }
                        byte[] inData    = new byte[maxPacketSize];
                        byte[] outData   = null;
                        int outDataPos   = 0;
                        byte[] borIPData = null;
                        int borIPDataPos = 0;

                        while (!ct.IsCancellationRequested &&
                               !(borIPClients.Count == 0 && (ControlPortNo > 0 && controlClients.Count == 0)))
                        {
                            int xferLen = inData.Length;
                            bool ret    = false;
                            if (USBDevice != null)
                            {
                                ret = endpoint2.XferData(ref inData, ref xferLen);
                            }
                            else
                            {
                                ret = MonoUsbApi.BulkTransfer(MonoDeviceHandle, 0x82, inData, inData.Length, out xferLen, TIMEOUT) == 0;
                            }
                            if (ret == false)
                            {
                                break;
                            }

                            int inDataPos = 0;
                            while (!ct.IsCancellationRequested && inDataPos < xferLen)
                            {
                                if (outData == null)
                                {
                                    outData = new byte[1472];
                                }
                                if (borIPData == null)
                                {
                                    borIPData = new byte[4 + 4 * NUM_SAMPLES];
                                    borIPData[borIPDataPos++] = (byte)((RunningState == ERunningState.Start) ? 0x10 : 0x00);
                                    RunningState = ERunningState.Continued;
                                    borIPData[borIPDataPos++] = 0;
                                    borIPData[borIPDataPos++] = (byte)(sequence & 0xff);
                                    borIPData[borIPDataPos++] = (byte)((sequence >> 8) & 0xff);
                                }

                                while (outDataPos < outData.Length && borIPDataPos < borIPData.Length && inDataPos < xferLen)
                                {
                                    byte b = inData[inDataPos++];
                                    outData[outDataPos++]     = b;
                                    borIPData[borIPDataPos++] = b;
                                }

                                if (borIPDataPos == borIPData.Length)
                                {
                                    List <string> remoteAddrList = new List <string>();
                                    foreach (var client in borIPClients.ToArray())
                                    {
                                        if (client.Header)
                                        {
                                            string remoteAddr;
                                            try
                                            {
                                                remoteAddr = client.DestAddr;
                                            }
                                            catch
                                            {
                                                continue;
                                            }

                                            if (remoteAddrList.Contains(remoteAddr) == false)
                                            {
                                                remoteAddrList.Add(remoteAddr);
                                                udp.Send(borIPData, borIPData.Length, remoteAddr, client.DestPort);
                                            }
                                        }
                                    }

                                    sequence++;
                                    if (sequence == 0x10000)
                                    {
                                        sequence = 0;
                                    }

                                    borIPData    = null;
                                    borIPDataPos = 0;
                                }

                                if (outDataPos == outData.Length)
                                {
                                    List <string> remoteAddrList = new List <string>();
                                    foreach (var client in borIPClients.ToArray())
                                    {
                                        if (client.Header == false)
                                        {
                                            string remoteAddr;
                                            try
                                            {
                                                remoteAddr = client.DestAddr;
                                            }
                                            catch
                                            {
                                                continue;
                                            }

                                            if (remoteAddrList.Contains(remoteAddr) == false)
                                            {
                                                remoteAddrList.Add(remoteAddr);
                                                udp.Send(outData, outData.Length, remoteAddr, client.DestPort);
                                            }
                                        }
                                    }

                                    remoteAddrList.Clear();
                                    foreach (var client in controlClients.ToArray())
                                    {
                                        string remoteAddr;
                                        try
                                        {
                                            remoteAddr = ((IPEndPoint)client.Client.RemoteEndPoint).Address.ToString();
                                        }
                                        catch
                                        {
                                            continue;
                                        }

                                        if (remoteAddrList.Contains(remoteAddr) == false)
                                        {
                                            remoteAddrList.Add(remoteAddr);
                                            udp.Send(outData, outData.Length, remoteAddr, dataPortNo);
                                        }
                                    }

                                    if (ControlPortNo == 0)
                                    {
                                        udp.Send(outData, outData.Length, "127.0.0.1", dataPortNo);
                                    }

                                    outData    = null;
                                    outDataPos = 0;
                                }
                            }
                        }
                    }
                    catch (OperationCanceledException)
                    {
                        // nothing to do
                    }
                    //catch (Exception ex)
                    //{
                    //	Console.WriteLine($"BorIP: {ex.Message}");
                    //}
                    finally
                    {
                        udp.Close();
                    }

                    Thread.Sleep(1000);
                }
            }, ct);
        }
Ejemplo n.º 10
0
        public DACDevice(CyUSBDevice usbDevice, MonoUsbProfile usbProfile, EDeviceType deviceType)
            : base(usbDevice, usbProfile, deviceType)
        {
            if (deviceType == EDeviceType.DAC)
            {
                byte[] response = ReceiveVendorResponse((byte)EVendorRequests.DeviceParam, 2);
                dataPortNo = (ushort)(response[0] + (response[1] << 8));
            }
            else
            {
                byte[] response = ReceiveVendorResponse((byte)EVendorRequests.DeviceParam, 4);
                dataPortNo    = (ushort)(response[0] + (response[1] << 8));
                ControlPortNo = (ushort)(response[2] + (response[3] << 8));
            }

            Console.WriteLine($"+ {this}");

            if (USBDevice != null)
            {
                endpoint2 = USBDevice.EndPointOf(0x02) as CyBulkEndPoint;
            }

            var ct = Cts.Token;

            Task.Run(() =>
            {
                try
                {
                    while (!ct.IsCancellationRequested)
                    {
                        if (ControlPortNo > 0 && controlClients.Count == 0)
                        {
                            Thread.Sleep(100);
                            continue;
                        }

                        TcpClient client = null;
                        try
                        {
                            string remoteAddr;
                            if (ControlPortNo == 0)
                            {
                                remoteAddr = "127.0.0.1";
                            }
                            else
                            {
                                try
                                {
                                    remoteAddr = ((IPEndPoint)controlClients[0].Client.RemoteEndPoint).Address.ToString();
                                }
                                catch
                                {
                                    continue;
                                }
                            }
                            client = new TcpClient(remoteAddr, dataPortNo);
                        }
                        catch (SocketException ex)
                        {
                            if (ex.ErrorCode == 10061)
                            {
                                Thread.Sleep(1000);
                                continue;
                            }

                            throw ex;
                        }
                        Console.WriteLine($"{dataPortNo}: accepted",
                                          DeviceType,
                                          ((IPEndPoint)client.Client.RemoteEndPoint).Address,
                                          ((IPEndPoint)client.Client.RemoteEndPoint).Port);

                        NetworkStream ns = client.GetStream();
                        try
                        {
                            int maxPacketSize;
                            if (USBDevice != null)
                            {
                                maxPacketSize = endpoint2.MaxPktSize;
                            }
                            else
                            {
                                maxPacketSize = MonoUsbApi.GetMaxPacketSize(USBProfile.ProfileHandle, 0x02);
                            }
                            byte[] inData  = new byte[64 * 1024];
                            byte[] outData = new byte[maxPacketSize - 16]; // Some PCs cannot send 1024 bytes
                            int outDataPos = 0;

                            while (!ct.IsCancellationRequested && !(ControlPortNo > 0 && controlClients.Count == 0))
                            {
                                int resSize = ns.Read(inData, 0, inData.Length);
                                if (resSize == 0)
                                {
                                    break;
                                }

                                int inDataLen = resSize;
                                int inDataPos = 0;
                                while (!ct.IsCancellationRequested && inDataPos < inDataLen)
                                {
                                    while (outDataPos < outData.Length && inDataPos < inDataLen)
                                    {
                                        outData[outDataPos++] = inData[inDataPos++];
                                    }

                                    if (outDataPos == outData.Length)
                                    {
                                        int xferLen = outData.Length;
                                        bool ret    = false;
                                        if (USBDevice != null)
                                        {
                                            ret = endpoint2.XferData(ref outData, ref xferLen);
                                        }
                                        else
                                        {
                                            ret = MonoUsbApi.BulkTransfer(MonoDeviceHandle, 0x02, outData, outData.Length, out xferLen, TIMEOUT) == 0;
                                        }
                                        if (ret == false || xferLen == 0)
                                        {
                                            break;
                                        }
                                        if (xferLen != outData.Length)
                                        {
                                            Console.WriteLine($"{dataPortNo}: the response size {xferLen} not equal to the requested size {outData.Length}");
                                        }
                                        outDataPos = 0;
                                    }
                                }
                            }
                        }
                        catch (Exception)
                        {
                            // nothing to do
                        }
                        finally
                        {
                            ns.Close();
                            client.Close();
                            Console.WriteLine($"{dataPortNo}: closed");
                        }
                    }
                }
                catch (OperationCanceledException)
                {
                    // nothing to do
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"{dataPortNo}: {ex.Message}");
                }
            }, ct);
        }
Ejemplo n.º 11
0
        public ADCDevice(CyUSBDevice usbDevice, MonoUsbProfile usbProfile)
            : base(usbDevice, usbProfile, EDeviceType.ADC)
        {
            byte[] response = ReceiveVendorResponse((byte)EVendorRequests.DeviceParam, 2);
            dataPortNo = (ushort)(response[0] + (response[1] << 8));

            Console.WriteLine($"DeviceAttached: {this}");

            if (USBDevice != null)
            {
                endpoint2 = USBDevice.EndPointOf(0x82) as CyBulkEndPoint;
            }

            var ct = Cts.Token;

            Task.Run(() =>
            {
                UdpClient udp = new UdpClient();
                try
                {
                    int maxPacketSize;
                    if (USBDevice != null)
                    {
                        maxPacketSize = endpoint2.MaxPktSize;
                    }
                    else
                    {
                        maxPacketSize = MonoUsbApi.GetMaxPacketSize(USBProfile.ProfileHandle, 0x82);
                    }
                    byte[] inData  = new byte[maxPacketSize];
                    byte[] outData = null;
                    int outDataPos = 0;

                    while (!ct.IsCancellationRequested)
                    {
                        int xferLen = inData.Length;
                        bool ret    = false;
                        if (USBDevice != null)
                        {
                            ret = endpoint2.XferData(ref inData, ref xferLen);
                        }
                        else
                        {
                            ret = MonoUsbApi.BulkTransfer(MonoDeviceHandle, 0x82, inData, inData.Length, out xferLen, TIMEOUT) == 0;
                        }
                        if (ret == false)
                        {
                            break;
                        }

                        int inDataPos = 0;
                        while (!ct.IsCancellationRequested && inDataPos < xferLen)
                        {
                            if (outData == null)
                            {
                                outData = new byte[1472];
                            }
                            while (outDataPos < outData.Length && inDataPos < xferLen)
                            {
                                outData[outDataPos++] = inData[inDataPos++];
                            }

                            if (outDataPos == outData.Length)
                            {
                                udp.Send(outData, outData.Length, "127.0.0.1", dataPortNo);
                                outData    = null;
                                outDataPos = 0;
                            }
                        }
                    }
                }
                catch (OperationCanceledException)
                {
                    // nothing to do
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"{DeviceType}: {ex.Message}");
                }
                finally
                {
                    udp.Close();
                }
            }, ct);
        }
Ejemplo n.º 12
0
        public ADCDevice(CyUSBDevice usbDevice, MonoUsbProfile usbProfile, EDeviceType deviceType)
            : base(usbDevice, usbProfile, deviceType)
        {
            if (deviceType == EDeviceType.ADC)
            {
                byte[] response = ReceiveVendorResponse((byte)EVendorRequests.DeviceParam, 2);
                dataPortNo = (ushort)(response[0] + (response[1] << 8));
            }
            else
            {
                byte[] response = ReceiveVendorResponse((byte)EVendorRequests.DeviceParam, 4);
                dataPortNo    = (ushort)(response[0] + (response[1] << 8));
                ControlPortNo = (ushort)(response[2] + (response[3] << 8));
            }

            Console.WriteLine($"+ {this}");

            if (USBDevice != null)
            {
                endpoint2 = USBDevice.EndPointOf(0x82) as CyBulkEndPoint;
            }

            var ct = Cts.Token;

            Task.Run(() =>
            {
                while (!ct.IsCancellationRequested)
                {
                    if (ControlPortNo > 0 && controlClients.Count == 0)
                    {
                        Thread.Sleep(100);
                        continue;
                    }

                    UdpClient udp = new UdpClient();
                    try
                    {
                        int maxPacketSize;
                        if (USBDevice != null)
                        {
                            maxPacketSize = endpoint2.MaxPktSize;
                        }
                        else
                        {
                            maxPacketSize = MonoUsbApi.GetMaxPacketSize(USBProfile.ProfileHandle, 0x82);
                        }
                        byte[] inData  = new byte[maxPacketSize];
                        byte[] outData = null;
                        int outDataPos = 0;

                        while (!ct.IsCancellationRequested && !(ControlPortNo > 0 && controlClients.Count == 0))
                        {
                            int xferLen = inData.Length;
                            bool ret    = false;
                            if (USBDevice != null)
                            {
                                ret = endpoint2.XferData(ref inData, ref xferLen);
                            }
                            else
                            {
                                ret = MonoUsbApi.BulkTransfer(MonoDeviceHandle, 0x82, inData, inData.Length, out xferLen, TIMEOUT) == 0;
                            }
                            if (ret == false)
                            {
                                break;
                            }

                            int inDataPos = 0;
                            while (!ct.IsCancellationRequested && inDataPos < xferLen)
                            {
                                if (outData == null)
                                {
                                    outData = new byte[1472];
                                }
                                while (outDataPos < outData.Length && inDataPos < xferLen)
                                {
                                    outData[outDataPos++] = inData[inDataPos++];
                                }

                                if (outDataPos == outData.Length)
                                {
                                    List <string> remoteAddrList = new List <string>();
                                    foreach (var client in controlClients.ToArray())
                                    {
                                        string remoteAddr;
                                        try
                                        {
                                            remoteAddr = ((IPEndPoint)client.Client.RemoteEndPoint).Address.ToString();
                                        }
                                        catch
                                        {
                                            continue;
                                        }

                                        if (remoteAddrList.Contains(remoteAddr) == false)
                                        {
                                            remoteAddrList.Add(remoteAddr);
                                            udp.Send(outData, outData.Length, remoteAddr, dataPortNo);
                                        }
                                    }

                                    if (ControlPortNo == 0)
                                    {
                                        udp.Send(outData, outData.Length, "127.0.0.1", dataPortNo);
                                    }

                                    outData    = null;
                                    outDataPos = 0;
                                }
                            }
                        }
                    }
                    catch (OperationCanceledException)
                    {
                        // nothing to do
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"{dataPortNo}: {ex.Message}");
                    }
                    finally
                    {
                        udp.Close();
                    }

                    Thread.Sleep(1000);
                }
            }, ct);
        }