-
Notifications
You must be signed in to change notification settings - Fork 0
/
Switcher.cs
2328 lines (2090 loc) · 99.8 KB
/
Switcher.cs
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
#region Namespaces Used
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Reflection;
using System.IO;
using System.Windows.Forms.DataVisualization.Charting;
using System.Diagnostics;
using System.Globalization;
#endregion
namespace TMB_Switcher
{
public partial class Switcher : Form
{
#region Variables
// Thread and API handles
private static Thread bgThread = null;
private static TMB_API tmbAPI = null;
private static Miner_API minerAPI = null;
// Configuration variables
private static string configFileLocation = "TMBSwitcher.conf";
private static bool verbose = false;
private static bool noAPI = false;
private static Dictionary<string, object> config = null;
private static string profitLogFile = null;
private static string minerName = "sgminer";
// Refresh variables
private static bool refreshPool = true;
private static bool refreshMiner = true;
private static bool refreshSettings = true;
private static DateTime lastPoolRefresh = DateTime.Now;
private static DateTime lastMinerRefresh = DateTime.Now;
private static DateTime lastUpdateCheck = DateTime.Now.AddHours(-1);
// Historical data
private static DataTable poolProfitInfo = null;
private static DataTable minerInfo = null;
private static int profitRowCount = 0;
private static double averageProfit = 0.0;
private static double minProfit = double.NaN;
private static double maxProfit = double.NaN;
private static int graphMovingAveragePoints = 30;
// Tray icon
private static NotifyIcon trayIcon = null;
// State information
private static string currentAlgo = "none";
private static string previousAlgo = "none";
private static MiningState currentState = MiningState.Starting;
private static DateTime lastStartTime = DateTime.Now;
private static DateTime lastSwitch = DateTime.Now;
private static bool switchingAlgorithm = false;
private static string statusFormat = null;
private enum MiningState
{
Stopped,
Paused,
Mining,
Starting
}
// Version information
private static string currentVersionFormat = null;
private static string latestVersionFormat = null;
private static Version lastVersionSeen = null;
private static DataTable algorithms = null;
// Current miner data
private static DataTable poolList = null;
private static int numGPU = 0;
// Chart last X mouse position
private static DataPoint lastProfitHitPoint = null;
private static string lastProfitSeriesName = null;
private static DataPoint lastMinerHitPoint = null;
private static string lastMinerSeriesName = null;
#endregion
#region Initialization
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
Thread.CurrentThread.CurrentUICulture = CultureInfo.InvariantCulture;
if (!parseArguments(args))
{
Application.Exit();
return;
}
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Switcher());
}
public Switcher()
{
InitializeComponent();
// Auto-select None on startup
switchingAlgorithm = true;
currentlyMiningCombo.SelectedIndex = 0;
switchingAlgorithm = false;
statusFormat = Text;
latestVersionFormat = latestVersionLabel.Text;
currentVersionFormat = currentVersionLabel.Text;
trayIcon = new NotifyIcon();
setStatus(Properties.Resources.redIcon, "Starting Up");
trayIcon.Visible = true;
linkLabel.Links[0].LinkData = null;
btcAddress.Links[0].LinkData = null;
ltcAddress.Links[0].LinkData = null;
drkAddress.Links[0].LinkData = null;
if (noAPI)
{
tabControl.TabPages.Remove(poolsPage);
tabControl.TabPages.Remove(devicesPage);
tabControl.TabPages.Remove(minerHistoryPage);
minerAddressText.Enabled = false;
minerPortText.Enabled = false;
batchFileButton.Enabled = false;
batchFileText.Enabled = false;
}
}
private void Switcher_Load(object sender, EventArgs e)
{
try
{
// Setup basic algorithm information
algorithms = new DataTable();
DataColumn name = algorithms.Columns.Add("name", typeof(string));
algorithms.Columns.Add("displayName", typeof(string));
algorithms.Columns.Add("type", typeof(string));
algorithms.Columns.Add("kernels", typeof(string));
algorithms.PrimaryKey = new DataColumn[] { name };
// Populate list of algorithms
algorithms.Rows.Add("scrypt", "Scrypt", "Scrypt", "*");
algorithms.Rows.Add("nscrypt", "N-Scrypt", "NScrypt", "");
algorithms.Rows.Add("x11", "X11", "X11", "darkcoin,x11");
algorithms.Rows.Add("x13", "X13", "X13", "marucoin,x13");
algorithms.Rows.Add("x15", "X15", "X15", "bitblock,x15");
algorithms.Rows.Add("nist5", "NIST5", "NIST", "talkcoin,nist");
//algorithms.Rows.Add("keccak", "Keccak", "Keccak", "maxcoin,keccak");
// Extra algorithm information
algorithms.Columns.Add("enabled", typeof(bool));
algorithms.Columns.Add("graphCheckbox", typeof(CheckBox));
algorithms.Columns.Add("settingCheckbox", typeof(CheckBox));
algorithms.Columns.Add("multiplierTextbox", typeof(TextBox));
algorithms.Columns.Add("offsetTextbox", typeof(TextBox));
algorithms.Columns.Add("batchTextbox", typeof(TextBox));
algorithms.Columns.Add("batchButton", typeof(Button));
// Set up profit table and generate per-algorithm controls
poolProfitInfo = new DataTable();
poolProfitInfo.Columns.Add("time", typeof(DateTime));
poolProfitInfo.Columns.Add("composite", typeof(double));
int i = 1;
foreach (DataRow algorithm in algorithms.Rows)
{
poolProfitInfo.Columns.Add(algorithm["name"].ToString(), typeof(double));
string displayName = algorithm["displayName"].ToString();
currentlyMiningCombo.Items.Add(displayName);
// Generate profit graph checkbox
CheckBox checkbox = new CheckBox();
algorithm["graphCheckBox"] = checkbox;
checkbox.Text = displayName;
checkbox.CheckedChanged += graphCheckbox_CheckedChanged;
profitFlowLayoutPanel.Controls.Add(checkbox);
checkbox.Tag = algorithm;
checkbox.AutoSize = true;
settingTableLayoutPanel.RowCount++;
// Generate setting checkbox
checkbox = new CheckBox();
algorithm["settingCheckbox"] = checkbox;
checkbox.Text = displayName + ":";
tooltip.SetToolTip(checkbox, String.Format("Whether mining of {0} is enabled or not", displayName));
settingTableLayoutPanel.Controls.Add(checkbox, 0, i);
checkbox.Anchor = AnchorStyles.Left | AnchorStyles.Top;
checkbox.AutoSize = true;
// Generate multiplier textbox
TextBox textbox = new TextBox();
algorithm["multiplierTextbox"] = textbox;
textbox.Text = "1.0";
tooltip.SetToolTip(textbox, String.Format("Multiplier applied to {0} profitability (applied before offset)", displayName));
settingTableLayoutPanel.Controls.Add(textbox, 1, i);
textbox.Dock = DockStyle.Fill;
// Generate offset textbox
textbox = new TextBox();
algorithm["offsetTextbox"] = textbox;
textbox.Text = "0.0";
tooltip.SetToolTip(textbox, String.Format("Offset applied to {0} profitability (applied after multiplier)", displayName));
settingTableLayoutPanel.Controls.Add(textbox, 2, i);
textbox.Dock = DockStyle.Fill;
// Generate batch textbox
textbox = new TextBox();
algorithm["batchTextbox"] = textbox;
tooltip.SetToolTip(textbox, String.Format("Location of the batch file used to start up the {0} miner (if not using sgminer v5.0)", displayName));
settingTableLayoutPanel.Controls.Add(textbox, 3, i);
textbox.Dock = DockStyle.Fill;
// Generate batch button
Button button = new Button();
algorithm["batchButton"] = button;
button.Text = "...";
button.Click += batchButton_Click;
tooltip.SetToolTip(button, String.Format("Select the batch file used to start up the {0} miner (if not using sgminer v5.0)", displayName));
settingTableLayoutPanel.Controls.Add(button, 4, i);
button.Tag = algorithm;
button.Anchor = AnchorStyles.Left | AnchorStyles.Top;
button.AutoSize = true;
i++;
}
// Read config file
readConfigFile();
// Set up miner table
minerInfo = new DataTable();
minerInfo.Columns.Add("time", typeof(DateTime));
minerInfo.Columns.Add("totalHash", typeof(double));
// Per GPU temp and hashrate columns added later
setupCharts();
bgThread = new Thread(new ThreadStart(backgroundThread));
bgThread.IsBackground = true;
bgThread.Start();
}
catch (Exception ex)
{
// Log failure
Utilities.WriteLog(ex.Message);
Utilities.WriteLog(ex.StackTrace);
if (verbose)
MessageBox.Show(ex.Message + "\n\n" + ex.StackTrace);
}
}
private void setupCharts()
{
profitChart.DataSource = poolProfitInfo;
foreach (DataRow algorithm in algorithms.Rows)
{
string algorithmName = algorithm["name"].ToString();
Series series = profitChart.Series.Add(algorithmName);
series.XValueMember = "time";
series.YValueMembers = algorithmName;
series.XValueType = ChartValueType.DateTime;
series.YValueType = ChartValueType.Double;
series.Enabled = false;
}
Series compositeSeries = profitChart.Series.Add("composite");
compositeSeries.XValueMember = "time";
compositeSeries.YValueMembers = "composite";
compositeSeries.XValueType = ChartValueType.DateTime;
compositeSeries.YValueType = ChartValueType.Double;
compositeSeries.Enabled = false;
profitChart.ChartAreas[0].AxisX.LabelStyle.Format = "dd/MM/yyyy\nhh:mm:ss";
minerChart.DataSource = minerInfo;
minerChart.ChartAreas[0].AxisX.LabelStyle.Format = "dd/MM/yyyy\nhh:mm:ss";
}
private static bool parseArguments(string[] args)
{
for (int i = 0; i < args.Length; i++)
{
switch (args[i])
{
case "-h":
case "--help":
case "/?":
printUsage();
return false;
case "-c":
case "--config":
if (args.Length <= i + 1 || args[i + 1][0] == '-' || args[i + 1][0] == '/')
{
Console.Out.WriteLine("Missing argument for -c.\n");
printUsage();
return false;
}
configFileLocation = args[++i].Trim('"');
break;
case "-v":
case "-verbose":
verbose = true;
break;
case "-n":
case "--no-api":
noAPI = true;
break;
default:
Console.Out.WriteLine("Bad argument: " + args[i] + "\n");
printUsage();
return false;
}
}
return true;
}
private static void printUsage()
{
StringBuilder usage = new StringBuilder();
usage.Append("TMB Switcher Version: ");
usage.AppendLine(Assembly.GetEntryAssembly().GetName().Version.ToString());
usage.AppendLine("\n\nArguments:");
usage.AppendLine(" -h,--help\tThis help message.");
usage.AppendLine(" -c,--config\tThe location of the config file. (Default: TMBSwitcher.conf)");
usage.AppendLine(" -n,--no-api\tUsed for miners that don't expose an API (i.e. cudaminer/ccminer)");
usage.AppendLine(" -v,--verbose\tDisplays verbose usage information (do not use this unattended as it will lock up the switcher)");
MessageBox.Show(usage.ToString());
}
private void Switcher_FormClosing(object sender, FormClosingEventArgs e)
{
// Check if the user wished to exit
if (MessageBox.Show("Are you sure you want to close TMB Switcher?", this.Text, MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.No)
{
e.Cancel = true;
return;
}
// Kill miner on exit if told to do so
if (config.GetBool("killMinerOnExit"))
killMiner();
// Kill background thread and wait for it to exit
bgThread.Abort();
bgThread.Join(1000);
trayIcon.Visible = false;
}
#endregion
#region Background Thread
private void backgroundThread()
{
Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
Thread.CurrentThread.CurrentUICulture = CultureInfo.InvariantCulture;
while (true)
{
try
{
DateTime currentTime = DateTime.Now;
if (lastUpdateCheck.AddHours(1) < currentTime)
{
Invoke(new MethodInvoker(delegate { checkForUpdate(); }));
lastUpdateCheck = currentTime;
}
// If user has changed any settings and applied them then we need to
// update our pool and miner connectivity
Invoke(new MethodInvoker(delegate { updateSettings(); }));
// If both miner and pool API are not connected update stats and go back to sleep
if (minerAPI == null && tmbAPI == null)
{
setStatus(Properties.Resources.redIcon, "APIs Disconnected");
clearMinerStats();
clearPoolStats();
Thread.Sleep(1000);
continue;
}
if (minerAPI != null || noAPI)
{
// Figure out if we want to auto-update the miner stats
double minerRefreshRate = config.GetDouble("minerRefreshRate");
if (config.GetBool("monitorMiner") && lastMinerRefresh.AddSeconds(minerRefreshRate) < currentTime)
{
refreshMiner = true;
lastMinerRefresh = currentTime;
}
// Need to verify miner is active before attempting any switching
if (refreshMiner)
{
if (noAPI)
{
Miner_API.IsActive = currentState == MiningState.Stopped || minerRunning();
// Switch to mining state if starting and process is alive
if (currentState == MiningState.Starting && Miner_API.IsActive)
currentState = MiningState.Mining;
// Check if miner is running and if necessary restart it
if (!Miner_API.IsActive)
{
// Give the miner X seconds to get started before trying to restart it (default 30)
int startupDeadDelay = config.GetInt("startupDeadDelay");
if (startupDeadDelay < 0)
startupDeadDelay = 30;
if (currentState != MiningState.Starting || DateTime.Now > lastStartTime.AddSeconds(startupDeadDelay))
{
// If we don't want to mine anything then don't restart the miner
// (unless we want to start mining which is handled later)
if (currentAlgo == "none" || currentAlgo == "off")
Miner_API.IsActive = true;
else
{
// Kill existing miner in case it was just having temporary issues
// so it doesn't get in the way of the newly started miner
string batchFile = config.GetString(currentAlgo + "Batch");
if (!string.IsNullOrEmpty(batchFile) && File.Exists(batchFile))
{
killMiner();
startMiner(batchFile);
}
}
}
}
}
else
{
// Gather and store miner info
poolList = minerAPI.pools();
Dictionary<string, double> summary = minerAPI.summary();
DataTable deviceList = minerAPI.devices();
// Update table with miner info
Invoke(new MethodInvoker(delegate { updateMinerInfo(deviceList); }));
Invoke(new MethodInvoker(delegate { updateMinerUI(summary, deviceList); }));
}
refreshMiner = false;
}
}
if (tmbAPI != null)
{
// Figure out if we want to auto-update the pool stats
double poolRefreshRate = config.GetDouble("poolRefreshRate");
if (config.GetBool("monitorPool") && lastPoolRefresh.AddSeconds(poolRefreshRate) < currentTime)
{
refreshPool = true;
lastPoolRefresh = currentTime;
}
if (refreshPool)
{
// Get pool hash info for display and add it to history
Dictionary<string, double> hashInfo = tmbAPI.hashInfo();
// Get balance data for display
Dictionary<string, double> balanceInfo = tmbAPI.balance();
// Get profit info for switching/logging/display
Dictionary<string, double> profitInfo = tmbAPI.bestAlgo();
if (profitInfo != null)
{
adjustProfit(profitInfo);
if (config.GetBool("enableProfitSwitching") && Miner_API.IsActive &&
((minerAPI != null && poolList != null && poolList.Rows.Count > 0) || noAPI) &&
(currentState == MiningState.Mining || currentState == MiningState.Starting))
{
if (currentState == MiningState.Starting)
currentState = MiningState.Mining;
// Figure out if we need to switch
string bestAlgo = checkProfit(profitInfo);
if (bestAlgo != "none" && bestAlgo != currentAlgo)
{
// Perform Switch
switchAlgorithm(bestAlgo);
}
}
// Add composite value to profit info
double compositeValue = 0.0;
if (currentAlgo != "none" && currentAlgo != "off")
compositeValue = profitInfo[currentAlgo];
profitInfo.Add("composite", compositeValue);
// Update log with profit info
if (!string.IsNullOrEmpty(profitLogFile))
Utilities.WriteProfitLog(profitInfo, profitLogFile);
// Add profit info to history
Utilities.AddToTable(profitInfo, poolProfitInfo);
// Delete any rows older than 24 hours to keep memory usage lower
Utilities.DeleteOlderThan24H(poolProfitInfo);
}
// Update UI with pool info
Invoke(new MethodInvoker(delegate { updatePoolUI(poolProfitInfo, hashInfo, balanceInfo); }));
refreshPool = false;
}
}
// Show status in the HMI
Invoke(new MethodInvoker(delegate { setHMIStatus(); }));
}
catch (Exception ex)
{
// Log failure
Utilities.WriteLog(ex.Message);
Utilities.WriteLog(ex.StackTrace);
if (verbose)
MessageBox.Show(ex.Message + "\n\n" + ex.StackTrace);
}
// Sleep for a second since the user can request a refresh at any time
Thread.Sleep(1000);
}
}
#endregion
#region HMI Update Methods
private void setHMIStatus()
{
if (!TMB_API.IsActive && !Miner_API.IsActive)
setStatus(Properties.Resources.redIcon, "APIs Disconnected");
else if (!Miner_API.IsActive)
setStatus(Properties.Resources.redIcon, "Miner Disconnected");
else if (!TMB_API.IsActive)
setStatus(Properties.Resources.redIcon, "Pool Disconnected");
else if (currentState == MiningState.Stopped)
setStatus(Properties.Resources.redIcon, "Mining Stopped");
else if (currentState == MiningState.Paused)
setStatus(Properties.Resources.redIcon, "Mining Paused");
else if (currentState == MiningState.Starting)
setStatus(Properties.Resources.redIcon, "Starting Miner");
else if (currentAlgo == "off" || currentAlgo == "none")
setStatus(Properties.Resources.redIcon, "Not Mining");
else
setStatus(Properties.Resources.greenIcon, "Mining " + mapInternalToDisplay(currentAlgo));
setStatusButtons();
}
private string mapInternalToDisplay(string algorithm)
{
DataRow row = algorithms.Rows.Find(algorithm);
if (row == null)
return "None";
else
return row["displayName"].ToString();
}
private void checkForUpdate()
{
Version currentVersion = Assembly.GetEntryAssembly().GetName().Version;
currentVersionLabel.Text = string.Format(currentVersionFormat, currentVersion);
string updateMessage = null;
Version latestVersion = Utilities.getLatestVersion(out updateMessage);
if (latestVersion != null)
{
latestVersionLabel.Text = string.Format(latestVersionFormat, latestVersion);
versionMessage.Text = updateMessage;
if (latestVersion > currentVersion && lastVersionSeen != latestVersion)
{
lastVersionSeen = latestVersion;
trayIcon.ShowBalloonTip(2000, "New Version Available", string.Format("Version {0} is now available", latestVersion), ToolTipIcon.Info);
}
}
else
{
latestVersionLabel.Text = string.Format(latestVersionFormat, "Could not find latest version");
}
}
private void updateMinerUI(Dictionary<string, double> summary, DataTable deviceList)
{
if (poolList != null)
{
// Reload pool list making sure that it refreshes without the user noticing
int selectedRow = -1;
if (poolView.SelectedRows.Count > 0)
selectedRow = poolView.SelectedRows[0].Index;
int horizScroll = poolView.HorizontalScrollingOffset;
int vertScroll = poolView.FirstDisplayedScrollingRowIndex;
poolView.DataSource = poolList;
// Hide unnecessary columns
// Sort by priority so that when user changes priority they sort appropriately
foreach (DataGridViewColumn col in poolView.Columns)
{
switch (col.Name.ToLowerInvariant())
{
case "pool":
case "url":
case "status":
case "user":
case "algorithm":
case "name":
col.Visible = true;
col.SortMode = DataGridViewColumnSortMode.NotSortable;
break;
case "priority":
col.Visible = true;
col.SortMode = DataGridViewColumnSortMode.Programmatic;
poolView.Sort(col, ListSortDirection.Ascending);
break;
default:
col.Visible = false;
break;
}
}
if (selectedRow >= 0 && selectedRow < poolView.Rows.Count)
poolView.Rows[selectedRow].Selected = true;
poolView.HorizontalScrollingOffset = horizScroll;
if (vertScroll >= 0)
poolView.FirstDisplayedScrollingRowIndex = vertScroll;
// Find last pool that had a share submitted and isn't disabled
// Not perfect detection but other methods don't seem reliable
DataRow currentPoolRow = null;
int lastShareTime = -1;
foreach (DataRow row in poolList.Rows)
{
int rowLastShare = Convert.ToInt32(row["Last Share Time"]);
if (rowLastShare > lastShareTime &&
!string.Equals(row["status"].ToString(), "disabled", StringComparison.InvariantCultureIgnoreCase))
{
lastShareTime = rowLastShare;
currentPoolRow = row;
}
}
if (currentPoolRow != null)
{
// Only sgminer 5.0 supports Name
string currentPool = null;
if (poolList.Columns.Contains("Name"))
currentPool = currentPoolRow["Name"].ToString();
else
currentPool = currentPoolRow["URL"].ToString();
currentPoolAtText.Text = currentPool;
currentPoolText.Text = currentPool;
currentAlgo = detectAlgo(currentPoolRow, currentAlgo);
}
else
{
currentPoolAtText.Text = "None";
currentPoolText.Text = "None";
}
// Update currently mining info
switchingAlgorithm = true;
currentlyMiningCombo.Text = mapInternalToDisplay(currentAlgo);
switchingAlgorithm = false;
}
if (summary != null)
{
currentHashrateText.Text = Utilities.formatHashSpeed(summary["KHS 5s"], Utilities.hashUnits.Kh);
averageHashrateText.Text = Utilities.formatHashSpeed(summary["KHS av"], Utilities.hashUnits.Kh);
string adpFormatString = "{0} {1} ({2}%)";
acceptedText.Text = string.Format("{0} {1}", summary["Accepted"], summary["Difficulty Accepted"]);
rejectedText.Text = string.Format(adpFormatString, summary["Rejected"], summary["Difficulty Rejected"], summary["Pool Rejected%"]);
staleText.Text = string.Format(adpFormatString, summary["Stale"], summary["Difficulty Stale"], summary["Pool Stale%"]);
hardwareErrorText.Text = string.Format("{0} ({1}%)", summary["Hardware Errors"], summary["Device Hardware%"]);
workUtilityText.Text = summary["Work Utility"].ToString() + " / " + summary["Utility"].ToString();
getworkText.Text = summary["Getworks"].ToString();
getworkFailureText.Text = summary["Get Failures"].ToString();
remoteFailureText.Text = summary["Remote Failures"].ToString();
foundBlocksText.Text = summary["Found Blocks"].ToString();
bestShareText.Text = summary["Best Share"].ToString();
}
if (deviceList != null)
{
// Reload pool list making sure that it refreshes without the user noticing
int selectedRow = -1;
if (deviceView.SelectedRows.Count > 0)
selectedRow = deviceView.SelectedRows[0].Index;
int horizScroll = deviceView.HorizontalScrollingOffset;
int vertScroll = deviceView.FirstDisplayedScrollingRowIndex;
deviceView.DataSource = deviceList;
// Hide unnecessary columns
// Sort by ID so that they appear in the correct order
foreach (DataGridViewColumn col in deviceView.Columns)
{
switch (col.Name.ToLowerInvariant())
{
case "model":
case "khs 5s":
case "temperature":
case "gpu clock":
case "fan speed":
case "device rejected%":
case "memory clock":
case "hardware errors":
case "status":
case "utility":
col.Visible = true;
col.SortMode = DataGridViewColumnSortMode.NotSortable;
break;
case "gpu":
col.Visible = true;
col.SortMode = DataGridViewColumnSortMode.Programmatic;
deviceView.Sort(col, ListSortDirection.Ascending);
break;
default:
col.Visible = false;
break;
}
}
if (selectedRow >= 0 && selectedRow < deviceView.Rows.Count)
deviceView.Rows[selectedRow].Selected = true;
deviceView.HorizontalScrollingOffset = horizScroll;
if (vertScroll >= 0)
deviceView.FirstDisplayedScrollingRowIndex = vertScroll;
}
// If all three API commands failed it's likely that the miner is dead
// We want to restart it unless the miner is stopped
if (poolList == null && summary == null && deviceList == null &&
currentState != MiningState.Stopped)
{
// Give the miner X seconds to get started before trying to restart it (default 30)
int startupDeadDelay = config.GetInt("startupDeadDelay");
if (startupDeadDelay < 0)
startupDeadDelay = 30;
if (currentState != MiningState.Starting || DateTime.Now > lastStartTime.AddSeconds(startupDeadDelay))
{
// Kill existing miner in case it was just having temporary issues
// so it doesn't get in the way of the newly started miner
string batchFile = config.GetString(currentAlgo + "Batch");
if (string.IsNullOrEmpty(batchFile) && !noAPI)
batchFile = config.GetString("batchFile");
if (!string.IsNullOrEmpty(batchFile) && File.Exists(batchFile))
{
killMiner();
startMiner(batchFile);
}
}
}
// Only show the selected period of history instead of all 24 hours
StringBuilder origSeries = new StringBuilder();
StringBuilder tempSeries = new StringBuilder();
StringBuilder newSeries = new StringBuilder();
foreach (DataColumn col in minerInfo.Columns)
{
if (col.Caption == "time")
continue;
origSeries.Append(col.Caption);
origSeries.Append(',');
newSeries.AppendFormat("filtered{0},", col.Caption);
tempSeries.AppendFormat("temp{0},", col.Caption);
}
origSeries.Length = origSeries.Length - 1;
tempSeries.Length = tempSeries.Length - 1;
newSeries.Length = newSeries.Length - 1;
string tempSeriesString = tempSeries.ToString();
minerChart.DataManipulator.Filter(CompareMethod.LessThan, DateTime.Now.AddHours(minerHistoryBar.LeftValue - 24).ToOADate(), origSeries.ToString(), tempSeriesString, "X");
minerChart.DataManipulator.Filter(CompareMethod.MoreThan, DateTime.Now.AddHours(minerHistoryBar.RightValue - 24).ToOADate(), tempSeriesString, newSeries.ToString(), "X");
foreach (DataColumn col in minerInfo.Columns)
{
if (col.Caption == "time")
continue;
Series series = minerChart.Series["filtered" + col.Caption];
StringBuilder seriesText = new StringBuilder(col.Caption);
if (seriesText[0] == 'G')
seriesText.Insert(3, ' ');
else if (seriesText[0] == 't')
seriesText[0] = 'T';
seriesText.Insert(seriesText.Length - 4, ' ');
// Allow user to disable total hash, GPU hash or GPU temp
bool enabled = false;
if (col.Caption == "totalHash")
enabled = graphTotalCheck.Checked;
else if (col.Caption.Contains("Hash"))
enabled = graphHashCheck.Checked;
else
enabled = graphTempCheck.Checked;
formatSeries(series, seriesText.ToString(), enabled, 4, 2);
// Put temperature on the second axis
if (seriesText[seriesText.Length - 4] == 'T')
series.YAxisType = AxisType.Secondary;
minerChart.Series["temp" + col.Caption].Enabled = false;
}
minerChart.DataBind();
}
private void updatePoolUI(DataTable profit, Dictionary<string, double> hashInfo, Dictionary<string, double> balanceInfo)
{
// Profit-related information
if (profit.Rows.Count > 0 && currentAlgo != "none" && currentAlgo != "off")
{
double currentProfit = Convert.ToDouble(profit.Rows[profit.Rows.Count - 1][currentAlgo]);
currentProfitText.Text = Utilities.formatProfit(currentProfit);
if (double.IsNaN(minProfit) || minProfit > currentProfit)
{
minProfit = currentProfit;
lowProfitText.Text = Utilities.formatProfit(minProfit);
}
if (double.IsNaN(maxProfit) || maxProfit < currentProfit)
{
maxProfit = currentProfit;
highProfitText.Text = Utilities.formatProfit(maxProfit);
}
averageProfit = ((averageProfit * profitRowCount) + currentProfit) / (profitRowCount + 1);
profitRowCount++;
averageProfitText.Text = Utilities.formatProfit(averageProfit);
}
// Only show the selected period of history instead of all 24 hours
StringBuilder origSeries = new StringBuilder("composite");
StringBuilder tempSeries = new StringBuilder("tempcomposite");
StringBuilder newSeries = new StringBuilder("filteredcomposite");
foreach (DataRow algorithm in algorithms.Rows)
{
string algorithmName = algorithm["name"].ToString();
origSeries.Append(',');
origSeries.Append(algorithmName);
newSeries.AppendFormat(",filtered{0}", algorithmName);
tempSeries.AppendFormat(",temp{0}", algorithmName);
}
string tempSeriesString = tempSeries.ToString();
profitChart.DataManipulator.Filter(CompareMethod.LessThan, DateTime.Now.AddHours(profitHistoryBar.LeftValue - 24).ToOADate(), origSeries.ToString(), tempSeriesString, "X");
profitChart.DataManipulator.Filter(CompareMethod.MoreThan, DateTime.Now.AddHours(profitHistoryBar.RightValue - 24).ToOADate(), tempSeriesString, newSeries.ToString(), "X");
Series compositeSeries = profitChart.Series["filteredcomposite"];
formatSeries(compositeSeries, "Your Profit", graphCompositeCheck.Checked, 6, 3);
profitChart.Series["tempcomposite"].Enabled = false;
// Set up the moving average (requires copying some data to force alignment)
if (compositeSeries.Points.Count > 0)
{
int points = Math.Min(graphMovingAveragePoints, compositeSeries.Points.Count);
compositeSeries = profitChart.Series.FindByName("MA");
if (compositeSeries == null)
compositeSeries = profitChart.Series.Add("MA");
for (int i = 0; i < points; i++)
compositeSeries.Points.AddXY(profitChart.Series["filteredcomposite"].Points[i].XValue, profitChart.Series["filteredcomposite"].Points[i].YValues[0]);
profitChart.DataManipulator.FinancialFormula(FinancialFormula.ExponentialMovingAverage, points.ToString(), "filteredcomposite", "MA");
formatSeries(compositeSeries, "Average Profit", graphAverageCheck.Checked, 6, 3);
}
foreach (DataRow algorithm in algorithms.Rows)
{
Series series = profitChart.Series["filtered" + algorithm["name"].ToString()];
formatSeries(series, algorithm["displayName"].ToString(), ((CheckBox)algorithm["graphCheckbox"]).Checked, 4, 2);
profitChart.Series["temp" + algorithm["name"].ToString()].Enabled = false;
}
profitChart.DataBind();
// Pool hash and pool-side user hash rate
if (hashInfo != null)
{
poolHashText.Text = Utilities.formatHashSpeed(hashInfo["pool_hash"], Utilities.hashUnits.h);
userHashText.Text = Utilities.formatHashSpeed(hashInfo["user_hash"], Utilities.hashUnits.h);
}
// Autoexchange and coin-related balances
if (balanceInfo != null)
{
DataTable coinList = new DataTable();
coinList.Columns.Add("Coin Name");
coinList.Columns.Add("Confirmed", typeof(double));
coinList.Columns.Add("Unconfirmed", typeof(double));
foreach (string key in balanceInfo.Keys)
{
double value = balanceInfo[key];
switch (key)
{
case "est_total":
totalText.Text = Utilities.formatProfit(value);
break;
case "unexchanged":
unexchangedText.Text = Utilities.formatProfit(value);
break;
case "exchanged":
exchangedText.Text = Utilities.formatProfit(value);
break;
case "alltime":
allTimeText.Text = Utilities.formatProfit(value);
break;
default:
if (key.EndsWith("-Confirmed"))
{
string coinName = key.Substring(0, key.Length - 10);
double unconfirmed = balanceInfo[coinName + "-Unconfirmed"];
if (filterBalancesCheck.Checked && value == 0.0 && unconfirmed == 0.0)
continue;
DataRow row = coinList.NewRow();
row[0] = coinName;
row[1] = value;
row[2] = unconfirmed;
coinList.Rows.Add(row);
}
break;
}
}
// Reload balance list making sure that it refreshes without the user noticing
int selectedRow = -1;
if (coinView.SelectedRows.Count > 0)
selectedRow = coinView.SelectedRows[0].Index;
int horizScroll = coinView.HorizontalScrollingOffset;
string sortColumn = null;
if (coinView.SortedColumn != null)
sortColumn = coinView.SortedColumn.Name;
SortOrder sortOrder = coinView.SortOrder;
int vertScroll = coinView.FirstDisplayedScrollingRowIndex;
coinView.DataSource = coinList;
if (sortColumn != null)
{
coinView.Sort(coinView.Columns[sortColumn],
sortOrder == SortOrder.Ascending ? ListSortDirection.Ascending : ListSortDirection.Descending);
}
if (selectedRow >= 0 && selectedRow < coinView.Rows.Count)
coinView.Rows[selectedRow].Selected = true;
coinView.HorizontalScrollingOffset = horizScroll;
if (vertScroll >= 0)
coinView.FirstDisplayedScrollingRowIndex = vertScroll;
}
// Update currently mining info here as we could have switched
switchingAlgorithm = true;
currentlyMiningCombo.Text = mapInternalToDisplay(currentAlgo);
switchingAlgorithm = false;
}
private void formatSeries(Series series, string displayName, bool enabled, int markerSize, int borderWidth)
{
series.LegendText = displayName;
series.XValueType = ChartValueType.DateTime;
series.YValueType = ChartValueType.Double;
series.ChartType = SeriesChartType.Line;
series.Enabled = enabled;
series.BorderWidth = borderWidth;
series.MarkerStyle = MarkerStyle.Circle;
series.MarkerSize = markerSize;
series.MarkerStep = 1;
}
private void clearMinerStats()
{
// Miner info
string blank = "--";
currentHashrateText.Text = blank;
averageHashrateText.Text = blank;
workUtilityText.Text = blank;
hardwareErrorText.Text = blank;
acceptedText.Text = blank;
getworkText.Text = blank;
rejectedText.Text = blank;
getworkFailureText.Text = blank;
bestShareText.Text = blank;
remoteFailureText.Text = blank;
foundBlocksText.Text = blank;
staleText.Text = blank;
}
private void clearPoolStats()
{
// Pool info
string blank = "--";
currentProfitText.Text = blank;
averageProfitText.Text = blank;
highProfitText.Text = blank;
lowProfitText.Text = blank;
userHashText.Text = blank;