LCC Fusion Project 1.0
LCC Automation
Loading...
Searching...
No Matches
SerialIO Class Reference

General-purpose input handler for text-based packets over multiple transports. More...

#include <SerialIO.h>

Collaboration diagram for SerialIO:

Public Member Functions

void onHelpRequest (const HelpHandler &cb)
 Install a callback to run whenever the user sends just "?". More...
 
void onTestRequest (const TestHandler &cb)
 Install a callback to run whenever the user sends just "T". More...
 
void onProgramRequest (const ProgramHandler &cb)
 Install a callback to run whenever the user sends just "P". More...
 
void begin (uint8_t baseAddr=0, uint8_t sdaPin=0, uint8_t sclPin=0, uint8_t addrPin1=0, uint8_t addrPin2=0, uint8_t addrPin3=0)
 Initialize all requested interfaces. More...
 
const char * getWebSSID () const
 Retrieve the WebSerial SSID in use. More...
 
String getWebURL () const
 Get the URL for the WebSerial interface. More...
 
const char * getBTName () const
 Get the active Bluetooth device name (with I²C suffix if present). More...
 
bool available () const
 Check if any input interface has pending data. More...
 
bool read ()
 Read one complete packet from any interface. More...
 
void parse_reset ()
 Reset the internal parse state so the next parse(...) call starts from the beginning of commandBuffer.
 
template<typename... Outs>
int parse (bool expectBrackets, Outs &...outs)
 Token-pointer parser: split space-delimited args, optionally requiring <...>. More...
 
void displayConnectionInfo ()
 Print currently active connection endpoints to all consoles. More...
 
uint8_t getI2cOffset ()
 Return the current I²C address offset (0..7) determined from pins. More...
 
void print (const char *msg)
 Print a string to all active consoles. More...
 
void sprintf (const char *fmt,...)
 printf-style logging to all active consoles (no newline). More...
 
void sprintlnf (const char *fmt,...)
 printf-style logging with newline (like println()). More...
 
void println (const char *msg)
 Print a line (with \n) to all active consoles. More...
 
template<typename... Args>
void printf (const char *fmt, Args... args)
 printf-style logging to all active consoles (no newline). More...
 

Public Attributes

char commandBuffer [CMD_BUF_SIZE] = {0}
 Raw command content without '<' or '>'.
 

Private Member Functions

bool _readSerial ()
 Read from UART into commandBuffer until '>' is received. More...
 
bool _readBluetooth ()
 Read from BluetoothSerial into commandBuffer until '>' is received. More...
 
void _vprintfAll (bool withNl, const char *fmt, va_list ap)
 Internal helper: format once and fan-out to all enabled consoles. More...
 

Static Private Member Functions

static uint8_t _computeI2cAddr (uint8_t base, uint8_t pin1, uint8_t pin2, uint8_t pin3)
 Compute I²C address from base + three address pins (active-low). More...
 
static void _onI2cReceive (int)
 I²C receive ISR callback: buffers chars between '<' and '>'. More...
 
static void _onWebReceive (uint8_t *data, size_t len)
 WebSerial message callback: buffers chars between '<' and '>'. More...
 

Detailed Description

General-purpose input handler for text-based packets over multiple transports.

Packet format

Commands are ASCII strings wrapped in angle brackets:

<OP arg1 arg2 ...>

The brackets are not stored; payload is placed in commandBuffer as a C string.

Typical usage

SerialIO serialIo;
serialIo.begin("BSD", "BSD_AP", baseAddr, SDA, SCL, A0, A1, A2);
while (!serialIo.available()) { }
if (serialIo.read()) {
char op;
char *a1 = nullptr, *a2 = nullptr;
serialIo.parse(&op, a1, a2);
// handle op/args...
}
General-purpose input handler for text-based packets over multiple transports.
Definition: SerialIO.h:98
bool read()
Read one complete packet from any interface.
Definition: SerialIO.h:300
bool available() const
Check if any input interface has pending data.
Definition: SerialIO.h:275
void begin(uint8_t baseAddr=0, uint8_t sdaPin=0, uint8_t sclPin=0, uint8_t addrPin1=0, uint8_t addrPin2=0, uint8_t addrPin3=0)
Initialize all requested interfaces.
Definition: SerialIO.h:167
int parse(bool expectBrackets, Outs &...outs)
Token-pointer parser: split space-delimited args, optionally requiring <...>.
Definition: SerialIO.h:470

Definition at line 97 of file SerialIO.h.

Member Function Documentation

◆ _computeI2cAddr()

