-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
246 lines (213 loc) · 5.88 KB
/
index.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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
/* eslint-env node */
/*
** Install Error Handler
*/
process.on('uncaughtException', handleError)
function handleError (error) {
if (error.response) {
// The request was made and the server responded with a status code out of range of 2xx
handleError(
new Error('URL GET response: <' + error.response.status + '>')
)
} else if (error.request) {
switch (error.errno) {
case 'ENOTFOUND':
handleError(
new Error(
'Unable to resolve / reach hostname <' +
error.hostname +
'>'
)
)
break
case 'ECONNREFUSED':
handleError(
new Error(
'Connection refused by server <' + error.address + '>'
)
)
break
default:
handleError(
new Error(
'No URL GET response received <' + error.toJSON() + '>'
)
)
}
} else {
console.error(error.toString())
}
process.exit(1) // mandatory (as per the Node.js docs)
}
/*
** Defaults + Commandline
*/
const config = require('./cli.js')
/*
** Establish MQTT Server Connection
*/
const os = require('os')
const mqttLib = require('mqtt')
// Base Topic
config.mqttTopic =
config.mqttTopic.toLowerCase() + '/' + os.hostname().toLowerCase()
// Options
const mqttOptions = {
username: config.mqttUsername,
password: config.mqttPassword,
will: {
topic: config.mqttTopic + '/status',
payload: Buffer.from(
'{"Host":"' + os.hostname + '","Status":"Disconnected"}'
), // Payloads are buffers
qos: 0
}
}
const mqttClient = mqttLib.connect(config.mqttBroker, mqttOptions)
mqttClient.on('error', function (err) {
// increase reconnect timer and exit if expired
handleError(new Error('MQTT ' + err.toString()))
})
mqttClient.on('close', function (err) {
// do nothing
return err
})
mqttClient.on('connect', function () {
// Publish power-on message
mqttClient.publish(
config.mqttTopic + '/status',
'{"Host":"' + os.hostname + '","Status":"Connected"}'
)
// register last will message for power-off
})
/*
** Open URL, Read file, send to MQTT
*/
const httpClient = require('axios')
function loopForever () {
httpClient
.get(config.jsonurl)
.then(verifyServerResponse)
.then(transformJSONData)
.then(filterData)
.then(publishToMQTT)
.catch(handleError)
setTimeout(loopForever, config.sendFrequency * 1000)
}
loopForever()
function transformJSONData (data) {
// no data transformation when raw requested
if (config.sendRawData) {
return data
}
// Transform JSON data - mqttwarn can not process nested structures
return recursiveParser(data.Children)
}
function recursiveParser (string1, string2 = [], var1 = 0, array1 = []) {
const object = string1
// WHY ???
const branch = JSON.parse(JSON.stringify(string2))
const level = var1
let dataArray = array1
const re = config.cleanValues ? new RegExp('[^0-9,]', 'g') : ''
const re2 = config.cleanValues ? new RegExp(',', 'g') : ''
// Recursion clause
for (var property in object) {
// recursion if property is object (=> branch in JSON data set)
if (typeof object[property] === 'object') {
if (typeof object.Text !== 'undefined') {
branch.push(object.Text)
dataArray = recursiveParser(
object[property],
branch,
level + 1,
dataArray
)
branch.pop()
} else {
dataArray = recursiveParser(
object[property],
branch,
level + 1,
dataArray
)
}
}
}
// Exit clause - value field set means measurement found ( => tree leaf node)
if (typeof object.Value !== 'undefined' && object.Value.length > 0) {
const jsonString =
'{"Value":"' +
object.Value.replace(re, '').replace(re2, '.') +
'",' +
'"Max":"' +
object.Max.replace(re, '').replace(re2, '.') +
'",' +
'"Min":"' +
object.Min.replace(re, '').replace(re2, '.') +
'"}'
branch.push(object.Text)
branch.push(jsonString)
dataArray.push(branch)
}
// catch all return
return dataArray
}
function filterData (data) {
// no filter applied for raw data to be sent
if (typeof config.filterMode === 'undefined') {
return data
}
// filter by ID or Text value - filterMode defines ALLOW or DENY approach when match is found
return data.filter((element) => {
switch (config.filterType) {
case 'id':
if (config.filterPattern.indexOf(element[0]) !== -1) {
return config.filterMode
}
break
case 'text':
if (
config.filterPattern.filter((pattern) => {
return element.indexOf(pattern) !== -1
}).length > 0
) {
return config.filterMode
}
break
default:
break
}
return !config.filterMode
})
}
function publishToMQTT (data) {
// console.log ("###########################################################################################")
// no data transformation when raw requested
if (config.sendRawData) {
mqttClient.publish(config.mqttTopic, JSON.stringify(data))
} else {
// Publish by topic
data.forEach((element) => {
var mqttData = element.pop()
var mqttTopic =
config.mqttTopic +
'/' +
element.join('/').replace(/[#+]/g, '').replace(/\s/g, '-')
// console.log(mqttTopic + " -> " + mqttData)
mqttClient.publish(mqttTopic, mqttData)
})
}
}
function verifyServerResponse (obj) {
if (obj.headers['content-type'] !== 'application/json') {
handleError(
new Error(
'Data from Webserver URL is not in JSON format (content type <' +
obj.headers['content-type'] +
'>)'
)
)
}
return obj.data
}