-
Notifications
You must be signed in to change notification settings - Fork 4
/
FastbootUsbDevice.cs
115 lines (99 loc) · 3.16 KB
/
FastbootUsbDevice.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
using LibUsbDotNet.Main;
using LibUsbDotNet;
using System.Text;
namespace quest_bootloader_unlocker
{
public class FastbootUsbDevice : IDisposable
{
private UsbDeviceFinder _usbDeviceFinder;
private UsbDevice? _device;
private UsbEndpointReader? _readEnpoint;
private UsbEndpointWriter? _writeEndpoint;
private object _readBufferLock;
private List<byte> _readBuffer;
public FastbootUsbDevice(int vid, int pid)
{
_usbDeviceFinder = new UsbDeviceFinder(vid, pid);
_readBufferLock = new object();
_readBuffer = new List<byte>();
_device = null;
_readEnpoint = null;
_writeEndpoint = null;
}
public bool IsConnected()
{
return UsbDevice.AllDevices.Select(v => v.DevicePath).Contains(_device?.DevicePath);
}
public bool TryConnect()
{
_device = UsbDevice.OpenUsbDevice(_usbDeviceFinder);
if (_device == null)
return false;
_readEnpoint = _device.OpenEndpointReader(ReadEndpointID.Ep01);
_writeEndpoint = _device.OpenEndpointWriter(WriteEndpointID.Ep01);
_readEnpoint.DataReceived += (sender, args) =>
{
lock(_readBufferLock)
{
var buffer = new byte[args.Count];
Array.Copy(args.Buffer, buffer, args.Count);
_readBuffer.AddRange(buffer);
_readBuffer.Add((byte)'\n');
}
};
_readEnpoint.DataReceivedEnabled = true;
return true;
}
public bool Close()
{
if (_device == null)
{
return false;
}
if (!IsConnected())
return false;
return _device.Close();
}
public int? Write(byte[] buffer)
{
if (!IsConnected())
return null;
int bytesWritten;
_writeEndpoint.Write(buffer, 10000, out bytesWritten);
return bytesWritten;
}
public int? WriteS(string data)
{
if (!IsConnected())
return null;
return Write(Encoding.ASCII.GetBytes(data));
}
public byte[]? Read()
{
if(!IsConnected())
return null;
lock(_readBufferLock)
{
if (_readBuffer.Count == 0)
return null;
var data = _readBuffer.ToArray();
_readBuffer.Clear();
return data;
}
}
public string? ReadS()
{
if (!IsConnected())
return null;
var data = Read();
if(data == null)
return null;
return Encoding.ASCII.GetString(data);
}
public void Dispose()
{
_readEnpoint?.Dispose();
_writeEndpoint?.Dispose();
}
}
}