-
Notifications
You must be signed in to change notification settings - Fork 2
/
signalk-send-put.js
52 lines (48 loc) · 1.75 KB
/
signalk-send-put.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
module.exports = function(RED) {
function signalKSendPut(config) {
RED.nodes.createNode(this,config)
var node = this
var app = node.context().global.get('app')
function onError(err) {
node.error(err)
console.error(err.stack)
node.status({fill:"red",shape:"dot",text:err.message})
}
node.on('input', msg => {
node.status({fill:"yellow",shape:"dot",text:`sending...`})
try {
const path = config.path && config.path.length > 0 ? config.path : msg.topic
let res = app.putSelfPath(path, msg.payload, (reply) => {
if ( reply.state === 'COMPLETED' ) {
if ( reply.statusCode === 200 ) {
node.status({fill:'green',shape:"dot",text:`value: ${msg.payload}`})
} else {
node.status({fill:'red',shape:"dot",text:`error`})
node.error(`put error ${reply.statusCode} ${reply.message || ''}`)
}
}
}, config.source && config.source.length > 0 ? config.source : undefined)
Promise.resolve(res)
.then(reply => {
let fill
let text
if ( !app.queryRequest || (reply.state === 'COMPLETED' && reply.statusCode === 200) ) {
fill = 'green'
text = `value: ${msg.payload}`
} else if ( reply.state === 'PENDING' ) {
fill = 'yellow'
text = 'pending...'
} else {
fill = 'red'
text = `error : ${reply.statusCode} ${reply.message || ''}`
}
node.status({fill:fill,shape:"dot",text:text})
})
.catch(onError)
} catch (err) {
onError(err)
}
})
}
RED.nodes.registerType("signalk-send-put", signalKSendPut)
}