Skip to main content

General

Example: MQTT Bridge

How to act as an MQTT Client to bridge data to external brokers (AWS/HiveMQ).

The SDK includes a fully managed MQTT Client. Use this to integrate with 3rd party clouds or legacy systems.

using MQTTnet; 
using Proxus.SDK.BaseFunctions;
using Proxus.Common.Messages;
using Proxus.Common;

namespace MyProject.Functions
{
    public class AwsBridge : FunctionBase
    {
        // 1. Override Configuration Properties
        protected override string MqttBrokerHost => "a3xyz-ats.iot.us-east-1.amazonaws.com";
        protected override int MqttBrokerPort => 8883;
        protected override string MqttBrokerUser => null; // Using Certs in prod

        public AwsBridge(object sys, object log, object config) : base(sys, log, config) { }

        protected override void OnStarted()
        {
            // 2. Subscribe to Internal Data
            Subscriptions?.Add(new SubscriptionContext {
                Type = typeof(TransportData),
                Topics = (HashSet<string>) ["Gen_01"]
            });

            // 3. Listen to Cloud Commands
            SubscribeToMqttTopic("cmd/reset");

            base.OnStarted();
        }

        // Internal -> External
        protected override void OnMessageReceive(FunctionContext ctx)
        {
            if (ctx.Message is TransportData data)
            {
                var temp = data.GetPayloadValueByName<double>("Temperature");
                string json = $"{{\"device\": \"{data.Topic}\", \"val\": {temp}}}";
                
                PublishMqttMessage("dt/telemetry", json);
            }
        }

        // External -> Internal
        protected override void HandleMqttMessage(MqttApplicationMessage message)
        {
            string cmd = message.ConvertPayloadToString();
            LogInformation($"Cloud Command Received: {cmd}");

            if (cmd == "RESET_COUNTER")
            {
                // Logic to reset local state or write to PLC
            }
        }
    }
}