public IResult Start() { Uri endpoint = new Uri(MqttConfig.BrokerEndpoint); MqttSslProtocols protocols = MqttConfig.SecureConnection ? MqttSslProtocols.TLSv1_2 : MqttSslProtocols.None; X509Certificate caCert = null; X509Certificate clientCert = null; if (MqttConfig.Security != null && MqttConfig.Security is MqttSecurity security) { caCert = security.CaCert ?? null; clientCert = security.ClientCert ?? null; } mqttClient = new MqttClient(endpoint.Host, endpoint.Port, MqttConfig.SecureConnection, caCert, clientCert, protocols, null, null); mqttClient.ConnectionClosed += MqttClient_ConnectionClosed; try { byte success; MqttConnectConfig config = MqttConfig.MqttConnectConfig; if (MqttConfig.Credentials is MqttCredentials mqttCreds) { success = mqttClient.Connect(Guid.NewGuid().ToString(), mqttCreds.UserName, mqttCreds.Password, config.WillRetain, config.WillQosLevel, config.WillFlag, config.WillTopic, config.WillMessage, config.CleanSession, config.KeepAlivePeriod); } else { success = mqttClient.Connect(Guid.NewGuid().ToString(), null, null, config.WillRetain, config.WillQosLevel, config.WillFlag, config.WillTopic, config.WillMessage, config.CleanSession, config.KeepAlivePeriod); } if (success != 0) { return(new Result(false, new Message(MessageType.Error, "Could not connect to MQTT Broker", success.ToString()))); } mqttClient.MqttMsgPublishReceived += MqttClient_MqttMsgPublishReceived; return(new Result(true)); } catch (Exception e) { logger.Error(e, "Could not connect MQTT-Broker"); return(new Result(e)); } }
public MqttConfig(string clientId, string brokerEndpoint) { ClientId = clientId; BrokerEndpoint = brokerEndpoint; MqttConnectConfig = new MqttConnectConfig(); }