-
Notifications
You must be signed in to change notification settings - Fork 15
/
FirmataDevice.cpp
837 lines (701 loc) · 31.2 KB
/
FirmataDevice.cpp
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
//
// FirmataDevice.cpp
// Firmata
//
// Created by Christopher Stawarz on 6/10/16.
// Copyright © 2016 The MWorks Project. All rights reserved.
//
#include "FirmataDevice.hpp"
#include "FirmataMessageTypes.h"
#include "FirmataServoChannel.hpp"
BEGIN_NAMESPACE_MW
const std::string FirmataDevice::SERIAL_PORT("serial_port");
const std::string FirmataDevice::BLUETOOTH_LOCAL_NAME("bluetooth_local_name");
const std::string FirmataDevice::DATA_INTERVAL("data_interval");
const std::string FirmataDevice::CONNECTED("connected");
const std::string FirmataDevice::RECONNECT_INTERVAL("reconnect_interval");
void FirmataDevice::describeComponent(ComponentInfo &info) {
IODevice::describeComponent(info);
info.setSignature("iodevice/firmata");
info.addParameter(SERIAL_PORT, false);
info.addParameter(BLUETOOTH_LOCAL_NAME, false);
info.addParameter(DATA_INTERVAL, false);
info.addParameter(CONNECTED, false);
info.addParameter(RECONNECT_INTERVAL, "0");
}
FirmataDevice::FirmataDevice(const ParameterValueMap ¶meters) :
IODevice(parameters),
connection(FirmataConnection::create(*this, parameters[SERIAL_PORT], parameters[BLUETOOTH_LOCAL_NAME])),
samplingIntervalUS(0),
connectedVar(optionalVariable(parameters[CONNECTED])),
reconnectIntervalUS(parameters[RECONNECT_INTERVAL]),
deviceProtocolVersionReceived(false),
deviceProtocolVersionMajor(0),
deviceProtocolVersionMinor(0),
capabilityInfoReceived(false),
analogMappingInfoReceived(false),
connected(false),
running(false)
{
if (!(parameters[DATA_INTERVAL].empty())) {
samplingIntervalUS = MWTime(parameters[DATA_INTERVAL]);
if (samplingIntervalUS < 1000) {
throw SimpleException(M_IODEVICE_MESSAGE_DOMAIN, "Data interval must be >=1ms");
} else if (samplingIntervalUS % 1000 != 0) {
throw SimpleException(M_IODEVICE_MESSAGE_DOMAIN, "Data interval must be a whole number of milliseconds");
}
}
if (reconnectIntervalUS < 0) {
throw SimpleException(M_IODEVICE_MESSAGE_DOMAIN, "Reconnection interval must be >=0");
}
}
FirmataDevice::~FirmataDevice() {
connection->finalize();
}
void FirmataDevice::addChild(std::map<std::string, std::string> parameters,
ComponentRegistryPtr reg,
boost::shared_ptr<Component> child)
{
auto channel = boost::dynamic_pointer_cast<FirmataChannel>(child);
if (!channel) {
throw SimpleException(M_IODEVICE_MESSAGE_DOMAIN, "Invalid channel type for Firmata device");
}
requestedChannels.push_back(channel);
}
bool FirmataDevice::initialize() {
unique_lock lock(mutex);
mprintf(M_IODEVICE_MESSAGE_DOMAIN, "Configuring Firmata device \"%s\"...", getTag().c_str());
if (!connection->initialize()) {
return false;
}
setConnected(true);
if (!checkProtocolVersion(lock) ||
!getDeviceInfo(lock) ||
!processChannelRequests() ||
!configurePins())
{
connection->finalize();
setConnected(false);
return false;
}
mprintf(M_IODEVICE_MESSAGE_DOMAIN, "Firmata device \"%s\" is ready", getTag().c_str());
return true;
}
bool FirmataDevice::startDeviceIO() {
unique_lock lock(mutex);
if (!running) {
if (!startIO()) {
return false;
}
running = true;
}
return true;
}
bool FirmataDevice::stopDeviceIO() {
unique_lock lock(mutex);
if (running) {
if (!stopIO()) {
return false;
}
running = false;
}
return true;
}
bool FirmataDevice::checkProtocolVersion(unique_lock &lock) {
if (!sendData({ REPORT_VERSION })) {
return false;
}
// Wait for receipt of protocol version
if (!condition.wait_for(lock, std::chrono::seconds(2), [this]() { return deviceProtocolVersionReceived; })) {
merror(M_IODEVICE_MESSAGE_DOMAIN,
"Firmata device \"%s\" did not respond to request for protocol version",
getTag().c_str());
return false;
}
// Confirm that device uses a compatible protocol version
if (deviceProtocolVersionMajor != protocolVersionMajor ||
deviceProtocolVersionMinor < protocolVersionMinor)
{
merror(M_IODEVICE_MESSAGE_DOMAIN,
"Firmata device \"%s\" uses protocol version %hhu.%hhu, which is not compatible with the version "
"used by MWorks (%hhu.%hhu)",
getTag().c_str(),
deviceProtocolVersionMajor,
deviceProtocolVersionMinor,
protocolVersionMajor,
protocolVersionMinor);
return false;
}
return true;
}
bool FirmataDevice::getDeviceInfo(unique_lock &lock) {
if (!sendData({ START_SYSEX, CAPABILITY_QUERY, END_SYSEX,
START_SYSEX, ANALOG_MAPPING_QUERY, END_SYSEX }))
{
return false;
}
// Wait for receipt of capability and analog mapping info
if (!condition.wait_for(lock, std::chrono::seconds(2), [this]() {
return (capabilityInfoReceived && analogMappingInfoReceived);
}))
{
merror(M_IODEVICE_MESSAGE_DOMAIN,
"Firmata device \"%s\" did not respond to capability requests",
getTag().c_str());
return false;
}
return true;
}
bool FirmataDevice::processChannelRequests() {
for (auto &channel : requestedChannels) {
std::vector<int> pinNumbers;
if (!(channel->resolvePinNumbers(pinForAnalogChannel, pinNumbers))) {
merror(M_IODEVICE_MESSAGE_DOMAIN, "Cannot resolve pin numbers on Firmata device \"%s\"", getTag().c_str());
return false;
}
for (const auto pinNumber : pinNumbers) {
if (pinNumber < minPinNumber || pinNumber > maxPinNumber) {
merror(M_IODEVICE_MESSAGE_DOMAIN,
"Pin numbers must be between %d and %d; %d is not valid",
minPinNumber,
maxPinNumber,
pinNumber);
return false;
}
const auto &pinModes = modesForPin[pinNumber];
if (pinModes.find(channel->getPinMode()) == pinModes.end()) {
merror(M_IODEVICE_MESSAGE_DOMAIN,
"Pin %d does not support the requested mode on Firmata device \"%s\"",
pinNumber,
getTag().c_str());
return false;
}
if (channel->isAnalog() && channel->isInput()) {
const auto analogChannelNumber = getAnalogChannelNumber(pinNumber);
if (analogChannelNumber < minAnalogChannelNumber || analogChannelNumber > maxAnalogChannelNumber) {
merror(M_IODEVICE_MESSAGE_DOMAIN,
"Pin %d is not an analog input on Firmata device \"%s\"",
pinNumber,
getTag().c_str());
return false;
}
}
auto &slot = getChannelForPin(pinNumber);
if (slot) {
merror(M_IODEVICE_MESSAGE_DOMAIN,
"Multiple channels map to pin %d on Firmata device \"%s\"",
pinNumber,
getTag().c_str());
return false;
}
slot = channel;
}
if (channel->isOutput()) {
boost::weak_ptr<FirmataDevice> weakThis(component_shared_from_this<FirmataDevice>());
// It's OK to capture channel by reference, because it will remain alive (in
// requestedChannels) for as long as the device is alive
auto callback = [weakThis, &channel, pinNumbers](const Datum &data, MWTime time) {
if (auto sharedThis = weakThis.lock()) {
unique_lock lock(sharedThis->mutex);
if (sharedThis->running) {
sharedThis->updateOutputChannel(channel, pinNumbers);
}
}
};
channel->addNewValueNotification(boost::make_shared<VariableCallbackNotification>(callback));
}
}
return true;
}
bool FirmataDevice::configurePins() {
if (!sendData({ SYSTEM_RESET })) {
return false;
}
if (samplingIntervalUS) {
const auto samplingIntervalMS = samplingIntervalUS / 1000;
if (!sendData({ START_SYSEX,
SAMPLING_INTERVAL,
std::uint8_t((samplingIntervalMS >> 0) & 0x7F), // LSB
std::uint8_t((samplingIntervalMS >> 7) & 0x7F), // MSB
END_SYSEX }))
{
merror(M_IODEVICE_MESSAGE_DOMAIN,
"Cannot set sampling interval on Firmata device \"%s\"",
getTag().c_str());
return false;
}
}
for (std::size_t portNum = 0; portNum < ports.size(); portNum++) {
const auto &port = ports.at(portNum);
for (std::size_t bitNum = 0; bitNum < port.size(); bitNum++) {
const auto &channel = port.at(bitNum);
if (channel) {
const auto pinNumber = getPinNumber(portNum, bitNum);
if (auto servoChannel = boost::dynamic_pointer_cast<FirmataServoChannel>(channel)) {
const auto minPulseWidth = servoChannel->getMinPulseWidth();
const auto maxPulseWidth = servoChannel->getMaxPulseWidth();
if (!sendData({ START_SYSEX,
SERVO_CONFIG,
std::uint8_t(pinNumber),
std::uint8_t((minPulseWidth >> 0) & 0x7F), // minPulseWidth LSB
std::uint8_t((minPulseWidth >> 7) & 0x7F), // minPulseWidth MSB
std::uint8_t((maxPulseWidth >> 0) & 0x7F), // maxPulseWidth LSB
std::uint8_t((maxPulseWidth >> 7) & 0x7F), // maxPulseWidth MSB
END_SYSEX }))
{
merror(M_IODEVICE_MESSAGE_DOMAIN,
"Cannot set servo configuration on pin %d of Firmata device \"%s\"",
pinNumber,
getTag().c_str());
return false;
}
}
if (!sendData({ SET_PIN_MODE, std::uint8_t(pinNumber), std::uint8_t(channel->getPinMode()) })) {
merror(M_IODEVICE_MESSAGE_DOMAIN,
"Cannot set mode of pin %d on Firmata device \"%s\"",
pinNumber,
getTag().c_str());
return false;
}
if (channel->isAnalog() && channel->isInput()) {
// StandardFirmata automatically enables reporting of pins in mode PIN_MODE_ANALOG.
// Since we don't want reporting to begin until startIO() is invoked, we must disable
// reporting of these pins.
const auto channelNumber = getAnalogChannelNumber(pinNumber);
if (!sendData({ std::uint8_t(REPORT_ANALOG | channelNumber), 0 })) {
merror(M_IODEVICE_MESSAGE_DOMAIN,
"Cannot disable reporting of analog input channel %d on Firmata device \"%s\"",
channelNumber,
getTag().c_str());
return false;
}
}
}
}
}
return true;
}
bool FirmataDevice::startIO() {
for (std::size_t portNum = 0; portNum < ports.size(); portNum++) {
const auto &port = ports.at(portNum);
bool portHasDigitalInputs = false;
bool portHasDigitalOutputs = false;
std::array<std::uint8_t, 2> portState = { 0, 0 };
for (std::size_t bitNum = 0; bitNum < port.size(); bitNum++) {
const auto &channel = port.at(bitNum);
if (channel) {
const auto pinNumber = getPinNumber(portNum, bitNum);
switch (channel->getType()) {
case FirmataChannel::Type::Analog: {
switch (channel->getDirection()) {
case FirmataChannel::Direction::Input: {
const auto channelNumber = getAnalogChannelNumber(pinNumber);
if (!sendData({ std::uint8_t(REPORT_ANALOG | channelNumber), 1 })) {
merror(M_IODEVICE_MESSAGE_DOMAIN,
"Cannot enable reporting of analog input channel %d on Firmata device \"%s\"",
channelNumber,
getTag().c_str());
return false;
}
break;
}
case FirmataChannel::Direction::Output:
if (!setAnalogOutput(pinNumber,
channel->getValueForPin(pinNumber).getFloat()))
{
return false;
}
break;
}
break;
}
case FirmataChannel::Type::Digital: {
switch (channel->getDirection()) {
case FirmataChannel::Direction::Input:
portHasDigitalInputs = true;
break;
case FirmataChannel::Direction::Output:
portHasDigitalOutputs = true;
portState.at(bitNum / 7) |= (channel->getValueForPin(pinNumber).getBool() << (bitNum % 7));
break;
}
break;
}
case FirmataChannel::Type::DigitalPulse: {
switch (channel->getDirection()) {
case FirmataChannel::Direction::Input:
if (!sendData({ START_SYSEX,
MWORKS_REPORT_DIGITAL_PULSE,
std::uint8_t(pinNumber),
1,
END_SYSEX }))
{
merror(M_IODEVICE_MESSAGE_DOMAIN,
"Cannot enable reporting of digital input pulses on pin %d of "
"Firmata device \"%s\"",
pinNumber,
getTag().c_str());
return false;
}
break;
case FirmataChannel::Direction::Output:
if (!sendDigitalPulseMessage(pinNumber, 0)) {
merror(M_IODEVICE_MESSAGE_DOMAIN,
"Cannot initialize digital output pulses on pin %d of Firmata device \"%s\"",
pinNumber,
getTag().c_str());
return false;
}
break;
}
break;
}
case FirmataChannel::Type::Servo: {
if (channel->isOutput()) {
if (!setServo(pinNumber,
channel->getValueForPin(pinNumber).getFloat()))
{
return false;
}
}
break;
}
}
}
}
if (portHasDigitalInputs &&
!sendData({ std::uint8_t(REPORT_DIGITAL | portNum), 1 }))
{
merror(M_IODEVICE_MESSAGE_DOMAIN,
"Cannot enable reporting of digital input pins on Firmata device \"%s\"",
getTag().c_str());
return false;
}
if (portHasDigitalOutputs &&
!sendData({ std::uint8_t(DIGITAL_MESSAGE | portNum), portState.at(0), portState.at(1) }))
{
merror(M_IODEVICE_MESSAGE_DOMAIN,
"Cannot set initial values of digital output pins on Firmata device \"%s\"",
getTag().c_str());
return false;
}
}
return true;
}
bool FirmataDevice::stopIO() {
for (std::size_t portNum = 0; portNum < ports.size(); portNum++) {
const auto &port = ports.at(portNum);
bool portHasDigitalInputs = false;
bool portHasDigitalOutputs = false;
for (std::size_t bitNum = 0; bitNum < port.size(); bitNum++) {
const auto &channel = port.at(bitNum);
if (channel) {
const auto pinNumber = getPinNumber(portNum, bitNum);
switch (channel->getType()) {
case FirmataChannel::Type::Analog: {
switch (channel->getDirection()) {
case FirmataChannel::Direction::Input: {
const auto channelNumber = getAnalogChannelNumber(pinNumber);
if (!sendData({ std::uint8_t(REPORT_ANALOG | channelNumber), 0 })) {
merror(M_IODEVICE_MESSAGE_DOMAIN,
"Cannot disable reporting of analog input channel %d on Firmata device \"%s\"",
channelNumber,
getTag().c_str());
return false;
}
break;
}
case FirmataChannel::Direction::Output:
if (!setAnalogOutput(pinNumber, 0.0)) {
return false;
}
break;
}
break;
}
case FirmataChannel::Type::Digital: {
switch (channel->getDirection()) {
case FirmataChannel::Direction::Input:
portHasDigitalInputs = true;
break;
case FirmataChannel::Direction::Output:
portHasDigitalOutputs = true;
break;
}
break;
}
case FirmataChannel::Type::DigitalPulse: {
switch (channel->getDirection()) {
case FirmataChannel::Direction::Input:
if (!sendData({ START_SYSEX,
MWORKS_REPORT_DIGITAL_PULSE,
std::uint8_t(pinNumber),
0,
END_SYSEX }))
{
merror(M_IODEVICE_MESSAGE_DOMAIN,
"Cannot disable reporting of digital input pulses on pin %d of "
"Firmata device \"%s\"",
pinNumber,
getTag().c_str());
return false;
}
break;
case FirmataChannel::Direction::Output:
if (!sendDigitalPulseMessage(pinNumber, 0)) {
merror(M_IODEVICE_MESSAGE_DOMAIN,
"Cannot reset digital output pulses on pin %d of Firmata device \"%s\"",
pinNumber,
getTag().c_str());
return false;
}
break;
}
break;
}
case FirmataChannel::Type::Servo: {
// We don't really know what the "ground" state is for a servo, so just
// leave it where it is
break;
}
}
}
}
if (portHasDigitalInputs &&
!sendData({ std::uint8_t(REPORT_DIGITAL | portNum), 0 }))
{
merror(M_IODEVICE_MESSAGE_DOMAIN,
"Cannot disable reporting of digital input pins on Firmata device \"%s\"",
getTag().c_str());
return false;
}
if (portHasDigitalOutputs &&
!sendData({ std::uint8_t(DIGITAL_MESSAGE | portNum), 0, 0 }))
{
merror(M_IODEVICE_MESSAGE_DOMAIN,
"Cannot reset values of digital output pins on Firmata device \"%s\"",
getTag().c_str());
return false;
}
}
return true;
}
void FirmataDevice::updateOutputChannel(const boost::shared_ptr<FirmataChannel> &channel,
const std::vector<int> &pinNumbers)
{
switch (channel->getType()) {
case FirmataChannel::Type::Analog:
for (auto pinNumber : pinNumbers) {
setAnalogOutput(pinNumber, channel->getValueForPin(pinNumber).getFloat());
}
break;
case FirmataChannel::Type::Digital: {
// Combine the updates for all pins in to a single message, so that the pins of word output channels
// are updated as close to simultaneously as possible
std::vector<std::uint8_t> data;
for (auto pinNumber : pinNumbers) {
data.push_back(SET_DIGITAL_PIN_VALUE);
data.push_back(pinNumber);
data.push_back(channel->getValueForPin(pinNumber).getBool());
}
if (!sendData(data)) {
for (auto pinNumber : pinNumbers) {
merror(M_IODEVICE_MESSAGE_DOMAIN,
"Cannot set digital output value on pin %d of Firmata device \"%s\"",
pinNumber,
getTag().c_str());
}
}
break;
}
case FirmataChannel::Type::DigitalPulse:
for (auto pinNumber : pinNumbers) {
auto duration = channel->getValueForPin(pinNumber).getInteger();
if (duration < 1000) {
merror(M_IODEVICE_MESSAGE_DOMAIN,
"Firmata digital output pulse duration must be >=1ms; %lld us is not valid",
duration);
} else if (duration % 1000 != 0) {
merror(M_IODEVICE_MESSAGE_DOMAIN,
"Firmata digital output pulse duration must be a whole number of milliseconds; "
"%g ms is not valid",
double(duration) / 1000.0);
} else if (!sendDigitalPulseMessage(pinNumber, duration / 1000 /*us to ms*/)) {
merror(M_IODEVICE_MESSAGE_DOMAIN,
"Cannot send digital output pulse on pin %d of Firmata device \"%s\"",
pinNumber,
getTag().c_str());
}
}
break;
case FirmataChannel::Type::Servo:
for (auto pinNumber : pinNumbers) {
setServo(pinNumber, channel->getValueForPin(pinNumber).getFloat());
}
break;
}
}
inline int FirmataDevice::getResolutionForPinMode(int pinNumber, int pinMode) const {
return modesForPin.at(pinNumber).at(pinMode);
}
inline double FirmataDevice::getMaximumValueForPinMode(int pinNumber, int pinMode) const {
return double((1 << getResolutionForPinMode(pinNumber, pinMode)) - 1);
}
bool FirmataDevice::setAnalogOutput(int pinNumber, double value) {
if (value < 0.0 || value > 1.0) {
merror(M_IODEVICE_MESSAGE_DOMAIN,
"Firmata analog output value must be between 0 and 1; %g is not valid",
value);
return false;
}
int intValue = std::round(value * getMaximumValueForPinMode(pinNumber, PIN_MODE_PWM));
if (!sendExtendedAnalogMessage(pinNumber, PIN_MODE_PWM, intValue)) {
merror(M_IODEVICE_MESSAGE_DOMAIN,
"Cannot set analog output value on pin %d of Firmata device \"%s\"",
pinNumber,
getTag().c_str());
return false;
}
return true;
}
bool FirmataDevice::setServo(int pinNumber, double value) {
if (value < 0.0 || value > 180.0) {
merror(M_IODEVICE_MESSAGE_DOMAIN,
"Firmata servo value must be between 0 and 180; %g is not valid",
value);
return false;
}
if (!sendExtendedAnalogMessage(pinNumber, PIN_MODE_SERVO, std::round(value))) {
merror(M_IODEVICE_MESSAGE_DOMAIN,
"Cannot set servo value on pin %d of Firmata device \"%s\"",
pinNumber,
getTag().c_str());
return false;
}
return true;
}
bool FirmataDevice::sendExtendedAnalogMessage(int pinNumber, int pinMode, int value) {
const int numBits = getResolutionForPinMode(pinNumber, pinMode);
std::vector<std::uint8_t> data = { START_SYSEX, EXTENDED_ANALOG, std::uint8_t(pinNumber) };
for (std::size_t bitNum = 0; bitNum < numBits; bitNum++) {
if (bitNum % 7 == 0) {
data.push_back(0);
}
data.back() |= (value & 1) << (bitNum % 7);
value >>= 1;
}
data.push_back(END_SYSEX);
if (!sendData(data)) {
return false;
}
return true;
}
bool FirmataDevice::sendDigitalPulseMessage(int pinNumber, MWTime durationMS) {
std::vector<std::uint8_t> data = { START_SYSEX, MWORKS_DIGITAL_PULSE, std::uint8_t(pinNumber) };
do {
data.push_back(durationMS & 0x7F);
durationMS >>= 7;
} while (durationMS);
data.push_back(END_SYSEX);
if (!sendData(data)) {
return false;
}
return true;
}
bool FirmataDevice::sendData(const std::vector<std::uint8_t> &data) {
if (connected) {
return connection->sendData(data);
}
merror(M_IODEVICE_MESSAGE_DOMAIN, "Cannot send data to Firmata device \"%s\": Not connected", getTag().c_str());
return false;
}
void FirmataDevice::receivedProtocolVersion(std::uint8_t protocolVersionMajor, std::uint8_t protocolVersionMinor) {
{
unique_lock lock(mutex);
deviceProtocolVersionMajor = protocolVersionMajor;
deviceProtocolVersionMinor = protocolVersionMinor;
deviceProtocolVersionReceived = true;
}
condition.notify_all();
}
void FirmataDevice::receivedCapabilityInfo(const PinModesMap &modesForPin) {
{
unique_lock lock(mutex);
this->modesForPin = modesForPin;
capabilityInfoReceived = true;
}
condition.notify_all();
}
void FirmataDevice::receivedAnalogMappingInfo(const AnalogChannelPinMap &pinForAnalogChannel) {
{
unique_lock lock(mutex);
this->pinForAnalogChannel = pinForAnalogChannel;
analogMappingInfoReceived = true;
}
condition.notify_all();
}
void FirmataDevice::receivedDigitalMessage(std::uint8_t portNum, const PortStateArray &portState, MWTime time) {
unique_lock lock(mutex);
if (running) {
const auto &port = ports.at(portNum);
for (std::size_t bitNum = 0; bitNum < port.size(); bitNum++) {
const auto &channel = port.at(bitNum);
if (channel && channel->isDigital() && channel->isInput()) {
const auto pinNumber = getPinNumber(portNum, bitNum);
const bool value = portState.at(bitNum / 7) & (1 << (bitNum % 7));
if (channel->getValueForPin(pinNumber).getBool() != value) {
channel->setValueForPin(pinNumber, value, time);
}
}
}
}
}
void FirmataDevice::receivedAnalogMessage(std::uint8_t channelNumber, int value, MWTime time) {
unique_lock lock(mutex);
if (running) {
const auto iter = pinForAnalogChannel.find(channelNumber);
if (iter != pinForAnalogChannel.end()) {
const auto pinNumber = iter->second;
const auto &channel = getChannelForPin(pinNumber);
if (channel && channel->isAnalog() && channel->isInput()) {
auto floatValue = double(value) / getMaximumValueForPinMode(pinNumber, PIN_MODE_ANALOG);
// The user expects analog samples at a steady rate, so set the value unconditionally
channel->setValueForPin(pinNumber, floatValue, time);
}
}
}
}
void FirmataDevice::receivedDigitalPulseMessage(std::uint8_t pinNumber, MWTime durationMS, MWTime time) {
unique_lock lock(mutex);
if (running) {
const auto &channel = getChannelForPin(pinNumber);
if (channel && channel->isDigitalPulse() && channel->isInput()) {
channel->setValueForPin(pinNumber, durationMS * 1000 /*ms to us*/, time);
}
}
}
void FirmataDevice::disconnected() {
unique_lock lock(mutex);
setConnected(false);
}
void FirmataDevice::reconnected() {
unique_lock lock(mutex);
if (!deviceProtocolVersionReceived ||
!capabilityInfoReceived ||
!analogMappingInfoReceived)
{
// We're still in initial configuration. Don't do anything here.
return;
}
setConnected(true);
// We're going to assume that we've reconnected to the same device and not request the
// protocol version and device info again. However, as the connection may have failed
// because the device lost power, we do need to reset, reconfigure, and (if running)
// restart I/O.
if (!configurePins() ||
(running && !startIO()))
{
running = false;
}
}
END_NAMESPACE_MW