Ejemplo n.º 1
0
        // Constructor
        public MqttManager(string IoTEndpoint, string Name, bool Security, int BrokerPort, X509Certificate pCaCert, X509Certificate2 pClientCert, MqttSslProtocols SslProtocol)
        {
            InitializeQueue();
            HasEventhandler = false;

            _ioTEndPoint = IoTEndpoint;
            _brokerPort  = BrokerPort;
            _name        = Name;
            _security    = Security;
            _caCert      = pCaCert;
            _clientCert  = pClientCert;
            _sslProtocol = SslProtocol;


            if (_ioTEndPoint != null)
            {
                if (Security)
                {
                    client = new MqttClient(_ioTEndPoint, _brokerPort, true, _caCert, _clientCert, MqttSslProtocols.TLSv1_2 /*this is what AWS IoT uses*/);
                }
                else
                {
                    client = new MqttClient(_ioTEndPoint);
                }

                _hasClient = true;

                client.ConnectionClosed       += Client_ConnectionClosed;
                client.MqttMsgSubscribed      += Client_MqttMsgSubscribed;
                client.MqttMsgUnsubscribed    += Client_MqttMsgUnsubscribed;
                client.MqttMsgPublished       += Client_MqttMsgPublished;
                client.MqttMsgPublishReceived += Client_MqttMsgPublishReceived;
            }
        }
Ejemplo n.º 2
0
    /// <summary>
    /// Start is called before the first frame update.
    /// </summary>
    private void Start()
    {
        //Set up default Mqtt properties for https://github.com/khilscher/MqttClient
        broker          = "mqtt.eclipse.org";
        port            = 1883;
        secure          = false;
        sslprotocol     = MqttSslProtocols.None;
        protocolversion = MqttProtocolVersion.Version_3_1_1;
        username        = "";
        password        = "";
        clientId        = "client123abcd";
        topic           = "vehicle/telemetry";
        publish         = false;
        qos             = (byte)2;
        retain          = false;
        cleansession    = false;
        keepalive       = 60;

        //Update the settings menu with default values
        settings.MQTTBrokerTextInputButton.TextObject.text = broker;
        settings.DeviceIDTextInputButton.TextObject.text   = clientId;
        settings.TopicTextInputButton.TextObject.text      = topic;

        //Default data properties
        data = null;
        dataHasBeenUpdated = false;

        //Add callback methods for setting ui
        settings.ConnectButton.OnClick.AddListener(() => MqttConnect());
        settings.DisconnectButton.OnClick.AddListener(() => MqttDisconnect());
        settings.SubscribeButton.OnClick.AddListener(() => MqttSubscribe());
        settings.UnsubscribeButton.OnClick.AddListener(() => MqttUnsubscribe());
    }
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="remoteHostName">Remote Host name</param>
        /// <param name="remotePort">Remote port</param>
        /// <param name="secure">Using SSL</param>
        /// <param name="caCert">CA certificate</param>
        /// <param name="clientCert">Client certificate</param>
        /// <param name="sslProtocol">SSL/TLS protocol version</param>
        public MqttNetworkChannel(string remoteHostName, int remotePort, bool secure, X509Certificate caCert, X509Certificate clientCert, MqttSslProtocols sslProtocol)
        {
            IPAddress   hostIpAddress = null;
            IPHostEntry hostEntry     = Dns.GetHostEntry(remoteHostName);

            if ((hostEntry != null) && (hostEntry.AddressList.Length > 0))
            {
                // check for the first address not null
                // it seems that with .Net Micro Framework, the IPV6 addresses aren't supported and return "null"
                int i = 0;
                while (hostEntry.AddressList[i] == null)
                {
                    i++;
                }
                hostIpAddress = hostEntry.AddressList[i];
            }
            else
            {
                throw new Exception("No address found for the remote host name");
            }

            _remoteHostName  = remoteHostName;
            _remoteIpAddress = hostIpAddress;
            _remotePort      = remotePort;
            _secure          = secure;
            _caCert          = caCert;
            _clientCert      = clientCert;
            _sslProtocol     = sslProtocol;
        }
Ejemplo n.º 4
0
        public MqttNetworkChannel(string remoteHostName, int remotePort, bool secure, X509Certificate caCert, X509Certificate clientCert, MqttSslProtocols sslProtocol, RemoteCertificateValidationCallback userCertificateValidationCallback, LocalCertificateSelectionCallback userCertificateSelectionCallback)
        {
            IPAddress ipAddress = (IPAddress)null;

            try
            {
                ipAddress = IPAddress.Parse(remoteHostName);
            }
            catch
            {
            }
            if (ipAddress == null)
            {
                IPHostEntry hostEntry = Dns.GetHostEntry(remoteHostName);
                if (hostEntry == null || (uint)hostEntry.AddressList.Length <= 0U)
                {
                    throw new Exception("No address found for the remote host name");
                }
                int index = 0;
                while (hostEntry.AddressList[index] == null)
                {
                    checked { ++index; }
                }
                ipAddress = hostEntry.AddressList[index];
            }
            this.remoteHostName  = remoteHostName;
            this.remoteIpAddress = ipAddress;
            this.remotePort      = remotePort;
            this.secure          = secure;
            this.caCert          = caCert;
            this.clientCert      = clientCert;
            this.sslProtocol     = sslProtocol;
            this.userCertificateValidationCallback = userCertificateValidationCallback;
            this.userCertificateSelectionCallback  = userCertificateSelectionCallback;
        }
