async function readCargo()

in other/train-to-cloud-city/devices/rfid/trainGame.js [90:127]


async function readCargo(chunk, role) {
  const motor = await getMotor();

  // In either cargo error & reload stage (backwards to station)
  // Or in victory lap mode (forwards to station)
  if (moveBackToStation || moveForwardsToStation) {
    await moveToStation(chunk, role);
    return;
  }

  const tagId = new String(chunk);
  const isFrontCar = frontCar.includes(tagId);
  const isBackCar = backCar.includes(tagId);
  const isCargo = !isFrontCar && !isBackCar;

  // MIDDLE: In the middle of train, store cargo chunk and continue on
  if (isCargo && beginReading) {
    stockedCargo.push(chunk);
  }
  // FRONT: Begin reading cargo
  if (isFrontCar) {
    beginReading = true;
  }
  // BACK: At tailend of train, wrap up and send read cargo to firestore
  if (isBackCar) {
    beginReading = false;
    motor?.brake();
    motor?.stop();

    try {
      // Submit held cargo
      await submitActualCargo(stockedCargo);
      queueMessageToPublish("cargo-read", { stockedCargo });
    } catch (error) {
      console.error(error);
    }
  }
}