|
| 1 | +using Meshtastic.Data; |
| 2 | +using Meshtastic.Data.MessageFactories; |
| 3 | +using MQTTnet; |
| 4 | +using Meshtastic.Protobufs; |
| 5 | +using MQTTnet.Client; |
| 6 | +using Microsoft.Extensions.Logging; |
| 7 | + |
| 8 | +namespace Meshtastic.Cli.CommandHandlers; |
| 9 | + |
| 10 | +public class MqttProxyCommandHandler : DeviceCommandHandler |
| 11 | +{ |
| 12 | + public MqttProxyCommandHandler(DeviceConnectionContext context, CommandContext commandContext) : base(context, commandContext) { } |
| 13 | + |
| 14 | + public async Task<DeviceStateContainer> Handle() |
| 15 | + { |
| 16 | + var wantConfig = new ToRadioMessageFactory().CreateWantConfigMessage(); |
| 17 | + var container = await Connection.WriteToRadio(wantConfig, CompleteOnConfigReceived); |
| 18 | + Connection.Disconnect(); |
| 19 | + return container; |
| 20 | + } |
| 21 | + |
| 22 | + public override async Task OnCompleted(FromRadio packet, DeviceStateContainer container) |
| 23 | + { |
| 24 | + // connect to mqtt server with mqttnet |
| 25 | + var factory = new MqttFactory(); |
| 26 | + using var mqttClient = factory.CreateMqttClient(); |
| 27 | + MqttClientOptions options = GetMqttClientOptions(container); |
| 28 | + await mqttClient.ConnectAsync(options, CancellationToken.None); |
| 29 | + |
| 30 | + var root = String.IsNullOrWhiteSpace(container.LocalModuleConfig.Mqtt.Root) ? "msh" : container.LocalModuleConfig.Mqtt.Root; |
| 31 | + var prefix = $"{root}/{container.Metadata.FirmwareVersion.First()}"; |
| 32 | + var subscriptionTopic = $"{prefix}/#"; |
| 33 | + |
| 34 | + Logger.LogInformation($"Subscribing to topic: {subscriptionTopic}"); |
| 35 | + await mqttClient.SubscribeAsync(new MqttTopicFilterBuilder() |
| 36 | + .WithTopic(subscriptionTopic) |
| 37 | + .Build()); |
| 38 | + |
| 39 | + mqttClient.ApplicationMessageReceivedAsync += async e => |
| 40 | + { |
| 41 | + if (e.ApplicationMessage.Topic.StartsWith($"{prefix}/stat/")) |
| 42 | + return; |
| 43 | + |
| 44 | + Logger.LogInformation($"Received MQTT from host on topic: {e.ApplicationMessage.Topic}"); |
| 45 | + |
| 46 | + // Get bytes from utf8 string |
| 47 | + var toRadio = new ToRadioMessageFactory() |
| 48 | + .CreateMqttClientProxyMessage(e.ApplicationMessage.Topic, e.ApplicationMessage.PayloadSegment.ToArray(), e.ApplicationMessage.Retain); |
| 49 | + Logger.LogDebug(toRadio.ToString()); |
| 50 | + await Connection.WriteToRadio(toRadio); |
| 51 | + }; |
| 52 | + |
| 53 | + await Connection.ReadFromRadio(async (fromRadio, container) => |
| 54 | + { |
| 55 | + if (fromRadio?.PayloadVariantCase == FromRadio.PayloadVariantOneofCase.MqttClientProxyMessage && |
| 56 | + fromRadio.MqttClientProxyMessage is not null) |
| 57 | + { |
| 58 | + var message = fromRadio.MqttClientProxyMessage; |
| 59 | + Logger.LogInformation($"Received MQTT message from device to proxy on topic: {message.Topic}"); |
| 60 | + if (message.PayloadVariantCase == MqttClientProxyMessage.PayloadVariantOneofCase.Data) |
| 61 | + { |
| 62 | + Logger.LogDebug(ServiceEnvelope.Parser.ParseFrom(message.Data).ToString()); |
| 63 | + await mqttClient.PublishAsync(new MqttApplicationMessageBuilder() |
| 64 | + .WithTopic(message.Topic) |
| 65 | + .WithPayload(message.Data.ToByteArray()) |
| 66 | + .WithRetainFlag(message.Retained) |
| 67 | + .Build()); |
| 68 | + } |
| 69 | + else if (message.PayloadVariantCase == MqttClientProxyMessage.PayloadVariantOneofCase.Text) |
| 70 | + { |
| 71 | + Logger.LogDebug(message.Text); |
| 72 | + await mqttClient.PublishAsync(new MqttApplicationMessageBuilder() |
| 73 | + .WithTopic(message.Topic) |
| 74 | + .WithPayload(message.Text) |
| 75 | + .WithRetainFlag(message.Retained) |
| 76 | + .Build()); |
| 77 | + } |
| 78 | + } |
| 79 | + return false; |
| 80 | + }); |
| 81 | + } |
| 82 | + |
| 83 | + private MqttClientOptions GetMqttClientOptions(DeviceStateContainer container) |
| 84 | + { |
| 85 | + var builder = new MqttClientOptionsBuilder() |
| 86 | + .WithClientId(container.GetDeviceNodeInfo()?.User?.Id ?? container.MyNodeInfo.MyNodeNum.ToString()); |
| 87 | + |
| 88 | + var address = container.LocalModuleConfig.Mqtt.Address; |
| 89 | + var host = address.Split(':').FirstOrDefault() ?? container.LocalModuleConfig.Mqtt.Address; |
| 90 | + var port = address.Contains(":") ? address.Split(':').LastOrDefault() : null; |
| 91 | + |
| 92 | + if (container.LocalModuleConfig.Mqtt.TlsEnabled) |
| 93 | + { |
| 94 | + builder = builder.WithTls() |
| 95 | + .WithTcpServer(host, Int32.Parse(port ?? "8883")); |
| 96 | + } |
| 97 | + else { |
| 98 | + builder = builder.WithTcpServer(host, Int32.Parse(port ?? "1883")); |
| 99 | + } |
| 100 | + |
| 101 | + if (container.LocalModuleConfig.Mqtt.Username is not null) |
| 102 | + builder = builder.WithCredentials(container.LocalModuleConfig.Mqtt.Username, container.LocalModuleConfig.Mqtt.Password); |
| 103 | + |
| 104 | + return builder.Build(); |
| 105 | + } |
| 106 | +} |
0 commit comments