forked from equinor/flotilla
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MqttTopics.cs
78 lines (76 loc) · 2.85 KB
/
MqttTopics.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
using System.Text.RegularExpressions;
using Api.Mqtt.MessageModels;
namespace Api.Mqtt
{
/// <summary>
/// This class contains a list of topics linked to their message models
/// </summary>
public static class MqttTopics
{
/// <summary>
/// A dictionary linking MQTT topics to their respective message models
/// </summary>
public static readonly Dictionary<string, Type> TopicsToMessages =
new()
{
{
"isar/+/robot_status", typeof(IsarRobotStatusMessage)
},
{
"isar/+/robot_info", typeof(IsarRobotInfoMessage)
},
{
"isar/+/robot_heartbeat", typeof(IsarRobotHeartbeatMessage)
},
{
"isar/+/mission", typeof(IsarMissionMessage)
},
{
"isar/+/task", typeof(IsarTaskMessage)
},
{
"isar/+/step", typeof(IsarStepMessage)
},
{
"isar/+/battery", typeof(IsarBatteryMessage)
},
{
"isar/+/pressure", typeof(IsarPressureMessage)
},
{
"isar/+/pose", typeof(IsarPoseMessage)
}
};
/// <summary>
/// Searches a dictionary for a specific topic name and returns the corresponding value from the wildcarded dictionary
/// </summary>
/// <remarks>
/// Will throw <see cref="InvalidOperationException"></see> if there are more than one matches for the topic.
/// </remarks>
/// <typeparam name="T"></typeparam>
/// <param name="dict"></param>
/// <param name="topic"></param>
/// <returns>
/// The value corresponding to the wildcarded topic
/// </returns>
/// <exception cref="InvalidOperationException">There was more than one topic pattern matching the provided topic</exception>
public static T? GetItemByTopic<T>(this Dictionary<string, T> dict, string topic)
{
return (
from p in dict
where Regex.IsMatch(topic, ConvertTopicToRegex(p.Key))
select p.Value
).SingleOrDefault();
}
/// <summary>
/// Converts from mqtt topic wildcards to the corresponding
/// regex expression to allow for searching the dictionary for the topic of a message
/// </summary>
/// <param name="topic"></param>
/// <returns></returns>
private static string ConvertTopicToRegex(string topic)
{
return topic.Replace('#', '*').Replace("+", "[^/\n]*", StringComparison.Ordinal);
}
}
}