From 3e567e94898df2ace9264630900697bc30c5d69c Mon Sep 17 00:00:00 2001 From: "Earle F. Philhower, III" Date: Wed, 5 Aug 2020 17:13:37 -0700 Subject: [PATCH] Add SerialEvent() callback to loop processing (#7505) * Add SerialEvent() callback to loop processing Match the AVR SerialEvent implicit callback. Callback is executed in normal user mode, not IRQ, so standard processing can be uses. Fixes #752 after 5 years. :) * Fix style --- cores/esp8266/HardwareSerial.cpp | 16 ++++++++++++++++ cores/esp8266/HardwareSerial.h | 2 ++ cores/esp8266/core_esp8266_main.cpp | 3 +++ 3 files changed, 21 insertions(+) diff --git a/cores/esp8266/HardwareSerial.cpp b/cores/esp8266/HardwareSerial.cpp index 5f7ea141c..26383dd43 100644 --- a/cores/esp8266/HardwareSerial.cpp +++ b/cores/esp8266/HardwareSerial.cpp @@ -32,6 +32,14 @@ #include "HardwareSerial.h" #include "Esp.h" + +// SerialEvent functions are weak, so when the user doesn't define them, +// the linker just sets their address to 0 (which is checked below). +// The Serialx_available is just a wrapper around Serialx.available(), +// but we can refer to it weakly so we don't pull in the entire +// HardwareSerial instance if the user doesn't also refer to it. +void serialEvent() __attribute__((weak)); + HardwareSerial::HardwareSerial(int uart_nr) : _uart_nr(uart_nr), _rx_size(256) {} @@ -162,6 +170,14 @@ size_t HardwareSerial::readBytes(char* buffer, size_t size) #if !defined(NO_GLOBAL_INSTANCES) && !defined(NO_GLOBAL_SERIAL) HardwareSerial Serial(UART0); + +// Executed at end of loop() processing when > 0 bytes available in the Serial port +void serialEventRun(void) +{ + if (serialEvent && Serial.available()) { + serialEvent(); + } +} #endif #if !defined(NO_GLOBAL_INSTANCES) && !defined(NO_GLOBAL_SERIAL1) HardwareSerial Serial1(UART1); diff --git a/cores/esp8266/HardwareSerial.h b/cores/esp8266/HardwareSerial.h index dd12e96d2..6b89f6800 100644 --- a/cores/esp8266/HardwareSerial.h +++ b/cores/esp8266/HardwareSerial.h @@ -207,4 +207,6 @@ protected: extern HardwareSerial Serial; extern HardwareSerial Serial1; +extern void serialEventRun(void) __attribute__((weak)); + #endif diff --git a/cores/esp8266/core_esp8266_main.cpp b/cores/esp8266/core_esp8266_main.cpp index 337686199..21724e2eb 100644 --- a/cores/esp8266/core_esp8266_main.cpp +++ b/cores/esp8266/core_esp8266_main.cpp @@ -195,6 +195,9 @@ static void loop_wrapper() { } loop(); loop_end(); + if (serialEventRun) { + serialEventRun(); + } esp_schedule(); }