Ejemplo n.º 1
0
        private void Filter_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            byte[] command1 = { 0x0a, 0x0b, 0x0c, 0x0d };
            byte[] command2 = { 0x01, 0x02, 0x03, 0x04 };
            int    bytesWritten;

            LibUsbDotNet.Main.ErrorCode ec = LibUsbDotNet.Main.ErrorCode.None;

            try
            {
                if (Filter.SelectedIndex == 0)
                {
                    ec = _writer.Write(command1, 1000, out bytesWritten);
                    if (ec != LibUsbDotNet.Main.ErrorCode.None)
                    {
                        throw new Exception(UsbDevice.LastErrorString);
                    }
                }

                if (Filter.SelectedIndex == 1)
                {
                    ec = _writer.Write(command2, 1000, out bytesWritten);
                    if (ec != LibUsbDotNet.Main.ErrorCode.None)
                    {
                        throw new Exception(UsbDevice.LastErrorString);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine();
                Console.WriteLine((ec != LibUsbDotNet.Main.ErrorCode.None ? ec + ":" : string.Empty) + ex.Message);
            }
        }
Ejemplo n.º 2
0
 public void SendOscillCommand(byte CommandType, byte Value)
 {
     byte[] sendArray = new byte[2];
     sendArray[0] = CommandType;
     sendArray[1] = Value;
     writer.Write(sendArray, 1000, out int out_l);
 }
Ejemplo n.º 3
0
        /// <summary>
        /// Prints the specified text.
        /// </summary>
        /// <param name="data">The text to print.</param>
        /// <exception cref="System.ArgumentException">
        ///     <paramref name="data" /> is null or empty.
        /// </exception>
        public ErrorCode PrintText(string data)
        {
            if (String.IsNullOrWhiteSpace(data))
            {
                throw new ArgumentException("Data cannot be null or empty.", "data");
            }

            // Write the data to the printer.
            List <byte> buffer = new List <byte>();

            buffer.AddRange(Encoding.ASCII.GetBytes(data));
            buffer.Add(0x0A);

            byte[] bufferArray = buffer.ToArray();

            int bytesWritten;
            int totalBytesWritten = 0;

            while (totalBytesWritten < bufferArray.Length)
            {
                ErrorCode writeErrorCode = _writer.Write(bufferArray, totalBytesWritten, (bufferArray.Length - totalBytesWritten), 10000, out bytesWritten);

                totalBytesWritten += bytesWritten;

                if (writeErrorCode != ErrorCode.None)
                {
                    //TODO: Log the error.
                    return(writeErrorCode);
                }
            }

            return(ErrorCode.None);
        }
Ejemplo n.º 4
0
        // Immediately updates the ardunio's buffer for the color
        private static bool sendClr(int pos, DRColor.RGB rgb, int strip)
        {
            posClamp(ref pos, 1);

            // Create color packet, add 64 for second led strip
            byte[] bytes = new byte[4];
            bytes[0] = (byte)pos;
            if (strip == 2)
            {
                bytes[0] += (byte)64;
            }
            bytes[1] = (byte)rgb.Red;
            bytes[2] = (byte)rgb.Green;
            bytes[3] = (byte)rgb.Blue;

            int       bytesWritten = 0;
            ErrorCode ec           = ErrorCode.None;

            if (Connected)
            {
                ec = writer.Write(bytes, 2000, out bytesWritten);
            }
            if (ec == ErrorCode.ResourceBusy)
            {
                return(true);
            }

            if (ec != ErrorCode.None)
            {
                throw new Exception(UsbDevice.LastErrorString);
            }

            return(true);
        }
Ejemplo n.º 5
0
        public override bool TransmitData <T>(T data)
        {
            ErrorCode ec = ErrorCode.None;

            try
            {
                if (typeof(T) == typeof(string))
                {
                    ec = _writer.Write(Encoding.Default.GetBytes(data as string), 2000, out int bytesWritten);
                }
                if (typeof(T) == typeof(byte[]))
                {
                    ec = _writer.Write(data as byte[], 2000, out int bytesWritten);
                }
                if (ec != ErrorCode.None)
                {
                    throw new Exception(UsbDevice.LastErrorString);
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.ToString());
            }

            return(true);
        }
Ejemplo n.º 6
0
        public bool SendReport(PSVRReport Report)
        {
            var data = Report.Serialize();
            int len;

            return(writer.Write(data, 1000, out len) == LibUsbDotNet.Main.ErrorCode.None);
        }
Ejemplo n.º 7
0
        private void SendScreenToCalc()
        {
            ErrorCode c;

#if DEBUG
            Stopwatch frameTimer = Stopwatch.StartNew();
#endif
            while (_connected)
            {
                if (_compressedImage != null)
                {
                    byte[] compImage = _compressedImage.ToArray();
                    if (compImage.Length >= 51200 || compImage.Length == 0)
                    {
                        _calcWriter.Write(_uncompressedImage.Length, 1000, out _);
                        c = _calcWriter.Write(_uncompressedImage, 0, _uncompressedImage.Length, 10000, out _);
                    }
                    else
                    {
                        _calcWriter.Write(compImage.Length, 1000, out _);
                        c = _calcWriter.Write(compImage, 0, compImage.Length, 1000, out _);
                    }
#if DEBUG
                    // Debug.WriteLine($"Size: {compImage.Length}");
                    // Debug.WriteLine($"Sending at {1.0 / (frameTimer.ElapsedMilliseconds/1000.0)} fps");
                    frameTimer.Restart();
#endif
                    if (c != ErrorCode.Success)
                    {
                        _connected = false;
                        OnUsbError.Invoke(this, c);
                    }
                }
            }
        }
Ejemplo n.º 8
0
        protected ErrorCode WriteToDevice(byte[] buf, int tries = 10)
        {
            if (buf == null)
            {
                throw new ArgumentNullException("buf");
            }
            Main.SendDebug(string.Format("Writing 0x{0:X} Bytes to device", buf.Length));
            var totalwrote = 0;
            var err        = ErrorCode.None;

            while (totalwrote < buf.Length && tries > 0)
            {
                int wrote;
                if (totalwrote > 0)
                {
                    var tmp = new byte[buf.Length - totalwrote];
                    Buffer.BlockCopy(buf, buf.Length - tmp.Length, tmp, 0, tmp.Length);
                    err = _writer.Write(tmp, 1000, out wrote);
                }
                else
                {
                    err = _writer.Write(buf, 1000, out wrote);
                }
                if (err != ErrorCode.None && err != ErrorCode.IoTimedOut)
                {
                    Main.SendDebug(String.Format("Error: {0}", err));
                }
                totalwrote += wrote;
                tries--;
                Main.SendDebug(string.Format("Wrote 0x{0:X} Attempt: {1} Total written data: 0x{2:X}", wrote, Math.Abs(tries - 10), totalwrote));
            }
            return(tries > 0 ? ErrorCode.Success : err);
        }
        void killAll()
        {
            int tLen;
            var buff = new byte[4];

            buff[0] = (byte)ClovershellCommand.CMD_SHELL_KILL_ALL;
            buff[1] = 0;
            buff[2] = 0;
            buff[3] = 0;
            var r = epWriter.Write(buff, 0, buff.Length, 1000, out tLen);

            if (tLen != buff.Length)
            {
                throw new ClovershellException("kill all shell: write error - " + r.ToString());
            }
            buff[0] = (byte)ClovershellCommand.CMD_EXEC_KILL_ALL;
            buff[1] = 0;
            buff[2] = 0;
            buff[3] = 0;
            r       = epWriter.Write(buff, 0, buff.Length, 1000, out tLen);
            if (tLen != buff.Length)
            {
                throw new ClovershellException("kill all exec: write error - " + r.ToString());
            }
        }
Ejemplo n.º 10
0
        private void button1_Click(object sender, EventArgs e)
        {
            logBox.AppendText("-------------USB Custom HID Loopback testing: 8 bytes, 15 repeats-------------");
            string cmdLine = "PD2 119\n";

            int bytesWritten;

            byte[] btwr         = Encoding.Default.GetBytes(cmdLine);
            int    numTransfers = 16;

            for (int i = 0; i < numTransfers; i++)
            {
                ec = writer.Write(btwr, 0, reader.ReadBufferSize, 2000, out bytesWritten);
                if (ec != ErrorCode.None || bytesWritten < reader.ReadBufferSize)
                {
                    throw new Exception(UsbDevice.LastErrorString);
                }
            }

            LastDataEventDate = DateTime.Now;
            while ((DateTime.Now - LastDataEventDate).TotalMilliseconds < 1000)
            {
            }

            logBox.AppendText("\r\nDone!\r\n");
        }
Ejemplo n.º 11
0
        public byte[] ReadMemoryCardFrame(ushort frameNumber)
        {
            // Split the 16-bit frame number into two bytes
            _readFrameCommand[8] = (byte)(frameNumber >> 8);
            _readFrameCommand[9] = (byte)(frameNumber & 0xFF);

            // Output a command to request the desired frame
            int bytesWritten;

            LastErrorCode = _writer.Write(_readFrameCommand, Timeout, out bytesWritten);
            if (LastErrorCode != ErrorCode.None || bytesWritten != ReadCommandLength)
            {
                return(null);
            }

            // Read the frame data from the memory card
            int bytesRead;

            LastErrorCode = _reader.Read(_buffer, Timeout, out bytesRead);
            if (LastErrorCode != ErrorCode.None || bytesRead != ReadCommandLength || _buffer[0] != 0x55 || _buffer[1] != 0x5A)
            {
                return(null);
            }

            // Strip the header data and return the requested frame
            byte[] frame = new byte[128];
            Array.Copy(_buffer, 14, frame, 0, 128);
            return(frame);
        }
Ejemplo n.º 12
0
        /// <summary>
        /// 打印文本
        /// </summary>
        /// <param name="mess"></param>
        /// <returns></returns>
        public int PrintString(string mess)
        {
            int       err = 0;
            ErrorCode ec  = ErrorCode.None;

            if (!String.IsNullOrEmpty(mess) && MyUsbDevice.IsOpen)
            {
                byte[]   OutBuffer;//数据
                int      BufferSize;
                Encoding targetEncoding;
                //将[UNICODE编码]转换为[GB码],仅使用于简体中文版mobile
                targetEncoding = Encoding.GetEncoding(0);           //得到简体中文字码页的编码方式,因为是简体中文操作系统,参数用0就可以,用936也行。
                BufferSize     = targetEncoding.GetByteCount(mess); //计算对指定字符数组中的所有字符进行编码所产生的字节数
                OutBuffer      = new byte[BufferSize];
                OutBuffer      = targetEncoding.GetBytes(mess);     //将指定字符数组中的所有字符编码为一个字节序列,完成后outbufer里面即为简体中文编码

                int bytesWritten;
                ec = Writer.Write(OutBuffer, 2000, out bytesWritten);
                if (ec != ErrorCode.None)
                {
                    err = (int)PrintError.SendFailure;
                    return(err);
                }
                else if (bytesWritten != OutBuffer.Length)
                {
                    err = (int)PrintError.SendFailure;
                    return(err);
                }

                byte[] readBuffer = new byte[1024];
                while (ec == ErrorCode.None)
                {
                    int bytesRead;

                    // If the device hasn't sent data in the last 100 milliseconds,
                    // a timeout error (ec = IoTimedOut) will occur.
                    ec = Reader.Read(readBuffer, 100, out bytesRead);

                    if (bytesRead == 0)
                    {
                    }
                }

                err = 1;
                return(err);
            }
            else
            {
                err = (int)PrintError.SendNull;
                return(err);
            }
        }
Ejemplo n.º 13
0
        public bool UsbStartComm(byte[] sendcomm)
        {
            _usbwriter.Write(sendcomm, 100, out int sendlength);

            if (sendlength > 0)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
Ejemplo n.º 14
0
        public void WriteBlock(byte[] data)
        {
            OpenDevice();

            if (data == null || data.Length <= 0)
            {
                return;
            }

            int tLength;
            var eCode = _epWriter.Write(data, TxTimeout, out tLength);

            Debug.Assert(eCode != ErrorCode.None, string.Format("Write error! {0}", eCode));
        }
Ejemplo n.º 15
0
 private void timer1_Tick(object sender, EventArgs e)
 {
     if (connected == true)
     {
         try
         {
             usb_command[0] = 1;
             ec             = writer.Write(usb_command, 1000, out actual_length);
             ec             = reader.Read(usb_command, 1000, out actual_length);
             if (usb_command[0] == 0xCE && usb_command[1] == 0xED)
             {
                 timer1.Enabled = false;
                 mode           = 4;
                 backgroundWorker1.RunWorkerAsync();
             }
             else
             {
                 Scan_b.Enabled     = true;
                 DumpRAM_b.Enabled  = false;
                 DumpROM_b.Enabled  = false;
                 WriteRAM_b.Enabled = false;
                 Banks_l.Text       = "Banks: ";
                 MBC_l.Text         = "MBC: ";
                 RAM_l.Text         = "RAM Size: ";
                 Size_l.Text        = "Size:";
                 Title_l.Text       = "Title:";
             }
         }
         catch (Exception ex)
         {
             MessageBox.Show((ec != ErrorCode.None ? ec + ":" : String.Empty) + ex.Message);
         }
     }
 }
Ejemplo n.º 16
0
        public bool Write(string strWrite, ref int bytesWritten)
        {
            bool bRe = false;

            if (!String.IsNullOrEmpty(strWrite))
            {
                ErrorCode ec = writer.Write(Encoding.Default.GetBytes(strWrite), nWriteTimeOut, out bytesWritten);
                if (ec != ErrorCode.None)
                {
                    bRe = false;
                }
            }

            return(bRe);
        }
Ejemplo n.º 17
0
        public bool SendCommand(PSVRCommand Command)
        {
            var data = Command.Serialize();
            int len;

            return(writer.Write(data, 1000, out len) == LibUsbDotNet.Main.ErrorCode.None);
        }
Ejemplo n.º 18
0
        //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
        //Writers

        public void Write(byte[] pOutput)
        {
            try
            {
                //Only Write if _usbWriter is Enabled else ignore all calls, this way we can call Write in Pos, and if Device is Missing it skips all writes
                if (_usbWriter != null)
                {
                    // write data, read data
                    int bytesWritten;
                    _usbErrorCode = _usbWriter.Write(pOutput, 2000, out bytesWritten);

                    //ErrorCode Enumeration
                    //http://libusbdotnet.sourceforge.net/V2/html/c3eab258-a324-25c8-68ac-06ecf6e0fe7f.htm
                    if (_usbErrorCode != ErrorCode.None)
                    {
                        Close();
                        // Write that output to the console.
                        _log.Error(UsbDevice.LastErrorString);
                        //throw new Exception(UsbDevice.LastErrorString);
                    }
                }
            }
            catch (Exception ex)
            {
                _log.Error(ex.Message, ex);
            }
        }
Ejemplo n.º 19
0
 private void WriteThreadEP1()
 {
     while (bWriteThreadEP1Enabled)
     {
         int bytesTransmitted;
         //if (mEP1Writer.Type == EndpointType.Isochronous)
         //    mEP1Writer.Reset();
         ErrorCode ec = mEP1Writer.Write(loopTestBytes, mBenchMarkParameters.Timeout, out bytesTransmitted);
         if (ec != ErrorCode.Success)
         {
             bWriteThreadEP1Enabled = false;
             break;
         }
         Thread.Sleep(0);
     }
 }
Ejemplo n.º 20
0
        public _radio_ack send_packet(byte[] dataOut)
        {
            _radio_ack ackIn = null;
            int        transferred;

            writer.Write(dataOut, 1000, out transferred);
            if (transferred == dataOut.Length)
            {
                byte[] data = new byte[64];
                reader.Read(data, 1000, out transferred);
                if (transferred > 0)
                {
                    ackIn = new _radio_ack();
                    if (data[0] != 0)
                    {
                        ackIn.ack      = (data[0] & 0x01) != 0;
                        ackIn.powerDet = (data[0] & 0x02) != 0;
                        ackIn.retry    = data[0] >> 4;
                        ackIn.data     = data.Take(transferred).Skip(1).ToArray();
                    }
                    else
                    {
                        ackIn.retry = this.arc;
                    }
                }
            }
            return(ackIn);
        }
Ejemplo n.º 21
0
    public static void Update(Record Record)
    {
        if (MyUsbDevice == null)
        {
            /* we failed to connect to M4ATX device, nothing to do here */
            return;
        }

        UsbEndpointWriter writer = MyUsbDevice.OpenEndpointWriter(WriteEndpointID.Ep01);

        // specify data to send
        ec = writer.Write(new byte[] { 0x81, 0x00 }, 5000, out bytesWritten);

        if (ec != ErrorCode.None)
        {
            throw new Exception("M4ATX: Error sending command: " + ec);
        }

        // open read endpoint 1.
        UsbEndpointReader reader = MyUsbDevice.OpenEndpointReader(ReadEndpointID.Ep01);

        // If the device hasn't sent data in the last 5 seconds,
        // a timeout error (ec = IoTimedOut) will occur.
        reader.Read(readBuffer, 3000, out bytesRead);

        if (ec != ErrorCode.None || bytesRead != readBuffer.Length)
        {
            var msg = string.Format("M4ATX: Error reading result, error {0}, got {1} bytes",
                                    ec, bytesRead);
            throw new Exception(msg);
        }

        Record.Set(Record.DataPoint.M4ATXTemperature, readBuffer[12]);
        Record.Set(Record.DataPoint.M4ATXVoltageIn, readBuffer[2]);
    }
Ejemplo n.º 22
0
 public async Task WriteAsync(byte[] data)
 {
     await Task.Run(() =>
     {
         _UsbEndpointWriter.Write(data, Timeout, out var bytesWritten);
     });
 }
Ejemplo n.º 23
0
        //@brief Send comand to USB device
        //
        public void usbSend(byte[] message, int messageSize)
        {
            int       numDataTx;
            ErrorCode rezTx;

            rezTx = writer.Write(message, 2000, out numDataTx);
        }
Ejemplo n.º 24
0
        /// <summary>
        /// Helper function to send a bluetooth packet with the parameters as a message.
        /// </summary>
        /// <param name="bytesToSend">bytes, without the bluetooth bytes, to send.</param>
        /// <returns>True if it succeeds, false if it errors.</returns>
        public bool SendPacket(byte[] bytesToSend)
        {
            if (useBluetooth)
            {
                try {
                    //get the length and convert to hex.
                    int lengthOfBytes = bytesToSend.Length;

                    //take the last first two bytes, reverse it. (Least significant first for bluetooth.)
                    byte[] hexLength = BitConverter.GetBytes(lengthOfBytes).Take(2).ToArray(); //.Reverse().ToArray(); //what the hell c#

                    //combine and send packet.
                    byte[] finalPacket = hexLength.Concat(bytesToSend).ToArray();
                    _serialPort.Write(finalPacket, 0, finalPacket.Length);
                    Console.WriteLine("Packet sent over serial: " + BitConverter.ToString(finalPacket));
                } catch (Exception error) {
                    Console.WriteLine("ERROR WHILE SENDING PACKET: " + error.ToString());
                    return(false);
                }
            }
            else
            {
                ErrorCode ec;
                int       bytesWritten;
                ec = usbWriter.Write(bytesToSend, 50, out bytesWritten);
                if (ec != ErrorCode.None)
                {
                    Console.Error.WriteLine("[ERROR] " + UsbDevice.LastErrorString);
                    return(false);
                }
            }
            return(true);
        }
Ejemplo n.º 25
0
        public override async Task WriteAsync(byte[] data)
        {
            await _WriteAndReadLock.WaitAsync();

            try
            {
                await Task.Run(() =>
                {
                    var errorCode = _UsbEndpointWriter.Write(data, Timeout, out var bytesWritten);
                    if (errorCode == ErrorCode.Ok || errorCode == ErrorCode.Success)
                    {
                        Tracer?.Trace(true, data);
                    }
                    else
                    {
                        var message = $"Error. Write error code: {errorCode}";
                        Logger?.Log(message, GetType().Name, null, LogLevel.Error);
                        throw new IOException(message);
                    }
                });
            }
            finally
            {
                _WriteAndReadLock.Release();
            }
        }
Ejemplo n.º 26
0
        public void EnableTracking(bool en, Action postAction = null)
        {
            if (!IsActive)
            {
                return;
            }
            var report = new PSVRReport(PSVRReportType.Tracking, new byte[] { (byte)(en ? 0x80 : 0x00), 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00 });

            if (postAction != null)
            {
                PostActions[report.ReportType] = postAction;
            }
            int len;

            _controlWrite.Write(report.Data, 1000, out len);
        }
Ejemplo n.º 27
0
    private void Start()
    {
        var USBFinder = new UsbDeviceFinder(0x057E, 0x0337);

        GCNAdapter = UsbDevice.OpenUsbDevice(USBFinder);


        if (GCNAdapter != null)
        {
            reader = GCNAdapter.OpenEndpointReader(ReadEndpointID.Ep01);
            writer = GCNAdapter.OpenEndpointWriter(WriteEndpointID.Ep02);

            //prompt controller to start sending
            writer.Write(Convert.ToByte((char)19), 10, out transferLength);

            // PORT 1: bytes 02-09
            // PORT 2: bytes 11-17
            // PORT 3: bytes 20-27
            // PORT 4: bytes 29-36l
            ReadBuffer = new byte[37]; // 32 (4 players x 8) bytes for input, 5 bytes for formatting
            //WriteBuffer = new byte[5]; // 1 for command, 4 for rumble state
            //WriteBuffer[0] = 0x11;
            //WriteBuffer[1] = 0;
            reader.ReadThreadPriority = System.Threading.ThreadPriority.Highest;
            reader.Flush();
            gcThread = new Thread(() => inputUpdate(ref ReadBuffer));
            gcThread.Start();
        }
        else
        {
            UnityEngine.Debug.Log("ERROR: Could not detect device WUP-028 Gamecube Controller Adapter.");
        }
    }
Ejemplo n.º 28
0
        public static void InitializeUSBDevice()
        {
            // Use the USB device finder to find our Gamecube adapter
            _usbDevice = UsbDevice.OpenUsbDevice(_usbDeviceFinder);
            if (_usbDevice == null)
            {
                // If the gamecube adapter isn't plugged in OR is being used by another application, throw an exception.
                // Is there even a way to take control over the adapter from another device?
                throw new Exception(Strings.ERROR_ADAPTERNOTFOUND);
            }

            IUsbDevice wholeUsbDevice = _usbDevice as IUsbDevice;

            if (!ReferenceEquals(wholeUsbDevice, null))
            {
                wholeUsbDevice.SetConfiguration(1); // Set the adapter to use config one
                wholeUsbDevice.ClaimInterface(0);   // Claim interface zero
            }

            // Set reader to read from endpoint 1 (apparently GCN adapters use endpoint 0x81, but this works?)
            _controllerReader = _usbDevice.OpenEndpointReader(ReadEndpointID.Ep01);

            // Write to endpoint 2
            _controllerWriter = _usbDevice.OpenEndpointWriter(WriteEndpointID.Ep02);

            // begin polling command - https://gbatemp.net/threads/wii-u-gamecube-adapter-reverse-engineering-cont.388169/
            _controllerWriter.Write(Convert.ToByte(0x13), 5000, out int transferLength);
        }
Ejemplo n.º 29
0
        protected void write_usb(byte[] buf, int timeout)
        {
            if (!IsOpen())
            {
                // fail silently
                return;
            }

            try {
                write_lock.WaitOne();

                // write to device
                Debug.Assert(ep_writer != null);
                int bytes_written;

                if (ep_writer.Write(buf, timeout, out bytes_written) != ErrorCode.None ||
                    bytes_written != buf.Length)
                {
                    throw new Exception("Failed to write to adapter");
                }
            }

            // clean up
            finally
            {
                write_lock.ReleaseMutex();
            }
        }
Ejemplo n.º 30
0
        private void WriteThreadEP1()
        {
            byte[] dat = new byte[8192];
            for (uint i = 0; i < 8192; i++)
            {
                dat[i] = (byte)(i & 0xff);
            }

            int ret;

            while (bWriteThreadEP1Enabled)
            {
                ret = mEP1Writer.Write(dat, 5000);
                Thread.Sleep(0);
            }
        }