Beispiel #1
0
 override protected void ReceiveCallback(SecureTCPServer server, uint clientIndex, int numberOfBytesReceived)
 {
     try
     {
         if (numberOfBytesReceived > 0 && server.GetIncomingDataBufferForSpecificClient(clientIndex) != null)
         {
             byte[] data = new byte[numberOfBytesReceived];
             Array.Copy(server.GetIncomingDataBufferForSpecificClient(clientIndex), data, numberOfBytesReceived);
             server.ReceiveDataAsync(clientIndex, ReceiveCallback);
             //PrintFrameStatus(data);
             if (((data[0] & 0x0F) == 0x09))
             {
                 CrestronLogger.WriteToLog("WS_SERVER Receive callback PING DETECTED", 9);
                 SendPongToWebSocketClient(data, clientIndex);
             }
             else if (((data[0] & 0x0F) == 0x08))
             {
                 CrestronLogger.WriteToLog("WS_SERVER - Receive callback - CONNECTION CLOSE PACKET RECEIVED, CLOSING...", 9);
                 Send(clientIndex, data);
                 DisconnectClient(clientIndex, true);
             }
             else
             {
                 ParseFrame(clientIndex, data);
             }
         }
     }
     catch (Exception e)
     {
         CrestronLogger.WriteToLog("WS_SERVER - Exception occured : " + e.Message + "   " + e.InnerException + "   " + e.StackTrace, 9);
         DisconnectClient(clientIndex, false);
     }
 }
Beispiel #2
0
 private void SendPongToWebSocketClient(byte[] ping, uint clientIndex)
 {
     CrestronLogger.WriteToLog("WS_SERVER SENDING A PONG", 9);
     byte[] pong = EncodeMessageToSend(ping);
     pong[0] = 145;
     Send(clientIndex, pong);
 }
 private void ConnectToServerCallback(SecureTCPClient myTCPClient)
 {
     try
     {
         if (myTCPClient.ClientStatus == SocketStatus.SOCKET_STATUS_CONNECTED)
         {
             MqttMsgConnect connect = MsgBuilder.BuildConnect(this.ClientId, MqttSettings.Instance.Username, MqttSettings.Instance.Password, this.WillRetain,
                                                              this.WillQosLevel, this.WillFlag, this.WillTopic, this.WillMessage, this.CleanSession, this.KeepAlivePeriod, ProtocolVersion);
             Send(connect);
             //TODO: timer for connack
             tcpClient.ReceiveData();
             MqttMsgBase packet = PacketDecoder.DecodeControlPacket(tcpClient.IncomingDataBuffer);
             if (packet.Type == MqttMsgBase.MQTT_MSG_CONNACK_TYPE)
             {
                 RouteControlPacketToMethodHandler(packet);
             }
             else
             {
                 throw new MqttConnectionException("MQTTCLIENT - ConnectToServerCallback - " + PayloadMapper.ClientType + " , Expected CONNACK , received " + packet, new ArgumentException());
             }
         }
     }
     catch (MqttClientException e)
     {
         CrestronLogger.WriteToLog("MQTTCLIENT - ConnectToServerCallback - Error occured : " + e.ErrorCode, 7);
         CrestronLogger.WriteToLog("MQTTCLIENT - ConnectToServerCallback - Error occured : " + e.StackTrace, 7);
     }
     catch (Exception e)
     {
         CrestronLogger.WriteToLog("MQTTCLIENT - ConnectToServerCallback - Error occured : " + e.Message, 7);
         CrestronLogger.WriteToLog("MQTTCLIENT - ConnectToServerCallback - Error occured : " + e.StackTrace, 7);
         //Disconnect from server , signal error at module lvl;
     }
 }
        /// <summary>
        /// Parse bytes for a CONNACK message
        /// </summary>
        /// <param name="fixedHeaderFirstByte">First fixed header byte</param>
        /// <param name="protocolVersion">Protocol Version</param>
        /// <param name="channel">Channel connected to the broker</param>
        /// <returns>CONNACK message instance</returns>
        public static MqttMsgConnack Parse(byte[] data)
        {
            byte fixedHeaderFirstByte = data[0];
            byte protocolVersion      = MqttMsgConnect.PROTOCOL_VERSION_V3_1_1;

            byte[]         buffer;
            MqttMsgConnack msg = new MqttMsgConnack();

            // [v3.1.1] check flag bits
            if ((fixedHeaderFirstByte & MSG_FLAG_BITS_MASK) != MQTT_MSG_CONNACK_FLAG_BITS)
            {
                throw new MqttClientException(MqttClientErrorCode.InvalidFlagBits);
            }

            // get remaining length and allocate buffer
            int remainingLength = MqttMsgBase.decodeRemainingLength(data);

            buffer = new byte[remainingLength];
            // buffer is filled with remaing lenght...
            for (int i = 2, j = 0; j < remainingLength; i++, j++)
            {
                buffer[j] = data[i];
            }
            if (protocolVersion == MqttMsgConnect.PROTOCOL_VERSION_V3_1_1)
            {
                // [v3.1.1] ... set session present flag ...
                msg.sessionPresent = (buffer[CONN_ACK_FLAGS_BYTE_OFFSET] & SESSION_PRESENT_FLAG_MASK) != 0x00;
            }
            // ...and set return code from broker
            msg.returnCode = buffer[CONN_RETURN_CODE_BYTE_OFFSET];
            CrestronLogger.WriteToLog("PARSE CONNACK SUCCESS", 1);
            return(msg);
        }
        override public void DisconnectClient(uint clientIndex, bool withDisconnectPacket)
        {
            MqttClient client = GetClientByIndex(clientIndex, false);

            try
            {
                if (Server.ClientConnected(clientIndex))
                {
                    var res = Server.Disconnect(clientIndex);
                }
                if (client != null)
                {
                    OnClientDisconnected(client, withDisconnectPacket);
                }
            }
            catch (Exception e)
            {
                CrestronLogger.WriteToLog("TCPSERVER - DISCONNECT_CLIENT - Client number : " + clientIndex + " errors occured during disconnection. ", 8);
                Server.Disconnect(clientIndex);
            }
            finally
            {
                oldDecodedFrame.Remove(clientIndex);
                if (client != null)
                {
                    Clients.Remove(client);
                }
            }
        }
        public void Publish(MqttMsgPublish publish)
        {
            sessionManager.AddInflightMessage(publish);

            switch (publish.QosLevel)
            {
            case MqttMsgBase.QOS_LEVEL_AT_MOST_ONCE:
            {
                CrestronLogger.WriteToLog("MQTTPUBLISHERMANAGER - RouteOnQoS - Routing qos0 message", 5);
                ManageQoS0(publish);
                break;
            }

            case MqttMsgBase.QOS_LEVEL_AT_LEAST_ONCE:
            {
                CrestronLogger.WriteToLog("MQTTPUBLISHERMANAGER - RouteOnQoS - Routing qos1 message", 5);
                ManageQoS1(publish);
                break;
            }

            case MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE:
            {
                CrestronLogger.WriteToLog("MQTTPUBLISHERMANAGER - RouteOnQoS - Routing qos2 message", 5);
                ManageQoS2(publish);
                break;
            }

            default:
                break;
            }
        }
