Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat:Add debug log output to caller interface #746

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions src/modbus.c
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@
#include "modbus-private.h"
#include "modbus.h"

static debuglog g_debuglog = NULL;

/* Internal use */
#define MSG_LENGTH_UNDEFINED -1

Expand Down Expand Up @@ -169,6 +171,15 @@ static int send_msg(modbus_t *ctx, uint8_t *msg, int msg_length)

msg_length = ctx->backend->send_msg_pre(msg, msg_length);

if (g_debuglog) {
char buf[2048];
memset(buf, 0, sizeof(buf));
snprintf(buf, sizeof(buf) - 1, "send:");
for (int i = 0; i < msg_length; i++) {
snprintf(buf + 5 + i * 3, sizeof(buf) - 1, "%.2X ", msg[i]);
}
g_debuglog(buf);
}
if (ctx->debug) {
for (i = 0; i < msg_length; i++)
printf("[%.2X]", msg[i]);
Expand Down Expand Up @@ -517,6 +528,15 @@ int _modbus_receive_msg(modbus_t *ctx, uint8_t *msg, msg_type_t msg_type)

if (ctx->debug)
printf("\n");
if (g_debuglog) {
char buf[2048];
memset(buf, 0, sizeof(buf));
snprintf(buf, sizeof(buf) - 1, "recv:");
for (int i = 0; i < msg_length; i++) {
snprintf(buf + 5 + i * 3, sizeof(buf) - 1, "%.2X ", msg[i]);
}
g_debuglog(buf);
}

return ctx->backend->check_integrity(ctx, msg, msg_length);
}
Expand Down Expand Up @@ -2067,4 +2087,7 @@ size_t strlcpy(char *dest, const char *src, size_t dest_size)

return (s - src - 1); /* count does not include NUL */
}
void register_debuglog(debuglog pf) {
g_debuglog = pf;
}
#endif
9 changes: 9 additions & 0 deletions src/modbus.h
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,12 @@

#include "modbus-version.h"

#ifdef _WIN32
#include <winsock2.h>
#include <windows.h>
#pragma comment ( lib, "ws2_32.lib" )
#endif

#if defined(_MSC_VER)
# if defined(DLLBUILD)
/* define DLLBUILD when building the DLL */
Expand Down Expand Up @@ -324,6 +330,9 @@ MODBUS_API void modbus_set_float_cdab(float f, uint16_t *dest);
#include "modbus-rtu.h"
#include "modbus-tcp.h"

typedef void(*debuglog)(const char*);
void MODBUS_API register_debuglog(debuglog pf);

MODBUS_END_DECLS

#endif /* MODBUS_H */