My Marlin configs for Fabrikator Mini and CTC i3 Pro B
Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

serial_base.h 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. /**
  2. * Marlin 3D Printer Firmware
  3. * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin]
  4. *
  5. * Based on Sprinter and grbl.
  6. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm
  7. *
  8. * This program is free software: you can redistribute it and/or modify
  9. * it under the terms of the GNU General Public License as published by
  10. * the Free Software Foundation, either version 3 of the License, or
  11. * (at your option) any later version.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License
  19. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  20. *
  21. */
  22. #pragma once
  23. #include "../inc/MarlinConfigPre.h"
  24. #if ENABLED(EMERGENCY_PARSER)
  25. #include "../feature/e_parser.h"
  26. #endif
  27. // Used in multiple places
  28. // You can build it but not manipulate it.
  29. // There are only few places where it's required to access the underlying member: GCodeQueue, SerialMask and MultiSerial
  30. struct serial_index_t {
  31. // A signed index, where -1 is a special case meaning no action (neither output or input)
  32. int8_t index;
  33. // Check if the index is within the range [a ... b]
  34. constexpr inline bool within(const int8_t a, const int8_t b) const { return WITHIN(index, a, b); }
  35. constexpr inline bool valid() const { return WITHIN(index, 0, 7); } // At most, 8 bits
  36. // Construction is either from an index
  37. constexpr serial_index_t(const int8_t index) : index(index) {}
  38. // Default to "no index"
  39. constexpr serial_index_t() : index(-1) {}
  40. };
  41. // In order to catch usage errors in code, we make the base to encode number explicit
  42. // If given a number (and not this enum), the compiler will reject the overload, falling back to the (double, digit) version
  43. // We don't want hidden conversion of the first parameter to double, so it has to be as hard to do for the compiler as creating this enum
  44. enum class PrintBase {
  45. Dec = 10,
  46. Hex = 16,
  47. Oct = 8,
  48. Bin = 2
  49. };
  50. // A simple feature list enumeration
  51. enum class SerialFeature {
  52. None = 0x00,
  53. MeatPack = 0x01, //!< Enabled when Meatpack is present
  54. BinaryFileTransfer = 0x02, //!< Enabled for BinaryFile transfer support (in the future)
  55. Virtual = 0x04, //!< Enabled for virtual serial port (like Telnet / Websocket / ...)
  56. Hookable = 0x08, //!< Enabled if the serial class supports a setHook method
  57. };
  58. ENUM_FLAGS(SerialFeature);
  59. // flushTX is not implemented in all HAL, so use SFINAE to call the method where it is.
  60. CALL_IF_EXISTS_IMPL(void, flushTX);
  61. CALL_IF_EXISTS_IMPL(bool, connected, true);
  62. CALL_IF_EXISTS_IMPL(SerialFeature, features, SerialFeature::None);
  63. // A simple forward struct to prevent the compiler from selecting print(double, int) as a default overload
  64. // for any type other than double/float. For double/float, a conversion exists so the call will be invisible.
  65. struct EnsureDouble {
  66. double a;
  67. operator double() { return a; }
  68. // If the compiler breaks on ambiguity here, it's likely because print(X, base) is called with X not a double/float, and
  69. // a base that's not a PrintBase value. This code is made to detect the error. You MUST set a base explicitly like this:
  70. // SERIAL_PRINT(v, PrintBase::Hex)
  71. EnsureDouble(double a) : a(a) {}
  72. EnsureDouble(float a) : a(a) {}
  73. };
  74. // Using Curiously-Recurring Template Pattern here to avoid virtual table cost when compiling.
  75. // Since the real serial class is known at compile time, this results in the compiler writing
  76. // a completely efficient code.
  77. template <class Child>
  78. struct SerialBase {
  79. #if ENABLED(EMERGENCY_PARSER)
  80. const bool ep_enabled;
  81. EmergencyParser::State emergency_state;
  82. inline bool emergency_parser_enabled() { return ep_enabled; }
  83. SerialBase(bool ep_capable) : ep_enabled(ep_capable), emergency_state(EmergencyParser::State::EP_RESET) {}
  84. #else
  85. SerialBase(const bool) {}
  86. #endif
  87. #define SerialChild static_cast<Child*>(this)
  88. // Static dispatch methods below:
  89. // The most important method here is where it all ends to:
  90. void write(uint8_t c) { SerialChild->write(c); }
  91. // Called when the parser finished processing an instruction, usually build to nothing
  92. void msgDone() const { SerialChild->msgDone(); }
  93. // Called on initialization
  94. void begin(const long baudRate) { SerialChild->begin(baudRate); }
  95. // Called on destruction
  96. void end() { SerialChild->end(); }
  97. /** Check for available data from the port
  98. @param index The port index, usually 0 */
  99. int available(serial_index_t index=0) const { return SerialChild->available(index); }
  100. /** Read a value from the port
  101. @param index The port index, usually 0 */
  102. int read(serial_index_t index=0) { return SerialChild->read(index); }
  103. /** Combine the features of this serial instance and return it
  104. @param index The port index, usually 0 */
  105. SerialFeature features(serial_index_t index=0) const { return static_cast<const Child*>(this)->features(index); }
  106. // Check if the serial port has a feature
  107. bool has_feature(serial_index_t index, SerialFeature flag) const { return (features(index) & flag) != SerialFeature::None; }
  108. // Check if the serial port is connected (usually bypassed)
  109. bool connected() const { return SerialChild->connected(); }
  110. // Redirect flush
  111. void flush() { SerialChild->flush(); }
  112. // Not all implementation have a flushTX, so let's call them only if the child has the implementation
  113. void flushTX() { CALL_IF_EXISTS(void, SerialChild, flushTX); }
  114. // Glue code here
  115. void write(const char *str) { while (*str) write(*str++); }
  116. void write(const uint8_t *buffer, size_t size) { while (size--) write(*buffer++); }
  117. void print(char *str) { write(str); }
  118. void print(const char *str) { write(str); }
  119. // No default argument to avoid ambiguity
  120. // Define print for every fundamental integer type, to ensure that all redirect properly
  121. // to the correct underlying implementation.
  122. // Prints are performed with a single size, to avoid needing multiple print functions.
  123. // The fixed integer size used for prints will be the larger of long or a pointer.
  124. #if __LONG_WIDTH__ >= __INTPTR_WIDTH__
  125. typedef long int_fixed_print_t;
  126. typedef unsigned long uint_fixed_print_t;
  127. #else
  128. typedef intptr_t int_fixed_print_t;
  129. typedef uintptr_t uint_fixed_print_t;
  130. FORCE_INLINE void print(intptr_t c, PrintBase base) { printNumber_signed(c, base); }
  131. FORCE_INLINE void print(uintptr_t c, PrintBase base) { printNumber_unsigned(c, base); }
  132. #endif
  133. FORCE_INLINE void print(char c, PrintBase base) { printNumber_signed(c, base); }
  134. FORCE_INLINE void print(short c, PrintBase base) { printNumber_signed(c, base); }
  135. FORCE_INLINE void print(int c, PrintBase base) { printNumber_signed(c, base); }
  136. FORCE_INLINE void print(long c, PrintBase base) { printNumber_signed(c, base); }
  137. FORCE_INLINE void print(unsigned char c, PrintBase base) { printNumber_unsigned(c, base); }
  138. FORCE_INLINE void print(unsigned short c, PrintBase base) { printNumber_unsigned(c, base); }
  139. FORCE_INLINE void print(unsigned int c, PrintBase base) { printNumber_unsigned(c, base); }
  140. FORCE_INLINE void print(unsigned long c, PrintBase base) { printNumber_unsigned(c, base); }
  141. void print(EnsureDouble c, int digits) { printFloat(c, digits); }
  142. // Forward the call to the former's method
  143. // Default implementation for anything without a specialization
  144. // This handles integers since they are the most common
  145. template <typename T>
  146. void print(T c) { print(c, PrintBase::Dec); }
  147. void print(float c) { print(c, 2); }
  148. void print(double c) { print(c, 2); }
  149. void println(char *s) { print(s); println(); }
  150. void println(const char *s) { print(s); println(); }
  151. void println(float c, int digits) { print(c, digits); println(); }
  152. void println(double c, int digits) { print(c, digits); println(); }
  153. void println() { write('\r'); write('\n'); }
  154. // Default implementations for types without a specialization. Handles integers.
  155. template <typename T>
  156. void println(T c, PrintBase base) { print(c, base); println(); }
  157. template <typename T>
  158. void println(T c) { println(c, PrintBase::Dec); }
  159. // Forward the call to the former's method
  160. void println(float c) { println(c, 2); }
  161. void println(double c) { println(c, 2); }
  162. // Print a number with the given base
  163. NO_INLINE void printNumber_unsigned(uint_fixed_print_t n, PrintBase base) {
  164. if (n) {
  165. unsigned char buf[8 * sizeof(long)]; // Enough space for base 2
  166. int8_t i = 0;
  167. while (n) {
  168. buf[i++] = n % (uint_fixed_print_t)base;
  169. n /= (uint_fixed_print_t)base;
  170. }
  171. while (i--) write((char)(buf[i] + (buf[i] < 10 ? '0' : 'A' - 10)));
  172. }
  173. else write('0');
  174. }
  175. NO_INLINE void printNumber_signed(int_fixed_print_t n, PrintBase base) {
  176. if (base == PrintBase::Dec && n < 0) {
  177. n = -n; // This works because all platforms Marlin's builds on are using 2-complement encoding for negative number
  178. // On such CPU, changing the sign of a number is done by inverting the bits and adding one, so if n = 0x80000000 = -2147483648 then
  179. // -n = 0x7FFFFFFF + 1 => 0x80000000 = 2147483648 (if interpreted as unsigned) or -2147483648 if interpreted as signed.
  180. // On non 2-complement CPU, there would be no possible representation for 2147483648.
  181. write('-');
  182. }
  183. printNumber_unsigned((uint_fixed_print_t)n , base);
  184. }
  185. // Print a decimal number
  186. NO_INLINE void printFloat(double number, uint8_t digits) {
  187. // Handle negative numbers
  188. if (number < 0.0) {
  189. write('-');
  190. number = -number;
  191. }
  192. // Round correctly so that print(1.999, 2) prints as "2.00"
  193. double rounding = 0.5;
  194. LOOP_L_N(i, digits) rounding *= 0.1;
  195. number += rounding;
  196. // Extract the integer part of the number and print it
  197. unsigned long int_part = (unsigned long)number;
  198. double remainder = number - (double)int_part;
  199. printNumber_unsigned(int_part, PrintBase::Dec);
  200. // Print the decimal point, but only if there are digits beyond
  201. if (digits) {
  202. write('.');
  203. // Extract digits from the remainder one at a time
  204. while (digits--) {
  205. remainder *= 10.0;
  206. unsigned long toPrint = (unsigned long)remainder;
  207. printNumber_unsigned(toPrint, PrintBase::Dec);
  208. remainder -= toPrint;
  209. }
  210. }
  211. }
  212. };
  213. // All serial instances will be built by chaining the features required
  214. // for the function in the form of a template type definition.