forked from lwsrbrts/PoSHue
/
PoSHue.ps1
1860 lines (1648 loc) · 69.1 KB
/
PoSHue.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
Enum LightState {
# Defines a state of the light for methods that can
# specify the state of the light to On or Off.
On = $True
Off = $False
}
Enum ColourMode {
# Defines the colour modes that can be set on the light.
none
xy
ct
hs
}
Enum AlertType {
# Defines the accepted values when invoking the Breathe method.
none
select
lselect
}
Enum Gamut {
# Defines the accepted gamut values when calculating RGB to XY conversions.
GamutA
GamutB
GamutC
GamutDefault
}
Enum RoomClass {
# Defines the room classes that lights can belong to.
Kitchen
Dining
Bedroom
Bathroom
Nursery
Recreation
Office
Gym
Hallway
Toilet
Garage
Terrace
Garden
Driveway
Carport
Other
}
Class HueFactory {
# Base class defining methods shared amongst other classes
# Builds request parameters.
hidden [hashtable] BuildRequestParams([string] $Method, [string] $Uri) {
$PSVersion = $global:PSVersionTable.PSVersion.Major
$ReqArgs = @{
Method = $Method
Uri = $this.ApiUri + $Uri
ContentType = 'application/json'
}
if ($this.RemoteApiAccessToken) {
$ReqArgs.Add('Headers', @{Authorization = "Bearer $($this.RemoteApiAccessToken)"})
}
elseif ($PSVersion -ge 6) {
$ReqArgs.Add('SkipCertificateCheck', $true)
}
elseif ($PSVersion -eq 5) {
$this.ResolvePs51HttpsCompatibility()
}
Return $ReqArgs
}
# Return errors and terminates execution
hidden [void] ReturnError([string] $e) {
Write-Error $e -ErrorAction Stop
}
# Simple string to help users get remote api access.
static [string] GetRemoteApiAccess() {
Return "To get an access token that permits this module to access your bridge via the Philips`r`nHue Remote API, please open a browser and visit https://www.lewisroberts.com/poshue"
}
# convert unix timestamps to local datetime objects
hidden [datetime] ConvertUnixTime([long] $Milliseconds) {
Return [System.DateTimeOffset]::FromUnixTimeMilliseconds($Milliseconds).LocalDateTime
}
# a technically static entry to configure the location of the remote api1
hidden [string] $HueRemoteApiUri = 'https://api.meethue.com/bridge/'
# get quota from the remote api
[pscustomobject] GetRemoteApiUsage() {
if (!($this.RemoteApiAccessToken)) {
Throw 'This method can only be used where the parent object is using the remote API.'
}
# Using a Web Request since Headers aren't available in Invoke-RestMethod in PS5.1
# 6.0+ would be Invoke-RestMethod @ReqParams -ResponseHeadersVariable HeaderVariable
$Result = Invoke-WebRequest -Method Get `
-Uri ("{0}{1}/{2}" -f $this.HueRemoteApiUri, $this.APIKey, 'lights') `
-Headers @{Authorization = "Bearer $($this.RemoteApiAccessToken)"} `
-ContentType 'application/json'
$QuotaObjects = $Result.Headers.Keys | Where-Object {$_ -match 'X-Quota'}
$Object = @{}
Foreach ($Item in $QuotaObjects) {
If ($Item -like '*Time*') {
$Object.Add($Item.ToString(), $this.ConvertUnixTime([long]$Result.Headers.Item($Item)[0]))
Continue
}
$Object.Add($Item.ToString(), $Result.Headers.Item($Item)[0])
}
Return $Object
}
# Some Windows PowerShell 5.1 specific code to handle move to HTTPS within Hue API 1.24.0
# Windows PowerShell 5.1 doesn't do well with self-signed certificates and needs to be
# forced to use TLS1.2 it seems.
# Second "if" may not be required since the same code run twice just returns the same class.
ResolvePs51HttpsCompatibility() {
$PSVersion = $global:PSVersionTable.PSVersion.Major
if (([System.Environment]::OSVersion.Platform -eq 'Win32NT') -and ($PSVersion -lt 6)) {
Add-Type -TypeDefinition "using System.Net; using System.Security.Cryptography.X509Certificates; public class TrustAllCertsPolicy : ICertificatePolicy { public bool CheckValidationResult(ServicePoint srvPoint, X509Certificate certificate, WebRequest request, int certificateProblem) {return true;} }"
[System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 # Force use of TLS 1.2
}
}
# End HueFactory
}
Class HueBridge : HueFactory {
##############
# PROPERTIES #
##############
[ipaddress] $BridgeIP
[ValidateLength(5, 50)][string] $APIKey
[ValidateLength(20, 50)][string] $RemoteApiAccessToken
[string] $ApiUri
################
# CONSTRUCTORS #
################
# Constructor to return an API Key
HueBridge([string] $Bridge) {
$this.BridgeIP = $Bridge
$this.ApiUri = "http://$($this.BridgeIP)/api/"
}
# Constructor to return lights and names of lights.
HueBridge([string] $Bridge, [string] $APIKey) {
$this.BridgeIP = $Bridge
$this.APIKey = $APIKey
$this.ApiUri = "http://$($this.BridgeIP)/api/$($this.APIKey)"
}
# Use a Remote API session but without a username/whitelist entry.
HueBridge([string] $RemoteApiAcccessToken, [bool]$RemoteSession) {
$this.RemoteApiAccessToken = $RemoteApiAcccessToken
$this.ApiUri = $this.HueRemoteApiUri
}
# Use a Remote API session with a username/whitelist entry.
HueBridge([string] $RemoteApiAcccessToken, [string] $APIKey, [bool] $RemoteSession) {
$this.RemoteApiAccessToken = $RemoteApiAcccessToken
$this.APIKey = $APIKey
$this.ApiUri = "{0}{1}" -f $this.HueRemoteApiUri, $this.APIKey
}
###########
# METHODS #
###########
static [PSObject] FindHueBridge() {
if ([System.Environment]::OSVersion.Platform -ne 'Win32NT') {
Throw 'Searching for your Philips Hue bridge via UPnP is not currently possible on Unix and Mac platforms. Please consult your network equipment to discover the bridge IP address.'
}
$UPnPFinder = New-Object -ComObject UPnP.UPnPDeviceFinder
$UPnPDevices = $UPnPFinder.FindByType("upnp:rootdevice", 0) | Where-Object {$_.Description -match "Hue"} | Select-Object FriendlyName, PresentationURL, SerialNumber | Format-List
Return $UPnPDevices
}
[string] GetNewAPIKey() {
if ($this.RemoteApiAccessToken) {
$ReqArgs = $this.BuildRequestParams('Put', '/0/config')
$Result = Invoke-RestMethod @ReqArgs -Body '{ "linkbutton":true }'
}
$ReqArgs = $this.BuildRequestParams('Post', '')
$Result = Invoke-RestMethod @ReqArgs -Body '{"devicetype":"PoSHue#PowerShell Hue"}'
If ($Result[0].error) {
Throw $Result[0].error.description
}
ElseIf ($Result[0].success) {
# Assign the API Key and return it.
$this.APIKey = $Result[0].success.username
$this.ApiUri = "$($this.ApiUri)$($this.APIKey)"
Return $Result[0].success.username
}
Else {
Throw "There was an error.`r`n$Result"
}
}
[array] GetLightNames() {
$Result = $null
If (!($this.APIKey)) {
Throw "This operation requires the APIKey property to be set."
}
$Result = $this.GetAllLights()
$Lights = $Result.PSObject.Members | Where-Object {$_.MemberType -eq "NoteProperty"}
Return $Lights.Value.Name
}
[PSCustomObject] GetAllLights() {
If (!($this.APIKey)) {
Throw "This operation requires the APIKey property to be set."
}
$Result = $null
Try {
$ReqArgs = $this.BuildRequestParams('Get', '/lights')
$Result = Invoke-RestMethod @ReqArgs
}
Catch {
$this.ReturnError('GetAllLights(): An error occurred while getting light data.' + $_)
}
Return $Result
}
[PSCustomObject] GetAllLightsObject() {
If (!($this.APIKey)) {
Throw "This operation requires the APIKey property to be set."
}
$Result = $this.GetAllLights()
$CountLights = ($Result.PSObject.Members | Where-Object {$_.MemberType -eq "NoteProperty"}).Count
$Object = for ($i = 1; $i -lt $CountLights + 1; $i++) {
$Property = [ordered]@{
Name = $Result.$i.name
Id = [int]$i
Type = $Result.$i.type
IsOn = $Result.$i.state.on
Brightness = $Result.$i.state.bri
Hue = $Result.$i.state.hue
Saturation = $Result.$i.state.sat
ColourTemp = $Result.$i.state.ct
XY = $Result.$i.state.xy
ColorMode = $Result.$i.state.colormode
Reachable = $Result.$i.state.reachable
ModelId = $Result.$i.modelid
Manufacturer = $Result.$i.manufacturername
}
# Create the new object.
New-Object -TypeName PSObject -Property $Property
}
Return $Object
}
[void] ToggleAllLights([LightState] $State) {
# A simple toggle affecting all lights in the system.
$Settings = @{}
Switch ($State) {
On {$Settings.Add("on", $true)}
Off {$Settings.Add("on", $false)}
}
Try {
$ReqArgs = $this.BuildRequestParams('Put', '/groups/0/action')
$Result = Invoke-RestMethod @ReqArgs -Body (ConvertTo-Json $Settings)
}
Catch {
$this.ReturnError('ToggleAllLights([LightState] $State): An error occurred while toggling lights.' + $_)
}
}
[void] SetHueScene([string] $SceneID) {
# Set a Hue Scene (collection of lights and their settings)
$Settings = @{}
$Settings.Add("scene", $SceneID)
Try {
$ReqArgs = $this.BuildRequestParams('Put', '/groups/0/action')
$Result = Invoke-RestMethod @ReqArgs -Body (ConvertTo-Json $Settings)
}
Catch {
$this.ReturnError('SetHueScene([string] $SceneID): An error occurred while setting a scene.' + $_)
}
}
[PSCustomObject] GetAllGroups() {
If (!($this.APIKey)) {
Throw "This operation requires the APIKey property to be set."
}
$Result = $null
Try {
$ReqArgs = $this.BuildRequestParams('Get', '/groups')
$Result = Invoke-RestMethod @ReqArgs
}
Catch {
$this.ReturnError('GetAllGroups(): An error occurred while getting group data.' + $_)
}
Return $Result
}
[PSCustomObject] GetAllSensors() {
If (!($this.APIKey)) {
Throw "This operation requires the APIKey property to be set."
}
$Result = $null
Try {
$ReqArgs = $this.BuildRequestParams('Get', '/sensors')
$Result = Invoke-RestMethod @ReqArgs
}
Catch {
$this.ReturnError('GetAllSensors(): An error occurred while getting sensor data.' + $_)
}
Return $Result
}
[pscustomobject] GetBridgeConfig() {
If (!($this.APIKey)) {
Throw "This operation requires the APIKey property to be set."
}
$Result = $null
Try {
$ReqArgs = $this.BuildRequestParams('Get', '/config')
$Result = Invoke-RestMethod @ReqArgs
}
Catch {
$this.ReturnError('GetBridgeConfig(): An error occurred while getting bridge configuration.' + $_)
}
Return $Result
}
[pscustomobject] GetWhitelistEntry() {
If (!($this.APIKey)) {
Throw "This operation requires the APIKey property to be set."
}
$Result = ($this.GetBridgeConfig()).whitelist
$Entries = $Result.PSObject.Members | Where-Object {$_.MemberType -eq "NoteProperty"}
$Object = foreach ($Entry in $Entries) {
$Property = [ordered]@{
WhitelistId = $Entry.Name
Name = $Entry.Value.name
CreationDate = $Entry.Value.'create date'
LastUsed = $Entry.Value.'last use date'
}
# Create the new object.
New-Object -TypeName PSObject -Property $Property
}
Return $Object
}
[pscustomobject] RemoveWhitelistEntry([string] $WhitelistEntry) {
If (!($this.APIKey)) {
Throw "This operation requires the APIKey property to be set."
}
$Result = $null
Try {
$ReqArgs = $this.BuildRequestParams('Delete', "/config/whitelist/$($WhitelistEntry)")
$Result = Invoke-RestMethod @ReqArgs
}
Catch {
$this.ReturnError('RemoveWhitelistEntry(): An error occurred while deleting the whitelist entry from the bridge.' + $_)
}
Return $Result
}
}
Class HueLight : HueFactory {
##############
# PROPERTIES #
##############
[ValidateLength(1, 2)][string] $Light
[ValidateLength(2, 80)][string] $LightFriendlyName
[ipaddress] $BridgeIP
[ValidateLength(5, 50)][string] $APIKey
[ValidateLength(1, 2000)][string] $JSON
[bool] $On
[ValidateRange(1, 254)][int] $Brightness
[ValidateRange(0, 65535)][int] $Hue
[ValidateRange(0, 254)][int] $Saturation
[ValidateRange(153, 500)][int] $ColourTemperature
[hashtable] $XY = @{ x = $null; y = $null }
[bool] $Reachable
[string] $ApiUri
[ValidateLength(20, 50)][string] $RemoteApiAccessToken
[ColourMode] $ColourMode
[AlertType] $AlertEffect
# Useful for if you would like visible temp indicators
hidden [hashtable] $ColourTemps = @{
t5 = [System.Drawing.Color]::FromArgb(80, 181, 221)
t6 = [System.Drawing.Color]::FromArgb(78, 178, 206)
t7 = [System.Drawing.Color]::FromArgb(76, 176, 190)
t8 = [System.Drawing.Color]::FromArgb(73, 173, 175)
t9 = [System.Drawing.Color]::FromArgb(72, 171, 159)
t10 = [System.Drawing.Color]::FromArgb(70, 168, 142)
t11 = [System.Drawing.Color]::FromArgb(68, 166, 125)
t12 = [System.Drawing.Color]::FromArgb(66, 164, 108)
t13 = [System.Drawing.Color]::FromArgb(102, 173, 94)
t14 = [System.Drawing.Color]::FromArgb(135, 190, 64)
t15 = [System.Drawing.Color]::FromArgb(179, 204, 26)
t16 = [System.Drawing.Color]::FromArgb(214, 213, 28)
t17 = [System.Drawing.Color]::FromArgb(249, 202, 3)
t18 = [System.Drawing.Color]::FromArgb(246, 181, 3)
t19 = [System.Drawing.Color]::FromArgb(244, 150, 26)
t20 = [System.Drawing.Color]::FromArgb(236, 110, 5)
t21 = [System.Drawing.Color]::FromArgb(234, 90, 36)
t22 = [System.Drawing.Color]::FromArgb(228, 87, 43)
t23 = [System.Drawing.Color]::FromArgb(225, 74, 41)
t24 = [System.Drawing.Color]::FromArgb(224, 65, 39)
t25 = [System.Drawing.Color]::FromArgb(217, 55, 43)
t26 = [System.Drawing.Color]::FromArgb(214, 49, 41)
t27 = [System.Drawing.Color]::FromArgb(209, 43, 43)
t28 = [System.Drawing.Color]::FromArgb(205, 40, 47)
t29 = [System.Drawing.Color]::FromArgb(200, 36, 50)
t30 = [System.Drawing.Color]::FromArgb(195, 35, 52)
}
###############
# CONSTRUCTOR #
###############
HueLight([string] $Name, [ipaddress] $Bridge, [string] $APIKey) {
$this.LightFriendlyName = $Name
$this.BridgeIP = $Bridge
$this.APIKey = $APIKey
$this.ApiUri = "http://$($this.BridgeIP)/api/$($this.APIKey)"
$this.Light = $this.GetHueLight($Name)
$this.GetStatus()
}
HueLight([int] $LightId, [ipaddress] $Bridge, [string] $APIKey) {
$this.BridgeIP = $Bridge
$this.APIKey = $APIKey
$this.ApiUri = "http://$($this.BridgeIP)/api/$($this.APIKey)"
$this.Light = $LightId
$this.GetStatus()
}
# Constructor to return lights and names of lights remotely.
HueLight([string] $Name, [string] $RemoteApiAcccessToken, [string] $APIKey, [bool] $RemoteSession) {
$this.LightFriendlyName = $Name
$this.RemoteApiAccessToken = $RemoteApiAcccessToken
$this.APIKey = $APIKey
$this.ApiUri = "{0}{1}" -f $this.HueRemoteApiUri, $this.APIKey
$this.Light = $this.GetHueLight($Name)
$this.GetStatus()
}
HueLight([int] $LightId, [string] $RemoteApiAcccessToken, [string] $APIKey, [bool] $RemoteSession) {
$this.RemoteApiAccessToken = $RemoteApiAcccessToken
$this.APIKey = $APIKey
$this.ApiUri = "{0}{1}" -f $this.HueRemoteApiUri, $this.APIKey
$this.Light = $LightId
$this.GetStatus()
}
###########
# METHODS #
###########
hidden [int] GetHueLight([string] $Name) {
If (!($Name)) { Throw "No light name was specified." }
# Change the named light in to the integer used by the bridge. We use this throughout.
$HueData = $null
Try {
$ReqArgs = $this.BuildRequestParams('Get', '/lights')
$HueData = Invoke-RestMethod @ReqArgs
}
Catch {
$this.ReturnError('GetHueLight([string] $Name): An error occurred while getting light information.' + $_)
}
$Lights = $HueData.PSObject.Members | Where-Object {$_.MemberType -eq "NoteProperty"}
$SelectedLight = $Lights | Where-Object {$_.Value.Name -eq $Name} | Select-Object Name -ExpandProperty Name
If ($SelectedLight) {
Return $SelectedLight
}
Else {
Throw "No light name matching `"$Name`" was found in the Hue Bridge.`r`nTry using [HueBridge]::GetLightNames() to get a full list of light names in this Hue Bridge."
}
}
hidden [void] GetStatus() {
# Get the current values of the State, Hue, Saturation, Brightness and Colour Temperatures
$Status = $null
Try {
$ReqArgs = $this.BuildRequestParams('Get', "/lights/$($this.Light)")
$Status = Invoke-RestMethod @ReqArgs
if ($Status.error -ne $null) {
$Output = 'Error: '
Foreach ($e in $Status) {
Switch ($e.error.type) {
# add more for specific errors if desired.
default {$Output += $e.error.description}
}
}
Throw $Output
}
}
Catch {
$this.ReturnError('GetStatus(): An error occurred while getting the status of the light.'+"`r`n" + $_)
}
$this.On = $Status.state.on
# If LightFriendlyName is null, fill it since we are probably working with LightId directly.
if (!($this.LightFriendlyName)) {
$this.LightFriendlyName = $Status.name
}
# If Light is not reachable, set On = false
if (!($Status.state.reachable)) {$this.On = $status.state.reachable}
$this.Reachable = $Status.state.reachable
# This is for compatibility reasons on Philips Ambient Lights
if ($Status.state.bri -ge 1) {$this.Brightness = $Status.state.bri}
$this.Hue = $Status.state.hue
$this.Saturation = $Status.state.sat
if (Get-Member -InputObject $Status.state -Name "colormode" -MemberType Properties) {
$this.ColourMode = $Status.state.colormode
# This is for compatibility reasons on Philips Ambient Lights
if ($Status.state.colormode -eq "xy") {
$this.XY.x = $Status.state.xy[0]
$this.XY.y = $Status.state.xy[1]
}
}
else {
$this.ColourMode = 'none'
}
If ($Status.state.ct) {
<#
My Hue Go somehow got itself to a colour temp of "15" which is supposed
to be impossible. The [ValidateRange] of Colour Temp meant it wasn't possible
to instantiate the [HueLight] class because it was outside the valid range of
values accepted by the property. Makes sense but now means I need to handle
possible impossible values. Added to the fact that this property might not
exist on lights that don't support colour temperature, it's a bit of a pain.
#>
Switch ($Status.state.ct) {
{($Status.state.ct -lt 153)} {$this.ColourTemperature = 153; break}
{($Status.state.ct -gt 500)} {$this.ColourTemperature = 500; break}
default {$this.ColourTemperature = $Status.state.ct}
}
}
$this.AlertEffect = $Status.state.alert
}
# A simple toggle. If on, turn off. If off, turn on.
[void] SwitchHueLight() {
Switch ($this.On) {
$false {$this.On = $true}
$true {$this.On = $false}
}
$Settings = @{}
$Settings.Add("on", $this.On)
Try {
$ReqArgs = $this.BuildRequestParams('Put', "/lights/$($this.Light)/state")
$Result = Invoke-RestMethod @ReqArgs -Body (ConvertTo-Json $Settings)
}
Catch {
$this.ReturnError('SwitchHueLight(): An error occurred while toggling the light.' + $_)
}
}
# Set the state of the light. Always does what you give it, irrespective of the current setting.
[void] SwitchHueLight([LightState] $State) {
# An overload for SwitchHueLight
Switch ($State) {
On {$this.On = $true}
Off {$this.On = $false}
}
$Settings = @{}
$Settings.Add("on", $this.On)
Try {
$ReqArgs = $this.BuildRequestParams('Put', "/lights/$($this.Light)/state")
$Result = Invoke-RestMethod @ReqArgs -Body (ConvertTo-Json $Settings)
}
Catch {
$this.ReturnError('SwitchHueLight([LightState] $State): An error occurred while switching the light .' + $_)
}
}
# Set the state of the light (from off) for a transition - like a sunrise.
[void] SwitchHueLight([LightState] $State, [bool] $Transition) {
# An overload for SwitchHueLight
Switch ($State) {
On {$this.On = $true}
Off {$this.On = $false}
}
$Settings = @{}
$Settings.Add("on", $this.On)
If ($this.On -and $Transition) {
$this.Brightness = 1
$Settings.Add("bri", $this.Brightness)
}
Try {
$ReqArgs = $this.BuildRequestParams('Put', "/lights/$($this.Light)/state")
$Result = Invoke-RestMethod @ReqArgs -Body (ConvertTo-Json $Settings)
}
Catch {
$this.ReturnError('SwitchHueLight([LightState] $State, [bool] $Transition): An error occurred while toggling the light for transition.' + $_)
}
}
### Set the light's brightness value ###
[string] SetHueLight([int] $Brightness) {
# Set the brightness values of the light.
If (!($this.On)) {
Throw "Light `"$($this.LightFriendlyName)`" must be on in order to set Brightness."
}
$Result = $null
$this.Brightness = $Brightness
$Settings = @{}
$Settings.Add("bri", $this.Brightness)
Try {
$ReqArgs = $this.BuildRequestParams('Put', "/lights/$($this.Light)/state")
$Result = Invoke-RestMethod @ReqArgs -Body (ConvertTo-Json $Settings)
}
Catch {
$this.ReturnError('SetHueLight([int] $Brightness): An error occurred while setting the light brightness.' + $_)
}
# Handle errors - incomplete in reality but should suffice for now.
If (($Result.success -ne $null) -and ($Result.error -eq $null)) {
$this.GetStatus()
Return "Success"
}
ElseIf ($Result.error -ne $null) {
$Output = 'Error: '
Foreach ($e in $Result) {
Switch ($e.error.type) {
201 {$Output += $e.error.description}
default {$Output += "Unknown error: $($e.error.description)"}
}
}
Throw $Output
}
Else {Throw "An error occurred setting the brightness."}
}
###############################################
# Importance of colour settings: XY > CT > HS #
###############################################
### Set an XY value ###
# Depends on the Gamut capability of the target Light
# See: http://www.developers.meethue.com/documentation/hue-xy-values
[string] SetHueLight([int] $Brightness, [float] $X, [float] $Y) {
# Set brightness and XY values.
If (!($this.On)) {
Throw "Light `"$($this.LightFriendlyName)`" must be on in order to set Brightness and/or Colour Temperature."
}
$Result = $null
$this.Brightness = $Brightness
$this.XY.x = $X
$this.XY.y = $Y
$Settings = @{}
$Settings.Add("xy", @($this.XY.x, $this.XY.y))
$Settings.Add("bri", $this.Brightness)
Try {
$ReqArgs = $this.BuildRequestParams('Put', "/lights/$($this.Light)/state")
$Result = Invoke-RestMethod @ReqArgs -Body (ConvertTo-Json $Settings)
}
Catch {
$this.ReturnError('SetHueLight([int] $Brightness, [float] $X, [float] $Y): An error occurred while setting the light for XY.' + $_)
}
If (($Result.success -ne $null) -and ($Result.error -eq $null)) {
$this.GetStatus()
Return "Success"
}
ElseIf ($Result.error -ne $null) {
$Output = 'Error: '
Foreach ($e in $Result) {
Switch ($e.error.type) {
201 {$Output += $e.error.description}
default {$Output += "Unknown error: $($e.error.description)"}
}
}
Throw $Output
}
Else {Throw "An error occurred setting the Brightness or XY colour value."}
}
### Set a colour temperature ###
[string] SetHueLight([int] $Brightness, [int] $ColourTemperature) {
# Set the brightness and colour temperature of the light.
If (!($this.On)) {
Throw "Light `"$($this.LightFriendlyName)`" must be on in order to set Brightness and/or Colour Temperature."
}
If (!($this.ColourTemperature)) {
Throw "Light named `"$($this.LightFriendlyName)`" does not hold the `"ct`" setting or it could not be read properly during`r`nobject instantiation. Does it support Colour Temperature? If so, please report a bug."
}
$Result = $null
$this.Brightness = $Brightness
$this.ColourTemperature = $ColourTemperature
$Settings = @{}
$Settings.Add("bri", $this.Brightness)
$Settings.Add("ct", $this.ColourTemperature)
Try {
$ReqArgs = $this.BuildRequestParams('Put', "/lights/$($this.Light)/state")
$Result = Invoke-RestMethod @ReqArgs -Body (ConvertTo-Json $Settings)
}
Catch {
$this.ReturnError('SetHueLight([int] $Brightness, [int] $ColourTemperature): An error occurred while setting the light for CT.' + $_)
}
If (($Result.success -ne $null) -and ($Result.error -eq $null)) {
$this.GetStatus()
Return "Success"
}
ElseIf ($Result.error -ne $null) {
$Output = 'Error: '
Foreach ($e in $Result) {
Switch ($e.error.type) {
201 {$Output += $e.error.description}
default {$Output += "Unknown error: $($e.error.description)"}
}
}
Throw $Output
}
Else {Throw "An error occurred setting the Brightness or Colour Temperature."}
}
### Set an HSB value ###
[string] SetHueLight([int] $Brightness, [int] $Hue, [int] $Saturation) {
# Set the brightness, hue and saturation values of the light.
If (!($this.On)) {
Throw "Light `"$($this.LightFriendlyName)`" must be on in order to set Hue, Saturation and/or Brightness."
}
$Result = $null
$this.Brightness = $Brightness
$this.Hue = $Hue
$this.Saturation = $Saturation
$Settings = @{}
$Settings.Add("bri", $this.Brightness)
$Settings.Add("hue", $this.Hue)
$Settings.Add("sat", $this.Saturation)
Try {
$ReqArgs = $this.BuildRequestParams('Put', "/lights/$($this.Light)/state")
$Result = Invoke-RestMethod @ReqArgs -Body (ConvertTo-Json $Settings)
}
Catch {
$this.ReturnError('SetHueLight([int] $Brightness, [int] $Hue, [int] $Saturation): An error occurred while setting the light for HS.' + $_)
}
# Handle errors - incomplete in reality but should suffice for now.
If (($Result.success -ne $null) -and ($Result.error -eq $null)) {
$this.GetStatus()
Return "Success"
}
ElseIf ($Result.error -ne $null) {
$Output = 'Error: '
Foreach ($e in $Result) {
Switch ($e.error.type) {
201 {$Output += $e.error.description}
default {$Output += "Unknown error: $($e.error.description)"}
}
}
Throw $Output
}
Else {Throw "An error occurred setting the Hue, Saturation or Brightness."}
}
[void] Breathe([AlertType] $AlertEffect) {
# Perform a breathe action on the light. Limited input values accepted, "none", "select", "lselect".
$this.AlertEffect = $AlertEffect
$Settings = @{}
$Settings.Add("alert", [string] $this.AlertEffect)
Try {
$ReqArgs = $this.BuildRequestParams('Put', "/lights/$($this.Light)/state")
$Result = Invoke-RestMethod @ReqArgs -Body (ConvertTo-Json $Settings)
}
Catch {
$this.ReturnError('Breathe([AlertType] $AlertEffect): An error occurred while setting the breathe state.' + $_)
}
}
# Set brightness and XY values with transition time.
[string] SetHueLightTransition([int] $Brightness, [float] $X, [float] $Y, [uint16] $TransitionTime) {
If (!($this.On)) {
Throw "Light `"$($this.LightFriendlyName)`" must be on in order to set Brightness and/or Colour Temperature."
}
$Result = $null
$this.Brightness = $Brightness
$this.XY.x = $X
$this.XY.y = $Y
$Settings = @{}
$Settings.Add("xy", @($this.XY.x, $this.XY.y))
$Settings.Add("bri", $this.Brightness)
$Settings.Add("transitiontime", $TransitionTime)
Try {
$ReqArgs = $this.BuildRequestParams('Put', "/lights/$($this.Light)/state")
$Result = Invoke-RestMethod @ReqArgs -Body (ConvertTo-Json $Settings)
}
Catch {
$this.ReturnError('SetHueLightTransition([int] $Brightness, [float] $X, [float] $Y, [uint16] $TransitionTime): An error occurred while setting the light for XY transition.' + $_)
}
If (($Result.success -ne $null) -and ($Result.error -eq $null)) {
$this.GetStatus()
Return "Success"
}
ElseIf ($Result.error -ne $null) {
$Output = 'Error: '
Foreach ($e in $Result) {
Switch ($e.error.type) {
201 {$Output += $e.error.description}
default {$Output += "Unknown error: $($e.error.description)"}
}
}
Throw $Output
}
Else {Throw "An error occurred setting the Brightness or XY colour value."}
}
# Set the brightness and colour temperature of the light with transition time
[string] SetHueLightTransition([int] $Brightness, [int] $ColourTemperature, [uint16] $TransitionTime) {
If (!($this.On)) {
Throw "Light `"$($this.LightFriendlyName)`" must be on in order to set Brightness and/or Colour Temperature."
}
If (!($this.ColourTemperature)) {
Throw "Light named `"$($this.LightFriendlyName)`" does not hold the `"ct`" setting or it could not be read properly during`r`nobject instantiation. Does it support Colour Temperature? If so, please report a bug."
}
$Result = $null
$this.Brightness = $Brightness
$this.ColourTemperature = $ColourTemperature
$Settings = @{}
$Settings.Add("bri", $this.Brightness)
$Settings.Add("ct", $this.ColourTemperature)
$Settings.Add("transitiontime", $TransitionTime)
Try {
$ReqArgs = $this.BuildRequestParams('Put', "/lights/$($this.Light)/state")
$Result = Invoke-RestMethod @ReqArgs -Body (ConvertTo-Json $Settings)
}
Catch {
$this.ReturnError('SetHueLightTransition([int] $Brightness, [int] $ColourTemperature, [uint16] $TransitionTime): An error occurred while setting the light for CT transition.' + $_)
}
If (($Result.success -ne $null) -and ($Result.error -eq $null)) {
$this.GetStatus()
Return "Success"
}
ElseIf ($Result.error -ne $null) {
$Output = 'Error: '
Foreach ($e in $Result) {
Switch ($e.error.type) {
201 {$Output += $e.error.description}
default {$Output += "Unknown error: $($e.error.description)"}
}
}
Throw $Output
}
Else {Throw "An error occurred setting the Brightness or Colour Temperature."}
}
[string] SetHueLightTransition([int] $Brightness, [int] $Hue, [int] $Saturation, [uint16] $TransitionTime) {
# Set the brightness, hue and saturation values of the light.
If (!($this.On)) {
Throw "Light `"$($this.LightFriendlyName)`" must be on in order to set Hue, Saturation and/or Brightness."
}
$Result = $null
$this.Brightness = $Brightness
$this.Hue = $Hue
$this.Saturation = $Saturation
$Settings = @{}
$Settings.Add("bri", $this.Brightness)
$Settings.Add("hue", $this.Hue)
$Settings.Add("sat", $this.Saturation)
$Settings.Add("transitiontime", $TransitionTime)
Try {
$ReqArgs = $this.BuildRequestParams('Put', "/lights/$($this.Light)/state")
$Result = Invoke-RestMethod @ReqArgs -Body (ConvertTo-Json $Settings)
}
Catch {
$this.ReturnError('SetHueLightTransition([int] $Brightness, [int] $Hue, [int] $Saturation, [uint16] $TransitionTime): An error occurred while setting the light for HS transition.' + $_)
}
# Handle errors - incomplete in reality but should suffice for now.
If (($Result.success -ne $null) -and ($Result.error -eq $null)) {
$this.GetStatus()
Return "Success"
}
ElseIf ($Result.error -ne $null) {
$Output = 'Error: '
Foreach ($e in $Result) {
Switch ($e.error.type) {
201 {$Output += $e.error.description}
default {$Output += "Unknown error: $($e.error.description)"}
}
}
Throw $Output
}
Else {Throw "An error occurred setting the Hue, Saturation or Brightness."}
}
# Convert an RGB colour to XYZ format
<#
Don't use this straight conversion XY output to push to the light as it may be outside
of the light's capabilities - it won't damage the light, the light will just
make a bad guess. Use the output from this method and feed it through
.xybForModel([hashtable] $ConvertedXYZ, [hashtable] $GamutTriangle)
to get a colour and brightness more appropriate for your model/Gamut of luminaire.
Yes, this could be improved by associating the model number with a Gamut
triangle but this would require maintaining as often as Philips release
new bulbs with different capabilities.
For now, use the Gamut name identified from:
http://www.developers.meethue.com/documentation/supported-lights
(You need to register to see the list unfortunately)
If you're asking yourself, what's a Gamut?! It's the ability of a bulb
to reproduce a colour within the CIE colour spectrum. Some Gamuts aren't
as wide.
For example, the hue bulbs (Gamut B) are very good at showing nice whites,
while the LivingColors (Gamut A) are generally a bit better at colours, like
green and cyan. Newer models like the Hue Go and Hue LightStrips Plus use Gamut C.
#>
[hashtable] RGBtoXYZ([System.Drawing.Color] $Colour) {
# Set up a return value [hashtable]
$ret = @{}
# Convert the RGB values to 0..1 values
[float] $r = $Colour.R / 255
[float] $g = $Colour.G / 255
[float] $b = $Colour.B / 255
# Gamma correction
[float] $red = if ($r -gt [float]0.04045) { [Math]::Pow(($r + [float]0.055) / ([float]1.0 + [float]0.055), [float]2.4) } Else { ($r / [float]12.92) }
[float] $green = if ($g -gt [float]0.04045) { [Math]::Pow(($g + [float]0.055) / ([float]1.0 + [float]0.055), [float]2.4) } Else { ($g / [float]12.92) }
[float] $blue = if ($b -gt [float]0.04045) { [Math]::Pow(($b + [float]0.055) / ([float]1.0 + [float]0.055), [float]2.4) } Else { ($b / [float]12.92) }
# Convert the RGB values to XYZ using the Wide RGB D65 conversion formula
[float] $x = ($red * [float]0.664511) + ($green * [float]0.154324) + ($blue * [float]0.162028)
[float] $y = ($red * [float]0.283881) + ($green * [float]0.668433) + ($blue * [float]0.047685)
[float] $z = ($red * [float]0.000088) + ($green * [float]0.072310) + ($blue * [float]0.986039)
# Create the return values
[float] $ret.x = $x / ($x + $y + $z)
[float] $ret.y = $y / ($x + $y + $z)
[float] $ret.z = $z / ($x + $y + $z)
If ($ret.x.ToString() -eq 'NaN') { $ret.x = [float]0.0 }
If ($ret.y.ToString() -eq 'NaN') { $ret.y = [float]0.0 }
If ($ret.z.ToString() -eq 'NaN') { $ret.z = [float]0.0 }
Return $ret
}
<#
Stores a set of Gamut values depicting the end points of a triangle
corresponding to the Gamut of a bulb. The calculated XY values are compared
with these points to see if the converted XY values fall within this triangle.
If not, they're smoothed out by calculating the closest point.
#>
[hashtable] GamutTriangles([Gamut] $GamutID) {
$GamutTriangles = @{
GamutA = @{
Red = @{ x = 0.704; y = 0.296 }
Green = @{ x = 0.2151; y = 0.7106 }
Blue = @{ x = 0.138; y = 0.08 }
}