static uint8_t SerialIO::_computeI2cAddr ( uint8_t  base,
uint8_t  pin1,
uint8_t  pin2,
uint8_t  pin3 
)
inlinestaticprivate

Compute I²C address from base + three address pins (active-low).

Each pin is sampled with INPUT_PULLUP. A LOW reads as '1' in the offset. The resulting 3-bit offset (0..7) is added to base.

Parameters
baseBase 7-bit I²C address.
pin1LSB select pin (active-low).
pin2Middle select pin (active-low).
pin3MSB select pin (active-low).
Returns
7-bit address for Wire.begin().

Definition at line 725 of file SerialIO.h.

Here is the caller graph for this function:

◆ _onI2cReceive()

static void SerialIO::_onI2cReceive ( int  )
inlinestaticprivate

I²C receive ISR callback: buffers chars between '<' and '>'.

Incoming bytes are appended into a static buffer. A '<' clears the buffer. A '>' marks end-of-packet; the function leaves the buffer intact for read(). Extra characters beyond CMD_BUF_SIZE-1 are dropped.

Definition at line 747 of file SerialIO.h.

Here is the caller graph for this function:

◆ _onWebReceive()

static void SerialIO::_onWebReceive ( uint8_t *  data,
size_t  len 
)
inlinestaticprivate

WebSerial message callback: buffers chars between '<' and '>'.

Accumulates characters into a static buffer; '<' clears, '>' ends. Content is later consumed by read() if useWeb_ is true.

Definition at line 840 of file SerialIO.h.

Here is the caller graph for this function:

◆ _readBluetooth()

bool SerialIO::_readBluetooth ( )
inlineprivate

Read from BluetoothSerial into commandBuffer until '>' is received.

Returns
true when a complete packet has been captured.

Definition at line 806 of file SerialIO.h.

Here is the caller graph for this function:

◆ _readSerial()

bool SerialIO::_readSerial ( )
inlineprivate

Read from UART into commandBuffer until '>' is received.

Returns
true when a complete packet has been captured.

Definition at line 776 of file SerialIO.h.

Here is the caller graph for this function:

◆ _vprintfAll()

void SerialIO::_vprintfAll ( bool  withNl,
const char *  fmt,
va_list  ap 
)
inlineprivate

Internal helper: format once and fan-out to all enabled consoles.

Parameters
withNlIf true, append a single '\n' to the formatted message.
fmtprintf-style format string.
apvarargs list.
Note
Uses a heap buffer sized exactly to the formatted output; frees after write.

Definition at line 872 of file SerialIO.h.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ available()

bool SerialIO::available ( ) const
inline

Check if any input interface has pending data.

Returns
true if Serial, Bluetooth, WebSerial, or I²C has buffered data.
Note
WebSerial/I²C use internal buffers; UART/BT query hardware FIFOs.

Definition at line 275 of file SerialIO.h.

◆ begin()

void SerialIO::begin ( uint8_t  baseAddr = 0,
uint8_t  sdaPin = 0,
uint8_t  sclPin = 0,
uint8_t  addrPin1 = 0,
uint8_t  addrPin2 = 0,
uint8_t  addrPin3 = 0 
)
inline

Initialize all requested interfaces.

Brings up any subset of:

  • UART (always available via Serial),
  • Bluetooth Classic SPP (only if HAS_BT_CLASSIC==1 and BT_DEVICE_NAME is defined),
  • WebSerial over Wi-Fi AP (only if WEB_SSID is defined; optional WEB_PASS),
  • I²C target (if baseAddr > 0; address select pins provide offset 0..7).

Configuration is controlled at compile time:

  • Define BT_DEVICE_NAME as a string literal (e.g., -DBT_DEVICE_NAME="LccFusion") and set HAS_BT_CLASSIC=1 on targets that support BT Classic (original ESP32). On targets without BT Classic (e.g., ESP32-S3), set HAS_BT_CLASSIC=0 and this feature is compiled out.
  • Define WEB_SSID (and optionally WEB_PASS) to enable the Wi-Fi AP + WebSerial. When useI2C_ is true, the SSID is suffixed with the 7-bit I²C address.
Parameters
baseAddrBase 7-bit I²C address; 0 disables I²C target mode.
sdaPinSDA pin for I²C.
sclPinSCL pin for I²C.
addrPin1LSB I²C address select pin.
addrPin2Mid I²C address select pin.
addrPin3MSB I²C address select pin.
Postcondition
useBT_, useWeb_, and useI2C_ reflect which transports were activated.
Note
On ESP32-S3 and other non-Classic parts, BluetoothSerial (SPP) is unavailable; the BT block is excluded by HAS_BT_CLASSIC==0. Use USB-CDC or a BLE UART instead.

