Skip to content

Commit 7113603

Browse files
committed
Firmata Support
1 parent 4f08d86 commit 7113603

15 files changed

Lines changed: 1474 additions & 230 deletions

‎ArduinoCore-Linux/cores/arduino/HardwareSetup.h‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,3 +25,6 @@
2525
#if defined(USE_FTDI)
2626
# include "../ftdi/HardwareSetupFTDI.h"
2727
#endif
28+
#if defined(USE_FIRMATA)
29+
# include "../firmata/HardwareSetupFIR.h"
30+
#endif
Lines changed: 160 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,160 @@
1+
/*
2+
FirmataTransport.cpp
3+
Copyright (c) 2025 Phil Schatzmann. All right reserved.
4+
5+
This library is free software; you can redistribute it and/or
6+
modify it under the terms of the GNU Lesser General Public
7+
License as published by the Free Software Foundation; either
8+
version 2.1 of the License, or (at your option) any later version.
9+
10+
This library is distributed in the hope that it will be useful,
11+
but WITHOUT ANY WARRANTY; without even the implied warranty of
12+
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13+
Lesser General Public License for more details.
14+
15+
You should have received a copy of the GNU Lesser General Public
16+
License along with this library; if not, write to the Free Software
17+
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18+
*/
19+
#ifdef USE_FIRMATA
20+
#include "FirmataTransport.h"
21+
#include <chrono>
22+
23+
namespace arduino {
24+
25+
static constexpr uint8_t DIGITAL_MESSAGE = 0x90;
26+
static constexpr uint8_t ANALOG_MESSAGE = 0xE0;
27+
static constexpr uint8_t START_SYSEX = 0xF0;
28+
static constexpr uint8_t END_SYSEX = 0xF7;
29+
30+
FirmataTransport::~FirmataTransport() { end(); }
31+
32+
bool FirmataTransport::begin(Stream &stream) {
33+
end(); // idempotent
34+
35+
stream_ = &stream;
36+
running_ = true;
37+
thread_ = std::thread(&FirmataTransport::readerLoop, this);
38+
return true;
39+
}
40+
41+
void FirmataTransport::end() {
42+
running_ = false;
43+
if (thread_.joinable()) {
44+
thread_.join();
45+
}
46+
stream_ = nullptr;
47+
}
48+
49+
void FirmataTransport::writeBytes(const uint8_t *data, size_t len) {
50+
std::lock_guard<std::mutex> lock(write_mutex_);
51+
if (!stream_) return;
52+
for (size_t i = 0; i < len; ++i) {
53+
stream_->write(data[i]);
54+
}
55+
}
56+
57+
void FirmataTransport::addSysexHandler(uint8_t command, SysexHandler handler) {
58+
std::lock_guard<std::mutex> lock(sysex_handlers_mutex_);
59+
sysex_handlers_[command] = std::move(handler);
60+
}
61+
62+
void FirmataTransport::removeSysexHandler(uint8_t command) {
63+
std::lock_guard<std::mutex> lock(sysex_handlers_mutex_);
64+
sysex_handlers_.erase(command);
65+
}
66+
67+
void FirmataTransport::readerLoop() {
68+
enum class State { kWaitCommand, kWaitLsb, kWaitMsb, kInSysex };
69+
State state = State::kWaitCommand;
70+
uint8_t command = 0;
71+
uint8_t channel = 0;
72+
uint8_t lsb = 0;
73+
std::vector<uint8_t> sysex_buffer;
74+
75+
while (running_.load()) {
76+
if (stream_ == nullptr || stream_->available() <= 0) {
77+
std::this_thread::sleep_for(std::chrono::milliseconds(2));
78+
continue;
79+
}
80+
81+
const int value = stream_->read();
82+
if (value < 0) continue;
83+
const uint8_t byte = static_cast<uint8_t>(value);
84+
85+
if (state == State::kInSysex) {
86+
if (byte == END_SYSEX) {
87+
state = State::kWaitCommand;
88+
if (!sysex_buffer.empty()) {
89+
const uint8_t sysexCommand = sysex_buffer.front();
90+
SysexHandler handler;
91+
{
92+
std::lock_guard<std::mutex> lock(sysex_handlers_mutex_);
93+
const auto it = sysex_handlers_.find(sysexCommand);
94+
if (it != sysex_handlers_.end()) handler = it->second;
95+
}
96+
if (handler) {
97+
FirmataSysexMessage msg;
98+
msg.command = sysexCommand;
99+
msg.data.assign(sysex_buffer.begin() + 1, sysex_buffer.end());
100+
handler(msg);
101+
}
102+
}
103+
sysex_buffer.clear();
104+
} else {
105+
sysex_buffer.push_back(byte);
106+
}
107+
continue;
108+
}
109+
110+
switch (state) {
111+
case State::kWaitCommand:
112+
if (byte == START_SYSEX) {
113+
state = State::kInSysex;
114+
sysex_buffer.clear();
115+
} else if ((byte & 0xF0) == DIGITAL_MESSAGE) {
116+
command = DIGITAL_MESSAGE;
117+
channel = byte & 0x0F;
118+
state = State::kWaitLsb;
119+
} else if ((byte & 0xF0) == ANALOG_MESSAGE) {
120+
command = ANALOG_MESSAGE;
121+
channel = byte & 0x0F;
122+
state = State::kWaitLsb;
123+
}
124+
// Any other command byte (REPORT_VERSION, SYSTEM_RESET, ...) is
125+
// outside the subset this client needs and is simply discarded.
126+
break;
127+
case State::kWaitLsb:
128+
lsb = byte & 0x7F;
129+
state = State::kWaitMsb;
130+
break;
131+
case State::kWaitMsb: {
132+
const uint8_t msb = byte & 0x7F;
133+
if (command == DIGITAL_MESSAGE) {
134+
if (digital_handler_) {
135+
FirmataDigitalMessage msg;
136+
msg.port = channel;
137+
msg.value = lsb | (static_cast<uint16_t>(msb) << 7);
138+
digital_handler_(msg);
139+
}
140+
} else {
141+
if (analog_handler_) {
142+
FirmataAnalogMessage msg;
143+
msg.pin = channel;
144+
msg.value = lsb | (static_cast<int>(msb) << 7);
145+
analog_handler_(msg);
146+
}
147+
}
148+
state = State::kWaitCommand;
149+
break;
150+
}
151+
case State::kInSysex:
152+
// handled above
153+
break;
154+
}
155+
}
156+
}
157+
158+
} // namespace arduino
159+
160+
#endif // USE_FIRMATA
Lines changed: 120 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,120 @@
1+
#pragma once
2+
/*
3+
FirmataTransport.h
4+
Copyright (c) 2025 Phil Schatzmann. All right reserved.
5+
6+
This library is free software; you can redistribute it and/or
7+
modify it under the terms of the GNU Lesser General Public
8+
License as published by the Free Software Foundation; either
9+
version 2.1 of the License, or (at your option) any later version.
10+
11+
This library is distributed in the hope that it will be useful,
12+
but WITHOUT ANY WARRANTY; without even the implied warranty of
13+
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14+
Lesser General Public License for more details.
15+
16+
You should have received a copy of the GNU Lesser General Public
17+
License along with this library; if not, write to the Free Software
18+
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
19+
*/
20+
#ifdef USE_FIRMATA
21+
#include "api/Stream.h"
22+
#include <atomic>
23+
#include <cstdint>
24+
#include <functional>
25+
#include <map>
26+
#include <mutex>
27+
#include <thread>
28+
#include <vector>
29+
30+
namespace arduino {
31+
32+
/// A digital port report (device -> host), 8 pins packed into one message.
33+
struct FirmataDigitalMessage {
34+
uint8_t port;
35+
uint16_t value;
36+
};
37+
38+
/// A single analog pin report (device -> host).
39+
struct FirmataAnalogMessage {
40+
uint8_t pin;
41+
int value;
42+
};
43+
44+
/// A raw SysEx message: `command` is the byte right after START_SYSEX,
45+
/// `data` holds everything up to (excluding) END_SYSEX, undecoded.
46+
struct FirmataSysexMessage {
47+
uint8_t command;
48+
std::vector<uint8_t> data;
49+
};
50+
51+
/**
52+
* @class FirmataTransport
53+
* @brief Single reader thread + byte-stream parser shared by every
54+
* Firmata-based hardware backend (GPIO, I2C, SPI, ...) that talks to the
55+
* same device.
56+
*
57+
* A real Firmata device is reached over exactly one Stream (typically a
58+
* serial port). Digital/analog GPIO reports, I2C replies and SPI replies
59+
* are all multiplexed over that single connection, so only one thread may
60+
* ever read from the Stream. Each hardware backend registers the message
61+
* types it cares about via onDigitalMessage()/onAnalogMessage()/
62+
* addSysexHandler() and shares one FirmataTransport instance; writes are
63+
* serialized with an internal mutex so requests from different backends
64+
* don't interleave on the wire.
65+
*/
66+
class FirmataTransport {
67+
public:
68+
using DigitalHandler = std::function<void(const FirmataDigitalMessage&)>;
69+
using AnalogHandler = std::function<void(const FirmataAnalogMessage&)>;
70+
using SysexHandler = std::function<void(const FirmataSysexMessage&)>;
71+
72+
~FirmataTransport();
73+
74+
/// Start the background reader thread on the given stream.
75+
bool begin(Stream& stream);
76+
77+
/// Stop the reader thread and detach from the stream.
78+
void end();
79+
80+
operator bool() const { return running_.load(); }
81+
82+
/// Thread-safe write of a raw byte sequence (e.g. a whole SysEx message).
83+
void writeBytes(const uint8_t* data, size_t len);
84+
void writeByte(uint8_t b) { writeBytes(&b, 1); }
85+
86+
/// Register the (single) handler for digital port reports.
87+
void onDigitalMessage(DigitalHandler handler) {
88+
digital_handler_ = std::move(handler);
89+
}
90+
91+
/// Register the (single) handler for analog pin reports.
92+
void onAnalogMessage(AnalogHandler handler) {
93+
analog_handler_ = std::move(handler);
94+
}
95+
96+
/// Register a handler for SysEx messages carrying the given command byte
97+
/// (e.g. I2C_REPLY or SPI_DATA). Replaces any previously registered
98+
/// handler for the same command.
99+
void addSysexHandler(uint8_t command, SysexHandler handler);
100+
101+
/// Remove a previously registered SysEx handler.
102+
void removeSysexHandler(uint8_t command);
103+
104+
private:
105+
Stream* stream_ = nullptr;
106+
std::atomic<bool> running_{false};
107+
std::thread thread_;
108+
std::mutex write_mutex_;
109+
110+
DigitalHandler digital_handler_;
111+
AnalogHandler analog_handler_;
112+
std::mutex sysex_handlers_mutex_;
113+
std::map<uint8_t, SysexHandler> sysex_handlers_;
114+
115+
void readerLoop();
116+
};
117+
118+
} // namespace arduino
119+
120+
#endif // USE_FIRMATA

0 commit comments

Comments
 (0)