<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
    <script src="/resources/testharness.js"></script>
    <script src="/resources/testharnessreport.js"></script>
    <script src="resources/common.js"></script>
    <script src="resources/manual.js"></script>
  </head>
  <body>
    <p>
      These tests require a device configured with the following Arduino sketch:

      <pre>
uint32_t seed = 0;
uint32_t bytesToSend = 0;

uint8_t nextByte() {
  seed = (1103515245 * seed + 12345) % 0x8000000;
  return (seed >> 16) & 0xFF;
}

void setup() {
  Serial.begin(115200);
}

void loop() {
  if (!Serial) {
    return;
  }

  if (bytesToSend == 0) {
    // Read the seed and number of bytes to send from the host as 32-bit
    // little-endian values.
    if (Serial.available() &lt 8) {
      return;
    }

    uint8_t buf[8];
    Serial.readBytes((char*)buf, sizeof buf);
    seed = (uint32_t)buf[0] |
            ((uint32_t)buf[1] &lt;&lt; 8) |
            ((uint32_t)buf[2] &lt;&lt; 16) |
            ((uint32_t)buf[3] &lt;&lt; 24);
    bytesToSend = (uint32_t)buf[4] |
                  ((uint32_t)buf[5] &lt;&lt; 8) |
                  ((uint32_t)buf[6] &lt;&lt; 16) |
                  ((uint32_t)buf[7] &lt;&lt; 24);
  } else {
    uint8_t buf[64];
    uint32_t count = min(sizeof buf, bytesToSend);
    for (uint32_t i = 0; i &lt; count; ++i) {
      buf[i] = nextByte();
    }
    bytesToSend -= count;
    Serial.write((char*)buf, count);
  }
}
      </pre>
    </p>
    <p>
      <progress id='progress'></progress>
    </p>
    <script>
      let seed = 10;
      const length = 1024 * 1024 * 10;

      function next_byte() {
        seed = (Math.imul(1103515245, seed) + 12345) % (1 << 31);
        return (seed >> 16) & 0xFF;
      }

      manual_serial_test(async (t, port) => {
        await port.open({baudRate: 115200, bufferSize: 1024});

        const config = new DataView(new ArrayBuffer(8));
        config.setUint32(0, seed, /*littleEndian=*/true);
        config.setUint32(4, length, /*littleEndian=*/true);

        const writer = port.writable.getWriter();
        writer.write(config);

        const progress = document.getElementById('progress');
        progress.max = length;
        progress.value = 0;

        const reader = port.readable.getReader();
        let bytesRead = 0;
        while (bytesRead < length) {
          const { value, done } = await reader.read();
          assert_false(done);
          for (let i = 0; i < value.byteLength; ++i) {
            assert_equals(value[i], next_byte(),
                          `mismatch at byte ${bytesRead + i}`);
          }
          bytesRead += value.byteLength;
          progress.value = bytesRead;
        }

        writer.releaseLock();
        reader.releaseLock();
        await port.close();
      }, `Reading ${length} bytes from the device succeeds.`);
    </script>
  </body>
</html>
