-
Notifications
You must be signed in to change notification settings - Fork 4
/
serial_worker.js
128 lines (112 loc) · 2.73 KB
/
serial_worker.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
'use strict'
const path = require('path')
const serial = require('serialport')
const SerialPort = serial.SerialPort
const processModule = require('process')
const SERIAL_EVENTS = require(path.join(__dirname, '/serial_events.js'))
var port = null
processModule.on('message', function (msg) {
let funcName = msg.func
let funcParam = msg.param
switch (funcName) {
case 'init':
let path = funcParam[0]
let opts = funcParam[1]
let immediate = funcParam[2]
port = new SerialPort(path, opts, false)
port.on('data', (data) => {
let res = {
eventType: SERIAL_EVENTS.data,
body: data
}
processModule.send(res)
})
// This event sometimes fired sometimes not fired
// Ommiting Original Open Event to avoid firing issue
// New Open Event will be fired in open() callback
port.on('open', () => {
let res = {
eventType: SERIAL_EVENTS.open,
body: undefined
}
processModule.send(res)
})
port.on('close', () => {
let res = {
eventType: SERIAL_EVENTS.close,
body: undefined
}
processModule.send(res)
})
port.on('error', (err) => {
let res = {
eventType: SERIAL_EVENTS.error,
body: err.message
}
processModule.send(res)
})
port.on('disconnect', (err) => {
let res = {
eventType: SERIAL_EVENTS.disconnect,
body: err.message
}
processModule.send(res)
})
// Open Immediate
if (immediate !== false) {
port.open()
};
break
case 'list':
let listRes
serial.list((err, ports) => {
if (err) {
listRes = {
eventType: SERIAL_EVENTS.list_failed,
body: err
}
} else {
listRes = {
eventType: SERIAL_EVENTS.list_success,
body: ports
}
}
processModule.send(listRes)
})
break
case 'isOpen':
let isRes = {
eventType: SERIAL_EVENTS.is_open,
body: port.isOpen()
}
processModule.send(isRes)
break
default:
let res = {}
let callbackfunc = (e) => {
if (e) {
res.eventType = SERIAL_EVENTS[funcName + '_failed']
res.body = e.message
} else {
res.eventType = SERIAL_EVENTS[funcName + '_success']
res.body = undefined
// fix open event not fired by ommiting original open event
/*
if(funcName === "open"){
processModule.send({
eventType : SERIAL_EVENTS.open,
body : undefined
});
}
*/
}
processModule.send(res)
}
if (funcParam) {
port[funcName](funcParam, callbackfunc)
} else {
port[funcName](callbackfunc)
}
}
})
//