示例#1
0
 /// <summary>
 /// Function verifies username and password, finding they in a DB.
 /// Проверяет имя пользователя и пароль, сопоставляя с записями в БД.
 /// </summary>
 /// <param name="username">Имя пользователя для проверки</param>
 /// <param name="password">Пароль в чистом виде (не хэш!)</param>
 /// <returns>При удачной проверке - true, если пользователя с этими username и password нет - false.</returns>
 public static bool CheckUserCredentials(string username, string password)
 {
     Logging.LogEvent(
         0, "Accounts", $"Checking user credentials ...\nUsername={username}\nPassword={password}"
         );
     try
     {
         List <object> sqlReqResult = DatabaseConnecting.ProcessSqlRequest(
             "SELECT id, name, passhash FROM users WHERE name = ?username",
             new List <MySqlParameter>()
         {
             new MySqlParameter("username", username)
         }
             );
         if (sqlReqResult.Count > 0)
         {
             if (BCrypt.Net.BCrypt.Verify(password, sqlReqResult[2].ToString()))
             {
                 Logging.LogEvent(1, "Accounts", "Credentials verifying success!");
                 return(true);
             }
         }
     }
     catch (Exception ex)
     {
         Logging.LogEvent(3, "Accounts", $"An error happened while checking credentials!\n{ex}");
     }
     Logging.LogEvent(2, "Accounts", "Credentials verifying failed!");
     return(false);
 }
示例#2
0
        public static Dictionary <string, object> GetMainSensorsValues(DateTime dt)
        {
            Logging.LogEvent(1, "HomeSensorApi", "GetMainSensorsValues(DateTime) started!");
            Dictionary <string, object> sensors_vals = new Dictionary <string, object>();

            try
            {
                List <object> sqlReqResult = DatabaseConnecting.ProcessSqlRequest(
                    $"SELECT id, valdatetime, IFNULL(temp, 0.00) AS temp, IFNULL(humidity, 0.00) AS humidity " +
                    $"FROM `sensors_values` " +
                    $"WHERE valdatetime < DATE_ADD('{dt:yyyy-MM-dd}', INTERVAL 1 DAY) " +
                    $"ORDER BY id DESC LIMIT 1"
                    );

                sensors_vals.Add("temperature", Convert.ToDouble(sqlReqResult[2]));
                sensors_vals.Add("humidity", Convert.ToDouble(sqlReqResult[3]));
                sensors_vals.Add("datetime", sqlReqResult[1]);
            }
            catch (Exception ex)
            {
                Logging.LogEvent(
                    3, "HomeSensorApi",
                    $"An error happened while receiving main sensors values!\n{ex}"
                    );
            }

            return(sensors_vals);
        }