Ejemplo n.º 5
0
 public MqttNetworkChannel(Socket socket, bool secure, X509Certificate serverCert, MqttSslProtocols sslProtocol, RemoteCertificateValidationCallback userCertificateValidationCallback, LocalCertificateSelectionCallback userCertificateSelectionCallback)
 {
     this.socket      = socket;
     this.secure      = secure;
     this.serverCert  = serverCert;
     this.sslProtocol = sslProtocol;
     this.userCertificateValidationCallback = userCertificateValidationCallback;
     this.userCertificateSelectionCallback  = userCertificateSelectionCallback;
 }
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="remoteHostName">Remote Host name</param>
        /// <param name="remotePort">Remote port</param>
        /// <param name="secure">Using SSL</param>
        /// <param name="sslProtocol">SSL/TLS protocol version</param>
        public MqttNetworkChannel(string remoteHostName, int remotePort, bool secure, MqttSslProtocols sslProtocol)
        {
            this.remoteHostName = new HostName(remoteHostName);
            this.remotePort = remotePort;
            this.secure = secure;
            this.sslProtocol = sslProtocol;

            if (secure && (sslProtocol == MqttSslProtocols.None))
                throw new ArgumentException("For secure connection, an SSL/TLS protocol version is needed");
        }
Ejemplo n.º 7
0
        public MqttBroker(string host, int port, bool secure, MqttSslProtocols sslprotocol, MqttProtocolVersion protocolversion, string username, string password)
        {
            this.host            = host;
            this.port            = port;
            this.secure          = secure;
            this.sslprotocol     = sslprotocol;
            this.protocolversion = protocolversion;
            this.username        = username;
            this.password        = password;

            Initialize();
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="remoteHostName">Remote Host name</param>
        /// <param name="remotePort">Remote port</param>
        /// <param name="secure">Using SSL</param>
        /// <param name="sslProtocol">SSL/TLS protocol version</param>
        public MqttNetworkChannel(string remoteHostName, int remotePort, bool secure, MqttSslProtocols sslProtocol)
        {
            this.remoteHostName = new HostName(remoteHostName);
            this.remotePort     = remotePort;
            this.secure         = secure;
            this.sslProtocol    = sslProtocol;

            if (secure && (sslProtocol == MqttSslProtocols.None))
            {
                throw new ArgumentException("For secure connection, an SSL/TLS protocol version is needed");
            }
        }
Ejemplo n.º 9
0
        public void Create(Configuration configuration)
        {
            this.config = configuration;

            this.client = CreateClient();

            this.client.MqttMsgPublishReceived += Client_MqttMsgPublishReceived;

            MqttClient CreateClient()
            {
                X509Certificate2 caCert     = null;
                X509Certificate2 clientCert = null;
                MqttSslProtocols protocol   = MqttSslProtocols.None;

                bool secure = bool.TryParse(this.config[SecureParam], out secure) && secure;

                if (secure)
                {
                    //MQTT can be made secure by a certificate from a Certificate Authority alone, or a CA certificate and a client certificate
                    //The CA certificate should never need a password
                    caCert = LoadCertificate(File.Parse(this.config[CACertParam]), string.Empty);

                    //The Client certificate should always require a password
                    if (!string.IsNullOrWhiteSpace(this.config[ClientCertParam]))
                    {
                        OnDecryptRequestArgs certDecryptArgs = new OnDecryptRequestArgs(this.config[CertPasswordParam]);
                        OnDecryptRequest(this, certDecryptArgs);
                        string clientPassword = certDecryptArgs.DecryptedValue;
                        clientCert = LoadCertificate(File.Parse(this.config[ClientCertParam]), clientPassword);
                    }

                    if (Enum.TryParse(this.config[SecureProtocolParam], out MqttSslProtocols parsedProtocol))
                    {
                        protocol = parsedProtocol;
                    }
                }

                return(new MqttClient(
                           this.config[BrokerParam]
                           , Int32.TryParse(this.config[BrokerPortParam], out int port) && port > 0 ? port : 1883
                           , secure
                           , caCert
                           , clientCert
                           , protocol
                           , null));
            }
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="remoteHostName">Remote Host name</param>
        /// <param name="remotePort">Remote port</param>
        /// <param name="secure">Using SSL</param>
        /// <param name="caCert">CA certificate</param>
        /// <param name="clientCert">Client certificate</param>
        /// <param name="sslProtocol">SSL/TLS protocol version</param>
        /// <param name="userCertificateSelectionCallback">A RemoteCertificateValidationCallback delegate responsible for validating the certificate supplied by the remote party</param>
        /// <param name="userCertificateValidationCallback">A LocalCertificateSelectionCallback delegate responsible for selecting the certificate used for authentication</param>
        public MqttNetworkChannel(string remoteHostName, int remotePort, bool secure, X509Certificate caCert, X509Certificate clientCert, MqttSslProtocols sslProtocol,
                                  RemoteCertificateValidationCallback userCertificateValidationCallback,
                                  LocalCertificateSelectionCallback userCertificateSelectionCallback)
        {
            IPAddress remoteIpAddress = null;

            try
            {
                // check if remoteHostName is a valid IP address and get it
                remoteIpAddress = IPAddress.Parse(remoteHostName);
            }
            catch
            {
            }

            // in this case the parameter remoteHostName isn't a valid IP address
            if (remoteIpAddress == null)
            {
                IPHostEntry hostEntry = Dns.GetHostEntry(remoteHostName);
                if ((hostEntry != null) && (hostEntry.AddressList.Length > 0))
                {
                    // check for the first address not null
                    // it seems that with .Net Micro Framework, the IPV6 addresses aren't supported and return "null"
                    int i = 0;
                    while (hostEntry.AddressList[i] == null)
                    {
                        i++;
                    }
                    remoteIpAddress = hostEntry.AddressList[i];
                }
                else
                {
                    throw new Exception("No address found for the remote host name");
                }
            }

            this.RemoteHostName  = remoteHostName;
            this.RemoteIpAddress = remoteIpAddress;
            this.RemotePort      = remotePort;
            this.secure          = secure;
            this.caCert          = caCert;
            this.clientCert      = clientCert;
            this.sslProtocol     = sslProtocol;
            this.userCertificateValidationCallback = userCertificateValidationCallback;
            this.userCertificateSelectionCallback  = userCertificateSelectionCallback;
        }
Ejemplo n.º 11
0
        public static SslProtocols ToSslPlatformEnum(MqttSslProtocols mqttSslProtocol)
        {
            switch (mqttSslProtocol)
            {
            case MqttSslProtocols.None:
                return(SslProtocols.None);

            case MqttSslProtocols.SSLv3:
                return(SslProtocols.Ssl3);

            case MqttSslProtocols.TLSv1_0:
                return(SslProtocols.Tls);

            default:
                throw new ArgumentException("SSL/TLS protocol version not supported");
            }
        }
Ejemplo n.º 12
0
        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));
            }
        }
