X-Ryl669
4 years ago
committed by
GitHub
64 changed files with 784 additions and 950 deletions
@ -0,0 +1,146 @@ |
|||
/**
|
|||
* Marlin 3D Printer Firmware |
|||
* Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin]
|
|||
* |
|||
* Based on Sprinter and grbl. |
|||
* Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm |
|||
* |
|||
* This program is free software: you can redistribute it and/or modify |
|||
* it under the terms of the GNU General Public License as published by |
|||
* the Free Software Foundation, either version 3 of the License, or |
|||
* (at your option) any later version. |
|||
* |
|||
* This program is distributed in the hope that it will be useful, |
|||
* but WITHOUT ANY WARRANTY; without even the implied warranty of |
|||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
|||
* GNU General Public License for more details. |
|||
* |
|||
* You should have received a copy of the GNU General Public License |
|||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|||
* |
|||
*/ |
|||
#pragma once |
|||
|
|||
#include "../inc/MarlinConfigPre.h" |
|||
|
|||
#if ENABLED(EMERGENCY_PARSER) |
|||
#include "../feature/e_parser.h" |
|||
#endif |
|||
|
|||
#ifndef DEC |
|||
#define DEC 10 |
|||
#define HEX 16 |
|||
#define OCT 8 |
|||
#define BIN 2 |
|||
#endif |
|||
|
|||
// flushTX is not implemented in all HAL, so use SFINAE to call the method where it is.
|
|||
CALL_IF_EXISTS_IMPL(void, flushTX ); |
|||
CALL_IF_EXISTS_IMPL(bool, connected, true); |
|||
|
|||
// Using Curiously Recurring Template Pattern here to avoid virtual table cost when compiling.
|
|||
// Since the real serial class is known at compile time, this results in compiler writing a completely
|
|||
// efficient code
|
|||
template <class Child> |
|||
struct SerialBase { |
|||
#if ENABLED(EMERGENCY_PARSER) |
|||
const bool ep_enabled; |
|||
EmergencyParser::State emergency_state; |
|||
inline bool emergency_parser_enabled() { return ep_enabled; } |
|||
SerialBase(bool ep_capable) : ep_enabled(ep_capable), emergency_state(EmergencyParser::State::EP_RESET) {} |
|||
#else |
|||
SerialBase(const bool) {} |
|||
#endif |
|||
|
|||
// Static dispatch methods below:
|
|||
// The most important method here is where it all ends to:
|
|||
size_t write(uint8_t c) { return static_cast<Child*>(this)->write(c); } |
|||
// Called when the parser finished processing an instruction, usually build to nothing
|
|||
void msgDone() { static_cast<Child*>(this)->msgDone(); } |
|||
// Called upon initialization
|
|||
void begin(const long baudRate) { static_cast<Child*>(this)->begin(baudRate); } |
|||
// Called upon destruction
|
|||
void end() { static_cast<Child*>(this)->end(); } |
|||
/** Check for available data from the port
|
|||
@param index The port index, usually 0 */ |
|||
bool available(uint8_t index = 0) { return static_cast<Child*>(this)->available(index); } |
|||
/** Read a value from the port
|
|||
@param index The port index, usually 0 */ |
|||
int read(uint8_t index = 0) { return static_cast<Child*>(this)->read(index); } |
|||
// Check if the serial port is connected (usually bypassed)
|
|||
bool connected() { return static_cast<Child*>(this)->connected(); } |
|||
// Redirect flush
|
|||
void flush() { static_cast<Child*>(this)->flush(); } |
|||
// Not all implementation have a flushTX, so let's call them only if the child has the implementation
|
|||
void flushTX() { CALL_IF_EXISTS(void, static_cast<Child*>(this), flushTX); } |
|||
|
|||
// Glue code here
|
|||
FORCE_INLINE void write(const char* str) { while (*str) write(*str++); } |
|||
FORCE_INLINE void write(const uint8_t* buffer, size_t size) { while (size--) write(*buffer++); } |
|||
FORCE_INLINE void print(const char* str) { write(str); } |
|||
FORCE_INLINE void print(char c, int base = 0) { print((long)c, base); } |
|||
FORCE_INLINE void print(unsigned char c, int base = 0) { print((unsigned long)c, base); } |
|||
FORCE_INLINE void print(int c, int base = DEC) { print((long)c, base); } |
|||
FORCE_INLINE void print(unsigned int c, int base = DEC) { print((unsigned long)c, base); } |
|||
void print(long c, int base = DEC) { if (!base) write(c); write((const uint8_t*)"-", c < 0); printNumber(c < 0 ? -c : c, base); } |
|||
void print(unsigned long c, int base = DEC) { printNumber(c, base); } |
|||
void print(double c, int digits = 2) { printFloat(c, digits); } |
|||
|
|||
FORCE_INLINE void println(const char s[]) { print(s); println(); } |
|||
FORCE_INLINE void println(char c, int base = 0) { print(c, base); println(); } |
|||
FORCE_INLINE void println(unsigned char c, int base = 0) { print(c, base); println(); } |
|||
FORCE_INLINE void println(int c, int base = DEC) { print(c, base); println(); } |
|||
FORCE_INLINE void println(unsigned int c, int base = DEC) { print(c, base); println(); } |
|||
FORCE_INLINE void println(long c, int base = DEC) { print(c, base); println(); } |
|||
FORCE_INLINE void println(unsigned long c, int base = DEC) { print(c, base); println(); } |
|||
FORCE_INLINE void println(double c, int digits = 2) { print(c, digits); println(); } |
|||
void println() { write("\r\n"); } |
|||
|
|||
// Print a number with the given base
|
|||
void printNumber(unsigned long n, const uint8_t base) { |
|||
if (n) { |
|||
unsigned char buf[8 * sizeof(long)]; // Enough space for base 2
|
|||
int8_t i = 0; |
|||
while (n) { |
|||
buf[i++] = n % base; |
|||
n /= base; |
|||
} |
|||
while (i--) write((char)(buf[i] + (buf[i] < 10 ? '0' : 'A' - 10))); |
|||
} |
|||
else write('0'); |
|||
} |
|||
|
|||
// Print a decimal number
|
|||
void printFloat(double number, uint8_t digits) { |
|||
// Handle negative numbers
|
|||
if (number < 0.0) { |
|||
write('-'); |
|||
number = -number; |
|||
} |
|||
|
|||
// Round correctly so that print(1.999, 2) prints as "2.00"
|
|||
double rounding = 0.5; |
|||
LOOP_L_N(i, digits) rounding *= 0.1; |
|||
number += rounding; |
|||
|
|||
// Extract the integer part of the number and print it
|
|||
unsigned long int_part = (unsigned long)number; |
|||
double remainder = number - (double)int_part; |
|||
printNumber(int_part, 10); |
|||
|
|||
// Print the decimal point, but only if there are digits beyond
|
|||
if (digits) { |
|||
write('.'); |
|||
// Extract digits from the remainder one at a time
|
|||
while (digits--) { |
|||
remainder *= 10.0; |
|||
int toPrint = int(remainder); |
|||
printNumber(toPrint, 10); |
|||
remainder -= toPrint; |
|||
} |
|||
} |
|||
} |
|||
}; |
|||
|
|||
// All serial instances will be built by chaining the features required for the function in a form of a template
|
|||
// type definition
|
@ -0,0 +1,230 @@ |
|||
/**
|
|||
* Marlin 3D Printer Firmware |
|||
* Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin]
|
|||
* |
|||
* Based on Sprinter and grbl. |
|||
* Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm |
|||
* |
|||
* This program is free software: you can redistribute it and/or modify |
|||
* it under the terms of the GNU General Public License as published by |
|||
* the Free Software Foundation, either version 3 of the License, or |
|||
* (at your option) any later version. |
|||
* |
|||
* This program is distributed in the hope that it will be useful, |
|||
* but WITHOUT ANY WARRANTY; without even the implied warranty of |
|||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
|||
* GNU General Public License for more details. |
|||
* |
|||
* You should have received a copy of the GNU General Public License |
|||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|||
* |
|||
*/ |
|||
#pragma once |
|||
|
|||
#include "serial_base.h" |
|||
|
|||
// The most basic serial class: it dispatch to the base serial class with no hook whatsoever. This will compile to nothing but the base serial class
|
|||
template <class SerialT> |
|||
struct BaseSerial : public SerialBase< BaseSerial<SerialT> >, public SerialT { |
|||
typedef SerialBase< BaseSerial<SerialT> > BaseClassT; |
|||
|
|||
// It's required to implement a write method here to help compiler disambiguate what method to call
|
|||
using SerialT::write; |
|||
using SerialT::flush; |
|||
|
|||
void msgDone() {} |
|||
|
|||
bool available(uint8_t index) { return index == 0 && SerialT::available(); } |
|||
int read(uint8_t index) { return index == 0 ? SerialT::read() : -1; } |
|||
bool connected() { return CALL_IF_EXISTS(bool, static_cast<SerialT*>(this), connected);; } |
|||
// We have 2 implementation of the same method in both base class, let's say which one we want
|
|||
using SerialT::available; |
|||
using SerialT::read; |
|||
using SerialT::begin; |
|||
using SerialT::end; |
|||
|
|||
using BaseClassT::print; |
|||
using BaseClassT::println; |
|||
|
|||
BaseSerial(const bool e) : BaseClassT(e) {} |
|||
|
|||
// Forward constructor
|
|||
template <typename... Args> |
|||
BaseSerial(const bool e, Args... args) : BaseClassT(e), SerialT(args...) {} |
|||
}; |
|||
|
|||
// A serial with a condition checked at runtime for its output
|
|||
// A bit less efficient than static dispatching but since it's only used for ethernet's serial output right now, it's ok.
|
|||
template <class SerialT> |
|||
struct ConditionalSerial : public SerialBase< ConditionalSerial<SerialT> > { |
|||
typedef SerialBase< ConditionalSerial<SerialT> > BaseClassT; |
|||
|
|||
bool & condition; |
|||
SerialT & out; |
|||
size_t write(uint8_t c) { if (condition) return out.write(c); return 0; } |
|||
void flush() { if (condition) out.flush(); } |
|||
void begin(long br) { out.begin(br); } |
|||
void end() { out.end(); } |
|||
|
|||
void msgDone() {} |
|||
bool connected() { return CALL_IF_EXISTS(bool, &out, connected); } |
|||
|
|||
bool available(uint8_t index) { return index == 0 && out.available(); } |
|||
int read(uint8_t index) { return index == 0 ? out.read() : -1; } |
|||
using BaseClassT::available; |
|||
using BaseClassT::read; |
|||
|
|||
ConditionalSerial(bool & conditionVariable, SerialT & out, const bool e) : BaseClassT(e), condition(conditionVariable), out(out) {} |
|||
}; |
|||
|
|||
// A simple foward class that taking a reference to an existing serial instance (likely created in their respective framework)
|
|||
template <class SerialT> |
|||
struct ForwardSerial : public SerialBase< ForwardSerial<SerialT> > { |
|||
typedef SerialBase< ForwardSerial<SerialT> > BaseClassT; |
|||
|
|||
SerialT & out; |
|||
size_t write(uint8_t c) { return out.write(c); } |
|||
void flush() { out.flush(); } |
|||
void begin(long br) { out.begin(br); } |
|||
void end() { out.end(); } |
|||
|
|||
void msgDone() {} |
|||
// Existing instances implement Arduino's operator bool, so use that if it's available
|
|||
bool connected() { return Private::HasMember_connected<SerialT>::value ? CALL_IF_EXISTS(bool, &out, connected) : (bool)out; } |
|||
|
|||
bool available(uint8_t index) { return index == 0 && out.available(); } |
|||
int read(uint8_t index) { return index == 0 ? out.read() : -1; } |
|||
bool available() { return out.available(); } |
|||
int read() { return out.read(); } |
|||
|
|||
ForwardSerial(const bool e, SerialT & out) : BaseClassT(e), out(out) {} |
|||
}; |
|||
|
|||
// A class that's can be hooked and unhooked at runtime, useful to capturing the output of the serial interface
|
|||
template <class SerialT> |
|||
struct RuntimeSerial : public SerialBase< RuntimeSerial<SerialT> >, public SerialT { |
|||
typedef SerialBase< RuntimeSerial<SerialT> > BaseClassT; |
|||
typedef void (*WriteHook)(void * userPointer, uint8_t c); |
|||
typedef void (*EndOfMessageHook)(void * userPointer); |
|||
|
|||
WriteHook writeHook; |
|||
EndOfMessageHook eofHook; |
|||
void * userPointer; |
|||
|
|||
size_t write(uint8_t c) { |
|||
if (writeHook) writeHook(userPointer, c); |
|||
return SerialT::write(c); |
|||
} |
|||
|
|||
void msgDone() { |
|||
if (eofHook) eofHook(userPointer); |
|||
} |
|||
|
|||
bool available(uint8_t index) { return index == 0 && SerialT::available(); } |
|||
int read(uint8_t index) { return index == 0 ? SerialT::read() : -1; } |
|||
using SerialT::available; |
|||
using SerialT::read; |
|||
using SerialT::flush; |
|||
using SerialT::begin; |
|||
using SerialT::end; |
|||
|
|||
using BaseClassT::print; |
|||
using BaseClassT::println; |
|||
|
|||
|
|||
void setHook(WriteHook writeHook = 0, EndOfMessageHook eofHook = 0, void * userPointer = 0) { |
|||
// Order is important here as serial code can be called inside interrupts
|
|||
// When setting a hook, the user pointer must be set first so if writeHook is called as soon as it's set, it'll be valid
|
|||
if (userPointer) this->userPointer = userPointer; |
|||
this->writeHook = writeHook; |
|||
this->eofHook = eofHook; |
|||
// Order is important here because of asynchronous access here
|
|||
// When unsetting a hook, the user pointer must be unset last so that any pending writeHook is still using the old pointer
|
|||
if (!userPointer) this->userPointer = 0; |
|||
} |
|||
|
|||
RuntimeSerial(const bool e) : BaseClassT(e), writeHook(0), eofHook(0), userPointer(0) {} |
|||
|
|||
// Forward constructor
|
|||
template <typename... Args> |
|||
RuntimeSerial(const bool e, Args... args) : BaseClassT(e), SerialT(args...) {} |
|||
}; |
|||
|
|||
// A class that's duplicating its output conditionally to 2 serial interface
|
|||
template <class Serial0T, class Serial1T, const uint8_t offset = 0> |
|||
struct MultiSerial : public SerialBase< MultiSerial<Serial0T, Serial1T, offset> > { |
|||
typedef SerialBase< MultiSerial<Serial0T, Serial1T, offset> > BaseClassT; |
|||
|
|||
uint8_t portMask; |
|||
Serial0T & serial0; |
|||
Serial1T & serial1; |
|||
|
|||
enum Masks { |
|||
FirstOutputMask = (1 << offset), |
|||
SecondOutputMask = (1 << (offset + 1)), |
|||
AllMask = FirstOutputMask | SecondOutputMask, |
|||
}; |
|||
|
|||
size_t write(uint8_t c) { |
|||
size_t ret = 0; |
|||
if (portMask & FirstOutputMask) ret = serial0.write(c); |
|||
if (portMask & SecondOutputMask) ret = serial1.write(c) | ret; |
|||
return ret; |
|||
} |
|||
void msgDone() { |
|||
if (portMask & FirstOutputMask) serial0.msgDone(); |
|||
if (portMask & SecondOutputMask) serial1.msgDone(); |
|||
} |
|||
bool available(uint8_t index) { |
|||
switch(index) { |
|||
case 0 + offset: return serial0.available(); |
|||
case 1 + offset: return serial1.available(); |
|||
default: return false; |
|||
} |
|||
} |
|||
int read(uint8_t index) { |
|||
switch(index) { |
|||
case 0 + offset: return serial0.read(); |
|||
case 1 + offset: return serial1.read(); |
|||
default: return -1; |
|||
} |
|||
} |
|||
void begin(const long br) { |
|||
if (portMask & FirstOutputMask) serial0.begin(br); |
|||
if (portMask & SecondOutputMask) serial1.begin(br); |
|||
} |
|||
void end() { |
|||
if (portMask & FirstOutputMask) serial0.end(); |
|||
if (portMask & SecondOutputMask) serial1.end(); |
|||
} |
|||
bool connected() { |
|||
bool ret = true; |
|||
if (portMask & FirstOutputMask) ret = CALL_IF_EXISTS(bool, &serial0, connected); |
|||
if (portMask & SecondOutputMask) ret = ret && CALL_IF_EXISTS(bool, &serial1, connected); |
|||
return ret; |
|||
} |
|||
|
|||
using BaseClassT::available; |
|||
using BaseClassT::read; |
|||
|
|||
// Redirect flush
|
|||
void flush() { |
|||
if (portMask & FirstOutputMask) serial0.flush(); |
|||
if (portMask & SecondOutputMask) serial1.flush(); |
|||
} |
|||
void flushTX() { |
|||
if (portMask & FirstOutputMask) CALL_IF_EXISTS(void, &serial0, flushTX); |
|||
if (portMask & SecondOutputMask) CALL_IF_EXISTS(void, &serial1, flushTX); |
|||
} |
|||
|
|||
MultiSerial(Serial0T & serial0, Serial1T & serial1, int8_t mask = AllMask, const bool e = false) : |
|||
BaseClassT(e), |
|||
portMask(mask), serial0(serial0), serial1(serial1) {} |
|||
}; |
|||
|
|||
// Build the actual serial object depending on current configuration
|
|||
#define Serial0Type TERN(SERIAL_RUNTIME_HOOK, RuntimeSerial, BaseSerial) |
|||
#define ForwardSerial0Type TERN(SERIAL_RUNTIME_HOOK, RuntimeSerial, ForwardSerial) |
|||
#ifdef HAS_MULTI_SERIAL |
|||
#define Serial1Type ConditionalSerial |
|||
#endif |
@ -0,0 +1,44 @@ |
|||
# Serial port architecture in Marlin |
|||
|
|||
Marlin is targeting a pletora of different CPU architecture and platforms. Each of these platforms has its own serial interface. |
|||
While many provide a Arduino-like Serial class, it's not all of them, and the differences in the existing API create a very complex brain teaser for writing code that works more or less on each platform. |
|||
|
|||
Moreover, many platform have intrinsic needs about serial port (like forwarding the output on multiple serial port, providing a *serial-like* telnet server, mixing USB-based serial port with SD card emulation) that are difficult to handle cleanly in the other platform serial logic. |
|||
|
|||
|
|||
Starting with version `2.0.9`, Marlin provides a common interface for its serial needs. |
|||
|
|||
## Common interface |
|||
|
|||
This interface is declared in `Marlin/src/core/serial_base.h` |
|||
Any implementation will need to follow this interface for being used transparently in Marlin's codebase. |
|||
|
|||
The implementation was written to prioritize performance over abstraction, so the base interface is not using virtual inheritance to avoid the cost of virtual dispatching while calling methods. |
|||
Instead, the Curiously Recurring Template Pattern (**CRTP**) is used so that, upon compilation, the interface abstraction does not incur a performance cost. |
|||
|
|||
Because some platform do not follow the same interface, the missing method in the actual low-level implementation are detected via SFINAE and a wrapper is generated when such method are missing. See `CALL_IF_EXISTS` macro in `Marlin/src/core/macros.h` for the documentation of this technic. |
|||
|
|||
## Composing the desired feature |
|||
The different specificities for each architecture are provided by composing the serial type based on desired functionality. |
|||
In the `Marlin/src/core/serial_hook.h` file, the different serial feature are declared and defined in each templated type: |
|||
1. `BaseSerial` is a simple 1:1 wrapper to the underlying, Arduino compatible, `Serial`'s class. It derives from it. You'll use this if the platform does not do anything specific for the `Serial` object (for example, if an interrupt callback calls directly the serial **instance** in the platform's framework code, this is not the right class to use). This wrapper is completely inlined so that it does not generate any code upon compilation. `BaseSerial` constructor forwards any parameter to the platform's `Serial`'s constructor. |
|||
2. `ForwardSerial` is a composing wrapper. It references an actual Arduino compatible `Serial` instance. You'll use this if the instance is declared in the platform's framework and is being referred directly in the framework. This is not as efficient as the `BaseSerial` implementation since static dereferencing is done for each method call (it'll still be faster than virtual dispatching) |
|||
3. `ConditionalSerial` is working a bit like the `ForwardSerial` interface, but it checks a boolean condition before calling the referenced instance. You'll use it when the serial output can be switch off at runtime, for example in a *telnet* like serial output that should not emit any packet if no client is connected. |
|||
4. `RuntimeSerial` is providing a runtime-modifiable hooking method for its `write` and `msgDone` method. You'll use it if you need to capture the serial output of Marlin, for example to display the G-Code parser's output on a GUI interface. The hooking interface is setup via the `setHook` method. |
|||
5. `MultiSerial` is a runtime modifiable serial output multiplexer. It can output (*respectively input*) to 2 different interface based on a port *mask*. You'll use this if you need to output the same serial stream to multiple port. You can plug a `MultiSerial` to itself to duplicate to more than 2 ports. |
|||
|
|||
## Plumbing |
|||
Since all the types above are using CRTP, it's possible to combine them to get the appropriate functionality. |
|||
This is easily done via type definition of the feature. |
|||
|
|||
For example, to present a serial interface that's outputting to 2 serial port, the first one being hooked at runtime and the second one connected to a runtime switchable telnet client, you'll declare the type to use as: |
|||
``` |
|||
typedef MultiSerial< RuntimeSerial<Serial>, ConditionalSerial<TelnetClient> > Serial0Type; |
|||
``` |
|||
|
|||
## Emergency parser |
|||
By default, the serial base interface provide an emergency parser that's only enable for serial classes that support it. |
|||
Because of this condition, all underlying type takes a first `bool emergencyParserEnabled` argument to their constructor. You must take into account this parameter when defining the actual type used. |
|||
|
|||
|
|||
*This document was written by [X-Ryl669](https://blog.cyril.by) and is under [CC-SA license](https://creativecommons.org/licenses/by-sa)* |
Loading…
Reference in new issue