fixed dispenser delivery confirmation

This commit is contained in:
2026-07-24 15:51:04 +01:00
parent fbf652720c
commit 5e99a8e0d4
8 changed files with 997 additions and 129 deletions
+53 -4
View File
@@ -1,6 +1,7 @@
package dispenser
import (
"errors"
"fmt"
"strings"
"time"
@@ -22,9 +23,13 @@ const (
// cache freshness for "continuous status" reads (tune as you wish)
defaultStatusTTL = 1500 * time.Millisecond
CardWellEmptyMessage = "Card well is empty"
)
var (
ErrCardWellEmpty = errors.New(CardWellEmptyMessage)
SerialPort string
Address []byte
@@ -67,10 +72,9 @@ var (
// Status helpers
// --------------------
func logStatus(statusBytes []byte) {
func statusDescription(statusBytes []byte) string {
if len(statusBytes) < 4 {
log.Infof("Dispenser status: <invalid len=%d>", len(statusBytes))
return
return fmt.Sprintf("<invalid len=%d>", len(statusBytes))
}
posStatus := []struct {
@@ -94,13 +98,58 @@ func logStatus(statusBytes []byte) {
result.WriteString(statusMsg + "; ")
}
}
log.Infof("Dispenser status: %s", result.String())
return result.String()
}
func logStatus(statusBytes []byte) {
log.Infof("Dispenser status: %s", statusDescription(statusBytes))
}
func isAtEncoderPosition(statusBytes []byte) bool {
return len(statusBytes) >= 4 && statusBytes[3] == 0x33
}
func validateDispenserStatusData(statusBytes []byte) error {
if len(statusBytes) != 4 {
return fmt.Errorf("malformed dispenser status: got %d bytes, want 4", len(statusBytes))
}
statusMaps := []map[byte]string{statusPos0, statusPos1, statusPos2, statusPos3}
for position, mapper := range statusMaps {
if _, ok := mapper[statusBytes[position]]; !ok {
return fmt.Errorf("unknown dispenser status 0x%X at position %d", statusBytes[position], position+1)
}
}
return nil
}
func dispenserStatusError(statusBytes []byte) error {
switch statusBytes[0] {
case 0x34, 0x32, 0x36:
return fmt.Errorf("dispenser error: %s", statusPos0[statusBytes[0]])
}
switch statusBytes[1] {
case 0x32, 0x31:
return fmt.Errorf("dispenser error: %s", statusPos1[statusBytes[1]])
}
switch statusBytes[2] {
case 0x34, 0x32:
return fmt.Errorf("dispenser error: %s", statusPos2[statusBytes[2]])
}
return nil
}
func isPreparationMoving(statusBytes []byte) bool {
return len(statusBytes) == 4 &&
(statusBytes[0] == 0x31 || statusBytes[1] == 0x38)
}
func hasPreparationDiagnostics(statusBytes []byte) bool {
return len(statusBytes) == 4 &&
(statusBytes[0] != 0x30 || statusBytes[1] != 0x30 || statusBytes[2] != 0x30)
}
func stockTake(statusBytes []byte) string {
if len(statusBytes) < 4 {
return ""
+163 -95
View File
@@ -30,12 +30,25 @@ type cmdResp struct {
err error
}
type sequenceTiming struct {
now func() time.Time
wait func(context.Context, time.Duration) error
}
const (
sequencePollInterval = time.Second
sequenceRetryAfter = 6 * time.Second
sequenceTimeout = 12 * time.Second
)
type Client struct {
port *serial.Port
reqCh chan cmdReq
done chan struct{}
sequenceTiming sequenceTiming
// status cache
mu sync.RWMutex
lastStatus []byte
@@ -54,15 +67,31 @@ func NewClient(port *serial.Port, queueSize int) *Client {
queueSize = 16
}
c := &Client{
port: port,
reqCh: make(chan cmdReq, queueSize),
done: make(chan struct{}),
port: port,
reqCh: make(chan cmdReq, queueSize),
done: make(chan struct{}),
sequenceTiming: sequenceTiming{
now: time.Now,
wait: waitForSequence,
},
statusTTL: defaultStatusTTL,
}
go c.loop()
return c
}
func waitForSequence(ctx context.Context, duration time.Duration) error {
timer := time.NewTimer(duration)
defer timer.Stop()
select {
case <-timer.C:
return nil
case <-ctx.Done():
return ctx.Err()
}
}
func (c *Client) Close() {
select {
case <-c.done:
@@ -268,113 +297,152 @@ func (c *Client) DispenserPrepare(ctx context.Context) (string, error) {
return stockStatus, nil
}
func (c *Client) DispenserStart(ctx context.Context) (string, error) {
const funcName = "DispenserStart"
stockStatus := ""
status, err := c.CheckStatus(ctx)
func (c *Client) readSequenceStatus(ctx context.Context, operation string) ([]byte, string, error) {
status, err := c.do(ctx, cmdStatus)
if err != nil {
return stockStatus, fmt.Errorf("[%s] check status: %w", funcName, err)
if ctxErr := ctx.Err(); ctxErr != nil {
return nil, "", fmt.Errorf("[%s] read status: %w", operation, ctxErr)
}
return nil, "", fmt.Errorf("[%s] read status: %w", operation, err)
}
defer func() {
stockStatus := ""
if len(status) == 4 {
stockStatus = stockTake(status)
c.setStock(status)
logStatus(status)
}()
stockStatus = stockTake(status)
c.setStock(status)
}
return status, stockStatus, nil
}
if isCardWellEmpty(status) {
return stockStatus, fmt.Errorf(stockStatus)
func preparationStatus(operation string, status []byte) (bool, error) {
if len(status) != 4 {
return false, fmt.Errorf("[%s] %w", operation, validateDispenserStatusData(status))
}
if isAtEncoderPosition(status) {
if hasPreparationDiagnostics(status) {
log.Warnf(
"[%s] card confirmed at encoder with dispenser diagnostics: %s raw status: % X",
operation,
statusDescription(status),
status,
)
}
return true, nil
}
if err := validateDispenserStatusData(status); err != nil {
return false, fmt.Errorf("[%s] %w", operation, err)
}
if isCardWellEmpty(status) {
return false, fmt.Errorf("[%s] %w", operation, ErrCardWellEmpty)
}
if isPreparationMoving(status) {
return false, nil
}
if err := dispenserStatusError(status); err != nil {
return false, fmt.Errorf("[%s] %w", operation, err)
}
return false, nil
}
func (c *Client) pollForEncoderPosition(
ctx context.Context,
operation string,
retryCommand func(context.Context) error,
) (string, error) {
started := c.sequenceTiming.now()
halfway := started.Add(sequenceRetryAfter)
deadline := started.Add(sequenceTimeout)
retried := false
stockStatus := ""
for {
if err := ctx.Err(); err != nil {
return stockStatus, fmt.Errorf("[%s] %w", operation, err)
}
now := c.sequenceTiming.now()
if !now.Before(deadline) {
return stockStatus, fmt.Errorf("[%s] timed out after %s", operation, sequenceTimeout)
}
status, currentStockStatus, err := c.readSequenceStatus(ctx, operation)
stockStatus = currentStockStatus
if err != nil {
return stockStatus, err
}
ready, err := preparationStatus(operation, status)
if err != nil {
return stockStatus, err
}
if ready {
return stockStatus, nil
}
now = c.sequenceTiming.now()
if !now.Before(deadline) {
return stockStatus, fmt.Errorf("[%s] timed out after %s", operation, sequenceTimeout)
}
if retryCommand != nil && !retried && !now.Before(halfway) {
if err := retryCommand(ctx); err != nil {
return stockStatus, fmt.Errorf("[%s] retry command: %w", operation, err)
}
retried = true
}
wait := sequencePollInterval
if remaining := deadline.Sub(now); remaining < wait {
wait = remaining
}
if err := c.sequenceTiming.wait(ctx, wait); err != nil {
return stockStatus, fmt.Errorf("[%s] %w", operation, err)
}
}
}
func (c *Client) prepareCardAtEncoder(ctx context.Context, operation string) (string, error) {
status, stockStatus, err := c.readSequenceStatus(ctx, operation)
if err != nil {
return stockStatus, err
}
ready, err := preparationStatus(operation, status)
if err != nil {
return stockStatus, err
}
if ready {
return stockStatus, nil
}
if err := c.ToEncoder(ctx); err != nil {
return stockStatus, fmt.Errorf("[%s] to encoder: %w", funcName, err)
}
halfway := time.Now().Add(6 * time.Second)
deadline := time.Now().Add(12 * time.Second)
for {
time.Sleep(delay * 2)
switch {
case time.Now().After(halfway):
if err := c.ToEncoder(ctx); err != nil {
return stockStatus, fmt.Errorf("[%s] to encoder: %w", funcName, err)
}
case time.Now().After(deadline):
return stockStatus, nil
}
status, _ = c.do(ctx, cmdStatus)
stockStatus = stockTake(status)
c.setStock(status)
logStatus(status)
// error states first
if isCardWellEmpty(status) {
return stockStatus, fmt.Errorf(stockStatus)
}
if isAtEncoderPosition(status) {
return stockStatus, nil
}
return stockStatus, fmt.Errorf("[%s] to encoder: %w", operation, err)
}
return c.pollForEncoderPosition(ctx, operation, c.ToEncoder)
}
func (c *Client) DispenserFinal(ctx context.Context) (string, error) {
const funcName = "DispenserFinal"
stockStatus := ""
var status []byte
// PrepareCurrentCard authoritatively places the card to be encoded at the encoder.
func (c *Client) PrepareCurrentCard(ctx context.Context) (string, error) {
return c.prepareCardAtEncoder(ctx, "PrepareCurrentCard")
}
// DeliverCurrentCard presents the encoded card and confirms command acceptance.
func (c *Client) DeliverCurrentCard(ctx context.Context) (string, error) {
const operation = "DeliverCurrentCard"
if err := c.OutOfMouth(ctx); err != nil {
return stockStatus, fmt.Errorf("[%s] out of mouth: %w", funcName, err)
}
time.Sleep(delay)
status, err := c.do(ctx, cmdStatus)
if err == nil && len(status) >= 4 {
c.setStock(status)
}
time.Sleep(delay)
if err := c.ToEncoder(ctx); err != nil {
return stockStatus, fmt.Errorf("[%s] to encoder: %w", funcName, err)
}
defer func() {
logStatus(status)
}()
halfway := time.Now().Add(6 * time.Second)
deadline := time.Now().Add(12 * time.Second)
for {
time.Sleep(delay * 2)
switch {
case time.Now().After(halfway):
if err := c.ToEncoder(ctx); err != nil {
return stockStatus, fmt.Errorf("[%s] to encoder: %w", funcName, err)
}
case time.Now().After(deadline):
return stockStatus, nil
}
status, _ = c.do(ctx, cmdStatus)
stockStatus = stockTake(status)
c.setStock(status)
logStatus(status)
if isCardWellEmpty(status) {
return stockStatus, nil
}
if isAtEncoderPosition(status) {
return stockStatus, nil
}
return "", fmt.Errorf("[%s] out of mouth: %w", operation, err)
}
return "", nil
}
// BeginPrepareNextCard starts moving the next card to the encoder without waiting for readiness.
func (c *Client) BeginPrepareNextCard(ctx context.Context) error {
if err := c.ToEncoder(ctx); err != nil {
return fmt.Errorf("[BeginPrepareNextCard] to encoder: %w", err)
}
return nil
}
// PrepareNextCard places a new card at the encoder for a later issuance attempt.
func (c *Client) PrepareNextCard(ctx context.Context) (string, error) {
return c.prepareCardAtEncoder(ctx, "PrepareNextCard")
}
+404
View File
@@ -0,0 +1,404 @@
package dispenser
import (
"bytes"
"context"
"errors"
"strings"
"testing"
"time"
log "github.com/sirupsen/logrus"
)
type fakeSequenceDevice struct {
statusResponses []cmdResp
commandErrors map[cmdType][]error
commands []cmdType
}
func newSequenceTestClient(t *testing.T, statusResponses ...cmdResp) (*Client, *fakeSequenceDevice) {
t.Helper()
device := &fakeSequenceDevice{
statusResponses: append([]cmdResp(nil), statusResponses...),
commandErrors: make(map[cmdType][]error),
}
now := time.Date(2026, time.July, 23, 12, 0, 0, 0, time.UTC)
client := &Client{
reqCh: make(chan cmdReq),
done: make(chan struct{}),
sequenceTiming: sequenceTiming{
now: func() time.Time {
return now
},
wait: func(ctx context.Context, duration time.Duration) error {
select {
case <-ctx.Done():
return ctx.Err()
default:
now = now.Add(duration)
return nil
}
},
},
}
go func() {
for {
select {
case <-client.done:
return
case request := <-client.reqCh:
device.commands = append(device.commands, request.typ)
if request.typ == cmdStatus {
if len(device.statusResponses) == 0 {
request.respCh <- cmdResp{err: errors.New("unexpected status read")}
continue
}
response := device.statusResponses[0]
device.statusResponses = device.statusResponses[1:]
request.respCh <- response
continue
}
var err error
if queued := device.commandErrors[request.typ]; len(queued) > 0 {
err = queued[0]
device.commandErrors[request.typ] = queued[1:]
}
request.respCh <- cmdResp{err: err}
}
}
}()
t.Cleanup(client.Close)
return client, device
}
func status(position byte) []byte {
return []byte{0x30, 0x30, 0x30, position}
}
func commandCount(commands []cmdType, target cmdType) int {
count := 0
for _, command := range commands {
if command == target {
count++
}
}
return count
}
func TestPrepareCurrentCardAcceptsEncoderPositionWithStaleDiagnostics(t *testing.T) {
tests := []struct {
name string
status []byte
wantStock string
}{
{
name: "dispense error and jam",
status: []byte{0x30, 0x32, 0x32, 0x33},
wantStock: "Card jammed",
},
{
name: "supply diagnostics",
status: []byte{0x32, 0x30, 0x31, 0x33},
wantStock: "Card pre-empty",
},
{
name: "combined stale jam and supply diagnostics",
status: []byte{0x30, 0x32, 0x33, 0x33},
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
var logOutput bytes.Buffer
standardLogger := log.StandardLogger()
previousOutput := standardLogger.Out
standardLogger.SetOutput(&logOutput)
t.Cleanup(func() {
standardLogger.SetOutput(previousOutput)
})
client, device := newSequenceTestClient(t, cmdResp{status: test.status})
stock, err := client.PrepareCurrentCard(context.Background())
if err != nil {
t.Fatal(err)
}
if stock != test.wantStock {
t.Fatalf("stock status = %q, want %q", stock, test.wantStock)
}
if got := commandCount(device.commands, cmdToEncoder); got != 0 {
t.Fatalf("to-encoder commands = %d, want 0", got)
}
if got := commandCount(device.commands, cmdStatus); got != 1 {
t.Fatalf("status reads = %d, want 1", got)
}
logged := logOutput.String()
if !strings.Contains(logged, "card confirmed at encoder") ||
!strings.Contains(logged, statusDescription(test.status)) ||
!strings.Contains(logged, "raw status") {
t.Fatalf("encoder diagnostic log = %q", logged)
}
})
}
}
func TestPrepareCurrentCardPollingAllowsTransientMovementWithStaleErrors(t *testing.T) {
client, device := newSequenceTestClient(t,
cmdResp{status: status(0x34)},
cmdResp{status: []byte{0x31, 0x38, 0x32, 0x30}},
cmdResp{status: []byte{0x30, 0x32, 0x32, 0x33}},
)
stock, err := client.PrepareCurrentCard(context.Background())
if err != nil {
t.Fatal(err)
}
if stock != "Card jammed" {
t.Fatalf("stock status = %q, want Card jammed", stock)
}
if got := commandCount(device.commands, cmdToEncoder); got != 1 {
t.Fatalf("to-encoder commands = %d, want 1", got)
}
if got := commandCount(device.commands, cmdStatus); got != 3 {
t.Fatalf("status reads = %d, want 3", got)
}
}
func TestPrepareCurrentCardRejectsFailureWithoutEncoderOrMovement(t *testing.T) {
tests := []struct {
name string
response cmdResp
wantError string
wantStock string
}{
{
name: "status read error",
response: cmdResp{err: errors.New("serial read failed")},
wantError: "serial read failed",
},
{
name: "malformed status",
response: cmdResp{status: []byte{0x30, 0x30, 0x31}},
wantError: "malformed dispenser status",
},
{
name: "unknown status",
response: cmdResp{status: []byte{0x30, 0x30, 0x30, 0x39}},
wantError: "unknown dispenser status",
},
{
name: "jammed preparation",
response: cmdResp{status: []byte{0x30, 0x30, 0x32, 0x34}},
wantError: "Card jammed",
wantStock: "Card jammed",
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
client, _ := newSequenceTestClient(t, test.response)
stock, err := client.PrepareCurrentCard(context.Background())
if err == nil || !strings.Contains(err.Error(), test.wantError) {
t.Fatalf("error = %v, want containing %q", err, test.wantError)
}
if stock != test.wantStock {
t.Fatalf("stock status = %q, want %q", stock, test.wantStock)
}
})
}
}
func TestPrepareCurrentCardReturnsAuthoritativeEmptyWellError(t *testing.T) {
client, device := newSequenceTestClient(t, cmdResp{status: status(0x38)})
stock, err := client.PrepareCurrentCard(context.Background())
if !errors.Is(err, ErrCardWellEmpty) {
t.Fatalf("error = %v, want ErrCardWellEmpty", err)
}
if stock != "Card empty" {
t.Fatalf("stock status = %q, want Card empty", stock)
}
if got := commandCount(device.commands, cmdToEncoder); got != 0 {
t.Fatalf("to-encoder commands = %d, want 0", got)
}
}
func TestDeliverCurrentCardSucceedsAfterCommandAcceptanceWithoutStatusPolling(t *testing.T) {
staleStatus := []byte{0x30, 0x32, 0x32, 0x33}
client, device := newSequenceTestClient(t, cmdResp{status: staleStatus})
stock, err := client.DeliverCurrentCard(context.Background())
if err != nil {
t.Fatal(err)
}
if stock != "" {
t.Fatalf("stock status = %q, want empty", stock)
}
if got := commandCount(device.commands, cmdOutOfMouth); got != 1 {
t.Fatalf("out-of-mouth commands = %d, want 1", got)
}
if got := commandCount(device.commands, cmdStatus); got != 0 {
t.Fatalf("status reads = %d, want 0", got)
}
if len(device.statusResponses) != 1 {
t.Fatalf("queued status responses = %d, want stale status unread", len(device.statusResponses))
}
}
func TestDeliverCurrentCardRejectsCommandFailures(t *testing.T) {
tests := []struct {
name string
err error
}{
{name: "serial dispatch failure", err: errors.New("serial write failed")},
{name: "invalid acknowledgement", err: errors.New("unexpected response status")},
{name: "missing acknowledgement", err: errors.New("no response from dispenser")},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
client, device := newSequenceTestClient(t)
device.commandErrors[cmdOutOfMouth] = []error{test.err}
_, err := client.DeliverCurrentCard(context.Background())
if err == nil || !strings.Contains(err.Error(), test.err.Error()) {
t.Fatalf("error = %v, want containing %q", err, test.err)
}
if got := commandCount(device.commands, cmdOutOfMouth); got != 1 {
t.Fatalf("out-of-mouth commands = %d, want 1", got)
}
if got := commandCount(device.commands, cmdStatus); got != 0 {
t.Fatalf("status reads = %d, want 0", got)
}
})
}
}
func TestDeliverCurrentCardPreservesContextCancellation(t *testing.T) {
client, _ := newSequenceTestClient(t)
ctx, cancel := context.WithCancel(context.Background())
cancel()
_, err := client.DeliverCurrentCard(ctx)
if !errors.Is(err, context.Canceled) {
t.Fatalf("error = %v, want context.Canceled", err)
}
}
func TestPrepareCurrentCardRetriesOnceThenTimesOut(t *testing.T) {
responses := make([]cmdResp, 13)
for index := range responses {
responses[index] = cmdResp{status: status(0x34)}
}
client, device := newSequenceTestClient(t, responses...)
_, err := client.PrepareCurrentCard(context.Background())
if err == nil || !strings.Contains(err.Error(), "timed out") {
t.Fatalf("error = %v, want preparation timeout", err)
}
if got := commandCount(device.commands, cmdToEncoder); got != 2 {
t.Fatalf("to-encoder commands = %d, want initial command plus one halfway retry", got)
}
if got := commandCount(device.commands, cmdStatus); got != 13 {
t.Fatalf("status reads = %d, want 13", got)
}
}
func TestPrepareCurrentCardPropagatesContextCancellation(t *testing.T) {
client, _ := newSequenceTestClient(t,
cmdResp{status: status(0x34)},
cmdResp{status: status(0x34)},
)
ctx, cancel := context.WithCancel(context.Background())
client.sequenceTiming.wait = func(context.Context, time.Duration) error {
cancel()
return ctx.Err()
}
_, err := client.PrepareCurrentCard(ctx)
if !errors.Is(err, context.Canceled) {
t.Fatalf("error = %v, want context.Canceled", err)
}
}
func TestBeginPrepareNextCardDispatchesWithoutReadinessPolling(t *testing.T) {
client, device := newSequenceTestClient(t)
if err := client.BeginPrepareNextCard(context.Background()); err != nil {
t.Fatal(err)
}
if got := commandCount(device.commands, cmdToEncoder); got != 1 {
t.Fatalf("to-encoder commands = %d, want 1", got)
}
if got := commandCount(device.commands, cmdStatus); got != 0 {
t.Fatalf("status reads = %d, want 0", got)
}
}
func TestBeginPrepareNextCardReturnsDispatchFailureWithoutPolling(t *testing.T) {
client, device := newSequenceTestClient(t)
device.commandErrors[cmdToEncoder] = []error{errors.New("dispatch failed")}
err := client.BeginPrepareNextCard(context.Background())
if err == nil || !strings.Contains(err.Error(), "dispatch failed") {
t.Fatalf("error = %v, want dispatch failure", err)
}
if got := commandCount(device.commands, cmdToEncoder); got != 1 {
t.Fatalf("to-encoder commands = %d, want 1", got)
}
if got := commandCount(device.commands, cmdStatus); got != 0 {
t.Fatalf("status reads = %d, want 0", got)
}
}
func TestPrepareCardAtEncoderRequiresConfirmedEncoderState(t *testing.T) {
tests := []struct {
name string
responses []cmdResp
wantError string
wantToEncoder int
}{
{
name: "already at encoder",
responses: []cmdResp{{status: status(0x33)}},
wantToEncoder: 0,
},
{
name: "moves ready card to encoder",
responses: []cmdResp{
{status: status(0x34)},
{status: status(0x33)},
},
wantToEncoder: 1,
},
{
name: "empty card well",
responses: []cmdResp{{status: status(0x38)}},
wantError: CardWellEmptyMessage,
wantToEncoder: 0,
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
client, device := newSequenceTestClient(t, test.responses...)
_, err := client.PrepareNextCard(context.Background())
if test.wantError == "" && err != nil {
t.Fatal(err)
}
if test.wantError != "" && (err == nil || !strings.Contains(err.Error(), test.wantError)) {
t.Fatalf("error = %v, want containing %q", err, test.wantError)
}
if got := commandCount(device.commands, cmdToEncoder); got != test.wantToEncoder {
t.Fatalf("to-encoder commands = %d, want %d", got, test.wantToEncoder)
}
})
}
}