-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMqttManager.cs
65 lines (59 loc) · 1.69 KB
/
MqttManager.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
using DotNetNuke.Framework;
using DotNetNuke.Instrumentation;
using Newtonsoft.Json;
using System;
using System.Text;
using uPLibrary.Networking.M2Mqtt;
namespace DnnSummit2023
{
public class MqttManager : ServiceLocator<IMqttManager, MqttManager>, IMqttManager
{
private MqttClient client { get; set; }
private AppSettings settings { get; set; }
private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(MqttManager));
protected override Func<IMqttManager> GetFactory()
{
return () => new MqttManager();
}
public MqttManager()
{
try
{
settings = AppSettings.GetAppSettings();
if (!string.IsNullOrEmpty(settings.MqttServer))
{
client = new MqttClient(settings.MqttServer, settings.MqttPort, false, null, MqttSslProtocols.None);
this.Reconnect();
}
}
catch (Exception ex)
{
DotNetNuke.Services.Exceptions.Exceptions.LogException(new Exception("Couldn't connect to MQTT server", ex));
}
}
public void SendMessage(string topic, object message)
{
try
{
if (!client.IsConnected)
{
this.Reconnect();
}
client.Publish(topic, Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(message)));
}
catch (Exception ex)
{
Logger.Error($"Error sending MQTT message");
DotNetNuke.Services.Exceptions.Exceptions.LogException(new Exception("Couldn't send message to MQTT server", ex));
}
}
private void Reconnect()
{
client.Connect((new Guid()).ToString());
}
}
public interface IMqttManager
{
void SendMessage(string topic, object message);
}
}