forked from dotnet/iot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathArduinoBoard.cs
573 lines (499 loc) · 19.8 KB
/
ArduinoBoard.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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Device.Analog;
using System.Text;
using System.Device.Gpio;
using System.Device.I2c;
using System.Device.Pwm;
using System.Device.Spi;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.IO.Ports;
using System.Threading;
using System.Linq;
using Iot.Device.Common;
using Iot.Device.Board;
using Microsoft.Extensions.Logging;
using UnitsNet;
namespace Iot.Device.Arduino
{
/// <summary>
/// Implements an interface to an arduino board which is running Firmata.
/// See documentation on how to prepare your arduino board to work with this.
/// Note that the program will run on the PC, so you cannot disconnect the
/// Arduino while this driver is connected.
/// </summary>
public class ArduinoBoard : Board.Board, IDisposable
{
private SerialPort? _serialPort;
private Stream? _dataStream;
private FirmataDevice? _firmata;
private IReadOnlyList<SupportedPinConfiguration> _supportedPinConfigurations = new List<SupportedPinConfiguration>();
private bool _initialized;
private bool _isDisposed = false;
// Counts how many spi devices are attached, to make sure we enable/disable the bus only when no devices are attached
private int _spiEnabled = 0;
private Version _firmwareVersion = new Version();
private string _firmwareName = string.Empty;
private Version _firmataVersion = new Version();
private object _initializationLock = new object();
private ILogger _logger;
/// <summary>
/// Creates an instance of an Ardino board connection using the given stream (typically from a serial port)
/// </summary>
/// <remarks>
/// The device is initialized when the first command is sent. The constructor always succeeds.
/// </remarks>
/// <param name="serialPortStream">A stream to an Arduino/Firmata device</param>
public ArduinoBoard(Stream serialPortStream)
{
_dataStream = serialPortStream ?? throw new ArgumentNullException(nameof(serialPortStream));
_logger = this.GetCurrentClassLogger();
}
/// <summary>
/// Creates an instance of the Arduino board connection connected to a serial port
/// </summary>
/// The device is initialized when the first command is sent. The constructor always succeeds.
/// <param name="portName">Port name. On Windows, this is usually "COM3" or "COM4" for an Arduino attached via USB.
/// On Linux, possible values include "/dev/ttyAMA0", "/dev/serial0", "/dev/ttyUSB1", etc.</param>
/// <param name="baudRate">Baudrate to use. It is recommended to use at least 115200 Baud.</param>
public ArduinoBoard(string portName, int baudRate)
{
_dataStream = null;
_serialPort = new SerialPort(portName, baudRate);
_logger = this.GetCurrentClassLogger();
}
/// <summary>
/// The board logger.
/// </summary>
protected ILogger Logger => _logger;
/// <summary>
/// Searches the given list of com ports for a firmata device.
/// </summary>
/// <remarks>
/// Scanning ports and testing for devices may affect unrelated devices. It is advisable to exclude ports known to contain other hardware from this scan.
/// A board won't be found if its port is already open (by the same or a different process).
/// </remarks>
/// <param name="comPorts">List of com ports. Can be used with <see cref="SerialPort.GetPortNames"/>.</param>
/// <param name="baudRates">List of baud rates to test. <see cref="CommonBaudRates"/>.</param>
/// <param name="board">[Out] Returns the board reference. It is already initialized.</param>
/// <returns>True on success, false if no board was found</returns>
public static bool TryFindBoard(IEnumerable<string> comPorts, IEnumerable<int> baudRates,
#if NET5_0_OR_GREATER
[NotNullWhen(true)]
#endif
out ArduinoBoard? board)
{
foreach (var port in comPorts)
{
foreach (var baud in baudRates)
{
ArduinoBoard? b = null;
try
{
b = new ArduinoBoard(port, baud);
b.Initialize();
board = b;
return true;
}
catch (Exception x) when (x is NotSupportedException || x is TimeoutException || x is IOException || x is UnauthorizedAccessException)
{
b?.Dispose();
}
}
}
board = null!;
return false;
}
/// <summary>
/// Searches all available com ports for an Arduino device.
/// </summary>
/// <param name="board">A board, already open and initialized. Null if none was found.</param>
/// <returns>True if a board was found, false otherwise</returns>
/// <remarks>
/// Scanning serial ports may affect unrelated devices. If there are problems, use the
/// <see cref="TryFindBoard(System.Collections.Generic.IEnumerable{string},System.Collections.Generic.IEnumerable{int},out Iot.Device.Arduino.ArduinoBoard?)"/> overload excluding ports that shall not be tested.
/// </remarks>
public static bool TryFindBoard(
#if NET5_0_OR_GREATER
[NotNullWhen(true)]
#endif
out ArduinoBoard? board)
{
return TryFindBoard(SerialPort.GetPortNames(), CommonBaudRates(), out board);
}
/// <summary>
/// Returns a list of commonly used baud rates.
/// </summary>
public static List<int> CommonBaudRates()
{
return new List<int>()
{
9600,
19200,
18400,
57600,
115200,
230400,
250000,
500000,
1000000,
2000000,
};
}
/// <summary>
/// Returns the current assignment of the given pin
/// </summary>
/// <param name="pinNumber">Pin number to query</param>
/// <returns>A value of the <see cref="PinUsage"/> enumeration</returns>
public override PinUsage DetermineCurrentPinUsage(int pinNumber)
{
SupportedMode mode = Firmata.GetPinMode(pinNumber);
switch (mode)
{
case SupportedMode.AnalogInput:
return PinUsage.AnalogIn;
case SupportedMode.DigitalInput:
return PinUsage.Gpio;
case SupportedMode.DigitalOutput:
return PinUsage.Gpio;
case SupportedMode.Pwm:
return PinUsage.Pwm;
case SupportedMode.Servo:
break;
case SupportedMode.Shift:
break;
case SupportedMode.I2c:
return PinUsage.I2c;
case SupportedMode.OneWire:
break;
case SupportedMode.Stepper:
break;
case SupportedMode.Encoder:
break;
case SupportedMode.Serial:
return PinUsage.Uart;
case SupportedMode.InputPullup:
return PinUsage.Gpio;
case SupportedMode.Spi:
return PinUsage.Spi;
case SupportedMode.Sonar:
break;
case SupportedMode.Tone:
break;
case SupportedMode.Dht:
return PinUsage.Gpio;
}
return PinUsage.Unknown;
}
/// <summary>
/// Initialize the board connection. This must be called before any other methods of this class.
/// </summary>
/// <exception cref="NotSupportedException">The Firmata firmware on the connected board is too old.</exception>
/// <exception cref="TimeoutException">There was no answer from the board</exception>
protected override void Initialize()
{
base.Initialize();
// Shortcut, so we do not need to take the lock
if (_initialized)
{
return;
}
lock (_initializationLock)
{
if (_initialized)
{
return;
}
if (_isDisposed)
{
throw new ObjectDisposedException("Board is already disposed");
}
if (_firmata != null)
{
throw new InvalidOperationException("Board already initialized");
}
if (_serialPort != null)
{
_serialPort.Open();
_dataStream = _serialPort.BaseStream;
}
else if (_dataStream == null)
{
// Should never get here
throw new InvalidOperationException("Constructor argument error: Neither port nor stream specified");
}
_firmata = new FirmataDevice();
_firmata.Open(_dataStream);
_firmata.OnError += FirmataOnError;
_firmataVersion = _firmata.QueryFirmataVersion();
if (_firmataVersion < _firmata.QuerySupportedFirmataVersion())
{
throw new NotSupportedException($"Firmata version on board is {_firmataVersion}. Expected {_firmata.QuerySupportedFirmataVersion()}. They must be equal.");
}
Logger.LogInformation($"Firmata version on board is {_firmataVersion}.");
_firmwareVersion = _firmata.QueryFirmwareVersion(out var firmwareName);
_firmwareName = firmwareName;
Logger.LogInformation($"Firmware version on board is {_firmwareVersion}");
_firmata.QueryCapabilities();
_supportedPinConfigurations = _firmata.PinConfigurations.AsReadOnly();
Logger.LogInformation("Device capabilities: ");
foreach (var pin in _supportedPinConfigurations)
{
Logger.LogInformation(pin.ToString());
}
_firmata.EnableDigitalReporting();
_initialized = true;
}
}
/// <summary>
/// Firmware version on the device
/// </summary>
public Version FirmwareVersion
{
get
{
Initialize();
return _firmwareVersion;
}
}
/// <summary>
/// Name of the firmware.
/// </summary>
public string FirmwareName
{
get
{
Initialize();
return _firmwareName;
}
}
/// <summary>
/// Firmata version found on the board.
/// </summary>
public Version FirmataVersion
{
get
{
Initialize();
return _firmataVersion;
}
}
internal FirmataDevice Firmata
{
get
{
if (_isDisposed)
{
throw new ObjectDisposedException(nameof(ArduinoBoard));
}
// This exception should not normally happen
return _firmata ?? throw new InvalidOperationException("Device not initialized");
}
}
/// <summary>
/// Returns the list of capabilities per pin
/// </summary>
public IReadOnlyList<SupportedPinConfiguration> SupportedPinConfigurations
{
get
{
Initialize();
return _supportedPinConfigurations;
}
}
private void FirmataOnError(string message, Exception? exception)
{
if (exception != null)
{
Logger.LogError(exception, message);
}
else
{
Logger.LogInformation(message);
}
}
/// <summary>
/// Creates a GPIO Controller instance for the board. This allows working with digital input/output pins.
/// </summary>
/// <returns>An instance of GpioController, using an Arduino-Enabled driver</returns>
public override GpioController CreateGpioController()
{
Initialize();
return new GpioController(PinNumberingScheme.Logical, new ArduinoGpioControllerDriver(this, _supportedPinConfigurations));
}
/// <inheritdoc />
protected override I2cBusManager CreateI2cBusCore(int busNumber, int[]? pins)
{
Initialize();
if (!SupportedPinConfigurations.Any(x => x.PinModes.Contains(SupportedMode.I2c)))
{
throw new NotSupportedException("No Pins with I2c support found. Is the I2c module loaded?");
}
return new I2cBusManager(this, busNumber, pins, new ArduinoI2cBus(this, busNumber));
}
/// <inheritdoc />
public override int GetDefaultI2cBusNumber()
{
return 0;
}
/// <summary>
/// Connect to a device connected to the primary SPI bus on the Arduino
/// Firmata's default implementation has no SPI support, so this first checks whether it's available at all.
/// </summary>
/// <param name="settings">Spi Connection settings</param>
/// <param name="pins">The pins to use.</param>
/// <returns>An <see cref="SpiDevice"/> instance.</returns>
/// <exception cref="NotSupportedException">The Bus number is not 0, or the SPI component has not been enabled in the firmware.</exception>
protected override SpiDevice CreateSimpleSpiDevice(SpiConnectionSettings settings, int[] pins)
{
Initialize();
if (settings == null)
{
throw new ArgumentNullException(nameof(settings));
}
if (settings.BusId != 0)
{
throw new NotSupportedException("Only Bus Id 0 is supported");
}
if (!SupportedPinConfigurations.Any(x => x.PinModes.Contains(SupportedMode.Spi)))
{
throw new NotSupportedException("No Pins with SPI support found. Is the SPI module loaded?");
}
return new ArduinoSpiDevice(this, settings);
}
/// <summary>
/// Creates a PWM channel.
/// </summary>
/// <param name="chip">Must be 0.</param>
/// <param name="channel">Pin number to use</param>
/// <param name="frequency">This value is ignored</param>
/// <param name="dutyCyclePercentage">The duty cycle as a fraction.</param>
/// <returns></returns>
protected override PwmChannel CreateSimplePwmChannel(
int chip,
int channel,
int frequency,
double dutyCyclePercentage)
{
Initialize();
return new ArduinoPwmChannel(this, chip, channel, frequency, dutyCyclePercentage);
}
/// <inheritdoc />
public override int GetDefaultPinAssignmentForPwm(int chip, int channel)
{
if (chip == 0)
{
return channel;
}
throw new NotSupportedException($"Unknown chip numbe {chip}");
}
/// <inheritdoc />
public override int[] GetDefaultPinAssignmentForI2c(int busId)
{
if (busId != 0)
{
throw new NotSupportedException("Only bus number 0 is currently supported");
}
var pins = _supportedPinConfigurations.Where(x => x.PinModes.Contains(SupportedMode.I2c)).Select(y => y.Pin);
return pins.ToArray();
}
/// <inheritdoc />
public override int[] GetDefaultPinAssignmentForSpi(SpiConnectionSettings connectionSettings)
{
if (connectionSettings.BusId != 0)
{
throw new NotSupportedException("Only bus number 0 is currently supported");
}
var pins = _supportedPinConfigurations.Where(x => x.PinModes.Contains(SupportedMode.Spi)).Select(y => y.Pin);
return pins.ToArray();
}
/// <summary>
/// Creates an anlog controller for this board.
/// </summary>
/// <param name="chip">Must be 0</param>
/// <returns>An <see cref="AnalogController"/> instance</returns>
public virtual AnalogController CreateAnalogController(int chip)
{
Initialize();
return new ArduinoAnalogController(this, SupportedPinConfigurations, PinNumberingScheme.Logical);
}
/// <summary>
/// Configures the sampling interval for analog input pins (when an event callback is enabled)
/// </summary>
/// <param name="timeSpan">Timespan between updates. Default ~20ms</param>
public void SetAnalogPinSamplingInterval(TimeSpan timeSpan)
{
Initialize();
Firmata.SetAnalogInputSamplingInterval(timeSpan);
}
/// <summary>
/// Special function to read DHT sensor, if supported
/// </summary>
/// <param name="pinNumber">Pin Number</param>
/// <param name="dhtType">Type of DHT Sensor: 11 = DHT11, 22 = DHT22, etc.</param>
/// <param name="temperature">Temperature</param>
/// <param name="humidity">Relative humidity</param>
/// <returns>True on success, false otherwise</returns>
public bool TryReadDht(int pinNumber, int dhtType, out Temperature temperature, out RelativeHumidity humidity)
{
Initialize();
if (!_supportedPinConfigurations[pinNumber].PinModes.Contains(SupportedMode.Dht))
{
temperature = default;
humidity = default;
return false;
}
return Firmata.TryReadDht(pinNumber, dhtType, out temperature, out humidity);
}
/// <summary>
/// Standard dispose pattern
/// </summary>
protected override void Dispose(bool disposing)
{
_isDisposed = true;
// Do this first, to force any blocking read operations to end
if (_dataStream != null)
{
_dataStream.Dispose();
_dataStream = null!;
}
if (_serialPort != null)
{
_serialPort.Dispose();
_serialPort = null;
}
if (_firmata != null)
{
_firmata.Dispose();
_firmata = null;
}
_initialized = false;
}
internal void EnableSpi()
{
_spiEnabled++;
if (_spiEnabled == 1)
{
Firmata.EnableSpi();
}
}
internal void DisableSpi()
{
if (_spiEnabled <= 0)
{
throw new InvalidOperationException("Internal reference counting error: Spi ports already closed");
}
_spiEnabled--;
if (_spiEnabled == 0)
{
Firmata.DisableSpi();
}
}
}
}