PoSHive.ps1

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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
Enum HeatingMode {
    <# Defines the heating modes that can be set. #>
    SCHEDULE
    MANUAL
    OFF
}

Enum ActivePlugMode {
    <# Defines the modes that can be set on an active plug. #>
    SCHEDULE
    MANUAL
}

Enum BoostTime {
    <# Defines accepted boost durations in hours. #>
    HALF
    ONE
    TWO
    THREE
    FOUR
    FIVE
    SIX
}

Class Hive {

    ##############
    # PROPERTIES #
    ##############

    [uri]$ApiUrl = "https://beekeeper.hivehome.com/1.0/global/login" # This is the global login URL - changes after login.
    [ValidateLength(4,100)][string] $Username
    [securestring] $Password
    [string] $ApiSessionId
    hidden [string] $Agent = 'PoSHive 2.1.3 - github.com-lwsrbrts-PoSHive'
    [psobject] $User
    [psobject] $Devices
    [psobject] $Products
    hidden [hashtable] $Headers = @{
        'Accept' = '*/*'
        'User-Agent' = $this.Agent
        'Content-Type' = 'application/json'
    }
    
    ###############
    # CONSTRUCTOR #
    ###############

    Hive([string] $Username, [string] $Password) {
        $this.Username = $Username
        $this.Password = ConvertTo-SecureString -String $Password -AsPlainText -Force
    }

    ###########
    # METHODS #
    ###########

    # Convert Unix time in milliseconds to local datetime object.
    hidden [datetime] ConvertUnixTime([long] $Milliseconds) {
        Return [System.DateTimeOffset]::FromUnixTimeMilliseconds($Milliseconds).LocalDateTime
    }

    # Convert date time to unix time in milliseconds.
    hidden [long] DateTimeToUnixTimestamp ([datetime] $dateTime) {
        Return ($dateTime.ToUniversalTime() - [datetime]::new(1970, 1, 1, 0, 0, 0, 0, [DateTimeKind]::Utc)).TotalMilliseconds
    }

    # Decrypt a securestring back to plain text.
    hidden [string] DecryptSecureString ([System.Security.SecureString] $SecureString) {
        $PlainString = [Runtime.InteropServices.Marshal]::PtrToStringBSTR([Runtime.InteropServices.Marshal]::SecureStringToBSTR($secureString))
        Return $PlainString
    }

    # Return errors and terminate execution
    <#
    hidden [void] ReturnError([System.Management.Automation.ErrorRecord] $e) {
        $sr = [System.IO.StreamReader]::new($e.Exception.Response.GetResponseStream())
        $sr.BaseStream.Position = 0
        $r = ConvertFrom-Json ($sr.ReadToEnd())
        Write-Error "An error occurred in the execution of the request:`r`nError Code:`t$($r.errors.code)`r`nError Title:`t$($r.errors.title)" -ErrorAction Stop
    }
    #>


    # Return errors and terminate execution
    hidden [void] ReturnError([string] $e) {
        Write-Error $e -ErrorAction Stop
    }

    # Login - could do this in the constructor but makes sense to have it as a separate method. May only want weather!
    [void] Login () {
        If ($this.ApiSessionId) {$this.ReturnError("You are already logged in.")}

        $Settings = [psobject]@{
            username = $this.Username
            password = ($this.DecryptSecureString($this.Password))
            devices = $true
            products = $true
        }

        Try {
            $Response = Invoke-RestMethod -Method Post -Uri $this.ApiUrl -Body (ConvertTo-Json $Settings) -Headers $this.Headers -ErrorAction Stop
            $this.ApiSessionId = $Response.token
            $this.Headers.Add('Authorization', $this.ApiSessionId)
            $this.ApiUrl = $Response.platform.endpoint
            $this.Devices = $Response.devices
            $this.Products = $Response.products
            $this.User = $Response.user
        }
        Catch {
            $this.ReturnError($_)
        }
    }

    # Log out - essentially deletes the ApiSession from the API and nulls the ApiSessionId
    [psobject] Logout() {
        If (-not $this.ApiSessionId) {$this.ReturnError("No ApiSessionId - must log in first.")}
        Try {
            $Response = Invoke-RestMethod -Method Delete -Uri "$($this.ApiUrl)/auth/logout" -Headers $this.Headers -ErrorAction Stop
            Return "Logged out successfully."
        }
        Catch [System.Net.WebException] {
            If ($_.Exception.Response.StatusCode.value__ -eq 401) {
                $Message = "Your session was not found on the remote server but your local session was reset.`n$($_.Exception.Message)"
            }
            Else { $Message = "An error occurred when communicating with the remote server. Your session was reset.`n$($_.Exception.Message)" }
            Return $Message 
        }
        Catch {
            $Message = "An error occurred when communicating with the remote server. Your session was reset.`n$($_.Exception.Message)"
            Return $Message
        }
        Finally {
            $this.ApiSessionId = $null
            $this.Headers.Remove('Authorization')
            $this.ApiUrl = "https://beekeeper.hivehome.com/1.0/global/login" # Reset the login URL.
        }
    }

    <#
        Get products data.
        Still exposed as a usable method in the class but acts primarily
        as a helper method to keep the $this.Products variable fresh. Is usually called
        before any setting method that includes logic or is dependent on the state
        of an attribute.
    #>

    [psobject] GetProducts() {
        If (-not $this.ApiSessionId) {$this.ReturnError("No ApiSessionId - must log in first.")}
        Try {
            $Response = Invoke-RestMethod -Method Get -Uri "$($this.ApiUrl)/products?after=" -Headers $this.Headers -ErrorAction Stop
            Return $Response
        }
        Catch {
            $this.ReturnError($_)
            Return $null
        }
    }

    <#
        Get devices data.
        Still exposed as a usable method in the class but acts primarily
        as a helper method to keep the $this.Devices variable fresh. Is usually called
        before any setting method that includes logic or is dependent on the state
        of an attribute.
    #>

    [psobject] GetDevices() {
        If (-not $this.ApiSessionId) {$this.ReturnError("No ApiSessionId - must log in first.")}
        Try {
            $Response = Invoke-RestMethod -Method Get -Uri "$($this.ApiUrl)/devices" -Headers $this.Headers -ErrorAction Stop
            Return $Response
        }
        Catch {
            $this.ReturnError($_)
            Return $null
        }
    }

    <#
        Does what it says on the tin. Returns the currently reported temperature
        value from the thermostat in a single heating zone system.
        Provide $true to get a formatted value: eg. 21.1C
        Provide $false to get a simple decimal: eg. 21.1
    #>

    [psobject] GetTemperature([bool] $FormattedValue) {
        If (-not $this.ApiSessionId) {$this.ReturnError("No ApiSessionId - must log in first.")}
        Try {
            $this.Products = $this.GetProducts()
            $this.Devices = $this.GetDevices()

            If (($this.Products | Where-Object {$_.type -eq "heating"}).Count -is [int]) { $this.ReturnError('There is more than one product of type "heating". Please identify which heating zone by providing the zone name.') }

            $HeatingNode = $this.Products | Where-Object {$_.type -eq "heating"}

            $Temperature = [Math]::Round([double]$HeatingNode.props.temperature, 1)

            If ($FormattedValue) {Return "$($Temperature.ToString())$([char] 176 )C"}
            Else {Return $Temperature}
        }
        Catch {
            $this.ReturnError($_)
            Return $null
        }
    }

    <#
        Does what it says on the tin. Returns the currently reported temperature
        value from the specified zone.
        Provide $true to get a formatted value: eg. 21.1C
        Provide $false to get a simple decimal: eg. 21.1
    #>

    [psobject] GetTemperature([string] $ZoneName, [bool] $FormattedValue) {
        If (-not $this.ApiSessionId) {$this.ReturnError("No ApiSessionId - must log in first.")}
        Try {
            $this.Products = $this.GetProducts()
            $this.Devices = $this.GetDevices()

            If (($this.Products | Where-Object {$_.type -eq "heating" -and $_.state.name -eq $ZoneName}).Count -is [int]) { $this.ReturnError("No heating zones matching the name provided: `"$ZoneName`" were found.") }
            
            # Find out the correct node to send the command to. Only the first heating node returned.
            $HeatingNode = $this.Products | Where-Object {$_.type -eq "heating" -and $_.state.name -eq $ZoneName}

            $Temperature = [Math]::Round([double]$HeatingNode.props.temperature, 1)

            If ($FormattedValue) {Return "$($Temperature.ToString())$([char] 176 )C"}
            Else {Return $Temperature}
        }
        Catch {
            $this.ReturnError($_)
            Return $null
        }
    }

    <#
        Sets the heating mode to one of the [HeatingMode] enum values. ie.
        SCHEDULE, MANUAL, OFF. $this.Products and $this.Devices is always refreshed prior to execution.
        This method does not identify the Thermostat on which to set the mode and is suitable only
        single zone heating systems. For multi-zone use the overload and define the zone name as well.
    #>

    [psobject] SetHeatingMode([HeatingMode] $Mode) {
        If (-not $this.ApiSessionId) {$this.ReturnError("No ApiSessionId - must log in first.")}

        # Update nodes
        $this.Products = $this.GetProducts()
        $this.Devices = $this.GetDevices()

        If (($this.Products | Where-Object {$_.type -eq "heating"}).Count -is [int]) { $this.ReturnError('There is more than one product of type "heating". Please identify which heating zone by providing the zone name.') }
        
        # Find out the correct node to send the temp to. Only the first Thermostat we find!
        $Thermostat = $this.Products | Where-Object {$_.type -eq "heating"} | Select-Object -First 1

        $Settings = [psobject]@{
            mode = $Mode.ToString()
        }
        If ($Mode -eq 'MANUAL') { $Settings.Add('target',20) }

        Try {
            $Response = Invoke-RestMethod -Method Post -Uri "$($this.ApiUrl)/nodes/heating/$($Thermostat.id)" -Headers $this.Headers -Body (ConvertTo-Json $Settings -Depth 99 -Compress)
            Return "Heating mode set to $($Mode.ToString()) successfully."
        }
        Catch {
            $this.ReturnError($_)
            Return $null
        }
    }

    <#
        Sets the heating mode to one of the [HeatingMode] enum values. ie.
        SCHEDULE, MANUAL, OFF. $this.Products and $this.Devices is always refreshed prior to execution.
        This method identifies the thermostat/programmer to change by the zone name and it does support multi-zones.
    #>

    [psobject] SetHeatingMode([string] $ZoneName, [HeatingMode] $Mode) {
        If (-not $this.ApiSessionId) {$this.ReturnError("No ApiSessionId - must log in first.")}

        # Update nodes
        $this.Products = $this.GetProducts()
        $this.Devices = $this.GetDevices()

        If (($this.Products | Where-Object {$_.type -eq "heating" -and $_.state.name -eq $ZoneName}).Count -is [int]) { $this.ReturnError("No heating zones matching the name provided: `"$ZoneName`" were found.") }
        
        # Find out the correct node to send the command to by using its name.
        $Thermostat = $this.Products | Where-Object {$_.type -eq "heating" -and $_.state.name -eq $ZoneName}

        $Settings = [psobject]@{
            mode = $Mode.ToString()
        }
        If ($Mode -eq 'MANUAL') { $Settings.Add('target',20) }

        Try {
            $Response = Invoke-RestMethod -Method Post -Uri "$($this.ApiUrl)/nodes/heating/$($Thermostat.id)" -Headers $this.Headers -Body (ConvertTo-Json $Settings -Depth 99 -Compress)
            Return "Heating mode set to $($Mode.ToString()) successfully."
        }
        Catch {
            $this.ReturnError($_)
            Return $null
        }
    }

    <#
        Sets the temperature value on the first thermostat device in the system.
        $this.Products and $this.Devices is always refreshed prior to execution.
    #>

    [psobject] SetTemperature([double] $targetTemperature) {
        If (-not $this.ApiSessionId) {$this.ReturnError("No ApiSessionId - must log in first.")}
        
        # Get a sensible temp from the input value rounded to nearest half degree
        $Temp = ([Math]::Round(($targetTemperature * 2), [System.MidpointRounding]::AwayFromZero)/2)

        # Update nodes
        $this.Products = $this.GetProducts()
        $this.Devices = $this.GetDevices()

        If (($this.Products | Where-Object {$_.type -eq "heating"}).Count -is [int]) { $this.ReturnError('There is more than one product of type "heating". Please identify which heating zone by providing the zone name.') }
        
        # Find out the correct node to send the commands to.
        $Thermostat = $this.Products | Where-Object {$_.type -eq "heating"} | Select-Object -First 1

        # Check the heating is not in OFF state
        If ($Thermostat.state.mode -eq 'OFF') {
            $this.ReturnError("Heating mode is currently OFF. Set to MANUAL or SCHEDULE first.")
        }

        # This will be converted to JSON. I suppose it could just be JSON but...meh.
        $Settings = [psobject]@{
            target = $Temp
        }

        Try {
            $Response = Invoke-RestMethod -Method Post -Uri "$($this.ApiUrl)/nodes/heating/$($Thermostat.id)" -Headers $this.Headers -Body (ConvertTo-Json $Settings -Depth 99 -Compress)
            Return "Desired temperature ($($targetTemperature.ToString())$([char] 176 )C) set successfully."
        }
        Catch {
            $this.ReturnError($_)
            Return $null
        }
    }

    <#
        Sets the temperature value on the named thermostat device in the system.
        $this.Products and $this.Devices is always refreshed prior to execution.
    #>

    [psobject] SetTemperature([string] $ZoneName, [double] $targetTemperature) {
        If (-not $this.ApiSessionId) {$this.ReturnError("No ApiSessionId - must log in first.")}
        
        # Get a sensible temp from the input value rounded to nearest half degree
        $Temp = ([Math]::Round(($targetTemperature * 2), [System.MidpointRounding]::AwayFromZero)/2)

        # Update nodes
        $this.Products = $this.GetProducts()
        $this.Devices = $this.GetDevices()

        If (($this.Products | Where-Object {$_.type -eq "heating" -and $_.state.name -eq $ZoneName}).Count -is [int]) { $this.ReturnError("No heating zones matching the name provided: `"$ZoneName`" were found.") }
        
       # Find out the correct node to send the commands to.
        $Thermostat = $this.Products | Where-Object {$_.type -eq "heating" -and $_.state.name -eq $ZoneName}

        # Check the heating is not in OFF state
        If ($Thermostat.state.mode -eq 'OFF') {
            $this.ReturnError("Heating mode is currently OFF. Set to MANUAL or SCHEDULE first.")
        }

        # This will be converted to JSON. I suppose it could just be JSON but...meh.
        $Settings = [psobject]@{
            target = $Temp
        }

        Try {
            $Response = Invoke-RestMethod -Method Post -Uri "$($this.ApiUrl)/nodes/heating/$($Thermostat.id)" -Headers $this.Headers -Body (ConvertTo-Json $Settings -Depth 99 -Compress)
            Return "Desired temperature ($($targetTemperature.ToString())$([char] 176 )C) set successfully."
        }
        Catch {
            $this.ReturnError($_)
            Return $null
        }
    }

    <#
        Boosts the heating system for the defined time.
        The [BoostTime] Enum is used to ensure proper time values are submitted.
        Always boosts to 22C - this is the same as the Hive site.
        Send a SetTemperature() afterward to adjust the Boost up or down.
        You can re-boost at any time but the timer starts again, obviously.
        This boosts only a single zone. For multi-zone systems, use the overload and define the zone name.
    #>

    [psobject] SetBoostMode([BoostTime] $Duration) {
        If (-not $this.ApiSessionId) {$this.ReturnError("No ApiSessionId - must log in first.")}
        
        # Update nodes
        $this.Products = $this.GetProducts()
        $this.Devices = $this.GetDevices()

        If (($this.Products | Where-Object {$_.type -eq "heating"}).Count -is [int]) { $this.ReturnError('There is more than one product of type "heating". Please identify which heating zone by providing the zone name.') }
        
        # Find out the correct node to send the commands to.
        $Thermostat = $this.Products | Where-Object {$_.type -eq "heating"} | Select-Object -First 1

        $ApiDuration = $null # Creating so it's there!
        $ApiTemperature = 22 # This is the same Boost default temp as the Hive site.

        Switch ($Duration) {
            'HALF' {$ApiDuration = 30}
            'ONE' {$ApiDuration = 60}
            'TWO' {$ApiDuration = 120}
            'THREE' {$ApiDuration = 180}
            'FOUR' {$ApiDuration = 240}
            'FIVE' {$ApiDuration = 300}
            'SIX' {$ApiDuration = 360}
        }

        # JSON structure in a PSObject
        $Settings = [psobject]@{
            mode = 'BOOST'
            boost = $ApiDuration
            target = $ApiTemperature
        }

        Try {
            $Response = Invoke-RestMethod -Method Post -Uri "$($this.ApiUrl)/nodes/heating/$($Thermostat.id)" -Headers $this.Headers -Body (ConvertTo-Json $Settings -Depth 99 -Compress)
            Return "Heating BOOST activated for $ApiDuration minutes at $($ApiTemperature.ToString())$([char] 176 )C"
        }
        Catch {
            $this.ReturnError($_)
            Return $null
        }
    }

    <#
        Boosts the named heating zone for the defined time.
        The [BoostTime] Enum is used to ensure proper time values are submitted.
        Always boosts to 22C - this is the same as the Hive site.
        Send a SetTemperature() afterward to adjust the Boost up or down.
        You can re-boost at any time but the timer starts again, obviously.
    #>

    [psobject] SetBoostMode([string] $ZoneName, [BoostTime] $Duration) {
        If (-not $this.ApiSessionId) {$this.ReturnError("No ApiSessionId - must log in first.")}
        
        # Update nodes
        $this.Products = $this.GetProducts()
        $this.Devices = $this.GetDevices()

        If (($this.Products | Where-Object {$_.type -eq "heating" -and $_.state.name -eq $ZoneName}).Count -is [int]) { $this.ReturnError("No heating zones matching the name provided: `"$ZoneName`" were found.") }
        
        # Find out the correct node to send the commands to.
        $Thermostat = $this.Products | Where-Object {$_.type -eq "heating" -and $_.state.name -eq $ZoneName}

        $ApiDuration = $null # Creating so it's there!
        $ApiTemperature = 22 # This is the same Boost default temp as the Hive site.

        Switch ($Duration) {
            'HALF' {$ApiDuration = 30}
            'ONE' {$ApiDuration = 60}
            'TWO' {$ApiDuration = 120}
            'THREE' {$ApiDuration = 180}
            'FOUR' {$ApiDuration = 240}
            'FIVE' {$ApiDuration = 300}
            'SIX' {$ApiDuration = 360}
        }

        # JSON structure in a PSObject
        $Settings = [psobject]@{
            mode = 'BOOST'
            boost = $ApiDuration
            target = $ApiTemperature
        }

        Try {
            $Response = Invoke-RestMethod -Method Post -Uri "$($this.ApiUrl)/nodes/heating/$($Thermostat.id)" -Headers $this.Headers -Body (ConvertTo-Json $Settings -Depth 99 -Compress)
            Return "Heating BOOST activated for $ApiDuration minutes at $($ApiTemperature.ToString())$([char] 176 )C in $ZoneName"
        }
        Catch {
            $this.ReturnError($_)
            Return $null
        }
    }

    <#
        If the current heating mode is set to BOOST, turn it off.
        This reverts the system to its previous configuration using the
        previous value stored for the Thermostat when
        BOOST was activated.
        If BOOST is activated during a schedule that has been overriden,
        canceling boost mode reverts to the scheduled value, not the overriden value.
    #>

    [string] CancelBoostMode() {
        If (-not $this.ApiSessionId) {$this.ReturnError("No ApiSessionId - must log in first.")}
        
        # Update nodes
        $this.Products = $this.GetProducts()
        $this.Devices = $this.GetDevices()

        If (($this.Products | Where-Object {$_.type -eq "heating"}).Count -is [int]) { $this.ReturnError('There is more than one product of type "heating". Please identify which heating zone by providing the zone name.') }
        
        # Find out the correct node to send the commands to.
        $Thermostat = $this.Products | Where-Object {$_.type -eq "heating"} | Select-Object -First 1

        # If the system isn't set to BOOST, return without doing anything.
        If ($Thermostat.state.mode -ne 'BOOST') {
            $this.ReturnError("The current heating mode is not BOOST.")
        }
        
        Switch ($Thermostat.props.previous.mode) {
            SCHEDULE { $this.SetHeatingMode('SCHEDULE') }
            MANUAL {
                $this.SetHeatingMode('MANUAL') 
                $this.SetTemperature($Thermostat.props.previous.target)
            }
            OFF { $this.SetHeatingMode('OFF') }
            Default {$this.SetHeatingMode('SCHEDULE')}
        }

        Return "Heating BOOST cancelled."
    }

    <#
        If the named heating zone mode is set to BOOST, turns it off.
        This reverts the system to its previous configuration using the
        previous value stored for the Thermostat when
        BOOST was activated.
        If BOOST is activated during a schedule that has been overriden,
        canceling boost mode reverts to the scheduled value, not the overriden value.
    #>

    [string] CancelBoostMode([string] $ZoneName) {
        If (-not $this.ApiSessionId) {$this.ReturnError("No ApiSessionId - must log in first.")}
        
        # Update nodes
        $this.Products = $this.GetProducts()
        $this.Devices = $this.GetDevices()

        If (($this.Products | Where-Object {$_.type -eq "heating" -and $_.state.name -eq $ZoneName}).Count -is [int]) { $this.ReturnError("No heating zones matching the name provided: `"$ZoneName`" were found.") }
        
        # Find out the correct node to send the commands to.
        $Thermostat = $this.Products | Where-Object {$_.type -eq "heating" -and $_.state.name -eq $ZoneName}

        # If the system isn't set to BOOST, return without doing anything.
        If ($Thermostat.state.mode -ne 'BOOST') {
            $this.ReturnError("The current heating mode is not BOOST.")
        }
        
        Switch ($Thermostat.props.previous.mode) {
            SCHEDULE { $this.SetHeatingMode('SCHEDULE') }
            MANUAL {
                $this.SetHeatingMode('MANUAL') 
                $this.SetTemperature($Thermostat.props.previous.target)
            }
            OFF { $this.SetHeatingMode('OFF') }
            Default {$this.SetHeatingMode('SCHEDULE')}
        }

        Return "Heating BOOST cancelled in $ZoneName."
    }


    <#
        Get information about current holiday mode settings.
        Returns a string value for start and end dates.
    #>

    [string] GetHolidayMode() {
        If (-not $this.ApiSessionId) {$this.ReturnError("No ApiSessionId - must log in first.")}
        Try {
            $Holiday = Invoke-RestMethod -Method Get -Uri "$($this.ApiUrl)/holiday-mode" -Headers $this.Headers -ErrorAction Stop
        }
        Catch {
            $this.ReturnError($_)
            Return $null
        }

        # Init variables...
        $Start = $End = $Temp = $null

        If ($Holiday.enabled -eq $true) {
            $Start = [DateTime]::SpecifyKind($this.ConvertUnixTime($Holiday.start), [DateTimeKind]::Local)
            $End = [DateTime]::SpecifyKind($this.ConvertUnixTime($Holiday.end), [DateTimeKind]::Local)
            $Temp = [int] $Holiday.temperature
        }
        ElseIf ($Holiday.enabled -eq $false) {
            Return "Holiday mode is not currently enabled."
        }
        Else {
            $this.ReturnError("Unable to determine the current settings of holiday mode.")
        }

        Return "Holiday mode is enabled from $($Start.ToLocalTime().ToString()) -> $($End.ToLocalTime().ToString()) @ $Temp$([char]176)C."        
    }

    <#
        Enable holiday mode, providing a start date, end date and temperature.
        Ranges are checked that you don't set anything silly and have your heating on 24/7
        while you're away.
    #>

    [string] SetHolidayMode([datetime] $StartDateTime, [datetime] $EndDateTime, [int] $Temperature) {
        If (-not $this.ApiSessionId) {$this.ReturnError("No ApiSessionId - must log in first.")}

        # Ensure date times are correctly stated.
        If ($StartDateTime -lt (Get-Date)) {$this.ReturnError("Start date and time is in the past.")}
        If ($EndDateTime -lt (Get-Date)) {$this.ReturnError("End date and time is in the past.")}
        If ($EndDateTime -lt $StartDateTime) {$this.ReturnError("End date is before start date.")}

        # Check the user didn't type the wrong temp value.
        If ($Temperature -notin 1..32) {
            $this.ReturnError("Your chosen holiday mode temperature exceeds the acceptable range (1$([char]176)C -> 32$([char]176)C)")
        }
        
        # Check the submitted temp doesn't exceed the permitted values
        If ($Temperature -ge 15) {
            Write-Warning -Message "Your chosen holiday temperature ($Temperature$([char]176)C) is quite warm. To change it, send the request again."
        }

        # Update nodes data
        $this.Products = $this.GetProducts()
        $this.Devices = $this.GetDevices()

        # The user will only ever define a local time but force it anyway.
        $StartDateUTC = [DateTime]::SpecifyKind($StartDateTime, [DateTimeKind]::Local)
        $EndDateUTC = [DateTime]::SpecifyKind($EndDateTime, [DateTimeKind]::Local)

        $Settings = [psobject]@{
            temperature = $Temperature
            start = $this.DateTimeToUnixTimestamp($StartDateUTC)
            end = $this.DateTimeToUnixTimestamp($EndDateUTC)
        }

        Try {
            $Response = Invoke-RestMethod -Method Post -Uri "$($this.ApiUrl)/holiday-mode" -Headers $this.Headers -Body (ConvertTo-Json $Settings -Depth 99 -Compress)
            Return "Holiday mode activated from $($StartDateTime.ToString()) -> $($EndDateTime.ToString()) @ $Temperature$([char]176)C."
        }
        Catch {
            $this.ReturnError($_)
            Return $null
        }
    }

    <#
        Cancels holiday mode. Sends the request whether holiday mode is enabled or not.
    #>

    [string] CancelHolidayMode() {
        If (-not $this.ApiSessionId) {$this.ReturnError("No ApiSessionId - must log in first.")}
        
        Try {
            $Response = Invoke-RestMethod -Method Delete -Uri "$($this.ApiUrl)/holiday-mode" -Headers $this.Headers
            Return "Holiday mode cancelled."
        }
        Catch {
            $this.ReturnError($_)
            Return $null
        }
    }

    <#
        Get the current weather (temp, conditions) for the users' postcode location.
    #>

    [psobject] GetWeather() {
        If (-not $this.ApiSessionId) {$this.ReturnError("No ApiSessionId - must log in first.")}
        $Postcode = $this.User.postcode
        $Country = $this.User.countryCode
        
        Try {
            $Response = Invoke-RestMethod -Method Get -Uri "https://weather-prod.bgchprod.info/weather?postcode=$Postcode&country=$Country"
            Return $Response.weather | Select-Object description, temperature
        }
        Catch {
            $this.ReturnError($_)
            Return $null
        }
    }

    <#
        Get the current weather (temp, conditions) for a specific postcode location.
        Make sure the postcode is accurate or you'll likely get an error. I don't validate it!
    #>

    [psobject] GetWeather([string] $Postcode, [string] $CountryCode) {
        $Postcode = $Postcode.Replace(' ', '').ToUpper()
        $CountryCode = $CountryCode.Replace(' ', '').ToUpper()
        
        Try {
            $Response = Invoke-RestMethod -Method Get -Uri "https://weather-prod.bgchprod.info/weather?postcode=$Postcode&country=$CountryCode"
            Return $Response.weather | Select-Object description, temperature
        }
        Catch {
            $this.ReturnError($_)
            Return $null
        }
    }

    <#
        Get the outside weather temperature for the users' postcode location in C
        Simply uses another method to retrieve the full result and return only the temp.
    #>

    [int] GetWeatherTemperature() {
        Return $this.GetWeather().temperature.value
    }

    <#
        Save your current heating schedule to a JSON formatted file.
        Save different schedules for different times of the year and upload them as required
        using SetHeatingScheduleFromFile().
        Specify a directory ONLY - the file will be named HiveSchedule-yyyyMMddHHmm.json
    #>

    [void] SaveHeatingScheduleToFile([System.IO.DirectoryInfo] $DirectoryPath) {
        If (-not $this.ApiSessionId) {$this.ReturnError("No ApiSessionId - must log in first.")}
        If (-not $DirectoryPath.Exists) {$this.ReturnError("The path should already exist.")}

        # Update nodes data
        $this.Products = $this.GetProducts()
        $this.Devices = $this.GetDevices()

        If (($this.Products | Where-Object {$_.type -eq "heating"}).Count -is [int]) { $this.ReturnError('There is more than one product of type "heating". Please identify which heating zone by providing the zone name.') }
        
        # Find out the correct node to send the commands to.
        $Thermostat = $this.Products | Where-Object {$_.type -eq "heating"} | Select-Object -First 1

        # Create the correct json structure.
        $Settings = [psobject]@{
            schedule = $Thermostat.state.schedule
        }

        # Create the file output path and name.
        $File = [System.IO.Path]::Combine($DirectoryPath, "HiveSchedule-$(Get-Date -Format "yyyyMMdd-HHmm").json")

        # Save the file to disk or error if it exists - let the user handle renaming/moving/deleting.
        Try {
            ConvertTo-Json -InputObject $Settings -Depth 99 | Out-File -FilePath $File -NoClobber
        }
        Catch {
            $this.ReturnError("An error occurred saving the file.`r`n$_")
        }
    }

    <#
        Save your named heating zone schedule to a JSON formatted file.
        Save different schedules for different times of the year and upload them as required
        using SetHeatingScheduleFromFile().
        Specify a directory ONLY - the file will be named HiveSchedule-yyyyMMddHHmm.json
    #>

    [void] SaveHeatingScheduleToFile([string] $ZoneName, [System.IO.DirectoryInfo] $DirectoryPath) {
        If (-not $this.ApiSessionId) {$this.ReturnError("No ApiSessionId - must log in first.")}
        If (-not $DirectoryPath.Exists) {$this.ReturnError("The path should already exist.")}

        # Update nodes data
        $this.Products = $this.GetProducts()
        $this.Devices = $this.GetDevices()

        If (($this.Products | Where-Object {$_.type -eq "heating" -and $_.state.name -eq $ZoneName}).Count -is [int]) { $this.ReturnError("No heating zones matching the name provided: `"$ZoneName`" were found.") }
        
        # Find out the correct node to send the commands to.
        $Thermostat = $this.Products | Where-Object {$_.type -eq "heating" -and $_.state.name -eq $ZoneName}

        # Create the correct json structure.
        $Settings = [psobject]@{
            schedule = $Thermostat.state.schedule
        }

        # Create the file output path and name.
        $File = [System.IO.Path]::Combine($DirectoryPath, "HiveSchedule-$ZoneName-$(Get-Date -Format "yyyyMMdd-HHmm").json")

        # Save the file to disk or error if it exists - let the user handle renaming/moving/deleting.
        Try {
            ConvertTo-Json -InputObject $Settings -Depth 99 | Out-File -FilePath $File -NoClobber
        }
        Catch {
            $this.ReturnError("An error occurred saving the file.`r`n$_")
        }
    }


    <#
        Reads in a JSON file containing heating schedule data, checks it and uploads to the Hive site.
        To ensure that the format is correct, it is recommended to save a copy of your current
        schedule first using SaveHeatingScheduleToFile().
    #>

    [string] SetHeatingScheduleFromFile([System.IO.FileInfo] $FilePath) {
        If (-not $this.ApiSessionId) {$this.ReturnError("No ApiSessionId - must log in first.")}
        If (-not (Test-Path -Path $FilePath )) {$this.ReturnError("The file path supplied does not exist.")}

        # Update nodes data
        $this.Products = $this.GetProducts()
        $this.Devices = $this.GetDevices()

        If (($this.Products | Where-Object {$_.type -eq "heating"}).Count -is [int]) { $this.ReturnError('There is more than one product of type "heating". Please identify which heating zone by providing the zone name.') }
        
        # Find out the correct node to send the commands to.
        $Thermostat = $this.Products | Where-Object {$_.type -eq "heating"} | Select-Object -First 1

        $Settings = $null
        
        # Read in the schedule data from the file.
        Try {
            $Settings = ConvertFrom-Json -InputObject (Get-Content -Path $FilePath -Raw)
        }
        Catch {
            $this.ReturnError("The file specified could not be parsed as valid JSON.`r`n$_")
        }

        # Seven days of events in the file?
        If (((($Settings.schedule).psobject.Members | Where-Object {$_.MemberType -eq 'NoteProperty'}).count) -eq 7) {
            Try {
                $Response = Invoke-RestMethod -Method Post -Uri "$($this.ApiUrl)/nodes/heating/$($Thermostat.id)" -Headers $this.Headers -Body (ConvertTo-Json $Settings -Depth 99 -Compress)
                Return "Schedule set successfully from $FilePath"
            }
            Catch {
                $this.ReturnError($_)
                Return $null
            }
        }
        Else {Return "The schedule in the file must contain entries for all seven days."}
    }

    <#
        Set a named heating zone schedule from a saved schedule file.
    #>

    [string] SetHeatingScheduleFromFile([string] $ZoneName, [System.IO.FileInfo] $FilePath) {
        If (-not $this.ApiSessionId) {$this.ReturnError("No ApiSessionId - must log in first.")}
        If (-not (Test-Path -Path $FilePath )) {$this.ReturnError("The file path supplied does not exist.")}

        # Update nodes data
        $this.Products = $this.GetProducts()
        $this.Devices = $this.GetDevices()

        If (($this.Products | Where-Object {$_.type -eq "heating" -and $_.state.name -eq $ZoneName}).Count -is [int]) { $this.ReturnError("No heating zones matching the name provided: `"$ZoneName`" were found.") }
        
        # Find out the correct node to send the commands to.
        $Thermostat = $this.Products | Where-Object {$_.type -eq "heating" -and $_.state.name -eq $ZoneName}

        $Settings = $null
        
        # Read in the schedule data from the file.
        Try {
            $Settings = ConvertFrom-Json -InputObject (Get-Content -Path $FilePath -Raw)
        }
        Catch {
            $this.ReturnError("The file specified could not be parsed as valid JSON.`r`n$_")
        }

        # Seven days of events in the file?
        If (((($Settings.schedule).psobject.Members | Where-Object {$_.MemberType -eq 'NoteProperty'}).count) -eq 7) {
            Try {
                $Response = Invoke-RestMethod -Method Post -Uri "$($this.ApiUrl)/nodes/heating/$($Thermostat.id)" -Headers $this.Headers -Body (ConvertTo-Json $Settings -Depth 99 -Compress)
                Return "Schedule set successfully from $FilePath"
            }
            Catch {
                $this.ReturnError($_)
                Return $null
            }
        }
        Else {Return "The schedule in the file must contain entries for all seven days."}
    }

    <#
        Advance your heating to the next setting based on the current schedule.
        If no time period exists in the current day's schedule, the first event in the next
        day's schedule is used.
    #>

    [string] SetHeatingAdvance() {
        If (-not $this.ApiSessionId) {$this.ReturnError("No ApiSessionId - must log in first.")}

        # Update nodes data
        $this.Products = $this.GetProducts()
        $this.Devices = $this.GetDevices()

        If (($this.Products | Where-Object {$_.type -eq "heating"}).Count -is [int]) { $this.ReturnError('There is more than one product of type "heating". Please identify which heating zone by providing the zone name.') }
        
        # Find out the correct node to send the temp to. Only the first Thermostat we find!
        $Thermostat = $this.Products | Where-Object {$_.type -eq "heating"} | Select-Object -First 1

        # Check the heating is in SCHEDULE mode.
        If (-not ($Thermostat.state.mode -eq 'SCHEDULE')) {
            $this.ReturnError("Heating mode is not currently SCHEDULE. Advancing is not possible.")
        }

        # Get the schedule data
        $Schedule = $Thermostat.state.schedule

        # Get the current date and time.
        $Date = Get-Date
        $MinutesPastMidnight = ($Date - $Date.Date).TotalMinutes

        # Set up variables.
        $NextEvent = $null
        
        # Get today's schedule
        $DaySchedule = Select-Object -InputObject $Schedule -ExpandProperty $Date.DayOfWeek.ToString()

        # Get the next period/schedule from today's events
        Foreach ($Period in $DaySchedule) {
            If (($Period.start) -gt $MinutesPastMidnight) {
                $NextEvent = $Period
                Break
            }
        }

        # If there is no event from today that's ahead of now, get tomorrow's first event.
        If (-not $NextEvent) {
            $DaySchedule = Select-Object -InputObject $Schedule -ExpandProperty $Date.AddDays(1).DayOfWeek.ToString()
            $NextEvent = $DaySchedule[0]
        }

        # Set the temperature to the next event.
        Return "Advancing to $($NextEvent.value.target)$([char]176)C...`r`n$($this.SetTemperature($NextEvent.value.target))"
    }

    <#
        Advance the named heating zone to the next slot based on the current schedule.
        If no time period exists in the current day's schedule, the first event in the next
        day's schedule is used.
    #>

    [string] SetHeatingAdvance([string] $ZoneName) {
        If (-not $this.ApiSessionId) {$this.ReturnError("No ApiSessionId - must log in first.")}

        # Update nodes data
        $this.Products = $this.GetProducts()
        $this.Devices = $this.GetDevices()

        If (($this.Products | Where-Object {$_.type -eq "heating" -and $_.state.name -eq $ZoneName}).Count -is [int]) { $this.ReturnError("No heating zones matching the name provided: `"$ZoneName`" were found.") }
        
        # Find out the correct node to send the commands to.
        $Thermostat = $this.Products | Where-Object {$_.type -eq "heating" -and $_.state.name -eq $ZoneName}

        # Check the heating is in SCHEDULE mode.
        If (-not ($Thermostat.state.mode -eq 'SCHEDULE')) {
            $this.ReturnError("Heating mode is not currently SCHEDULE. Advancing is not possible.")
        }

        # Get the schedule data
        $Schedule = $Thermostat.state.schedule

        # Get the current date and time.
        $Date = Get-Date
        $MinutesPastMidnight = ($Date - $Date.Date).TotalMinutes

        # Set up variables.
        $NextEvent = $null
        
        # Get today's schedule
        $DaySchedule = Select-Object -InputObject $Schedule -ExpandProperty $Date.DayOfWeek.ToString()

        # Get the next period/schedule from today's events
        Foreach ($Period in $DaySchedule) {
            If (($Period.start) -gt $MinutesPastMidnight) {
                $NextEvent = $Period
                Break
            }
        }

        # If there is no event from today that's ahead of now, get tomorrow's first event.
        If (-not $NextEvent) {
            $DaySchedule = Select-Object -InputObject $Schedule -ExpandProperty $Date.AddDays(1).DayOfWeek.ToString()
            $NextEvent = $DaySchedule[0]
        }

        # Set the temperature to the next event.
        Return "Advancing to $($NextEvent.value.target)$([char]176)C...`r`n$($this.SetTemperature($NextEvent.value.target))"
    }


    <#
        Get the object data for an Active Plug by its name.
    #>

    hidden [psobject] GetActivePlug([string]$Name) {
        $ActivePlug = $this.Products | Where-Object {($_.type -eq "activeplug") -and ($_.state.name -eq $Name)}
        If ($ActivePlug) { Return $ActivePlug }
        Else { Return $false }
    }

    <#
        Set the mode of an active plug to be either MANUAL or SCHEDULE.
        If you switch to schedule and the plug schedule is to be on, the plug will turn on.
        If you subsequently switch back to MANUAL, the plug will not switch off again
        as there is no previous configuration setting on Active Plugs.
    #>

    [string] SetActivePlugMode([ActivePlugMode]$Mode, [string]$Name) {
        If (-not $this.ApiSessionId) {$this.ReturnError("No ApiSessionId - must log in first.")}

        # Update nodes
        $this.Products = $this.GetProducts()
        $this.Devices = $this.GetDevices()

        # Check that the plug name exists and assign to a var if so.
        If (-not ($ActivePlug = $this.GetActivePlug($Name))) {
            $this.ReturnError("The active plug name provided `"$Name`" does not exist.")
        }
        
        $Settings = $null

        Switch ($ActivePlug.state.mode) {
           {($_ -eq "MANUAL") -and ($Mode -eq 'MANUAL') } { Return "`"$Name`" is already in MANUAL." }
           {($_ -eq "SCHEDULE") -and ($Mode -eq 'SCHEDULE') } { Return "`"$Name`" is already in SCHEDULE." }
        }

        Switch ($Mode) {
            'MANUAL' { $Settings = [psobject]@{mode = "MANUAL"} }
            'SCHEDULE' { $Settings = [psobject]@{mode = "SCHEDULE"} }
        }

        Try {
            $Response = Invoke-RestMethod -Method Post -Uri "$($this.ApiUrl)/nodes/activeplug/$($ActivePlug.id)" -Headers $this.Headers -Body (ConvertTo-Json $Settings -Depth 99 -Compress)
        }
        Catch {
            $this.ReturnError($_)
            Return $null
        }
        
        Return "Active Plug `"$Name`" set to $($Settings.mode) successfully."
    }

    <#
        Set the state of a named Active Plug to be either on ($true) or off ($false).
        Uses a boolean as opposed to a text value.
    #>

    [string] SetActivePlugState([bool]$State, [string]$Name) {
        If (-not $this.ApiSessionId) {$this.ReturnError("No ApiSessionId - must log in first.")}

        # Update nodes
        $this.Products = $this.GetProducts()
        $this.Devices = $this.GetDevices()

        # Check that the plug name exists and assign to a var if so.
        If (-not ($ActivePlug = $this.GetActivePlug($Name))) {
            $this.ReturnError("The active plug name provided `"$Name`" does not exist.")
        }
        
        $Settings = $null

        Switch ($ActivePlug.state.status) {
           {($_ -eq "ON") -and ($State -eq $true) } { Return "`"$Name`" is already ON." }
           {($_ -eq "OFF") -and ($State -eq $false) } { Return "`"$Name`" is already OFF." }
        }

        Switch ($State) {
            $true { $Settings = [psobject]@{status = "ON"} }
            $false { $Settings = [psobject]@{status = "OFF"} }
        }

        Try {
            $Response = Invoke-RestMethod -Method Post -Uri "$($this.ApiUrl)/nodes/activeplug/$($ActivePlug.id)" -Headers $this.Headers -Body (ConvertTo-Json $Settings -Depth 99 -Compress)
        }
        Catch {
            $this.ReturnError($_)
            Return $null
        }
        
        Return "Active Plug `"$Name`" set to $($Settings.status) successfully."
    }

    <#
        Save an Active Plug schedule to a JSON formatted file.
        Specify a directory ONLY - the file will be named HiveActivePlugSchedule-yyyyMMddHHmm.json
    #>

    [void] SaveActivePlugScheduleToFile([System.IO.DirectoryInfo] $DirectoryPath, [string] $Name) {
        If (-not $this.ApiSessionId) {$this.ReturnError("No ApiSessionId - must log in first.")}
        If (-not $DirectoryPath.Exists) {$this.ReturnError("The path should already exist.")}

        # Update nodes data
        $this.Products = $this.GetProducts()
        $this.Devices = $this.GetDevices()
        
        # Check that the plug name exists and assign to a var if so.
        If (-not ($ActivePlug = $this.GetActivePlug($Name))) {
            $this.ReturnError("The active plug name provided `"$Name`" does not exist.")
        }

        # Create the correct json structure.
        $Settings = [psobject]@{
            schedule = $ActivePlug.state.schedule
        }

        # Create the file output path and name.
        $File = [System.IO.Path]::Combine($DirectoryPath, "HiveActivePlugSchedule-$(Get-Date -Format "yyyyMMdd-HHmm").json")

        # Save the file to disk or error if it exists - let the user handle renaming/moving/deleting.
        Try {
            ConvertTo-Json -InputObject $Settings -Depth 99 | Out-File -FilePath $File -NoClobber
        }
        Catch {
            $this.ReturnError("An error occurred saving the file.`r`n$_")
        }
    }

    <#
        Reads in a JSON file containing Active Plug schedule data, checks it and uploads to the Hive site.
        To ensure that the format is correct, it is recommended to save a copy of your current
        schedule first using SaveActivePlugScheduleToFile().
        If you have multiple plugs and want them synchronised, you only have to update one schedule, save it,
        then upload it to all the other plugs identified by name.
    #>

    [string] SetActivePlugScheduleFromFile([System.IO.FileInfo] $FilePath, [string] $Name) {
        If (-not $this.ApiSessionId) {$this.ReturnError("No ApiSessionId - must log in first.")}
        If (-not (Test-Path -Path $FilePath )) {$this.ReturnError("The file path supplied does not exist.")}

        # Update nodes data
        $this.Products = $this.GetProducts()
        $this.Devices = $this.GetDevices()

        # Check that the plug name exists and assign to a var if so.
        If (-not ($ActivePlug = $this.GetActivePlug($Name))) {
            $this.ReturnError("The active plug name provided `"$Name`" does not exist.")
        }

        $Settings = $null
        
        # Read in the schedule data from the file.
        Try {
            $Settings = ConvertFrom-Json -InputObject (Get-Content -Path $FilePath -Raw)
        }
        Catch {
            $this.ReturnError("The file specified could not be parsed as valid JSON.`r`n$_")
        }

        # Seven days of events in the file?
        If (((($Settings.schedule).psobject.Members | Where-Object {$_.MemberType -eq 'NoteProperty'}).count) -eq 7) {
            Try {
                $Response = Invoke-RestMethod -Method Post -Uri "$($this.ApiUrl)/nodes/activeplug/$($ActivePlug.id)" -Headers $this.Headers -Body (ConvertTo-Json $Settings -Depth 99 -Compress)
                Return "$($ActivePlug.state.name) schedule set successfully from `"$FilePath`""
            }
            Catch {
                $this.ReturnError($_)
                Return $null
            }
        }
        Else {Return "The schedule in the file must contain entries for all seven days."}
    }

    <#
        Get the current power consumption, in watts, of the named Active Plug.
        This is useful for monitoring devices that might run for an indeterminate
        amount of time, such as an auto-sensing clothes dryer. As this value falls to a low number,
        the Active Plug can be turned off.
    #>

    [int] GetActivePlugPowerConsumption([string] $Name) {
        If (-not $this.ApiSessionId) {$this.ReturnError("No ApiSessionId - must log in first.")}

        # Update nodes data
        $this.Products = $this.GetProducts()
        $this.Devices = $this.GetDevices()
        
        # Check that the plug name exists and assign to a var if so.
        If (-not ($ActivePlug = $this.GetActivePlug($Name))) {
            $this.ReturnError("The active plug name provided `"$Name`" does not exist.")
        }

        # Return the current power consumption.
        Return $ActivePlug.props.powerConsumption    
    }

    <#
        Get Active Plug State - whether it is currently on or off.
    #>

    [bool] GetActivePlugState([string]$Name) {
        If (-not $this.ApiSessionId) {$this.ReturnError("No ApiSessionId - must log in first.")}

        # Update nodes
        $this.Products = $this.GetProducts()
        $this.Devices = $this.GetDevices()

        # Check that the plug name exists and assign to a var if so.
        If (-not ($ActivePlug = $this.GetActivePlug($Name))) {
            $this.ReturnError("The active plug name provided `"$Name`" does not exist.")
        }

        $State = $null

        Switch ($ActivePlug.state.status) {
           {($_ -eq "ON") } { $State = $true }
           {($_ -eq "OFF") } { $State = $false }
           Default { $State = $null }
        }
        Return $State
    }

    <#
        Set the Hot Water mode. Requires one of the following: OFF, MANUAL, SCHEDULE
    #>

    [psobject] SetHotWaterMode([HeatingMode] $Mode) {
        If (-not $this.ApiSessionId) {$this.ReturnError("No ApiSessionId - must log in first.")}

        # Update nodes
        $this.Products = $this.GetProducts()
        $this.Devices = $this.GetDevices()

        If (($this.Products | Where-Object {$_.type -eq "hotwater"}).Count -is [int]) { $this.ReturnError('There is no hot water device attached to this system.') }
        
        # Find out the correct node to send the commands to.
        $HotWater = $this.Products | Where-Object {$_.type -eq "hotwater"} | Select-Object -First 1

        $Settings = [psobject]@{
            mode = $Mode.ToString()
        }

        Try {
            $Response = Invoke-RestMethod -Method Post -Uri "$($this.ApiUrl)/nodes/hotwater/$($HotWater.id)" -Headers $this.Headers -Body (ConvertTo-Json $Settings -Depth 99 -Compress)
            Return "Hot water mode set to $($Mode.ToString()) successfully."
        }
        Catch {
            $this.ReturnError($_)
            Return $null
        }
    }

    <#
        Hot water boost.
    #>

    [psobject] SetHotWaterBoostMode([BoostTime] $Duration) {
        If (-not $this.ApiSessionId) {$this.ReturnError("No ApiSessionId - must log in first.")}
        
        # Update nodes
        $this.Products = $this.GetProducts()
        $this.Devices = $this.GetDevices()

        If (($this.Products | Where-Object {$_.type -eq "hotwater"}).Count -is [int]) { $this.ReturnError('There is no hot water device attached to this system.') }
        
        # Find out the correct node to send the commands to.
        $HotWater = $this.Products | Where-Object {$_.type -eq "hotwater"} | Select-Object -First 1

        $ApiDuration = $null # Creating so it's there!

        Switch ($Duration) {
            'HALF' {$ApiDuration = 30}
            'ONE' {$ApiDuration = 60}
            'TWO' {$ApiDuration = 120}
            'THREE' {$ApiDuration = 180}
            'FOUR' {$ApiDuration = 240}
            'FIVE' {$ApiDuration = 300}
            'SIX' {$ApiDuration = 360}
        }

        # JSON structure in a PSObject
        $Settings = [psobject]@{
            mode = 'BOOST'
            boost = $ApiDuration
        }

        Try {
            $Response = Invoke-RestMethod -Method Post -Uri "$($this.ApiUrl)/nodes/hotwater/$($HotWater.id)" -Headers $this.Headers -Body (ConvertTo-Json $Settings -Depth 99 -Compress)
            Return "Hot water BOOST activated for $ApiDuration minutes."
        }
        Catch {
            $this.ReturnError($_)
            Return $null
        }
    }

    <#
        Cancel hot water boost.
    #>

    [string] CancelHotWaterBoostMode() {
        If (-not $this.ApiSessionId) {$this.ReturnError("No ApiSessionId - must log in first.")}
        
        # Update nodes
        $this.Products = $this.GetProducts()
        $this.Devices = $this.GetDevices()

        If (($this.Products | Where-Object {$_.type -eq "hotwater"}).Count -is [int]) { $this.ReturnError('There is no hot water device attached to this system.') }
        
        # Find out the correct node to send the commands to.
        $HotWater = $this.Products | Where-Object {$_.type -eq "hotwater"} | Select-Object -First 1

        # If the system isn't set to BOOST, return without doing anything.
        If ($HotWater.state.mode -ne 'BOOST') {
            $this.ReturnError("The current hot water mode is not BOOST.")
        }
        
        Switch ($HotWater.props.previous.mode) {
            SCHEDULE { $this.SetHotWaterMode('SCHEDULE') }
            MANUAL { $this.SetHotWaterMode('MANUAL') }
            OFF { $this.SetHotWaterMode('OFF') }
            Default {$this.SetHotWaterMode('OFF')}
        }

        Return "Hot water BOOST cancelled."
    }

    <#
        Save hot water schedule to a file.
    #>

    [void] SaveHotWaterScheduleToFile([System.IO.DirectoryInfo] $DirectoryPath) {
        If (-not $this.ApiSessionId) {$this.ReturnError("No ApiSessionId - must log in first.")}
        If (-not $DirectoryPath.Exists) {$this.ReturnError("The path should already exist.")}

        # Update nodes data
        $this.Products = $this.GetProducts()
        $this.Devices = $this.GetDevices()

        If (($this.Products | Where-Object {$_.type -eq "hotwater"}).Count -is [int]) { $this.ReturnError('There is no hot water device attached to this system.') }
        
        # Find out the correct node to send the commands to.
        $HotWater = $this.Products | Where-Object {$_.type -eq "hotwater"} | Select-Object -First 1

        # Create the correct json structure.
        $Settings = [psobject]@{
            schedule = $HotWater.state.schedule
        }

        # Create the file output path and name.
        $File = [System.IO.Path]::Combine($DirectoryPath, "HiveHotWaterSchedule-$(Get-Date -Format "yyyyMMdd-HHmm").json")

        # Save the file to disk or error if it exists - let the user handle renaming/moving/deleting.
        Try {
            ConvertTo-Json -InputObject $Settings -Depth 99 | Out-File -FilePath $File -NoClobber
        }
        Catch {
            $this.ReturnError("An error occurred saving the file.`r`n$_")
        }
    }

    <#
        Reads in a JSON file containing heating schedule data, checks it and uploads to the Hive site.
        To ensure that the format is correct, it is recommended to save a copy of your current
        schedule first using SaveHeatingScheduleToFile().
    #>

    [string] SetHotWaterScheduleFromFile([System.IO.FileInfo] $FilePath) {
        If (-not $this.ApiSessionId) {$this.ReturnError("No ApiSessionId - must log in first.")}
        If (-not (Test-Path -Path $FilePath )) {$this.ReturnError("The file path supplied does not exist.")}

        # Update nodes data
        $this.Products = $this.GetProducts()
        $this.Devices = $this.GetDevices()

        If (($this.Products | Where-Object {$_.type -eq "hotwater"}).Count -is [int]) { $this.ReturnError('There is no hot water device attached to this system.') }
        
        # Find out the correct node to send the commands to.
        $HotWater = $this.Products | Where-Object {$_.type -eq "hotwater"} | Select-Object -First 1

        $Settings = $null
        
        # Read in the schedule data from the file.
        Try {
            $Settings = ConvertFrom-Json -InputObject (Get-Content -Path $FilePath -Raw)
        }
        Catch {
            $this.ReturnError("The file specified could not be parsed as valid JSON.`r`n$_")
        }

        # Seven days of events in the file?
        If (((($Settings.schedule).psobject.Members | Where-Object {$_.MemberType -eq 'NoteProperty'}).count) -eq 7) {
            Try {
                $Response = Invoke-RestMethod -Method Post -Uri "$($this.ApiUrl)/nodes/hotwater/$($HotWater.id)" -Headers $this.Headers -Body (ConvertTo-Json $Settings -Depth 99 -Compress)
                Return "Schedule set successfully from $FilePath"
            }
            Catch {
                $this.ReturnError($_)
                Return $null
            }
        }
        Else {Return "The schedule in the file must contain entries for all seven days."}
    }

    <#
        Retrieves the status of a named motion sensor.
    #>

    [psobject] GetMotionSensorState([string] $SensorName, [bool] $IncludeTodaysEvents) {
        If (-not $this.ApiSessionId) {$this.ReturnError("No ApiSessionId - must log in first.")}
        Try {
            $this.Products = $this.GetProducts()
            $this.Devices = $this.GetDevices()

            If (($this.Products | Where-Object {$_.type -eq "motionsensor" -and $_.state.name -eq $SensorName}).Count -is [int]) { $this.ReturnError("No motion sensor matching the name provided: `"$SensorName`" was found.") }
            
            # Find out the correct motion sensor node to obtain the state of.
            $SensorNode = $this.Products | Where-Object {$_.type -eq "motionsensor" -and $_.state.name -eq $SensorName}

            $Response = $null

            If ($IncludeTodaysEvents) {
                # Get the events from today - note this is from "products" not "nodes".
                Try {
                    $TodayStart = Get-Date -Hour 0 -Minute 0 -Second 0
                    $TodayEnd = Get-Date -Hour 23 -Minute 59 -Second 59
                    $Response = Invoke-RestMethod -Method Get -Uri "$($this.ApiUrl)/products/motionsensor/$($SensorNode.id)/events?from=$($this.DateTimeToUnixTimestamp($TodayStart))&to=$($this.DateTimeToUnixTimestamp($TodayEnd))" -Headers $this.Headers
                }
                Catch {
                    $this.ReturnError($_)
                    Return $null
                }

                # Convert the unix timestamps in the response to date time objects so they can be read easily.
                for ($i=0; $i -le ($Response.Count - 1); $i++) {
                    $Response[$i].start = $this.ConvertUnixTime($Response[$i].start)
                    $Response[$i].end = $this.ConvertUnixTime($Response[$i].end)
                }
            }
            If ($IncludeTodaysEvents) {
                $MotionSensor = [ordered]@{
                    Online = $SensorNode.props.online
                    MotionDetected = $SensorNode.props.motion.status
                    StartTime = $this.ConvertUnixTime($SensorNode.props.motion.start)
                    EndTime = $this.ConvertUnixTime($SensorNode.props.motion.end)
                    LatestEvent = $Response | Sort-Object -Descending -Property start | Select-Object -First 1
                    TodaysEvents = $Response
                }
            }
            Else {
                $MotionSensor = [ordered]@{
                    Online = $SensorNode.props.online
                    MotionDetected = $SensorNode.props.motion.status
                    StartTime = $this.ConvertUnixTime($SensorNode.props.motion.start)
                    EndTime = $this.ConvertUnixTime($SensorNode.props.motion.end)
                }
            }

            Return $MotionSensor
        }
        Catch {
            $this.ReturnError($_)
            Return $null
        }
    }

    <#
        Retrieves the status of a named contact (window/door) sensor and its event history.
    #>

    [psobject] GetContactSensorState([string] $SensorName, [bool] $IncludeTodaysEvents) {
        If (-not $this.ApiSessionId) {$this.ReturnError("No ApiSessionId - must log in first.")}
        Try {
            $this.Products = $this.GetProducts()
            $this.Devices = $this.GetDevices()

            If (($this.Products | Where-Object {$_.type -eq "contactsensor" -and $_.state.name -eq $SensorName}).Count -is [int]) { $this.ReturnError("No contact sensor matching the name provided: `"$SensorName`" was found.") }
            
            # Find out the correct contact sensor node to obtain the state of.
            $SensorNode = $this.Products | Where-Object {$_.type -eq "contactsensor" -and $_.state.name -eq $SensorName}

            $Response = $null # Declare variable

            If ($IncludeTodaysEvents) {
                # Get the events from today - this is the first time we're getting the history of something - note this is from "products" not "nodes".
                Try {
                    $TodayStart = Get-Date -Hour 0 -Minute 0 -Second 0
                    $TodayEnd = Get-Date -Hour 23 -Minute 59 -Second 59
                    $Response = Invoke-RestMethod -Method Get -Uri "$($this.ApiUrl)/products/contactsensor/$($SensorNode.id)/events?from=$($this.DateTimeToUnixTimestamp($TodayStart))&to=$($this.DateTimeToUnixTimestamp($TodayEnd))" -Headers $this.Headers
                }
                Catch {
                    $this.ReturnError($_)
                    Return $null
                }

                # Convert the unix timestamps in the response to date time objects so they can be read easily.
                for ($i=0; $i -le ($Response.Count - 1); $i++) {
                    $Response[$i].start = $this.ConvertUnixTime($Response[$i].start)
                    $Response[$i].end = $this.ConvertUnixTime($Response[$i].end)
                }
            }
            If ($IncludeTodaysEvents) {
                $ContactSensor = [ordered]@{
                    SensorStatus = $SensorNode.props.status
                    LatestEvent = $Response | Sort-Object -Descending -Property start | Select-Object -First 1
                    TodaysEvents = $Response
                }
            }
            Else {
                $ContactSensor = [ordered]@{
                    SensorStatus = $SensorNode.props.status
                }
            }

            Return $ContactSensor
        }
        Catch {
            $this.ReturnError($_)
            Return $null
        }
    }

    
# END HIVE CLASS
}