Ejemplo n.º 13
0
        void BntEscrever(object sender, EventArgs e)
        {
            // create client instance
            X509Certificate  caCert           = new X509Certificate();
            X509Certificate  caCert2          = new X509Certificate();
            MqttSslProtocols mqttSslProtocols = new MqttSslProtocols();

            MqttClient client = new MqttClient("m12.cloudmqtt.com", 19337, false, caCert, caCert2, mqttSslProtocols);



            string clientId = Guid.NewGuid().ToString();

            client.Connect(clientId, "dmsjvruj", "miXaqhWnTVA9");

            string strValue = Convert.ToString("tetetet");

            // publish a message on "/home/temperature" topic with QoS 2
            client.Publish("/home/temperature", Encoding.UTF8.GetBytes(strValue), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, false);
            txtCampo.Text = "TUDO SIM LINDO";
        }
Ejemplo n.º 14
0
        //[END iot_mqtt_jwt]

        // [START iot_mqtt_client]
        public static MqttClient GetClient(string projectId, string cloudRegion,
                                           string registryId, string deviceId, string privateKeyFile,
                                           string algorithm, string caCert, string mqttBridgeHostname,
                                           int mqttBridgePort)
        {
            // Enable SSL/TLS support.
            MqttSslProtocols mqttSslProtocols = MqttSslProtocols.TLSv1_2;

            byte[] data;
            using (FileStream fs = File.OpenRead(caCert))
            {
                data = new byte[fs.Length];
                fs.Read(data, 0, data.Length);
                if (data[0] != 0x30)
                {
                    // maybe it's ASCII PEM base64 encoded ?
                    data = PEM("CERTIFICATE", data);
                }
                fs.Close();
            }
            X509Certificate x509Certificate = new X509Certificate(data);

            // Create client instance, Connect to the Google MQTT bridge.
            MqttClient client = new MqttClient(mqttBridgeHostname, mqttBridgePort,
                                               true, x509Certificate, null, mqttSslProtocols, null)
            {
                ProtocolVersion = MqttProtocolVersion.Version_3_1_1
            };

            Console.WriteLine("Creating the client {0}", client);
            // register to message received
            client.ConnectionClosed       += Client_ConnectionClosed;
            client.MqttMsgSubscribed      += Client_MqttMsgSubscribed;
            client.MqttMsgPublishReceived += Client_MqttMsgPublishReceived;
            client.MqttMsgPublished       += Client_MqttMsgPublished;

            return(client);
        }
        /// <summary>
        /// Defines the possible versions of Secure Sockets Layer (SSL).
        /// </summary>
        /// <remarks>
        /// Note: Following the recommendation of the .NET documentation, nanoFramework implementation does not have SSL3 nor Default because those are deprecated and unsecure.
        /// </remarks>
        public static SslProtocols ToSslPlatformEnum(MqttSslProtocols mqttSslProtocol)
        {
            switch (mqttSslProtocol)
            {
            case MqttSslProtocols.None:
                return(SslProtocols.None);

            case MqttSslProtocols.TLSv1_0:
                return(SslProtocols.Tls);

            case MqttSslProtocols.TLSv1_1:
                return(SslProtocols.Tls11);

            case MqttSslProtocols.TLSv1_2:
                return(SslProtocols.Tls12);

            case MqttSslProtocols.TLSv1_3:
                throw new ArgumentException("TLS 1.3 is currently disabled, awaiting support from OS/Device Firmware.");

            default:
                throw new ArgumentException("SSL/TLS protocol version not supported");
            }
        }
