forked from barnstee/UA-CloudPublisher
-
Notifications
You must be signed in to change notification settings - Fork 0
/
StoreForwardPublisher.cs
185 lines (151 loc) · 6.13 KB
/
StoreForwardPublisher.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
namespace Opc.Ua.Cloud.Publisher
{
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using Opc.Ua.Cloud.Publisher.Interfaces;
public class StoreForwardPublisher : IMessagePublisher
{
private IBrokerClient _client;
private readonly ILogger _logger;
private Queue<long> _lastMessageLatencies = new Queue<long>();
private object _lastMessageLatenciesLock = new object();
public StoreForwardPublisher(ILoggerFactory loggerFactory, Settings.BrokerResolver brokerResolver)
{
_logger = loggerFactory.CreateLogger("StoreForwardPublisher");
if (Settings.Instance.UseKafka)
{
_client = brokerResolver("Kafka");
}
else
{
_client = brokerResolver("MQTT");
}
}
public bool SendMetadata(byte[] message)
{
bool success = false;
Stopwatch watch = new Stopwatch();
watch.Start();
try
{
if (_client != null)
{
_client.PublishMetadata(message);
success = true;
Diagnostics.Singleton.Info.SentBytes += message.Length;
Diagnostics.Singleton.Info.SentMessages++;
Diagnostics.Singleton.Info.SentLastTime = DateTime.UtcNow;
}
else
{
_logger.LogError("MQTT client not available for sending message.");
}
}
catch (Exception ex)
{
if (ex is AggregateException)
{
ex = ((AggregateException)ex).Flatten();
}
_logger.LogError(ex, "Error while sending metadata message.");
}
watch.Stop();
lock (_lastMessageLatenciesLock)
{
_lastMessageLatencies.Enqueue(watch.ElapsedMilliseconds);
// calc the average for the last 100 messages
if (_lastMessageLatencies.Count > 100)
{
_lastMessageLatencies.Dequeue();
}
long sum = 0;
foreach (long latency in _lastMessageLatencies)
{
sum += latency;
}
Diagnostics.Singleton.Info.AverageMessageLatency = sum / _lastMessageLatencies.Count;
}
return success;
}
public bool SendMessage(byte[] message)
{
bool success = false;
string pathToStore = Path.Combine(Directory.GetCurrentDirectory(), "store");
if (!Directory.Exists(pathToStore))
{
Directory.CreateDirectory(pathToStore);
}
Stopwatch watch = new Stopwatch();
watch.Start();
try
{
if (_client != null)
{
_client.Publish(message);
success = true;
Diagnostics.Singleton.Info.SentBytes += message.Length;
Diagnostics.Singleton.Info.SentMessages++;
Diagnostics.Singleton.Info.SentLastTime = DateTime.UtcNow;
// check if there are still messages in our store we should also send
string[] filePaths = Directory.GetFiles(pathToStore);
if (filePaths.Length > 0)
{
// send at least 1
_logger.LogInformation("Forwarding stored message to Broker, now that the connection has been re-established...");
try
{
byte[] bytes = File.ReadAllBytes(filePaths[0]);
_client.Publish(bytes);
File.Delete(filePaths[0]);
Diagnostics.Singleton.Info.SentBytes += bytes.Length;
Diagnostics.Singleton.Info.SentMessages++;
Diagnostics.Singleton.Info.FailedMessages--;
Diagnostics.Singleton.Info.SentLastTime = DateTime.UtcNow;
_logger.LogInformation($"There are {filePaths.Length - 1} stored messages left to send.");
}
catch (Exception ex)
{
// do nothing, just try again next time around
_logger.LogError(ex, $"Sending stored message failed, will retry later. There are {filePaths.Length} stored messages left to send.");
}
}
}
else
{
throw new Exception("MQTT client not available for sending message.");
}
}
catch (Exception ex)
{
if (ex is AggregateException)
{
ex = ((AggregateException)ex).Flatten();
}
_logger.LogError(ex, "Error while sending message. Storing locally for later forward...");
Diagnostics.Singleton.Info.FailedMessages++;
File.WriteAllBytes(Path.Combine(pathToStore, Path.GetRandomFileName()), message);
}
watch.Stop();
lock (_lastMessageLatenciesLock)
{
_lastMessageLatencies.Enqueue(watch.ElapsedMilliseconds);
// calc the average for the last 100 messages
if (_lastMessageLatencies.Count > 100)
{
_lastMessageLatencies.Dequeue();
}
long sum = 0;
foreach (long latency in _lastMessageLatencies)
{
sum += latency;
}
Diagnostics.Singleton.Info.AverageMessageLatency = sum / _lastMessageLatencies.Count;
}
return success;
}
}
}