Пример #1
0
        public void WritingPas(object objectInfo)
        {
            foreach (Form1.Pas pas in Form1._form._newRoot.pases)
            {
                string pubPath  = Environment.CurrentDirectory;
                string dataPath = pubPath + "\\..\\..\\data\\indications\\" +
                                  DateTime.Now.Year.ToString() +
                                  "\\" + DateTime.Now.Year.ToString() +
                                  "-" + DateTime.Now.Month.ToString() +
                                  "-" + DateTime.Now.Day.ToString() +
                                  "\\pressure";
                System.IO.Directory.CreateDirectory(dataPath);

                BinaryFormatter formatter = new BinaryFormatter();
                try
                {
                    using (FileStream fs = new FileStream(dataPath + "\\pas_" + pas.id + ".dat", FileMode.Append, FileAccess.Write, FileShare.Read))
                    {
                        using (BinaryWriter writer = new BinaryWriter(fs))
                        {
                            writer.Write(DateTime.Now.ToString());
                            writer.Write(pas.pressure);
                        }
                        fs.Close();
                    }
                }
                catch (Exception e)
                {
                    Mylog.writeExc("класс: " + GetType().Name + ". метод: " + System.Reflection.MethodBase.GetCurrentMethod().Name + e.Message);
                    return;
                }
            }
        }
Пример #2
0
      public void uploadIMG(string name)
      {
          try
          {
              // Создаем объект FtpWebRequest - он указывает на файл, который будет создан
              FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://" + host + "/img/" + name);
              // устанавливаем метод на загрузку файлов
              request.Method = WebRequestMethods.Ftp.UploadFile;
              // если требуется логин и пароль, устанавливаем их
              request.Credentials = new NetworkCredential(login, password);
              //request.EnableSsl = true; // если используется ssl

              // создаем поток для загрузки файла
              FileStream fs           = new FileStream(imgsPath + "\\" + name, FileMode.Open);
              byte[]     fileContents = new byte[fs.Length];
              fs.Read(fileContents, 0, fileContents.Length);
              fs.Close();
              request.ContentLength = fileContents.Length;

              // пишем считанный в массив байтов файл в выходной поток
              Stream requestStream = request.GetRequestStream();
              requestStream.Write(fileContents, 0, fileContents.Length);
              requestStream.Close();

              // получаем ответ от сервера в виде объекта FtpWebResponse
              FtpWebResponse response = (FtpWebResponse)request.GetResponse();
              response.Close();
          }
          catch (Exception exc)
          {
              Mylog.writeExc("класс: " + GetType().Name + ". метод: " + System.Reflection.MethodBase.GetCurrentMethod().Name + exc.Message);

              return;
          }
      }
Пример #3
0
      public void uploadIndications(string path)
      {
          //загрузить файл если размер разный
          using (Session session = new Session())
          {
              try
              {
                  session.Open(sessionOptions);

                  DirectoryInfo directory = new DirectoryInfo(@indicationsPath + path);
                  foreach (var fileInfo in directory.GetFiles())
                  {
                      if (!session.FileExists("/indications" + path.Replace("\\", "/") + "/" + fileInfo.Name))
                      {
                          session.PutFiles(indicationsPath + path + "\\" + fileInfo.Name, "/indications" + path.Replace("\\", "/") + "/" + fileInfo.Name);
                      }
                      else
                      {
                          //если существует файл, проверяем размеры
                          long fileLength = session.GetFileInfo("/indications" + path.Replace("\\", "/") + "/" + fileInfo.Name).Length;
                          //MessageBox.Show(fileLength.ToString() + " < " + fileInfo.Length.ToString());
                          if (fileLength < fileInfo.Length)
                          {
                              session.PutFiles(indicationsPath + path + "\\" + fileInfo.Name, "/indications" + path.Replace("\\", "/") + "/" + fileInfo.Name);
                          }
                      }
                  }
                  session.Close();
              }catch (Exception exc)
              {
                  Mylog.writeExc("класс: " + GetType().Name + ". метод: " + System.Reflection.MethodBase.GetCurrentMethod().Name + exc.Message);
                  return;
              }
          }
      }
Пример #4
0
            public void Pool(object objectInfo)
            {
                if (_modbusIpMaster != null)
                {
                    try
                    {
                        // получаем температуру влажность
                        var temps = _modbusIpMaster.ReadInputRegisters(Convert.ToByte(sirialID), 0, 2);
                        pressure = System.Math.Round(FloatRegToString(temps[0], temps[1]), 2).ToString();
                        // Form1._form.CreatModbIPMaster("ivit", ivit.id, ivit.ip, ivit.port);
                    }
                    catch (Exception exc)
                    {
                        if (exc.Message == "Read resulted in 0 bytes returned.")
                        {
                            return;
                        }
                        if (exc.Message == "Операция не разрешается на неподключенных сокетах.")
                        {
                            CreatModbIPMaster();
                            return;
                        }

                        Mylog.writeExc("класс: " + GetType().Name + ". метод: " + System.Reflection.MethodBase.GetCurrentMethod().Name + exc.Message);
                        return;
                        // Form1._form.richTextBox1.Invoke(new Action(() => Form1._form.richTextBox1.Text = Form1._form.richTextBox1.Text + "\n" + name + ": - " + exc.Message));
                        //Form1._form.richTextBox1.Text = exc.Message;
                    }
                }
                else
                {
                    CreatModbIPMaster();
                }
            }
