BaseQRCodeScan.java 1.96 KB
Newer Older
pye52 committed
1 2 3 4 5 6 7 8 9 10
package com.bgycc.smartcanteen.qrcode;

import com.blankj.utilcode.util.LogUtils;

import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;

import static com.bgycc.smartcanteen.utils.SmartCanteenUtils.TAG;

pye52 committed
11
public abstract class BaseQRCodeScan implements IQRCodeScan {
pye52 committed
12 13
    private InputStream serialPortIS;

pye52 committed
14 15
    void setup(InputStream serialPortIS) {
        this.serialPortIS = serialPortIS;
pye52 committed
16 17
    }

pye52 committed
18
    @Override
pye52 committed
19 20 21 22 23 24 25 26 27 28 29
    public boolean available() {
        if (serialPortIS == null) {
            return false;
        }
        try {
            return serialPortIS.available() > 0;
        } catch (IOException e) {
            return false;
        }
    }

pye52 committed
30
    @Override
pye52 committed
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
    public String scan() throws IOException {
        if (serialPortIS == null) {
            return "";
        }
        byte[] buf = null;
        int len = 0;
        while (buf == null || end(buf)) {
            byte[] b = new byte[64];
            int l = serialPortIS.read(b);
            if (l == 0) break;
            b = Arrays.copyOfRange(b, 0, l);
            buf = merge(buf, b);
            len += l;
        }

        String str = null;
        if (buf != null) {
            str = new String(buf, 0, len - 2);
        }
        return str;
    }

pye52 committed
53
    @Override
pye52 committed
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
    public void close() {
        if (serialPortIS != null) {
            try {
                serialPortIS.close();
            } catch (IOException e) {
                LogUtils.w(TAG, "端口关闭失败: " + e.getMessage(), e);
            }
        }
    }

    private boolean end(byte[] buf) {
        return buf.length >= 2 && buf[buf.length - 2] == 0x0D && buf[buf.length - 1] == 0x0A;
    }

    private byte[] merge(byte[] hand, byte[] tail) {
        if (hand == null) {
            return tail;
        }
        byte[] data = new byte[hand.length + tail.length];
        System.arraycopy(hand, 0, data, 0, hand.length);
        System.arraycopy(tail, 0, data, hand.length, tail.length);
        return data;
    }
}