Definition at line 167 of file SerialIO.h.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ displayConnectionInfo()

void SerialIO::displayConnectionInfo ( )
inline

Print currently active connection endpoints to all consoles.

Prints Bluetooth device name (if BT active) and, if WebSerial is active, waits briefly for AP to start then prints SSID and URL. On error, prints a WebSerial-not-started message.

Definition at line 561 of file SerialIO.h.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ getBTName()

const char * SerialIO::getBTName ( ) const
inline

Get the active Bluetooth device name (with I²C suffix if present).

Returns
BT name string, or an empty string if BT is disabled.

Definition at line 265 of file SerialIO.h.

Here is the caller graph for this function:

◆ getI2cOffset()

uint8_t SerialIO::getI2cOffset ( )
inline

Return the current I²C address offset (0..7) determined from pins.

Returns
3-bit address offset used in begin().

Definition at line 585 of file SerialIO.h.

Here is the caller graph for this function:

◆ getWebSSID()

const char * SerialIO::getWebSSID ( ) const
inline

Retrieve the WebSerial SSID in use.

Returns
SSID string if WebSerial is enabled, otherwise an empty string.

Definition at line 240 of file SerialIO.h.

Here is the caller graph for this function:

◆ getWebURL()

String SerialIO::getWebURL ( ) const
inline

Get the URL for the WebSerial interface.

Returns
"http://&lt;AP_IP&gt;/" if WebSerial is enabled, otherwise empty.

Definition at line 249 of file SerialIO.h.

Here is the caller graph for this function:

◆ onHelpRequest()

void SerialIO::onHelpRequest ( const HelpHandler &  cb)
inline

Install a callback to run whenever the user sends just "?".

Parameters
cbCallable invoked when a single-question-mark packet is received. The packet is swallowed and not returned by read().

Definition at line 112 of file SerialIO.h.

Here is the caller graph for this function:

◆ onProgramRequest()

void SerialIO::onProgramRequest ( const ProgramHandler &  cb)
inline

Install a callback to run whenever the user sends just "P".

Parameters
cbCallable invoked when a single 'P' packet is received. The packet is swallowed and not returned by read().

Definition at line 132 of file SerialIO.h.

Here is the caller graph for this function:

◆ onTestRequest()

void SerialIO::onTestRequest ( const TestHandler &  cb)
inline

Install a callback to run whenever the user sends just "T".

Parameters
cbCallable invoked when a single 'T' packet is received. The packet is swallowed and not returned by read().

Definition at line 122 of file SerialIO.h.

Here is the caller graph for this function:

◆ parse()

template<typename... Outs>
int SerialIO::parse ( bool  expectBrackets,
Outs &...  outs 
)
inline

Token-pointer parser: split space-delimited args, optionally requiring <...>.

Accepts two input styles in commandBuffer: • Plain: "arg1 arg2 ..." • Bracketed: "< arg1 arg2 ... >"

Behavior:

  • If expectBrackets is true, input MUST be framed with '<' ... '>'. Brackets are stripped before tokenizing. If missing/invalid, returns 0.
  • If expectBrackets is false, both styles are accepted. Well-formed brackets (if present) are stripped; otherwise '<' and '>' are ordinary chars.
  • Returns pointers into the in-place tokenized commandBuffer (no copies).
  • Repeated calls continue consuming tokens from the same buffer until exhausted; then the internal state auto-resets.

Delimiter: single space ' ' (tabs are not treated as delimiters).

