-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCpopSubscriber.cs
77 lines (65 loc) · 2.29 KB
/
CpopSubscriber.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
using System;
using System.Collections.Concurrent;
using System.Threading;
using MQTTnet;
using MQTTnet.Client;
using MQTTnet.Client.Options;
using UnityEngine;
namespace CognitiveXR.Cpop
{
public class CpopServerOptions
{
public string Server { get; set; }
public int? Port { get; set; }
}
public class CpopSubscriber
{
public ConcurrentQueue<CpopData> Queue { get; }
private CpopServerOptions _options;
private CancellationTokenSource _cancellationTokenSource;
private IMqttClient _client;
public CpopSubscriber(ConcurrentQueue<CpopData> queue, CpopServerOptions options)
{
Queue = queue;
_options = options;
_cancellationTokenSource = new CancellationTokenSource();
var factory = new MqttFactory();
_client = factory.CreateMqttClient();
}
public CpopSubscriber(CpopServerOptions options) : this(new ConcurrentQueue<CpopData>(), options)
{
}
public CpopSubscriber() : this(new CpopServerOptions {Server = "localhost"})
{
}
public void Unsubscribe()
{
_cancellationTokenSource.Cancel();
}
public async void Subscribe()
{
var options = new MqttClientOptionsBuilder()
.WithClientId("CS-Client")
.WithTcpServer(_options.Server, _options.Port)
.WithCleanSession()
.Build();
_client.UseApplicationMessageReceivedHandler(DefaultCpopMessageHandlerJson);
await _client.ConnectAsync(options, _cancellationTokenSource.Token);
await _client.SubscribeAsync(new MqttTopicFilterBuilder().WithTopic("cpop").Build());
}
private void DefaultCpopMessageHandlerJson(MqttApplicationMessageReceivedEventArgs e)
{
try
{
var payload = e.ApplicationMessage.Payload;
String jsonText = System.Text.Encoding.UTF8.GetString(payload);
var cpopData = JsonUtility.FromJson<CpopData>(jsonText);
Queue.Enqueue(cpopData);
}
catch (Exception exp)
{
Debug.LogError(exp);
}
}
}
}