示例#3
0
        private void GetSensorsValuesAndUpdate(DateTime dt)
        {
            Logging.LogEvent(0, "ControlPanelUpdater", $"Updating main sensors values... DT = {dt:dd.MM.yyyy,HH:mm}");
            try
            {
                label1.Text     = sensorsText[0];
                label2.Text     = sensorsText[1];
                label5.Text     = sensorsText[2];
                linkLabel1.Text = sensorsText[3];
                label3.Text     = sensorsText[4];

                System.Collections.Generic.Dictionary <string, object> reqResult = HomeSensor.GetMainSensorsValues(dt);

                if (reqResult.Count > 0)
                {
                    label1.Text =
                        Convert.ToDouble(reqResult["temperature"]).ToString() + " °C / " +
                        ((Convert.ToDouble(reqResult["temperature"]) * 9.00 / 5.00) + 32.00).ToString() + " °F";

                    sensorsToolTips[0].SetToolTip(
                        label1, sensorsToolTips[0].ToolTipTitle + reqResult["datetime"].ToString()
                        );

                    label2.Text = Convert.ToInt32(reqResult["humidity"]).ToString() + "%";

                    sensorsToolTips[1].SetToolTip(
                        label2, sensorsToolTips[1].ToolTipTitle + reqResult["datetime"].ToString()
                        );
                }
                else
                {
                    Logging.LogEvent(
                        2, "ControlPanelUpdater",
                        $"The server did not return sensors values. DT={dt:dd.MM.yyyy HH:mm:ss}"
                        );
                }

                System.Collections.Generic.List <object> sqlReqWateringResult =
                    DatabaseConnecting.ProcessSqlRequest(
                        $"SELECT id, valdatetime, flowernum, state FROM `watering` " +
                        $"WHERE valdatetime > ('{dt:yyyy-MM-dd}') " +
                        $"AND valdatetime < DATE_ADD('{dt:yyyy-MM-dd}', INTERVAL 1 DAY) " +
                        $"ORDER BY id DESC LIMIT 1"
                        );

                if (sqlReqWateringResult.Count > 0)
                {
                    label3.Text += $" {Convert.ToDateTime(sqlReqWateringResult[1]):dd.MM.yyyy HH:mm:ss}";
                }
            }
            catch (Exception ex)
            {
                Logging.LogEvent(
                    3, "ControlPanelUpdater",
                    $"An error happened while updating main sensors values!\n{ex}"
                    );
                MessageBox.Show($"Произошла ошибка!\n{ex.Message}");
            }
        }
 private void RenderDoorbellImage()
 {
     pictureBox1.Image = DatabaseConnecting.GetImageByRequest(
         $"SELECT picture FROM doorbell WHERE photonum = {imageNavPos} ORDER BY photosid DESC LIMIT 1"
         );
     label1.Text =
         Languages.GetLocalizedString("DoorbellDateTime", "Doorbell rang at:") +
         DatabaseConnecting.ProcessSqlRequest(
             $"SELECT camdatetime FROM doorbell WHERE photonum = 1 ORDER BY photosid DESC LIMIT 1"
             )[0];
 }
        private void GetSensorsValuesAndUpdate(DateTime dt, bool clearTable = true)
        {
            Logging.LogEvent(
                0, "OtherSensors",
                $"Updating custom sensors values... DT = {dt:dd.MM.yyyy,HH:mm}"
                );
            try
            {
                List <object> sqlReqResult = DatabaseConnecting.ProcessSqlRequest(
                    $"SELECT id, valdatetime, sensor_name, sensor_val " +
                    $"FROM `other_sensors` " +
                    $"WHERE valdatetime < DATE_ADD('{dt:yyyy-MM-dd}', INTERVAL 1 DAY) " +
                    $"AND id > 0 ORDER BY valdatetime DESC"
                    );

                List <string>     sensorsNames = new List <string>();
                List <HomeSensor> otherSensors = new List <HomeSensor>();
                for (int i = 0; i < sqlReqResult.Count; i += 4)
                {
                    if (sensorsNames.Contains(sqlReqResult[i + 2].ToString()))
                    {
                        continue;
                    }
                    sensorsNames.Add(sqlReqResult[i + 2].ToString());
                    otherSensors.Add(new HomeSensor(
                                         Convert.ToInt32(sqlReqResult[i + 0]),
                                         Convert.ToDouble(sqlReqResult[i + 3]),
                                         Convert.ToDateTime(sqlReqResult[i + 1]),
                                         sqlReqResult[i + 2].ToString()
                                         ));
                }

                if (clearTable)
                {
                    dataGridView1.Rows.Clear();
                }

                foreach (HomeSensor shsensor in otherSensors)
                {
                    string[] sensorValArr = new string[3]
                    {
                        shsensor.Dt.ToString(), shsensor.Name, shsensor.Value.ToString()
                    };
                    dataGridView1.Rows.Add(sensorValArr);
                }
            }
            catch (Exception ex)
            {
                Logging.LogEvent(3, "OtherSensors", $"An error happened while updating custom sensors values!\n{ex}");
                MessageBox.Show("Произошла ошибка!\n" + ex.Message);
            }
        }
示例#6
0
 private void GetLightData()
 {
     lampCheckboxes = new CheckBox[4]
     {
         checkBox1, checkBox2, checkBox3, checkBox4
     };
     for (int i = 1; i <= 4; i++)
     {
         System.Collections.Generic.List <object> lampResult = DatabaseConnecting.ProcessSqlRequest(
             $"SELECT id, valdatetime, lampnum, state from `light` WHERE (lampnum = {i}) ORDER BY id DESC LIMIT 1"
             );
         if (lampResult.Count > 0)
         {
             lampCheckboxes[i - 1].Checked = Convert.ToBoolean(lampResult[3]);
         }
     }
 }
