public void Write(HidStream stream, byte[] data, BackgroundWorker worker = null) { var offset = 0; while (offset < data.Length) { var bufferLength = data.Length - offset > m_sentBufferLength ? m_sentBufferLength : data.Length - offset; var buffer = new byte[bufferLength + 1]; { buffer[0] = 0; Buffer.BlockCopy(data, offset, buffer, 1, bufferLength); } stream.Write(buffer); offset += bufferLength; if (worker != null) { worker.ReportProgress((int)(offset * 100f / data.Length)); } } if (worker != null) { worker.ReportProgress(100); } }
static void UpdateLNP(HidStream lnp, Color c1, Color c2, Color c3, Color c4) { do { c1 = backIOColor; c2 = headerTwoColor; c3 = pchColor; c4 = headerOneColor; LightingNodeUtils.BeignUpdate(lnp); byte[][] stripInfo = LightingNodeUtils.UpdateFourStrips(c1, c2, c3, c4); for (int i = 0; i < stripInfo.Length; i++) { lnp.Write(stripInfo[i]); } byte[][] fanInfo = LightingNodeUtils.UpdateSixFans(c1, c2, c3, c4); for (int i = 0; i < fanInfo.Length; i++) { lnp.Write(fanInfo[i]); } LightingNodeUtils.SubmitUpdate(lnp); System.Threading.Thread.Sleep(15); } while (running); }
byte[] SendCommand(HidStream stream, uint cmd, byte[] data) { byte[] send = new byte[64]; send[0] = 0x3f; send[1] = (byte)cmd; send[2] = (byte)data.Length; if (data.Length > 0) { Array.Copy(data, 0, send, 3, data.Length); } stream.Write(send); byte[] ret = new byte[64]; stream.Read(ret); byte[] real; if (ret[2] == 0) { real = new byte[1]; } else { real = new byte[2 + ret[2]]; } Array.Copy(ret, 1, real, 0, real.Length); return(real); }
private byte[] Read(HidStream stream, int length, BackgroundWorker worker = null) { var offset = 0; var result = new byte[length]; while (offset < length) { var rawPacket = new byte[m_receiveBufferLength]; stream.Read(rawPacket); // First byte is always HID Report ID, which is useless in our cases, so we are skipping it. var data = new byte[m_receiveDataLength]; Buffer.BlockCopy(rawPacket, 1, data, 0, data.Length); var bufferLength = offset + data.Length < length ? data.Length : length - offset; Buffer.BlockCopy(data, 0, result, offset, bufferLength); offset += bufferLength; if (worker != null) { worker.ReportProgress((int)(offset * 100f / length)); } } if (worker != null) { worker.ReportProgress(100); } return(result); }
/// <summary> /// /// </summary> protected virtual void OpenDelayed() { // Fix the size. if (m_SizeRead <= 0) { m_SizeRead = 64; } // Fix points. if (points.Length == 0) { int i = 2; points = new BlobsID3D[i]; while (i-- > 0) { points[i] = new BlobsID3D(); points[i].poseName = (i == 0)?"Left_Hand":"Right_Hand"; points[i].id = i; points[i].OnStart(this); } } // Open the steam. if (m_UsbStream == null) { // Fix VID & PID if (vId * pId == 0) { vId = 0x1f3b; pId = 0x10ff; } // m_UsbStream = new #if UNITY_EDITOR || UNITY_STANDALONE_WIN HidStream #elif UNITY_ANDROID UsbStream #endif (vId, pId, /*0x1f3b,0x10ff,*/ 0); // m_UsbStream.readBufferSize = m_SizeRead; m_UsbStream.SetOnStreamOpenListener(this); #if !UNITY_EDITOR && UNITY_ANDROID ((UsbStream)m_UsbStream).SetInterfaceFilters(3, 0, 1); #endif #if UNITY_EDITOR || UNITY_STANDALONE_WIN if (safeReadMode) { if (m_BufferRead == null) { m_BufferRead = new byte[m_SizeRead]; } } else #endif { m_UsbStream.SetOnStreamReadListener(this); } } m_UsbStream.Open(); }
public StadiaController(HidDevice device, HidStream stream, ViGEmClient client, int index) : base(device, stream, client, index) { profiles = new List <Dictionary <Type, Xbox360Property> >(); xboxMap = new Dictionary <Type, Xbox360Property> { [typeof(StadiaButton.A)] = Xbox360Button.A, [typeof(StadiaButton.B)] = Xbox360Button.B, [typeof(StadiaButton.X)] = Xbox360Button.X, [typeof(StadiaButton.Y)] = Xbox360Button.Y, [typeof(StadiaButton.Up)] = Xbox360Button.Up, [typeof(StadiaButton.Down)] = Xbox360Button.Down, [typeof(StadiaButton.Left)] = Xbox360Button.Left, [typeof(StadiaButton.Right)] = Xbox360Button.Right, [typeof(StadiaButton.L1)] = Xbox360Button.LeftShoulder, [typeof(StadiaButton.R1)] = Xbox360Button.RightShoulder, [typeof(StadiaButton.L3)] = Xbox360Button.LeftThumb, [typeof(StadiaButton.R3)] = Xbox360Button.RightThumb, [typeof(StadiaButton.Select)] = Xbox360Button.Back, [typeof(StadiaButton.Start)] = Xbox360Button.Start, [typeof(StadiaButton.Stadia)] = Xbox360Button.Guide, [typeof(StadiaAxis.LX)] = Xbox360Axis.LeftThumbX, [typeof(StadiaAxis.LY)] = Xbox360Axis.LeftThumbY, [typeof(StadiaAxis.RX)] = Xbox360Axis.RightThumbX, [typeof(StadiaAxis.RY)] = Xbox360Axis.RightThumbY, [typeof(StadiaSlider.L2)] = Xbox360Slider.LeftTrigger, [typeof(StadiaSlider.R2)] = Xbox360Slider.RightTrigger, }; Dictionary <Type, Xbox360Property> codMap = new Dictionary <Type, Xbox360Property>(); foreach (Type key in xboxMap.Keys) { codMap.Add(key, xboxMap[key]); } codMap[typeof(StadiaButton.B)] = Xbox360Slider.RightTrigger; codMap[typeof(StadiaSlider.R2)] = Xbox360Button.B; profiles.Add(xboxMap); profiles.Add(codMap); target360.FeedbackReceived += this.Target360_FeedbackReceived; targetDS4.FeedbackReceived += this.TargetDS4_FeedbackReceived; if (!pluggedIn360) { pluggedIn360 = true; target360.Connect(); } writeEvent = new AutoResetEvent(false); writeQueue = new ConcurrentQueue <byte[]>(); inputThread = new Thread(() => input_thread()); inputThread.Name = "Controller #" + index + " Input"; writeThread = new Thread(() => write_thread()); writeThread.Name = "Controller #" + index + " Output"; writeThread.Start(); inputThread.Start(); }
/// <summary> /// Cleans up all open connections. This should be called when you are done using the card. /// </summary> public void dispose() { if (_stream != null) { _stream.Close(); _stream = null; } }
public static void SaveSettingToMCU(this HidStream stream) { byte[] save = new byte[64]; save[0] = 0xCC; save[1] = 0x5E; stream.SendPacket(save); }
private void Download_Click(object sender, RoutedEventArgs e) { var path = Path.Text; byte[] binary = new Byte[1024]; HidStream hidStream = device.Open(); if (!string.IsNullOrEmpty(path)) { if (!File.Exists(path)) { lbl_status.Text = "配列文件不存在"; return; } if (path.EndsWith("bin", StringComparison.CurrentCultureIgnoreCase)) { using (var stream = File.Open(path, FileMode.Open)) { stream.Read(binary, 0, 1024); } } else { HexFileReader reader = new HexFileReader(path, 1024); MemoryBlock memoryRepresentation = reader.Parse(); int index = 0; foreach (var item in memoryRepresentation.Cells) { binary[index++] = item.Value; if (index == 1024) { break; } } } // 第一个Byte为0x55代表启用此Keymap binary[0] = 0x55; } try { byte[] packet = new byte[60]; for (int i = 0; i < (binary.Length / 60); i++) { Array.Copy(binary, i * 60, packet, 0, 60); SendPacket(hidStream, (uint)i, packet); } } catch (Exception exp) { lbl_status.Text = exp.Message; } lbl_status.Text = "完成"; }
/// <summary> /// Close the connection with the HDK. /// </summary> public void Close() { if (m_Stream != null) { m_Stream.Dispose(); m_Stream.Close(); m_Stream = null; } }
public HidDevice FindDevice(int?VendorID, int?ProductID) { HidDevice hidDevice = null; foreach (var device in DeviceList.Local.GetHidDevices(VendorID, ProductID)) { Console.WriteLine(device.DevicePath); HidStream hstrm = null; try { device.TryOpen(out hstrm); if (hstrm == null) { continue; } var GetProtocolRequest = BuildMessage(Commands.Protocol_GetVersion); hstrm.Write(GetProtocolRequest); byte[] response = hstrm.Read(); if (response[1] == (byte)Commands.Protocol_GetVersion) { if (response[2] != 0x01) { throw new Exception($"Expected Length is wrong: {response[1].ToString()}"); } if (response[3] != PROTOCOL_VERSION) { throw new Exception($"Unsupported protocol version:{response[2].ToString()}"); } Console.WriteLine("Negotiation successful."); Console.WriteLine(device.GetManufacturer() + " " + device.GetProductName()); hidDevice = device; break; } else { throw new Exception($"Unsupported firmware:{response[0].ToString()}"); } } catch (Exception e) { // Not a RawHID Device!! //Console.WriteLine(e.ToString()); } finally { hstrm?.Close(); } } return(hidDevice); }
bool SearchDevices() { if (hidStream != null) { hidStream.Dispose(); hidStream = null; } var list = DeviceList.Local; var dev = list.GetHidDevices().FirstOrDefault(d => d.GetProductName().Contains("FrSky")); if (dev == null) { Console.WriteLine("No FrSky device found."); return(false); } if (dev.TryOpen(out hidStream)) { hidStream.ReadTimeout = Timeout.Infinite; var inputReportBuffer = new byte[dev.GetMaxInputReportLength()]; var rawReportDescriptor = dev.GetRawReportDescriptor(); var reportDescriptor = dev.GetReportDescriptor(); var inputReceiver = reportDescriptor.CreateHidDeviceInputReceiver(); foreach (var deviceItem in reportDescriptor.DeviceItems) { var inputParser = deviceItem.CreateDeviceItemInputParser(); inputReceiver.Received += (sender, e) => { Report report; while (inputReceiver.TryRead(inputReportBuffer, 0, out report)) { if (inputParser.TryParseReport(inputReportBuffer, 0, report)) { WriteDeviceItemInputParserResult(inputParser); } } if (oldState == null || !controllerState.Equals(oldState)) { Console.WriteLine(controllerState); UpdateControlState(); oldState = controllerState.Clone(); } }; } inputReceiver.Start(hidStream); Console.WriteLine("FrSky device found and initialized."); } else { Console.WriteLine($"Can't open device {dev.GetFriendlyName()}. Check permissions for {dev.GetFileSystemName()}."); return(false); } return(true); }
private static void loop() { while (true) { HidDevice hidDevice = _co2DeviceHandler.connectDevice(VendorId, ProductId); HidStream stream = _co2DeviceHandler.openStream(hidDevice); DeviceLoop(stream); _co2DeviceHandler.closeStream(stream); } }
public void Dispose() { Trace.WriteLine("Releasing control of USB device..."); if (Stream != null) { Stream.Close(); Stream.Dispose(); Stream = null; } }
public RB3KeyboardController(HidDevice device, HidStream stream, ViGEmClient client, int index) : base(device, stream, client, index) { target360.FeedbackReceived += this.Target360_FeedbackReceived; targetDS4.FeedbackReceived += this.TargetDS4_FeedbackReceived; inputThread = new Thread(() => input_thread()); inputThread.Priority = ThreadPriority.AboveNormal; inputThread.Name = "Controller #" + index + " Input"; inputThread.Start(); }
/// <summary> /// Очищает всё FLASH-память /// </summary> public void EraseFlash() { using (HidStream stream = dev.Open()) { byte[] buffer = new byte[REPORT_SIZE]; buffer[REPORT_COMMAND] = (byte)(LoaderCommand.EraseFlash | LoaderCommand.ResetAddress); SignBuffer(buffer); stream.SetFeature(buffer); } }
/// <summary> /// Выходит из режима загрузчика /// </summary> /// <remarks> /// Загрузчик должен быть скомпилирован с поддержкой выхода /// </remarks> public void LeaveBootloader() { using (HidStream stream = dev.Open()) { byte[] buffer = new byte[REPORT_SIZE]; buffer[REPORT_COMMAND] = (byte)LoaderCommand.LeaveBootloader; SignBuffer(buffer); stream.SetFeature(buffer); } }
public static void SubmitUpdate(HidStream device) { byte[] submit = new byte[] { 0x00, 0x33, 0xFF, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; device.Write(submit); }
/// <summary> /// Очищает весь EEPROM /// </summary> /// <remarks> /// Загрузчик должен быть скомпилирован с поддержкой очистки EEPROM /// </remarks> public void EraseEeprom() { using (HidStream stream = dev.Open()) { byte[] buffer = new byte[REPORT_SIZE]; buffer[REPORT_COMMAND] = (byte)LoaderCommand.EraseEeprom; SignBuffer(buffer); stream.SetFeature(buffer); } }
public RedragonImpactMouse() { var devices = FilteredDeviceList .Local .GetHidDevices(VendorId, ProductId) .ToArray(); _device = devices.First(d => d.DevicePath.Contains("mi_02&col02")); _deviceStream = _device.Open(); }
public void Start() { this.hidDevice = FindDevice(this.VendorId, this.ProductId); DeviceList.Local.Changed += (object sender, DeviceListChangedEventArgs a) => { if (this.hidDevice == null) { this.hidDevice = FindDevice(this.VendorId, this.ProductId); } }; readThread = new Thread(() => { while (true) { if (hidDevice == null) { Console.WriteLine("No Numpad found, searching in background..."); while (hidDevice == null) { Thread.Sleep(100); } } if (hidDevice.TryOpen(out hidStream)) { hidStream.ReadTimeout = Timeout.Infinite; while (true) { try { byte[] report = hidStream.Read(); this.RaiseEventOnUIThread(MessageReceived, new object[] { report }); } catch (Exception e) { hidStream?.Close(); hidDevice = null; hidStream = null; break; } } } else { Console.WriteLine("Error communicating with HID device."); continue; } hidStream?.Close(); } }); readThread.Start(); }
public HidDeviceProxy(HidDevice device) { _device = device; _stream = device.Open(); _stream.ReadTimeout = 1000; _stream.WriteTimeout = 1000; _writeBuffer = new byte[_device.GetMaxOutputReportLength()]; _readBuffer = new byte[_device.GetMaxInputReportLength()]; }
protected virtual void PrintUsbDevices() { var devices = HidStream.EnumerateDevices().ToArray(); var sb = new System.Text.StringBuilder(); for (int i = 0, imax = devices.Length; i < imax; ++i) { sb.AppendLine(string.Format("name:{0} path:{1}", devices[i].product_string, devices[i].path)); } Log.v("XHawkService", "Devices:\n" + sb.ToString()); }
private void DisposeConnection() { if (dStream is null) { return; } dStream.Dispose(); dStream = null; ConnectionStateChanged?.Invoke(this, new ConnectionEventArgs(false)); }
public static void SendData(this HidStream stream, byte[] buffer) { if (useStreamWrite) { stream.Write(buffer); } else { stream.SetFeature(buffer); } }
public int Init() { var stream = GetFusionKbdStream(); if (stream == null) { return(-1); } _stream = stream; return(0); }
public void Stop() { lock (StreamLock) { hidStream?.Close(); } hidDevice = null; hidStream = null; readThread.Abort(); }
private void DoWork(object sender, DoWorkEventArgs e) { if (_worker.CancellationPending) { e.Cancel = true; } HidDevice headset = DeviceList.Local.GetHidDeviceOrNull(_vendorId, _productId); if (headset == null) { UpdateError("device not found"); return; } using (HidStream stream = headset.Open()) { stream.ReadTimeout = int.MaxValue; // i hate this so much while (true) { byte[] buf; try { buf = stream.Read(); } catch (TimeoutException) { Debug.WriteLine("Timed out. How the f**k?"); continue; } Debug.WriteLine($"Received packet: length {buf.Length}, payload {BitConverter.ToString(buf)}"); if (buf.Length != 5) { continue; } // indicators if (buf[0] != 0x64 || buf[4] != 0x01) { continue; } int value = buf[2] & 0x7F; Debug.WriteLine($"Registering new value: {value}"); Packets.RegisterPacket(value); UpdateBattery(Packets.CurrentLevel); } } }
public BasePointer(IVirtualScreen screen, byte ReportID, string Name) { Report = new T { ReportID = ReportID }; VirtualScreen = screen; Device = VMultiDevice.Retrieve(Name); ScreenToVMulti = new Vector2(VirtualScreen.Width, VirtualScreen.Height) / 32767; }
// TODO: Handle the case where the library user is not calling TryRead fast enough for the HID device. /// <summary> /// Starts the receiver. It will continue until the stream is closed or the device is disconnected. /// Be sure to call <see cref="TryRead"/> to read HID reports as they come in. /// </summary> /// <param name="stream">The stream to receive on.</param> public void Start(HidStream stream) { Throw.If.Null(stream); lock (_syncRoot) { int length = _maxInputReportLength; if (length == 0) { return; } // Nothing to parse. stream.ReadTimeout = Timeout.Infinite; if (_running) { throw new InvalidOperationException("The receiver is already running."); } _running = true; _stream = stream; byte[] buffer = new byte[length * 16]; Action beginRead = null; AsyncCallback endRead = null; beginRead = () => { try { stream.BeginRead(buffer, 0, buffer.Length, endRead, null); } catch { Stop(); return; } }; endRead = ar => { int count; try { count = stream.EndRead(ar); } catch { Stop(); return; } if (count == 0) { Stop(); return; } ProvideReceivedData(buffer, 0, count); beginRead(); }; beginRead(); _waitHandle.Reset(); } var ev = Started; if (ev != null) { ev(this, EventArgs.Empty); } }