-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgps.js
69 lines (58 loc) · 1.73 KB
/
gps.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
const {
EventEmitter
} = require("events")
class GPS extends EventEmitter {
constructor(port) {
super()
this.portName = port
this.running = false
this.SerialPort = require('serialport')
this.NodeNMEA = require('node-nmea')
this.start()
}
start() {
if (!this.getState()) {
this.port = new this.SerialPort(this.portName, {
baudRate: 9600
})
const readline = new this.SerialPort.parsers.Readline({
delimiter: '\r\n'
})
this.parser = this.port.pipe(readline)
this.parser.on('data', (data) => {
this.lastState = this.NodeNMEA.parse(data)
try {
this.emit('data', {
latitude: this.lastState.loc.geojson.coordinates[1],
longitude: this.lastState.loc.geojson.coordinates[0],
altitude: this.lastState.altitude
})
} catch (e) {
this.emit('data', {
latitude: 0,
longitude: 0,
altitude: 0
})
}
})
this.running = true
}
}
stop() {
this.port = null
this.lastState = null
this.running = false
}
getState() {
return this.running
}
getData() {
if (!this.getState()) return null
else return {
latitude: this.lastState.loc.geojson.coordinates[1],
longitude: this.lastState.loc.geojson.coordinates[0],
altitude: this.lastState.altitude
}
}
}
module.exports = GPS