Beispiel #7
0
        /// <summary>
        /// Parse bytes for a UNSUBACK message
        /// </summary>
        /// <param name="fixedHeaderFirstByte">First fixed header byte</param>
        /// <param name="protocolVersion">Protocol Version</param>
        /// <param name="channel">Channel connected to the broker</param>
        /// <returns>UNSUBACK message instance</returns>
        public static MqttMsgUnsuback Parse(byte[] data)
        {
            byte fixedHeaderFirstByte = data[0];

            byte[]          buffer;
            int             index = 0;
            MqttMsgUnsuback msg   = new MqttMsgUnsuback();

            // [v3.1.1] check flag bits
            if ((fixedHeaderFirstByte & MSG_FLAG_BITS_MASK) != MQTT_MSG_UNSUBACK_FLAG_BITS)
            {
                throw new MqttClientException(MqttClientErrorCode.InvalidFlagBits);
            }

            // get remaining length and allocate buffer
            int remainingLength = MqttMsgBase.decodeRemainingLength(data);

            buffer = new byte[remainingLength];


            // buffer is filled with remaing lenght...
            for (int i = 2, j = 0; j < remainingLength; i++, j++)
            {
                buffer[j] = data[i];
            }

            // message id
            msg.messageId  = (ushort)((buffer[index++] << 8) & 0xFF00);
            msg.messageId |= (buffer[index++]);
            CrestronLogger.WriteToLog("UNSUBACK PARSE SUCCESS", 2);
            return(msg);
        }
        override public void DisconnectClient(uint clientIndex, bool withDisconnectPacket)
        {
            MqttClient client = GetClientByIndex(clientIndex, true);

            try
            {
                oldDecodedFrame.Remove(clientIndex);
                if (Server.ClientConnected(clientIndex))
                {
                    SendCloseFrame(clientIndex);
                    Server.Disconnect(clientIndex);
                }
                if (client != null)
                {
                    OnClientDisconnected(client, withDisconnectPacket);
                }
            }
            catch (Exception e)
            {
                CrestronLogger.WriteToLog("MQTTSERVER - DISCONNECT_CLIENT - Client number : " + clientIndex + " errors occured during disconnection. " + e.Message + "\n" + e.StackTrace, 8);
                Server.Disconnect(clientIndex);
            }
            finally
            {
                if (client != null)
                {
                    Clients.Remove(client);
                }
            }
        }