Template Parameters
OutsVariadic pack where every parameter is a char*& to receive a token pointer.
Parameters
expectBracketsRequire "< ... >" framing if true.
outschar*& outputs (pointers into commandBuffer tokens).
Returns
Number of tokens assigned to outs (0..N).
Warning
Uses strtok on commandBuffer (modifies it). Returned pointers remain valid until commandBuffer is overwritten.
Examples
// --- Example 1: Your original loop (plain input, no op token) ---
// Input: "10 25 30 45 60 80"
strcpy(commandBuffer, "10 25 30 45 60 80");
parse_reset(); // start fresh for this line
char *minStr, *maxStr;
while (parse(false, minStr, maxStr) == 2) {
int minCm = atoi(minStr);
int maxCm = atoi(maxStr);
// handle one sensor window here...
}
// --- Example 2: Bracketed input required ---
// Input: "< 12 24 40 55 >"
strcpy(commandBuffer, "< 12 24 40 55 >");
while (parse(true, minStr, maxStr) == 2) {
// minStr -> "12", maxStr -> "24" (first pair), then "40","55"
}
// --- Example 3: Mixed acceptance (accept either plain or bracketed) ---
// Accepts "< 5 15 20 30 >" or "5 15 20 30" transparently:
strcpy(commandBuffer, "< 5 15 20 30 >");
while (parse(false, minStr, maxStr) == 2) { }
strcpy(commandBuffer, "5 15 20 30");
while (parse(false, minStr, maxStr) == 2) { }
// --- Example 4: Handling odd token counts gracefully ---
// Input: "10 25 30" -> last '30' has no pair; final parse returns 1
strcpy(commandBuffer, "10 25 30");
int got = parse(false, minStr, maxStr); // got==2, min="10", max="25"
got = parse(false, minStr, maxStr); // got==1, min="30" only
// You can decide to ignore incomplete pairs if got != 2.
// --- Example 5: Early validation of bracket requirement ---
// If closing '>' is missing, function returns 0 immediately.
strcpy(commandBuffer, "< 10 25 30 45"); // missing '>'
if (parse(true, minStr, maxStr) == 0) {
// report malformed bracketed frame to caller
}
// --- Example 6: Parsing a fixed tuple (three tokens per call) ---
// Input: "< A 100 200 B 300 400 >"
strcpy(commandBuffer, "< A 100 200 B 300 400 >");
char *label, *lo, *hi;
while (parse(true, label, lo, hi) == 3) {
// label="A", lo="100", hi="200", then label="B", lo="300", hi="400"
}
// --- Example 7: Integrating into your processCommand() ---
sensorStatus.triggeredSensors = 0;
parse_reset(); // new line
char *minStr, *maxStr;
int idx = 0;
while (idx < NUM_SENSORS && parse(false, minStr, maxStr) == 2) {
int minCm = atoi(minStr);
int maxCm = atoi(maxStr);
unsigned int dist = hc.dist(idx);
if (dist >= minCm && dist <= maxCm) {
sensorStatus.triggeredSensors |= (1U << idx);
}
++idx;
}
}
char commandBuffer[CMD_BUF_SIZE]
Raw command content without '<' or '>'.
Definition: SerialIO.h:101
void parse_reset()
Reset the internal parse state so the next parse(...) call starts from the beginning of commandBuffer...
Definition: SerialIO.h:357
void processCommand()
Execute the previously parsed command.
Definition: Audio_Card.ino:190
static HCSR04 hc(UOD_TRIGGER_PIN, ECHO_PINS_SET, NUM_UOD_SENSORS_PER_CARD)
HC-SR04 driver instance.
uint16_t triggeredSensors
Bitmask: 1 if sensor in range.
Definition: UOD_Card.ino:115

Definition at line 470 of file SerialIO.h.

Here is the caller graph for this function:

◆ print()

void SerialIO::print ( const char *  msg)
inline

Print a string to all active consoles.

Parameters
msgNUL-terminated C string to send (no newline appended).
Postcondition
Written to UART, and to BT/WebSerial if enabled.

Definition at line 595 of file SerialIO.h.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ printf()

template<typename... Args>
void SerialIO::printf ( const char *  fmt,
Args...  args 
)
inline

printf-style logging to all active consoles (no newline).

Parameters
fmtprintf-style format string.
argsArguments for fmt.
Note
Uses a fixed 128-byte stack buffer; output is truncated to fit.
See also
println(), printf()

Definition at line 668 of file SerialIO.h.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ println()

void SerialIO::println ( const char *  msg)
inline

Print a line (with \n) to all active consoles.

Parameters
msgNUL-terminated C string; a single '\n' is appended.

Definition at line 640 of file SerialIO.h.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ read()

bool SerialIO::read ( )
inline

Read one complete packet from any interface.

Consumes characters until a closing '>' is seen (or a whole buffered packet is available from WebSerial/I²C). The payload between '<' and '>' is copied into commandBuffer as a C string. A single "?" packet triggers helpHandler_ (if installed) and is not returned to the caller.

Returns
true if a packet (other than "?") was read into commandBuffer.

Definition at line 300 of file SerialIO.h.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ sprintf()

void SerialIO::sprintf ( const char *  fmt,
  ... 
)
inline

printf-style logging to all active consoles (no newline).

Parameters
fmtNUL-terminated C string.

Definition at line 617 of file SerialIO.h.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ sprintlnf()

void SerialIO::sprintlnf ( const char *  fmt,
  ... 
)
inline

printf-style logging with newline (like println()).

Parameters
fmtNUL-terminated C string.

Definition at line 628 of file SerialIO.h.

Here is the call graph for this function:
Here is the caller graph for this function:

The documentation for this class was generated from the following file: