-
Notifications
You must be signed in to change notification settings - Fork 586
/
UnixSpiDevice.Linux.cs
242 lines (206 loc) · 8.46 KB
/
UnixSpiDevice.Linux.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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Device.Gpio;
using System.IO;
using System.Runtime.InteropServices;
namespace System.Device.Spi
{
/// <summary>
/// Represents a SPI communication channel running on Unix.
/// </summary>
internal class UnixSpiDevice : SpiDevice
{
private const string DefaultDevicePath = "/dev/spidev";
private const uint SPI_IOC_MESSAGE_1 = 0x40206b00;
private static readonly object s_initializationLock = new object();
private readonly SpiConnectionSettings _settings;
private int _deviceFileDescriptor = -1;
/// <summary>
/// Initializes a new instance of the <see cref="UnixSpiDevice"/> class that will use the specified settings to communicate with the SPI device.
/// </summary>
/// <param name="settings">
/// The connection settings of a device on a SPI bus.
/// </param>
public UnixSpiDevice(SpiConnectionSettings settings)
{
_settings = settings;
DevicePath = DefaultDevicePath;
}
/// <summary>
/// Path to SPI resources located on the platform.
/// </summary>
public string DevicePath { get; set; }
/// <summary>
/// The connection settings of a device on a SPI bus. The connection settings are immutable after the device is created
/// so the object returned will be a clone of the settings object.
/// </summary>
public override SpiConnectionSettings ConnectionSettings => new SpiConnectionSettings(_settings);
private unsafe void Initialize()
{
if (_deviceFileDescriptor >= 0)
{
return;
}
lock (s_initializationLock)
{
string deviceFileName = $"{DevicePath}{_settings.BusId}.{_settings.ChipSelectLine}";
if (_deviceFileDescriptor >= 0)
{
return;
}
_deviceFileDescriptor = Interop.open(deviceFileName, FileOpenFlags.O_RDWR);
if (_deviceFileDescriptor < 0)
{
throw new IOException($"Error {Marshal.GetLastWin32Error()}. Can not open SPI device file '{deviceFileName}'.");
}
UnixSpiMode mode = SpiSettingsToUnixSpiMode();
IntPtr nativePtr = new IntPtr(&mode);
int result = Interop.ioctl(_deviceFileDescriptor, (uint)SpiSettings.SPI_IOC_WR_MODE, nativePtr);
if (result == -1)
{
throw new IOException($"Error {Marshal.GetLastWin32Error()}. Can not set SPI mode to {_settings.Mode}.");
}
byte dataLengthInBits = (byte)_settings.DataBitLength;
nativePtr = new IntPtr(&dataLengthInBits);
result = Interop.ioctl(_deviceFileDescriptor, (uint)SpiSettings.SPI_IOC_WR_BITS_PER_WORD, nativePtr);
if (result == -1)
{
throw new IOException($"Error {Marshal.GetLastWin32Error()}. Can not set SPI data bit length to {_settings.DataBitLength}.");
}
int clockFrequency = _settings.ClockFrequency;
nativePtr = new IntPtr(&clockFrequency);
result = Interop.ioctl(_deviceFileDescriptor, (uint)SpiSettings.SPI_IOC_WR_MAX_SPEED_HZ, nativePtr);
if (result == -1)
{
throw new IOException($"Error {Marshal.GetLastWin32Error()}. Can not set SPI clock frequency to {_settings.ClockFrequency}.");
}
}
}
private UnixSpiMode SpiSettingsToUnixSpiMode()
{
UnixSpiMode mode = SpiModeToUnixSpiMode(_settings.Mode);
if (_settings.ChipSelectLineActiveState == PinValue.High)
{
mode |= UnixSpiMode.SPI_CS_HIGH;
}
if (_settings.DataFlow == DataFlow.LsbFirst)
{
mode |= UnixSpiMode.SPI_LSB_FIRST;
}
return mode;
}
private UnixSpiMode SpiModeToUnixSpiMode(SpiMode mode)
{
return mode switch
{
SpiMode.Mode0 => UnixSpiMode.SPI_MODE_0,
SpiMode.Mode1 => UnixSpiMode.SPI_MODE_1,
SpiMode.Mode2 => UnixSpiMode.SPI_MODE_2,
SpiMode.Mode3 => UnixSpiMode.SPI_MODE_3,
_ => throw new ArgumentException("Invalid SPI mode.", nameof(mode))
};
}
/// <summary>
/// Reads a byte from the SPI device.
/// </summary>
/// <returns>A byte read from the SPI device.</returns>
public override unsafe byte ReadByte()
{
Initialize();
int length = sizeof(byte);
byte result = 0;
Transfer(null, &result, length);
return result;
}
/// <summary>
/// Reads data from the SPI device.
/// </summary>
/// <param name="buffer">
/// The buffer to read the data from the SPI device.
/// The length of the buffer determines how much data to read from the SPI device.
/// </param>
public override unsafe void Read(Span<byte> buffer)
{
if (buffer.Length == 0)
{
throw new ArgumentException($"{nameof(buffer)} cannot be empty.");
}
Initialize();
fixed (byte* bufferPtr = buffer)
{
Transfer(null, bufferPtr, buffer.Length);
}
}
/// <summary>
/// Writes a byte to the SPI device.
/// </summary>
/// <param name="value">The byte to be written to the SPI device.</param>
public override unsafe void WriteByte(byte value)
{
Initialize();
int length = sizeof(byte);
Transfer(&value, null, length);
}
/// <summary>
/// Writes data to the SPI device.
/// </summary>
/// <param name="buffer">
/// The buffer that contains the data to be written to the SPI device.
/// </param>
public override unsafe void Write(ReadOnlySpan<byte> buffer)
{
Initialize();
fixed (byte* dataPtr = buffer)
{
Transfer(dataPtr, null, buffer.Length);
}
}
/// <summary>
/// Writes and reads data from the SPI device.
/// </summary>
/// <param name="writeBuffer">The buffer that contains the data to be written to the SPI device.</param>
/// <param name="readBuffer">The buffer to read the data from the SPI device.</param>
public override unsafe void TransferFullDuplex(ReadOnlySpan<byte> writeBuffer, Span<byte> readBuffer)
{
Initialize();
if (writeBuffer.Length != readBuffer.Length)
{
throw new ArgumentException($"Parameters '{nameof(writeBuffer)}' and '{nameof(readBuffer)}' must have the same length.");
}
fixed (byte* writeBufferPtr = writeBuffer)
{
fixed (byte* readBufferPtr = readBuffer)
{
Transfer(writeBufferPtr, readBufferPtr, writeBuffer.Length);
}
}
}
private unsafe void Transfer(byte* writeBufferPtr, byte* readBufferPtr, int buffersLength)
{
var tr = new spi_ioc_transfer()
{
tx_buf = (ulong)writeBufferPtr,
rx_buf = (ulong)readBufferPtr,
len = (uint)buffersLength,
speed_hz = (uint)_settings.ClockFrequency,
bits_per_word = (byte)_settings.DataBitLength,
delay_usecs = 0
};
int result = Interop.ioctl(_deviceFileDescriptor, SPI_IOC_MESSAGE_1, new IntPtr(&tr));
if (result < 1)
{
throw new IOException($"Error {Marshal.GetLastWin32Error()} performing SPI data transfer.");
}
}
protected override void Dispose(bool disposing)
{
if (_deviceFileDescriptor >= 0)
{
Interop.close(_deviceFileDescriptor);
_deviceFileDescriptor = -1;
}
base.Dispose(disposing);
}
}
}