From 514d3e3b064def29f25a2a5f7c5447efcab3ccf8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Asbj=C3=B8rn=20Sloth=20T=C3=B8nnesen?= Date: Sun, 9 Jul 2023 00:18:48 +0000 Subject: ql: optimize USB data flow Write column data into a buffer, and only write to USB once the buffer is filled past threshould. This reduces the amount of data frames on the USB bus, in a 429x336 sample image it was reduced from 1000 frames to about 100 frames, where the image data is only 20 frames, while the rest is mainly polling for status reponses. --- src/ql.c | 32 +++++++++++++++++++++++++++++--- 1 file changed, 29 insertions(+), 3 deletions(-) (limited to 'src/ql.c') diff --git a/src/ql.c b/src/ql.c index 1023dbe..31bd24b 100644 --- a/src/ql.c +++ b/src/ql.c @@ -13,21 +13,29 @@ #include #include +#define QL_XMIT_SIZE 4096 +#define QL_BUF_SIZE (QL_XMIT_SIZE * 2) + struct ql_ctx { char *printer; int fd; + ssize_t pos; + char buf[QL_BUF_SIZE]; }; #define ESC 0x1b #define STATUS_READ_TIMEOUT 5 /* seconds */ -#define full_write(ctx, buf) (retry_write(ctx, buf, sizeof(buf)) == (ssize_t)sizeof(buf)) +#define partial_write(ctx, buf) (do_write(ctx, buf, sizeof(buf), 0) == (ssize_t)sizeof(buf)) +#define full_write(ctx, buf) (do_write(ctx, buf, sizeof(buf), 1) == (ssize_t)sizeof(buf)) -ssize_t retry_write(ql_ctx_t ctx, const char *buf, size_t len) +ssize_t retry_write(ql_ctx_t ctx) { int fd = ctx->fd; size_t written = 0; + size_t len = ctx->pos; + char *buf = (char *)&ctx->buf; int retval; fd_set wfds; @@ -54,9 +62,27 @@ ssize_t retry_write(ql_ctx_t ctx, const char *buf, size_t len) written += n; } } + if (written == len) { + ctx->pos = 0; + } return written; } +static ssize_t do_write(ql_ctx_t ctx, const char *buf, ssize_t len, int flush_buffer) +{ + if (ctx->pos + len >= QL_BUF_SIZE) + return 0; + + memcpy(ctx->buf + ctx->pos, buf, len); + ctx->pos += len; + + ssize_t pos = ctx->pos; + if (flush_buffer || pos > QL_XMIT_SIZE) { + return retry_write(ctx) == pos ? len : 0; + } + return len; +} + static void get_mono_time(struct timespec *tp) { if (clock_gettime(CLOCK_MONOTONIC, tp) == -1) { @@ -240,7 +266,7 @@ bool ql_print_raster_image(ql_ctx_t ctx, const ql_status_t * status, block[1] = 0; block[2] = dn; pack_column((uint8_t *) block + 3, dn, w, img, cfg->threshold); - if (!full_write(ctx, block)) + if (!partial_write(ctx, block)) return false; } -- cgit v1.2.1