1import * as I2C from 'I2C'
2
3function byteArrayToArrayBuffer(byteArray) {
4    return new Uint8Array(byteArray).buffer
5}
6class HW_I2C {
7    constructor(options) {
8        if (!options || !options.id) {
9            throw new Error("options is invalid");
10        }
11
12        this.options = {
13            id: options.id
14        };
15
16        this.success = options.success || function(){};
17        this.fail = options.fail || function(){};
18        this._open();
19    }
20
21    _open() {
22        this.i2cInstance = I2C.open(this.options.id);
23        if (!this.i2cInstance) {
24            this.fail();
25            return;
26        }
27        this.success();
28    }
29
30    write(data) {
31        if (!this.i2cInstance || !data) {
32            throw new Error("i2c not init or params is invalid");
33        }
34        return this.i2cInstance.write(byteArrayToArrayBuffer(data));
35    }
36
37    read(bytes) {
38        if (!this.i2cInstance || !bytes) {
39            throw new Error("i2c not init or params is invalid");
40        }
41        return Array.prototype.slice.call(new Uint8Array(this.i2cInstance.read(bytes)));
42    };
43
44    writeMem(memaddr, data) {
45        if (!this.i2cInstance) {
46            throw new Error("i2c not init or params is invalid");
47        }
48        return this.i2cInstance.writeReg(memaddr, byteArrayToArrayBuffer(data));
49    }
50
51    readMem(memaddr, bytes) {
52        if (!this.i2cInstance) {
53            throw new Error("i2c not init or params is invalid");
54        }
55        return Array.prototype.slice.call(new Uint8Array(this.i2cInstance.readReg(memaddr, bytes)));
56    };
57
58    close() {
59        if (!this.i2cInstance) {
60            throw new Error("i2c not init");
61        }
62        this.i2cInstance.close();
63    };
64}
65
66export function open(options) {
67    return new HW_I2C(options);
68}
69