public void Initialize(string username, string password, ushort port, string ipAddressOfTheServer, ushort bufferSize, string clientId,
                        ushort willFlag, ushort willReatin, uint willQoS, string willTopic, string willMessage, ushort keepAlivePeriod, ClientType clientType, uint publishQoSLevel,
                        uint retain, uint cleanSession, string certificateFileName, string privateKeyFileName)
 {
     {
         MqttSettings.Instance.Username             = username;
         MqttSettings.Instance.Password             = password;
         MqttSettings.Instance.BufferSize           = Convert.ToInt32(bufferSize);
         MqttSettings.Instance.Port                 = Convert.ToInt32(port);
         MqttSettings.Instance.IPAddressOfTheServer = IPAddress.Parse(ipAddressOfTheServer);
     }
     CrestronLogger.WriteToLog("Settings initialized", 1);
     {
         KeepAlivePeriod = keepAlivePeriod;
         ClientId        = clientId;
         WillFlag        = willFlag == 0 ? false : true;
         WillRetain      = willReatin == 0 ? false : true;
         WillQosLevel    = (byte)willQoS;
         WillTopic       = willTopic;
         WillMessage     = willMessage;
         Topics          = new Dictionary <string, byte>();
         PublishQoSLevel = publishQoSLevel;
         Retain          = retain == 0 ? false : true;
         CleanSession    = cleanSession == 0 ? false : true;
     }
     CrestronLogger.WriteToLog("CLIENT STUFF initialized", 1);
     {
         try
         {
             tcpClient = new SecureTCPClient(ipAddressOfTheServer.ToString(), port, bufferSize);
             if (certificateFileName != "//" && privateKeyFileName != "//")
             {
                 var certificate           = ReadFromResource(@"NVRAM\\" + certificateFileName);
                 X509Certificate2 x509Cert = new X509Certificate2(certificate);
                 tcpClient.SetClientCertificate(x509Cert);
                 tcpClient.SetClientPrivateKey(ReadFromResource(@"NVRAM\\" + privateKeyFileName));
             }
             tcpClient.SocketStatusChange += this.OnSocketStatusChange;
             PayloadMapper                  = new PayloadMapper();
             PayloadMapper.ClientType       = clientType;
             PacketDecoder                  = new PacketDecoder();
             sessionManager                 = new MqttSessionManager(clientId);
             publisherManager               = new MqttPublisherManager(sessionManager);
             publisherManager.PacketToSend += this.OnPacketToSend;
         }
         catch (Exception e)
         {
             OnErrorOccured("ERROR DURING INITIALIZATION: " + e.Message);
         }
     }
     CrestronLogger.WriteToLog("MQTTCLIENT - Initialize - completed : " + clientId, 1);
 }
