Exemple #1
0
    public void close()
    {
        init_defaults();

        if (MyUsbDevice != null)
        {
            if (MyUsbDevice.IsOpen)
            {
                // If this is a "whole" usb device (libusb-win32, linux libusb-1.0)
                // it exposes an IUsbDevice interface. If not (WinUSB) the
                // 'wholeUsbDevice' variable will be null indicating this is
                // an interface of a device; it does not require or support
                // configuration and interface selection.
                IUsbDevice wholeUsbDevice = MyUsbDevice as IUsbDevice;
                if (!ReferenceEquals(wholeUsbDevice, null))
                {
                    // Release interface #0.
                    wholeUsbDevice.ReleaseInterface(0);
                }

                MyUsbDevice.Close();
            }
            MyUsbDevice = null;
            // Free usb resources
            UsbDevice.Exit();
        }
    }
Exemple #2
0
 /// <summary>
 /// ForceClose calls the Close method on the device, and then sets the current device to null
 /// </summary>
 public void ForceClose()
 {
     try
     {
         MyUsbDevice.Close();
     }
     catch
     {
     }
     finally
     {
         MyUsbDevice = null;
     }
 }
Exemple #3
0
 bool transfer(int request_type = 0x40, int request = 0, int value = 0, int index = 0)
 {
     if (MyUsbDevice == null)
     {
         throw new Exception("Device not connected");
     }
     try {
         int            transferred;
         UsbSetupPacket setup = new UsbSetupPacket((byte)request_type, (byte)request, value, index, 0);
         return(MyUsbDevice.ControlTransfer(ref setup, null, 0, out transferred));
     }
     catch
     {
         return(false);
     }
 }
