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