示例#2
0
        public void Initialize(
            string clientID,
            string brokerAddress,
            ushort brokerPort,
            ushort enableSSL,
            string username,
            string password,
            ushort willFlag,
            ushort willRetain,
            uint willQoS,
            string willTopic,
            string willMessage,
            uint cleanSession,
            ushort bufferSize
            )
        {
            MqttSettings.Instance.Username   = username;
            MqttSettings.Instance.Password   = password;
            MqttSettings.Instance.BufferSize = Convert.ToInt32(bufferSize);
            MqttSettings.Instance.Port       = Convert.ToInt32(brokerPort);
            MqttSettings.Instance.Broker     = brokerAddress;
            EnableSSL = (enableSSL > 0);
            CrestronLogger.WriteToLog("Instance Settings initialized", 1);

            KeepAlivePeriod = 0; // currently set to 0, as the keepalive mechanism has not been implemented
            ClientID        = clientID;
            WillFlag        = willFlag == 0 ? false : true;
            WillRetain      = willRetain == 0 ? false : true;
            WillQosLevel    = (byte)willQoS;
            WillTopic       = willTopic;
            WillMessage     = willMessage;
            Subscriptions   = new Dictionary <string, byte>();
            CleanSession    = cleanSession == 0 ? false : true;

            CrestronLogger.WriteToLog("Client settings initialized", 1);

            try
            {
                if (EnableSSL)
                {
                    SSLClient = new SecureTCPClient(brokerAddress.ToString(), brokerPort, bufferSize);
                    if (CertificateFile != "" && KeyFile != "")
                    {
                        var certificate           = ReadFromResource(@"NVRAM\\" + CertificateFile);
                        X509Certificate2 x509Cert = new X509Certificate2(certificate);
                        SSLClient.SetClientCertificate(x509Cert);
                        SSLClient.SetClientPrivateKey(ReadFromResource(@"NVRAM\\" + KeyFile));
                    }
                    SSLClient.SocketStatusChange += this.OnSSLSocketStatusChange;
                }
                else
                {
                    NoSSLClient = new TCPClient(brokerAddress.ToString(), brokerPort, bufferSize);
                    NoSSLClient.SocketStatusChange += this.OnNoSSLSocketStatusChange;
                }
                PacketDecoder    = new PacketDecoder();
                sessionManager   = new MqttSessionManager(clientID);
                publisherManager = new MqttPublisherManager(sessionManager);
                publisherManager.PacketToSend += this.OnPacketToSend;
            }
            catch (Exception e)
            {
                OnErrorOccured("ERROR DURING INITIALIZATION: " + e.Message);
            }

            CrestronLogger.WriteToLog("MQTTCLIENT - Initialize - completed : " + clientID, 1);
        }
        public void Connect(string args_str)
        {
            if (client != null && client.ClientStatus == SocketStatus.SOCKET_STATUS_CONNECTED)
            {
                CrestronConsole.ConsoleCommandResponse("Client is already connected. Disconnect first");
                return;
            }

            // Parse command-line arguments
            // You can optionally associate the client object with a certifiate and private key, which both must be in DER format, from the file system
            // For this particular example, the filenames must not contains spaces and must be located in the application directory
            string[] args = args_str.Split(' ');
            if (args.Length != 2 && args.Length != 4)
            {
                CrestronConsole.ConsoleCommandResponse("usage: connect [<cert_file> <key_file>] <hostname> <port>");
                return;
            }

            bool   provideCert = false;
            string cert_fn     = null; // certificate filename
            string key_fn      = null; // private key filename
            int    start       = 0;    // starting index of the hostname and port arguments in args

            if (args.Length == 4)      // user provides filenames for the cert/key before the hostname and port arguments.
            {
                provideCert = true;
                cert_fn     = args[0];
                key_fn      = args[1];
                start      += 2;
            }

            string server_hostname = args[start];
            int    port            = 0;

            try
            {
                port = int.Parse(args[start + 1]);
            }
            catch
            {
                CrestronConsole.ConsoleCommandResponse("Error: port number passed in is not numeric");
                return;
            }

            if (port > 65535 || port < 0)
            {
                CrestronConsole.ConsoleCommandResponse("Port number is out of range\r\n");
                return;
            }

            int bufsize = 100; // This is simply a hard-coded buffer size for this example

            if (client == null)
            {
                PrintAndLog("Instantiating a new client object...");
                try
                {
                    client = new SecureTCPClient(server_hostname, port, bufsize);
                    client.SocketStatusChange += new SecureTCPClientSocketStatusChangeEventHandler(clientSocketStatusChange);
                }
                catch (Exception e)
                {
                    PrintAndLog("Error encountered while instantiating the client object: " + e.Message);
                    return;
                }
            }
            // client object already exists; just update the destination hostname/port.
            // This allows to user to simply run connect again if the connection fails, possibly trying a new host/port
            else
            {
                client.AddressClientConnectedTo = server_hostname;
                client.PortNumber = port;
            }

            if (provideCert)
            {
                X509Certificate cert;
                byte[]          key;

                // Populate cert and key
                loadCertAndKey(cert_fn, key_fn, out cert, out key);

                // Set the client's certificate and private key

                /*
                 * The X509Certificate passed to SetClientCertificate should have the following attributes in these extension
                 * fields:
                 *
                 * [...]
                 * X509v3 Basic Constraints: critical
                 *     CA:FALSE
                 * X509v3 Key Usage: critical
                 *     Digital Signature, Key Encipherment, Key Agreement
                 * X509v3 Extended Key Usage:
                 *     TLS Web Client Authentication, TLS Web Server Authentication
                 * [...]
                 */
                // Only call SetClientCertificate and SetClientPrivateKey if loadCertAndKey succeeded in populating cert and key.
                // Otherwise, the client will be associated with a default key and certificate determined by the control system's SSL settings
                if (cert != null && key != null)
                {
                    PrintAndLog("Associating user-specified certificate and key with client...");
                    client.SetClientCertificate(cert);

                    // The user-provided private key set here must correspond to the public key embedded in the client's certificate
                    client.SetClientPrivateKey(key);
                }
                else
                {
                    PrintAndLog("Associating default certificate and key with client...");
                }
            }

            SocketErrorCodes err;

            ErrorLog.Notice("Trying to connect with server...");
            try
            {
                // clientConnectCallback gets invoked once client either
                // connects successfully or encounters an error
                err = client.ConnectToServerAsync(clientConnectCallback);
                PrintAndLog("ConnectToServerAsync returned: " + err);
            }
            catch (Exception e)
            {
                PrintAndLog("Error connecting to server: " + e.Message);
            }
        }