diff --git a/palm-client/src/session.c b/palm-client/src/session.c index a29ba5e..c73ae2e 100644 --- a/palm-client/src/session.c +++ b/palm-client/src/session.c @@ -58,13 +58,40 @@ static Err WaitFor(UInt8 code, Int32 timeout) return WaitForEither(code, code, timeout); } -/* Sends a request frame and waits for the reply code, retrying sends the host isn't reading yet. */ +/* + * Discards anything already received before a new request, so a late reply to + * an earlier request can't be taken as this one's. Pushes in it are still noted. + */ +static void DrainInput(void) +{ + Err err; + + for (;;) { + while (gRxPos < gRxLen) { + if (VmDecoderFeed(&gDecoder, gRx[gRxPos++]) && gDecoder.len && + gDecoder.payload[0] == VM_PUSH_MSG_WAITING) + gMsgWaiting = true; + } + gRxPos = 0; + gRxLen = TransportRecv(gRx, sizeof(gRx), 0, &err); + if (gRxLen == 0) + break; + } + VmDecoderReset(&gDecoder); +} + +/* + * Sends a request frame and waits for the reply code. A try is repeated if + * the frame couldn't be sent or no reply came, so only use tries > 1 for + * commands that are safe to repeat. + */ static Err Request(const UInt8 *frame, UInt16 len, UInt8 code, UInt16 tries) { Err err = vmErrNoReply; UInt16 t; for (t = 0; t < tries; t++) { + DrainInput(); err = TransportSend(frame, len); if (err == serErrTimeOut) continue; diff --git a/palm-client/src/transport_srm.c b/palm-client/src/transport_srm.c index aa40f97..a855b16 100644 --- a/palm-client/src/transport_srm.c +++ b/palm-client/src/transport_srm.c @@ -1,7 +1,8 @@ #include #include "transport.h" -#define VM_BAUD 115200 +#define VM_BAUD 115200 +#define VM_SEND_TRIES 5 /* SrmSend attempts for one buffer (USB re-attach) */ static UInt16 gPortId; static Boolean gPortOpen = false; @@ -40,12 +41,26 @@ void TransportClose(void) Err TransportSend(const UInt8 *buf, UInt16 len) { Err err = errNone; + UInt32 sent = 0; + UInt16 tries; if (!gPortOpen) return serErrNotOpen; - /* No SrmSendWait: over USB it can block indefinitely if no host is reading. */ - SrmSend(gPortId, (void *)buf, len, &err); - return err; + /* + * Over USB, SrmSend can time out while the host re-attaches and still + * deliver the bytes it accepted, so only ever resend the remainder; + * resending the whole frame duplicated commands. No SrmSendWait: it can + * block indefinitely if no host is reading. + */ + for (tries = 0; tries < VM_SEND_TRIES; tries++) { + sent += SrmSend(gPortId, (void *)(buf + sent), len - sent, &err); + if (sent >= len) + return errNone; + if (err != serErrTimeOut) + return err; + SrmClearErr(gPortId); + } + return serErrTimeOut; } UInt16 TransportRecv(UInt8 *buf, UInt16 max, Int32 timeoutTicks, Err *errP)