forked from andrewjfreyer/monitor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mqtt
404 lines (329 loc) · 11.3 KB
/
mqtt
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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
#!/bin/bash
# ----------------------------------------------------------------------------------------
# GENERAL INFORMATION
# ----------------------------------------------------------------------------------------
#
# Written by Andrew J Freyer
# GNU General Public License
# http://github.com/andrewjfreyer/monitor
#
# MQTT SCANNING
#
# ----------------------------------------------------------------------------------------
# ----------------------------------------------------------------------------------------
# UTILITY FUNCTION FOR JOINING STRINGS
# ----------------------------------------------------------------------------------------
#GLOBALS
last_error_message=""
duplicate_error_count=1
#UTILITY FUNCTIONS
function join_string () (IFS=$1; shift; printf "$*");
function json_keypair () (join_string ":" "\"$1\"" "\"$2\"")
#UNFORMAT A JASON STRING
function json_unformat (){
#https://stackoverflow.com/a/38607019/225270
printf "$1" | grep -Eo '"[^"]*" *(: *([0-9]*|"[^"]*")[^{}\["]*|,)?|[^"\]\[\}\{]*|\{|\},?|\[|\],?|[0-9 ]*,?' | awk '{if ($0 ~ /^[}\]]/ ) offset-=4; printf "%*c%s\n", offset, " ", $0; if ($0 ~ /^[{\[]/) offset+=4}'
}
#FORMAT OF 'KEY=OBJECT' IN ARGV VALUES
function json_format (){
local concat
local key
local object
for var in "$@"
do
object="${var##*=}"
key="${var%%=*}"
concat="$concat,$(json_keypair "$key" "$object")"
done
printf "{%s}\n" "${concat/,/}"
}
# ----------------------------------------------------------------------------------------
# MQTT ANNOUNCE ONLINE
# ----------------------------------------------------------------------------------------
mqtt_announce_online(){
#ANNOUCEE HEALTH
mqtt_error_handler $($mosquitto_pub_path \
-I "$mqtt_publisher_identity" \
$mqtt_version_append \
$mqtt_ca_file_append \
-L "$mqtt_url$mqtt_topicpath/$mqtt_publisher_identity/status" \
-m "online" -q "2" 2>&1)
}
# ----------------------------------------------------------------------------------------
# MQTT ECHO
# ----------------------------------------------------------------------------------------
mqtt_echo(){
#ANNOUCEE HEALTH
mqtt_error_handler $($mosquitto_pub_path \
-I "$mqtt_publisher_identity" \
$mqtt_version_append \
$mqtt_ca_file_append \
-L "$mqtt_url$mqtt_topicpath/$mqtt_publisher_identity/echo" \
-m "ok" \
-q "2" 2>&1)
}
# ----------------------------------------------------------------------------------------
# CLEAR RETAINED
# ----------------------------------------------------------------------------------------
mqtt_broker_clean (){
#DEFINE LOCALS
local topic_data
local topic_path
#MQTT LOOP
while read instruction; do
#ERROR HANDLING
mqtt_error_handler "$instruction" && break
#EXTRACT TOPIC PATH FROM FORMATTED MQTT MESSAGE
topic_path_of_instruction="${instruction%%|*}"
[ -z "$topic_path_of_instruction" ] && continue
#PUBLISH CLEARING MESSAGE
$mosquitto_pub_path \
$mqtt_version_append \
$mqtt_ca_file_append \
-r \
-n \
-L "$mqtt_url$topic_path_of_instruction" 2>&1
done < <($(which mosquitto_sub) \
-I "$mqtt_publisher_identity" \
-v $mqtt_version_append \
$mqtt_ca_file_append \
-F '%t|%p' \
-W 1 \
-q 2 \
-L "$mqtt_url$mqtt_topicpath/$mqtt_publisher_identity/#" 2>&1 )
printf "%s\n" "> retained messages cleaned from broker"
}
# ----------------------------------------------------------------------------------------
# MQTT LISTENER
# ----------------------------------------------------------------------------------------
mqtt_listener (){
#ANNOUNCE ONLINE PRESENCE
mqtt_announce_online
#DEFINE LOCALS
local topic_data
local topic_path
while true; do
#MQTT LOOP
while read instruction; do
#ERROR HANDLING
mqtt_error_handler "$instruction" && break
#PRINT THE INSTRUCTION BACK TO THE MAIN THREAD
printf "MQTT$instruction\n" > main_pipe
done < <($(which mosquitto_sub) -I \
"$mqtt_publisher_identity" \
$mqtt_version_append \
$mqtt_ca_file_append \
-v \
-F '%t|%p' \
-q 2 \
-L "$mqtt_url$mqtt_topicpath/#" \
--will-topic "$mqtt_topicpath/$mqtt_publisher_identity/status" \
--will-payload "offline" 2>&1 )
#NEED TO RESUBSCRIBE
sleep 10
done
}
# ----------------------------------------------------------------------------------------
# MQTT ERROR HANDLER
# ----------------------------------------------------------------------------------------
mqtt_error_handler () {
local received="$*"
local return_value
local print_message=""
#SET RETURN VALUE TO TRUE
return_value=1
if [ -n "$received" ]; then
#ERRORS
[[ ${received^^} =~ .*CONNECTION.* ]] && [[ ${received^^} =~ .*REFUSED.* ]] && return_value=1 && print_message="mqtt broker refused connection - check username, password, and host address"
[[ ${received^^} =~ .*NETWORK.* ]] && [[ ${received^^} =~ .*UNREACHABLE.* ]] && return_value=0 && print_message="network is down. enqueuing command to try again after a delay"
[[ ${received^^} =~ .*LOOKUP.* ]] && [[ ${received^^} =~ .*ERROR.* ]] && return_value=0 && print_message="issue connecting to mqtt server (lookup error). enqueuing command to try again after a delay"
if [ -n "$last_error_message" ] && [ "$last_error_message" == "$print_message" ]; then
#HERE, WE HAVE A REPEATED ERROR
duplicate_error_count=$((duplicate_error_count + 1 ))
last_error_message="$print_message"
if [ "$duplicate_error_count" -gt "3" ]; then
log "${RED}[CMD-ERRO]${NC} ${RED}fatal mqtt error - messages may not be delivered as intended ($print_message / $duplicate_error_count)${NC}"
duplicate_error_count=0
last_error_message=""
fi
#SET TO TRUE TO CAUSE A LOOP OF
return_value=0
elif [ -n "$print_message" ]; then
#MESSAGE IS NOT REPEATED, SO FEEL FREE TO LOG IT
log "${YELLOW}[CMD-MQTT]${NC} ${YELLOW}warning: $print_message ${NC}"
duplicate_error_count=0
last_error_message="$print_message"
#SET TO TRUE TO CAUSE A LOOP OF
return_value=0
fi
else
duplicate_error_count=0
last_error_message=""
fi
#RETURN VALUE
return $return_value
}
# ----------------------------------------------------------------------------------------
# PUBLISH RSSI MESSAGE
# ----------------------------------------------------------------------------------------
publish_rssi_message () {
if [ -n "$1" ]; then
#TIMESTAMP
local stamp
local address
local message
local mqtt_topic_branch
#SET ISOLATED ADDRESS
address="$1"
message="$2"
mqtt_topic_branch="$address"
#ALIASES?
$PREF_ALIAS_MODE && [ "${mqtt_aliases[$address]+abc}" ] && mqtt_topic_branch=${mqtt_aliases[$address]:-$address}
local topic="$mqtt_topicpath/$mqtt_publisher_identity/$mqtt_topic_branch/rssi"
$PREF_VERBOSE_LOGGING && log "${YELLOW}[CMD-MQTT]${NC} ${YELLOW}$topic${NC}"
#POST TO MQTT
while mqtt_error_handler $($mosquitto_pub_path \
-I "$mqtt_publisher_identity" \
$mqtt_version_append \
$mqtt_ca_file_append \
-L "$mqtt_url$topic" \
-m "$message" 2>&1); do
sleep 15
done
fi
}
# ----------------------------------------------------------------------------------------
# PUBLISH MESSAGE
# ----------------------------------------------------------------------------------------
publish_presence_message () {
if [ -n "$1" ]; then
#TIMESTAMP
local stamp
local should_retain
local isolated_address
local retain_flag
local message
local existing_alias
local mqtt_topic_branch
local confidence_printable
local device_tracker_message
#SET ISOLATED ADDRESS
isolated_address="${1##*=}"
mqtt_topic_branch="$isolated_address"
#ALIASES?
$PREF_ALIAS_MODE && [ "${mqtt_aliases[$isolated_address]+abc}" ] && mqtt_topic_branch=${mqtt_aliases[$isolated_address]:-$isolated_address}
#SET TIMESTAMP
stamp=$(date "+%a %b %d %Y %H:%M:%S GMT%z (%Z)")
#CLEAR PREVIOUS RETAINED MESSAGE
retain_flag="false"
if [ "$PREF_SHOULD_RETAIN" == true ]; then
should_retain="-r "
retain_flag="true"
fi
#ASSEMBLE
message=$( \
json_format "$@" \
"retained=$retain_flag" \
"timestamp=$stamp" \
"version=$version" \
)
#DEFINE THE TOPIC
local topic="$mqtt_topicpath/$mqtt_publisher_identity/$mqtt_topic_branch"
[ "$PREF_MQTT_SINGLE_TOPIC_MODE" == true ] && topic="$mqtt_topicpath/$mqtt_publisher_identity"
#SHOULD FORMAT AS LETTERS/NUMBERS
[ "$PREF_FORMAT_MQTT" == true ] && topic=$(echo "$topic" | sed 's/[^0-9a-z/]//gi')
#ANNOUNCE ONLINE
mqtt_announce_online
#SHOULD WE BE REPORTING AS A DEVICE TRACKER?
if [ "$PREF_DEVICE_TRACKER_REPORT" == true ]; then
if [[ $message =~ \"confidence\":\"100\" ]]; then
#OVERRIDE MESSAGE
device_tracker_message="$PREF_DEVICE_TRACKER_HOME_STRING"
elif [[ $message =~ \"confidence\":\"0\" ]]; then
#OVERRIDE MESSAGE
device_tracker_message="$PREF_DEVICE_TRACKER_AWAY_STRING"
else
#NO MQTT MESSAGES IF NOT ZERO OR 100
device_tracker_message=""
fi
#ONLY POST A MESSAGE TO DEVICE TRACKER BOARD IF WE HAVE
#A COMPLETE CONFIDENCE MESSAGE
if [ -n "$device_tracker_message" ]; then
#POST TO MQTT
while mqtt_error_handler $($mosquitto_pub_path \
-I "$mqtt_publisher_identity" \
$should_retain \
$mqtt_version_append \
$mqtt_ca_file_append \
-L "$mqtt_url$topic/$PREF_DEVICE_TRACKER_TOPIC_BRANCH" \
-m "$device_tracker_message" 2>&1); do
sleep 10
done
#PRINT FOR DEVICE TRACKER
if [ $PREF_VERBOSE_LOGGING == true ]; then
log "${YELLOW}[CMD-MQTT]${NC} ${YELLOW}$topic/$PREF_DEVICE_TRACKER_TOPIC_BRANCH $device_tracker_message${NC}"
fi
fi
fi
#POST TO MQTT
while mqtt_error_handler $($mosquitto_pub_path \
-I "$mqtt_publisher_identity" \
$should_retain \
$mqtt_version_append \
$mqtt_ca_file_append \
-q 2 \
-L "$mqtt_url$topic" \
-m "$message" 2>&1); do
sleep 5
done
#MESSAGE PRINTING
if [ $PREF_VERBOSE_LOGGING == true ]; then
log "${YELLOW}[CMD-MQTT]${NC} ${YELLOW}$topic${NC}"
#REDACTIONS?
if [ "$PREF_REDACT" == true ]; then
printf "%s\n" "${YELLOW}$(json_unformat "$message" | sed "s/\([0-9A-Fa-f]\{2\}:\)\{5\}/ [REDACTED]:/gi;s/\([0-9A-Fa-f-]\{36\}\)/ [REDACTED]/gi" )${NC}"
else
printf "%s\n" "${YELLOW}$(json_unformat "$message")${NC}"
fi
#EXTRACT RAW CONFIDENC
elif [[ "${message,,}" =~ \"confidence\":\"([0-9]{1,3})\" ]]; then
#GET CONFIDENCE VALUE
confidence_printable="${BASH_REMATCH[1]}"
#EXTRACT CONFIDENCE VALUE TO POST
log "${YELLOW}[CMD-MQTT]${NC} ${YELLOW}$topic { ... confidence : $confidence_printable ... } ${NC}"
fi
fi
}
publish_cooperative_scan_message () {
#ANNOUNCE ONLINE
mqtt_announce_online
if [ -n "$1" ] && [ -z "$2" ]; then
#POST TO MQTT
$mosquitto_pub_path \
-I "$mqtt_publisher_identity" \
$mqtt_version_append \
$mqtt_ca_file_append \
-q 2 \
-L "$mqtt_url$mqtt_topicpath/scan/$1" \
-m "{\"identity\":\"$mqtt_publisher_identity\"}" 2>&1
elif [ -n "$1" ] && [ -n "$2" ]; then
#POST TO MQTT
$mosquitto_pub_path \
-I "$mqtt_publisher_identity" \
$mqtt_version_append \
$mqtt_ca_file_append \
-q 2 \
-L "$mqtt_url$mqtt_topicpath/$2/$1" \
-m "{\"identity\":\"$mqtt_publisher_identity\"}" 2>&1
else
$mosquitto_pub_path \
-I "$mqtt_publisher_identity" \
$mqtt_version_append \
-q 2 \
$mqtt_ca_file_append \
-L "$mqtt_url$mqtt_topicpath/scan" \
-m "{\"identity\":\"$mqtt_publisher_identity\"}" 2>&1
fi
}
#SHOULD CLEAN?
[ "$PREF_CLEAN_MQTT" == true ] && mqtt_broker_clean