From 8ac52aedff4582e7ede41b1c111790e29e156942 Mon Sep 17 00:00:00 2001
From: Lucio Tarantino <lucio.tarantino@gmail.com>
Date: Sun, 8 Sep 2019 07:57:59 +0200
Subject: [PATCH] M118 multiserial support (#15176)

---
 Marlin/src/gcode/host/M118.cpp | 43 +++++++++++++++++++++++++++++-----
 1 file changed, 37 insertions(+), 6 deletions(-)

diff --git a/Marlin/src/gcode/host/M118.cpp b/Marlin/src/gcode/host/M118.cpp
index 7655a27f15..3d8a84fb5f 100644
--- a/Marlin/src/gcode/host/M118.cpp
+++ b/Marlin/src/gcode/host/M118.cpp
@@ -21,24 +21,55 @@
  */
 
 #include "../gcode.h"
+#include "../../core/serial.h"
 
 /**
  * M118: Display a message in the host console.
  *
  *  A1  Prepend '// ' for an action command, as in OctoPrint
  *  E1  Have the host 'echo:' the text
+ *  Pn  Redirect to another serial port
+ *        0 : Announce to all ports
+ *      1-9 : Serial ports 1 to 9
  */
 void GcodeSuite::M118() {
   bool hasE = false, hasA = false;
+  #if NUM_SERIAL > 1
+    int8_t port = -1; // Assume no redirect
+  #endif
   char *p = parser.string_arg;
-  for (uint8_t i = 2; i--;)
-    if ((p[0] == 'A' || p[0] == 'E') && p[1] == '1') {
-      if (p[0] == 'A') hasA = true;
-      if (p[0] == 'E') hasE = true;
-      p += 2;
-      while (*p == ' ') ++p;
+  for (uint8_t i = 3; i--;) {
+    // A1, E1, and Pn are always parsed out
+    if (!( ((p[0] == 'A' || p[0] == 'E') && p[1] == '1') || (p[0] == 'P' && NUMERIC(p[1])) )) break;
+    switch (p[0]) {
+      case 'A': hasA = true; break;
+      case 'E': hasE = true; break;
+      #if NUM_SERIAL > 1
+        case 'P': port = p[1] - '0'; break;
+      #endif
     }
+    p += 2;
+    while (*p == ' ') ++p;
+  }
+
+  #if NUM_SERIAL > 1
+    const int8_t old_serial = serial_port_index;
+    if (WITHIN(port, 0, NUM_SERIAL))
+      serial_port_index = (
+        port == 0 ? SERIAL_BOTH
+        : port == 1 ? SERIAL_PORT
+        #ifdef SERIAL_PORT_2
+          : port == 2 ? SERIAL_PORT_2
+        #endif
+        : SERIAL_PORT
+      );
+  #endif
+
   if (hasE) SERIAL_ECHO_START();
   if (hasA) SERIAL_ECHOPGM("// ");
   SERIAL_ECHOLN(p);
+
+  #if NUM_SERIAL > 1
+    serial_port_index = old_serial;
+  #endif
 }
-- 
GitLab