-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathbbload
executable file
·85 lines (68 loc) · 1.92 KB
/
bbload
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
#!/bin/bash
mac_address="$1"
file="$2"
handle="0x0021"
function error() {
cat <<- EOH
$1
Usage: $0 <MAC address> <file>
This tool will upload the file to the BlueBasic device that has that MAC address
Need gatttool installed
EOH
exit 1
}
function upload_progress() {
progress_character='='
progress_length=20
progress_step=$((100/progress_length))
if (($1 >= progress_step)); then
percent_bar="$(head -c "$(($1/progress_step))" < /dev/zero | tr '\0' $progress_character)"
percent_bar="${percent_bar}$(printf "%$((progress_length-($1/progress_step)))s")"
else
percent_bar="$(printf "%${progress_length}s")"
fi
printf "\rUploading... [%s] (%s%%)" "$percent_bar" "$1"
}
function load() {
hexdump=""
chunks=()
eol=13
while read line; do
line=$(printf '%s\r' "$line" | xxd -p | tr -d '\n')
hexdump+="$line"
done < $file
length=(${#hexdump})
for ((chunk=0; chunk<length; )); do
byte=0
buffer=""
for ((count=0; ((chunk<length && byte != eol && count < 20)); count++, chunk+=2)); do
byte=("0x${hexdump:chunk:2}")
buffer+="${hexdump:chunk:2}"
done
chunks+=("$buffer")
done
upload_progress 0
for chunk in ${!chunks[@]}; do
result="$(gatttool -i hci0 \
-a "$handle" \
-b "$mac_address" \
-n "${chunks[chunk]}" \
--char-write-req 2>&1)"
if [[ "$result" == "Characteristic value was written successfully" ]]; then
percentage=$(bc <<< "scale=2; ($((chunk+1))/${#chunks[@]})*100")
upload_progress "${percentage%.*}"
else
printf "\n%s\n" "$result"
exit 1
fi
done
printf "\n"
}
if ! [[ "$mac_address" =~ ^([a-fA-F0-9]{2}:){5}[a-zA-Z0-9]{2}$ ]]; then
error "Wrong MAC address! Example: AA:BB:CC:DD:EE:FF"
elif ! [[ -r $file && -f $file ]]; then
error "No such file!"
else
printf "using handle %s\n" "$handle"
load
fi