Ejemplo n.º 16
0
        public static SocketProtectionLevel ToSslPlatformEnum(MqttSslProtocols mqttSslProtocol)
        {
            switch (mqttSslProtocol)
            {
            case MqttSslProtocols.None:
                return(SocketProtectionLevel.PlainSocket);

            case MqttSslProtocols.SSLv3:
                return(SocketProtectionLevel.SslAllowNullEncryption);

            case MqttSslProtocols.TLSv1_0:
                return(SocketProtectionLevel.Tls10);

            case MqttSslProtocols.TLSv1_1:
                return(SocketProtectionLevel.Tls11);

            case MqttSslProtocols.TLSv1_2:
                return(SocketProtectionLevel.Tls12);

            default:
                throw new ArgumentException("SSL/TLS protocol version not supported");
            }
        }
Ejemplo n.º 17
0
        protected override void OnStart(string[] args)
        {
            // Update the service state to Start Pending.
            ServiceStatus serviceStatus = new ServiceStatus
            {
                dwCurrentState = ServiceState.SERVICE_START_PENDING,
                dwWaitHint     = 100000
            };

            SetServiceStatus(this.ServiceHandle, ref serviceStatus);

            eventLog1.WriteEntry("In OnStart");

            startWatch.Start();
            stopWatch.Start();

            UpdateFromDb();

            MqttSslProtocols mqttProtocols = new MqttSslProtocols();
            MqttClient       client        = new MqttClient("MQTT_CLIENT_ADDR", 8883, false, mqttProtocols, null, null);

            // register to message received
            client.MqttMsgPublishReceived += Client_MqttMsgPublishReceived;

            string clientId = Guid.NewGuid().ToString();

            client.Connect(clientId, "james", "USER_PASSWORD");

            // subscribe to the topic "/home/temperature" with QoS 2
            client.Subscribe(new string[] { "/home/games" }, new byte[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE });

            eventLog1.WriteEntry("INIT COMPLETED");

            // Update the service state to Running.
            serviceStatus.dwCurrentState = ServiceState.SERVICE_RUNNING;
            SetServiceStatus(this.ServiceHandle, ref serviceStatus);
        }
Ejemplo n.º 18
0
 /// <summary>
 /// Constructor (TCP/IP communication layer on port 8883 with SSL/TLS and default settings)
 /// </summary>
 /// <param name="serverCert">X509 Server certificate</param>
 /// <param name="sslProtocol">SSL/TLS protocol version</param>
 /// <param name="userCertificateSelectionCallback">A RemoteCertificateValidationCallback delegate responsible for validating the certificate supplied by the remote party</param>
 /// <param name="userCertificateValidationCallback">A LocalCertificateSelectionCallback delegate responsible for selecting the certificate used for authentication</param>
 public MqttBroker(X509Certificate serverCert, MqttSslProtocols sslProtocol, int connectTimeout,
                   RemoteCertificateValidationCallback userCertificateValidationCallback,
                   LocalCertificateSelectionCallback userCertificateSelectionCallback)
     : this(new MqttTcpCommunicationLayer(MqttSettings.MQTT_BROKER_DEFAULT_SSL_PORT, true, serverCert, sslProtocol, connectTimeout, userCertificateValidationCallback, userCertificateSelectionCallback), MqttSettings.Instance)
 {
 }