Exemple #4
0
 bool transfer(out byte[] data, int request_type = 0xC0, int request = 0, int value = 0, int index = 0, int data_or_length = 0)
 {
     if (MyUsbDevice == null)
     {
         throw new Exception("Device not connected");
     }
     try
     {
         int transferred;
         data = new byte[data_or_length];
         UsbSetupPacket setup = new UsbSetupPacket((byte)request_type, (byte)request, value, index, data_or_length);
         bool           res   = MyUsbDevice.ControlTransfer(ref setup, data, data_or_length, out transferred);
         return(res == true && transferred == data_or_length);
     }
     catch
     {
         data = null;
         return(false);
     }
 }
        private static void TheActualLoop()
        {
            var vid = 0x6b56;
            var pid = 0x8802;

            if (_shouldLogConnection)
            {
                _logger.Info($"Connecting to VID: {vid} PID: {pid}");
            }

            UsbRegistry volumeControllerRegistry = UsbDevice.AllDevices.FirstOrDefault(d => d.Vid == vid && d.Pid == pid);

            // If the device is open and ready
            if (volumeControllerRegistry == null || volumeControllerRegistry.Open(out var MyUsbDevice) == false)
            {
                if (_shouldLogConnection)
                {
                    _logger.Warn("Device Not Found.");
                    _shouldLogConnection = false;
                }
                System.Threading.Thread.Sleep(1000);
                return;
            }

            _shouldLogConnection = true;
            _logger.Info("Connected with great success.");
            App.notifyIcon.Text = "Tray Icon of Greatness";
            App.notifyIcon.Icon = Software.Properties.Resources.MainIcon;

            // If this is a "whole" usb device (libusb-win32, linux libusb)
            // it will have an IUsbDevice interface. If not (WinUSB) the
            // variable will be null indicating this is an interface of a
            // device.
            IUsbDevice wholeUsbDevice = MyUsbDevice as IUsbDevice;

            if (!ReferenceEquals(wholeUsbDevice, null))
            {
                // This is a "whole" USB device. Before it can be used,
                // the desired configuration and interface must be selected.

                // Select config #1
                wholeUsbDevice.SetConfiguration(1);

                // Claim interface #2.
                wholeUsbDevice.ClaimInterface(2);
            }


            UsbEndpointWriter Writer3 = MyUsbDevice.OpenEndpointWriter(WriteEndpointID.Ep03);
            UsbEndpointWriter Writer4 = MyUsbDevice.OpenEndpointWriter(WriteEndpointID.Ep04);
            UsbEndpointReader reader  = MyUsbDevice.OpenEndpointReader(ReadEndpointID.Ep03);

            sbyte[]      enc                 = new sbyte[ChannelCount];
            byte[][]     actualLedState      = new byte[ChannelCount][];
            Renderable[] actualLcdRenderable = new Renderable[ChannelCount];
            byte         ledCursor           = 0;
            byte         lcdCursor           = 0;

            bool firstLoop = true;

            do
            {
                int       transferredIn;
                byte[]    readBuffer = new byte[38];
                ErrorCode ecRead     = reader.Transfer(readBuffer, 0, readBuffer.Length, 1000, out transferredIn);
                if (ecRead != ErrorCode.None)
                {
                    throw new Exception($"Submit Async Read Failed. ErrorCode: {ecRead}");
                }

                if (transferredIn > 0)
                {
                    ushort touchReading   = (ushort)((ushort)readBuffer[2] | (ushort)(((ushort)readBuffer[3]) << 8));
                    ushort ambientReading = (ushort)((ushort)readBuffer[4] | (ushort)(((ushort)readBuffer[5]) << 8));
                    ambientReading = readBuffer[1];
                    for (int i = 0; i < ChannelCount; i++)
                    {
                        sbyte newenc  = (sbyte)(readBuffer[6 + 2 * i]);
                        sbyte encdiff = (sbyte)(firstLoop ? 0 : newenc - enc[i]);
                        enc[i] = newenc;
                        byte[]     newLedState;
                        Renderable newLcdRenderable;
                        _scriptManager.channels[i].HandleFrame(encdiff, readBuffer[7 + 2 * i], touchReading, ambientReading, out newLedState, out newLcdRenderable);
                        if (newLedState != null)
                        {
                            _wantedLedState[i] = newLedState;
                        }
                        if (newLcdRenderable != null)
                        {
                            _wantedLcdRenderable[i] = newLcdRenderable;
                        }
                    }

                    {
                        IEnumerable <byte> buffer = new byte[0];
                        for (int i = 0; i < ChannelCount && buffer.Count() < 52; i++)
                        {
                            if (_wantedLedState[ledCursor] != null && (actualLedState[ledCursor] == null || !_wantedLedState[ledCursor].SequenceEqual(actualLedState[ledCursor])))
                            {
                                byte[] wanted = _wantedLedState[ledCursor];
                                buffer = buffer.Concat(new byte[] {
                                    ledCursor, 0,
                                    wanted[0], wanted[1], wanted[2], wanted[3], wanted[4], wanted[5], wanted[6], wanted[7], wanted[8], wanted[9], wanted[20], wanted[20],
                                    wanted[10], wanted[11], wanted[12], wanted[13], wanted[14], wanted[15], wanted[16], wanted[17], wanted[18], wanted[19], wanted[20], wanted[20]
                                });
                                actualLedState[ledCursor] = wanted;
                            }
                            ledCursor = (byte)((ledCursor + 1) % ChannelCount);
                        }
                        if (buffer.Count() != 0)
                        {
                            if (buffer.Count() == 26)
                            {
                                buffer = buffer.Concat(buffer);
                            }

                            byte[] bytesToSend = buffer.ToArray();

                            int       transferredOut;
                            ErrorCode ecWrite = Writer4.Transfer(bytesToSend, 0, bytesToSend.Length, 100, out transferredOut);
                            if (ecWrite != ErrorCode.None)
                            {
                                // usbReadTransfer.Dispose();
                                throw new Exception($"Submit Async Write Failed on Writer4. ErrorCode: {ecWrite}");
                            }
                        }
                    }
                    {
                        for (int i = 0; i < ChannelCount; i++)
                        {
                            if (_wantedLcdRenderable[lcdCursor] != null && (actualLcdRenderable[lcdCursor] == null || !_wantedLcdRenderable[lcdCursor].Equals(actualLcdRenderable[lcdCursor])))
                            {
                                byte[] bytesToSend = (actualLcdRenderable[lcdCursor] = _wantedLcdRenderable[lcdCursor]).Render();

                                bytesToSend = new byte[] { 8, 2, lcdCursor, 0 }.Concat(bytesToSend).Concat(new byte[] { 0, 0, 0, 0 }).ToArray();

                                int       transferredOut;
                                ErrorCode ecLcdWrite = Writer3.Transfer(bytesToSend, 0, bytesToSend.Length, 900, out transferredOut);
                                if (ecLcdWrite != ErrorCode.None)
                                {
                                    // usbReadTransfer.Dispose();
                                    throw new Exception($"Submit Async Write Failed on Writer3. ErrorCode: {ecLcdWrite}");
                                }
                                else
                                {
                                    _logger.Info($"Wrote to LCD {lcdCursor}");
                                }
                                break;
                            }
                            lcdCursor = (byte)((lcdCursor + 1) % ChannelCount);
                        }
                    }
                }
                else
                {
                    _logger.Warn("Didn't get an interrupt packet?????");
                }

                firstLoop = false;
            } while (!_cancellationTokenSource.Token.IsCancellationRequested && !_shouldReloadConfig);

            MyUsbDevice.Close();
        }
