AutomaTD.psm1

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
function GetTelldusAccessToken
{
    [cmdletbinding()]
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingConvertToSecureStringWithPlainText", '', Scope="Function", Target="GetTelldusAccessToken")]
    Param(
        $RequestToken
    )

    BEGIN { }

    PROCESS {
        $RequestTokenJson = $RequestToken | ConvertTo-Json
        $TokenResponse = Invoke-RestMethod -Uri https://tl.p0wershell.com/api/GetAccessToken -Method Post -Body $RequestTokenJson   

        [PSCustomObject] @{
            Token = $TokenResponse.Token
            TokenSecret = (ConvertTo-SecureString -String $TokenResponse.TokenSecret -AsPlainText -Force -ErrorAction Stop)
        }

        Remove-Variable TokenResponse -ErrorAction SilentlyContinue
        [GC]::Collect()
    }

    END { }
}
function GetTelldusProperty
{
    [cmdletbinding()]
    Param(
        $Data
    )

    BEGIN {
        $TextFormat = (Get-Culture).TextInfo
    }

    PROCESS {
        foreach ($dataObj in $Data) {
            $Properties = @{}

            $KeyName = $textFormat.ToTitleCase($dataObj.Name.ToLower())

            # Resolve sensors types to friendly names if they are known
            $KeyName = switch ($KeyName) {
                'Temp'   { 'Temperature' }
                'rrate'  { 'RainRate' }
                'rtot'   { 'RainTotal' }
                'wdir'   { 'WindDirection' }
                'wavg'   { 'WindAverage' }
                'wgust'  { 'WindGust' }
                'watt'   { 'Watt' }
                'lum'    { 'Luminance' }
                default  { $KeyName }
            }

            if ($Properties.ContainsKey($KeyName)) {
                Write-Warning "Property $KeyName already exists. It will be dropped."
            }
            else {
                $Properties.Add($TextFormat.ToTitleCase($KeyName), $dataObj.value)
            }

            $Properties
        }
    }

    END { }
}
function GetTelldusRequestToken
{
    Invoke-RestMethod -Uri https://tl.p0wershell.com/api/GetRequestToken
}
function InvokeTelldusAction
{
    Param($URI)

    BEGIN {
        $ApiUri = 'https://tl.p0wershell.com/api/InvokeAction'

        if (-not [Net.ServicePointManager]::SecurityProtocol.HasFlag([Net.SecurityProtocolType]::Tls12) -AND $EnableTls12) {
            [Net.ServicePointManager]::SecurityProtocol += [Net.SecurityProtocolType]::Tls12
        }
    }

    PROCESS {
        $Payload = @{
            Token = $Global:TelldusLiveAccessToken.Token
            TokenSecret = [System.Runtime.InteropServices.Marshal]::PtrToStringUni([System.Runtime.InteropServices.Marshal]::SecureStringToCoTaskMemUnicode($Global:TelldusLiveAccessToken.TokenSecret))
            URI = $URI
        } | ConvertTo-Json

        $Response = try {
            Invoke-RestMethod -Uri $ApiUri -Method Post -Body $Payload -ErrorAction Stop
        }
        catch {
            throw "Request failed with error: $($_.Exception.Message)"
        }

        if ($Response.error) {
            throw $Response.error
        }
        else {
            $Response
        }
    }

    END {
        Remove-Variable Payload -ErrorAction SilentlyContinue
        [GC]::Collect()
    }
}
function Backup-TDAccount
{
    <#
    .SYNOPSIS
    Exports information from Telldus Live! to the specified folder
 
    .DESCRIPTION
    This function will fetch information about Clients (Locations), devices,
    sensors, schedules and events from the Telldus Live! API and export the
    data as XML to the specified folder.
 
    This backup can potentially be used to restore for example events or
    schedules if they become broken.
 
    This backup does NOT include device/sensor history and values!
 
    .EXAMPLE
    Backup-TDAccount -Verbose
 
    Exports the backups and logs a verbose message for each type of information that get's exported
    #>


    [CmdletBinding()]
    Param(
        $BackupFolderPath
    )

    BEGIN {
        if ($TelldusLiveAccessToken -eq $null) {
            throw "You must first connect using the Connect-TelldusLive cmdlet"
        }
    }

    PROCESS {
        if (-not (Test-Path -Path $BackupFolderPath)) {
            $null = New-Item -Path $BackupFolderPath -ItemType Directory -Force
        }

        Write-Verbose "Backing up client/location information..."
        $ClientBackupPath = Join-Path -Path $BackupFolderPath -ChildPath ClientBackup.xml
        Get-TDClient | Get-TDClient | Export-Clixml -Path $ClientBackupPath -Encoding UTF8 -Depth 10 -Force

        Write-Verbose "Backing up device information..."
        $DeviceBackupPath = Join-Path -Path $BackupFolderPath -ChildPath DeviceBackup.xml
        Get-TDDevice | Export-Clixml -Path $DeviceBackupPath -Encoding UTF8 -Depth 10 -Force

        Write-Verbose "Backing up sensor information..."
        $SensorBackupPath = Join-Path -Path $BackupFolderPath -ChildPath SensorBackup.xml
        Get-TDSensor | Export-Clixml -Path $SensorBackupPath -Encoding UTF8 -Depth 10 -Force

        Write-Verbose "Backing up schedule information..."
        $ScheduleBackupPath = Join-Path -Path $BackupFolderPath -ChildPath ScheduleBackup.xml
        Get-TDSchedule | Export-Clixml -Path $ScheduleBackupPath -Encoding UTF8 -Depth 10 -Force

        Write-Verbose "Backing up trigger event information..."
        $EventBackupPath = Join-Path -Path $BackupFolderPath -ChildPath EventBackup.xml
        Get-TDTriggerEvent | Get-TDTriggerEvent | Export-Clixml -Path $EventBackupPath -Encoding UTF8 -Depth 10 -Force
    }

    END { }
}
function Connect-TelldusLive
{
    <#
    .SYNOPSIS
    Connects to Telldus Live!
 
    .DESCRIPTION
    This function connects to Telldus Live! by either using a saved access token or
    by creating a new one.
 
    .EXAMPLE
    Connect-TelldusLive
 
    .EXAMPLE
    Connect-TelldusLive -SaveCredential
 
    Will return a link which you need to authorize and then save that access token for later use.
 
    .PARAMETER Profile
    The name of the profile you use to connect. You can leave this to "Default" (default value)
    if you don't have more than one Telldus Live! account.
 
    .PARAMETER Credential
    If you have a known access token, you can specify it as a PSCredential object.
 
    Username should be the AccessToken
    Password Should be the AccessTokenSecret
 
    .PARAMETER AccessToken
    If you have a known access token, you can specify it here (not the AccessTokenSecret)
 
    .PARAMETER AccessTokenSecret
    If you have a known access TokenSecret, you can specify it here (as a secure string)
 
    .PARAMETER SaveCredential
    Will save and store the access token after it has been retieved so it can be reused later
     
    You can then connect by simply using the -UseSavedCredential switch. The credential is saved using your logon session.
 
    .PARAMETER UseSavedCredential
    Specify this switch to use a saved credential instead of specifying one.
 
    #>


    [cmdletbinding(DefaultParameterSetName='SpecifyCredential')]
    Param (
        [Parameter(Mandatory=$false)]
        $Profile = 'Default',

        [Parameter(Mandatory=$true, ParameterSetName='SpecifyAccessTokenAsCredential')]
        [PSCredential] $Credential,

        [Parameter(Mandatory=$true, ParameterSetName='SpecifyAccessToken')]
        $AccessToken,

        [Parameter(Mandatory=$true, ParameterSetName='SpecifyAccessToken')]
        [System.Security.SecureString] $AccessTokenSecret,

        [Parameter(Mandatory=$false)]
        [Switch] $SaveCredential,

        [Parameter(Mandatory=$false, ParameterSetName='SavedCredential')]
        [Switch] $UseSavedCredential
    )

    BEGIN { }

    PROCESS {
        $AccessTokenFolder = Join-Path -Path $($env:APPDATA) -ChildPath AutomaTD

        if ( -not (Test-Path -Path $AccessTokenFolder)) {
            $null = New-Item -Path $AccessTokenFolder -ItemType Directory -Force
        }

        $AccessTokenFilename = "TelldusAccessToken-$($Profile).json"
        $AccessTokenFilePath = Join-Path -Path $AccessTokenFolder -ChildPath $AccessTokenFilename

        if ($PSCmdlet.ParameterSetName -eq 'SavedCredential') {
            if (Test-Path -Path $AccessTokenFilePath) {
                $AccessTokenFromDisk = Get-Content $AccessTokenFilePath -Raw -Encoding UTF8 | ConvertFrom-Json

                $Token = $AccessTokenFromDisk.Token
                $TokenSecret = $AccessTokenFromDisk.TokenSecret | ConvertTo-SecureString

                # Build the token
                $AccessToken = [PSCustomObject] @{
                    Token = $Token
                    TokenSecret = $TokenSecret
                }
            }
            else {
                throw "Didn't locate any saved access tokens. Please run this command with the 'SaveCredential' switch first to store the credentials or verify which profile you choose."
            }
        }
        elseif ($PSCmdlet.ParameterSetName -eq 'SpecifyAccessToken') {
            # Build the credential
            $AccessToken = [PSCustomObject] @{
                Token = $AccessToken
                TokenSecret = $AccessTokenSecret
            }
        }
        elseif ($PSCmdlet.ParameterSetName -eq 'SpecifyAccessTokenAsCredential') {
            # Build the credential
            $AccessToken = [PSCustomObject] @{
                Token = $Credential.UserName
                TokenSecret = $Credential.Password
            }
        }
        else {
            $RequestToken = GetTelldusRequestToken
            Write-Output "Please go to the following URL to authenticate this module:`n$($RequestToken.AuthURL)"

            $PollingAttempts = 20
            Do {
                $PollingAttempts--
                $AuthFailed = $false

                try {
                    $AccessToken = GetTelldusAccessToken -RequestToken $RequestToken -ErrorAction Stop
                }
                catch {
                    $AuthFailed = $true

                    Start-Sleep -Seconds 15
                }
            }
            while ($AuthFailed -and $PollingAttempts -gt 0)

            if (-not $AccessToken) {
                throw "Authorization failed or timed out. Please try again."
            }

            if ($SaveCredential.IsPresent) {
                $ExportToken = @{
                    Token = $AccessToken.Token
                    TokenSecret = ConvertFrom-SecureString -SecureString $AccessToken.TokenSecret
                }

                $ExportToken | ConvertTo-Json -Compress | Out-File -FilePath $AccessTokenFilePath -Encoding utf8 -Force
            }
        }

        $Global:TelldusLiveAccessToken = $AccessToken

        try {
            $null = Get-TDClient -ErrorAction Stop
        }
        catch {
            throw "Failed to connect to Telldus Live! The error was: $($_.Exception.Message)"
        }
    }

    END {
    
    }
}
function ConvertTo-TDNormalizedOutput
{
    <#
    .SYNOPSIS
    Makes sure all objects have the same set of properties
 
    .DESCRIPTION
    Makes sure all objects have the same set of properties
 
    Makes exporting to for example CSV-files easiser since all sensors will have
    the same set of "columns" in the file (but blank values for those missing that
    sensor value type).
 
    .EXAMPLE
    Get-TDSensor | Get-TDSensorData | ConvertTo-TDNormalizedOutput
 
    Makes sure all objects have the same set of properties
 
    .EXAMPLE
    Get-TDSensor | Get-TDSensorData | ConvertTo-TDNormalizedOutput -PropertiesToAlwaysInclude CustomSensorData
 
    Makes sure all objects have the same set of properties, and "CustomSensorData" will always be a property
    of the objects even if it doesn't exist in the results.
 
    #>


    [cmdletbinding()]
    param(
        [Parameter(Mandatory=$true, ValueFromPipeline=$true)]
        $InputObject,

        [Parameter(Mandatory=$false)]
        [string[]] $PropertiesToAlwaysInclude
    )

    begin {
        $Properties = New-Object System.Collections.Generic.HashSet[string]
        $Objects = New-Object System.Collections.Generic.List[System.Object]
    }

    process {
        $null = $InputObject.psobject.Properties.Name.foreach({$Properties.Add($_)})
        $Objects.Add($InputObject)
    }

    end {
        if ($PropertiesToAlwaysInclude) {
            foreach ($Property in $PropertiesToAlwaysInclude) {
                if ($Property -notin $Properties) {
                    $null = $Properties.Add($Property)
                }
            }
        }

        $Objects | Select-Object -Property @($Properties)
    }
}
function Get-TDAccessToken
{
    <#
    .SYNOPSIS
    Used to export the access token as a PSCredential or as plain text
 
    .DESCRIPTION
    Used to export the access token as a PSCredential or as plain text
 
    Useful if you want to set it up on a new computer where you wont be able to
    interact with the login command interactively or store the token.
 
    Be aware that exporting the access token as plain-text is a security risk!
 
    Only do this on systems that you trust.
 
    .EXAMPLE
    Get-TDAccessToken -ExportAsPSCredential
 
    #>


    [CmdletBinding(DefaultParameterSetName='AsPSCredential')]
    Param(
        [Parameter(Mandatory=$false, ParameterSetName='AsPSCredential')]
        [switch] $ExportAsPSCredential,

        [Parameter(Mandatory=$true, ParameterSetName='AsPlainText')]
        [switch] $ExportAsPlainText,

        [Parameter(Mandatory=$false, ParameterSetName='AsPlainText')]
        [switch] $Force
    )

    BEGIN {
        if ($TelldusLiveAccessToken -eq $null) {
            throw "You must first connect using the Connect-TelldusLive cmdlet to load the access token"
        }
    }

    PROCESS {
        if ($PSCmdlet.ParameterSetName -eq 'AsPSCredential') {
            New-Object System.Management.Automation.PSCredential ($Global:TelldusLiveAccessToken.Token, $Global:TelldusLiveAccessToken.TokenSecret)
        }
        elseif ($PSCmdlet.ParameterSetName -eq 'AsPlainText') {
            if ($Force.IsPresent) {
                [PSCustomObject] @{
                    Token = $Global:TelldusLiveAccessToken.Token
                    TokenSecret = [System.Runtime.InteropServices.Marshal]::PtrToStringUni([System.Runtime.InteropServices.Marshal]::SecureStringToCoTaskMemUnicode($Global:TelldusLiveAccessToken.TokenSecret))
                }
            }
            else {
                throw "The system cannot protect plain text output. To suppress this warning and output the access token as plain text anyway, reissue the command specifying the Force parameter."
            }
        }
    }

    END { }
}
function Get-TDClient
{
    <#
    .SYNOPSIS
    Retrieves all clients/locations associated with a Telldus Live! account.
 
    .DESCRIPTION
    Retrieves all clients/locations associated with a Telldus Live! account.
 
    .EXAMPLE
    Get-TDClient
 
    #>


    [CmdletBinding()]
    Param(
        [Parameter(Mandatory=$false, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
        [Alias('id')]
        [string] $ClientID
    )

    BEGIN {
        if ($TelldusLiveAccessToken -eq $null) {
            throw "You must first connect using the Connect-TelldusLive cmdlet"
        }
    }

    PROCESS {
        if ($ClientID) {
            $response = InvokeTelldusAction -URI "client/info?id=$ClientID&extras=coordinate,suntime,timezone,tzoffset"
            $Clients = $response
        }
        else {
            $response = InvokeTelldusAction -URI "clients/list"
            $Clients = $response.client
        }

        foreach ($Client in $Clients) {
            $Client.online = [bool] $Client.online
            $Client.editable = [bool] $Client.editable

            if ($Client.sunrise) {
                $Client.sunrise = (Get-Date "1970-01-01 00:00:00").AddSeconds($Client.sunrise)
            }

            if ($Client.sunset) {
                $Client.sunset = (Get-Date "1970-01-01 00:00:00").AddSeconds($Client.sunset)
            }
            
            $Client
        }
    }

    END { }
}
function Get-TDDevice
{
    <#
    .SYNOPSIS
    Retrieves all devices associated with a Telldus Live! account.
 
    .DESCRIPTION
    This command will list all devices associated with an Telldus Live!-account and their current status and other information.
 
    .EXAMPLE
    Get-TDDevice
 
    .EXAMPLE
    Get-TDDevice | Format-Table
 
    #>


    [CmdletBinding()]
    Param(
        [Parameter(Mandatory=$false, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
        [Alias('id')]
        [string] $DeviceID
    )

    BEGIN {
        if ($TelldusLiveAccessToken -eq $null) {
            throw "You must first connect using the Connect-TelldusLive cmdlet"
        }
    }

    PROCESS {

        if ($DeviceID) {
            $response = InvokeTelldusAction -URI "device/info?id=$DeviceID&supportedMethods=19&extras=coordinate,metadata,timezone,transport,tzoffset"
            $DeviceList = $response
        }
        else {
            $response = InvokeTelldusAction -URI 'devices/list?supportedMethods=19'
            $DeviceList = $response.device
        }

        foreach ($Device in $DeviceList) {

            $PropertiesToOutput = [ordered] @{
                                 'Name' = $Device.name
                                 'DeviceID' = $Device.id
                                 'State' = switch ($Device.state)
                                           {
                                                 1 { "On" }
                                                 2 { "Off" }
                                                16 { "Dimmed" }
                                                default { "Unknown" }
                                           }
                                 'Statevalue' = $Device.statevalue
                                 'Methods' = switch ($Device.methods)
                                             {
                                                 3 { "On/Off" }
                                                19 { "On/Off/Dim" }
                                                default { "Unknown" }
                                             }
                                 'Type' = $Device.type
                                 'Client' = $Device.client
                                 'Online' = switch ($Device.online)
                                            {
                                                0 { $false }
                                                1 { $true }
                                            }
                                 }

            if ($Device.longitude) {
                $PropertiesToOutput.Add('Longitude', $Device.longitude)
            }

            if ($Device.latitude) {
                $PropertiesToOutput.Add('Latitude', $Device.latitude)
            }

            if ($Device.clientName) {
                $PropertiesToOutput.Add('ClientName', $Device.clientName)
            }

            if ($Device.metadata) {
                $PropertiesToOutput.Add('Metadata', $Device.metadata)
            }

            if ($Device.timezone) {
                $PropertiesToOutput.Add('TimeZone', $Device.timezone)
            }

            if ($Device.transport) {
                $PropertiesToOutput.Add('Transport', $Device.transport)
            }

            if ($Device.tzoffset) {
                $PropertiesToOutput.Add('TimeOffset', $Device.tzoffset)
            }

            $returnObject = New-Object -TypeName PSObject -Property $PropertiesToOutput

            $returnObject
        }
    }

    END { }
}
function Get-TDDeviceHistory
{
    <#
    .SYNOPSIS
    Retrieves all events associated with the specified device.
    .DESCRIPTION
    This command will list all events associated with the specified device
    .EXAMPLE
    Get-TDDeviceHistory
    .EXAMPLE
    Get-TDDeviceHistory | Format-Table
    #>


    [cmdletbinding()]
    param(
    [Parameter(Mandatory=$True, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
    [Alias('id')]
    [string] $DeviceID)

    BEGIN {
        if ($TelldusLiveAccessToken -eq $null) {
            throw "You must first connect using the Connect-TelldusLive cmdlet"
        }
    }

    PROCESS {
        $HistoryEvents = InvokeTelldusAction -URI "device/history?id=$DeviceID"
        
        foreach ($HistoryEvent in $HistoryEvents.history)
        {
            $PropertiesToOutput = @{
                                 'DeviceID' = $DeviceID
                                 'State' = switch ($HistoryEvent.state)
                                           {
                                                 1 { "On" }
                                                 2 { "Off" }
                                                16 { "Dimmed" }
                                                default { "Unknown" }
                                           }
                                 'Statevalue' = $HistoryEvent.statevalue
                                 'Origin' = $HistoryEvent.Origin;
                                 'EventDate' = (Get-Date "1970-01-01 00:00:00").AddSeconds($HistoryEvent.ts)
                                 }

            $returnObject = New-Object -TypeName PSObject -Property $PropertiesToOutput

            Write-Output $returnObject | Select-Object DeviceID, EventDate, State, Statevalue, Origin
        }
    }

    END { }
}
function Get-TDEvent
{

    <#
    .SYNOPSIS
    List all events available in Telldus Live!
 
    .DESCRIPTION
    List all events available in Telldus Live!
 
    .EXAMPLE
    Get-TDEvent
 
    #>


    [CmdletBinding()]
    param()

    BEGIN {
        if ($TelldusLiveAccessToken -eq $null) {
            throw "You must first connect using the Connect-TelldusLive cmdlet"
        }
    }

    PROCESS {
        $EventHistory = InvokeTelldusAction -URI "events/list"

        $EventHistory.event
    }
}
function Get-TDSchedule
{
    <#
    .SYNOPSIS
    Retrieves all schedules associated with a Telldus Live! account.
 
    .DESCRIPTION
    This command will list all schedules associated with an Telldus Live!-account
 
    .EXAMPLE
    Get-TDSchedule
 
    Fetch all schedules in the Telldus Live! account
 
    .EXAMPLE
    Get-TDSchedule -ScheduleID 1234567
 
    Fetch the schedule with id 1234567 from the Telldus Live! account
 
    #>


    [CmdletBinding()]
    Param(
        [Parameter(Mandatory=$false, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
        [Alias('id')]
        [string] $ScheduleID
    )

    BEGIN {
        if ($TelldusLiveAccessToken -eq $null) {
            throw "You must first connect using the Connect-TelldusLive cmdlet"
        }
    }

    PROCESS {

        if ($ScheduleID) {
            $response = InvokeTelldusAction -URI "scheduler/jobInfo?id=$ScheduleID"
            $jobList = $response
        }
        else {
            $response = InvokeTelldusAction -URI 'scheduler/jobList'
            $jobList = $response.job
        }

        foreach ($job in $jobList) {
            $job | Add-Member -MemberType NoteProperty -Name ScheduleID -Value $job.id

            $job
        }
    }

    END { }
}
function Get-TDSensor
{
    <#
    .SYNOPSIS
    Retrieves all sensors associated with a Telldus Live! account.
 
    .DESCRIPTION
    This command will list all sensors associated with an Telldus Live!-account and their current status and other information.
 
    .PARAMETER IncludeIgnored
    Returns hidden/ignored sensors as well
 
    .EXAMPLE
    Get-TDSensor
 
    .EXAMPLE
    Get-TDSensor | Format-Table
 
    #>

    [cmdletbinding()]
    Param(
        [switch] $IncludeIgnored
    )

    BEGIN {
        if ($TelldusLiveAccessToken -eq $null) {
            throw "You must first connect using the Connect-TelldusLive cmdlet"
        }
    }

    PROCESS {
        if ($IncludeIgnored.IsPresent) {
            $URI = "sensors/list?includeValues=1&includeIgnored=1"
        }
        else {
            $URI = "sensors/list?includeValues=1&includeIgnored=0"
        }

        $Response = InvokeTelldusAction -URI $URI

        $Sensors = $Response.sensor
        [datetime] $TelldusDate="1970-01-01 00:00:00"

        foreach ($Sensor in $Sensors) {
            $Sensor.lastUpdated = $TelldusDate.AddSeconds($Sensor.lastUpdated)
            $Sensor.Ignored = [bool] $Sensor.Ignored
            $Sensor.keepHistory = [bool] $Sensor.keepHistory
            $Sensor.Editable = [bool] $Sensor.Editable
            $Sensor.Online = [bool] $Sensor.Online
            Write-Output $Sensor
        }
    }

    END { }
}
function Get-TDSensorData
{
    <#
    .SYNOPSIS
    Retrieves the sensordata of specified sensor.
 
    .DESCRIPTION
    This command will retrieve the sensordata associated with the specified ID.
 
    .EXAMPLE
    Get-TDSensorData -DeviceID 123456
 
    .PARAMETER DeviceID
    The DeviceID of the sensor which data you want to retrieve.
 
    .PARAMETER HideRawData
    Specify this switch to hide the raw data response from Telldus Live!
 
    #>


    [CmdletBinding()]
    param(
      [Parameter(Mandatory=$True, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
      [Alias('id')]
      [string] $DeviceID,
      
      [Parameter(Mandatory=$false)]
      [switch] $HideRawData
    )

    BEGIN {
        if ($TelldusLiveAccessToken -eq $null) {
            throw "You must first connect using the Connect-TelldusLive cmdlet"
        }
    }

    PROCESS {
        $SensorData = InvokeTelldusAction -URI "sensor/info?id=$DeviceID"
        
        [datetime] $TelldusDate="1970-01-01 00:00:00"

        $PropertiesToOutput = @{
            DeviceId = $SensorData.id
            Name = $SensorData.name
            ClientName = $SensorData.clientName
            LastUpdated = $TelldusDate.AddSeconds($SensorData.lastUpdated)
            Ignored = [bool] $SensorData.Ignored
            Editable = [bool] $SensorData.editable
            Protocol = $SensorData.protocol
            SensorId = $SensorData.sensorId
            TimeZoneOffset = $SensorData.timezoneoffset
            Battery = $SensorData.battery
            KeepHistory = [bool] $SensorData.keepHistory
        }

        if (-not $HideRawData.IsPresent) {
            $PropertiesToOutput += @{ 'Data' = $SensorData.data }
        }

        $expandedProperties = GetTelldusProperty -Data $SensorData.data

        foreach ($expandedProperty in $expandedProperties) {
            $PropertiesToOutput += $expandedProperty
        }
        
        New-Object -TypeName PSObject -Property $PropertiesToOutput
    }

    END { }
}
function Get-TDSensorHistoryData
{
    <#
    .SYNOPSIS
    Retrieves sensor data history from Telldus Live!
     
    .DESCRIPTION
    This command will retrieve the sensor history data of the specified sensor.
     
    .PARAMETER DeviceID
    The DeviceID of the sensor which data you want to retrieve.
 
    .PARAMETER After
    Specify from which date you would like to retrieve sensor history.
 
    Always use UTC time.
 
    .PARAMETER Before
    Specify the "end date" of the data samples.
    Default value is current date.
 
    Always use UTC time.
 
    .PARAMETER PostRawData
    Specify this switch to post the raw data response from Telldus Live!
 
    .EXAMPLE
    Get-TDSensorHistoryData -DeviceID 123456
 
    .EXAMPLE
    Get-TDSensorHistoryData -DeviceID 123456 | Format-Table
 
    .EXAMPLE
    Get-TDSensorHistoryData -DeviceID 123456 -After (get-date).AddDays(-1)
     
    Get's the history from yesterday until today
 
    #>


    [cmdletbinding(DefaultParameterSetName='AllData')]
    param(
        [Parameter(Mandatory=$True, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, ParameterSetName='AllData')]
        [Parameter(Mandatory=$True, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, ParameterSetName='DateRange')]
        [Alias('id')]
        [string] $DeviceID,

        [Parameter(Mandatory=$true, ValueFromPipelineByPropertyName=$true, ParameterSetName='DateRange')]
        [DateTime] $After,

        [Parameter(Mandatory=$false, ValueFromPipelineByPropertyName=$true, ParameterSetName='DateRange')]
        [DateTime] $Before,

        [Parameter(Mandatory=$false)]
        [switch] $PostRawData
    )

    BEGIN {
        if ($TelldusLiveAccessToken -eq $null) {
            throw "You must first connect using the Connect-TelldusLive cmdlet"
        }

        
    }

    PROCESS {
        $ApiEndpoint = "sensor/history`?id=$DeviceID"

        if ($PSCmdlet.ParameterSetName -eq 'DateRange') {
            if (-not $Before) {
                $Before = (Get-Date).ToUniversalTime()
            }

            if ($Before -gt $After) {
                $FromDateToPost = [Math]::Floor((New-TimeSpan -Start '1970-01-01' -End $After).TotalSeconds)
                $ToDateToPost = [Math]::Floor((New-TimeSpan -Start '1970-01-01' -End $Before).TotalSeconds)

                $ApiEndpoint = $ApiEndpoint + "&from=$FromDateToPost" + "&to=$ToDateToPost"
            }
            else {
                throw 'The value for Before must be greater than the value for After.'
            }
        }

        $HistoryDataPoints = InvokeTelldusAction -URI $ApiEndpoint


        foreach ($HistoryDataPoint in $HistoryDataPoints.history) {

            $PropertiesToOutput = @{
                                 'DeviceID' = $DeviceID
                                 'Date' = (Get-Date "1970-01-01 00:00:00").AddSeconds($HistoryDataPoint.ts)
                                 }

            $expandedProperties = GetTelldusProperty -Data $HistoryDataPoint.data

            foreach ($expandedProperty in $expandedProperties) {
                $PropertiesToOutput += $expandedProperty
            }

            if ($PostRawData.IsPresent) {
                $PropertiesToOutput += @{ 'Data' = $HistoryDataPoint.data }
            }

            $returnObject = New-Object -TypeName PSObject -Property $PropertiesToOutput

            Write-Output $returnObject
        }
    }

    END { }
}
function Get-TDTriggerEvent
{

    <#
    .SYNOPSIS
    Lists trigger events available in Telldus Live!
 
    .DESCRIPTION
    Lists trigger events available in Telldus Live!
 
    If you specify an EventId, you'll also get all the events properties back
 
    .EXAMPLE
    Get-TDTriggerEvent
 
    List all Trigger events in the associated Telldus Live! account
 
    .EXAMPLE
    Get-TDTriggerEvent -EventId 123456
 
    Get information about the event with id 123456 from Telldus Live! (including all properties)
 
    #>


    [CmdletBinding()]
    param(
        [Parameter(Mandatory=$false, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
        [Alias('id')]
        [string] $EventId
    )

    BEGIN {
        if ($TelldusLiveAccessToken -eq $null) {
            throw "You must first connect using the Connect-TelldusLive cmdlet"
        }
    }

    PROCESS {
        if ($EventId) {
            $URI = "event/info`?id=$EventId"
        }
        else {
            $URI = "events/list`?listOnly=1"
        }

        $Response = InvokeTelldusAction -URI $URI

        if ($Response.event) {
            $Response.event
        }
        else {
            $Response
        }
    }
}
function Invoke-TDAction
{
    <#
    .SYNOPSIS
    Generic function that can trigger any endpoint in the Telldus Live! API
 
    .DESCRIPTION
    Generic function that can trigger any endpoint in the Telldus Live! API
 
    Just specify the URL you want to call with all the parameters.
 
    .EXAMPLE
    Invoke-TDAction -URI "events/list"
 
    Lists all events
 
    #>


    [CmdletBinding()]
    Param(
        [string] $URI
    )

    BEGIN {
        if ($TelldusLiveAccessToken -eq $null) {
            throw "You must first connect using the Connect-TelldusLive cmdlet"
        }
    }

    PROCESS {
        InvokeTelldusAction -URI $URI
    }

    END { }
}
function Rename-TDDevice
{

    <#
    .SYNOPSIS
    Renames a device in Telldus Live!
 
    .DESCRIPTION
    Renames a device in Telldus Live!
 
    .EXAMPLE
    Rename-TDDevice -DeviceID 123456 -NewName MyNewDeviceName
 
    .PARAMETER DeviceID
    The DeviceID of the device to rename
 
    .PARAMETER NewName
    The new name for that device
 
    #>


    [CmdletBinding()]
    param(

      [Parameter(Mandatory=$True, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
      [Alias('id')]
      [string] $DeviceID,

      [Parameter(Mandatory=$True)]
      [string] $NewName)


    BEGIN {
        if ($TelldusLiveAccessToken -eq $null) {
            throw "You must first connect using the Connect-TelldusLive cmdlet"
        }
    }

    PROCESS {
        $Response = InvokeTelldusAction -URI "device/setName`?id=$DeviceID&name=$([uri]::EscapeDataString($NewName))"

        Write-Verbose "Renamed device with id $DeviceID. Result: $($Response.status)."
    }
}

function Set-TDDevice
{

    <#
    .SYNOPSIS
    Turns a device on or off.
 
    .DESCRIPTION
    This command can set the state of a device to on or off through the Telldus Live! service.
 
    .EXAMPLE
    Set-TDDevice -DeviceID 123456 -Action turnOff
 
    .EXAMPLE
    Set-TDDevice -DeviceID 123456 -Action turnOn
 
    .EXAMPLE
    Set-TDDevice -DeviceID 123456 -Action bell
 
    .PARAMETER DeviceID
    The DeviceID of the device to turn off or on. (Pipelining possible)
 
    .PARAMETER Action
    What to do with that device. Possible values are "turnOff", "turnOn" and "bell".
 
    .NOTES
    Thank you Ispep (automatiserar.se) for fixing "bell" support!
 
    #>


    [CmdletBinding()]
    param(
      [Parameter(Mandatory=$True, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
      [Alias('id')]
      [string] $DeviceID,
      [Parameter(Mandatory=$True)]
      [ValidateSet("turnOff","turnOn", "bell", "down", "up", "stop")]
      [string] $Action)


    BEGIN {
        if ($TelldusLiveAccessToken -eq $null) {
            throw "You must first connect using the Connect-TelldusLive cmdlet"
        }
    }

    PROCESS {

        $Response = InvokeTelldusAction -URI "device/$Action`?id=$DeviceID"

        Write-Verbose "Doing action $Action on device $DeviceID. Result: $($Response.status)."
    }
}
function Set-TDDimmer
{
    <#
    .SYNOPSIS
    Dims a device to a certain level.
 
    .DESCRIPTION
    This command can set the dimming level of a device to through the Telldus Live! service.
 
    .EXAMPLE
    Set-TDDimmer -DeviceID 123456 -Level 89
 
    .EXAMPLE
    Set-TDDimmer -Level 180
 
    .PARAMETER DeviceID
    The DeviceID of the device to dim. (Pipelining possible)
 
    .PARAMETER Level
    What level to dim to. Possible values are 0 - 255.
 
    #>


    [CmdletBinding()]
    param(

      [Parameter(Mandatory=$True,
                 ValueFromPipeline=$true,
                 ValueFromPipelineByPropertyName=$true,
                 HelpMessage="Enter the DeviceID.")] [Alias('id')] [string] $DeviceID,

      [Parameter(Mandatory=$True,
                 HelpMessage="Enter the level to dim to between 0 and 255.")]
      [ValidateRange(0,255)]
      [int] $Level)


    BEGIN {
        if ($TelldusLiveAccessToken -eq $null) {
            throw "You must first connect using the Connect-TelldusLive cmdlet"
        }
    }

    PROCESS {

        $Response = InvokeTelldusAction -URI "device/dim`?id=$DeviceID&level=$Level"

        Write-Verbose "Dimming device $DeviceID to level $Level. Result: $($Response.status)."
    }
}
function Set-TDSensor
{

    <#
    .SYNOPSIS
    Sets/updates settings for sensors
 
    .DESCRIPTION
    Sets/updates settings for sensors
 
    It can for example enable history on the sensor, ignore/hide a sensor or
    rename a sensor
 
    .EXAMPLE
    Set-TDSensor -DeviceID 123456 -NewName Garage
 
    Changes the name of the sensor with id 123456 to Garage
 
    .EXAMPLE
    Set-TDSensor -DeviceID 123456 -KeepHistory $true -IgnoreSensor $false
 
    Enables history on sensor with id 123456 and unhides it
 
    .PARAMETER DeviceID
    The ID of the sensor which settings you wish to update
 
    #>


    [CmdletBinding()]
    param(
      [Parameter(Mandatory=$True, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
      [Alias('id')]
      [string] $DeviceID,
      [Parameter(Mandatory=$false)]
      [bool] $KeepHistory,
      [Parameter(Mandatory=$false)]
      [bool] $IgnoreSensor,
      [Parameter(Mandatory=$false)]
      [string] $NewName
    )


    BEGIN {
        if ($TelldusLiveAccessToken -eq $null) {
            throw "You must first connect using the Connect-TelldusLive cmdlet"
        }
    }

    PROCESS {
        if ($PSBoundParameters.ContainsKey('KeepHistory')) {
            if ($KeepHistory) {
                $HistorySetting = 1
            }
            else {
                $HistorySetting = 0
            }

            $Response = InvokeTelldusAction -URI "sensor/setKeepHistory?id=$DeviceID&keepHistory=$HistorySetting"
        }

        if ($PSBoundParameters.ContainsKey('IgnoreSensor')) {
            if ($IgnoreSensor) {
                $IgnoreSetting = 1
            }
            else {
                $IgnoreSetting = 0
            }

            $Response = InvokeTelldusAction -URI "sensor/setIgnore?id=$DeviceID&ignore=$IgnoreSetting"
        }

        if ($NewName) {
            $Response = InvokeTelldusAction -URI "sensor/setName?id=$DeviceID&name=$([uri]::EscapeDataString($NewName))"
        }
    }
}