Ejemplo n.º 19
0
 public MqttBroker(X509Certificate serverCert, MqttSslProtocols sslProtocol, int port, int connectTimeout)
     : this(new MqttTcpCommunicationLayer(port, true, serverCert, sslProtocol, connectTimeout, null, null), MqttSettings.Instance)
 {
 }
Ejemplo n.º 20
0
 public MqttClient(string brokerHostName, int brokerPort, bool secure, X509Certificate caCert, MqttSslProtocols sslProtocol,
     RemoteCertificateValidationCallback userCertificateValidationCallback)
 {
 }
Ejemplo n.º 21
0
 public MqttClient(string brokerHostName, int brokerPort, bool secure, X509Certificate caCert,
     MqttSslProtocols sslProtocol)
 {
 }
 public static SslProtocols ToSslPlatformEnum(MqttSslProtocols mqttSslProtocol)
 {
     switch (mqttSslProtocol)
     {
         case MqttSslProtocols.None:
             return SslProtocols.None;
         case MqttSslProtocols.SSLv3:
             return SslProtocols.SSLv3;
         case MqttSslProtocols.TLSv1_0:
             return SslProtocols.TLSv1;
         case MqttSslProtocols.TLSv1_1:
         case MqttSslProtocols.TLSv1_2:
         default:
             throw new ArgumentException("SSL/TLS protocol version not supported");
     }
 }
Ejemplo n.º 23
0
 public MQTTMan(string ClientEui, string ServerEui, string brokerHostName, int brokerPort, X509Certificate caCert, MqttSslProtocols protocols)
     : base(ServerEui, brokerHostName, brokerPort, caCert, protocols)
 {
     this.ClientEui = ClientEui;
 }
Ejemplo n.º 24
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="socket">Socket opened with the client</param>
 public MqttNetworkChannel(StreamSocket socket)
 {
     this.socket      = socket;
     this.sslProtocol = MqttSslProtocols.None;
 }
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="socket">Socket opened with the client</param>
 public MqttNetworkChannel(StreamSocket socket)
 {
     this.socket = socket;
     this.sslProtocol = MqttSslProtocols.None;
 }
Ejemplo n.º 26
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="socket">Socket opened with the client</param>
 public MqttNetworkChannel(TcpSocketClient socket)
 {
     this.socket = socket;
     this.sslProtocol = MqttSslProtocols.None;
 }
Ejemplo n.º 27
0
 /// <summary>
 /// Constructor (TCP/IP communication layer on port 8883 with SSL/TLS and default settings)
 /// </summary>
 /// <param name="serverCert">X509 Server certificate</param>
 /// <param name="sslProtocol">SSL/TLS protocol versiokn</param>
 public MqttBroker(X509Certificate serverCert, MqttSslProtocols sslProtocol)
     : this(new MqttTcpCommunicationLayer(MqttSettings.MQTT_BROKER_DEFAULT_SSL_PORT, true, serverCert, sslProtocol, null, null), MqttSettings.Instance)
 {
 }
 public static SocketProtectionLevel ToSslPlatformEnum(MqttSslProtocols mqttSslProtocol)
 {
     switch (mqttSslProtocol)
     {
         case MqttSslProtocols.None:
             return SocketProtectionLevel.PlainSocket;
         case MqttSslProtocols.SSLv3:
             return SocketProtectionLevel.SslAllowNullEncryption;
         case MqttSslProtocols.TLSv1_0:
             return SocketProtectionLevel.Tls10;
         case MqttSslProtocols.TLSv1_1:
             return SocketProtectionLevel.Tls11;
         case MqttSslProtocols.TLSv1_2:
             return SocketProtectionLevel.Tls12;
         default:
             throw new ArgumentException("SSL/TLS protocol version not supported");
     }
 }
