ESPTelnet

repository·main·Indexed 42 days ago

https://github.com/lennarthennigs/esptelnet

An ESP8266/ESP32 library that provides a Telnet server for remote communication of status messages, debug logs, and input. It includes the EscapeCodes library for ANSI terminal formatting, support for Arduino Stream objects via ESPTelnetStream, and built-in debug macros for remote device monitoring.

Tokens
3.8K
Snippets
17
Records
20
Agent score
53%

What's inside ESPTelnet

  1. Use ESPTelnetStream for Stream-based communication

    main
    If you require a Stream implementation rather than the standard print-heavy interface, use the ESPTelnetStream class. This class provides standard stream methods like available(), read(), peek(), and write(), but does not include print() or println() methods.
  2. Send output and receive input via ESPTelnet

    main

    Sending Output

    You can send text to the connected client using standard print methods:

    • print(), printf(), println()

    Receiving Input

    Input is received via the onInputReceived() callback.

    Configuration Options:

    • Line Mode: By default, the library waits for a newline character and sends data one line at a time. Use setLineMode(false) to deactivate this behavior.
    • Newline Character: The default newline character is \n. You can change this using setNewlineCharacter(char value) (e.g., setNewlineCharacter('\r')).
    telnet.onInputReceived([](String input) {
      Serial.println("Received: " + input);
    });
    
    telnet.println("Hello Client!");
  3. Debug remote ESP devices using ESPTelnet macros

    main

    When you don't have serial access, you can use ESPTelnet as a debug output channel.

    1. Enable debugging by setting #define DEBUG_ON 1.
    2. Select output channels by setting #define DEBUG_USE_SERIAL 1 and/or #define DEBUG_USE_TELNET 1.

    Available Macros:

    • DEBUG_INFO: Prints compilation date & time.
    • DEBUG_WHERE: Prints file name and line number.
    • DEBUG_MSG(x): Prints a message.
    • DEBUG_VAR(...): Prints a variable's value.
    #define DEBUG_ON 1
    #define DEBUG_USE_SERIAL 1
    #define DEBUG_USE_TELNET 1
    
    void setup() {
      // ...
      DEBUG_MSG("System starting...");
    }
  4. Install ESPTelnet via Arduino IDE or PlatformIO

    main

    You can install the ESPTelnet library using one of the following methods:

    Arduino IDE

    1. Open Arduino IDE.
    2. Go to Sketch > Include Library and search for "ESPTelnet".
    3. Alternatively, download the ZIP archive from GitHub and use Sketch > Include Library > Add .ZIP Library...

    PlatformIO

    Add the following line to the lib_deps option in your platformio.ini file:

    lennarthennigs/ESP Telnet@^2.2.3
    lennarthennigs/ESP Telnet@^2.2.3
  5. Use ANSI Escape Sequences for terminal formatting

    main

    You can send ANSI escape sequences to the telnet client to clear the screen, move the cursor, or change text colors. The library provides an ansi object (from EscapeCodes.h) that returns these sequences as Strings.

    Example usage:

    telnet.print(ansi.cls());
    telnet.print(ansi.home());
    telnet.print(ansi.setFG(ANSI_BRIGHT_WHITE));
    telnet.println("\nWelcome " + telnet.getIP());
    telnet.print(ansi.reset());
    telnet.print(ansi.cls());
    telnet.print(ansi.home());
    telnet.print(ansi.setFG(ANSI_BRIGHT_WHITE));
    telnet.println("\nWelcome " + telnet.getIP());
    telnet.println("(Use ^] + q  to disconnect.)");
    telnet.print(ansi.reset());
  6. Handle Telnet events with callback handlers

    main

    ESPTelnet uses callback functions to notify you of network events. All callback functions must accept a single String parameter. For onInputReceived, this parameter contains the input text; for other events, it contains the IP address of the client.

    Available callbacks:

    • onConnect(CallbackFunction f)
    • onConnectionAttempt(CallbackFunction f)
    • onReconnect(CallbackFunction f)
    • onDisconnect(CallbackFunction f)
    • onInputReceived(CallbackFunction f)
  7. Start and stop the ESPTelnet server

    main

    To manage the lifecycle of the telnet server, use the begin() and stop() methods.

    • begin(uint16_t port = 23, bool checkConnection = true): Starts the server. You can specify a custom port. If you are using an Ethernet adapter and want to bypass the WiFi connection check, set the second parameter to false (e.g., begin(23, false)).
    • stop(bool disconnectClient = true): Stops the server. The disconnectClient parameter (default true) determines if existing clients should be disconnected.

    Note: You must call loop() in your main sketch loop for the server to function.

    telnet.begin(23, true);
    // ... in loop()
    // telnet.loop();
    // ...
    telnet.stop();
  8. Manage the ESPTelnet lifecycle

    main

    Use the following methods to control the server state and execution:

    • loop(): Crucial. This must be called repeatedly in your main loop() to process connections, handle input, and perform keep-alive checks.
    • stop(bool disconnectClient): Stops the server. If disconnectClient is true, it will also disconnect the current client (defaults to true).
    • isConnected(): Returns true if a client is currently connected.
    • disconnectClient(bool triggerEvent): Manually disconnects the current client. If triggerEvent is true, it will trigger the onDisconnect callback (defaults to true).
    void loop() {
      telnet.loop(); // Must be called to process events
    }
  9. Retrieve connection information

    main

    Use these methods to inspect the network state:

    • getIP(): Returns the IP address of the ESP device.
    • getLastAttemptIP(): Returns the IP address of the last client that attempted to connect.
    • getClient(): Returns a reference to the TCPClient (WiFiClient) currently in use.
  10. Manage cursor visibility and blinking

    main

    Control whether the terminal cursor is visible and how it behaves using showCursor and setCursorBlink.

    // Hide the cursor
    client.print(EscapeCodes::showCursor(false));
    
    // Show the cursor
    client.print(EscapeCodes::showCursor(true));
    
    // Toggle cursor blinking
    client.print(EscapeCodes::setCursorBlink(true));
  11. Register callback handlers for connection events

    main

    ESPTelnet provides several callback methods to react to network events. You can register a CallbackFunction (a function taking a String argument) for each event:

    • onConnect(CallbackFunction f): Triggered when a client successfully connects.
    • onConnectionAttempt(CallbackFunction f): Triggered when a connection attempt is made.
    • onReconnect(CallbackFunction f): Triggered when a client reconnects.
    • onDisconnect(CallbackFunction f): Triggered when a client disconnects.
    • onInputReceived(CallbackFunction f): Triggered when data is received from the client.
    telnet.onConnect([](String str) {
      Serial.println("Client connected!");
    });
    
    telnet.onInputReceived([](String data) {
      Serial.print("Received: ");
      Serial.println(data);
    });
  12. Apply text styling and colors with EscapeCodes

    main

    The EscapeCodes class provides methods to wrap strings in ANSI styling sequences or to set the current terminal state for foreground/background colors.

    // Set current terminal color state
    client.print(EscapeCodes::setFG(ANSI_RED));
    client.print(EscapeCodes::setBG(ANSI_BLACK));
    
    // Wrap specific strings in styles
    String styled = EscapeCodes::bold("Important");
    String slanted = EscapeCodes::italic("Slanted");
    String underlined = EscapeCodes::underline("Underlined");
    String flashing = EscapeCodes::blink("Blinking");
    String inverted = EscapeCodes::inverse("Inverted");
    
    // Reset terminal state
    client.print(EscapeCodes::reset());