示例#7
0
        /// <summary>
        /// Function receives advanced user account data - identifier and privileges.
        /// Получает дополнительные данные о пользователе - идентификатор и привилегии.
        /// </summary>
        public static void GetUserData()
        {
            try
            {
                userid = Convert.ToInt32(
                    DatabaseConnecting.ProcessSqlRequest(
                        "SELECT id FROM users WHERE name = ?username ORDER BY id LIMIT 1",
                        new List <MySqlParameter>()
                {
                    new MySqlParameter("username", username)
                }
                        )[0]
                    );
            }
            catch (Exception ex)
            {
                Logging.LogEvent(
                    3, "Accounts",
                    $"Can\'t receive user identifier!\n{ex}"
                    );
            }

            try
            {
                userprivs = Convert.ToInt32(
                    DatabaseConnecting.ProcessSqlRequest(
                        "SELECT privs FROM users WHERE name = ?username ORDER BY id DESC LIMIT 1",
                        new List <MySqlParameter>()
                {
                    new MySqlParameter("username", username)
                }
                        )[0]
                    );
            }
            catch (Exception ex)
            {
                Logging.LogEvent(
                    3, "Accounts",
                    $"Can\'t receive user privileges!\nUsername={username}\nID={userid}\n{ex}"
                    );
            }
        }
示例#8
0
 /// <summary>
 /// Function registers user.
 /// Регистрирует пользователя.
 /// </summary>
 /// <param name="_username">Имя пользователя</param>
 /// <param name="_password">Пароль в чистом виде (не хэш!)</param>
 /// <returns>При успешной регистрации - true, иначе - false</returns>
 public static bool RegisterUser(string _username, string _password)
 {
     Logging.LogEvent(1, "Accounts", "Trying to register user ...");
     if (userprivs == 0)
     {
         DatabaseConnecting.ProcessSqlRequest(
             "INSERT INTO users(name, passhash, privs) VALUES (?username, ?passhash, 1)",
             new List <MySqlParameter>()
         {
             new MySqlParameter("username", _username.Trim()),
             new MySqlParameter("passhash", BCrypt.Net.BCrypt.HashPassword(_password))
         }, true
             );
         return(true);
     }
     else
     {
         Logging.LogEvent(2, "Accounts", "Insufficient privileges! (Registration)");
     }
     return(false);
 }
示例#9
0
        public MainForm()
        {
            InitializeComponent();

            Logging.DeleteLogFile();

            #region Checking configuration files
            foreach (string impfile in importantFiles)
            {
                if (!File.Exists(impfile))
                {
                    Logging.LogEvent(2, "ConfFilesCheck", $"File {impfile} not found!");
                    ExtractFiles();
                    break;
                }
            }
            #endregion

            #region Connecting to DB
            DatabaseConnecting.ReadDefaultDbParams();
            if (!DatabaseConnecting.ConnectToDb())
            {
                MessageBox.Show(
                    "An error happened while connecting to database! Application will be closed.", "Error",
                    MessageBoxButtons.OK, MessageBoxIcon.Error
                    );
                Close();
            }
            ;
            #endregion

            Accounts.LoadCredentials();

            #region Receiving "last update" value
            List <object> lastUpdateResult = DatabaseConnecting.ProcessSqlRequest(
                "SELECT valdatetime FROM `other_sensors` WHERE id = 0 LIMIT 1"
                );
            if (lastUpdateResult.Count < 1)
            {
                Logging.LogEvent(
                    4, "BackgroundMonitor",
                    "The server did not return last update field! Timer will be disabled."
                    );
                notifyIcon1.ShowBalloonTip(
                    2000, "AchSmartHome",
                    Languages.GetLocalizedString(
                        "GetUpdateResultError",
                        "The server did not return the critical system value \"last update\"! " +
                        "Background process will be terminated."
                        ),
                    ToolTipIcon.Error);
                timer1.Enabled = false;
                timer1.Stop();
            }
            lastUpdateDt = DateTime.Parse(lastUpdateResult[0].ToString());
            #endregion

            GlobalSettings.InitThemeAndLang(Controls, this);
            saveFileDialog1.Title = Languages.GetLocalizedString("ChooseLogDest", "Choose Log-file Copying Destination");

            panel1               = new Panel();
            panel1.Name          = "panel1";
            panel1.Location      = new System.Drawing.Point(12, 51);
            panel1.AutoSize      = true;
            panel1.ControlAdded += new ControlEventHandler(PanelChanged);
            Controls.Add(panel1);

            while (Accounts.username.Trim().Equals(""))
            {
                Logging.LogEvent(1, "WindowInit", "User is not logged in. Opening connection dialog ...");
                ConnectForm  cf = new ConnectForm();
                DialogResult dr = cf.ShowDialog();
                if (dr == DialogResult.Cancel)
                {
                    CloseApp();
                }
            }

            ReplacePanel <ControlPanel>();
            панельНавигацииToolStripMenuItem.Checked = GlobalSettings.showNavigationPanel;
            ChangeNavPanelVisibility(GlobalSettings.showNavigationPanel);
        }