Ejemplo n.º 29
0
        private void btnConnect_Click(object sender, RoutedEventArgs e)
        {
            if (cboxQoS.SelectedItem == null)
            {
                // Missing QoS level
                NotifyUser("Select QoS level");
                return;
            }

            if (cboxProtocolVersion.SelectedItem == null)
            {
                // Missing MQTT version
                NotifyUser("Select a protocol version.");
                return;
            }

            if (cboxSslVersion.SelectedItem == null)
            {
                // Missing SSL version
                NotifyUser("Select a SSL version.");
                return;
            }

            var broker = txtBoxMqttBroker.Text.Trim();

            if (broker.Length == 0)
            {
                // Missing broker
                NotifyUser("Enter a hostname for the MQTT broker.");
                return;
            }

            int port = -1;

            if (!(int.TryParse(txtBoxMqttPort.Text.Trim(), out port)))
            {
                // Invalid port
                NotifyUser("Enter a valid port number");
                return;
            }

            if (txtBoxTopic.Text.Trim().Length == 0)
            {
                // Invalid topic
                NotifyUser("Enter a valid topic");
                return;
            }

            // Parse the input values
            var sslprotocol     = (MqttSslProtocols)Enum.Parse(typeof(MqttSslProtocols), cboxSslVersion.SelectedItem.ToString());
            var protocolversion = (MqttProtocolVersion)Enum.Parse(typeof(MqttProtocolVersion), cboxProtocolVersion.SelectedItem.ToString());

            // Connect to Mqtt Broker
            try
            {
                this.broker          = txtBoxMqttBroker.Text;
                this.clientId        = txtBoxDeviceID.Text;
                this.port            = port;
                this.secure          = ckboxUseSecure.IsChecked.Value;
                this.sslprotocol     = sslprotocol;
                this.protocolversion = protocolversion;
                this.username        = txtBoxUsername.Text;
                this.password        = txtBoxPassword.Text;
                this.qos             = (byte)cboxQoS.SelectedValue;
                this.retain          = chkBoxRetain.IsChecked.Value;
                this.cleansession    = false; // http://www.steves-internet-guide.com/mqtt-clean-sessions-example/
                this.keepalive       = 60;    // 60 seconds http://www.steves-internet-guide.com/mqtt-keep-alive-by-example/

                client = new MqttClient(this.broker, this.port, this.secure, this.sslprotocol);

                // Set MQTT version
                client.ProtocolVersion = this.protocolversion;

                // Setup callback for receiving messages
                client.MqttMsgPublishReceived += _client_MqttMsgPublishReceived;

                // MQTT return codes
                // https://www.hivemq.com/blog/mqtt-essentials-part-3-client-broker-connection-establishment/
                // https://www.eclipse.org/paho/clients/dotnet/api/html/4158a883-de72-1ec4-2209-632a86aebd74.htm
                byte resp = client.Connect(this.clientId, this.username, this.password, this.cleansession, this.keepalive);
                NotifyUser("Connect() Response: " + resp.ToString());
            }
            catch (Exception ex)
            {
                NotifyUser(ex.Message + ": " + ex.InnerException);
            }
        }
Ejemplo n.º 30
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="brokerHostName">Broker Host Name or IP Address</param>
 /// <param name="brokerPort">Broker port</param>
 /// <param name="sslProtocol">SSL/TLS protocol version</param>
 public MqttSecureClient(string brokerHostName, int brokerPort, MqttSslProtocols sslProtocol)
     : base(brokerHostName, brokerPort, true)
 {
     this.InitSecureChannel(sslProtocol);
 }
Ejemplo n.º 31
0
 /// <summary>
 /// Constructor (TCP/IP communication layer on port 8883 with SSL/TLS and default settings)
 /// </summary>
 /// <param name="serverCert">X509 Server certificate</param>
 /// <param name="sslProtocol">SSL/TLS protocol versiokn</param>
 public MqttBroker(X509Certificate serverCert, MqttSslProtocols sslProtocol, int connectTimeout)
     : this(new MqttTcpCommunicationLayer(MqttSettings.MQTT_BROKER_DEFAULT_SSL_PORT, true, serverCert, sslProtocol, connectTimeout, null, null), MqttSettings.Instance)
 {
 }
Ejemplo n.º 32
0
 /// <summary>
 /// MqttClient initialization
 /// </summary>
 /// <param name="caCert">CA certificate for secure connection</param>
 /// <param name="clientCert">Client certificate</param>
 /// <param name="sslProtocol">SSL/TLS protocol version</param>
 private void InitSecureChannel(X509Certificate caCert, X509Certificate clientCert, MqttSslProtocols sslProtocol)
 {
     // create network channel
     this.channel = new MqttSecureNetworkChannel(this.brokerHostName, this.brokerPort, caCert, clientCert, sslProtocol);
 }
Ejemplo n.º 33
0
 /**
  * \brief constructor
  * \param [in] brokerInfo : informations relative to the broker
  * \param [in] secure : define if the communication is secure or not
  * \param [in] caCert :
  * \param [in] clientCert :
  * \param [in] ssProtocol :
  */
 public SampleMqttClient(MqttBrokerInfo brokerInfo, bool secure, X509Certificate caCert, X509Certificate clientCert, MqttSslProtocols sslProtocol)
     : base(brokerInfo.broker_address, brokerInfo.broker_port, secure, caCert, clientCert, sslProtocol)
 {
     BrokerInfo = brokerInfo;
     ID         = Guid.NewGuid().ToString();
 }
