1import * as SPI from 'SPI'
2
3function byteArrayToArrayBuffer(byteArray) {
4    return new Uint8Array(byteArray).buffer
5}
6
7class HW_SPI {
8    constructor(options) {
9        if (!options || !options.id) {
10            throw new Error("options is invalid");
11        }
12
13        this.options = {
14            id: options.id
15        };
16
17        this.success = options.success || function(){};
18        this.fail = options.fail || function(){};
19        this._open();
20    }
21
22    _open() {
23        this.spiInstance = SPI.open(this.options.id);
24        if (Object.prototype.toString.call(this.spiInstance) !== '[object Object]') {
25            this.fail();
26        } else {
27            this.success();
28        }
29    }
30
31    write(data) {
32        if (!this.spiInstance || !data) {
33            throw new Error("spi not init or params is invalid");
34        }
35        return this.spiInstance.write(byteArrayToArrayBuffer(data));
36    }
37
38    read(bytes) {
39        if (!this.spiInstance || !bytes) {
40            throw new Error("spi not init or params is invalid");
41        }
42        return Array.prototype.slice.call(new Uint8Array(this.spiInstance.read(bytes)));
43    };
44
45    readWrite(sendData, bytes) {
46        if (!this.spiInstance || !sendData ||!bytes) {
47            throw new Error("spi not init or params is invalid");
48        }
49        return Array.prototype.slice.call(new Uint8Array(this.spiInstance.sendRecv(byteArrayToArrayBuffer(sendData),bytes)));
50    };
51
52    close() {
53        if (!this.spiInstance) {
54            throw new Error("spi not init");
55        }
56        this.spiInstance.close(this.spiInstance);
57    };
58}
59
60export function open(options) {
61    return new HW_SPI(options);
62}