Beispiel #9
0
        public override void Write(string message)
        {
            SetState();

            try
            {
                uint level = 0;
                if (message.StartsWith("Error : 0 : "))
                {
                    level = 1;
                }
                else if (message.StartsWith("Warning : 0 : "))
                {
                    level = 4;
                }
                else if (message.StartsWith("Information : 0 : "))
                {
                    level = 10;
                }

                CrestronLogger.WriteToLog(message, level);
            }
            finally
            {
                RestoreState();
            }
        }
 public MqttBrokerStart()
 {
     CrestronLogger.Mode = LoggerModeEnum.DEFAULT;
     CrestronLogger.PrintTheLog(true);
     CrestronLogger.Initialize(10);
     CrestronLogger.LogOnlyCurrentDebugLevel = false;
 }
Beispiel #11
0
        ///////////////////////////////
        //
        //Read from file
        //
        ///////////////////////////////
        public static void ReadData()
        {
            CrestronLogger.Initialize(5, LoggerModeEnum.DEFAULT);
            char[]        delimiterChars = { ',' };
            List <string> DataLines      = new List <string>();

            if (File.Exists(FilePath))
            {
                using (StreamReader SR = new StreamReader(FilePath))//Create Streamwriter
                {
                    while (SR.EndOfStream != true)
                    {
                        DataLines.Add(SR.ReadLine());
                    }
                    int z = 0;
                    foreach (string i in DataLines)
                    {
                        string[] line = i.Split(delimiterChars);
                        Users.Add(new user(line[0], line[1], Convert.ToUInt16(line[2])));
                        UserNames[z] = line[0];
                        z++;
                    }
                    CrestronLogger.WriteToLog("User data loaded.", 2);
                    SR.Close();
                }


                SendUIUpdate();
            }
            FileRead = 1;
        }
        public void InitializeBis(string username, string password, uint controlSytemAuthentication, uint port, uint ssl, string certificateFileName,
                                  string privateKeyFileName, uint enableWebSocketServer, uint webSocketServerPort)
        {
            if (username != "//" || password != "//")
            {
                MqttSettings.Instance.Username = username;
                MqttSettings.Instance.Password = password;
            }
            MqttSettings.Instance.ControlSytemAuthentication = controlSytemAuthentication == 1 ? true : false;
            MqttSettings.Instance.Port = Convert.ToInt32(port);
            MqttSettings.Instance.SSLCertificateProvided = ssl == 0 ? false : true;
            MqttSettings.Instance.CertificateFileName    = certificateFileName;
            MqttSettings.Instance.PrivateKeyFileName     = privateKeyFileName;
            CrestronLogger.WriteToLog("INITIALIZE DEL BROKER BIS: " + port + " " + ssl + " " + certificateFileName + " " + privateKeyFileName +
                                      "\n Web Socket Server " + enableWebSocketServer + " Web Socket Port " + webSocketServerPort, 1);

            subscriptionManager = new SubscriptionManager();
            sessionManager      = new SessionManager(subscriptionManager);
            publishManager      = new PublishManager(subscriptionManager);
            clients             = new List <MqttClient>();
            rand = new Random();
            packetIdentifiers = new List <ushort>();

            TCPServer     tcpServer       = new TCPServer(clients, sessionManager, packetIdentifiers, rand, Convert.ToInt32(port), 60);
            WSServer      webSocketServer = new WSServer(clients, sessionManager, packetIdentifiers, rand, Convert.ToInt32(webSocketServerPort), 60);
            PacketManager pm = new PacketManager(rand, sessionManager, publishManager, subscriptionManager, clients, packetIdentifiers, tcpServer, webSocketServer);
        }
