-
Notifications
You must be signed in to change notification settings - Fork 0
/
remote.js
105 lines (87 loc) · 2.44 KB
/
remote.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
const AWS = require('aws-sdk')
const AWSMqttClient = require('aws-mqtt/lib/NodeClient')
const SerialPort = require('serialport')
const path = require('path')
const { throttle } = require('lodash')
const { MAVLink20Processor, mavlink20 } = require('./MAVLink20')
// Load configs
const config = require('./config.json')
AWS.config.loadFromPath(path.join(__dirname, 'aws.keys.json'))
// Create resources
const mqttclient = new AWSMqttClient({
region: AWS.config.region,
credentials: AWS.config.credentials,
endpoint: config.endpoint,
reconnectPeriod: 0,
will: {
topic: '/will',
payload: 'Connection Closed abnormally..!',
qos: 0,
retain: false
}
})
const serialport = new SerialPort(
config.serial.path,
{ baudRate: config.serial.baudRate },
exitOnError
)
const mav2 = new MAVLink20Processor()
// Connect all together
mqttclient.on('connect', () => {
mqttclient.subscribe(config.topicToThing, exitOnError)
})
mqttclient.on('message', (topic, buff) => {
if (serialport.isOpen) {
console.log('recv', buff.length)
serialport.write(buff)
}
else
console.log('skip', 'recv', buff.length)
})
serialport.on('data', buff => {
for (const message of mav2.parseBuffer(buff)) {
if (message instanceof mavlink20.messages.bad_data) {
pong()
}
else {
if (mqttclient.connected) {
console.log('send', message.msgbuf.length, 'as', message.name)
mqttclient.publish(config.topicFromThing, message.msgbuf)
}
else {
console.log('skip', 'send', message.msgbuf.length, 'as', message.name)
}
}
}
})
serialport.on('error', exitOnError)
serialport.on('close', () => exitOnError(new Error('Serialport closed')))
mqttclient.on('close', () => exitOnError(new Error('MQTTClient closed')))
mqttclient.on('disconnect', () => exitOnError(new Error('MQTTClient disconnected')))
mqttclient.on('offline', () => exitOnError(new Error('MQTTClient went offline')))
// Cleanup on exit
process.on('exit', () => {
mqttclient.end(true)
serialport.close()
})
// Utils
function exitOnError(error) {
if (error) {
console.error(error.message)
process.exit(1)
}
}
const pong = throttle(() => {
console.log('pong')
serialport.write(
Uint8Array.from(
mav2.send(
new mavlink20.messages.command_long(
config.sysid, 1, 0,
mav2.MAV_CMD_REQUEST_MESSAGE,
mav2.MAVLINK_MSG_ID_PROTOCOL_VERSION
)
)
)
)
}, config.pongThrottle)