-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy paththermmode-unifi.sh
executable file
·652 lines (554 loc) · 15.4 KB
/
thermmode-unifi.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
#!/bin/bash
##############################################################################
# Script Name : thermmode-unifi
# Description : Netatmo smart thermostat mode by connected UniFi clients
# Args : <config_file>
# Author : Pieter Smets
# E-mail : mail@pietersmets.be
##############################################################################
# exit when any command fails
set -e
#
# Some usefull links to documentation to create this script
#
# https://ubntwiki.com/products/software/unifi-controller/api
# https://gist.github.com/jcconnell/0ee6c9d5b25c572863e8ffa0a144e54b
# https://github.com/NickWaterton/Unifi-websocket-interface/blob/master/controller.py
# https://dev.netatmo.com/apidocumentation/energy
# Name of the script
SCRIPT=$( basename "$0" )
# Current version from git
VERSION="v0.4.1"
#-------------------------------------------------------------------------------
#
# Function definitions
#
#-------------------------------------------------------------------------------
function usage {
#
# Message to display for usage and help
#
local txt=(
"UniFi client montoring for geolocation-like functionality of the Netatmo Smart Thermostat."
""
"Usage: $SCRIPT <config_file>"
""
"Options:"
" -C, --config Print a demo configuration file with all variables"
" -h, --help Print help"
" -m, --mode Print the previous unifi mode"
" -f, --force Ignore the stored unifi mode and force syncing the thermostat"
" -v, --verbose Make the operation more talkative"
" -V, --version Show version number and quit"
)
printf "%s\n" "${txt[@]}"
exit 0
}
function badUsage {
#
# Message to display when bad usage
#
local message="$1"
local txt=(
"For an overview of the command, execute:"
"$SCRIPT --help"
)
[[ $message ]] && printf "$message\n"
printf "%s\n" "${txt[@]}"
exit -1
}
function version
{
#
# Message to display for version.
#
printf "$VERSION\n"
exit 0
}
function config
{
#
# Message to display for version.
#
local txt=(
"### thermmode-unifi configuration file."
""
"# The commented out lines are the configuration field and the default value used."
""
"###"
"### UniFi controller configuration"
"###"
""
"# UniFi controller address"
"UNIFI_ADDRESS = https://url_or_ip_of_your_controller"
""
"# UniFi sitename."
"# UNIFI_SITENAME = default"
""
"# UniFi controller username and password (preferably a local account with read-only rights)"
"UNIFI_USERNAME = ..."
"UNIFI_PASSWORD = ..."
""
"# List of client mac addresses (space separated)"
"UNIFI_CLIENTS = aa:aa:aa:aa:aa:aa bb:bb:bb:bb:bb:bb cc:cc:cc:cc:cc:cc"
""
"# Clients last seen threshold to set thermmode=away"
"# UNIFI_CLIENTS_OFFLINE_SECONDS = 600"
"# UNIFI_CLIENTS_IGNORE_SECONDS = 1800"
""
"###"
"### Netatmo connect configuration"
"###"
""
"# A personal netatmo connect app registered to your username is required."
"# Create your app at https://dev.netatmo.com/apps."
"# The app is needed for authentication to obtain an Oauth2 Bearer token from"
"# your username and password."
""
"# Netatmo connect app technical parameters: client id and secret."
"NETATMO_CLIENT_ID = ..."
"NETATMO_CLIENT_SECRET = ..."
""
"# Netatmo access token"
"NETATMO_ACCESS_TOKEN = ..."
"NETATMO_REFRESH_TOKEN = ..."
""
"# Netamo home id (optional, defaults to the first of your homes)"
"# NETATMO_HOME_ID = ..."
)
printf "%s\n" "${txt[@]}"
exit 0
}
function parse_config { # parse_config file.cfg var_name1 var_name2
#
# This function will read key=value pairs from a configfile.
#
# After invoking 'readconfig somefile.cfg my_var',
# you can 'echo "$my_var"' in your script.
#
# ONLY those keys you give as args to the function will be evaluated.
# This is a safeguard against unexpected items in the file.
#
# ref: https://stackoverflow.com/a/20815951
#
# The config-file could look like this:
#-------------------------------------------------------------------------------
# This is my config-file
# ----------------------
# Everything that is not a key=value pair will be ignored. Including this line.
# DO NOT use comments after a key-value pair!
# They will be assigend to your key otherwise.
#
# singlequotes = 'are supported'
# doublequotes = "are supported"
# but = they are optional
#
# this=works
#
# # key = value this will be ignored
#
#-------------------------------------------------------------------------------
shopt -s extglob # needed the "one of these"-match below
local configfile="${1?No configuration file given}"
local keylist="${@:2}" # positional parameters 2 and following
local lhs rhs
if [[ ! -f "$configfile" ]];
then
>&2 echo "\"$configfile\" is not a file!"
exit 1
fi
if [[ ! -r "$configfile" ]];
then
>&2 echo "\"$configfile\" is not readable!"
exit 1
fi
keylist="${keylist// /|}" # this will generate a regex 'one of these'
# lhs : "left hand side" : Everything left of the '='
# rhs : "right hand side": Everything right of the '='
#
# "lhs" will hold the name of the key you want to read.
# The value of "rhs" will be assigned to that key.
while IFS='= ' read -r lhs rhs
do
# IF lhs in keylist
# AND rhs not empty
if [[ "$lhs" =~ ^($keylist)$ ]] && [[ -n $rhs ]];
then
rhs="${rhs%\"*}" # Del opening string quotes
rhs="${rhs#\"*}" # Del closing string quotes
rhs="${rhs%\'*}" # Del opening string quotes
rhs="${rhs#\'*}" # Del closing string quotes
eval $lhs=\"$rhs\" # The magic happens here
fi
# tr used as a safeguard against dos line endings
done < $configfile
# done <<< $( tr -d '\r' < $configfile )
shopt -u extglob # Switching it back off after use
}
function check_config { # check_config var1 var2 ...
#
# Check if the provided variables are set
#
local var
for var in "${@}";
do
if [ -z "${!var}" ];
then
echo "Error: variable $var is empty!"
exit 1
fi
done
}
function unifi_curl {
#
# UI curl alias with cookie
#
/usr/bin/curl \
--silent \
--show-error \
--cookie ${UNIFI_COOKIE} \
--cookie-jar ${UNIFI_COOKIE} \
--insecure \
"$@"
}
function unifi_login {
#
# Login to the configured UI controller
#
unifi_curl \
--request POST \
--header "Content-Type: application/json" \
--data "{\"password\":\"$UNIFI_PASSWORD\",\"username\":\"$UNIFI_USERNAME\"}" \
$UNIFI_ADDRESS:443/api/auth/login > /dev/null
}
function unifi_logout {
#
# Logout from the configured UI controller
#
unifi_curl ${UNIFI_API}/logout > /dev/null
}
function unifi_active_clients {
#
# Get a list of all active clients on the site
#
unifi_curl ${UNIFI_SITE_API}/stat/sta --compressed
}
function unifi_client {
#
# Get client details on the site
#
local mac=$1
unifi_curl ${UNIFI_SITE_API}/stat/user/${mac} --compressed
}
function netatmo_access_token {
#
# Netatmo Connect oauth2 refresh access token
#
response=$(/usr/bin/curl \
--silent \
--show-error \
--header "accept: application/json" \
--data grant_type=refresh_token \
--data client_id=$NETATMO_CLIENT_ID \
--data client_secret=$NETATMO_CLIENT_SECRET \
--data refresh_token=$NETATMO_REFRESH_TOKEN \
https://api.netatmo.com/oauth2/token)
if echo $response | grep error > /dev/null;
then
echo $response && exit 1
fi
verbose $response
NETATMO_ACCESS_TOKEN_="${response##*\"access_token\":\"}"
NETATMO_ACCESS_TOKEN_="${NETATMO_ACCESS_TOKEN_%%\"*}"
if [ "$NETATMO_ACCESS_TOKEN" != "$NETATMO_ACCESS_TOKEN_" ];
then
sed -i 's#'$NETATMO_ACCESS_TOKEN'#'$NETATMO_ACCESS_TOKEN_'#g' $1
NETATMO_ACCESS_TOKEN=$NETATMO_ACCESS_TOKEN_
verbose "** Netatmo access token updated **"
fi
NETATMO_REFRESH_TOKEN_="${response##*\"refresh_token\":\"}"
NETATMO_REFRESH_TOKEN_="${NETATMO_REFRESH_TOKEN_%%\"*}"
if [ "$NETATMO_REFRESH_TOKEN" != "$NETATMO_REFRESH_TOKEN_" ];
then
sed -i 's#'$NETATMO_REFRESH_TOKEN'#'$NETATMO_REFRESH_TOKEN_'#g' $1
NETATMO_REFRESH_TOKEN=$NETATMO_REFRESH_TOKEN_
verbose "** Netatmo refresh token updated **"
fi
}
function netatmo_curl {
#
# Netatmo Connect curl alias
#
if [ "$NETATMO_ACCESS_TOKEN" == "" ];
then
echo "error: NETATMO_ACCESS_TOKEN is empty"
exit 1
fi
response=$(/usr/bin/curl \
--silent \
--show-error \
--header "accept: application/json" \
--header "Authorization: Bearer $NETATMO_ACCESS_TOKEN" \
"$@")
echo $response
if echo $response | grep error > /dev/null;
then
exit 1
fi
}
function netatmo_homesdata {
#
# Get the homesdata from Netatmo Connect
#
netatmo_curl \
--request GET \
${NETATMO_API}/homesdata
}
function netatmo_gethomeid {
#
# Get the first home id from Netatmo Connect
#
local resp="$(netatmo_homesdata || echo "error")"
if ! echo $resp | grep error > /dev/null;
then
resp="${resp##*\"homes\":[\{\"id\":\"}"
resp="${resp%%\"*}"
fi
echo $resp
}
function netatmo_homestatus {
#
# Get the homestatus from Netatmo energy
#
netatmo_curl \
--request GET \
--data home_id=$NETATMO_HOME_ID \
${NETATMO_API}/homestatus
}
function netatmo_isthermmode {
#
# Verify if the current thermostat mode is schedule|away|hg
#
case "$1" in
schedule|away|hg)
;;
*)
echo "thermmode status should be any of 'schedule|away|hg'!"
exit 1
;;
esac
netatmo_homestatus | grep "\"therm_setpoint_mode\":\"$1\""
}
function netatmo_getthermmode {
#
# Get the thermostat mode
#
local resp="$(netatmo_homestatus || echo "error")"
if ! echo $resp | grep error > /dev/null;
then
resp="${resp##*\"therm_setpoint_mode\":\"}"
resp="${resp%%\"*}"
fi
echo $resp
}
function netatmo_setthermmode {
#
# Set the thermostat mode
#
case "$1" in
schedule|away|hg)
;;
*)
echo "thermmode status should be any of 'schedule|away|hg'!"
exit 1
;;
esac
netatmo_curl \
--request POST \
--data home_id=$NETATMO_HOME_ID \
--data mode=$1 \
${NETATMO_API}/setthermmode
}
function verbose {
#
# Talkative mode: echo only when --verbose
#
if [ $DO_VERB -eq 1 ];
then
echo "$@"
fi
}
#-------------------------------------------------------------------------------
#
# Previous run thermmode status
#
#-------------------------------------------------------------------------------
touch $HOME/.thermmode-unifi.mode
previous_mode=$(cat $HOME/.thermmode-unifi.mode)
#-------------------------------------------------------------------------------
#
# Parse arguments and configuration file
#
#-------------------------------------------------------------------------------
#
# Parse options
#
DO_VERB=0
while (( $# ));
do
case "$1" in
-c|--config) config
;;
-h|--help) usage
;;
-m|--mode) echo "unifi_mode=$previous_mode" && exit 0
;;
-f|--force) previous_mode="__NONE__"
;;
-v|--verbose) DO_VERB=1
;;
-V|--version) version
;;
*) break
esac
shift
done
#
# Check arguments
#
if (($# > 1 ));
then
badUsage "Illegal number of arguments"
fi
#
# Set UNIFI and NETATMO variables
#
# Initialize defaults
UNIFI_SITENAME="${UNIFI_SITENAME:-default}"
UNIFI_CLIENTS_OFFLINE_SECONDS=${UNIFI_CLIENTS_OFFLINE_SECONDS:-600}
UNIFI_CLIENTS_IGNORE_SECONDS=${UNIFI_CLIENTS_IGNORE_SECONDS:-1800}
# Parse config file
if (($# == 1 ));
then
parse_config $1 \
UNIFI_ADDRESS UNIFI_USERNAME UNIFI_PASSWORD UNIFI_SITENAME \
UNIFI_CLIENTS UNIFI_CLIENTS_OFFLINE_SECONDS UNIFI_CLIENTS_IGNORE_SECONDS \
NETATMO_CLIENT_ID NETATMO_CLIENT_SECRET NETATMO_ACCESS_TOKEN NETATMO_REFRESH_TOKEN \
NETATMO_HOME_ID
fi
# Check if mandatory variables are set
check_config UNIFI_ADDRESS UNIFI_USERNAME UNIFI_PASSWORD UNIFI_SITENAME UNIFI_CLIENTS
check_config NETATMO_CLIENT_ID NETATMO_CLIENT_SECRET NETATMO_ACCESS_TOKEN NETATMO_REFRESH_TOKEN
# Construct derived variables
UNIFI_COOKIE=$(mktemp)
UNIFI_API="${UNIFI_ADDRESS}/proxy/network/api"
UNIFI_SITE_API="${UNIFI_API}/s/${UNIFI_SITENAME}"
NETATMO_API="https://api.netatmo.com/api"
#-------------------------------------------------------------------------------
#
# Netatmo Connect access token and home id
#
#-------------------------------------------------------------------------------
netatmo_access_token $1
if [ "$NETATMO_HOME_ID" == "" ];
then
NETATMO_HOME_ID=$(netatmo_gethomeid)
fi
verbose "Start $0 for home id $NETATMO_HOME_ID"
#-------------------------------------------------------------------------------
#
# Client verification
#
#-------------------------------------------------------------------------------
now=$(date +%s)
# init states
ignore=1
offline=1
# login to unifi controller
unifi_login
# verify client activity
for CLIENT in $UNIFI_CLIENTS;
do
# Get client data
CLIENT_DATA="$(unifi_client $CLIENT)"
# Check if client is configured
if ! echo $CLIENT_DATA | grep "\"meta\":{\"rc\":\"ok\"}" >/dev/null 2>&1;
then
verbose "$CLIENT is not a configured client."
continue
fi
# echo $CLIENT_DATA
# Parse client data
hostname="${CLIENT_DATA##*\"hostname\":\"}"
hostname="${hostname%%\",*}"
last_seen="${CLIENT_DATA##*\"last_seen\":}"
last_seen="${last_seen%%,*}"
elapsed=$(($now - $last_seen))
# echo "$now $last_seen"
verbose "$CLIENT $hostname last seen $elapsed seconds ago."
if [ $elapsed -lt $UNIFI_CLIENTS_OFFLINE_SECONDS ];
then
offline=0
ignore=0
elif [ $elapsed -lt $UNIFI_CLIENTS_IGNORE_SECONDS ];
then
ignore=0
fi
done
# logout from unifi controller
unifi_logout
# set mode from states
if [ $offline -eq 0 ] && [ $ignore -eq 0 ];
then
unifi_mode='active'
elif [ $offline -eq 1 ] && [ $ignore -eq 0 ];
then
unifi_mode='offline'
else
unifi_mode='ignore'
fi
# compare current with previous mode
if [ "$previous_mode" == "$unifi_mode" ];
then
verbose "** No change in thermostat mode **"
exit 0
fi
echo "$unifi_mode" > $HOME/.thermmode-unifi.mode
#-------------------------------------------------------------------------------
#
# Set thermostat mode
#
#-------------------------------------------------------------------------------
resp=''
if [ "$unifi_mode" != "ignore" ];
then
therm_mode="$(netatmo_getthermmode || echo "error")"
if echo $therm_mode | grep error > /dev/null;
then
echo "** $therm_mode ** "
exit 1
elif [ "$therm_mode" == "hg" ];
then
verbose "** Thermostat is in frost guard mode ** "
exit 0
else
verbose "** Thermostat mode = $therm_mode **"
fi
if [ "$unifi_mode" == "offline" ] && [ "$therm_mode" == "schedule" ];
then
echo "** Set thermostat mode to away **"
resp=$(netatmo_setthermmode 'away')
elif [ "$unifi_mode" == "active" ] && [ "$therm_mode" == "away" ];
then
echo "** Set thermostat mode to schedule **"
resp=$(netatmo_setthermmode 'schedule')
else
verbose "** No need to change the thermostat mode **"
fi
if echo $resp | grep error > /dev/null;
then
echo $resp
exit 1
fi
fi
exit 0