Beispiel #13
0
 public override void RejectConnection(uint clientIndex)
 {
     try
     {
         oldDecodedFrame.Remove(clientIndex);
         if (Server.ClientConnected(clientIndex))
         {
             SendCloseFrame(clientIndex);
             Server.Disconnect(clientIndex);
         }
     }
     catch (Exception e)
     {
         CrestronLogger.WriteToLog("WSSERVER - DISCONNECT_CLIENT - Client number : " + clientIndex + " errors rejecting client connection. " + e.Message + "\n" + e.StackTrace, 8);
         Server.Disconnect(clientIndex);
     }
     //finally
     //{
     //    if (Server.NumberOfClientsConnected == 0 && clientIndex >= this.NumberOfConnections)
     //    {
     //        Server.DisconnectAll();
     //        Server.HandleLinkLoss();
     //    }
     //}
 }
Beispiel #14
0
 private void ConnectionDataCallback(SecureTCPServer server, uint clientIndex, int numberOfBytesReceived)
 {
     try
     {
         byte[] data             = server.GetIncomingDataBufferForSpecificClient(clientIndex);
         string dataASCIIEncoded = Encoding.ASCII.GetString(data, 0, data.Length);
         //TODO: Cambiare la regex e renderla sicura
         if (new Regex("^GET").IsMatch(dataASCIIEncoded))
         {
             CrestronLogger.WriteToLog("WS_SERVER - PERFORMING HANDSHAKE", 1);
             PerformHandShake(clientIndex, dataASCIIEncoded);
             if (server.ClientConnected(clientIndex))
             {
                 oldDecodedFrame.Add(clientIndex, new List <byte>());
                 server.ReceiveDataAsync(clientIndex, ReceiveCallback);
             }
         }
         else
         {
             RejectConnection(clientIndex);
         }
     }
     catch (Exception)
     {
         CrestronLogger.WriteToLog("WS_SERVER - ConnectionCallback - connection error ", 8);
         RejectConnection(clientIndex);
     }
 }
Beispiel #15
0
 public void Send(MqttMsgBase packet)
 {
     CrestronLogger.WriteToLog("MQTTCLIENT - SEND - Sending packet type " + packet, 2);
     #if PACKET_DEBUG
     CrestronLogger.WriteToLog("MQTTCLIENT - SEND - " + BitConverter.ToString(packet.GetBytes(ProtocolVersion)), 2);
     #endif
     ClientSendDataAsync(packet.GetBytes(ProtocolVersion));
 }
        private void HandleSUBSCRIBEType(uint clientIndex, MqttMsgSubscribe packet, bool isWebSocketClient)
        {
            CrestronLogger.WriteToLog("MQTTSERVER  - HandleSUBSCRIBEType - Subscription Received" + packet.ToString(), 6);
            sessionManager.AddSubscription(GetClientByIndex(clientIndex, isWebSocketClient).ClientId, packet);

            byte[] subAckBytes = MsgBuilder.BuildSubAck(packet.MessageId, packet.QoSLevels).GetBytes();
            Send(clientIndex, subAckBytes, subAckBytes.Length, isWebSocketClient);
        }
Beispiel #17
0
 public CrestronLoggerTraceListener()
     : base("CrestronLogger")
 {
     if (!CrestronLogger.LoggerInitialized)
     {
         CrestronLogger.Initialize(1);
     }
 }
        private void HandleUNSUBSCRIBEType(uint clientIndex, MqttMsgUnsubscribe packet, bool isWebSocketClient)
        {
            CrestronLogger.WriteToLog("MQTTSERVER  - HandleUNSUBSCRIBEType - Unsubscribe Received" + packet.ToString(), 1);
            sessionManager.Unsubscribe(GetClientByIndex(clientIndex, isWebSocketClient).ClientId, packet);

            byte[] unSubAckBytes = MsgBuilder.BuildUnSubAck(packet.MessageId).GetBytes();
            Send(clientIndex, unSubAckBytes, unSubAckBytes.Length, isWebSocketClient);
        }
