WingMan – Blame information for rev 1
?pathlinks?
Rev | Author | Line No. | Line |
---|---|---|---|
1 | office | 1 | using System; |
2 | using System.Collections.Generic; |
||
3 | using System.Linq; |
||
4 | using System.Net; |
||
5 | using System.Text; |
||
6 | using System.Threading.Tasks; |
||
7 | using MQTTnet; |
||
8 | using MQTTnet.Client; |
||
9 | using MQTTnet.Extensions.ManagedClient; |
||
10 | |||
11 | namespace WingMan.Communication |
||
12 | { |
||
13 | public class MQTTClient : IDisposable |
||
14 | { |
||
15 | private IManagedMqttClient Client { get; set; } |
||
16 | public bool ClientRunning { get; set; } |
||
17 | |||
18 | public MQTTClient() |
||
19 | { |
||
20 | Client = new MqttFactory().CreateManagedMqttClient(); |
||
21 | } |
||
22 | |||
23 | public async Task Start(IPAddress ipAddress, int port) |
||
24 | { |
||
25 | // Setup and start a managed MQTT client. |
||
26 | var options = new ManagedMqttClientOptionsBuilder() |
||
27 | .WithAutoReconnectDelay(TimeSpan.FromSeconds(5)) |
||
28 | .WithClientOptions(new MqttClientOptionsBuilder() |
||
29 | .WithTcpServer(ipAddress.ToString(), port) |
||
30 | .WithTls().Build()) |
||
31 | .Build(); |
||
32 | BindHandlers(); |
||
33 | |||
34 | await Client.SubscribeAsync( |
||
35 | new TopicFilterBuilder() |
||
36 | .WithTopic("lobby") |
||
37 | .WithTopic("exchange") |
||
38 | .Build() |
||
39 | ); |
||
40 | |||
41 | await Client.StartAsync(options); |
||
42 | |||
43 | ClientRunning = true; |
||
44 | } |
||
45 | |||
46 | private void ClientOnApplicationMessageReceived(object sender, MqttApplicationMessageReceivedEventArgs e) |
||
47 | { |
||
48 | |||
49 | } |
||
50 | |||
51 | private void ClientOnConnected(object sender, MqttClientConnectedEventArgs e) |
||
52 | { |
||
53 | |||
54 | } |
||
55 | |||
56 | public async Task Stop() |
||
57 | { |
||
58 | UnbindHandlers(); |
||
59 | |||
60 | await Client.StopAsync(); |
||
61 | |||
62 | ClientRunning = false; |
||
63 | } |
||
64 | |||
65 | public void Dispose() |
||
66 | { |
||
67 | UnbindHandlers(); |
||
68 | |||
69 | Client.StopAsync().Wait(); |
||
70 | |||
71 | Client?.Dispose(); |
||
72 | } |
||
73 | |||
74 | public void BindHandlers() |
||
75 | { |
||
76 | Client.Connected += ClientOnConnected; |
||
77 | Client.ApplicationMessageReceived += ClientOnApplicationMessageReceived; |
||
78 | } |
||
79 | |||
80 | public void UnbindHandlers() |
||
81 | { |
||
82 | Client.Connected -= ClientOnConnected; |
||
83 | Client.ApplicationMessageReceived -= ClientOnApplicationMessageReceived; |
||
84 | } |
||
85 | } |
||
86 | } |