-
Notifications
You must be signed in to change notification settings - Fork 585
/
FirmataDevice.cs
1620 lines (1400 loc) · 65.1 KB
/
FirmataDevice.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
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// 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;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Device.Gpio;
using System.Device.Spi;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Iot.Device.Common;
using Microsoft.Extensions.Logging;
using UnitsNet;
namespace Iot.Device.Arduino
{
internal delegate void AnalogPinValueUpdated(int pin, uint rawValue);
/// <summary>
/// Low-level communication layer for the firmata protocol. Creates the binary command stream for the different commands and returns back results.
/// </summary>
internal sealed class FirmataDevice : IDisposable
{
private const byte FIRMATA_PROTOCOL_MAJOR_VERSION = 2;
private const byte FIRMATA_PROTOCOL_MINOR_VERSION = 5; // 2.5 works, but 2.6 is recommended
private const int FIRMATA_INIT_TIMEOUT_SECONDS = 2;
internal static readonly TimeSpan DefaultReplyTimeout = TimeSpan.FromMilliseconds(3000);
private byte _firmwareVersionMajor;
private byte _firmwareVersionMinor;
private Version _actualFirmataProtocolVersion;
private Version _firmwareVersion;
private int _lastRequestId;
private string _firmwareName;
private Stream? _firmataStream;
private Thread? _inputThread;
private List<SupportedPinConfiguration> _supportedPinConfigurations;
private BlockingConcurrentBag<byte[]> _pendingResponses;
private List<PinValue> _lastPinValues;
private Dictionary<int, uint> _lastAnalogValues;
private object _lastPinValueLock;
private object _lastAnalogValueLock;
private object _synchronisationLock;
private Queue<byte> _dataQueue;
private StringBuilder _lastRawLine;
private CommandError _lastCommandError;
private int _i2cSequence;
/// <summary>
/// Event used when waiting for answers (i.e. after requesting firmware version)
/// </summary>
private AutoResetEvent _dataReceived;
private ILogger _logger;
public event PinChangeEventHandler? DigitalPortValueUpdated;
public event AnalogPinValueUpdated? AnalogPinValueUpdated;
public event Action<string, Exception?>? OnError;
public event Action<ReplyType, byte[]>? OnSysexReply;
private long _bytesTransmitted = 0;
private int _numberOfConsecutiveI2cWrites = 0;
private bool _systemVariablesSupported = false;
public FirmataDevice(List<SupportedMode> supportedModes)
{
_firmwareVersionMajor = 0;
_firmwareVersionMinor = 0;
_firmwareVersion = new Version(0, 0);
_actualFirmataProtocolVersion = new Version(0, 0);
_firmataStream = null;
InputThreadShouldExit = false;
_dataReceived = new AutoResetEvent(false);
_supportedPinConfigurations = new List<SupportedPinConfiguration>();
_synchronisationLock = new object();
_lastPinValues = new List<PinValue>();
_lastPinValueLock = new object();
_lastAnalogValues = new Dictionary<int, uint>();
_lastAnalogValueLock = new object();
_dataQueue = new Queue<byte>(1024);
_pendingResponses = new BlockingConcurrentBag<byte[]>();
_lastRequestId = 1;
_lastCommandError = CommandError.None;
_firmwareName = string.Empty;
_lastRawLine = new StringBuilder();
SupportedModes = supportedModes;
_i2cSequence = 0;
_logger = this.GetCurrentClassLogger();
}
internal List<SupportedPinConfiguration> PinConfigurations
{
get
{
return _supportedPinConfigurations;
}
}
internal List<SupportedMode> SupportedModes { get; set; }
internal long BytesTransmitted => _bytesTransmitted;
internal bool InputThreadShouldExit { get; set; }
public void Open(Stream stream)
{
lock (_synchronisationLock)
{
if (_firmataStream != null)
{
throw new InvalidOperationException("The device is already open");
}
_firmataStream = stream;
if (_firmataStream.CanRead && _firmataStream.CanWrite)
{
StartListening();
}
else
{
throw new NotSupportedException("Need a read-write stream to the hardware device");
}
}
}
private void StartListening()
{
if (_firmataStream == null)
{
throw new ObjectDisposedException(nameof(FirmataDevice));
}
if (_inputThread != null && _inputThread.IsAlive)
{
return;
}
InputThreadShouldExit = false;
_inputThread = new Thread(InputThread);
_inputThread.Name = "Firmata input thread";
_inputThread.Start();
}
private void ProcessInput()
{
if (_dataQueue.Count == 0)
{
FillQueue();
}
if (_dataQueue.Count == 0)
{
// Still no data? (End of stream or stream closed)
return;
}
int data = _dataQueue.Dequeue();
// OnError?.Invoke($"0x{data:X}", null);
byte b = (byte)(data & 0x00FF);
byte upper_nibble = (byte)(data & 0xF0);
byte lower_nibble = (byte)(data & 0x0F);
/*
* the relevant bits in the command depends on the value of the data byte. If it is less than 0xF0 (start sysex), only the upper nibble identifies the command
* while the lower nibble contains additional data
*/
FirmataCommand command = (FirmataCommand)((data < ((ushort)FirmataCommand.START_SYSEX) ? upper_nibble : b));
// determine the number of bytes remaining in the message
int bytes_remaining = 0;
bool isMessageSysex = false;
switch (command)
{
default: // command not understood
char c = (char)data;
_lastRawLine.Append(c);
if (c == '\n')
{
OnError?.Invoke(_lastRawLine.ToString().Trim(), null);
OnSysexReply?.Invoke(ReplyType.AsciiData, Encoding.Unicode.GetBytes(_lastRawLine.ToString()));
_lastRawLine.Clear();
}
return;
case FirmataCommand.END_SYSEX: // should never happen
return;
// commands that require 2 additional bytes
case FirmataCommand.DIGITAL_MESSAGE:
case FirmataCommand.ANALOG_MESSAGE:
case FirmataCommand.SET_PIN_MODE:
case FirmataCommand.PROTOCOL_VERSION:
bytes_remaining = 2;
break;
// commands that require 1 additional byte
case FirmataCommand.REPORT_ANALOG_PIN:
case FirmataCommand.REPORT_DIGITAL_PIN:
bytes_remaining = 1;
break;
// commands that do not require additional bytes
case FirmataCommand.SYSTEM_RESET:
// do nothing, as there is nothing to reset
return;
case FirmataCommand.START_SYSEX:
// this is a special case with no set number of bytes remaining
isMessageSysex = true;
_lastRawLine.Clear();
break;
}
// read the remaining message while keeping track of elapsed time to timeout in case of incomplete message
List<byte> message = new List<byte>();
int bytes_read = 0;
Stopwatch timeout_start = Stopwatch.StartNew();
while (bytes_remaining > 0 || isMessageSysex)
{
if (_dataQueue.Count == 0)
{
int timeout = 10;
while (!FillQueue() && timeout-- > 0)
{
Thread.Sleep(5);
}
if (timeout == 0)
{
// Synchronisation problem: The remainder of the expected message is missing
_lastCommandError = CommandError.Timeout;
return;
}
}
data = _dataQueue.Dequeue();
// OnError?.Invoke($"0x{data:X}", null);
// if no data was available, check for timeout
if (data == 0xFFFF)
{
// get elapsed seconds, given as a double with resolution in nanoseconds
TimeSpan elapsed = timeout_start.Elapsed;
if (elapsed > DefaultReplyTimeout)
{
_lastCommandError = CommandError.Timeout;
return;
}
continue;
}
timeout_start.Restart();
// if we're parsing sysex and we've just read the END_SYSEX command, we're done.
if (isMessageSysex && (data == (short)FirmataCommand.END_SYSEX))
{
break;
}
message.Add((byte)(data & 0xFF));
++bytes_read;
--bytes_remaining;
}
// process the message
switch (command)
{
// ignore these message types (they should not be in a reply)
default:
case FirmataCommand.REPORT_ANALOG_PIN:
case FirmataCommand.REPORT_DIGITAL_PIN:
case FirmataCommand.SET_PIN_MODE:
case FirmataCommand.END_SYSEX:
case FirmataCommand.SYSTEM_RESET:
return;
case FirmataCommand.PROTOCOL_VERSION:
if (_actualFirmataProtocolVersion.Major != 0)
{
// Firmata sends this message automatically after a device reset (if you press the reset button on the arduino)
// If we know the version already, this is unexpected.
_lastCommandError = CommandError.DeviceReset;
OnError?.Invoke("The device was unexpectedly reset. Please restart the communication.", null);
}
_actualFirmataProtocolVersion = new Version(message[0], message[1]);
_logger.LogInformation($"Received protocol version: {_actualFirmataProtocolVersion}.");
_dataReceived.Set();
return;
case FirmataCommand.ANALOG_MESSAGE:
// report analog commands store the pin number in the lower nibble of the command byte, the value is split over two 7-bit bytes
{
int channel = lower_nibble;
uint value = (uint)(message[0] | (message[1] << 7));
// This must work
int pin = _supportedPinConfigurations.First(x => x.AnalogPinNumber == channel).Pin;
lock (_lastAnalogValueLock)
{
_lastAnalogValues[pin] = value;
}
AnalogPinValueUpdated?.Invoke(channel, value);
}
break;
case FirmataCommand.DIGITAL_MESSAGE:
// digital messages store the port number in the lower nibble of the command byte, the port value is split over two 7-bit bytes
// Each port corresponds to 8 pins
{
int offset = lower_nibble * 8;
ushort pinValues = (ushort)(message[0] | (message[1] << 7));
if (offset + 7 >= _lastPinValues.Count)
{
_logger.LogError($"Firmware reported an update for port {lower_nibble}, but there are only {_supportedPinConfigurations.Count} pins");
break;
}
lock (_lastPinValueLock)
{
for (int i = 0; i < 8; i++)
{
PinValue oldValue = _lastPinValues[i + offset];
int mask = 1 << i;
PinValue newValue = (pinValues & mask) == 0 ? PinValue.Low : PinValue.High;
if (newValue != oldValue)
{
PinEventTypes eventTypes = newValue == PinValue.High ? PinEventTypes.Rising : PinEventTypes.Falling;
_lastPinValues[i + offset] = newValue;
// TODO: The callback should not be within the lock
DigitalPortValueUpdated?.Invoke(this, new PinValueChangedEventArgs(eventTypes, i + offset));
}
}
}
}
break;
case FirmataCommand.START_SYSEX:
// a sysex message must include at least one extended-command byte
if (bytes_read < 1)
{
_lastCommandError = CommandError.InvalidArguments;
return;
}
// retrieve the raw data array & extract the extended-command byte
byte[] raw_data = message.ToArray();
FirmataSysexCommand sysCommand = (FirmataSysexCommand)(raw_data[0]);
int index = 0;
++index;
--bytes_read;
switch (sysCommand)
{
case FirmataSysexCommand.REPORT_FIRMWARE:
// See https://github.com/firmata/protocol/blob/master/protocol.md
// Byte 0 is the command (0x79) and can be skipped here, as we've already interpreted it
{
_firmwareVersionMajor = raw_data[1];
_firmwareVersionMinor = raw_data[2];
_firmwareVersion = new Version(_firmwareVersionMajor, _firmwareVersionMinor);
int stringLength = (raw_data.Length - 3) / 2;
Span<byte> bytesReceived = stackalloc byte[stringLength];
ReassembleByteString(raw_data, 3, stringLength * 2, bytesReceived);
_firmwareName = Encoding.ASCII.GetString(bytesReceived);
_logger.LogDebug($"Received Firmware name {_firmwareName}");
_dataReceived.Set();
}
return;
case FirmataSysexCommand.STRING_DATA:
{
// condense back into 1-byte data
int stringLength = (raw_data.Length - 1) / 2;
Span<byte> bytesReceived = stackalloc byte[stringLength];
ReassembleByteString(raw_data, 1, stringLength * 2, bytesReceived);
string message1 = Encoding.UTF8.GetString(bytesReceived);
int idxNull = message1.IndexOf('\0');
if (message1.Contains("%") && idxNull > 0) // C style printf formatters
{
message1 = message1.Substring(0, idxNull);
string message2 = PrintfFromByteStream(message1, bytesReceived, idxNull + 1);
OnError?.Invoke(message2, null);
}
else
{
OnError?.Invoke(message1, null);
}
}
break;
case FirmataSysexCommand.CAPABILITY_RESPONSE:
{
_supportedPinConfigurations.Clear();
int idx = 1;
SupportedPinConfiguration currentPin = new SupportedPinConfiguration(0);
int pin = 0;
while (idx < raw_data.Length)
{
int mode = raw_data[idx++];
if (mode == 0x7F)
{
_supportedPinConfigurations.Add(currentPin);
currentPin = new SupportedPinConfiguration(++pin);
continue;
}
int resolution = raw_data[idx++];
SupportedMode? sm = SupportedModes.FirstOrDefault(x => x.Value == mode);
if (sm == SupportedMode.AnalogInput)
{
currentPin.PinModes.Add(SupportedMode.AnalogInput);
currentPin.AnalogInputResolutionBits = resolution;
}
else if (sm == SupportedMode.Pwm)
{
currentPin.PinModes.Add(SupportedMode.Pwm);
currentPin.PwmResolutionBits = resolution;
}
else if (sm == null)
{
sm = new SupportedMode((byte)mode, $"Unknown mode {mode}");
currentPin.PinModes.Add(sm);
}
else
{
currentPin.PinModes.Add(sm);
}
}
// Add 8 entries, so that later we do not need to check whether a port (bank) is complete
_lastPinValues = new PinValue[_supportedPinConfigurations.Count + 8].ToList();
_dataReceived.Set();
// Do not add the last instance, should also be terminated by 0xF7
}
break;
case FirmataSysexCommand.ANALOG_MAPPING_RESPONSE:
{
// This needs to have been set up previously
if (_supportedPinConfigurations.Count == 0)
{
return;
}
int idx = 1;
int pin = 0;
while (idx < raw_data.Length)
{
if (raw_data[idx] != 127)
{
_supportedPinConfigurations[pin].AnalogPinNumber = raw_data[idx];
}
idx++;
pin++;
}
_dataReceived.Set();
}
break;
case FirmataSysexCommand.EXTENDED_ANALOG:
// report analog commands store the pin number in the lower nibble of the command byte, the value is split over two 7-bit bytes
{
int channel = raw_data[1];
uint value = (uint)(raw_data[2] | (raw_data[3] << 7));
// This must work
int pin = _supportedPinConfigurations.First(x => x.AnalogPinNumber == channel).Pin;
lock (_lastAnalogValueLock)
{
_lastAnalogValues[pin] = value;
}
AnalogPinValueUpdated?.Invoke(channel, value);
}
break;
case FirmataSysexCommand.I2C_REPLY:
_lastCommandError = CommandError.None;
_pendingResponses.Add(raw_data);
break;
case FirmataSysexCommand.SPI_DATA:
_lastCommandError = CommandError.None;
_pendingResponses.Add(raw_data);
break;
default:
// we pass the data forward as-is for any other type of sysex command
_lastCommandError = CommandError.None;
_pendingResponses.Add(raw_data);
OnSysexReply?.Invoke(ReplyType.SysexCommand, raw_data);
break;
}
break;
}
}
/// <summary>
/// Send a command that does not generate a reply.
/// This method must only be used for commands that do not generate a reply. It must not be used if only the caller is not
/// interested in the answer.
/// </summary>
/// <param name="sequence">The command sequence to send</param>
public void SendCommand(FirmataCommandSequence sequence)
{
if (!sequence.Validate())
{
throw new ArgumentException("The command sequence is invalid", nameof(sequence));
}
lock (_synchronisationLock)
{
if (_firmataStream == null)
{
throw new ObjectDisposedException(nameof(FirmataDevice));
}
_firmataStream.Write(sequence.Sequence.ToArray());
_bytesTransmitted += sequence.Sequence.Count;
_firmataStream.Flush();
}
}
/// <summary>
/// Send a command and wait for a reply
/// </summary>
/// <param name="sequence">The command sequence, typically starting with <see cref="FirmataCommand.START_SYSEX"/> and ending with <see cref="FirmataCommand.END_SYSEX"/></param>
/// <param name="timeout">A non-default timeout</param>
/// <param name="isMatchingAck">A callback function that should return true if the given reply is the one this command should wait for. The default is true, because asynchronous replies
/// are rather the exception than the rule</param>
/// <param name="error">An error code in case of failure</param>
/// <returns>The raw sequence of sysex reply bytes. The reply does not include the START_SYSEX byte, but it does include the terminating END_SYSEX byte. The first byte is the
/// <see cref="FirmataSysexCommand"/> command number of the corresponding request</returns>
public byte[] SendCommandAndWait(FirmataCommandSequence sequence, TimeSpan timeout, Func<FirmataCommandSequence, byte[], bool> isMatchingAck, out CommandError error)
{
if (!sequence.Validate())
{
throw new ArgumentException("The command sequence is invalid", nameof(sequence));
}
if (_firmataStream == null)
{
throw new ObjectDisposedException(nameof(FirmataDevice));
}
_firmataStream.Write(sequence.Sequence.ToArray(), 0, sequence.Sequence.Count);
_bytesTransmitted += sequence.Sequence.Count;
_firmataStream.Flush();
byte[]? response;
if (!_pendingResponses.TryRemoveElement(x => isMatchingAck(sequence, x!), timeout, out response))
{
throw new TimeoutException("Timeout waiting for command answer");
}
error = _lastCommandError;
return response ?? throw new InvalidOperationException("Got a null reply"); // should not happen in our case
}
/// <summary>
/// Send a set of command and wait for a reply
/// </summary>
/// <param name="sequences">The command sequences to send, typically starting with <see cref="FirmataCommand.START_SYSEX"/> and ending with <see cref="FirmataCommand.END_SYSEX"/></param>
/// <param name="timeout">A non-default timeout</param>
/// <param name="isMatchingAck">A callback function that should return true if the given reply is the one this command should wait for. The default is true, because asynchronous replies
/// are rather the exception than the rule</param>
/// <param name="errorFunc">A callback that determines a possible error in the reply message</param>
/// <param name="error">An error code in case of failure</param>
/// <returns>The raw sequence of sysex reply bytes. The reply does not include the START_SYSEX byte, but it does include the terminating END_SYSEX byte. The first byte is the
/// <see cref="FirmataSysexCommand"/> command number of the corresponding request</returns>
public bool SendCommandsAndWait(IList<FirmataCommandSequence> sequences, TimeSpan timeout, Func<FirmataCommandSequence, byte[], bool> isMatchingAck,
Func<FirmataCommandSequence, byte[], CommandError> errorFunc, out CommandError error)
{
if (sequences.Any(s => s.Validate() == false))
{
throw new ArgumentException("At least one command sequence is invalid", nameof(sequences));
}
if (sequences.Count > 127)
{
// Because we only have 7 bits for the sequence counter.
throw new ArgumentException("At most 127 sequences can be chained together", nameof(sequences));
}
if (isMatchingAck == null)
{
throw new ArgumentNullException(nameof(isMatchingAck));
}
error = CommandError.None;
if (_firmataStream == null)
{
throw new ObjectDisposedException(nameof(FirmataDevice));
}
Dictionary<FirmataCommandSequence, bool> sequencesWithAck = new();
foreach (FirmataCommandSequence s in sequences)
{
sequencesWithAck.Add(s, false);
_firmataStream.Write(s.InternalSequence, 0, s.Length);
}
_firmataStream.Flush();
byte[]? response;
do
{
foreach (KeyValuePair<FirmataCommandSequence, bool> s2 in sequencesWithAck)
{
if (s2.Value == false && _pendingResponses.TryRemoveElement(x => isMatchingAck(s2.Key, x!), timeout, out response))
{
CommandError e = CommandError.None;
if (response == null)
{
error = CommandError.Aborted;
}
else if (_lastCommandError != CommandError.None)
{
error = _lastCommandError;
}
else if ((e = errorFunc(s2.Key, response)) != CommandError.None)
{
error = e;
}
sequencesWithAck[s2.Key] = true;
break;
}
}
}
while (sequencesWithAck.Any(x => x.Value == false));
return sequencesWithAck.All(x => x.Value);
}
/// <summary>
/// Replaces the first occurrence of search in input with replace.
/// </summary>
private static string ReplaceFirst(String input, string search, string replace)
{
int idx = input.IndexOf(search, StringComparison.InvariantCulture);
string output = input.Remove(idx, search.Length);
output = output.Insert(idx, replace);
return output;
}
/// <summary>
/// Simulates a printf C statement.
/// Note that the word size on the arduino is 16 bits, so any argument not specifying an l prefix is considered to
/// be 16 bits only.
/// </summary>
/// <param name="fmt">Format string (with %d, %x, etc)</param>
/// <param name="bytesReceived">Total bytes received</param>
/// <param name="startOfArguments">Start of arguments (first byte of formatting parameters)</param>
/// <returns>A formatted string</returns>
private string PrintfFromByteStream(string fmt, in Span<byte> bytesReceived, int startOfArguments)
{
string output = fmt;
while (output.Contains("%"))
{
int idxPercent = output.IndexOf('%');
string type = output[idxPercent + 1].ToString();
if (type == "l")
{
type += output[idxPercent + 2];
}
switch (type)
{
case "lx":
{
Int32 arg = BitConverter.ToInt32(bytesReceived.ToArray(), startOfArguments);
output = ReplaceFirst(output, "%" + type, arg.ToString("x"));
startOfArguments += 4;
break;
}
case "x":
{
Int16 arg = BitConverter.ToInt16(bytesReceived.ToArray(), startOfArguments);
output = ReplaceFirst(output, "%" + type, arg.ToString("x"));
startOfArguments += 2;
break;
}
case "d":
{
Int16 arg = BitConverter.ToInt16(bytesReceived.ToArray(), startOfArguments);
output = ReplaceFirst(output, "%" + type, arg.ToString());
startOfArguments += 2;
break;
}
case "ld":
{
Int32 arg = BitConverter.ToInt32(bytesReceived.ToArray(), startOfArguments);
output = ReplaceFirst(output, "%" + type, arg.ToString());
startOfArguments += 4;
break;
}
}
}
return output;
}
private bool FillQueue()
{
if (_firmataStream == null)
{
throw new ObjectDisposedException(nameof(FirmataDevice));
}
Span<byte> rawData = stackalloc byte[512];
int bytesRead = _firmataStream.Read(rawData);
for (int i = 0; i < bytesRead; i++)
{
_dataQueue.Enqueue(rawData[i]);
}
return _dataQueue.Count > 0;
}
private void InputThread()
{
while (!InputThreadShouldExit)
{
try
{
ProcessInput();
}
catch (Exception ex)
{
// If the exception happens because the stream was closed, don't print an error
if (!InputThreadShouldExit)
{
_logger.LogError(ex, $"Error in parser: {ex.Message}");
OnError?.Invoke($"Firmata protocol error: Parser exception {ex.Message}", ex);
}
}
}
}
public Version QueryFirmataVersion()
{
if (_firmataStream == null)
{
throw new ObjectDisposedException(nameof(FirmataDevice));
}
// Try a few times (because we have to make sure the receiver's input queue is properly synchronized and the device
// has properly booted)
for (int i = 0; i < 20; i++)
{
lock (_synchronisationLock)
{
_dataReceived.Reset();
_firmataStream.WriteByte((byte)FirmataCommand.PROTOCOL_VERSION);
_firmataStream.Flush();
bool result = _dataReceived.WaitOne(TimeSpan.FromSeconds(FIRMATA_INIT_TIMEOUT_SECONDS));
if (result == false)
{
// Attempt to send a SYSTEM_RESET command
_firmataStream.WriteByte(0xFF);
Thread.Sleep(20);
continue;
}
if (_actualFirmataProtocolVersion.Major == 0)
{
// The device may be resetting itself as part of opening the serial port (this is the typical
// behavior of the Arduino Uno, but not of most newer boards)
Thread.Sleep(100);
continue;
}
return _actualFirmataProtocolVersion;
}
}
throw new TimeoutException("Timeout waiting for firmata version");
}
internal Version QuerySupportedFirmataVersion()
{
return new Version(FIRMATA_PROTOCOL_MAJOR_VERSION, FIRMATA_PROTOCOL_MINOR_VERSION);
}
internal Version QueryFirmwareVersion(out string firmwareName)
{
if (_firmataStream == null)
{
throw new ObjectDisposedException(nameof(FirmataDevice));
}
// Try 3 times (because we have to make sure the receiver's input queue is properly synchronized)
for (int i = 0; i < 3; i++)
{
lock (_synchronisationLock)
{
_dataReceived.Reset();
_firmataStream.WriteByte((byte)FirmataCommand.START_SYSEX);
_firmataStream.WriteByte((byte)FirmataSysexCommand.REPORT_FIRMWARE);
_firmataStream.WriteByte((byte)FirmataCommand.END_SYSEX);
bool result = _dataReceived.WaitOne(TimeSpan.FromSeconds(FIRMATA_INIT_TIMEOUT_SECONDS));
if (result == false || _firmwareVersionMajor == 0)
{
// Wait a bit until we try again.
Thread.Sleep(100);
continue;
}
firmwareName = _firmwareName;
return new Version(_firmwareVersionMajor, _firmwareVersionMinor);
}
}
throw new TimeoutException("Timeout waiting for firmata firmware version");
}
internal void QueryCapabilities()
{
if (_firmataStream == null)
{
throw new ObjectDisposedException(nameof(FirmataDevice));
}
lock (_synchronisationLock)
{
_dataReceived.Reset();
_firmataStream.WriteByte((byte)FirmataCommand.START_SYSEX);
_firmataStream.WriteByte((byte)FirmataSysexCommand.CAPABILITY_QUERY);
_firmataStream.WriteByte((byte)FirmataCommand.END_SYSEX);
bool result = _dataReceived.WaitOne(DefaultReplyTimeout);
if (result == false)
{
throw new TimeoutException("Timeout waiting for device capabilities");
}
_dataReceived.Reset();
_firmataStream.WriteByte((byte)FirmataCommand.START_SYSEX);
_firmataStream.WriteByte((byte)FirmataSysexCommand.ANALOG_MAPPING_QUERY);
_firmataStream.WriteByte((byte)FirmataCommand.END_SYSEX);
result = _dataReceived.WaitOne(DefaultReplyTimeout);
if (result == false)
{
throw new TimeoutException("Timeout waiting for PWM port mappings");
}
}
}
private void StopThread()
{
InputThreadShouldExit = true;
if (_inputThread != null)
{
_inputThread.Join();
_inputThread = null;
}
}
private T PerformRetries<T>(int numberOfRetries, Func<T> operation)
{
Exception? lastException = null;
while (numberOfRetries-- > 0)
{
try
{
T result = operation();
return result;
}
catch (TimeoutException x)
{
lastException = x;
OnError?.Invoke("Timeout waiting for answer. Retries possible.", x);
Thread.Sleep(20);
}
}
throw new TimeoutException("Timeout waiting for answer. Aborting. ", lastException);
}
internal void SetPinMode(int pin, SupportedMode mode)
{
byte firmataMode = mode.Value;
FirmataCommandSequence s = new FirmataCommandSequence(FirmataCommand.SET_PIN_MODE);
s.WriteByte((byte)pin);
s.WriteByte((byte)firmataMode);
for (int i = 0; i < 3; i++)
{
SendCommand(s);
if (GetPinMode(pin) == firmataMode)
{
return;
}
}
throw new TimeoutException($"Unable to set Pin mode to {firmataMode}.");
}
internal byte GetPinMode(int pinNumber)
{
FirmataCommandSequence getPinModeSequence = new FirmataCommandSequence(FirmataCommand.START_SYSEX);
getPinModeSequence.WriteByte((byte)FirmataSysexCommand.PIN_STATE_QUERY);
getPinModeSequence.WriteByte((byte)pinNumber);
getPinModeSequence.WriteByte((byte)FirmataCommand.END_SYSEX);
return PerformRetries(3, () =>
{
byte[] response = SendCommandAndWait(getPinModeSequence, DefaultReplyTimeout, (sequence, bytes) =>
{
return bytes.Length >= 4 && bytes[1] == pinNumber;
}, out _);
// The mode is byte 4
if (response.Length < 4)
{
throw new InvalidOperationException("Not enough data in reply");
}
if (response[1] != pinNumber)
{
throw new InvalidOperationException(
"The reply didn't match the query (another port was indicated)");
}
return (response[2]);
});
}
/// <summary>
/// Enables digital pin reporting for all ports (one port has 8 pins)
/// </summary>
internal void EnableDigitalReporting()
{
if (_firmataStream == null)
{
throw new ObjectDisposedException(nameof(FirmataDevice));
}
int numPorts = (int)Math.Ceiling(PinConfigurations.Count / 8.0);
lock (_synchronisationLock)
{
for (byte i = 0; i < numPorts; i++)
{
_firmataStream.WriteByte((byte)(0xD0 + i));
_firmataStream.WriteByte(1);
_firmataStream.Flush();
}
}
}
public PinValue ReadDigitalPin(int pinNumber)
{
lock (_lastPinValueLock)
{
return _lastPinValues[pinNumber];
}
}
internal void WriteDigitalPin(int pin, PinValue value)
{
if (_firmataStream == null)
{
throw new ObjectDisposedException(nameof(FirmataDevice));
}
FirmataCommandSequence writeDigitalPin = new FirmataCommandSequence(FirmataCommand.SET_DIGITAL_VALUE);