Warm tip: This article is reproduced from stackoverflow.com, please click
bluetooth flutter serial-port zebra-printers zpl

Flutter Bluetooth printing to Zebra

发布于 2020-05-18 17:16:27

I need to add printing functionality on a zebra zq520 bluetooth thermal printer. I manage to do so using the flutter_blue plugin and the code below but I am not happy with the implementation. I hate to break the string to smaller chunks in order to pass through bluetooth (and wait!!!!!). I also may need a better regular expression, but that is by far second!

I was wondering if there is a better approach, like the one we used in the (good?) old days of java for android using the android.bluetooth.BluetoothAdapter class

Thanks.

FlutterBlue flutterBlue = FlutterBlue.instance;

bool printOnZebra(String str)  {
  BluetoothDevice _zebra;


 flutterBlue.scan(timeout: Duration(seconds: 4)).listen((scanResult) async {
    BluetoothDevice dev = scanResult.device;
    if (dev.name.startsWith("zebra")) {
      flutterBlue.stopScan();
      _zebra = dev;
      await _zebra.connect();
      List<String> lst = [];

      RegExp exp = new RegExp(r".{" + zebraLen.toString() + "}");
      Iterable<Match> matches = exp.allMatches(str);
      matches.forEach((m) => lst.add(m.group(0)));

      String finalPart = str.substring(lst.length * zebraLen);
      lst.add(finalPart);

      List<BluetoothService> services = await _zebra.discoverServices();


      services.forEach((service) {
        List<BluetoothCharacteristic> blueChar = service.characteristics;
        blueChar.forEach((f) {
          if (f.uuid
              .toString()
              .compareTo("38eb4a82-c570-11e3-9507-0002a5d5c51b") ==
              0) {
            lst.forEach((_str) {
              f.write(utf8.encode(_str));
              sleep(new Duration(milliseconds: zebraWait));
            });
          }
        });
      });

      _zebra.disconnect();


    }

  });
  return true;
}

For those wondering ... the printer's name on the installation site always starts with zebra, that's why I stop discovery after that

Questioner
John Anderton
Viewed
77
John Anderton 2019-12-22 20:33

I ended up creating my own plugin. It works fine but it has two limitations. It assumes that the printer is already paired, and it is only for android. That is because the installation site is a factory and there is no need for iOS devices on my case

I have no problem publish it, if anyone interested