Пример #5
0
 //прекращает опрос ивита
 public void stopSynch()
 {
     try
     {
         timerSynch.Change(System.Threading.Timeout.Infinite, 0);
         timerSynch.Dispose();
     }
     catch (Exception exc)
     {
         Mylog.writeExc("класс: " + GetType().Name + ". метод: " + System.Reflection.MethodBase.GetCurrentMethod().Name + exc.Message);
         return;
     }
 }
Пример #6
0
 //прекращает опрос ивита
 public void stopPooling()
 {
     try
     {
         timer.Change(System.Threading.Timeout.Infinite, 0);
         timer.Dispose();
     }
     catch (Exception exc)
     {
         Mylog.writeExc("класс: " + GetType().Name + ". метод: " + System.Reflection.MethodBase.GetCurrentMethod().Name + exc.Message);
         return;
     }
     pressure = "0";
     // Form1._form.richTextBox1.Text = Form1._form.richTextBox1.Text + "\r\n IVIT #" + id + " stop";
 }
Пример #7
0
 public async Task UploadFile(string path)
 {
     await Task.Run(() =>
     {
         try
         {
             _ftp.uploadIndications(path + "\\wets");
             _ftp.uploadIndications(path + "\\temps");
             _ftp.uploadIndications(path + "\\pressure");
         }
         catch (Exception exc)
         {
             Mylog.writeExc("Ошибка класс: " + GetType().Name + ". метод: " + System.Reflection.MethodBase.GetCurrentMethod().Name + " Mes: " + exc.Message);
             return;
         }
     });
 }
Пример #8
0
            //создает подключение модбус
            private void CreatModbIPMaster()
            {
                // await Task.Run(() => {
                try
                {
                    this._modbusIpMaster = ModbusIpMaster.CreateIp(new TcpClient(ip, port));
                }
                catch (Exception exc)
                {
                    //Form1._form.richTextBox1.Invoke(new Action(() => Form1._form.richTextBox1.Text = "\r\n IVIT #" + id + " ошибка при подключении \r\n" + exc.Message + "\r\n" + Form1._form.richTextBox1.Text));
                    if (exc.HResult.ToString() != "-2147467259")
                    {
                        Mylog.writeExc("класс: " + GetType().Name + ". метод: " + System.Reflection.MethodBase.GetCurrentMethod().Name + exc.Message);
                    }
                    status = "no connect!";
                    return;
                }

                //});
            }
Пример #9
0
      public void loadJConfig()
      {
          try
          {
              // Создаем объект FtpWebRequest
              FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://" + host + "/JConfig.json");
              // устанавливаем метод на загрузку файлов
              request.Method = WebRequestMethods.Ftp.DownloadFile;

              // если требуется логин и пароль, устанавливаем их
              request.Credentials = new NetworkCredential(login, password);
              //request.EnableSsl = true; // если используется ssl

              // получаем ответ от сервера в виде объекта FtpWebResponse
              FtpWebResponse response = (FtpWebResponse)request.GetResponse();

              // получаем поток ответа
              Stream responseStream = response.GetResponseStream();
              // сохраняем файл в дисковой системе
              // создаем поток для сохранения файла

              FileStream fs = new FileStream(@configPath + "\\JConfig.json", FileMode.Create);

              //Буфер для считываемых данных
              byte[] buffer = new byte[64];
              int    size   = 0;

              while ((size = responseStream.Read(buffer, 0, buffer.Length)) > 0)
              {
                  fs.Write(buffer, 0, size);
              }
              fs.Close();
              response.Close();
          }catch (Exception exc)
          {
              Mylog.writeExc("класс: " + GetType().Name + ". метод: " + System.Reflection.MethodBase.GetCurrentMethod().Name + exc.Message);

              return;
          }
      }
Пример #10
0
      public void loadIndications(string path)
      {
          try
          {
              //загрузить файл если размер разный
              using (Session session = new Session())
              {
                  session.Open(sessionOptions);
                  var directory = session.ListDirectory("/indications" + path.Replace("\\", "/"));
                  foreach (RemoteFileInfo fileInfo in directory.Files)
                  {
                      if (!File.Exists(indicationsPath + path + "\\" + fileInfo.Name))
                      {
                          session.GetFiles("/indications" + path.Replace("\\", "/") + "/" + fileInfo.Name, indicationsPath + path + "\\" + fileInfo.Name);
                      }
                      else
                      {
                          //если существует файл, проверяем размеры
                          FileInfo file = new FileInfo(indicationsPath + path + "\\" + fileInfo.Name);

                          if (file.Length < fileInfo.Length)
                          {
                              MessageBox.Show(file.Length + " < " + fileInfo.Length);
                              session.GetFiles("/indications" + path.Replace("\\", "/") + "/" + fileInfo.Name, indicationsPath + path + "\\" + fileInfo.Name);
                          }
                      }
                  }
                  session.Close();
              }
          }
          catch (Exception exc)
          {
              Mylog.writeExc("класс: " + GetType().Name + ". метод: " + System.Reflection.MethodBase.GetCurrentMethod().Name + exc.Message);
              if (exc.HResult.ToString() == "-2146233088" || exc.HResult.ToString() == "2146233088")
              {
                  loadIndications(path);
              }
              return;
          }
      }