/*
 * scan.c - Phase 1: WL2:D scanner, asynchronous read (reverse-engineered).
 *
 * Confirmed: opening WL2:D and issuing control ops 6/7 triggers a scan (laser
 * fires, green LED). Neither synchronous read form returned data, and SCANAPP
 * in the ROM uses an async pattern (post read -> P_FREAD -> P_FCANCEL). So this
 * posts an asynchronous read (p_ioc), triggers the scan (ops 6/7), then waits
 * for completion (p_iowait). Decoded output is CR/LF-terminated.
 */
#include <plib.h>

#define WL2_TRIG1 6
#define WL2_TRIG2 7

GLDEF_C INT main(VOID)
{
    VOID *chan;
    UBYTE buf[256];
    WORD  stat;
    UWORD len;
    INT   err, 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. Async reads:\n\n");

    for (;;) {
        len  = sizeof(buf);
        stat = E_FILE_PENDING;
        p_ioc(chan, P_FREAD, &stat, buf, &len);   /* post async read */

        p_iow(chan, WL2_TRIG1);                    /* trigger the scan */
        p_iow(chan, WL2_TRIG2);

        p_iowait();                                /* wait for a completion */

        if (stat == E_FILE_PENDING) {              /* our read didn't finish */
            p_iow(chan, P_FCANCEL);
            p_waitstat(&stat);
            continue;
        }
        if (stat < 0) {
            p_printf("stat %d\n", stat);
            continue;
        }
        p_printf("len=%d:", len);
        for (i = 0; i < 40 && i < 256; i++)
            p_printf(" %d", buf[i]);
        p_printf("  \"");
        for (i = 0; i < 40 && i < 256; i++)
            p_putch(buf[i] >= ' ' ? buf[i] : '.');
        p_printf("\"\n");
    }
}
