From: Martin Ling Date: Fri, 22 Nov 2013 22:41:03 +0000 (+0000) Subject: Add API for and default handler for debug messages. X-Git-Tag: libserialport-0.1.0~67 X-Git-Url: https://sigrok.org/gitweb/?p=libserialport.git;a=commitdiff_plain;h=863b35e69cbad5dce9f9f0547968730de8789256 Add API for and default handler for debug messages. --- diff --git a/libserialport.h.in b/libserialport.h.in index 0e3dc1b..3de68a9 100644 --- a/libserialport.h.in +++ b/libserialport.h.in @@ -615,6 +615,29 @@ char *sp_last_error_message(void); */ void sp_free_error_message(char *message); +/** + * Set the handler function for library debugging messages. + * + * Debugging messages are generated by the library during each operation, + * to help in diagnosing problems. The handler will be called for each + * message. The handler can be set to NULL to ignore all debug messages. + * + * The handler function should accept a format string and variable length + * argument list, in the same manner as e.g. printf(). + * + * The default handler is sp_default_debug_handler(). + */ +void sp_set_debug_handler(void (*handler)(const char *format, ...)); + +/** + * Default handler function for library debugging messages. + * + * This function prints debug messages to the standard error stream if the + * environment variable LIBSERIALPORT_DEBUG is set. Otherwise, they are + * ignored. + */ +void sp_default_debug_handler(const char *format, ...); + /** @} */ #ifdef __cplusplus diff --git a/serialport.c b/serialport.c index fb2e973..2bb53b4 100644 --- a/serialport.c +++ b/serialport.c @@ -27,6 +27,8 @@ #include #include #include +#include +#include #ifdef _WIN32 #include #include @@ -101,6 +103,8 @@ const struct std_baudrate std_baudrates[] = { #endif }; +void (*sp_debug_handler)(const char *format, ...) = sp_default_debug_handler; + #define ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0])) #define NUM_STD_BAUDRATES ARRAY_SIZE(std_baudrates) @@ -1424,3 +1428,19 @@ void sp_free_error_message(char *message) (void)message; #endif } + +void sp_set_debug_handler(void (*handler)(const char *format, ...)) +{ + sp_debug_handler = handler; +} + +void sp_default_debug_handler(const char *format, ...) +{ + va_list args; + va_start(args, format); + if (getenv("LIBSERIALPORT_DEBUG")) { + fputs("libserialport: ", stderr); + vfprintf(stderr, format, args); + } + va_end(args); +}