-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcommon.ps1
More file actions
1536 lines (1263 loc) · 56.8 KB
/
Copy pathcommon.ps1
File metadata and controls
1536 lines (1263 loc) · 56.8 KB
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
####################################################################
# ham_docker_container - Containers for APRS and ham radio #
# Version 0.1.0 #
# https://github.com/iontodirel/ham_docker_container #
# Copyright (c) 2023 Ion Todirel #
####################################################################
enum FailureTypes {
None
ParameterValueIsEmpty
ParameterValueIsNotANumber
FileNotFound
FindDevicesNotFound
FindDevicesConfigNotFound
FindDevicesFailed
ProcessExecutionFailed
CouldNotCreateFile
ExecutableNotFound
DatabaseOperationUnsuccessful
DatabaseConnectionUnsuccessful
InvalidValue
ExpectedDataNotReceived
SerialPortNotFound
SoundCardNotFound
ServiceDisabledButProcessRunning
FailedToGetGpsLocation
TcpConnectionUnsuccessful
ModemConnectionUnsuccessful
AudioLevelLow
WebServiceTimeout
WebServiceConnectionFailed
FoundTooManySerialPorts
FoundTooManySoundCards
SoundCardTestVolumeFailed
SerialPortTestFailed
SoundCardTestFailed
ServiceExecutableExited
ServiceConnectionFailed
Generic
}
enum LogType {
normal
warning
error
}
######################################################################
# #
# LOG #
# #
######################################################################
function Log {
param (
[LogType]$log_type = [LogType]::normal,
[FailureTypes]$failure_type = [FailureTypes]::None,
[string]$service_name = "",
[string]$message = "",
[string]$log_file_name = $log_file_name ?? "log.txt"
)
$newJsonLog=[ordered]@{
type = $log_type.ToString()
failure = $failure_type.ToString()
service_name = $service_name
message = $message
time = [DateTime]::Now.ToString("yyyy-MM-dd HH:mm:ss")
utcTime = [DateTime]::UtcNow.ToString("yyyy-MM-dd HH:mm:ss")
}
if (-not (Test-Path -Path $log_file_name -PathType Leaf) -or (Get-Content -Path $log_file_name -Raw) -eq $null) {
$jsonObject = @{
log = @($newJsonLog)
}
$jsonObject | ConvertTo-Json | Set-Content -Path $log_file_name
return
}
$json = Get-Content $log_file_name -Raw | ConvertFrom-Json
if (-not $json.log -or $json.log -isnot [System.Collections.IList]) {
$json.log = @()
}
$json.log += $newJsonLog
$json.log = $json.log | Select-Object -Last 1000
$json | ConvertTo-Json | Set-Content -Path $log_file_name
}
function Get-TimeStamp {
return "[{0:MM/dd/yy} {0:HH:mm:ss}]" -f (Get-Date)
}
function Get-UTCTimeStamp {
return "[{0:MM/dd/yy} {0:HH:mm:ss}]" -f [System.DateTime]::UtcNow
}
######################################################################
# #
# SETTINGS #
# #
######################################################################
function Get-SettingValue {
param (
[string]$settings_file_name,
[string]$service_name,
[string]$setting_name
)
if (-not (Test-Path -Path $settings_file_name -PathType Leaf)) {
Throw "Settings file '$settings_file_name' does not exist."
}
if (-not $service_name) {
Throw "'service_name' is empty."
}
if (-not $setting_name) {
Throw "'setting_name' is empty."
}
$settings = Get-Content -Raw -Path $settings_file_name | ConvertFrom-Json
$default_value = ($settings.services | Where-Object { $_.name -eq $service_name }).settings | Where-Object { $_.name -eq $setting_name } | Select-Object -ExpandProperty default_value
return $default_value
}
function Invoke-Init {
param (
[string]$service_name,
[string]$web_service_name,
[string]$web_service_port,
[bool]$wait_service_enabled = $True
)
$result = Invoke-WaitServiceReady -web_service_name $web_service_name -web_service_port $web_service_port
if ($result -eq $False) {
Return $False
}
$serviceResponse = Invoke-WebRequest -Uri "http://${web_service_name}:$web_service_port/api/v1/service/$service_name/settings" -Method Get -ErrorAction SilentlyContinue 2>$null
if ($serviceResponse.StatusCode -ne 200) {
Write-Host "Request failed."
Return $False
}
$serviceResponseJson = $serviceResponse.Content | ConvertFrom-Json
Write-Host "Service settings:"
foreach ($serviceSetting in $serviceResponseJson.settings) {
$settingName = $serviceSetting.name
$settingType = $serviceSetting.data_type
switch ($settingType) {
'bool' {
$settingValue = [bool]::Parse($serviceSetting.value)
}
default {
$settingValue = $serviceSetting.value
}
}
Set-Variable -Name "script:$settingName" -Value $settingValue
Write-Host "$settingName='$settingValue'"
}
$script:web_service_name = $web_service_name
$script:web_service_port = $web_service_port
if ($wait_service_enabled -eq $True) {
Invoke-WaitServiceEnabled -service_name $service_name -web_service_name $web_service_name -web_service_port $web_service_port
}
Return $True
}
function Invoke-Init-ExitOnError {
param (
[string]$service_name = $env:SERVICE_NAME,
[string]$web_service_name = $env:WS_SERVICE_NAME,
[string]$web_service_port = $env:WS_PORT,
[bool]$wait_service_enabled = $True
)
try {
$result = Invoke-Init -service_name $service_name -wait_service_enabled $wait_service_enabled -web_service_name $web_service_name -web_service_port $web_service_port
if ($result -ne $true) {
Write-Error "Function Invoke-Init returned false."
exit 1
}
}
catch {
Write-Host "Function Invoke-Init execution failed. $($_.Exception.Message)"
exit 1
}
}
function Get-SettingValue-ExitOnError {
param (
[string]$settings_file_name,
[string]$service_name,
[string]$setting_name
)
try {
return Get-SettingValue -settings_file_name $settings_file_name -service_name $service_name -setting_name $setting_name
}
catch {
Write-Host "Function Get-SettingValue execution failed. Error: $($_.Exception.Message)"
exit 1
}
}
######################################################################
# #
# SERVICES #
# #
######################################################################
function Invoke-WaitServiceReady {
param (
[string]$web_service_name,
[string]$web_service_port
)
for ($i = 1; $i -lt 30; $i++) {
try {
$serviceResponse = Invoke-WebRequest -Uri "http://${web_service_name}:$web_service_port/api/v1/ready" -Method Get -ErrorAction SilentlyContinue 2>$null
if ($serviceResponse.StatusCode -eq 200) {
$serviceResponseJson = $serviceResponse.Content | ConvertFrom-Json
if ($serviceResponseJson.ready -eq 'true') {
Write-Host "Request succeeded with status code 200."
return $True
}
}
}
catch {
Write-Host "Invoke-WebRequest failed with an exception $($_.Exception.Message)"
}
Start-Sleep -s 1
}
Write-Error "Invoke-WaitServiceReady returned false"
return $False
}
function Get-ServiceEnabled {
param (
[string]$service_name,
[string]$web_service_name,
[string]$web_service_port
)
$serviceResponse = Invoke-WebRequest -Uri "http://${web_service_name}:$web_service_port/api/v1/service/$service_name/enabled" -Method Get -ErrorAction SilentlyContinue 2>$null
if ($serviceResponse.StatusCode -ne 200) {
Write-Host "Request failed."
Return $False
}
$serviceResponseJson = $serviceResponse.Content | ConvertFrom-Json
if ($serviceResponseJson.enabled -eq $True) {
Return $True
}
Return $False
}
function Invoke-WaitServiceEnabled {
param (
[string]$service_name,
[string]$web_service_name,
[string]$web_service_port
)
while ($True) {
$result = Get-ServiceEnabled -service_name $service_name -web_service_name $web_service_name -web_service_port $web_service_port
if ($result -eq $True) {
Write-Host "$service_name service state is enabled"
Return $True
}
else {
Write-Host "$service_name service state is disabled, waiting for service state change to 'enabled'"
}
Start-Sleep -Seconds 10
}
Return $False
}
function Invoke-ExitIfServiceDisabled-ExitOnError {
param (
[string]$service_name,
[string]$process_name,
[string]$web_service_name = $web_service_name,
[string]$web_service_port = $web_service_port
)
try {
$enable_service_state = Get-ServiceEnabled -service_name $service_name -web_service_name $web_service_name -web_service_port $web_service_port
}
catch {
Write-Error "Function Get-ServiceEnabled execution failed. Error: $($_.Exception.Message)"
exit 1
}
if ($enable_service_state -eq $False) {
# Check if the process is running
$process = Get-Process -Name $process_name -ErrorAction SilentlyContinue
if ($process) {
Write-Error "$service_name service disabled but $process_name process running. Exiting."
exit 1
}
# just exit and succeed the check, as we are just waiting to be enabled
exit 0
}
}
######################################################################
# #
# DIREWOLF #
# #
######################################################################
function Start-Direwolf-ExitOnError {
param (
[string]$callsign,
[string]$audio_device,
[string]$serial_port,
[string]$modem_internal_agwp_port_number,
[string]$modem_internal_kiss_port_number,
[string]$direwolf_internal_config_file_name,
[string]$direwolf_internal_config_working_file_name,
[string]$modem_internal_log_directory,
[string]$find_devices_output_json_file = "output.json",
[string]$log_file_name = $log_file_name ?? "log.txt",
[string]$service_name = $service_name ?? ""
)
try {
Start-Direwolf -callsign $callsign `
-audio_device $audio_device `
-serial_port $serial_port `
-modem_internal_agwp_port_number $modem_internal_agwp_port_number `
-modem_internal_kiss_port_number $modem_internal_kiss_port_number `
-direwolf_internal_config_file_name $direwolf_internal_config_file_name `
-direwolf_internal_config_working_file_name $direwolf_internal_config_working_file_name `
-modem_internal_log_directory $modem_internal_log_directory `
-find_devices_output_json_file $find_devices_output_json_file `
-log_file_name $log_file_name `
-service_name $service_name
}
catch {
Write-Host "Function Start-Direwolf execution failed. $($_.Exception.Message)"
exit 1
}
}
function Start-Direwolf {
param (
[string]$callsign,
[string]$audio_device,
[string]$serial_port,
[string]$modem_internal_agwp_port_number,
[string]$modem_internal_kiss_port_number,
[string]$direwolf_internal_config_file_name,
[string]$direwolf_internal_config_working_file_name,
[string]$modem_internal_log_directory,
[string]$find_devices_output_json_file = "output.json",
[string]$log_file_name = $log_file_name ?? "log.txt",
[string]$service_name = $service_name ?? ""
)
Copy-Item -Path $direwolf_internal_config_file_name -Destination $direwolf_internal_config_working_file_name
Update-DirewolfConfigFile -file_path $direwolf_internal_config_working_file_name `
-audio_device $audio_device `
-ptt_serial_port $serial_port `
-callsign $callsign `
-modem_internal_agwp_port $modem_internal_agwp_port_number `
-modem_internal_kiss_port $modem_internal_kiss_port_number
Write-Host "Starting direwolf with callsign '$callsign', devices '$audio_device', '$serial_port', and ports '$modem_internal_agwp_port_number', '$modem_internal_kiss_port_number'"
Log -log_type normal -failure_type None -service_name $service_name -message "Starting direwolf with callsign '$callsign', devices '$audio_device', '$serial_port', and ports '$modem_internal_agwp_port_number', '$modem_internal_kiss_port_number'"
& /usr/local/bin/direwolf -t 0 -a 10 -c $direwolf_internal_config_working_file_name -l $modem_internal_log_directory 2>&1 | tee -a $modem_internal_log_directory/direwolf-stdout.log
$exit_code = $LASTEXITCODE
Write-Host "Finished executing direwolf with exit code $exit_code"
Log -log_type warning -failure_type ServiceExecutableExited -service_name $service_name -message "Finished executing direwolf with exit code $exit_code" -log_file_name $log_file_name
exit $exit_code
}
function Update-DirewolfConfigFile {
param (
[string]$file_path,
[string]$audio_device,
[string]$ptt_serial_port, # serial_port
[string]$callsign,
[int]$modem_internal_agwp_port, # agwp_port
[int]$modem_internal_kiss_port, # kiss_port
[string]$log_file_name = $log_file_name ?? "log.txt",
[string]$service_name = $service_name ?? ""
)
if (-not (Test-Path -Path $file_path -PathType Leaf)) {
Log -log_type error -failure_type FileNotFound -service_name $service_name -message "Update-DirewolfConfigFile: File not found: $file_path" -log_file_name $log_file_name
Throw "File not found: $file_path"
}
if (-not $audio_device) {
Log -log_type error -failure_type ParameterValueIsEmpty -service_name $service_name -message "Update-DirewolfConfigFile: 'audio_device' is empty." -log_file_name $log_file_name
Throw "'audio_device' is empty."
}
if (-not $ptt_serial_port) {
Log -log_type error -failure_type ParameterValueIsEmpty -service_name $service_name -message "Update-DirewolfConfigFile: 'ptt_serial_port' is empty." -log_file_name $log_file_name
Throw "'ptt_serial_port' is empty."
}
if (-not $callsign) {
Log -log_type error -failure_type ParameterValueIsEmpty -service_name $service_name -message "Update-DirewolfConfigFile: 'callsign' is empty." -log_file_name $log_file_name
Throw "'callsign' is empty."
}
if (-not ($modem_internal_agwp_port -is [int])) {
Log -log_type error -failure_type ParameterValueIsNotANumber -service_name $service_name -message "Update-DirewolfConfigFile: 'modem_internal_agwp_port' is not a valid number." -log_file_name $log_file_name
Throw "'modem_internal_agwp_port' is not a valid number."
}
if (-not ($modem_internal_kiss_port -is [int])) {
Log -log_type error -failure_type ParameterValueIsNotANumber -service_name $service_name -message "Update-DirewolfConfigFile: 'modem_internal_kiss_port' is not a valid number." -log_file_name $log_file_name
Throw "'modem_internal_kiss_port' is not a valid number."
}
# Read the content of the file
$content = Get-Content $file_path
# Perform replacements based on the provided parameters
$content = $content -replace '@ADEVICE.*', "ADEVICE $audio_device"
$content = $content -replace '@PTT.*', "PTT $ptt_serial_port RTS"
$content = $content -replace '@MYCALL.*', "MYCALL $callsign"
$content = $content -replace '@AGWPORT.*', "AGWPORT $modem_internal_agwp_port"
$content = $content -replace '@KISSPORT.*', "KISSPORT $modem_internal_kiss_port"
# Write the updated content back to the file
$content | Set-Content $file_path
}
function Update-DirewolfConfigFile-ExitOnError {
try {
Update-DirewolfConfigFile -file_path $file_path -audio_device $audio_device -ptt_serial_port $ptt_serial_port -callsign $callsign -modem_internal_agwp_port $modem_internal_agwp_port -modem_internal_kiss_port $modem_internal_kiss_port
}
catch {
Write-Error "Error occurred updating Direwolf configurtion: $($_.Exception.Message)"
exit 1
}
}
function Test-ModemConnection {
param (
[string]$modem_host_name,
[int]$modem_kiss_port_number,
[int]$duration_in_seconds = 60
)
if (-not $modem_host_name) {
Throw "'modem_host_name' is empty."
}
$end_time = (Get-Date).AddSeconds($duration_in_seconds)
$result = $false
while ((Get-Date) -lt $end_time -and $result -ne $true) {
Write-Host "Attempting connection to modem on host ""$modem_host_name"" with port ""$modem_kiss_port_number""."
$result = Test-TcpConnection -host_name $modem_host_name -port_number $modem_kiss_port_number
Start-Sleep -Seconds 1
}
return $result
}
function Test-ModemConnection-ExitOnError {
param (
[string]$modem_host_name,
[int]$modem_kiss_port_number,
[int]$duration_in_seconds = 60
)
try {
$result = Test-ModemConnection -modem_host_name $modem_host_name -modem_kiss_port_number $modem_kiss_port_number -duration_in_seconds $duration_in_seconds
}
catch {
Write-Error "Error occurred calling Test-ModemConnection: $($_.Exception.Message)"
exit 1
}
if ($result -ne $true) {
Write-Error "Test-ModemConnection failed"
exit 1
}
}
######################################################################
# #
# SERIAL PORTS #
# #
######################################################################
function Read-DataFromSerialPort {
param (
[string]$serial_port,
[int]$timeout_seconds = 30
)
if (-not $serial_port) {
Throw "'serial_port' is empty."
}
$endTime = (Get-Date).AddSeconds($timeout_seconds)
$charCount = 0
$counter = 0
while ((Get-Date) -lt $endTime) {
$ddOutput = & dd if=$serial_port bs=1 count=100 2>&1
$currentCount = $ddOutput.Length
$charCount += $currentCount
if ($charCount -ge 100) {
Write-Host "Received $charCount bytes of data from GPS device on serial port '$serial_port' and it took '$counter' reads"
return $true
}
$counter++
Start-Sleep -Milliseconds 100
}
Write-Host "Did not receive 100 or more bytes of data on serial port '$serial_port'"
return $false
}
function Get-SerialPort {
param (
[string]$find_devices_config_file,
[string]$find_devices_utility,
[string]$find_devices_output_json_file,
[string]$log_file_name = $log_file_name ?? "log.txt",
[string]$service_name = $service_name ?? ""
)
if ([string]::IsNullOrEmpty($find_devices_output_json_file)) {
$find_devices_output_json_file = (New-TemporaryFile).FullName
}
if (-not (Test-Path -Path $find_devices_config_file -PathType Leaf)) {
Log -log_type error -failure_type FindDevicesConfigNotFound -service_name $service_name -message "Get-SerialPort: No find_devices config file found: '$find_devices_config_file'" -log_file_name $log_file_name
Throw "No find_devices config file found: '$find_devices_config_file'"
}
if (-not (Test-Path -Path $find_devices_utility -PathType Leaf)) {
Log -log_type error -failure_type FindDevicesNotFound -service_name $service_name -message "Get-SerialPort: find_devices executable '$find_devices_utility' not found" -log_file_name $log_file_name
Throw "find_devices executable '$find_devices_utility' not found"
}
Remove-Item -Path $find_devices_output_json_file -ErrorAction SilentlyContinue
Write-Host "Calling find_devices with command line options: -c $find_devices_config_file -o $find_devices_output_json_file --no-stdout --audio.disable-volume-control"
& $find_devices_utility -c $find_devices_config_file -o $find_devices_output_json_file --no-stdout --audio.disable-volume-control > $null
$find_devices_exit_code = $LASTEXITCODE
if ($find_devices_exit_code -ne 0) {
Log -log_type error -failure_type FindDevicesFailed -service_name $service_name -message "Get-SerialPort: Failed to execute find_devices to find a serial port" -log_file_name $log_file_name
Throw "Failed to execute find_devices to find a serial port"
}
if (-not (Test-Path -Path $find_devices_output_json_file -PathType Leaf)) {
Log -log_type error -failure_type FileNotFound -service_name $service_name -message "Get-SerialPort: File '$find_devices_output_json_file' does not exist" -log_file_name $log_file_name
Throw "File '$find_devices_output_json_file' does not exist"
}
$find_devices_output = Get-Content -Path $find_devices_output_json_file -Raw | ConvertFrom-Json
$serial_ports_count = $find_devices_output.serial_ports.Count
Write-Host "Serial ports count: '$serial_ports_count'"
if ($serial_ports_count -ne 1) {
Log -log_type error -failure_type SerialPortNotFound -service_name $service_name -message "Get-SerialPort: Failed to find a serial port." -log_file_name $log_file_name
Throw "Failed to find a serial port."
}
$serial_port = $find_devices_output.serial_ports[0].name
Write-Host "Serial port: '$serial_port'"
return $serial_port
}
function Read-DataFromSerialPort-ExitOnError {
param (
[string]$serial_port,
[int]$timeout_seconds = 30
)
try {
$result = Read-DataFromSerialPort -serial_port $serial_port -timeout_seconds $timeout_seconds
}
catch {
Write-Error "Function Read-DataFromSerialPort execution failed. Error: $($_.Exception.Message)"
exit 1
}
if ($result -eq $false) {
Write-Error "Function Read-DataFromSerialPort execution failed."
exit 1
}
}
function Get-SerialPort-ExitOnError {
param (
[string]$find_devices_config_file,
[string]$find_devices_utility,
[string]$find_devices_output_json_file
)
try {
return Get-SerialPort -find_devices_config_file $find_devices_config_file -find_devices_utility $find_devices_utility -find_devices_output_json_file $find_devices_output_json_file
}
catch {
Write-Error "Function Get-SerialPort execution failed. Error: $($_.Exception.Message)"
exit 1
}
}
function Test-SerialPort-ExitOnError {
param (
[string]$serial_port
)
if (-not $serial_port) {
Write-Error "'serial_port' is empty."
exit 1
}
$null = & stty -F $serial_port 2>&1
if ($LASTEXITCODE -ne 0) {
Write-Error "Could not successfully connect to serial port $serial_port"
exit 1
}
}
######################################################################
# #
# SOUND CARD #
# #
######################################################################
function Get-AudioDevice {
param (
[string]$find_devices_config_file,
[string]$find_devices_utility,
[string]$find_devices_output_json_file,
[string]$log_file_name = $log_file_name ?? "log.txt",
[string]$service_name = $service_name ?? ""
)
if ([string]::IsNullOrEmpty($find_devices_output_json_file)) {
$find_devices_output_json_file = (New-TemporaryFile).FullName
}
if (-not (Test-Path -Path $find_devices_config_file -PathType Leaf)) {
Log -log_type error -failure_type FindDevicesConfigNotFound -service_name $service_name -message "Get-AudioDevice: No find_devices config file found: '$find_devices_config_file'" -log_file_name $log_file_name
Throw "No find_devices config file found: '$find_devices_config_file'"
}
if (-not (Test-Path -Path $find_devices_utility -PathType Leaf)) {
Log -log_type error -failure_type FindDevicesNotFound -service_name $service_name -message "Get-AudioDevice: find_devices executable '$find_devices_utility' not found" -log_file_name $log_file_name
Throw "find_devices executable '$find_devices_utility' not found"
}
Remove-Item -Path $find_devices_output_json_file -ErrorAction SilentlyContinue
& $find_devices_utility -c $find_devices_config_file -o $find_devices_output_json_file --no-stdout --audio.disable-volume-control > $null
$find_devices_exit_code = $LASTEXITCODE
if ($find_devices_exit_code -ne 0) {
Log -log_type error -failure_type FindDevicesFailed -service_name $service_name -message "Get-AudioDevice: Failed to execute find_devices to find an audio device" -log_file_name $log_file_name
Throw "Failed to execute find_devices to find an audio device"
}
if (-not (Test-Path -Path $find_devices_output_json_file -PathType Leaf)) {
Log -log_type error -failure_type FileNotFound -service_name $service_name -message "Get-AudioDevice: File '$find_devices_output_json_file' does not exist" -log_file_name $log_file_name
Throw "File '$find_devices_output_json_file' does not exist. Exiting."
}
$find_devices_output = Get-Content -Path $find_devices_output_json_file -Raw | ConvertFrom-Json
$audio_devices_count = $find_devices_output.audio_devices.Count
Write-Host "Audio device count: '$audio_devices_count'"
if ($audio_devices_count -ne 1) {
Log -log_type error -failure_type SerialPortNotFound -service_name $service_name -message "Get-AudioDevice: Failed to find an audio device." -log_file_name $log_file_name
Throw "Failed to find an audio device."
}
$audio_device = $find_devices_output.audio_devices[0].plughw_id
Write-Host "Audio device: '$audio_device'"
return $audio_device
}
function Get-AudioDevice-ExitOnError {
param (
[string]$find_devices_config_file,
[string]$find_devices_utility,
[string]$find_devices_output_json_file
)
try {
return Get-AudioDevice -find_devices_config_file $find_devices_config_file -find_devices_utility $find_devices_utility -find_devices_output_json_file $find_devices_output_json_file
}
catch {
Write-Host "Function Get-AudioDevice execution failed. Error: $($_.Exception.Message)"
exit 1
}
}
function Test-AudioDevice-ExitOnError {
param (
[string]$audio_device,
[string]$soundcard_test_wav_file_name,
[string]$log_file_name = $log_file_name ?? "log.txt",
[string]$service_name = $service_name ?? ""
)
if (-not $audio_device) {
Log -log_type error -failure_type ParameterValueIsEmpty -service_name $service_name -message "Test-AudioDevice-ExitOnError: 'audio_device' is empty." -log_file_name $log_file_name
Write-Error "'audio_device' is empty."
exit 1
}
if (-not $soundcard_test_wav_file_name) {
Log -log_type error -failure_type ParameterValueIsEmpty -service_name $service_name -message "Test-AudioDevice-ExitOnError: 'soundcard_test_wav_file_name' is empty." -log_file_name $log_file_name
Write-Error "'soundcard_test_wav_file_name' is empty."
exit 1
}
# Run arecord command and redirect output to null (suppressing output)
& arecord -D $audio_device -f S16_LE -c 1 -r 48000 -d 5 $soundcard_test_wav_file_name > $null 2>&1
# Get the maximum amplitude using sox and store it in $max_amplitude
$max_amplitude = & sox $soundcard_test_wav_file_name -n stat 2>&1 | Select-String "Maximum amplitude" | ForEach-Object { $_.ToString().Split(":")[1].Trim() }
# Convert $max_amplitude to a floating-point number
$max_amplitude = [double]$max_amplitude
# Print the maximum sound amplitude to the console and the log file
Write-Output "Max sound amplitude on soundcard ""$audio_device"" is ""$max_amplitude"""
# Check if max amplitude is less than 0.2 and exit if it is
if ($max_amplitude -lt 0.2) {
Log -log_type error -failure_type AudioLevelLow -service_name $service_name -message "Test-AudioDevice-ExitOnError: Could not successfully read a valid buffer of 5 seconds from soundcard '$audio_device'." -log_file_name $log_file_name
Write-Error "Could not successfully read a valid buffer of 5 seconds from soundcard ""$audio_device"". Exiting."
exit 1
}
}
function Test-AudioDeviceVolume {
param (
[string]$find_devices_config_file,
[string]$find_devices_utility,
[string]$log_file_name = $log_file_name ?? "log.txt",
[string]$service_name = $service_name ?? ""
)
if (-not (Test-Path -Path $find_devices_config_file -PathType Leaf)) {
Log -log_type error -failure_type FindDevicesConfigNotFound -service_name $service_name -message "Test-AudioDeviceVolume: No find_devices config file found: '$find_devices_config_file'" -log_file_name $log_file_name
Throw "No find_devices config file found: '$find_devices_config_file'"
}
if (-not (Test-Path -Path $find_devices_utility -PathType Leaf)) {
Log -log_type error -failure_type FindDevicesNotFound -service_name $service_name -message "Test-AudioDeviceVolume: find_devices executable '$find_devices_utility' not found" -log_file_name $log_file_name
Throw "find_devices executable '$find_devices_utility' not found"
}
$temp_file = New-TemporaryFile
& $find_devices_utility -c $find_devices_config_file --no-stdout -o $temp_file.FullName --no-volume-control --test-volume-control > $null
$find_devices_exit_code = $LASTEXITCODE
if ($find_devices_exit_code -ne 0) {
Log -log_type error -failure_type FindDevicesFailed -service_name $service_name -message "Test-AudioDeviceVolume: find_devices failed, exit code $find_devices_exit_code, output file $temp_file" -log_file_name $log_file_name
Throw "find_devices failed, exit code $find_devices_exit_code"
}
if (-not (Test-Path -Path $temp_file.FullName -PathType Leaf)) {
Log -log_type error -failure_type FileNotFound -service_name $service_name -message "Test-AudioDeviceVolume: File '$find_devices_output_json_file' does not exist" -log_file_name $log_file_name
Throw "find_devices output file $($temp_file.FullName) does not exist."
}
$find_devices_output = Get-Content -Path $temp_file.FullName -Raw | ConvertFrom-Json
$volume_control_test_result = $find_devices_output.volume_control_test_result
Write-Host "Volume test results:"
foreach ($device in $find_devices_output.audio_devices) {
foreach ($control in $device.controls) {
foreach ($channel in $control.channels) {
Write-Host "Device name: $($device.hw_id), Control name: $($control.name), Channel name: $($channel.name), Channel value: $($channel.volume), Channel type: $($channel.type)"
}
}
}
Remove-Item $temp_file.FullName
if ($volume_control_test_result -ne "success") {
Log -log_type error -failure_type SoundCardTestVolumeFailed -service_name $service_name -message "Test-AudioDeviceVolume: find_devices failed the audio volume check" -log_file_name $log_file_name
Throw "find_devices failed the audio volume check"
}
}
function Set-AudioDeviceVolume {
param (
[string]$find_devices_config_file,
[string]$find_devices_utility,
[string]$log_file_name = $log_file_name ?? "log.txt",
[string]$service_name = $service_name ?? ""
)
if (-not (Test-Path -Path $find_devices_config_file -PathType Leaf)) {
Log -log_type error -failure_type FindDevicesConfigNotFound -service_name $service_name -message "Set-AudioDeviceVolume: No find_devices config file found: '$find_devices_config_file'" -log_file_name $log_file_name
Throw "No find_devices config file found: '$find_devices_config_file'"
}
if (-not (Test-Path -Path $find_devices_utility -PathType Leaf)) {
Log -log_type error -failure_type FindDevicesNotFound -service_name $service_name -message "Set-AudioDeviceVolume: find_devices executable '$find_devices_utility' not found" -log_file_name $log_file_name
Throw "find_devices executable '$find_devices_utility' not found"
}
& $find_devices_utility -c $find_devices_config_file --no-stdout --disable-file-write > $null
$find_devices_exit_code = $LASTEXITCODE
if ($find_devices_exit_code -ne 0) {
Log -log_type error -failure_type FindDevicesFailed -service_name $service_name -message "Set-AudioDeviceVolume: Failed to execute find_devices to find an audio device" -log_file_name $log_file_name
Throw "Failed to execute find_devices to find an audio device and set the volume"
}
}
function Test-AudioDeviceVolume-ExitOnError {
param (
[string]$find_devices_config_file,
[string]$find_devices_utility
)
try {
Test-AudioDeviceVolume -find_devices_config_file $find_devices_config_file -find_devices_utility $find_devices_utility
}
catch {
Write-Error "Function Test-AudioDeviceVolume execution failed. Error: $($_.Exception.Message)"
exit 1
}
}
function Set-AudioDeviceVolume-ExitOnError {
param (
[string]$find_devices_config_file,
[string]$find_devices_utility,
[int]$max_retries = 10
)
$retry_count = 0
while ($retry_count -lt $max_retries) {
try {
Set-AudioDeviceVolume -find_devices_config_file $find_devices_config_file -find_devices_utility $find_devices_utility
Test-AudioDeviceVolume -find_devices_config_file $find_devices_config_file -find_devices_utility $find_devices_utility
break
}
catch {
$retry_count++
Write-Error "Function Set-AudioDeviceVolume execution failed. Error: $($_.Exception.Message)"
if ($retry_count -lt $max_retries) {
Write-Host "Retrying..."
Start-Sleep -Seconds 5
} else {
exit 1
}
}
}
}
######################################################################
# #
# APRX #
# #
######################################################################
function Update-APRXConfigFile { # TODO
param (
[string]$aprx_internal_working_config_file_name,
[string]$callsign,
[string]$aprsis_pass,
[string]$aprsis_server,
[string]$modem_host_name,
[int]$modem_kiss_port_number,
[string]$lat, # consider simply taking coordinates in DD format
[string]$lon,
[string]$aprx_internal_log_directory
)
if (-not (Test-Path -Path $aprx_internal_working_config_file_name -PathType Leaf)) {
Throw "File not found: $aprx_internal_working_config_file_name"
}
if (-not $callsign) {
Throw "'callsign' is empty."
}
if (-not $aprsis_pass) {
Throw "'aprsis_pass' is empty."
}
if (-not $aprsis_server) {
Throw "'aprsis_server' is empty."
}
if (-not $modem_host_name) {
Throw "'modem_host_name' is empty."
}
if (-not ($modem_kiss_port_number -is [int])) {
Throw "'modem_kiss_port_number' is not a valid number."
}
if (-not $lat) {
Throw "'lat' is empty."
}
if (-not $lon) {
Throw "'lon' is empty."
}
if (-not (Test-Path -Path $aprx_internal_log_directory -PathType Container)) {
Throw "Directory not found: $aprx_internal_log_directory"
}
(Get-Content $aprx_internal_working_config_file_name) | ForEach-Object {
$_ -replace '@mycall.*', "mycall $callsign" `
-replace '@passcode.*', "passcode $aprsis_pass" `
-replace '@server.*', "server $aprsis_server" `
-replace '@tcp-device.*', "tcp-device $modem_host_name $modem_kiss_port_number KISS" `
-replace '@myloc.*', "myloc lat $lat lon $lon" `
-replace '@rflog.*', "rflog $aprx_internal_log_directory/aprx-rf.log" `
-replace '@aprxlog.*', "aprxlog $aprx_internal_log_directory/aprx.log" `
-replace '@dprslog.*', "dprslog $aprx_internal_log_directory/dprs.log"
} | Set-Content $aprx_internal_working_config_file_name
}
function Update-APRXConfigFile-ExitOnError {
param (
[string]$aprx_internal_working_config_file_name,
[string]$callsign,
[string]$aprsis_pass,
[string]$aprsis_server,
[string]$modem_host_name,
[int]$modem_kiss_port_number,
[string]$lat,
[string]$lon,
[string]$aprx_internal_log_directory
)
try {
Update-APRXConfigFile -aprx_internal_working_config_file_name $aprx_internal_working_config_file_name `
-callsign $callsign `
-aprsis_pass $aprsis_pass `
-aprsis_server $aprsis_server `
-modem_host_name $modem_host_name `
-modem_kiss_port_number $modem_kiss_port_number `
-lat $lat `
-lon $lon `
-aprx_internal_log_directory $aprx_internal_log_directory
}
catch {
Write-Error "Error occurred updating APRX configuration: $($_.Exception.Message)"
exit 1
}
}
function Start-Aprx {
param (