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
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 1.4.1 - 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
            # Needs some error checking.
            $this.ApiSessionId = $null
            $this.Headers.Remove('Authorization')
            Return "Logged out successfully."
        }
        Catch {
            $this.ReturnError($_)
            Return $null
        }
    }

    <#
        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. Not likely to work as expected in multi-zone/thermostat
        Hive systems. Sorry.
        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". Apologies but this module does not currently support multiple heat zones.') }

            $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
        }
    }

    <#
        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,
        it only sets it on the first returned thermostat in the system. (Identified by
        the type of product being "heating" attribute on a device).
        It therefore DOES NOT support multi-zone/thermostat Hive installations, sorry!
    #>

    [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". Apologies but this module does not currently support multiple heat zones.') }
        
        # 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 -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 temperature value on the first thermostat device in the system.
        $this.Products and $this.Devices is always refreshed prior to execution.
        This method does not identify the thermostat on which to set the temperature.
        It only sets it on the first returned thermostat in the system. (Identified by
        the product type being "heating").
        It therefore DOES NOT support multi-zone/thermostat Hive installations, sorry!
    #>

    [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". Apologies but this module does not currently support multiple heat zones.') }
        
        # 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 -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
        }
    }

    <#
        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.
    #>

    [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". Apologies but this module does not currently support multiple heat zones.') }
        
        # 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 -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 "BOOST mode activated for $ApiDuration minutes at $($ApiTemperature.ToString())$([char] 176 )C"
        }
        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". Apologies but this module does not currently support multiple heat zones.') }
        
        # 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 -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 "Boost mode stopped."
    }

    <#
        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 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 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". Apologies but this module does not currently support multiple heat zones.') }
        
        # 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 -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$_")
        }
    }

    <#
        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". Apologies but this module does not currently support multiple heat zones.') }
        
        # 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 -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 {$_.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". Apologies but this module does not currently support multiple heat zones.') }
        
        # 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 -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))"
    }

    <#
        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 {$_.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."}
    }

# END HIVE CLASS
}