/*
 * scan.c - Phase 1: WL2:D scanner, trigger + read loop (reverse-engineered).
 *
 * Confirmed from the previous build: opening WL2:D then issuing control ops 6
 * and 7 triggers a scan (laser fires, green good-read LED). What was missing was
 * the read: a bare p_iow(chan, P_FREAD, buf) passes no length. This uses p_read
 * (which passes &len) to collect the decoded result, and re-triggers (ops 6/7)
 * each iteration so successive scans work without relying on the scan key.
 * Decoded output is CR/LF-terminated (default Symbol2 postamble).
 */
#include <plib.h>

#define WL2_TRIG1 6
#define WL2_TRIG2 7

GLDEF_C INT main(VOID)
{
    VOID *chan;
    UBYTE buf[256];
    INT   err, n, i;

    err = p_open(&chan, "WL2:D", (UINT)-1);
    p_printf("open WL2:D: %d\n", err);
    if (err < 0) {
        p_printf("Press a key to exit.\n");
        p_getch();
        return 1;
    }

    p_printf("Present a barcode under the laser. Reads:\n\n");

    for (;;) {
        p_iow(chan, WL2_TRIG1);            /* trigger a scan */
        p_iow(chan, WL2_TRIG2);
        n = p_read(chan, buf, sizeof(buf));   /* collect decoded result (with len) */
        if (n < 0) {
            p_printf("read %d\n", n);
            continue;
        }
        if (n == 0)
            continue;
        p_printf("n=%d:", n);
        for (i = 0; i < n && i < 40; i++)
            p_printf(" %d", buf[i]);
        p_printf("  \"");
        for (i = 0; i < n && i < 40; i++)
            p_putch(buf[i] >= ' ' ? buf[i] : '.');
        p_printf("\"\n");
    }
}
