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