Skip to content

Commit f17f298

Browse files
authored
Merge pull request #5 from CorefluxCommunity/worker_cleanUp
Worker refactored.
2 parents 647c050 + dbc69b2 commit f17f298

File tree

1 file changed

+34
-43
lines changed

1 file changed

+34
-43
lines changed

ClientSampleBackgroundService/Worker.cs

Lines changed: 34 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -1,60 +1,47 @@
1+
using Coreflux.API.Networking.MQTT;
12
using Microsoft.Extensions.Hosting;
23
using Microsoft.Extensions.Logging;
34
using System;
4-
using System.Collections.Generic;
5-
using System.Linq;
65
using System.Threading;
76
using System.Threading.Tasks;
8-
using Coreflux.API.Networking.MQTT;
97

108
namespace ClientSampleBackgroundService
119
{
1210
public class Worker : BackgroundService
1311
{
1412
private bool AlreadyConnectedOneTime;
1513
private readonly ILogger<Worker> _logger;
16-
private MQTTControllerInstance MQTTControllerInstance;
14+
private MQTTControllerInstance mqttInstance;
1715
public bool isConnected;
18-
public int Teste;
19-
public Coreflux.API.Client API = new Coreflux.API.Client("localhost", Coreflux.API.Client.Version.LegacyHTTPS);
2016
public Worker(ILogger<Worker> logger)
2117
{
2218
_logger = logger;
23-
MQTTControllerInstance = new MQTTControllerInstance();
24-
25-
MQTTControllerInstance.OnConnect += MQTTController_OnConnect;
26-
MQTTControllerInstance.OnDisconnect += MQTTController_OnDisconnect;
27-
MQTTControllerInstance.NewPayload += MQTTController_NewPayload;
28-
MQTTControllerInstance.PersistentConnection = true;
19+
mqttInstance = new MQTTControllerInstance();
20+
mqttInstance.OnConnect += MQTTController_OnConnect;
21+
mqttInstance.OnDisconnect += MQTTController_OnDisconnect;
22+
mqttInstance.NewPayload += MQTTController_NewPayload;
23+
mqttInstance.PersistentConnection = true;
2924
AlreadyConnectedOneTime = false;
3025
isConnected = false;
3126
}
3227

3328

3429
private void MQTTController_NewPayload(MQTTNewPayload obj)
3530
{
36-
_logger.LogInformation("received" + obj.topic + " , " + obj.payload + " @ {time} ", DateTimeOffset.Now);
31+
_logger.LogInformation(string.Format("Message received on topic {0} , paylod: {1} @ Time: {2}"), obj.topic, obj.payload, DateTimeOffset.Now);
3732
}
3833

3934
private void MQTTController_OnDisconnect()
4035
{
41-
42-
// MQTTController.StartAsync("127.0.0.1", timeOut: 5, keepAlive: 1).Wait();
43-
_logger.LogInformation("Disconnected of broker {time}", DateTimeOffset.Now);
36+
_logger.LogInformation(string.Format("Disconnected of broker {0}", DateTimeOffset.Now));
4437
isConnected = false;
45-
// ReConnect();
46-
4738
}
4839

4940
private void MQTTController_OnConnect()
5041
{
51-
_logger.LogInformation("Connected to broker {time}", DateTimeOffset.Now);
52-
if (!AlreadyConnectedOneTime)
53-
{
54-
42+
_logger.LogInformation(string.Format("Connected to broker {0}", DateTimeOffset.Now));
43+
if (!AlreadyConnectedOneTime)
5544
_logger.LogInformation("Get inside MQTT_Controller");
56-
57-
}
5845
AlreadyConnectedOneTime = true;
5946
isConnected = true;
6047
}
@@ -63,56 +50,60 @@ private async void ReConnect()
6350
{
6451
try
6552
{
66-
await MQTTControllerInstance.StartAsync("127.0.0.1", timeOut: 5, keepAlive: 1);
53+
await mqttInstance.StartAsync("127.0.0.1", timeOut: 5, keepAlive: 1);
6754
}
68-
catch
55+
catch (Exception ex)
6956
{
70-
_logger.LogInformation("Failed to find the broker {time}", DateTimeOffset.Now);
57+
_logger.LogInformation(string.Format("Failed to find the broker {0}. Exception: {1}", DateTimeOffset.Now, ex.ToString()));
7158
}
7259
}
7360

7461

7562
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
7663
{
77-
try
78-
{
79-
MQTTControllerInstance.ClientName = "Test";
80-
await MQTTControllerInstance.StartAsync("127.0.0.1", port: 1883, timeOut: 5, keepAlive: 5, mqttSecure: false);
81-
}
82-
catch
83-
{
84-
_logger.LogInformation("Failed to find the broker {time}", DateTimeOffset.Now);
85-
}
64+
await ConnectToBroker();
65+
8666
while (!stoppingToken.IsCancellationRequested)
8767
{
8868
if (isConnected)
8969
{
9070
//Get the last value of the topic received
91-
var t = MQTTControllerInstance.GetDataAsync("CF/GetTest").GetAwaiter();
71+
var t = mqttInstance.GetDataAsync("CF/GetTest").GetAwaiter();
9272
_logger.LogInformation("Was able to subscribe CF/GetTest with {string} ", t.GetResult());
9373
Task.Delay(100).Wait();
9474
//Set the new value of topic CF/Test
95-
var t1 = MQTTControllerInstance.SetDataAsync("CF/Test", "test", qoslevel: 1);
75+
var t1 = mqttInstance.SetDataAsync("CF/Test", "test", qoslevel: 1);
9676
t1.Wait(100);
9777
var result = t1.GetAwaiter().GetResult();
9878
if (result != null)
9979
{
10080
if (result.ReasonFeedback == MQTTPublishFeedback.FeedbackType.PublishSucess)
10181
{
102-
_logger.LogInformation("Was able to publish CF/Test by publish sucess @ {time} ", DateTimeOffset.Now);
82+
_logger.LogInformation(string.Format("Message publish to CF/Test with success @ {0} ", DateTimeOffset.Now));
10383
}
10484
else
10585
{
106-
_logger.LogInformation("Failed to publish CF/Test by publish failed @ {time} ", DateTimeOffset.Now);
86+
_logger.LogInformation(string.Format("Failed to publish message to CF/Test @ {0} ", DateTimeOffset.Now));
10787
}
10888
}
10989
}
11090
else
11191
{
112-
_logger.LogInformation("Failed to publish CF/Test by null @ {time} ", DateTimeOffset.Now);
92+
_logger.LogInformation(string.Format("Failed to publish message to CF/Test. Isn't connected. @ {0} ", DateTimeOffset.Now));
11393
}
114-
115-
94+
}
95+
}
96+
97+
private async Task ConnectToBroker()
98+
{
99+
try
100+
{
101+
mqttInstance.ClientName = "Test";
102+
await mqttInstance.StartAsync("127.0.0.1", port: 1883, timeOut: 5, keepAlive: 5, mqttSecure: false);
103+
}
104+
catch (Exception ex)
105+
{
106+
_logger.LogInformation(string.Format("Failed to find the broker {0}. Exception {1}", DateTimeOffset.Now, ex.ToString()));
116107
}
117108
}
118109
}

0 commit comments

Comments
 (0)