Ejemplo n.º 34
0
 /// <summary>
 /// Constructor (TCP/IP communication layer on port 8883 with SSL/TLS and default settings)
 /// </summary>
 /// <param name="serverCert">X509 Server certificate</param>
 /// <param name="sslProtocol">SSL/TLS protocol version</param>
 /// <param name="userCertificateSelectionCallback">A RemoteCertificateValidationCallback delegate responsible for validating the certificate supplied by the remote party</param>
 /// <param name="userCertificateValidationCallback">A LocalCertificateSelectionCallback delegate responsible for selecting the certificate used for authentication</param>
 public MqttBroker(X509Certificate serverCert, MqttSslProtocols sslProtocol,
     RemoteCertificateValidationCallback userCertificateValidationCallback,
     LocalCertificateSelectionCallback userCertificateSelectionCallback)
     : this(new MqttTcpCommunicationLayer(MqttSettings.MQTT_BROKER_DEFAULT_SSL_PORT, true, serverCert, sslProtocol, userCertificateValidationCallback, userCertificateSelectionCallback), MqttSettings.Instance)
 {
 }
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="port">TCP listening port</param>
        /// <param name="secure">Secure connection (SSL/TLS)</param>
        /// <param name="serverCert">X509 server certificate</param>
        /// <param name="protocol">SSL/TLS protocol version</param>
        /// <param name="userCertificateSelectionCallback">A RemoteCertificateValidationCallback delegate responsible for validating the certificate supplied by the remote party</param>
        /// <param name="userCertificateValidationCallback">A LocalCertificateSelectionCallback delegate responsible for selecting the certificate used for authentication</param>
        public MqttTcpCommunicationLayer(int port, bool secure, X509Certificate serverCert, MqttSslProtocols protocol,
                                         RemoteCertificateValidationCallback userCertificateValidationCallback,
                                         LocalCertificateSelectionCallback userCertificateSelectionCallback)
        {
            if (secure && serverCert == null)
            {
                throw new ArgumentException("Secure connection requested but no server certificate provided");
            }

            this.Port       = port;
            this.Secure     = secure;
            this.ServerCert = serverCert;
            this.Protocol   = protocol;
            this.UserCertificateValidationCallback = userCertificateValidationCallback;
            this.UserCertificateSelectionCallback  = userCertificateSelectionCallback;
        }
Ejemplo n.º 36
0
 /// <summary>
 /// MqttClient initialization
 /// </summary>
 /// <param name="sslProtocol">SSL/TLS protocol version</param>
 private void InitSecureChannel(MqttSslProtocols sslProtocol)
 {
     // create network channel
     this.channel = new MqttSecureNetworkChannel(this.brokerHostName, this.brokerPort, sslProtocol);
 }
Ejemplo n.º 37
0
        /// <summary>
        /// 此通讯代理相关的服务器角色

        public MQTTManBase(string ServerEui, string brokerHostName, int brokerPort, X509Certificate caCert, MqttSslProtocols protocols)
        {
            RemoteCertificateValidationCallback certValidationCallBack = RemoteCertificateValidate;

            _client = new MqttClient(brokerHostName, brokerPort, caCert != null, caCert, null, protocols, certValidationCallBack);
            //register to message received
            _client.MqttMsgPublishReceived += Client_MqttMsgPublishReceived;
            _client.ConnectionClosed       += Client_ConnectionClosed;
            ServerId = ServerEui;
        }
Ejemplo n.º 38
0
        public MqttClient(IPAddress brokerIpAddress, int brokerPort, bool secure, X509Certificate caCert, X509Certificate clientCert, MqttSslProtocols sslProtocol)
        {
#if !(MF_FRAMEWORK_VERSION_V4_2 || MF_FRAMEWORK_VERSION_V4_3 || COMPACT_FRAMEWORK)
            this.Init(brokerIpAddress.ToString(), brokerPort, secure, caCert, clientCert, sslProtocol, null, null);
#else
            this.Init(brokerIpAddress.ToString(), brokerPort, secure, caCert, clientCert, sslProtocol);
#endif
        }
