-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPeriodicPoller.cs
More file actions
213 lines (188 loc) · 7.68 KB
/
PeriodicPoller.cs
File metadata and controls
213 lines (188 loc) · 7.68 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
using System.Net;
using System.Timers;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using SolarUseOptimiser.Models.ChargeHQ;
using SolarUseOptimiser.Models.Configuration;
using SolarUseOptimiser.Models.Huawei;
using Timer = System.Timers.Timer;
namespace SolarUseOptimiser
{
public class PeriodicPoller
{
private readonly IConfiguration configuration;
private readonly ILogger<PeriodicPoller> logger;
private bool isStarted = false;
private bool initialised = false;
private int errorCount = 0;
private Timer Timer
{
get; set;
}
private IDataTarget DataTarget
{
get; set;
}
private IDataSource DataSource
{
get; set;
}
private int MaxErrors
{
get; set;
}
private static CancellationTokenSource CancellationTokenSource;
public PeriodicPoller(IConfiguration configuration, IDataSource dataProducer, IDataTarget dataConsumer, ILogger<PeriodicPoller> logger)
{
this.configuration = configuration;
this.DataSource = dataProducer;
this.DataTarget = dataConsumer;
try
{
this.MaxErrors = configuration.GetValue<int>(Constants.MAX_ERRORS);
if (this.MaxErrors == 0)
{
logger.LogError("Failed to read the MaxErrors configuration for how many times to have an error before forcing a restart. Using a default of 2.");
this.MaxErrors = 2;
}
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to read the MaxErrors configuration for how many times to have an error before forcing a restart. Using a default of 2.");
this.MaxErrors = 2;
}
this.logger = logger;
}
/// <summary>
/// <c>InitialiseAsync</c> - Sets up the component for polling the Huawei Fusion Solar API.
/// It will login to the API and read some data objects out that will be used for polling solar production data
/// </summary>
/// <returns>The HuaweiSolarPoller object that was initialised</summary>
public async Task<PeriodicPoller> InitialiseAsync(CancellationTokenSource cancellationTokenSource)
{
if (!initialised)
{
initialised = true;
CancellationTokenSource = cancellationTokenSource;
await DataSource.InitialiseAsync(cancellationTokenSource);
Timer = new Timer(DataSource.PollRate * 60000);
Timer.Enabled = false;
Timer.AutoReset = true;
Timer.Elapsed += PollGenerationStatistics_Elapsed;
}
return this;
}
/// <summary>
/// <c>Start</c> - Starts the poller and does an initial poll immediately.
/// </summary>
internal void Start()
{
if (!isStarted)
{
isStarted = true;
logger.LogInformation("Starting Polling. The interval is every {0}ms.", Timer.Interval);
Timer.Start();
//Do first poll manually
if (DataSource.DeviceCount == 1)
{
PollGenerationStatistics_Elapsed(this, null);
}
}
}
/// <summary>
/// <c>Stop</c> - Stops the poller
/// </summary>
internal void Stop()
{
if (isStarted)
{
Timer.Stop();
CancellationTokenSource.Cancel();
isStarted = false;
}
}
private void PollGenerationStatistics_Elapsed(object sender, ElapsedEventArgs e)
{
try
{
if (!CancellationTokenSource.IsCancellationRequested)
{
SiteMeterPush pushData = null;
int retryCount = 3;
while (!DataSource.IsInitialised)
{
var response = DataSource.Authenticate(CancellationTokenSource).GetAwaiter().GetResult();
if (retryCount > 0)
{
Thread.Sleep(5000);
retryCount--;
}
else
{
pushData = new SiteMeterPush
{
apiKey = DataTarget.UserId,
error = string.Format($"{DataSource.Name} responded with {response.Message}")
};
break;
}
}
if (pushData == null)
{
pushData = DataSource.GetSiteMeterData(DataTarget.UserId, CancellationTokenSource);
}
if (string.IsNullOrWhiteSpace(pushData.error))
{
bool successfullySent = DataTarget.SendData(pushData).GetAwaiter().GetResult();
if (successfullySent)
{
logger.LogDebug("Sent the power data successfully to {0}.", DataTarget.Name);
}
else
{
logger.LogError("Failed to send the power data to {0}.", DataTarget.Name);
}
}
else
{
errorCount++;
bool sentErrorDataSuccess = DataTarget.SendErrorData(pushData).GetAwaiter().GetResult();
if (sentErrorDataSuccess)
{
logger.LogDebug("Sent the error data successfully to {0}.", DataTarget.Name);
}
else
{
logger.LogError("Failed to send the error data to {0}.", DataTarget.Name);
}
if (errorCount >= MaxErrors)
{
logger.LogWarning("The maximum number of errors has occurred and the system is being reset.");
DataSource.Restart(CancellationTokenSource);
errorCount = 0;
}
}
}
}
catch (Exception ex)
{
logger.LogError(ex, "An exception was caught while polling for power data to send to {0}.", DataTarget.Name);
SiteMeterPush pushData = new SiteMeterPush
{
apiKey = DataTarget.UserId,
error = string.Format("An error occurred while polling the {0}", DataSource.Name)
};
bool successfullySent = this.DataTarget.SendErrorData(pushData).GetAwaiter().GetResult();
if (successfullySent)
{
logger.LogDebug("Sent the error data successfully to {0}.", DataTarget.Name);
}
else
{
logger.LogError("Failed to send the error data to {0}.", DataTarget.Name);
}
}
}
}
}