1'use strict';
2
3const EventEmitter = require('events');
4
5class HW_CAN 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        };
15
16        this.success = options.success || function(){};
17        this.fail = options.fail || function(){};
18        this._open();
19        this._onData();
20    }
21
22    _open() {
23        this.canInstance = __native.CAN.open(this.options.id);
24        if (!this.canInstance) {
25            this.fail();
26            return;
27        }
28        this.success();
29    }
30
31    receive() {
32        if (!this.canInstance) {
33            throw new Error('can not init');
34        }
35        return __native.CAN.receive(this.canInstance);
36    };
37
38    _onData() {
39        if (!this.canInstance) {
40            throw new Error("can not init");
41        }
42        __native.CAN.receive(this.canInstance, function(type, id, data){
43            this.emit('data', type, id, data);
44        }.bind(this));
45    };
46
47    send(txheader, data) {
48        if (!this.canInstance || !data) {
49            throw new Error('can not init or params is invalid');
50        }
51        __native.CAN.send(this.canInstance, txheader, data);
52    };
53
54    close() {
55        if (!this.canInstance) {
56            throw new Error('can not init');
57        }
58        __native.CAN.close(this.canInstance);
59    };
60}
61
62function open(options) {
63    return new HW_CAN(options);
64}
65
66module.exports = {
67    open,
68}