Example #1
0
        public void Sender(string id, int type, string msg)
        {
            if (!disc_client)
            {
                return;
            }

            bool stat = true;

            try
            {
                if (!disc_client)
                {
                    return;
                }

                while (client == null || !client.Connected)
                {
                    if (!disc_client)
                    {
                        stat = false;
                        ThreadAbort.th_abort();
                        return;
                    }

                    listbox_msg("Соединение отсутствует. ");
                    Connect();
                    Thread.Sleep(2000);
                }

                MSG packet = new MSG(id, type, msg);

                byte[] buf = new byte[1024];

                buf = Util.Serialization(packet);

                client.Send(buf);
            }
            catch (SocketException se)
            {
                stat = false;

                if (se.ErrorCode == 10054)
                {
                    listbox_msg("Соединение потеряно.Пробуем переподключиться... ");

                    Thread.Sleep(3000);

                    Sender(id, type, msg);
                }
            }
            catch (Exception exc)
            {
                stat = false;

                listbox_msg(exc.Message);
            }
            finally
            {
                if (stat)
                {
                    listbox_msg("Пакет отправлен!");
                }
            }
        }
Example #2
0
        private void StartScan()
        {
            if (!server.disc_client)
            {
                ThreadAbort.th_abort();
                return;
            }

            if (cas.Init() < 0)
            {
                list_msg("Отказ инициализации библиотеки.");
                return;
            }

            OleDbDataReader dr;

            Dbf dbf = new Dbf();

            dr = dbf.ExecuteReader("SELECT ip,name,port,model  FROM struct.dbf");

            if (dr == null)
            {
                return;
            }

            if (!dr.HasRows)
            {
                list_msg("База весов пустая!");
            }

            while (dr.Read())
            {
                try
                {
                    m_ip    = dr.GetString(0).Replace(" ", "");
                    m_name  = Convertall(dr.GetString(1).Replace(" ", ""), Encoding.GetEncoding(866), Encoding.GetEncoding(1251));
                    m_port  = Convert.ToInt32(dr.GetString(2));
                    m_model = Convert.ToInt32(dr.GetString(3));

                    this.Invoke((Action) delegate { checkedListBox1.Items.Add(m_ip + ":" + m_port + " " + m_name); });
                }
                catch (System.Exception ex)
                {
                    //TODO Написать обработчик исключений ,с отправкой на сервер отчетов ;
                    list_msg("Произошло исключение при считывании параметров весов! Адрес" + m_ip + " Имя: " + m_name + " Порт: " + m_port + " Модель: " + m_model);
                    list_msg("Текст исключения: " + ex.Message);

                    Log.log_write(ex.Message, "Exception", "Exception");

                    break;
                }

                int a = 0;

                try { a = cas.Connection(m_ip, m_port, 1, m_model); }
                catch (Exception exc) { MessageBox.Show(exc.Message); }



                if (a == -1)
                {
                    list_msg("Соединение с весами " + m_ip + ": " + m_port + " не удалось!");

                    int i = 3;

                    while (i != 0)
                    {
                        try
                        {
                            list_msg("Пробуем еще раз...");
                            Thread.Sleep(2000);

                            if (cas.Connection(m_ip, m_port, 1, m_model) != -1)
                            {
                                i = 0;
                            }
                            else
                            {
                                list_msg("Соединение с весами " + m_ip + ": " + m_port + " не удалось!");
                                i--;
                            }
                        }
                        catch (Exception ex)
                        {
                            i = 0;
                            send_msg("BalanceModule", 1, "BalanceModule: Соединение с весами " + m_ip + ": " + m_port + " не удалось!");
                            Log.log_write(ex.Message, "Exception", "Exception");
                        }
                        finally
                        {
                            if (i == 0)
                            {
                                send_msg("BalanceModule", 1, "BalanceModule: " + m_ip + ": " + m_port + " весы пропущены!");
                            }
                        }
                    }
                    continue;
                }

                if (cas.RecvPLU() < 0)
                {
                    list_msg("Соединение не удалось!Количество полученых записей меньше 0");
                    break;
                }

                /*
                 * 1	Disconnect or don't start
                 * 11	Connecting
                 * 20	Reconnect
                 * 30	Disconnection
                 * 40	Receive data
                 * 50	Send data
                 * 51	1:Success
                 * 52	2:Connect fail
                 * 53	3:Retry fail
                 * 54	4:Data error
                 * 55	5:Timeout
                 * 60	Send fail
                 * 65	Find not ip of scale
                 * 70	No define
                 * 80	Send timeout
                 * 82	Data range over
                 * 88	Direct MSG full
                 * 89	Full data
                 * 97	Format Error
                 * 98	Retry over
                 * 99	Disconnect
                 */

                int r = cas.GetState();

                while (!(r == 99 || r == 55 || r == 30))
                {
                    r = cas.GetState();
                    string str = String.Empty;
                    cas.GetTransStatus(m_ip, ref str);  //ipadress
                    list_msg(str);
                    Thread.Sleep(500);
                }

                string dataplu = String.Empty;

                try
                {
                    while (cas.RecvPLUData(ref dataplu) >= 0)
                    {
                        parse_plu_str(dataplu);
                    }
                }

                catch { return; }

                list_msg("Сканирование " + m_ip + " завершено!");
                list_msg("Количество найденых проблем: " + count_error);
                send_msg("BalanceModule", 1, m_ip + " " + m_name + " Количество найденых проблем: " + count_error);

                cas.DisconnectAll();

                delete_plu();

                list_msg("Удаление с весов " + m_ip + " завершено!");

                Array.Clear(data_delete, 0, data_delete.Length);

                count_error = 0;

                this.Invoke((Action) delegate { label2.Text = String.Empty; });
                this.Invoke((Action) delegate { label2.Refresh(); });

                this.Invoke((Action) delegate { checkedListBox1.SetItemChecked(checkedListBox1.Items.IndexOf(m_ip + ":" + m_port + " " + m_name), true); });
            }

            list_msg("Деинициализация...");
            send_msg("BalanceModule", 1, "Спящий режим активирован.");

            try
            {
                cas.DeInit();
            }
            catch (System.Exception ex)
            {
                Log.log_write(ex.Message, "Exception", "Exception");
                Application.Exit();
            }
            finally
            {
                timer_par();
                send_msg("BalanceModule", 1, "Деактивация спящего режима через: " + (timer_start_scan.Interval) / 3600000 + " часа\n");
            }
        }