Ejemplo n.º 39
0
        private void bt_connect_Click(object sender, RoutedEventArgs e)
        {
            var broker = tb_broker.Text.Trim();

            if (broker.Length == 0)
            {
                //no broker given
                NotifyUser("Enter a hostname for the MQTT broker.", NotifyType.ErrorMessage);
            }
            else
            {
                int port = -1;
                if (!(int.TryParse(tb_port.Text.Trim(), out port)))
                {
                    //invalid port
                    NotifyUser("Enter a valid port number", NotifyType.ErrorMessage);
                }
                else
                {
                    if (cb_protocol_version.SelectedItem == null)
                    {
                        //no protocol version selected
                        NotifyUser("Select a protocol", NotifyType.ErrorMessage);
                    }
                    else
                    {
                        if (cb_ssl_protocol_version.SelectedItem == null)
                        {
                            //no ssl protocol selected
                            NotifyUser("Select a protocol version", NotifyType.ErrorMessage);
                        }
                        else
                        {
                            uint interval = 15;
                            if (!uint.TryParse(tb_interval.Text.Trim(), out interval) || interval <= 0)
                            {
                                //invalid interval
                                NotifyUser("Enter a valid interval", NotifyType.ErrorMessage);
                            }
                            else
                            {
                                if (tb_topic.Text.Trim().Length == 0)
                                {
                                    //invalid topic
                                    NotifyUser("Enter a valid topic", NotifyType.ErrorMessage);
                                }
                                else
                                {
                                    //parse the input values
                                    var sslprotocol     = (MqttSslProtocols)Enum.Parse(typeof(MqttSslProtocols), cb_ssl_protocol_version.SelectedItem.ToString());
                                    var protocolversion = (MqttProtocolVersion)Enum.Parse(typeof(MqttProtocolVersion), cb_protocol_version.SelectedItem.ToString());
                                    this._interval = interval;
                                    //connect
                                    try
                                    {
                                        //store all settings
                                        StoreAllSettings();
                                        this.broker          = tb_broker.Text;
                                        this.port            = port;
                                        this.secure          = cb_secure.IsChecked.Value;
                                        this.sslprotocol     = sslprotocol;
                                        this.protocolversion = protocolversion;
                                        this.username        = tb_username.Text;
                                        this.password        = tb_password.Password;
                                        MqttBroker mqttbroker = new MqttBroker(this.broker, this.port, this.secure, this.sslprotocol, this.protocolversion, this.username, this.password);
                                        mqttbroker.Connect();

                                        //register extended execution.
                                        BeginExtendedExecution(_interval);
                                    }
                                    catch (Exception ex)
                                    {
                                        NotifyUser(ex.Message + ": " + ex.InnerException, NotifyType.ErrorMessage);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
Ejemplo n.º 40
0
 public AdafruitClient(string brokerHostName, int brokerPort, bool secure, MqttSslProtocols sslProtocol,
                       RemoteCertificateValidationCallback userCertificateValidationCallback,
                       LocalCertificateSelectionCallback userCertificateSelectionCallback) : base(brokerHostName, brokerPort, secure, sslProtocol, userCertificateValidationCallback, userCertificateSelectionCallback)
 {
 }
Ejemplo n.º 41
0
        public static async Task Get()
        {
            MqttClient client = new MqttClient("127.0.0.1", 1883, false, null, MqttSslProtocols.None); // 1883 default
           // MqttClient client = new MqttClient("mqtt.phelicks.net");

            X509Certificate cert = null; //X509Certificate.CreateFromCertFile(Certificate); Not used atm.
            MqttSslProtocols sslProtocol = new MqttSslProtocols();

            string clientId = Guid.NewGuid().ToString(); 
            var simJobIndex = 0;

            //client.Connect(clientId, "cab", "sjuttongubbar");
            client.Connect(clientId);
            //client.MqttMsgPublished += client_MqttMsgPublished;
            simJobStatus.Clear();

            for (;;)
            {

                using (var httpclient = new HttpClient())
                {
                    httpclient.BaseAddress = new Uri("http://localhost:50780/");
                    httpclient.DefaultRequestHeaders.Accept.Clear();
                    httpclient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                    HttpResponseMessage response = await httpclient.GetAsync("api/SimJob"+"?includeSnapshots=true");
                    if (response.IsSuccessStatusCode)
                    {
                        List<SimJobModel> simJobList = await response.Content.ReadAsAsync<List<SimJobModel>>();

                        foreach (var simjob in simJobList)
                        {
                            //var simjobx = simJobStatus.Find(x => x.SimJobId.Contains(simjob.SimJobId));
                            simJobIndex = findSimJob(simjob); // simjob already exist
                            if (simJobIndex >= 0)
                            {
                                if (simjob.jobStarted == false) // existing simjob stopped - remove thread
                                {
                                    simJobStatus[simJobIndex].active = false; // mark passive- to be removed
                                }
                                else // update with latest fields from GUI
                                    simJobStatus[simJobIndex].tws.UpdateSimulatedCar(simjob.carId, simjob.repeatJob, simjob.speedX);
                            }
                            else
                            { // new simjob, not stored locally
                                if (simjob.jobStarted)
                                {
                                    SimJobStatus sim = new SimJobStatus();
                                    sim.ObjectId = simjob.SimJobId;
                                    sim.active = true;

                                    SimulatedCar tws = new SimulatedCar(client, simjob);
                                    tws.UpdateSimulatedCar(simjob.carId, simjob.repeatJob, simjob.speedX);
                                    Thread t = new Thread(new ThreadStart(tws.ThreadProc));
                                    sim.task = t;
                                    sim.tws = tws;
                                    simJobStatus.Add(sim); 
                                    t.Start();
                                }
                            }
                        }
                        for (int i = simJobStatus.Count - 1; i >= 0; i--) // remove passive simjobs
                        {
                            if (simJobStatus[i].active == false)
                            {
                                simJobStatus[i].task.Abort();
                                Console.WriteLine("Simjob terminated.\n");

                                simJobStatus.RemoveAt(i);
                            }
                        }
                    }
                }
                System.Threading.Thread.Sleep(100);
            }
        }