-
Notifications
You must be signed in to change notification settings - Fork 69
/
core.ps1
1641 lines (1156 loc) · 96 KB
/
core.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
#using module .\Include.psm1
param(
[Parameter(Mandatory = $false)]
[Array]$Algorithm = $null,
[Parameter(Mandatory = $false)]
[Array]$PoolsName = $null,
[Parameter(Mandatory = $false)]
[array]$CoinsName= $null,
[Parameter(Mandatory = $false)]
[String]$MiningMode = $null,
[Parameter(Mandatory = $false)]
[array]$Groupnames = $null,
[Parameter(Mandatory = $false)]
[string]$PercentToSwitch = $null
)
. .\Include.ps1
##Parameters for testing, must be commented on real use
#$MiningMode='Automatic'
#$MiningMode='Manual'
#$PoolsName=('ahashpool','miningpoolhub','hashrefinery')
#$PoolsName='whattomine'
#$PoolsName='zergpool'
#$PoolsName='yiimp'
#$PoolsName='ahashpool'
#$PoolsName=('hashrefinery','zpool')
#$PoolsName='miningpoolhub'
#$PoolsName='zpool'
#$PoolsName='hashrefinery'
#$PoolsName='altminer'
#$PoolsName='blazepool'
#$PoolsName="Nicehash"
#$PoolsName="Nanopool"
#$Coinsname =('bitcore','Signatum','Zcash')
#$Coinsname ='zcash'
#$Algorithm =('phi','x17')
#$Groupnames=('rx580')
$error.clear()
$currentDir = Split-Path -Parent $MyInvocation.MyCommand.Path
#Start log file
$logname=".\Logs\$(Get-Date -Format "yyyy-MM-dd_HH-mm-ss").txt"
Start-Transcript $logname #for start log msg
Stop-Transcript
$LogFile= [System.IO.StreamWriter]::new( $logname,$true )
$LogFile.AutoFlush=$true
clear_files
[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]'Ssl3,Tls,Tls11,Tls12'
$ErrorActionPreference = "Continue"
$config=get_config
$Release="6.4"
writelog ("Release $Release") $logfile $false
if ($Groupnames -eq $null) {$Host.UI.RawUI.WindowTitle = "MegaMiner"} else {$Host.UI.RawUI.WindowTitle = "MM-" + ($Groupnames -join "/")}
$env:CUDA_DEVICE_ORDER = 'PCI_BUS_ID' #This align cuda id with nvidia-smi order
$env:GPU_FORCE_64BIT_PTR = 0 #For AMD
$env:GPU_MAX_HEAP_SIZE = 100 #For AMD
$env:GPU_USE_SYNC_OBJECTS = 1 #For AMD
$env:GPU_MAX_ALLOC_PERCENT = 100 #For AMD
$env:GPU_SINGLE_ALLOC_PERCENT = 100 #For AMD
$progressPreference = 'silentlyContinue' #No progress message on web requests
#$progressPreference = 'Stop'
Set-Location (Split-Path $script:MyInvocation.MyCommand.Path)
Get-ChildItem . -Recurse | Unblock-File
#add MM path to windows defender exclusions
$DefenderExclusions = (Get-MpPreference).CimInstanceProperties |Where-Object name -eq 'ExclusionPath'
if ($DefenderExclusions.value -notcontains (Convert-Path .)) {Start-Process powershell -Verb runAs -ArgumentList "Add-MpPreference -ExclusionPath '$(Convert-Path .)'"}
$ActiveMiners = @()
$Activeminers = @()
$ShowBestMinersOnly=$true
$FirstTotalExecution =$true
$StartTime=get-date
if (($config.DEBUGLOG) -eq "ENABLED"){$DetailedLog=$True} else {$DetailedLog=$false}
$Screen = $config.STARTSCREEN
#---Paraneters checking
if ($MiningMode -ne 'Automatic' -and $MiningMode -ne 'Manual' -and $MiningMode -ne 'Automatic24h'){
"Parameter MiningMode not valid, valid options: Manual, Automatic, Automatic24h" |Out-host
EXIT
}
$PoolsChecking=Get_Pools -Querymode "info" -PoolsFilterList $PoolsName -CoinFilterList $CoinsName -Location $location -AlgoFilterList $Algorithm
$PoolsErrors=@()
switch ($MiningMode){
"Automatic"{$PoolsErrors =$PoolsChecking |Where-Object ActiveOnAutomaticMode -eq $false}
"Automatic24h"{$PoolsErrors =$PoolsChecking |Where-Object ActiveOnAutomatic24hMode -eq $false}
"Manual"{$PoolsErrors =$PoolsChecking |Where-Object ActiveOnManualMode -eq $false }
}
$PoolsErrors |ForEach-Object {
"Selected MiningMode is not valid for pool "+$_.name |Out-host
EXIT
}
if ($MiningMode -eq 'Manual' -and ($Coinsname | Measure-Object).count -gt 1){
"On manual mode only one coin must be selected" |Out-host
EXIT
}
if ($MiningMode -eq 'Manual' -and ($Coinsname | Measure-Object).count -eq 0){
"On manual mode must select one coin" |Out-host
EXIT
}
if ($MiningMode -eq 'Manual' -and ($Algorithm | measure-object).count -gt 1){
"On manual mode only one algorithm must be selected" |Out-host
EXIT
}
#parameters backup
$ParamAlgorithmBCK=$Algorithm
$ParamPoolsNameBCK=$PoolsName
$ParamCoinsNameBCK=$CoinsName
$ParamMiningModeBCK=$MiningMode
try {set_WindowSize 185 60 } catch {}
$IntervalStartAt = (Get-Date) #first inicialization, must be outside loop
ErrorsToLog $LogFile
$Msg="Starting Parameters: "
$Msg+=" //Algorithm: "+[String]($Algorithm -join ",")
$Msg+=" //PoolsName: "+[String]($PoolsName -join ",")
$Msg+=" //CoinsName: "+[String]($CoinsName -join ",")
$Msg+=" //MiningMode: "+$MiningMode
$Msg+=" //Groupnames: "+[String]($Groupnames -join ",")
$Msg+=" //PercentToSwitch: "+$PercentToSwitch
WriteLog $msg $LogFile $False
#get mining types
$Types=Get_Mining_Types -filter $Groupnames
writelog ( get_gpu_information $Types |ConvertTo-Json) $logfile $false
Writelog ( $Types |ConvertTo-Json) $logfile $false
$NumberTypesGroups=($Types | Measure-Object).count
if ($NumberTypesGroups -gt 0) {$InitialProfitsScreenLimit=[Math]::Floor( 25 /$NumberTypesGroups)} #screen adjust to number of groups
$ProfitsScreenLimit=$InitialProfitsScreenLimit
Check_GpuGroups_Config $types
#Enable api
if ($config.ApiPort -gt 0) {
writelog ("Starting API in port "+[string]$config.ApiPort) $logfile $false
$ApiSharedFile=$currentDir +"\ApiShared"+[string](Get-Random -minimum 0 -maximum 99999999)+".tmp"
$command = "-WindowStyle minimized -noexit -executionpolicy bypass -file $currentDir\ApiListener.ps1 -port "+[string]$config.ApiPort+" -SharedFile $ApiSharedFile "
$APIprocess = Start-Process -FilePath "powershell.exe" -ArgumentList $command -Verb RunAs -PassThru
#open firewall port
$command='New-NetFirewallRule -DisplayName "Megaminer" -Direction Inbound -Action Allow -Protocol TCP -LocalPort '+[string]$config.ApiPort
Start-Process -FilePath "powershell.exe" -ArgumentList $command -Verb RunAs
$command='New-NetFirewallRule -DisplayName "Megaminer" -Direction Outbound -Action Allow -Protocol TCP -LocalPort '+[string]$config.ApiPort
Start-Process -FilePath "powershell.exe" -ArgumentList $command -Verb RunAs
}
$Quit=$false
#enable EthlargementPill
if (($config.EthlargementPill) -like "REV*")
{
writelog "Starting ETHlargementPill " $logfile $false
$arg="-"+$config.EthlargementPill
$EthPill = Start-Process -FilePath "OhGodAnETHlargementPill-r2.exe" -passthru -Verb RunAs -ArgumentList $arg
}
# Check for updates
try {
$Request = Invoke-RestMethod -Uri "https://api.github.com/repos/tutulino/Megaminer/releases/latest" -UseBasicParsing -TimeoutSec 10 -ErrorAction Stop
$RemoteVersion = ($Request.tag_name -replace '^v')
if ($RemoteVersion -gt $Release) {
writelog "THERE IS A NEW MEGAMINER RELEASE AVAILABLE, PLEASE DOWNLOAD" $logfile $false
Write-Host "THERE IS A NEW MEGAMINER RELEASE AVAILABLE, PLEASE DOWNLOAD" -ForegroundColor Yellow
start-sleep 5
}
} catch {
writelog "Failed to get $Application updates." $logfile $false
}
#----------------------------------------------------------------------------------------------------------------------------
#----------------------------------------------------------------------------------------------------------------------------
#----------------------------------------------------------------------------------------------------------------------------
#----------------------------------------------------------------------------------------------------------------------------
#This loop will be runnig forever
#----------------------------------------------------------------------------------------------------------------------------
#----------------------------------------------------------------------------------------------------------------------------
#----------------------------------------------------------------------------------------------------------------------------
#----------------------------------------------------------------------------------------------------------------------------
while ($Quit -eq $false) {
$config=get_config
Clear-Host;$repaintScreen=$true
WriteLog "New interval starting............." $LogFile $True
Writelog ( Get_ComputerStats |ConvertTo-Json) $logfile $false
$Location=$config.LOCATION
if ($PercentToSwitch -eq "") {$PercentToSwitch2 = [int]($config.PERCENTTOSWITCH)} else {$PercentToSwitch2=[int]$PercentToSwitch}
$DelayCloseMiners=$config.DELAYCLOSEMINERS
#$Currency= $config.CURRENCY
$BenchmarkintervalTime=[int]($config.BENCHMARKTIME )
$LocalCurrency= $config.LOCALCURRENCY
if ($LocalCurrency.length -eq 0) { #for old config.txt compatibility
switch ($location) {
'EU' {$LocalCurrency="EURO"}
'US' {$LocalCurrency="DOLLAR"}
'ASIA' {$LocalCurrency="DOLLAR"}
'GB' {$LocalCurrency="GBP"}
default {$LocalCurrency="DOLLAR"}
}
}
$DelayCloseMiners=[int]($config.DELAYCLOSEMINERS)
#Donation
$LastIntervalTime= (get-date) - $IntervalStartAt
$IntervalStartAt = (Get-Date)
$DonationPastTime= ((Get-Content Donation.ctr) -split '_')[0]
$DonatedTime = ((Get-Content Donation.ctr) -split '_')[1]
If ($DonationPastTime -eq $null -or $DonationPastTime -eq "" ) {$DonationPastTime=0}
If ($DonatedTime -eq $null -or $DonatedTime -eq "" ) {$DonatedTime=0}
$ElapsedDonationTime = [int]($DonationPastTime) + $LastIntervalTime.minutes + ($LastIntervalTime.hours *60)
$ElapsedDonatedTime = [int]($DonatedTime) + $LastIntervalTime.minutes + ($LastIntervalTime.hours *60)
$ConfigDonateTime= [int]($config.DONATE)
#if ($DonateTime -gt 5) {[int]$DonateTime=5}
#Activate or deactivate donation
if ($ElapsedDonationTime -gt 1440 -and $ConfigDonateTime -gt 0) { # donation interval
$DonationInterval = $true
$UserName = "tutulino"
#$WorkerName = "Megaminer"
$CoinsWallets=@{}
$CoinsWallets.add("BTC","1AVMHnFgc6SW33cwqrDyy2Fug9CsS8u6TM")
$NextInterval= ($ConfigDonateTime *60) - ($ElapsedDonatedTime *60)
$Algorithm=$null
$PoolsName="DonationPool"
$CoinsName=$null
$MiningMode="Automatic"
if ($ElapsedDonatedTime -ge $ConfigDonateTime) {"0_0" | Set-Content -Path Donation.ctr} else {[string]$DonationPastTime+"_"+[string]$ElapsedDonatedTime | Set-Content -Path Donation.ctr}
WriteLog ("Next interval you will be donating , thanks for your support") $LogFile $True
}
else { #NOT donation interval
$DonationInterval = $false
#get interval time based on pool kind (pps/ppls)
$NextInterval=0
Get_Pools -Querymode "Info" -PoolsFilterList $PoolsName -CoinFilterList $CoinsName -Location $Location -AlgoFilterList $Algorithm | foreach-object {
$PItime=$config.("INTERVAL_"+$_.Rewardtype)
if ([int]$PItime -gt $NextInterval) {$NextInterval= [int]$PItime}
WriteLog ("Next interval will be $NextInterval") $LogFile $True
}
$Algorithm=$ParamAlgorithmBCK
$PoolsName=$ParamPoolsNameBCK
$CoinsName=$ParamCoinsNameBCK
$MiningMode=$ParamMiningModeBCK
$UserName= $config.USERNAME
$WorkerName= $config.WORKERNAME
$CoinsWallets=@{}
((Get-Content config.txt | Where-Object {$_ -like '@@WALLET_*=*'}) -replace '@@WALLET_*=*','').TrimEnd() | ForEach-Object {$CoinsWallets.add(($_ -split "=")[0],($_ -split "=")[1])}
[string]$ElapsedDonationTime+"_0" | Set-Content -Path Donation.ctr
}
ErrorsToLog $LogFile
#get actual hour electricity cost
$ElectricityCostValue= [double](($config.ElectricityCost |ConvertFrom-Json) |where-object HourStart -le (get-date).Hour |where-object HourEnd -ge (get-date).Hour).CostKwh
WriteLog "Loading Pools Information............." $LogFile $True
#Load information about the Pools, only must read parameter passed files (not all as mph do), level is Pool-Algo-Coin
do
{
$Pools=Get_Pools -Querymode "core" -PoolsFilterList $PoolsName -CoinFilterList $CoinsName -Location $Location -AlgoFilterList $Algorithm
if ($Pools.Count -eq 0) {
$Msg="NO POOLS!....retry in 10 sec --- REMEMBER, IF YOUR ARE MINING ON ANONYMOUS WITHOUT AUTOEXCHANGE POOLS LIKE YIIMP, NANOPOOL, ETC. YOU MUST SET WALLET FOR AT LEAST ONE POOL COIN IN CONFIG.TXT"
WriteLog $msg $logFile $true
Start-Sleep 10}
}
while ($Pools.Count -eq 0)
$Pools | Select-Object name -unique | foreach-object {Writelog ("Pool "+$_.name+" was responsive....") $logfile $true}
writelog ("Detected "+[string]$Pools.count+" pools......") $logfile $true
#Filter by minworkers variable (only if there is any pool greater than minimum)
$PoolsFiltered=($Pools | Where-Object {$_.Poolworkers -ge ($config.MINWORKERS) -or $_.Poolworkers -eq $null})
if ($PoolsFiltered.count -ge 1) {
$Pools = $PoolsFiltered
writelog ([string]$Pools.count+" pools left after min workers filter.....") $logfile $true
}
else {
writelog ("No pools with workers greater than minimum config, filter is discarded.....") $logfile $true
}
Remove-Variable PoolsFiltered
#Call api to local currency conversion
try {
$CDKResponse = Invoke-WebRequest "https://api.coindesk.com/v1/bpi/currentprice.json" -UseBasicParsing -TimeoutSec 2 | ConvertFrom-Json | Select-Object -ExpandProperty BPI
writelog "Coindesk api was responsive.........." $logfile $true
switch ($LocalCurrency) {
'EURO' {$LocalSymbol=[convert]::ToChar(8364) ; $localBTCvalue = [double]$CDKResponse.eur.rate}
'DOLLAR' {$LocalSymbol=[convert]::ToChar(36) ; $localBTCvalue = [double]$CDKResponse.usd.rate}
'GBP' {$LocalSymbol=[convert]::ToChar(163) ; $localBTCvalue = [double]$CDKResponse.gbp.rate}
default {$LocalSymbol=" $" ; $localBTCvalue = [double]$CDKResponse.usd.rate}
}
}
catch {
writelog "Coindesk api not responding, not possible/deactuallized local coin conversion.........." $logfile $true
}
#Load information about the Miner asociated to each Coin-Algo-Miner
$Miners= @()
$MinersFolderContent=(Get-ChildItem "Miners" | Where-Object extension -eq '.json')
Writelog ("Files in miner folder: "+ [string]($MinersFolderContent.count)) $LogFile $false
Writelog ("Number of gpu groups: "+ $types.count) $LogFile $false
foreach ($MinerFile in $MinersFolderContent)
{
try { $Miner =$MinerFile | Get-Content | ConvertFrom-Json }
catch {Writelog "-------BAD FORMED JSON: $MinerFile" $LogFile $true;Exit}
ForEach ($TypeGroup in $types) { #generate a line for each gpu group that has algorithm as valid
if ($Miner.Types -notcontains $TypeGroup.type) {
if ($DetailedLog) {Writelog ([string]$MinerFile.pschildname+" is NOT valid for "+ $TypeGroup.groupname+"...ignoring") $LogFile $false }
continue
} #check group and miner types are the same
else
{ if ($DetailedLog) {Writelog ([string]$MinerFile.pschildname+" is valid for "+ $TypeGroup.groupname) $LogFile $false }}
foreach ($Algo in $Miner.Algorithms)
{
##Algoname contains real name for dual and no dual miners
$AlgoTmp=($Algo.PSObject.Properties.Name -split "\|")[0]
$AlgoLabel = ($Algo.PSObject.Properties.Name -split ("\|"))[1]
$AlgoName = (($AlgoTmp -split ("_"))[0]).toupper().trimend()
$AlgoNameDual = (($AlgoTmp -split ("_"))[1])
if ($AlgoNameDual -ne $null) {
$AlgoNameDual=$AlgoNameDual.toupper()
$Algorithms=$AlgoName+"_"+$AlgoNameDual
}
else {$Algorithms=$AlgoName}
if ($Typegroup.Algorithms -notcontains $Algorithms) {continue} #check config has this algo as minable
Foreach ($Pool in ($Pools | where-object Algorithm -eq $AlgoName)) { #Search pools for that algo
if ((($Pools | Where-Object Algorithm -eq $AlgoNameDual) -ne $null) -or ($AlgoNameDual -eq $null)){
if ($Miner.DualMiningMainCoin -contains $Pool.info -or $AlgoNameDual -eq $null) { #not allow dualmining if main coin not coincide
#Replace wildcards patterns
if ($Types.Count -gt 1) {
if ($Pool.name -eq 'Nicehash') {$WorkerName2=$WorkerName+$TypeGroup.GroupName} else {$WorkerName2=$WorkerName+'_'+$TypeGroup.GroupName}
}
else {$WorkerName2=$WorkerName}
$Arguments = $Miner.Arguments -replace '#PORT#',$Pool.Port -replace '#SERVER#',$Pool.Host -replace '#PROTOCOL#',$Pool.Protocol -replace '#LOGIN#',$Pool.user -replace '#PASSWORD#',$Pool.Pass -replace "#GpuPlatform#",$TypeGroup.GpuPlatform -replace '#ALGORITHM#',$Algoname -replace '#ALGORITHMPARAMETERS#',$Algo.PSObject.Properties.Value -replace '#WORKERNAME#',$WorkerName2 -replace '#DEVICES#',$TypeGroup.Gpus -replace '#DEVICESCLAYMODE#',$TypeGroup.GpusClayMode -replace '#DEVICESETHMODE#',$TypeGroup.GpusETHMode -replace '#GROUPNAME#',$TypeGroup.Groupname -replace "#ETHSTMODE#",$Pool.EthStMode -replace "#DEVICESNSGMODE#",$TypeGroup.GpusNsgMode
if ($Miner.PatternConfigFile -ne $null) {
$ConfigFileArguments = replace_foreach_gpu (get-content $Miner.PatternConfigFile -raw) $TypeGroup.Gpus
$ConfigFileArguments = $ConfigFileArguments -replace '#PORT#',$Pool.Port -replace '#SERVER#',$Pool.Host -replace '#PROTOCOL#',$Pool.Protocol -replace '#LOGIN#',$Pool.user -replace '#PASSWORD#',$Pool.Pass -replace "#GpuPlatform#",$TypeGroup.GpuPlatform -replace '#ALGORITHM#',$Algoname -replace '#ALGORITHMPARAMETERS#',$Algo.PSObject.Properties.Value -replace '#WORKERNAME#',$WorkerName2 -replace '#DEVICES#',$TypeGroup.Gpus -replace '#DEVICESCLAYMODE#',$TypeGroup.GpusClayMode -replace '#DEVICESETHMODE#',$TypeGroup.GpusETHMode -replace '#GROUPNAME#',$TypeGroup.Groupname -replace "#ETHSTMODE#",$Pool.EthStMode -replace "#DEVICESNSGMODE#",$TypeGroup.GpusNsgMode
}
$PoolPass=$Pool.Pass -replace '#WORKERNAME#',$WorkerName2
$PoolUser=$Pool.User -replace '#WORKERNAME#',$WorkerName2
#Adjust pool price by pool defined factor
$PoolProfitFactor=[double]($config.("POOLPROFITFACTOR_"+$Pool.name))
if ($PoolProfitFactor -eq "") { $PoolProfitFactor=1}
#select correct price by mode
if ($MiningMode -eq 'Automatic24h') {$Price = [double]$Pool.Price24h * $PoolProfitFactor}
else {$Price = [double]$Pool.Price * $PoolProfitFactor}
#Search for dualmining pool
if ($Miner.Dualmining) {
#Adjust pool dual price by pool defined factor
$PoolProfitFactorDual=[double]($config.("POOLPROFITFACTOR_"+$PoolDual.name))
if ($PoolProfitFactorDual -eq "") { $PoolProfitFactorDual=1}
#search dual pool and select correct price by mode
if ($MiningMode -eq 'Automatic24h') {
$PoolDual = $Pools |where-object Algorithm -eq $AlgoNameDual | sort-object price24h -Descending| Select-Object -First 1
$PriceDual=[double]$PoolDual.Price24h * $PoolProfitFactor
}
else {
$PoolDual = $Pools |where-object Algorithm -eq $AlgoNameDual | sort-object price -Descending| Select-Object -First 1
$PriceDual=[double]$PoolDual.Price * $PoolProfitFactor
}
#Replace wildcards patterns
$WorkerName3=$WorkerName2+'D'
$PoolPassDual=$PoolDual.Pass -replace '#WORKERNAME#',$WorkerName3
$PoolUserDual=$PoolDual.user -replace '#WORKERNAME#',$WorkerName3
$Arguments = $Arguments -replace '#PORTDUAL#',$PoolDual.Port -replace '#SERVERDUAL#',$PoolDual.Host -replace '#PROTOCOLDUAL#',$PoolDual.Protocol -replace '#LOGINDUAL#',$PoolUserDual -replace '#PASSWORDDUAL#',$PoolPassDual -replace '#ALGORITHMDUAL#',$AlgonameDual -replace '#WORKERNAME#',$WorkerName3
if ($Miner.PatternConfigFile -ne $null) {
$ConfigFileArguments = $ConfigFileArguments -replace '#PORTDUAL#',$PoolDual.Port -replace '#SERVERDUAL#',$PoolDual.Host -replace '#PROTOCOLDUAL#',$PoolDual.Protocol -replace '#LOGINDUAL#',$PoolUserDual -replace '#PASSWORDDUAL#',$PoolPassDual -replace '#ALGORITHMDUAL#' -replace '#WORKERNAME#',$WorkerName3
}
}
#Subminer are variations of miner that not need to relaunch
#Creates a "subminer" object for each PL
$Subminers=@()
Foreach ($PowerLimit in ($TypeGroup.PowerLimits)) { #always exists as least a power limit 0
#writelog ("$MinerFile $AlgoName "+$TypeGroup.Groupname+" "+$Pool.Info+" $PowerLimit") $logfile $true
#look in Activeminers collection if we found that miner to conserve some properties and not read files
$FoundMiner = $ActiveMiners | Where-Object {
$_.Name -eq $Minerfile.basename -and
$_.Coin -eq $Pool.Info -and
$_.Algorithm -eq $AlgoName -and
$_.CoinDual -eq $PoolDual.Info -and
$_.AlgorithmDual -eq $AlgoNameDual -and
$_.PoolAbbName -eq $Pool.AbbName -and
$_.PoolAbbNameDual -eq $PoolDual.AbbName -and
$_.GpuGroup.Id -eq $TypeGroup.Id -and
$_.AlgoLabel -eq $AlgoLabel }
$FoundSubminer= $FoundMiner.subminers | Where-Object { $_.powerlimit -eq $PowerLimit}
if ($FoundSubminer -eq $null) {
$Hrs = Get_Hashrates -algorithm $Algorithms -minername $Minerfile.basename -GroupName $TypeGroup.GroupName -PowerLimit $PowerLimit -AlgoLabel $AlgoLabel | Where-Object {$_.TimeSinceStartInterval -gt ($_.BenchmarkintervalTime * 0.66)}
}
else
{$Hrs=$FoundSubminer.SpeedReads}
$PowerValue=[double]($Hrs | measure-object -property Power -average).average
$HashrateValue=[double]($Hrs | measure-object -property Speed -average).average
$HashrateValueDual=[double]($Hrs | measure-object -property SpeedDual -average).average
#calculates revenue
$SubMinerRevenue = [double]($HashrateValue * $Price)
$SubMinerRevenueDual = [Double]([double]$HashrateValueDual * $PriceDual)
#apply fee to revenues
if ([double]$Miner.Fee -gt 0) { #MinerFee
$SubMinerRevenue-=($SubMinerRevenue*[double]$Miner.fee)
$SubMinerRevenueDual-=($MinerRevenueDual*[double]$Miner.fee)
}
if ([double]$Pool.Fee -gt 0) {$SubMinerRevenue-=($SubMinerRevenue*[double]$Pool.fee)} #PoolFee
if ([double]$PoolDual.Fee -gt 0) {$SubMinerRevenueDual-=($MinerRevenueDual*[double]$PoolDual.fee)}
if ($FoundSubminer -eq $null) {
$StatsHistory=Get_Stats -algorithm $Algorithms -minername $Minerfile.basename -GroupName $TypeGroup.GroupName -PowerLimit $PowerLimit -AlgoLabel $AlgoLabel
}
else {
$StatsHistory=$FoundSubminer.StatsHistory
}
$Stats=[pscustomobject]@{
BestTimes = 0
BenchmarkedTimes = 0
LastTimeActive = [TimeSpan]0
ActivatedTimes = 0
ActiveTime = [TimeSpan]0
FailedTimes =0
StatsTime = get-date
}
if ($StatsHistory -eq $null) {$StatsHistory=$stats}
if ($Subminers.count -eq 0 -or $Subminers[0].StatsHistory.BestTimes -gt 0) { #only add a subminer (distint from first if sometime first was best)
$Subminers+=[pscustomObject]@{
Id = $Subminers.count
Best = $False
BestBySwitch = ""
Hashrate = $HashrateValue
HashrateDual = $HashrateValueDual
NeedBenchmark = if ($HashrateValue -eq 0 -or ($AlgorithmDual -ne $null -and $HashrateValueDual -eq 0)) {$true} else {$False}
PowerAvg = $PowerValue
PowerLimit = [int]$PowerLimit
PowerLive = 0
Profits = (($SubMinerRevenue + $SubMinerRevenueDual)* $localBTCvalue) - ($ElectricityCostValue*($PowerValue*24)/1000) #Profit is revenue less electricity cost, can separate profit in dual and non dual because electricity cost can be divided
ProfitsLive = 0
Revenue = $SubMinerRevenue
RevenueDual = $SubMinerRevenueDual
RevenueLive = 0
RevenueLiveDual = 0
SpeedLive = 0
SpeedLiveDual = 0
SpeedReads = if ($Hrs -ne $null) {[array]$Hrs} else {@()}
Status = 'Idle'
Stats = $Stats
StatsHistory = $StatsHistory
TimeSinceStartInterval= [TimeSpan]0
CancelationTime = $null
}
}
}
$Miners += [pscustomobject] @{
AlgoLabel=$AlgoLabel
Algorithm = $AlgoName
AlgorithmDual = $AlgoNameDual
Algorithms=$Algorithms
API = $Miner.API
Arguments=$Arguments
Coin = $Pool.Info.tolower()
CoinDual = $PoolDual.Info
ConfigFileArguments = $ConfigFileArguments
DualMining = $Miner.Dualmining
ExtractionPath = $Miner.ExtractionPath
GenerateConfigFile = $miner.GenerateConfigFile -replace '#GROUPNAME#',$TypeGroup.Groupname
GpuGroup = $TypeGroup
Host =$Pool.Host
Location = $Pool.location
MinerFee= if ($Miner.Fee -eq $null) {$null} else {[double]$Miner.fee}
Name = $Minerfile.basename
Path = $Miner.Path
PoolAbbName = $Pool.AbbName
PoolAbbNameDual = $PoolDual.AbbName
PoolFee = if ($Pool.Fee -eq $null) {$null} else {[double]$Pool.fee}
PoolName = $Pool.name
PoolNameDual = $PoolDual.name
PoolPass= $PoolPass
PoolPrice=$Price
PoolPriceDual=$PriceDual
PoolWorkers = $Pool.PoolWorkers
PoolWorkersDual = $PoolDual.PoolWorkers
Port = if (($Types |Where-object type -eq $TypeGroup.type).count -le 1 -and $DelayCloseMiners -eq 0 -and $config.ForceDynamicPorts -ne "Enabled" ) {$miner.ApiPort} else {$null}
PrelaunchCommand = $Miner.PrelaunchCommand
Subminers = $Subminers
Symbol = $Pool.Symbol
SymbolDual = $PoolDual.Symbol
URI = $Miner.URI
Username = $PoolUser
UsernameDual = $PoolUserDual
UsernameReal = ($PoolUser -split '\.')[0]
UsernameRealDual = ($PoolUserDual -split '\.')[0]
WalletMode=$Pool.WalletMode
WalletSymbol = $Pool.WalletSymbol
Workername= $WorkerName2
WorkernameDual= $WorkerName3
}
} #dualmining
}
} #end foreach pool
} #end foreach algo
} # end if types
} #end foreach miner
Writelog ("Miners/Pools combinations detected: "+ [string]($Miners.count)+".........") $LogFile $true
#Launch download of miners
$Miners | where-object {$_.URI -ne $null -and $_.ExtractionPath -ne $null -and $_.Path -ne $null -and $_.URI -ne "" -and $_.ExtractionPath -ne "" -and $_.Path -ne ""} | Select-Object URI, ExtractionPath,Path -Unique | ForEach-Object {
if (-not (Test-Path $_.Path)) { Start_Downloader -URI $_.URI -ExtractionPath $_.ExtractionPath -Path $_.Path}
}
ErrorsToLog $LogFile
#Paint no miners message
$Miners = $Miners | Where-Object {Test-Path $_.Path}
if ($Miners.Count -eq 0) {Writelog "NO MINERS!" $LogFile $true ; EXIT}
#Update the active miners list which is alive for all execution time
ForEach ($ActiveMiner in ($ActiveMiners|Sort-Object [int]id)) { #Search existant miners to update data
$Miner = $miners | Where-Object {$_.Name -eq $ActiveMiner.Name -and
$_.Coin -eq $ActiveMiner.Coin -and
$_.Algorithm -eq$ActiveMiner.Algorithm -and
$_.CoinDual -eq $ActiveMiner.CoinDual -and
$_.AlgorithmDual -eq $ActiveMiner.AlgorithmDual -and
$_.PoolAbbName -eq $ActiveMiner.PoolAbbName -and
$_.PoolAbbNameDual -eq $ActiveMiner.PoolAbbNameDual -and
$_.GpuGroup.Id -eq $ActiveMiner.GpuGroup.Id -and
$_.AlgoLabel -eq $ActiveMiner.AlgoLabel }
if (($Miner | Measure-Object).count -gt 1) {
Clear-Host; Writelog ("DUPLICATED MINER "+$MINER.ALGORITHMS+" ON "+$MINER.NAME) $LogFile $true
EXIT
}
if ($Miner) { # we found that miner
$ActiveMiner.Arguments= $miner.Arguments
$ActiveMiner.PoolPrice = $Miner.PoolPrice
$ActiveMiner.PoolPriceDual = $Miner.PoolPriceDual
$ActiveMiner.PoolFee= $Miner.PoolFee
$ActiveMiner.PoolWorkers = $Miner.PoolWorkers
$ActiveMiner.IsValid=$true
foreach ($subminer in $miner.Subminers) {
if (($ActiveMiner.Subminers | where-object {$_.Id -eq $subminer.Id}).count -eq 0) {
$Subminer | Add-Member IdF $ActiveMiner.Id
$ActiveMiner.Subminers+=$Subminer
}
else {
$ActiveMiner.Subminers[$subminer.Id].Hashrate = $Subminer.Hashrate
$ActiveMiner.Subminers[$subminer.Id].HashrateDual=$Subminer.HashrateDual
$ActiveMiner.Subminers[$subminer.Id].NeedBenchmark=$Subminer.NeedBenchmark
$ActiveMiner.Subminers[$subminer.Id].PowerAvg=$Subminer.PowerAvg
$ActiveMiner.Subminers[$subminer.Id].Profits=$Subminer.Profits
$ActiveMiner.Subminers[$subminer.Id].Revenue=$Subminer.Revenue
$ActiveMiner.Subminers[$subminer.Id].RevenueDual=$Subminer.RevenueDual
}
}
}
else { #An existant miner is not found now
$ActiveMiner.IsValid=$false
}
}
##Add new miners to list
ForEach ($miner in $miners) {
$ActiveMiner = $ActiveMiners | Where-Object {$_.Name -eq $Miner.Name -and
$_.Coin -eq $Miner.Coin -and
$_.Algorithm -eq $Miner.Algorithm -and
$_.CoinDual -eq $Miner.CoinDual -and
$_.AlgorithmDual -eq $Miner.AlgorithmDual -and
$_.PoolAbbName -eq $Miner.PoolAbbName -and
$_.PoolAbbNameDual -eq $Miner.PoolAbbNameDual -and
$_.GpuGroup.Id -eq $Miner.GpuGroup.Id -and
$_.AlgoLabel -eq $Miner.AlgoLabel}
if ($ActiveMiner -eq $null) {
$Miner.SubMiners | Add-Member IdF $ActiveMiners.count
$ActiveMiners += [pscustomObject]@{
AlgoLabel = $Miner.AlgoLabel
Algorithm = $Miner.Algorithm
AlgorithmDual = $Miner.AlgorithmDual
Algorithms = $Miner.Algorithms
API = $Miner.API
Arguments = $Miner.Arguments
ConsecutiveZeroSpeed = 0
Coin = $Miner.coin
CoinDual = $Miner.CoinDual
ConfigFileArguments = $Miner.ConfigFileArguments
DualMining = $Miner.DualMining
GenerateConfigFile = $Miner.GenerateConfigFile
GpuGroup = $Miner.GpuGroup
Host = $Miner.Host
Id = $ActiveMiners.count
IsValid = $true
Location = $Miner.Location
MinerFee = $Miner.MinerFee
Name = $Miner.Name
Path = Convert-Path $Miner.Path
PoolAbbName = $Miner.PoolAbbName
PoolAbbNameDual = $Miner.PoolAbbNameDual
PoolFee = $Miner.PoolFee
PoolName = $Miner.PoolName
PoolNameDual = $Miner.PoolNameDual
PoolPrice = $Miner.PoolPrice
PoolPriceDual = $Miner.PoolPriceDual
PoolWorkers = $Miner.PoolWorkers
PoolHashrate = $null
PoolHashrateDual = $null
PoolPass = $Miner.PoolPass
Port = $Miner.Port
PrelaunchCommand = $Miner.PrelaunchCommand
Process = $null
SubMiners = $Miner.SubMiners
Symbol = $Miner.Symbol
SymbolDual = $Miner.SymbolDual
Username = $Miner.Username
UsernameDual = $Miner.UsernameDual
UserNameReal = $Miner.UserNameReal
UserNameRealDual = $Miner.UserNameRealDual
WalletMode = $Miner.WalletMode
WalletSymbol = $Miner.WalletSymbol
Workername = $Miner.Workername
WorkernameDual = $Miner.WorkernameDual
}
}
}
Writelog ("Active Miners-pools: "+ [string]($ActiveMiners.count)+".........") $LogFile $true
ErrorsToLog $LogFile
Writelog ("Pending benchmarks: "+ [string](($ActiveMiners.subminers | where-object NeedBenchmark -eq $true).count)+".........") $LogFile $true
$msg=""
if ($DetailedLog) {
$ActiveMiners.subminers| foreach-object {$msg+=[string] $_.Idf+'-'+[string]$_.Id+','+$ActiveMiners[$_.idf].gpugroup.groupname+','+$ActiveMiners[$_.idf].IsValid+', PL'+[string]$_.PowerLimit+','+$_.Status+','+$ActiveMiners[$_.idf].name+','+$ActiveMiners[$_.idf].algorithms+','+$ActiveMiners[$_.idf].Coin+','+[string]($ActiveMiners[$_.idf].process.id)+"`r`n"}
Writelog $msg $LogFile $false
}
#checks if there is any cancelled miner must be reactivated
$ActiveMiners.subminers | Where-Object {$_.Status -eq "Cancelled" -and $_.CancellationTime.TotalMinutes -gt 3600} | foreach-object {
$_.Status = "Iddle"
$_.CancellationTime = $null
Writelog ("Cancelation time elapsed, reactivated"+$ActiveMiners[$_.IdF].name+"/"+$ActiveMiners[$_.IdF].Algorithms+'/'+$ActiveMiners[$_.IdF].Coin+" with Power Limit "+[string]$_.PowerLimit+" (id "+[string]$_.IdF+"-"+[string]$_.Id+")") $LogFile $true
}
#For each type, select most profitable miner, not benchmarked has priority, only new miner is lauched if new profit is greater than old by percenttoswitch
#This section changes subminer
foreach ($Type in $Types) {
#look for last round best
$Candidates = $ActiveMiners | Where-Object {$_.GpuGroup.Id -eq $Type.Id}
$BestLast = $Candidates.subminers | Where-Object {$_.Status -eq "Running" -or $_.Status -eq 'PendingCancellation'}
if ($BestLast -ne $null) {
$ProfitLast=$BestLast.profits
$BestLastLogMsg=$ActiveMiners[$BestLast.IdF].name+"/"+$ActiveMiners[$BestLast.IdF].Algorithms+'/'+$ActiveMiners[$BestLast.IdF].Coin+" with Power Limit "+[string]$BestLast.PowerLimit+" (id "+[string]$BestLast.IdF+"-"+[string]$BestLast.Id+") for group "+$Type.groupname
}
else {
$ProfitLast=0
}
#check if must cancell miner/algo/coin combo
if ($BestLast.Status -eq 'PendingCancellation') {
if (($ActiveMiners[$BestLast.IdF].subminers.stats.FailedTimes | Measure-Object -sum).sum -ge 2) {
$ActiveMiners[$BestLast.IdF].subminers |foreach-object{
$_.Status = 'Cancelled'
$_.CancelationTime = get-date
}
Writelog ("Detected more than 3 fails,cancelling combination for $BestNowLogMsg") $LogFile $true
}
}
#look for best for next round
$Candidates = $ActiveMiners | Where-Object {$_.GpuGroup.Id -eq $Type.Id -and $_.IsValid -and $_.Username -ne ""}
$BestNow = $Candidates.Subminers |where-object Status -ne 'Cancelled' | Sort-Object -Descending {if ($_.NeedBenchmark) {1} else {0}}, Profits,{$Activeminers[$_.IdF].Algorithm},{$Activeminers[$_.IdF].PoolPrice},PowerLimit | Select-Object -First 1
if ($BestNow -eq $null) {Writelog ("No detected any valid candidate for gpu group "+$Type.groupname) $LogFile $true ; continue }
$BestNowLogMsg=$ActiveMiners[$BestNow.IdF].name+"/"+$ActiveMiners[$BestNow.IdF].Algorithms+'/'+$ActiveMiners[$BestNow.IdF].Coin+" with Power Limit "+[string]$BestNow.PowerLimit+" (id "+[string]$BestNow.IdF+"-"+[string]$BestNow.Id+") for group "+$Type.groupname
$ProfitNow=$BestNow.Profits
if ($BestNow.NeedBenchmark -eq $false) {
$ActiveMiners[$BestNow.IdF].Subminers[$BestNow.Id].Stats.BestTimes++
$ActiveMiners[$BestNow.IdF].Subminers[$BestNow.Id].StatsHistory.BestTimes++
}
else
{$NextInterval=$BenchmarkintervalTime}
Writelog ("$BestNowLogMsg is the best combination for gpu group, last was $BestLastLogMsg") $LogFile $true
if ($BestLast.IdF -ne $BestNow.IdF -or $BestLast.Id -ne $BestNow.Id -or $BestLast.Status -eq 'PendingCancellation' -or $BestLast.Status -eq 'Cancelled') { #something changes or some miner error
if ($BestLast.IdF -eq $BestNow.IdF -and $BestLast.Id -ne $BestNow.Id) { #Must launch other subminer
if ($ActiveMiners[$BestNow.IdF].GpuGroup.Type -eq 'NVIDIA' -and $BestNow.PowerLimit -gt 0) {set_Nvidia_Powerlimit $BestNow.PowerLimit $ActiveMiners[$BestNow.IdF].GpuGroup.gpus}
if ($ActiveMiners[$BestNow.IdF].GpuGroup.Type -eq 'AMD'-and $BestNow.PowerLimit -gt 0){}
$ActiveMiners[$BestNow.IdF].Subminers[$BestNow.Id].best=$true
$ActiveMiners[$BestNow.IdF].Subminers[$BestNow.Id].Status= "Running"
$ActiveMiners[$BestNow.IdF].Subminers[$BestNow.Id].Stats.LastTimeActive = get-date
$ActiveMiners[$BestNow.IdF].Subminers[$BestNow.Id].StatsHistory.LastTimeActive = get-date
$ActiveMiners[$BestNow.IdF].Subminers[$BestNow.Id].Stats.StatsTime = get-date
$ActiveMiners[$BestNow.IdF].Subminers[$BestNow.Id].stats.ActivatedTimes++
$ActiveMiners[$BestNow.IdF].Subminers[$BestNow.Id].statsHistory.ActivatedTimes++
$ActiveMiners[$BestNow.IdF].Subminers[$BestNow.Id].TimeSinceStartInterval = [TimeSpan]0
$ActiveMiners[$BestLast.IdF].Subminers[$BestLast.Id].best=$false
Switch ($BestLast.Status) {
"Running"{$ActiveMiners[$BestLast.IdF].Subminers[$BestLast.Id].Status="Idle"}
"PendingCancellation"{$ActiveMiners[$BestLast.IdF].Subminers[$BestLast.Id].Status="Failed"}
"Cancelled"{$ActiveMiners[$BestLast.IdF].Subminers[$BestLast.Id].Status="Cancelled"}
}
Writelog ("$BestNowLogMsg - Marked as best, changed Power Limit from "+$BestLast.PowerLimit) $LogFile $true
}
elseif ($ProfitNow -gt ($ProfitLast *(1+($PercentToSwitch2/100))) -or $BestNow.NeedBenchmark -or $BestLast.Status -eq 'PendingCancellation' -or $BestLast.Status -eq 'Cancelled' -or $BestLast -eq $null) { #Must launch other miner and stop actual
#Stop old
if ($BestLast -ne $null) {
WriteLog ("Killing in "+[string]$DelayCloseMiners+" seconds $BestLastLogMsg with system process id "+[string]$ActiveMiners[$BestLast.IdF].Process.Id) $LogFile
if ($Bestnow.NeedBenchmark -or $DelayCloseMiners -eq 0 -or $BestLast.Status -eq 'PendingCancellation') { #inmediate kill
Kill_Process $ActiveMiners[$BestLast.IdF].Process
}
else { #delayed kill
$code={
param($ProcessId,$DelaySeconds)
Start-Sleep $DelaySeconds
if ((get-process |Where-Object id -eq 11484) -ne $ProcessId ) {Stop-Process $ProcessId -force -wa SilentlyContinue -ea SilentlyContinue }
}
Start-Job -ScriptBlock $Code -ArgumentList ($ActiveMiners[$BestLast.IdF].Process.Id),$DelayCloseMiners
}
$ActiveMiners[$BestLast.IdF].Process=$null
$ActiveMiners[$BestLast.IdF].Subminers[$BestLast.Id].best=$false
Switch ($BestLast.Status) {
"Running" {$ActiveMiners[$BestLast.IdF].Subminers[$BestLast.Id].Status="Idle"}
"PendingCancellation" {$ActiveMiners[$BestLast.IdF].Subminers[$BestLast.Id].Status="Failed"}
"Cancelled" {$ActiveMiners[$BestLast.IdF].Subminers[$BestLast.Id].Status="Cancelled"}
}
}
#Start New
if ($ActiveMiners[$BestNow.IdF].GpuGroup.Type -eq 'NVIDIA' -and $BestNow.PowerLimit -gt 0) {set_Nvidia_Powerlimit $BestNow.PowerLimit $ActiveMiners[$BestNow.IdF].GpuGroup.gpus}
if ($ActiveMiners[$BestNow.IdF].GpuGroup.Type -eq 'AMD'-and $BestNow.PowerLimit -gt 0){}
$ActiveMiners[$BestNow.IdF].Subminers[$BestNow.Id].best=$true
if ($ActiveMiners[$BestNow.IdF].Port -eq $null) { $ActiveMiners[$BestNow.IdF].Port = get_next_free_port (Get-Random -minimum 2000 -maximum 48000)}
$ActiveMiners[$BestNow.IdF].Arguments = $ActiveMiners[$BestNow.IdF].Arguments -replace '#APIPORT#',$ActiveMiners[$BestNow.IdF].Port
$ActiveMiners[$BestNow.IdF].ConfigFileArguments = $ActiveMiners[$BestNow.IdF].ConfigFileArguments -replace '#APIPORT#',$ActiveMiners[$BestNow.IdF].Port
$ActiveMiners[$BestNow.IdF].Subminers[$BestNow.Id].stats.ActivatedTimes++
$ActiveMiners[$BestNow.IdF].Subminers[$BestNow.Id].statsHistory.ActivatedTimes++
if ($ActiveMiners[$BestNow.IdF].GenerateConfigFile -ne "") {$ActiveMiners[$BestNow.IdF].ConfigFileArguments | Set-Content ($ActiveMiners[$BestNow.IdF].GenerateConfigFile)}
if ($ActiveMiners[$BestNow.IdF].PrelaunchCommand -ne $null -and $ActiveMiners[$BestNow.IdF].PrelaunchCommand -ne "") {Start-Process -FilePath $ActiveMiners[$BestNow.IdF].PrelaunchCommand} #run prelaunch command
if ($ActiveMiners[$BestNow.IdF].Api -eq "Wrapper") {$ActiveMiners[$BestNow.IdF].Process = Start-Process -FilePath "PowerShell" -ArgumentList "-executionpolicy bypass -command . '$(Convert-Path ".\Wrapper.ps1")' -ControllerProcessID $PID -Id '$($ActiveMiners[$BestNow.IdF].Port)' -FilePath '$($ActiveMiners[$BestNow.IdF].Path)' -ArgumentList '$($ActiveMiners[$BestNow.IdF].Arguments)' -WorkingDirectory '$(Split-Path $ActiveMiners[$BestNow.IdF].Path)'" -PassThru}
else {$ActiveMiners[$BestNow.IdF].Process = Start_SubProcess -FilePath $ActiveMiners[$BestNow.IdF].Path -ArgumentList $ActiveMiners[$BestNow.IdF].Arguments -WorkingDirectory (Split-Path $ActiveMiners[$BestNow.IdF].Path)}
$ActiveMiners[$BestNow.IdF].Subminers[$BestNow.Id].Status = "Running"
$ActiveMiners[$BestNow.IdF].Subminers[$BestNow.Id].Stats.LastTimeActive = get-date
$ActiveMiners[$BestNow.IdF].Subminers[$BestNow.Id].StatsHistory.LastTimeActive = get-date
$ActiveMiners[$BestNow.IdF].Subminers[$BestNow.Id].TimeSinceStartInterval = [TimeSpan]0
Writelog ("Started System process Id "+[string]($ActiveMiners[$BestNow.IdF].Process.Id)+" for $BestNowLogMsg --> "+$ActiveMiners[$BestNow.IdF].Path+" "+$ActiveMiners[$BestNow.IdF].Arguments) $LogFile $false
}
else {
#Must mantain last miner by switch
$ActiveMiners[$BestLast.IdF].Subminers[$BestLast.Id].best=$true
if ($Profitlast -lt $ProfitNow) {
$ActiveMiners[$BestLast.IdF].Subminers[$BestLast.Id].BestBySwitch= "*"
Writelog ("$BestNowLogMsg continue mining due to @@percenttoswitch value") $LogFile $true
}
}
}
Set_Stats -algorithm $ActiveMiners[$BestNow.IdF].Algorithms -minername $ActiveMiners[$BestNow.IdF].Name -GroupName $ActiveMiners[$BestNow.IdF].GpuGroup.GroupName -AlgoLabel $ActiveMiners[$BestNow.IdF].AlgoLabel -Powerlimit $BestNow.PowerLimit -value $ActiveMiners[$BestNow.IdF].Subminers[$BestNow.Id].StatsHistory
}
ErrorsToLog $LogFile
$FirstLoopExecution=$True
$LoopStarttime=Get-Date