1import * as UART from 'UART'
2import * as event from 'events'
3
4function byteArrayToArrayBuffer(byteArray) {
5    return new Uint8Array(byteArray).buffer
6}
7
8class HW_UART extends event.EventEmitter{
9    constructor(options) {
10        super();
11
12        if (!options || !options.id) {
13            throw new Error("options is invalid");
14        }
15        this.options = {
16            id: options.id,
17            mode: options.mode
18        };
19
20        this.success = options.success || function(){};
21        this.fail = options.fail || function(){};
22        this._open();
23        if (this.options.mode !== 'poll') {
24            this._onData();
25        }
26    }
27
28    _open() {
29        this.uartInstance = UART.open(this.options.id);
30        if (this.uartInstance === null) {
31            this.fail();
32            return;
33        }
34        this.success();
35    }
36
37    write(data) {
38        if (this.uartInstance === null || !data) {
39            throw new Error("uart not init");
40        }
41
42        if (Object.prototype.toString.call(data) !== '[object String]') {
43            this.uartInstance.write(byteArrayToArrayBuffer(data));
44        } else {
45            this.uartInstance.write(data);
46        }
47    }
48
49    read() {
50        if (this.uartInstance === null) {
51        throw new Error("uart not init");
52        }
53        return this.uartInstance.read();
54    };
55
56    off() {
57        if (this.uartInstance === null) {
58            throw new Error("uart not init");
59        }
60        this.removeAllListeners('data');
61    }
62    _onData() {
63        if (this.uartInstance === null) {
64            throw new Error("uart not init");
65        }
66
67        this.uartInstance.on(function(data, len){
68            this.emit('data', data, len);
69        }.bind(this));
70    };
71
72    close() {
73        if (this.uartInstance === null) {
74            throw new Error("uart not init");
75        }
76        this.uartInstance.close();
77    };
78
79    on_mode() {
80        if (this.uartInstance === null) {
81            throw new Error("uart not init");
82        }
83        this._onData();
84    };
85}
86
87export function open(options) {
88    return new HW_UART(options);
89}
90