writeBytes method

  1. @override
Future<ConnectionResponse> writeBytes(
  1. List<int> data, {
  2. bool isDisconnect = true,
  3. int? vendorId,
  4. int? productId,
})
override

Implementation

@override
Future<ConnectionResponse> writeBytes(List<int> data,
    {bool isDisconnect = true, int? vendorId, int? productId}) async {
  if (Platform.isWindows) {
    try {
      if (!this.isConnected) {
        await connect();
      }

      // Inform the spooler the document is beginning.
      final dwJob = StartDocPrinter(hPrinter, 1, docInfo!);
      if (dwJob == 0) {
        ClosePrinter(hPrinter);
        return ConnectionResponse.printInProgress;
      }
      // Start a page.
      if (StartPagePrinter(hPrinter) == 0) {
        EndDocPrinter(hPrinter);
        ClosePrinter(hPrinter);
        return ConnectionResponse.printerNotSelected;
      }

      // Send the data to the printer.
      final lpData = data.toUint8();
      dwCount = data.length;
      if (WritePrinter(hPrinter, lpData, dwCount!, dwBytesWritten!) == 0) {
        EndPagePrinter(hPrinter);
        EndDocPrinter(hPrinter);
        ClosePrinter(hPrinter);
        return ConnectionResponse.printerNotWritable;
      }

      // End the page.
      if (EndPagePrinter(hPrinter) == 0) {
        EndDocPrinter(hPrinter);
        ClosePrinter(hPrinter);
      }

      // Inform the spooler that the document is ending.
      if (EndDocPrinter(hPrinter) == 0) {
        ClosePrinter(hPrinter);
      }

      // Check to see if correct number of bytes were written.
      if (dwBytesWritten!.value != dwCount) {}

      if (isDisconnect) {
        // Tidy up the printer handle.
        ClosePrinter(hPrinter);
        // await disconnect();
      }
      return ConnectionResponse.success;
    } catch (e) {
      return ConnectionResponse.unknown;
    }
  } else if (Platform.isAndroid) {
    var res = await connect();
    if (res == ConnectionResponse.success) {
      var bytes = Uint8List.fromList(data);
      int max = 16384;

      /// maxChunk limit on android
      var datas = bytes.chunkBy(max);
      for (var data in datas) {
        await usbPrinter.write(Uint8List.fromList(data));
      }
      // await Future.forEach(
      //     datas,
      //     (dynamic data) async =>
      //         await usbPrinter.write(data, super.vendorId!, super.productId!));

      if (isDisconnect) {
        try {
          await usbPrinter.close();
          this.isConnected = false;
          this.printer.connected = false;
        } catch (e) {
          return ConnectionResponse.unknown;
        }
      }
      return ConnectionResponse.success;
    } else {
      return res;
    }
  }
  return ConnectionResponse.unsupport;
}