public static void Main(string[] Args) { Initialize(); Warn.LLogL("Make sure to open Goldtree after having opened Goldleaf on your console. Looking for connection..."); try { var pat = new KLST_PATTERN_MATCH { DeviceID = @"USB\VID_057E&PID_3000" }; var lst = new LstK(0, ref pat); lst.MoveNext(out var dinfo); USB = new UsbK(dinfo); Log.LogL("Connection was established."); } catch { Error.LLogL("Unable to find USB communication. Are you sure Goldleaf is open and plugged in?"); } Console.WriteLine(); while (true) { USB.CommandHandleLoop(); } Error.LLogL("An error ocurred handling Goldleaf's latest command request."); }
public MainForm() { InitializeComponent(); ViewerButton.Enabled = Utils.IsWindows(); if (Utils.IsWindows()) { try { var pat = new KLST_PATTERN_MATCH { DeviceID = @"USB\VID_057E&PID_3000" }; var lst = new LstK(0, ref pat); lst.MoveNext(out var dinfo); USB = new UsbK(dinfo); } catch { } if (USB == null) { ViewerButton.Enabled = false; } } var drive = Utils.DetectSDCardDrive(); if (drive != null) { EntryManagerButton.Enabled = true; PluginButton.Enabled = true; FoundDriveText.Text = "Found SD card on drive \"" + drive.VolumeLabel + "\" (" + drive.Name + ")"; } }
public static byte[] ReadBuffer(this UsbK USB, ulong Size) { var data = new byte[Size]; USB.ReadPipe(ReadPipeId, data, (int)Size, out int _, IntPtr.Zero); return(data); }
public UsbStream(UsbK usb, byte pipeId, int maxTransferSize, int maxPendingTransfers, int maxPendingIo, bool useTimeout, UInt16 timeout) { mUsb = usb; mPipeId = pipeId; if (UseCallbacks) { mCallbacks.Complete = StmComplete; if (((mPipeId & AllKConstants.USB_ENDPOINT_DIRECTION_MASK) > 0)) { mCallbacks.Submit = StmSubmitRead; } else { mCallbacks.Submit = StmSubmitWrite; } } KSTM_FLAG flags = useTimeout ? KSTM_FLAG.USE_TIMEOUT | (KSTM_FLAG)timeout : KSTM_FLAG.NONE; mStm = new StmK(mUsb.Handle, pipeId, maxTransferSize, maxPendingTransfers, maxPendingIo, ref mCallbacks, flags); }
private void connect(bool re) { try { var pat = new KLST_PATTERN_MATCH { DeviceID = @"USB\VID_057E&PID_3000" }; var lst = new LstK(0, ref pat); lst.MoveNext(out var dinfo); this.USB = new UsbK(dinfo); } catch (Exception) { this.USB = null; } if (this.USB == null) { MessageBox.Show("No Switch running uLaunch detected!"); disconnect(); } else { if (!re) { MessageBox.Show("Switch running uLaunch detected, continuing!"); } miConn.IsEnabled = false; miReConn.IsEnabled = true; miDisConn.IsEnabled = true; USBThread = new Thread(new ThreadStart(USBThreadMain)); USBThread.Start(); } }
//! Custom vendor requests that must be implemented in the benchmark firmware. #region Public Members public static bool Configure(UsbK usb, BM_COMMAND command, byte interfaceNumber, ref BM_TEST_TYPE testType) { int transferred; WINUSB_SETUP_PACKET pkt; byte[] data = new byte[1]; pkt.RequestType = (1 << 7) | (2 << 5); pkt.Request = (byte)command; pkt.Value = (ushort)testType; pkt.Index = interfaceNumber; pkt.Length = 1; bool success = usb.ControlTransfer(pkt, Marshal.UnsafeAddrOfPinnedArrayElement(data, 0), 1, out transferred, IntPtr.Zero); testType = (BM_TEST_TYPE)data[0]; return(success); }
public static Command Read(this UsbK USB) { Command cmd = new Command(); USB.Read(out uint magic); USB.Read(out uint cmdid); cmd.Magic = magic; cmd.CommandId = (CommandId)cmdid; return(cmd); }
private static void Write(UsbK wrt, byte[] payload) { var buffer = new byte[0x1000]; for (var i = 0; i < payload.Length - 1; i += 0x1000, _writes++) { Buffer.BlockCopy(payload, i, buffer, 0, 0x1000); wrt.WritePipe(1, buffer, 0x1000, out _, IntPtr.Zero); } }
private void CloseDevice() { lock (UsbLock) { if (DriverAPI != null) { DriverAPI.Free(); // Problematic... DriverAPI = null; } } }
protected override void Dispose(bool disposing) { if (!mbDisposed) { mStm.Dispose(); mStm = null; mUsb = null; mbDisposed = true; } base.Dispose(disposing); }
public ViewerMainForm(UsbK USB) { InitializeComponent(); InitializePictureBox(CaptureBox); this.USB = USB; Toolbox = new ToolboxForm(this); Toolbox.Show(); USBThread = new Thread(new ThreadStart(USBThreadMain)); USBThread.Start(); }
private void disconnect() { if (USBThread != null) { USBThread.Abort(); } disconnected = false; this.USB = null; miConn.IsEnabled = true; miDisConn.IsEnabled = false; miReConn.IsEnabled = false; InitializeCaptureBox(iCapture); }
public static CommandReadResult ReadCommandInput(this UsbK USB, out NewCommandId Type) { CommandReadResult res = CommandReadResult.Success; uint magic = USB.Read32(); while (magic == 0) { magic = USB.Read32(); } uint cmdid = USB.Read32(); Type = (NewCommandId)cmdid; return(res); }
public bool FindPipeAndInterface(UsbK usb, out USB_INTERFACE_DESCRIPTOR interfaceDescriptor, out WINUSB_PIPE_INFORMATION pipeInfo) { if (FindPipeAndInterface(usb, out interfaceDescriptor, out pipeInfo, AltInterfaceId, PipeId)) { AltInterfaceId = interfaceDescriptor.bAlternateSetting; PipeId = pipeInfo.PipeId; return(true); } return(false); }
// Note: set pipeId's to 0xff to pick default bulk endpoints. private UsbLinkDevice(KLST_DEVINFO_HANDLE deviceInfo, byte readPipeId = 0xff, byte writePipeId = 0xff) { AllocId = ++AllocCounter; UsbLock = new Object(); DriverAPI = null; IsFTDI = false; TempWriteBuffer = new byte[UsbMaxBufferSize]; TempReadBuffer = new byte[UsbMaxBufferSize]; TempControlBuffer = new byte[UsbMaxBufferSize]; // SUPER IMPORTANT: // IO buffers MUST be pinned to stop GC moving them, // Otherwise read/writes will be corrupted! gcHndWrite = GCHandle.Alloc(TempWriteBuffer, GCHandleType.Pinned); gcHndRead = GCHandle.Alloc(TempReadBuffer, GCHandleType.Pinned); gcHndControl = GCHandle.Alloc(TempControlBuffer, GCHandleType.Pinned); InitDevice(deviceInfo, readPipeId, writePipeId); }
public static bool FindPipeAndInterface(UsbK usb, out USB_INTERFACE_DESCRIPTOR interfaceDescriptor, out WINUSB_PIPE_INFORMATION pipeInfo, int altInterfaceId, int pipeId) { byte interfaceIndex = 0; interfaceDescriptor = new USB_INTERFACE_DESCRIPTOR(); pipeInfo = new WINUSB_PIPE_INFORMATION(); while (usb.SelectInterface(interfaceIndex, true)) { byte altSettingNumber = 0; while (usb.QueryInterfaceSettings(altSettingNumber, out interfaceDescriptor)) { if (altInterfaceId == -1 || altInterfaceId == altSettingNumber) { byte pipeIndex = 0; while (usb.QueryPipe(altSettingNumber, pipeIndex++, out pipeInfo)) { if ((pipeInfo.MaximumPacketSize > 0) && pipeId == -1 || pipeInfo.PipeId == pipeId || ((pipeId & 0xF) == 0 && ((pipeId & 0x80) == (pipeInfo.PipeId & 0x80)))) { goto FindInterfaceDone; } pipeInfo.PipeId = 0; } } altSettingNumber++; } interfaceIndex++; } FindInterfaceDone: return(pipeInfo.PipeId != 0); }
public static CommandReadResult ReadCommandInput(this UsbK USB, out CommandId Type) { CommandReadResult res = CommandReadResult.Success; uint magic = 0; do { magic = USB.Read32(); } while(magic != Command.GLUC); uint cmdid = USB.Read32(); Type = (CommandId)cmdid; if (magic != Command.GLUC) { res = CommandReadResult.InvalidMagic; } if (cmdid >= (uint)CommandId.Max) { res = CommandReadResult.InvalidCommandId; } return(res); }
public ReadIsoTransferQueue(UsbK usb, ref WINUSB_PIPE_INFORMATION pipeInfo, int maxPendingTransfers, int numberOfPackets) { PipeInfo = pipeInfo; Usb = usb; OvlPool = new OvlK(usb.Handle, maxPendingTransfers, KOVL_POOL_FLAG.NONE); DataBufferSize = (pipeInfo.MaximumPacketSize * numberOfPackets); for (int pos = 0; pos < maxPendingTransfers; pos++) { IsoTransferItem isoTransferItem = new IsoTransferItem(); isoTransferItem.Buffer = new byte[pipeInfo.MaximumPacketSize * numberOfPackets]; isoTransferItem.BufferGC = GCHandle.Alloc(isoTransferItem.Buffer, GCHandleType.Pinned); isoTransferItem.Iso = new IsoK(numberOfPackets, 0); isoTransferItem.Iso.SetPackets(pipeInfo.MaximumPacketSize); OvlPool.Acquire(out isoTransferItem.Ovl); Master.AddLast(isoTransferItem); Completed.AddLast(isoTransferItem); } }
public static void Refresh() { WMIDeviceInfo = null; Device = null; DeviceWrapper = null; foreach (UsbDeviceInfo info in CreateUsbControllerDeviceInfos(GetUsbDevices())) { if (info.DeviceID.StartsWith($"USB\\VID_{VID}&PID_{PID}")) { WMIDeviceInfo = info; var patternMatch = new KLST_PATTERN_MATCH { ClassGUID = WMIDeviceInfo.ClassGuid }; var deviceList = new LstK(0, ref patternMatch); deviceList.MoveNext(out KLST_DEVINFO_HANDLE deviceInfo); Device = new UsbK(deviceInfo); Device.SetAltInterface(0, false, 0); DeviceWrapper = new UsbKWrapper(Device); break; } } }
public static void Scan() { WMIDeviceInfo = null; Device = null; DeviceWrapper = null; foreach (UsbDeviceInfo info in AllUsbDevices) { if (info.DeviceID.StartsWith($"USB\\VID_{VID}&PID_{PID}")) { WMIDeviceInfo = info; if (!LibusbKInstalled) { MessageBoxResult result = MessageBox.Show("You have plugged in your console, but it lacks the libusbK driver. Want to install it? (You cannot inject anything until this is done)", "", MessageBoxButton.YesNo); if (result == MessageBoxResult.Yes) { InstallDriver(); } WMIDeviceInfo = AllUsbDevices.First(x => x.DeviceID == WMIDeviceInfo.DeviceID); // we need to refresh the info } if (LibusbKInstalled) { var patternMatch = new KLST_PATTERN_MATCH { ClassGUID = WMIDeviceInfo.ClassGuid }; var deviceList = new LstK(0, ref patternMatch); deviceList.MoveNext(out KLST_DEVINFO_HANDLE deviceInfo); Device = new UsbK(deviceInfo); Device.SetAltInterface(0, false, 0); DeviceWrapper = new UsbKWrapper(Device); } break; } } }
public ViewerMainForm() { InitializeComponent(); InitializePictureBox(CaptureBox); try { var pat = new KLST_PATTERN_MATCH { DeviceID = @"USB\VID_057E&PID_3000" }; var lst = new LstK(0, ref pat); lst.MoveNext(out var dinfo); USB = new UsbK(dinfo); } catch { } Toolbox = new ToolboxForm(this); Toolbox.Show(); USBThread = new Thread(new ThreadStart(USBThreadMain)); USBThread.Start(); }
public static void Main(string[] Args) { Initialize(); Warn.LLogL("Make sure Goldleaf is already opened and the console is connected to this system via USB. Looking for connection..."); try { var pat = new KLST_PATTERN_MATCH { DeviceID = @"USB\VID_057E&PID_3000" }; var lst = new LstK(0, ref pat); lst.MoveNext(out var dinfo); USB = new UsbK(dinfo); Log.LogL("Connection with Goldleaf was established."); } catch { Error.LLogL("Unable to find connection. Have you installed libusbK drivers? Are you sure Goldleaf is open and the USB icon is shown there?"); } Console.WriteLine(); while (true) { USB.CommandHandleLoop(); } }
public bool ConfigureDevice(out WINUSB_PIPE_INFORMATION pipeInfo, out UsbK usb, out USB_INTERFACE_DESCRIPTOR interfaceDescriptor) { bool success; Console.WriteLine("Finding usb device by VID/PID.. ({0:X4}h / {1:X4}h)", Vid, Pid); // Use a patttern match to include only matching devices. // NOTE: You can use the '*' and '?' chars as wildcards for all chars or a single char (respectively). KLST_PATTERN_MATCH patternMatch = new KLST_PATTERN_MATCH(); if (MI != -1) patternMatch.DeviceID = String.Format("USB\\VID_{0:X4}&PID_{1:X4}&MI_{2:X2}*", Vid, Pid, MI); else patternMatch.DeviceID = String.Format("USB\\VID_{0:X4}&PID_{1:X4}*", Vid, Pid); LstK deviceList = new LstK(KLST_FLAG.NONE, ref patternMatch); KLST_DEVINFO_HANDLE deviceInfo; interfaceDescriptor = new USB_INTERFACE_DESCRIPTOR(); pipeInfo = new WINUSB_PIPE_INFORMATION(); usb = null; // Iterate the devices looking for a matching alt-interface and endpoint id. while (deviceList.MoveNext(out deviceInfo)) { // libusbK class contructors can throw exceptions; For instance, if the device is // using the WinUsb driver and already in-use by another application. Console.WriteLine("Opening usb device.."); usb = new UsbK(deviceInfo); Console.WriteLine("Finding interface and endpoint by PipeId.."); success = FindPipeAndInterface(usb, out interfaceDescriptor, out pipeInfo); if (success) break; Console.WriteLine("PipeId {0:X2}h not found on this device.", PipeId); usb.Free(); usb = null; } if (ReferenceEquals(usb, null)) { Console.WriteLine("Usb device not found: {0}", patternMatch.DeviceID); success = false; goto Done; } MI = interfaceDescriptor.bInterfaceNumber; AltInterfaceId = interfaceDescriptor.bAlternateSetting; PipeId = pipeInfo.PipeId; // Set interface alt setting. Console.WriteLine("Setting interface #{0} to bAlternateSetting #{1}..", interfaceDescriptor.bInterfaceNumber, interfaceDescriptor.bAlternateSetting); success = usb.SetAltInterface(interfaceDescriptor.bInterfaceNumber, false, interfaceDescriptor.bAlternateSetting); if (!success) { Console.WriteLine("SetAltInterface failed. ErrorCode={0:X8}h", Marshal.GetLastWin32Error()); Console.WriteLine(interfaceDescriptor.ToString()); } Done: deviceList.Free(); return success; }
// When device is (re)connected, enumerate endpoints and set policy. // Returns null on success or error message. private string ConfigureDevice(KLST_DEVINFO_HANDLE deviceInfo, bool checkForAccessory = false) { IsWriting = false; IsReading = false; if (State != ComponentState.Unresponsive || checkForAccessory || DriverAPI == null) { // libusbK class contructors can throw exceptions; For instance, if the device is // using the WinUsb driver and already in-use by another application. // This could happen if this App was previsouly aborted. try { if (DriverAPI != null) { DriverClose(); } DriverAPI = new UsbK(deviceInfo); } catch (Exception e) { DriverAPI = null; return("Unable to initialize device:" + e.Message); } } try { DriverAPI.ResetDevice(); } catch (Exception e) { return("Unable to reset device:" + e.Message); } // Find Pipe And Interface. byte interfaceIndex = 0; bool hasRead = false, hasWrite = false; USB_INTERFACE_DESCRIPTOR InterfaceDescriptor; WINUSB_PIPE_INFORMATION PipeInfo; while (DriverAPI.SelectInterface(interfaceIndex, true)) { byte altSettingNumber = 0; while (DriverAPI.QueryInterfaceSettings(altSettingNumber, out InterfaceDescriptor)) { if (AltInterfaceId == -1 || AltInterfaceId == altSettingNumber) { byte pipeIndex = 0; while (DriverAPI.QueryPipe(altSettingNumber, pipeIndex++, out PipeInfo)) { if (PipeInfo.MaximumPacketSize > 0) { if (!hasRead && ((PipeInfo.PipeId == ReadPipeId) || ((((ReadPipeId & 0xF) == 0) || (ReadPipeId == 0xff)) && ((ReadPipeId & 0x80) == (PipeInfo.PipeId & 0x80)))) ) { ReadPipeId = PipeInfo.PipeId; hasRead = true; } if (!hasWrite && ((PipeInfo.PipeId == WritePipeId) || ((((WritePipeId & 0xF) == 0) || (WritePipeId == 0x7f)) && ((WritePipeId & 0x80) == (PipeInfo.PipeId & 0x80)))) ) { WritePipeId = PipeInfo.PipeId; hasWrite = true; if (TransferBufferSize == -1) { TransferBufferSize = PipeInfo.MaximumPacketSize; } } if (hasRead && hasWrite) { goto FindInterfaceDone; } } PipeInfo.PipeId = 0; } } altSettingNumber++; } interfaceIndex++; } FindInterfaceDone: if (!hasRead && !hasWrite) { return("Unable to open i/o pipes:R=" + hasRead + ",W=" + hasWrite + "."); } ReadPipeId |= 0x80; WritePipeId &= 0x7f; if (TransferBufferSize == -1) { TransferBufferSize = 64; } #if false // TODO: should test this. // Set interface alt setting. if (!DriverAPI.SetAltInterface(InterfaceDescriptor.bInterfaceNumber, false, InterfaceDescriptor.bAlternateSetting)) { return("Unable to set Alt Interface"); } #endif bool isAccessory = UsbLinkAccessory.IsAccessory(deviceInfo.Common.Vid, deviceInfo.Common.Pid); // Set configuration for accessory. if (isAccessory) { int configNum = 0; if (GetConfiguration(out configNum)) { if (configNum != 1) { if (!SetConfiguration(1)) { return("Unable to set configuration"); } } } } // In most cases, the pipe timeout policy should be set before using synchronous I/O. // By default, sync transfers wait infinitely for a transfer to complete. // Set the pipe timeout policy to 0 for infinite timeout. int[] pipeTimeoutMS = new[] { 0 }; int[] autoClearStall = new[] { 1 }; DriverAPI.SetPipePolicy(ReadPipeId, (int)PipePolicyType.PIPE_TRANSFER_TIMEOUT, Marshal.SizeOf(typeof(int)), pipeTimeoutMS); DriverAPI.SetPipePolicy(ReadPipeId, (int)PipePolicyType.AUTO_CLEAR_STALL, Marshal.SizeOf(typeof(int)), autoClearStall); DriverAPI.SetPipePolicy(WritePipeId, (int)PipePolicyType.PIPE_TRANSFER_TIMEOUT, Marshal.SizeOf(typeof(int)), pipeTimeoutMS); DriverAPI.SetPipePolicy(WritePipeId, (int)PipePolicyType.AUTO_CLEAR_STALL, Marshal.SizeOf(typeof(int)), autoClearStall); /* * int[] useRawIO = new[] { 1 }; * mUsb.SetPipePolicy(mReadPipeId, (int)PipePolicyType.RAW_IO, * Marshal.SizeOf(typeof(int)), useRawIO); */ // Next, check if it's an accessory. if (checkForAccessory && !isAccessory && UsbLinkAccessory.TryOpeningAccessory(this)) { return("Switching to accessory mode."); } // Finally, check if it's an FTDI device. IsFTDI = FTDIHandler.IsFtdiDevice(this); if (IsFTDI) { if (!FTDIHandler.ConfigureFTDI(this)) { return("Unable to configure FTDI device."); } } return(null); }
public static string ReadString(this UsbK USB) { uint strlen = USB.Read32(); return(Encoding.ASCII.GetString(USB.ReadBytes((int)strlen))); }
public static ulong Read64(this UsbK USB) { return(BitConverter.ToUInt64(USB.ReadBytes(8), 0)); }
public static uint Read32(this UsbK USB) { return(BitConverter.ToUInt32(USB.ReadBytes(4), 0)); }
public static byte Read8(this UsbK USB) { return(USB.ReadBytes(1)[0]); }
public static byte[] ReadBytes(this UsbK USB, int Length) { byte[] b = new byte[Length]; USB.ReadPipe(0x81, b, Length, out _, IntPtr.Zero); return(b); }
public static void WriteString(this UsbK USB, string Data) { USB.Write32((uint)Data.Length); USB.WriteBytes(Encoding.ASCII.GetBytes(Data)); }
public static void Write64(this UsbK USB, ulong Data) { USB.WriteBytes(BitConverter.GetBytes(Data)); }
public static bool FindPipeAndInterface(UsbK usb, out USB_INTERFACE_DESCRIPTOR interfaceDescriptor, out WINUSB_PIPE_INFORMATION pipeInfo, int altInterfaceId, int pipeId) { byte interfaceIndex = 0; interfaceDescriptor = new USB_INTERFACE_DESCRIPTOR(); pipeInfo = new WINUSB_PIPE_INFORMATION(); while (usb.SelectInterface(interfaceIndex, true)) { byte altSettingNumber = 0; while (usb.QueryInterfaceSettings(altSettingNumber, out interfaceDescriptor)) { if (altInterfaceId == -1 || altInterfaceId == altSettingNumber) { byte pipeIndex = 0; while (usb.QueryPipe(altSettingNumber, pipeIndex++, out pipeInfo)) { if ((pipeInfo.MaximumPacketSize > 0) && pipeId == -1 || pipeInfo.PipeId == pipeId || ((pipeId & 0xF) == 0 && ((pipeId & 0x80) == (pipeInfo.PipeId & 0x80)))) { goto FindInterfaceDone; } pipeInfo.PipeId = 0; } } altSettingNumber++; } interfaceIndex++; } FindInterfaceDone: return pipeInfo.PipeId != 0; }
public bool FindPipeAndInterface(UsbK usb, out USB_INTERFACE_DESCRIPTOR interfaceDescriptor, out WINUSB_PIPE_INFORMATION pipeInfo) { if (FindPipeAndInterface(usb, out interfaceDescriptor, out pipeInfo, AltInterfaceId, PipeId)) { AltInterfaceId = interfaceDescriptor.bAlternateSetting; PipeId = pipeInfo.PipeId; return true; } return false; }