Exemple #6
0
        /// <summary>
        /// The method performs the main function of the service. It runs on
        /// a thread pool worker thread.
        /// </summary>
        /// <param name="state"></param>
        private void ServiceWorkerThread(object state)
        {
            GetIDs();
            ErrorCode ec = ErrorCode.None;

            try
            {
                // Find and open the usb device.
                MyUsbDevice = UsbDevice.OpenUsbDevice(MyUsbFinder);
                // If the device is open and ready
                if (MyUsbDevice == null)
                {
                    throw new Exception("Device Not Found.");
                }

                IUsbDevice wholeUsbDevice = MyUsbDevice as IUsbDevice;
                if (!ReferenceEquals(wholeUsbDevice, null))
                {
                    wholeUsbDevice.SetConfiguration(1);
                    wholeUsbDevice.ClaimInterface(0);
                }
                // open read endpoint 1.
                UsbEndpointReader reader = MyUsbDevice.OpenEndpointReader(ReadEndpointID.Ep01);

                byte[] readBuffer = new byte[1024];
                int    bytesRead  = 0;

                // Periodically check if the service is stopping.
                while (!this.stopping)
                {
                    //Thread.Sleep(2000);  // Simulate some lengthy operations.
                    ec = reader.Read(readBuffer, 30000, out bytesRead);
                    if (bytesRead > 0)
                    {
                        string   trackString = Encoding.Default.GetString(readBuffer, 0, bytesRead);
                        string[] words       = trackString.Split('?');
                        System.IO.StreamWriter fileReader2 = new System.IO.StreamWriter(trackFile, true);

                        if (words.Length > 0)
                        {
                            //Console.WriteLine();
                            string[] track1 = words[0].Split('%');
                            if (track1.Length > 1 && track1[1].Length > 0)
                            {
                                fileReader2.WriteLine(track1[1]);
                                //Console.WriteLine(track1[1]);
                            }
                        }
                        if (words.Length > 1)
                        {
                            string[] track2 = words[1].Split(';');
                            if (track2.Length > 1 && track2[1].Length > 0)
                            {
                                fileReader2.WriteLine(track2[1]);
                                //Console.WriteLine(track2[1]);
                            }
                        }
                        if (words.Length > 2)
                        {
                            string[] track3 = words[2].Split(';');
                            if (track3.Length > 1 && track3[1].Length > 0)
                            {
                                fileReader2.WriteLine(track3[1]);
                                //Console.WriteLine(track3[1]);
                            }
                        }
                        fileReader2.Close();
                    }
                }
            }
            catch (Exception ex)
            {
                System.IO.StreamWriter file = new System.IO.StreamWriter(logFile, true);
                file.WriteLine();
                file.WriteLine((ec != ErrorCode.None ? ec + ":" : String.Empty) + ex.Message);
                file.Close();
            }
            finally
            {
                if (MyUsbDevice != null)
                {
                    if (MyUsbDevice.IsOpen)
                    {
                        IUsbDevice wholeUsbDevice = MyUsbDevice as IUsbDevice;
                        if (!ReferenceEquals(wholeUsbDevice, null))
                        {
                            // Release interface #0.
                            wholeUsbDevice.ReleaseInterface(0);
                        }
                        MyUsbDevice.Close();
                    }
                    MyUsbDevice = null;
                    UsbDevice.Exit();
                }
            }
            // Signal the stopped event.
            this.stoppedEvent.Set();
        }