-
Notifications
You must be signed in to change notification settings - Fork 194
/
monitor.sh
executable file
·1990 lines (1523 loc) · 69.7 KB
/
monitor.sh
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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/bin/bash
# ----------------------------------------------------------------------------------------
# GENERAL INFORMATION
# ----------------------------------------------------------------------------------------
#
# Written by Andrew J Freyer
# GNU General Public License
# http://github.com/andrewjfreyer/monitor
#
# Credits to:
# Radius Networks iBeacon Script
# • http://developer.radiusnetworks.com/ibeacon/idk/ibeacon_scan
#
# Reely Active advlib
# • https://github.com/reelyactive/advlib
#
# _ _
# (_) |
# _ __ ___ ___ _ __ _| |_ ___ _ __
# | '_ ` _ \ / _ \| '_ \| | __/ _ \| '__|
# | | | | | | (_) | | | | | || (_) | |
# |_| |_| |_|\___/|_| |_|_|\__\___/|_|
#
# ----------------------------------------------------------------------------------------
#VERSION NUMBER
export version=0.2.200
if [ -z ${NO_COLOR} -o -z ${NOCOLOR} ] ; then
#COLOR OUTPUT FOR RICH OUTPUT
ORANGE=$'\e[1;33m'
RED=$'\e[1;31m'
NC=$'\e[0m'
GREEN=$'\e[1;32m'
PURPLE=$'\e[1;35m'
BLUE=$'\e[1;34m'
CYAN=$'\e[1;36m'
YELLOW=$'\e[01;33m'
REPEAT=$'\e[1A'
else
:
fi
# ----------------------------------------------------------------------------------------
# BETA WARNING ONLY IF ON THE BETA CHANNEL
# ----------------------------------------------------------------------------------------
if command -v git >/dev/null && [[ $(git status) =~ .*beta.* ]]; then
printf "\n%s\n" "${RED}===================================================${NC}"
printf "\n%s\n" "${RED} ${PURPLE}*** BETA/DEV BRANCH ***${NC}"
printf "\n%s\n" "${RED}===================================================${NC}"
fi
#CAPTURE ARGS IN VAR TO USE IN SOURCED FILE
export RUNTIME_ARGS=("$@")
# ----------------------------------------------------------------------------------------
# SOURCES
# ----------------------------------------------------------------------------------------
#SOURCE SETUP AND ARGV FILES
source './support/argv'
source './support/init'
#SOURCE FUNCTIONS
source './support/mqtt'
source './support/log'
source './support/data'
source './support/btle'
source './support/time'
# ----------------------------------------------------------------------------------------
# CLEANUP ROUTINE
# ----------------------------------------------------------------------------------------
clean() {
#CLEANUP FOR TRAP
pkill -f monitor.sh
#REMOVE PIPES
rm main_pipe &>/dev/null
rm log_pipe &>/dev/null
rm packet_pipe &>/dev/null
#MESSAGE
echo 'Exited.'
}
trap "clean" EXIT
# ----------------------------------------------------------------------------------------
# DEFINE VALUES AND VARIABLES
# ----------------------------------------------------------------------------------------
#CYCLE BLUETOOTH INTERFACE
hciconfig "$PREF_HCI_DEVICE" down && sleep 3 && hciconfig "$PREF_HCI_DEVICE" up
#STOP OTHER INSTANCES OF MONITOR WITHOUT STOPPING THIS ONE
for pid in $(pidof -x "$(basename "$0")"); do
if [ "$pid" != $$ ]; then
kill -9 "$pid"
fi
done
#SETUP MAIN PIPE
rm main_pipe &>/dev/null
mkfifo main_pipe
#SETUP LOG PIPE
rm log_pipe &>/dev/null
mkfifo log_pipe
#SETUP BTLE PIPE
rm packet_pipe &>/dev/null
mkfifo packet_pipe
#DEFINE DEVICE TRACKING VARS
declare -A public_device_log
declare -A random_device_log
declare -A rssi_log
#STATIC DEVICE ASSOCIATIVE ARRAYS
declare -A known_public_device_log
declare -A expiring_device_log
declare -A known_static_device_scan_log
declare -A known_public_device_name
declare -A blacklisted_devices
declare -A beacon_mac_address_log
declare -A mqtt_aliases
declare -A advertisement_interval_observation
#LAST TIME THIS
scan_pid=""
scan_type=""
#SCAN VARIABLES
now=$(date +%s)
last_rssi_scan=""
last_arrival_scan=$((now - 25))
last_depart_scan=$((now - 25))
first_arrive_scan=true
# ----------------------------------------------------------------------------------------
# POPULATE THE ASSOCIATIVE ARRAYS THAT INCLUDE INFORMATION ABOUT THE STATIC DEVICES
# WE WANT TO TRACK
# ----------------------------------------------------------------------------------------
#LOAD PUBLIC ADDRESSES TO SCAN INTO ARRAY, IGNORING COMMENTS
mapfile -t known_static_beacons < <(sed 's/#.\{0,\}//gi' < "$BEAC_CONFIG" | awk '{print $1}' | grep -oiE "([0-9a-f]{2}:){5}[0-9a-f]{2}" )
mapfile -t known_static_addresses < <(sed 's/#.\{0,\}//gi' < "$PUB_CONFIG" | awk '{print $1}' | grep -oiE "([0-9a-f]{2}:){5}[0-9a-f]{2}" )
mapfile -t address_blacklist < <(sed 's/#.\{0,\}//gi' < "$ADDRESS_BLACKLIST" | awk '{print $1}' | grep -oiE "([0-9a-f]{2}:){5}[0-9a-f]{2}" )
#ASSEMBLE COMMENT-CLEANED BLACKLIST INTO BLACKLIST ARRAY
for addr in "${address_blacklist[@]^^}"; do
blacklisted_devices[$addr]=1
printf "%s\n" "> ${RED}blacklisted device:${NC} $addr"
done
# ----------------------------------------------------------------------------------------
# POPULATE MAIN DEVICE ARRAY
# ----------------------------------------------------------------------------------------
#LIST CONNECTED DEVICES
previously_connected_devices=$(echo "paired-devices" | bluetoothctl | grep -Eio "Device ([0-9A-F]{2}:){5}[0-9A-F]{2}" | sed 's/Device //gi')
#POPULATE KNOWN DEVICE ADDRESS
for addr in "${known_static_addresses[@]^^}"; do
#================= SHOULD WE USE AN ALIAS? =====================
#WAS THERE A NAME HERE?
known_name=$(grep -i "$addr" "$PUB_CONFIG" | tr "\\t" " " | sed 's/ */ /gi;s/#.\{0,\}//gi' | sed "s/$addr //gi;s/ */ /gi" )
#IF THE VALUE DOES NOT EXIST, USE THE KEY (MAC ADDRESS INSTEAD)
alias_value=${known_name//[^A-Za-z0-9]/_}
#LOWERCASE
alias_value=${alias_value,,}
#REMOVE FINAL UNDERSCORES SHOUDL THERE BE
alias_value=$(echo "$alias_value" | sed 's/[^0-9a-z]\{1,\}$//gi;s/^[^0-9a-z]\{1,\}//gi;s/__*/_/gi')
#DEFAULT
alias_value=${alias_value:-$addr}
#ALIASES
[ -n "$addr" ] && [ -n "$alias_value" ] && mqtt_aliases[$addr]="$alias_value"
#================= PROCESS THE KNOWN ADDR =====================
#IF WE FOUND A NAME, RECORD IT
[ -n "$known_name" ] && known_public_device_name[$addr]="$known_name"
#CONNECTED?
is_connected="not previously connected"
[[ $previously_connected_devices =~ .*$addr.* ]] && is_connected="previously connected"
#CORRECT
$PREF_ALIAS_MODE && mqtt_topic_branch=${mqtt_aliases[$addr]:-$addr} || mqtt_topic_branch=$addr
#PUBLICATION TOPIC
pub_topic="$mqtt_topicpath/$mqtt_publisher_identity/$mqtt_topic_branch"
$PREF_MQTT_SINGLE_TOPIC_MODE && pub_topic="$mqtt_topicpath/$mqtt_publisher_identity { id: $addr ... }"
#FOR DEBUGGING
printf "%s\n" "> ${GREEN}$addr${NC} confidence topic: $pub_topic (has $is_connected to $PREF_HCI_DEVICE)"
[ "$PREF_DEVICE_TRACKER_REPORT" == 'true' ] && printf "%s\n" "> ${GREEN}$addr${NC} device_tracker topic: $pub_topic/$PREF_DEVICE_TRACKER_TOPIC_BRANCH [$PREF_DEVICE_TRACKER_AWAY_STRING or $PREF_DEVICE_TRACKER_HOME_STRING]"
done
# ----------------------------------------------------------------------------------------
# POPULATE BEACON ADDRESS ARRAY
# ----------------------------------------------------------------------------------------
#POPULATE KNOWN DEVICE ADDRESS
for addr in "${known_static_beacons[@]^^}"; do
#WAS THERE A NAME HERE?
known_name=$(grep "$addr" "$BEAC_CONFIG" | tr "\\t" " " | sed 's/ */ /gi;s/#.\{0,\}//gi' | sed "s/$addr //gi;s/ */ /gi" )
#================= SHOULD WE USE AN ALIAS? =====================
#IF THE VALUE DOES NOT EXIST, USE THE KEY (MAC ADDRESS INSTEAD)
alias_value=${known_name//[^A-Za-z0-9]/_}
#LOWERCASE
alias_value=${alias_value,,}
#REMOVE FINAL UNDERSCORES SHOUDL THERE BE
alias_value=$(echo "$alias_value" | sed 's/[^0-9a-z]\{1,\}$//gi;s/^[^0-9a-z]\{1,\}//gi;s/__*/_/gi')
#DEFAULT
alias_value=${alias_value:-$addr}
#ALIASES
[ -n "$addr" ] && [ -n "$alias_value" ] && mqtt_aliases[$addr]="$alias_value"
#IF WE FOUND A NAME, RECORD IT
[ -n "$known_name" ] && known_public_device_name[$addr]="$known_name"
#CORRECT
$PREF_ALIAS_MODE && mqtt_topic_branch=${mqtt_aliases[$addr]:-$addr} || mqtt_topic_branch=$addr
#PUBLICATION TOPIC
pub_topic="$mqtt_topicpath/$mqtt_publisher_identity/$mqtt_topic_branch"
$PREF_MQTT_SINGLE_TOPIC_MODE && pub_topic="$mqtt_topicpath/$mqtt_publisher_identity { id: $addr ... }"
#FOR DBUGGING
echo "> known beacon: $addr publishes to: $pub_topic"
done
# ----------------------------------------------------------------------------------------
# ASSEMBLE RSSI LISTS
# ----------------------------------------------------------------------------------------
connectable_present_devices () {
#DEFINE LOCAL VARS
local this_state
local known_device_rssi
local avg_total
local scan_result
#ITERATE THROUGH THE KNOWN DEVICES
local known_addr
for known_addr in "${known_static_addresses[@]^^}"; do
#GET STATE; ONLY SCAN FOR DEVICES WITH SPECIFIC STATE
this_state="${known_public_device_log[$known_addr]}"
this_state=${this_state:-0}
#TEST IF THIS DEVICE MATCHES THE TARGET SCAN STATE
if [ "$this_state" == "1" ] && [[ "$previously_connected_devices" =~ .*$known_addr.* ]] ; then
#CREATE CONNECTION AND DETERMINE RSSI
#AVERAGE OVER THREE CYCLES; IF BLANK GIVE VALUE OF 100
known_device_rssi=$(counter=0; \
avg_total=0; \
hcitool cc "$known_addr"; \
avg_total=""; \
for i in 1 2 3; \
do scan_result=$(hcitool rssi "$known_addr" 2>&1); \
scan_result=${scan_result//[^0-9]/}; \
scan_result=${scan_result:-99}; \
[[ "$scan_result" == "0" ]] && scan_result=99; \
counter=$((counter+1)); \
avg_total=$((avg_total + scan_result )); \
sleep 0.5; \
done; \
printf "%s" "$(( avg_total / counter ))")
#PUBLISH MESSAGE TO RSSI SENSOR
publish_rssi_message \
"$known_addr" \
"-$known_device_rssi"
#REPORT
$PREF_VERBOSE_LOGGING && log "${CYAN}[CMD-RSSI] ${NC}$known_addr ${GREEN}$cmd ${NC}RSSI: -$known_device_rssi dBm ${NC}"
#SET RSSI LOG
rssi_log[$known_addr]="$known_device_rssi"
fi
done
}
# ----------------------------------------------------------------------------------------
# ASSEMBLE SCAN LISTS
# ----------------------------------------------------------------------------------------
scannable_devices_with_state () {
#DEFINE LOCAL VARS
local return_list
local timestamp
local scan_state
local scan_type_diff
local this_state
local last_scan
local time_diff
#SET VALUES AFTER DECLARATION
timestamp=$(date +%s)
scan_state="$1"
#FIRST, TEST IF WE HAVE DONE THIS TYPE OF SCAN TOO RECENTLY
if [ "$scan_state" == "1" ]; then
#SCAN FOR DEPARTED DEVICES
scan_type_diff=$((timestamp - last_depart_scan))
elif [ "$scan_state" == "0" ]; then
#SCAN FOR ARRIVED DEVICES
scan_type_diff=$((timestamp - last_arrival_scan))
fi
#REJECT IF WE SCANNED TO RECENTLY
[ "$scan_type_diff" -lt "$PREF_MINIMUM_TIME_BETWEEN_SCANS" ] && return 0
#SCAN ALL? SET THE DEFAULT SCAN STATE TO [X]
scan_state=${scan_state:-2}
#ITERATE THROUGH THE KNOWN DEVICES
local known_addr
for known_addr in "${known_static_addresses[@]^^}"; do
#GET STATE; ONLY SCAN FOR DEVICES WITH SPECIFIC STATE
this_state="${known_public_device_log[$known_addr]}"
#IF WE HAVE NEVER SCANNED THIS DEVICE BEFORE, WE MARK AS
#SCAN STATE [X]; THIS ALLOWS A FIRST SCAN TO PROGRESS TO
#COMPLETION FOR ALL DEVICES
this_state=${this_state:-3}
#FIND LAST TIME THIS DEVICE WAS SCANNED
last_scan="${known_static_device_scan_log[$known_addr]}"
time_diff=$((timestamp - last_scan))
#SCAN IF DEVICE HAS NOT BEEN SCANNED
#WITHIN LAST [X] SECONDS
if [ "$time_diff" -gt "$PREF_MINIMUM_TIME_BETWEEN_SCANS" ]; then
#TEST IF THIS DEVICE MATCHES THE TARGET SCAN STATE
if [ "$this_state" == "$scan_state" ]; then
#ASSEMBLE LIST OF DEVICES TO SCAN
return_list="$return_list $this_state$known_addr"
elif [ "$this_state" == "2" ] || [ "$this_state" == "3" ]; then
#SCAN FOR ALL DEVICES THAT HAVEN'T BEEN RECENTLY SCANNED;
#PRESUME DEVICE IS ABSENT
return_list="$return_list $this_state$known_addr"
fi
fi
done
#RETURN LIST, CLEANING FOR EXCESS SPACES OR STARTING WITH SPACES
return_list=$(echo "$return_list" | sed 's/^ //gi;s/ $//gi;s/ */ /gi')
#RETURN THE LIST
echo "$return_list"
}
# ----------------------------------------------------------------------------------------
# SCAN FOR DEVICES
# ----------------------------------------------------------------------------------------
perform_complete_scan () {
#IF WE DO NOT RECEIVE A SCAN LIST, THEN RETURN 0
if [ -z "$1" ]; then
#log "${GREEN}[CMD-INFO] ${GREEN}**** Rejected group scan. No devices in desired state. **** ${NC}"
return 0
fi
#REPEAT THROUGH ALL DEVICES THREE TIMES, THEN RETURN
local repetitions=2
[ -n "$2" ] && repetitions="$2"
[ "$repetitions" -lt "1" ] && repetitions=1
#PRE
local previous_state=0
[ -n "$3" ] && previous_state="$3"
#SCAN TYPE
local transition_type="arrival"
[ "$previous_state" == "1" ] && transition_type="departure"
#INTERATION VARIABLES
local devices="$1"
local devices_next="$devices"
local scan_start=""
local scan_duration=""
local should_report=""
local manufacturer="Unknown"
local has_requested_collaborative_depart_scan=false
#LOG START OF DEVICE SCAN
$PREF_MQTT_REPORT_SCAN_MESSAGES && publish_cooperative_scan_message "$transition_type/start"
$PREF_VERBOSE_LOGGING && log "${GREEN}[CMD-INFO] ${GREEN}**** started $transition_type scan [x$repetitions max rep] **** ${NC}"
#ITERATE THROUGH THE KNOWN DEVICES
local repetition
for repetition in $(seq 1 $repetitions); do
#SET DONE TO MAIN PIPE
printf "%s\n" "DONE" > main_pipe
#SET DEVICES
devices="$devices_next"
#ITERATE THROUGH THESE
local known_addr
local known_addr_stated
local expected_name
local name_raw
local name
local scan_end
local scan_duration
local percent_confidence
local adjusted_delay
for known_addr_stated in $devices; do
#EXTRACT KNOWN ADDRESS FROM STATE-PREFIXED KNOWN ADDRESS, IF PRESENT
if [[ "$known_addr_stated" =~ .*[0-9A-Fa-f]{3}.* ]]; then
#SET KNOWN ADDRESS
known_addr=${known_addr_stated:1}
#SET PREVIOUS STATE
previous_state=${known_addr_stated:0:1}
else
#THIS ELEMENT OF THE ARRAY DOES NOT CONTAIN A STATE PREFIX; GO WITH GLOBAL
#STATE SCAN TYPE
known_addr=$known_addr_stated
fi
#DETERMINE MANUFACTUERE
manufacturer="$(determine_manufacturer "$known_addr")"
manufacturer=${manufacturer:-Unknown}
#IN CASE WE HAVE A BLANK ADDRESS, FOR WHATEVER REASON
[ -z "$known_addr" ] && continue
#DETERMINE START OF SCAN
scan_start="$(date +%s)"
#GET LOCAL NAME
expected_name="$(determine_name "$known_addr")"
expected_name=${expected_name:-Unknown}
#DEBUG LOGGING
$PREF_VERBOSE_LOGGING && log "${GREEN}[CMD-SCAN] ${GREEN}(No. $repetition)${NC} $known_addr $transition_type? ${NC}"
#PERFORM NAME SCAN FROM HCI TOOL. THE HCITOOL CMD 0X1 0X0019 IS POSSIBLE, BUT HCITOOL NAME
#SCAN PERFORMS VERIFICATIONS THAT REDUCE FALSE NEGATIVES.
#L2SCAN MAY INVOLVE LESS INTERFERENCE
name_raw=$(hcitool -i "$PREF_HCI_DEVICE" name "$known_addr" 2>/dev/null)
name=$(echo "$name_raw" | grep -ivE 'input/output error|invalid device|invalid|error|network')
#COLLECT STATISTICS ABOUT THE SCAN
scan_end="$(date +%s)"
scan_duration=$((scan_end - scan_start))
#MARK THE ADDRESS AS SCANNED SO THAT IT CAN BE LOGGED ON THE MAIN PIPE
printf "%s\n" "SCAN$known_addr" > main_pipe &
#IF STATUS CHANGES TO PRESENT FROM NOT PRESENT, REMOVE FROM VERIFICATIONS
if [ -n "$name" ] && [ "$previous_state" == "0" ]; then
#PUSH TO MAIN POPE
printf "%s\n" "NAME$known_addr|$name" > main_pipe
#DEVICE FOUND; IS IT CHANGED? IF SO, REPORT
publish_presence_message \
"id=$known_addr" \
"confidence=100" \
"name=$expected_name" \
"manufacturer=$manufacturer" \
"type=KNOWN_MAC"
#REMOVE FROM SCAN
devices_next=$(echo "$devices_next" | sed "s/$known_addr_stated//gi;s/ */ /gi")
elif [ -n "$name" ] && [ "$previous_state" == "3" ]; then
#HERE, WE HAVE FOUND A DEVICE FOR THE FIRST TIME
devices_next=$(echo "$devices_next" | sed "s/$known_addr_stated//gi;s/ */ /gi")
#NEED TO UPDATE STATE TO MAIN THREAD
printf "%s\n" "NAME$known_addr|$name" > main_pipe
#NEVER SEEN THIS DEVICE; NEED TO PUBLISH STATE MESSAGE
publish_presence_message \
"id=$known_addr" "confidence=100" \
"name=$expected_name" \
"manufacturer=$manufacturer" \
"type=KNOWN_MAC"
#COOPERATIVE SCAN ON RESTART
$PREF_TRIGGER_MODE_REPORT_OUT && publish_cooperative_scan_message "arrive"
elif [ -n "$name" ] && [ "$previous_state" == "1" ]; then
#THIS DEVICE IS STILL PRESENT; REMOVE FROM VERIFICATIONS
devices_next=$(echo "$devices_next" | sed "s/$known_addr_stated//gi;s/ */ /gi")
#NEED TO REPORT?
if [[ $should_report =~ .*$known_addr.* ]] || [ "$PREF_REPORT_ALL_MODE" == true ] ; then
#REPORT PRESENCE
publish_presence_message \
"id=$known_addr" \
"confidence=100" \
"name=$expected_name" \
"manufacturer=$manufacturer" \
"type=KNOWN_MAC"
fi
fi
#SHOULD WE REPORT A DROP IN CONFIDENCE?
if [ -z "$name" ] && [ "$previous_state" == "1" ]; then
#CALCULATE PERCENT CONFIDENCE
percent_confidence=$(echo "scale=1; ($repetitions - $repetition + 1) / $repetitions * 90" | bc )
#FALLBACK TO REMOVE DECIMAL AND PRINT INTEGER ONLY
percent_confidence=${percent_confidence%.*}
#ONLY PUBLISH COOPERATIVE SCAN MODE IF WE ARE NOT IN TRIGGER MODE
#TRIGGER ONLY MODE DOES NOT SEND COOPERATIVE MESSAGES
if [ "$has_requested_collaborative_depart_scan" == false ]; then
#SEND THE MESSAGE IF APPROPRIATE
if [ "$percent_confidence" -lt "$PREF_COOPERATIVE_SCAN_THRESHOLD" ] && $PREF_TRIGGER_MODE_REPORT_OUT; then
has_requested_collaborative_depart_scan=true
publish_cooperative_scan_message "depart"
fi
fi
#REPORT PRESENCE OF DEVICE
publish_presence_message \
"id=$known_addr" \
"confidence=$percent_confidence" \
"name=$expected_name" \
"manufacturer=$manufacturer" \
"type=KNOWN_MAC"
#IF WE DO FIND A NAME LATER, WE SHOULD REPORT OUT
should_report="$should_report$known_addr"
elif [ -z "$name" ] && [ "$previous_state" == "3" ]; then
#NEVER SEEN THIS DEVICE; NEED TO PUBLISH STATE MESSAGE
publish_presence_message \
"id=$known_addr" \
"confidence=0" \
"name=$expected_name" \
"manufacturer=$manufacturer" \
"type=KNOWN_MAC"
#PUBLISH MESSAGE TO RSSI SENSOR
publish_rssi_message \
"$known_addr" \
"-99"
#NREMOVE FROM THE SCAN LIST TO THE MAIN BECAUSE THIS IS A BOOT UP
devices_next=$(echo "$devices_next" | sed "s/$known_addr_stated//gi;s/ */ /gi")
#PUBLISH A NOT PRESENT TO THE NAME PIPE
printf "%s\n" "NAME$known_addr|" > main_pipe
#COOPERATIVE SCAN ON RESTART
$PREF_TRIGGER_MODE_REPORT_OUT && publish_cooperative_scan_message "depart"
elif [ -z "$name" ] && [ "$previous_state" == "0" ]; then
if [ "$PREF_REPORT_ALL_MODE" == true ] ; then
#REPORT PRESENCE
publish_presence_message \
"id=$known_addr" \
"confidence=0" \
"name=$expected_name" \
"manufacturer=$manufacturer" \
"type=KNOWN_MAC"
#PUBLISH MESSAGE TO RSSI SENSOR
publish_rssi_message \
"$known_addr" \
"-99"
fi
fi
#IF WE HAVE NO MORE DEVICES TO SCAN, IMMEDIATELY RETURN
[ -z "$devices_next" ] && break
#TO PREVENT HARDWARE PROBLEMS
if [ "$scan_duration" -lt "$PREF_INTERSCAN_DELAY" ]; then
adjusted_delay="$((PREF_INTERSCAN_DELAY - scan_duration))"
if [ "$adjusted_delay" -gt "0" ]; then
sleep "$adjusted_delay"
else
#DEFAULT MINIMUM SLEEP
sleep "$PREF_INTERSCAN_DELAY"
fi
else
#DEFAULT MINIMUM SLEEP
sleep "$PREF_INTERSCAN_DELAY"
fi
done
#ARE WE DONE WITH ALL DEVICES?
[ -z "$devices_next" ] && break
done
#ANYHTING LEFT IN THE DEVICES GROUP IS NOT PRESENT
local known_addr_stated
local known_addr
local expected_name
for known_addr_stated in $devices_next; do
#EXTRACT KNOWN ADDRESS FROM STATE-PREFIXED KNOWN ADDRESS, IF PRESENT
if [[ "$known_addr_stated" =~ .*[0-9A-Fa-f]{3}.* ]]; then
#SET KNOWN ADDRESS
known_addr=${known_addr_stated:1}
else
#THIS ELEMENT OF THE ARRAY DOES NOT CONTAIN A STATE PREFIX
known_addr=$known_addr_stated
fi
#PUBLISH MESSAGE
if [ ! "$previous_state" == "0" ]; then
expected_name="$(determine_name "$known_addr")"
expected_name=${expected_name:-Unknown}
#DETERMINE MANUFACTUERE
manufacturer="$(determine_manufacturer "$known_addr")"
manufacturer=${manufacturer:-Unknown}
#PUBLISH PRESENCE METHOD
publish_presence_message \
"id=$known_addr" \
"confidence=0" \
"name=$expected_name" \
"manufacturer=$manufacturer" \
"type=KNOWN_MAC"
#PUBLISH MESSAGE TO RSSI SENSOR
publish_rssi_message \
"$known_addr" \
"-99"
fi
printf "%s\n" "NAME$known_addr|" > main_pipe
done
#SET DONE TO MAIN PIPE
printf "%s\n" "DONE" > main_pipe
#GROUP SCAN FINISHED
$PREF_VERBOSE_LOGGING && log "${GREEN}[CMD-INFO] ${GREEN}**** completed $transition_type scan **** ${NC}"
#PUBLISH END OF COOPERATIVE SCAN
$PREF_MQTT_REPORT_SCAN_MESSAGES && publish_cooperative_scan_message "$transition_type/end"
}
# ----------------------------------------------------------------------------------------
# SCAN TYPE FUNCTIONS
# ----------------------------------------------------------------------------------------
perform_departure_scan () {
#SET SCAN TYPE
local depart_list
depart_list=$(scannable_devices_with_state 1)
#LOCAL SCAN ACTIVE VARIABLE
local scan_active
scan_active=true
#SCAN ACTIVE?
kill -0 "$scan_pid" >/dev/null 2>&1 && scan_active=true || scan_active=false
#ONLY ASSEMBLE IF WE NEED TO SCAN FOR ARRIVAL
if [ "$scan_active" == false ] ; then
#ADD A FLAG TO SCAN FOR
[ -n "$depart_list" ] && printf "%s\n" "BEXP" > main_pipe &
#ONCE THE LIST IS ESTABLISHED, TRIGGER SCAN OF THESE DEVICES IN THE BACKGROUND
perform_complete_scan "$depart_list" "$PREF_DEPART_SCAN_ATTEMPTS" "1" &
disown "$!"
scan_pid=$!
scan_type=1
else
#HERE A DEPART SCAN IS ACTIVE; ENQUEUE ANOTHER DEPART SCAN AFTER DELAY
[ "$scan_type" == "0" ] && sleep 5 && printf "%s\n" "ENQUdepart" > main_pipe &
fi
}
perform_arrival_scan () {
#SET SCAN TYPE
local arrive_list
arrive_list=$(scannable_devices_with_state 0)
#LOCAL SCAN ACTIVE VARIABLE
local scan_active
scan_active=true
#SCAN ACTIVE?
kill -0 "$scan_pid" >/dev/null 2>&1 && scan_active=true || scan_active=false
#ONLY ASSEMBLE IF WE NEED TO SCAN FOR ARRIVAL
if [ "$scan_active" == false ] ; then
#FIRST SCAN IS DEAD
first_arrive_scan=false
#ONCE THE LIST IS ESTABLISHED, TRIGGER SCAN OF THESE DEVICES IN THE BACKGROUND
perform_complete_scan "$arrive_list" "$PREF_ARRIVAL_SCAN_ATTEMPTS" "0" &
disown "$!"
scan_pid=$!
scan_type=0
else
#HERE A DEPART SCAN IS ACTIVE; ENQUEUE ANOTHER DEPART SCAN AFTER DELAY
[ "$scan_type" == "1" ] && sleep 5 && printf "%s\n" "ENQUarrive" > main_pipe &
fi
}
# ----------------------------------------------------------------------------------------
# NAME DETERMINATIONS
# ----------------------------------------------------------------------------------------
determine_name () {
#SET DATA
local address
address="$1"
#RETURN ADDRESS
[ -z "$address" ] && return 0
#ALTERNATIVE ADDRESS
local alternate_address
alternate_address="$2"
alternate_address=${alternate_address:-Unknown}
#IF IS NEW AND IS PUBLIC, SHOULD CHECK FOR NAME
local expected_name
expected_name="${known_public_device_name[$address]}"
#ALTERNATE NAME?
[ -z "$expected_name" ] && expected_name="${known_public_device_name[$alternate_address]}"
#FIND PERMANENT DEVICE NAME OF PUBLIC DEVICE
if [ -z "$expected_name" ]; then
#CHECK CACHE
expected_name=$(grep "$address" < "$base_directory/.public_name_cache" | awk -F "\t" '{print $2}')
#IF CACHE DOES NOT EXIST, TRY TO SCAN
if [ -z "$expected_name" ]; then
#DOES SCAN PROCESS CURRENTLY EXIST?
kill -0 "$scan_pid" >/dev/null 2>&1 && scan_active=true || scan_active=false
#ONLY SCAN IF WE ARE NOT OTHERWISE SCANNING; NAME FOR THIS DEVICE IS NOT IMPORTANT
if [ "$scan_active" == false ] ; then
#FIND NAME OF THIS DEVICE
expected_name=$(hcitool -i "$PREF_HCI_DEVICE" name "$address" 2>/dev/null)
#IS THE EXPECTED NAME BLANK?
if [ -n "$expected_name" ]; then
#ADD TO SESSION ARRAY
known_public_device_name[$address]="$expected_name"
#ADD TO CACHE
echo "$address $expected_name" >> .public_name_cache
else
#ADD TO CACHE TO PREVENT RE-SCANNING
echo "$address Undeterminable" >> .public_name_cache
fi
fi
else
#WE HAVE A CACHED NAME, ADD IT BACK TO THE PUBLIC DEVICE ARRAY
known_public_device_name[$address]="$expected_name"
fi
fi
printf "%s\n" "$expected_name"
}
# ----------------------------------------------------------------------------------------
# BACKGROUND PROCESSES
# ----------------------------------------------------------------------------------------
#SET LOG
(rm .pids) 2>&1 1>/dev/null
log_listener &
listener_pid="$!"
echo "> log listener pid = $listener_pid" >> .pids
$PREF_VERBOSE_LOGGING && echo "> log listener pid = $listener_pid"
disown "$listener_pid"
btle_scanner &
btle_scan_pid="$!"
echo "> btle scan pid = $btle_scan_pid" >> .pids
$PREF_VERBOSE_LOGGING && echo "> btle scan pid = $btle_scan_pid"
disown "$btle_scan_pid"
btle_text_listener &
btle_text_pid="$!"
echo "> btle text pid = $btle_text_pid" >> .pids
$PREF_VERBOSE_LOGGING && echo "> btle text pid = $btle_text_pid"
disown "$btle_text_pid"
btle_listener &
btle_listener_pid="$!"
echo "> btle listener pid = $btle_listener_pid" >> .pids
$PREF_VERBOSE_LOGGING && echo "> btle listener pid = $btle_listener_pid"
disown "$btle_listener_pid"
mqtt_listener &
mqtt_pid="$!"
echo "> mqtt listener pid = $mqtt_pid" >> .pids
$PREF_VERBOSE_LOGGING && echo "> mqtt listener pid = $mqtt_pid"
disown "$mqtt_pid"
btle_packet_listener &
btle_packet_listener_pid="$!"
echo "> packet listener pid = $btle_packet_listener_pid" >> .pids
$PREF_VERBOSE_LOGGING && echo "> packet listener pid = $btle_packet_listener_pid"
disown "$btle_packet_listener_pid"
beacon_database_expiration_trigger &
beacon_database_expiration_trigger_pid="$!"
echo "> beacon database time trigger pid = $beacon_database_expiration_trigger_pid" >> .pids
$PREF_VERBOSE_LOGGING && echo "> beacon database time trigger pid = $beacon_database_expiration_trigger_pid"
disown "$beacon_database_expiration_trigger_pid"
# ----------------------------------------------------------------------------------------
# MAIN LOOPS. INFINITE LOOP CONTINUES, NAMED PIPE IS READ INTO SECONDARY LOOP
# ----------------------------------------------------------------------------------------
#MAIN LOOP
while true; do
#READ FROM THE MAIN PIPE
while read -r event; do
#DIVIDE EVENT MESSAGE INTO TYPE AND DATA
cmd="${event:0:4}"
data="${event:4}"
timestamp=$(date +%s)
uptime=$((timestamp - now))
#FLAGS TO DETERMINE FRESHNESS OF DATA
is_new=false
should_update=false
did_change=false
is_apple_beacon=false
#CLEAR DATA IN NONLOCAL VARS
manufacturer="unknown"
current_associated_beacon_mac_address=""
name=""
expected_name=""
mac=""
rssi=""
adv_data=""
resolvable=""
pdu_header=""
power=""
major=""
minor=""
uuid=""
beacon_type="GENERIC_BEACON"
beacon_last_seen=""
key_last_seen=""
uuid_reference=""
last_appearance=""
beacon_uuid_key=""
instruction_timestamp=""
instruction_delay=""
observation_made=false
most_recent_beacon=""
observed_max_advertisement_interval=""
temp_observation=""
device_state=""
#PROCEED BASED ON COMMAND TYPE
if [ "$cmd" == "ENQU" ] && [ "$uptime" -gt "$PREF_STARTUP_SETTLE_TIME" ]; then
#WE HAVE AN ENQUEUED OPPOSITE SCAN; NEED TO TRIGGER THAT SCAN
if [ "$data" == "arrive" ]; then
#LOG
$PREF_VERBOSE_LOGGING && log "${GREEN}[ENQ-ARR] ${NC}Enqueued arrival scan triggered.${NC}"
#WAIT 5 SECONDS
sleep 5
#TRIGGER
perform_arrival_scan
elif [ "$data" == "depart" ]; then
#LOG
$PREF_VERBOSE_LOGGING && log "${GREEN}[ENQ-DEP] ${NC}Enqueued depart scan triggered.${NC}"
#WAIT 5 SECONDS
sleep 5
#TRIGGER
perform_departure_scan
fi
elif [ "$cmd" == "RAND" ]; then
#PARSE RECEIVED DATA
mac=$(echo "$data" | awk -F "|" '{print $1}')
pdu_header=$(echo "$data" | awk -F "|" '{print $2}')
name=$(echo "$data" | awk -F "|" '{print $3}')
rssi=$(echo "$data" | awk -F "|" '{print $4}')
adv_data=$(echo "$data" | awk -F "|" '{print $5}')
manufacturer=$(echo "$data" | awk -F "|" '{print $6}')
device_type=$(echo "$data" | awk -F "|" '{print $7}')
flags=$(echo "$data" | awk -F "|" '{print $8}')
oem_data=$(echo "$data" | awk -F "|" '{print $9}')
instruction_timestamp=$(echo "$data" | awk -F "|" '{print $10}')
resolvable=$(echo "$data" | awk -F "|" '{print $11}')
hex_data=$(echo "$data" | awk -F "|" '{print $12}')
#FIND DELAY BASED ON INSTRUCTINO TIMESTAMP
instruction_delay=$((timestamp - instruction_timestamp))
#GET LAST RSSI
rssi_latest="${rssi_log[$mac]}"
#IF WE HAVE A NAME; UNSEAT FROM RANDOM AND ADD TO STATIC
#THIS IS A BIT OF A FUDGE, A RANDOM DEVICE WITH A LOCAL
#NAME IS TRACKABLE, SO IT'S UNLIKELY THAT ANY CONSUMER
#ELECTRONIC DEVICE OR CELL PHONE IS ASSOCIATED WITH THIS
#ADDRESS. CONSIDER THE ADDRESS AS A STATIC ADDRESS
#ALSO NEED TO CHECK WHETHER THE RANDOM BROADCAST
#IS INCLUDED IN THE KNOWN DEVICES LOG...
if [ -n "${public_device_log[$mac]}" ]; then
#GET INTERVAL SINCE LAST SEEN
last_appearance=${public_device_log[$mac]:-$timestamp}
if [ "$observation_made" == false ]; then
observation_made=true
temp_observation="" && temp_observation=$((((timestamp - last_appearance - 1 + PREF_ADVERTISEMENT_OBSERVED_INTERVAL_STEP) / PREF_ADVERTISEMENT_OBSERVED_INTERVAL_STEP) * PREF_ADVERTISEMENT_OBSERVED_INTERVAL_STEP))
[ "$temp_observation" -gt "${advertisement_interval_observation[$mac]:-0}" ] && [ "$temp_observation" -gt "0" ] && [ "$temp_observation" -lt "300" ] && advertisement_interval_observation[$mac]=$temp_observation
fi
#IS THIS A NEW STATIC DEVICE?
public_device_log[$mac]="$timestamp"
[ -n "$rssi" ] && rssi_log[$mac]="$rssi"
cmd="PUBL"
#BEACON TYPE
beacon_type="GENERIC_BEACON_PUBLIC"
else
#DO WE HAVE A NAME FOR THIS MAC ADDRESSS?
#THAT IS NOT IN THE PUBLIC DEVICE ARRAY?
expected_name="${known_public_device_name[$mac]}"
#DOES THIS DEVICE HAVE A NAME?
if [ -n "$name" ] || [ -n "$expected_name" ]; then
#RESET COMMAND
cmd="PUBL"
unset "random_device_log[$mac]"
#BEACON TYPE
beacon_type="GENERIC_BEACON_RANDOM"