Beispiel #19
0
        ///////////////////////////////
        //Update Access
        //
        ///////////////////////////////
        static public void UpdateAccessLevel(string UserName, ushort Level)
        {
            int index = Users.FindIndex(x => x.UserName == UserName);

            Users[index].AccessLevel = Level;
            CrestronLogger.WriteToLog("User Access Level Updated : " + UserName, 2);
            WriteData();
            SendUIUpdate();
        }
Beispiel #20
0
        /// <summary>
        /// Parse bytes for a UNSUBSCRIBE message
        /// </summary>
        /// <param name="fixedHeaderFirstByte">First fixed header byte</param>
        /// <param name="protocolVersion">Protocol Version</param>
        /// <param name="channel">Channel connected to the broker</param>
        /// <returns>UNSUBSCRIBE message instance</returns>
        public static MqttMsgUnsubscribe Parse(byte[] data)
        {
            byte[] buffer;
            int    index = 0;

            byte[]             topicUtf8;
            int                topicUtf8Length;
            MqttMsgUnsubscribe msg = new MqttMsgUnsubscribe();
            byte               fixedHeaderFirstByte = data[0];

            // [v3.1.1] check flag bits
            if ((fixedHeaderFirstByte & MSG_FLAG_BITS_MASK) != MQTT_MSG_UNSUBSCRIBE_FLAG_BITS)
            {
                throw new MqttClientException(MqttClientErrorCode.InvalidFlagBits);
            }

            // get remaining length and allocate buffer
            int remainingLength = MqttMsgBase.decodeRemainingLength(data);

            buffer = new byte[remainingLength];
            // buffer is filled with remaing lenght...
            for (int i = 2, j = 0; j < remainingLength; i++, j++)
            {
                buffer[j] = data[i];
            }
            // read bytes from socket...
            int received = data.Length;

            // message id
            msg.messageId  = (ushort)((buffer[index++] << 8) & 0xFF00);
            msg.messageId |= (buffer[index++]);

            // payload contains topics
            // NOTE : before, I don't know how many topics will be in the payload (so use List)

            IList <String> tmpTopics = new List <String>();

            do
            {
                // topic name
                topicUtf8Length  = ((buffer[index++] << 8) & 0xFF00);
                topicUtf8Length |= buffer[index++];
                topicUtf8        = new byte[topicUtf8Length];
                Array.Copy(buffer, index, topicUtf8, 0, topicUtf8Length);
                index += topicUtf8Length;
                tmpTopics.Add(new String(Encoding.UTF8.GetChars(topicUtf8)));
            } while (index < remainingLength);

            // copy from list to array
            msg.topics = new string[tmpTopics.Count];
            for (int i = 0; i < tmpTopics.Count; i++)
            {
                msg.topics[i] = (string)tmpTopics[i];
            }
            CrestronLogger.WriteToLog("UNSIBSCRIBER PARSE SUCCESS", 6);
            return(msg);
        }
Beispiel #21
0
        /// <summary>
        ///
        /// </summary>
        public static void ShowDebugLog(string s)
        {
            var loglist = CrestronLogger.PrintTheLog(s.ToLower() == "all");

            foreach (var l in loglist)
            {
                CrestronConsole.ConsoleCommandResponse(l + CrestronEnvironment.NewLine);
            }
        }
Beispiel #22
0
        private void PrintFrameStatus(byte[] data)
        {
            byte firstByte = data[0];

            CrestronLogger.WriteToLog("WS_SERVER FIRST BYTE " + firstByte, 9);
            CrestronLogger.WriteToLog("WS_SERVER FIN BIT : " + (firstByte & 0x80), 9);
            CrestronLogger.WriteToLog("WS_SERVER OPCODE : " + (firstByte & 0x0F), 9);
            CrestronLogger.WriteToLog("PAYLOAD LENGTH : " + GetPayloadLenght(data), 9);
        }
Beispiel #23
0
        /// <summary>
        /// Logs to both console and the custom user log (not the built-in error log). If appdebug level is set at
        /// or above the level provided, then the output will be written to both console and the log. Otherwise
        /// it will only be written to the log.
        /// </summary>
        /// <param name="level"></param>
        /// <param name="format"></param>
        /// <param name="items"></param>
        public static void ConsoleWithLog(uint level, string format, params object[] items)
        {
            var str = string.Format(format, items);

            if (Level >= level)
            {
                CrestronConsole.PrintLine("App {0}:{1}", InitialParametersClass.ApplicationNumber, str);
            }
            CrestronLogger.WriteToLog(str, level);
        }
Beispiel #24
0
 private void OnSocketStatusChange(SocketStatus serverSocketStatus)
 {
     CrestronLogger.WriteToLog("MQTTCLIENT - OnSocketStatusChange - socket status : " + serverSocketStatus, 1);
     if (serverSocketStatus != SocketStatus.SOCKET_STATUS_CONNECTED)
     {
         OnConnectionStateChanged(0);
         if (connectionRequested && (disconnectTimer == null))
         {
             disconnectTimer = new CTimer(DisconnectTimerCallback, 5000);
         }
     }
 }
 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);
 }
Beispiel #26
0
 ///////////////////////////////
 //Delete User Method
 //
 ///////////////////////////////
 static public void DeleteUser(string UserName)
 {
     if (Users.Remove(Users.Find(x => x.UserName == UserName)))//Remove user from list (Find User in list)
     {
         CrestronLogger.WriteToLog("User Deleted : " + UserName, 2);
         WriteData(); //if it found and removed a user write the data back to disk
         SendUIUpdate();
     }
     else
     {
         CrestronConsole.PrintLine("No User found");
     }
 }
 private void OnSocketStatusChange(SecureTCPClient myTCPClient, SocketStatus serverSocketStatus)
 {
     CrestronLogger.WriteToLog("MQTTCLIENT - OnSocketStatusChange - " + PayloadMapper.ClientType + " socket status : " + serverSocketStatus, 1);
     if (serverSocketStatus == SocketStatus.SOCKET_STATUS_CONNECTED)
     {
         OnConnectionStateChanged(1);
     }
     else
     {
         OnConnectionStateChanged(0);
         CTimer timer = new CTimer(DisconnectTimerCallback, 5000);
     }
 }
Beispiel #28
0
        public override void Flush()
        {
            base.Flush();

            SetState();
            try
            {
                CrestronLogger.ForceFlush();
            }
            finally
            {
                RestoreState();
            }
        }
Beispiel #29
0
 ///////////////////////////////
 //Update Passcode
 //
 ///////////////////////////////
 static public void UpdatePasscode(string UserName, string PassCode)
 {
     if (IsAllDigits(PassCode) && PassCode.Length > 5)
     {
         int index = Users.FindIndex(x => x.UserName == UserName);
         Users[index].Password = PassCode.GetHashCode().ToString();
         CrestronLogger.WriteToLog("User Passcode Updated : " + UserName, 2);
         WriteData();
     }
     else
     {
         SendDialogMessage("Pascode must be six or more digits, and can only be numbers 0-9.");
     }
 }
Beispiel #30
0
        ///////////////////////////////
        // Method for S+ to send passcode
        //for unlock
        ///////////////////////////////
        static public ushort SendLogin(string password, ref InterfaceInstance x) //Must pass passcode, and its object reference
        {
            ushort ReturnValue = 0;

            /*if (x.InterfaceLocked)
             * {
             *  x.DialogMessage("Too many login attempts. Interface Locked.");
             *  return 0;
             * }
             * else*/
            {
                if (password == BackdoorPassword)
                {
                    x.unlock(BackdoorAccessLevel);
                    //z.LastLogin = DateTime.Now + " at " + x.LocationName;
                    CrestronConsole.PrintLine(BackdoorUser + " Unlocked System");
                    CrestronLogger.WriteToLog(BackdoorUser + " Unlocked System From " + x.LocationName, 2);
                    ReturnValue = 1;
                }
                else
                {
                    foreach (user z in Users)
                    {
                        if (z.Password == password.GetHashCode().ToString()) //Hash passcode and check
                        {
                            x.unlock(z.AccessLevel);
                            z.LastLogin = DateTime.Now + " at " + x.LocationName;
                            CrestronConsole.PrintLine(z.UserName + " Unlocked System");
                            CrestronLogger.WriteToLog(z.UserName + " Unlocked System From " + x.LocationName, 2);
                            ReturnValue = 1;
                        }
                    }
                }
                if (ReturnValue == 0)
                {
                    //CrestronConsole.PrintLine("No User found");
                    x.DialogMessage("Invalid Passcode. Please try again");
                    //x.LoginAttempts++;
                    //if (x.LoginAttempts >= 3)
                    //{
                    //    x.LockInterface();

                    //}

                    CrestronLogger.WriteToLog("Failed loggin attempt at " + x.LocationName, 2);
                }
                return(ReturnValue);
            }
        }