Sp Rec

Материал из Wiki МИАЦ ВО
Версия от 12:52, 20 февраля 2018; Dmitriy (обсуждение | вклад) (Новая страница: «<pre> using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using spsdksvr; using spsdksw; using SpR…»)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к навигации Перейти к поиску
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using spsdksvr;
using spsdksw;
using SpRecord;
using System.Threading; 
using System.IO;
using System.Windows.Forms;
using namespase_mysql_connection;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Net;
using System.Web;
using Newtonsoft.Json;
using System.Security.Cryptography;
using System.Web.Script.Serialization;

namespace sprec
{
    public class myThread
        {
            public static Thread thread;

            public myThread(string name,int start_stop,int count_thread) //Конструктор получает имя функции
            {

                if (start_stop == 1)
                {
                    thread = new Thread(Program.ChannelListen);
                    thread.Name = name;
                    Console.WriteLine("thread.Name =" + thread.Name + ", " + thread.ManagedThreadId);
                    thread.IsBackground = true;
                    thread.Start();//передача параметра в поток
                }
                else if (start_stop == 2)
                {
                    thread.Abort();
                }

            }
            
/*            void func(object num)//Функция потока, передаем параметр
            {
                {
                    Console.WriteLine(Thread.CurrentThread.Name + " выводит " );
                    Thread.Sleep(0);
                }
                Console.WriteLine(Thread.CurrentThread.Name + " завершился");
            }
*/      
        
        }

    public class Connect_to_sprecord
    {
        public const int SPR_CHANNEL_INFO_CONVERSATIONACTIVE = 0x00000001; // WordBool //Запрашивается информация о наличии сеанса связи с удаленным абонентом. Value будет содержать TRUE, если сеанс связи начался, и FALSE, если нет. 
        public const int SPR_CHANNEL_INFO_PHONEFROM = 0x00000007;// BSTR  //  информация о телефоном номере вызывающего абонента. Value будет содержать строку с номером телефона. 
        public const int SPR_CHANNEL_INFO_SUBPHONEFROM = 0x00000008; // BSTR //  информация о дополнительном/внутреннем телефоном номере вызывающего абонента. Value будет содержать строку с номером телефона. 
        public const int SPR_CHANNEL_INFO_RINGFIRSTDATETIME = 0x0000000E; // DateTime
        public const int SPR_CHANNEL_INFO_PHONETO = 0x00000009; // BSTR //информация о телефоном номере вызываемого абонента. Value будет содержать строку с номером телефона. 
        public const int SPR_S_OK = 0x00000000;
        public const int SPR_CHANNEL_INFO_RECORDTYPE = 0x0000000B; // LONG // титп записи (вх, исх)
        public const int SPR_CHANNEL_INFO_FILENAME = 0x0000000C; // BSTR // имя файла
        public const int SPR_CHANNEL_INFO_CONVERSATIONLENG = 0x00000003;// LONG //  информация о времени с момента начала сеанса связи с удаленным абонентом. Value будет содержать время в секундах с момента начала сеанса связи. 
        public const int SPR_CHANNEL_INFO_RINGCOUNT = 0x00000010;  // LONG  // информация о количестве сигналов вызова
        public const int SPR_CHANNEL_INFO_CONVERSATIONDATETIME = 0x00000002; // DateTime // информация о времени начала сеанса связи с удаленным абонентом
        static string FileLogFileName = "connect_log.log";
        public Connect_to_sprecord(string ch_name, int start_stop) //Конструктор получает имя функции
        {

            if (start_stop == 1)
            {
                string ChannelName = ch_name;
                Console.WriteLine(ChannelName);
                string FileName = "";
                string TimeLine = "";
                string PhoneFrom = "";
                string SubPhoneFrom = "";
                string StartTime = "";
                bool GetLineState;
                bool GetWriting;
                int WaitMessage;
                string TypeCall = "";
                bool IsLineActive;
                object ChannelInfo = "";
                object IsLineActiveObj = "";
                int a = 0;

                SpRecordChannelClientW SPRecordChannel = new spsdksw.SpRecordChannelClientW();
                SPRecordChannel.Connect(ChannelName, 1, "", "");
                while (SPRecordChannel.Connected == true)
                {
                    if (Program.glo_status_int == 1) break;
                    //SPRecordChannel.GetLineState(out GetLineState);
                    //Console.WriteLine(GetLineState);
                    //SPRecordChannel.GetLineState(out GetWriting);
                    //Console.WriteLine(GetWriting);
                    //export_to_file(FileLogFileName, ChannelInfo.ToString());
                    //SPRecordChannel.GetReadyToCall(out IsLineActive);
                    SPRecordChannel.GetLineState(out IsLineActive);
                    if (IsLineActive != true) break;
                    //Console.WriteLine("IsLineActive1=" + IsLineActive);                
                    IsLineActive = true;
                    //while (IsLineActive == true)
                    //{
                    WaitMessage = SPRecordChannel.WaitMessage(-1);
                    if (WaitMessage == SPR_S_OK)
                    {
                        SPRecordChannel.GetInfo(SPR_CHANNEL_INFO_CONVERSATIONACTIVE, out IsLineActiveObj);
                        IsLineActive = (bool)IsLineActiveObj;
                        if (IsLineActive == false) continue;
                        /*object Msg;
                        var eee = SPRecordChannel.PeekMessage(out Msg);
                        byte[] bytes = (byte[])Msg;
                        string str = System.Text.Encoding.ASCII.GetString(bytes);
                        export_to_file(FileLogFileName, str);*/
                        SPRecordChannel.GetInfo(SPR_CHANNEL_INFO_FILENAME, out ChannelInfo);
                        FileName = ChannelInfo.ToString();
                        SPRecordChannel.GetInfo(SPR_CHANNEL_INFO_CONVERSATIONLENG, out ChannelInfo);
                        TimeLine = ChannelInfo.ToString();
                        SPRecordChannel.GetInfo(SPR_CHANNEL_INFO_CONVERSATIONDATETIME, out ChannelInfo);
                        StartTime = ChannelInfo.ToString();
                        SPRecordChannel.GetInfo(SPR_CHANNEL_INFO_RECORDTYPE, out ChannelInfo);
                        TypeCall = ChannelInfo.ToString();
                        //export_to_file(FileLogFileName, ChannelInfo.ToString());
                        //SPRecordChannel.GetInfo(SPR_CHANNEL_INFO_CONVERSATIONACTIVE, out ChannelInfo);
                        //export_to_file(FileLogFileName, ChannelInfo.ToString());
                        if ((int)TypeCall[0] == 2)
                        {
                            SPRecordChannel.GetInfo(SPR_CHANNEL_INFO_PHONEFROM, out ChannelInfo);
                            PhoneFrom = ChannelInfo.ToString();
                            SPRecordChannel.GetInfo(SPR_CHANNEL_INFO_SUBPHONEFROM, out ChannelInfo);
                            SubPhoneFrom = ChannelInfo.ToString();
                        }
                        System.Threading.Thread.Sleep(100); // пауза 0.1 сек.
                        Console.WriteLine("ChannelName=" + ChannelName + ", StartTime= " + StartTime + ", TimeLine=" + TimeLine + ", FileName=" + FileName + ", TypeCall= " + TypeCall[0] + ", PhoneFrom=" + PhoneFrom + ", SubPhoneFrom=" + SubPhoneFrom);
                        //glo_status1 = ChannelName + " " + TypeCall[0];
                        if (TypeCall[0] == 2)
                        {
                            TypeCall = "входящий, номер: " + PhoneFrom + "," + SubPhoneFrom;
                        }
                        else
                        {
                            TypeCall = "исходящий";
                        }
                        Program.glo_status1 = "Канал " + ChannelName + " , звонок " + TypeCall;
                    }
                    else
                    {
                        Program.export_to_file(FileLogFileName, FileName + " " + TimeLine + " " + PhoneFrom);
                    }
                    //export_to_file(FileLogFileName, WaitMessage.ToString());
                    //SPRecordChannel.GetInfo(SPR_CHANNEL_INFO_PHONEFROM, out ChannelInfo);
                    //Console.WriteLine("Идет разговор ... ");
                    Console.WriteLine(WaitMessage);
                    System.Threading.Thread.Sleep(300); // пауза 0.1 сек.
                    //}
                }
                SPRecordChannel.Disconnect();
            }

        }

        /*            void func(object num)//Функция потока, передаем параметр
                    {
                        {
                            Console.WriteLine(Thread.CurrentThread.Name + " выводит " );
                            Thread.Sleep(0);
                        }
                        Console.WriteLine(Thread.CurrentThread.Name + " завершился");
                    }
        */

    }

    class Program
    {
        public const int SPR_CHANNEL_INFO_CONVERSATIONACTIVE = 0x00000001; // WordBool //Запрашивается информация о наличии сеанса связи с удаленным абонентом. Value будет содержать TRUE, если сеанс связи начался, и FALSE, если нет. 
        public const int SPR_CHANNEL_INFO_PHONEFROM = 0x00000007;// BSTR  //  информация о телефоном номере вызывающего абонента. Value будет содержать строку с номером телефона. 
        public const int SPR_CHANNEL_INFO_SUBPHONEFROM = 0x00000008; // BSTR //  информация о дополнительном/внутреннем телефоном номере вызывающего абонента. Value будет содержать строку с номером телефона. 
        public const int SPR_CHANNEL_INFO_RINGFIRSTDATETIME=0x0000000E; // DateTime
        public const int SPR_CHANNEL_INFO_PHONETO = 0x00000009; // BSTR //информация о телефоном номере вызываемого абонента. Value будет содержать строку с номером телефона. 
        public const int SPR_S_OK = 0x00000000;
        public const int SPR_CHANNEL_INFO_RECORDTYPE = 0x0000000B; // LONG // титп записи (вх, исх)
        public const int SPR_CHANNEL_INFO_FILENAME = 0x0000000C; // BSTR // имя файла
        public const int SPR_CHANNEL_INFO_CONVERSATIONLENG = 0x00000003;// LONG //  информация о времени с момента начала сеанса связи с удаленным абонентом. Value будет содержать время в секундах с момента начала сеанса связи. 
        public const int SPR_CHANNEL_INFO_RINGCOUNT = 0x00000010;  // LONG  // информация о количестве сигналов вызова
        public const int SPR_CHANNEL_INFO_CONVERSATIONDATETIME = 0x00000002; // DateTime // информация о времени начала сеанса связи с удаленным абонентом
        public const int SPR_CHANNEL_INFO_RING = 0x0000000D; // WordBool
        public const int SPR_CHANNEL_INFO_SUBPHONETO = 0x0000000A; // BSTR

        // max число каналов =4 
        public static string glo_status1 = " Ожидание запуска ...";
        public static int glo_status_int = 0;
        static string FileLogFileName = "connect_log.log";
        static void Main(string[] args)
        {
            /*string json1 ="{\"error\":[],\"data\":{\"status\":\"ok\",\"unicod\":42}}";
            var json2 ="{\"error\":{\"id\":1,\"text\":\"error autorization\"},\"data\":[]}";
          
            var json3 ="{\"response\":[{\"id\":269058571,\"first_name\":\"Name\",\"last_name\":\"LastName\",\"photo_50\":\"http://cs624717.vk.me/v624717571/21718/X8.jpg\"}]}";


            using (var reader = new StreamReader(json1))
            {
                System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer();
                var objText = reader.ReadToEnd();
                var jsonData = (Dictionary<string, object>)js.DeserializeObject(json1);
                Console.WriteLine(jsonData);
                Console.WriteLine("end");
            }
            return;		*/
            // Подключаемся
            //SpRecordClient SPRecordClient = new spsdksvr.SpRecordClient();
            Form1 Forma = new Form1();
            Forma.ShowDialog();
            //Forma.SetLabelText(glo_status1);
            //Forma.Show();
            //Console.ReadKey();
        }

        class RootObject
        {
            public Item1 error { get; set; }
            public Item2 data { get; set; }
        }
        class Item1
        {
            public string id { get; set; }
            public string text { get; set; }
        }
        class Item2
        {
            public string status { get; set; }
            public string unicod { get; set; }
        }
        public static void Connect_to_stop()
        {
            try
            {
                glo_status_int = 1;
            }
            catch (ThreadAbortException)
            {
                    Console.WriteLine("Поток не прерван ");
            }
        }
        public static void Connect_to_asp()
        {
            //MessageBox.Show("hello pr");
            try
            {
                glo_status_int = 0;
                SpRecordClient SPRecordClient = new SpRecordClient();
                Console.WriteLine("Connect_to_asp =");
                var Connect = SPRecordClient.Connect(0, "", "");
                // Получаем список каналов
                string ChannelList = "";
                string FileLogFileName = "connect_log.log";
                var Channel = SPRecordClient.GetChannelNames(out ChannelList, 1);
                Char delimiter = '|';
                String[] substrings = ChannelList.Split(delimiter);
                //export_to_file(FileLogFileName, "1 start");
                //Program p = new Program();
                int i = 0;
                foreach (var substring in substrings)
                {
                    i += 1;
                    Console.WriteLine("substring " + substring);
                    //myThread t1 = new myThread(substring, 1, i);
                    switch (i)
                    {
                        case 1:
                            //Connect_to_sprecord t1 = new Connect_to_sprecord(substring, 1);
                            myThread t1 = new myThread(substring, 1, i);
                            break;
                        case 2:
                            //Connect_to_sprecord t2 = new Connect_to_sprecord(substring, 1);
                            myThread t2= new myThread(substring, 1, i);
                            break;
                        case 3:
                            //Connect_to_sprecord t3 = new Connect_to_sprecord(substring, 1);
                            myThread t3 = new myThread(substring, 1, i);
                            break;
                        case 4:
                            myThread t4 = new myThread(substring, 1, i);
                            //Connect_to_sprecord t4 = new Connect_to_sprecord(substring, 1);
                            break;
                    }
                    //Console.ReadKey();
                    System.Threading.Thread.Sleep(300); // пауза 0.1 сек. для инициализации
                    Console.WriteLine("pause ");
                }
                SPRecordClient.Disconnect();
                //var devName = SPRecordClient.GetDeviceNames;
                Console.WriteLine("pause ");
            }
            catch (ThreadAbortException exc)
            {
                if ((int)exc.ExceptionState == 0)
                {
                    Console.WriteLine("Прерывание отменено! Код завершения: "
                        + exc.ExceptionState);
                    Thread.ResetAbort();
                }
                else
                    Console.WriteLine("Поток прерван, код завершения "
                        + exc.ExceptionState);
            }
        }
        public static void ChannelListen()
        {
            string ChannelName = myThread.thread.Name;
            int id_calldetails = 0;
            Console.WriteLine(ChannelName);
            string current_FileName = "";
            string FileName = "";
            int priznak_incomin_ring = 0;
            string TimeLine = "";
            string PhoneFrom = "";
            string SubPhoneFrom = "";
            DateTime StartTime;
            int ring_count = 0; 
            bool GetLineState;
            bool GetWriting;
            int WaitMessage;
            int TypeCall = 0;
            string TypeCall_str = "";
            bool IsLineActive;
            object ChannelInfo = "";
            object IsLineActiveObj = "";
            bool incoming_ring;
            object Is_incoming_ring = "";

            SpRecordChannelClientW SPRecordChannel = new spsdksw.SpRecordChannelClientW();
            SPRecordChannel.Connect(ChannelName, 1, "", "");
            current_FileName = "";
            priznak_incomin_ring = 0;
            while (SPRecordChannel.Connected == true)
            {
                if (glo_status_int==1) break;
                //SPRecordChannel.GetLineState(out GetLineState);
                //Console.WriteLine(GetLineState);
                //SPRecordChannel.GetLineState(out GetWriting);
                //Console.WriteLine(GetWriting);
                //export_to_file(FileLogFileName, ChannelInfo.ToString());
                    //SPRecordChannel.GetReadyToCall(out IsLineActive);
                SPRecordChannel.GetLineState(out IsLineActive);
                if (IsLineActive != true) break;
                //Console.WriteLine("IsLineActive1=" + IsLineActive);                
                 IsLineActive = true;
                //while (IsLineActive == true)
                    //{
                        WaitMessage = SPRecordChannel.WaitMessage(-1);
                        if (WaitMessage == SPR_S_OK)
                        {
                            SPRecordChannel.GetInfo(SPR_CHANNEL_INFO_CONVERSATIONACTIVE, out IsLineActiveObj);
                            IsLineActive = (bool)IsLineActiveObj;
                            SPRecordChannel.GetInfo(SPR_CHANNEL_INFO_RING, out Is_incoming_ring);
                            incoming_ring = (bool)Is_incoming_ring;
                            if (incoming_ring == true)
                            {
                                if (current_FileName == "" & priznak_incomin_ring == 0)
                                {
                                    priznak_incomin_ring = 1;       // идет звонок оператору
                                }
                                //if (current_FileName != FileName)
                                SPRecordChannel.GetInfo(SPR_CHANNEL_INFO_RINGCOUNT, out ChannelInfo);
                                if ((int)ChannelInfo > ring_count)
                                {
                                    ring_count = (int)ChannelInfo;
                                    Console.WriteLine("ring_count=" + ring_count);
                                }
                                if (priznak_incomin_ring == 1)
                                {
                                    ring_count = 0;
                                    priznak_incomin_ring = 2; // статус - снята трубка
                                    SPRecordChannel.GetInfo(SPR_CHANNEL_INFO_RINGFIRSTDATETIME, out ChannelInfo);
                                    StartTime = ((DateTime)ChannelInfo);
                                    //StartTime = StartTime.Date.ToString("yyyy-MM-dd") + " " + StartTime.Hour+":"StartTime.Minute+":"+StartTime.Second;
                                    SPRecordChannel.GetInfo(SPR_CHANNEL_INFO_RECORDTYPE, out ChannelInfo);
                                    TypeCall = (int)ChannelInfo;
                                    //if (TypeCall != 2)
                                    {
                                        SPRecordChannel.GetInfo(SPR_CHANNEL_INFO_PHONEFROM, out ChannelInfo);
                                        PhoneFrom = (string)ChannelInfo;
                                        SPRecordChannel.GetInfo(SPR_CHANNEL_INFO_SUBPHONEFROM, out ChannelInfo);
                                        SubPhoneFrom = (string)ChannelInfo;
                                    }
                                    TypeCall_str = "входящий, номер: " + PhoneFrom + ", " + SubPhoneFrom;
                                    List<List<string>> arr = namespase_mysql_connection.MySql.mysql_connect_read_status_file(Form1.Srv, Form1.DataBase, Form1.User, Form1.Passwrd, 0, StartTime.Date.ToString("yyyy-MM-dd") + " "+StartTime.Hour+":"+StartTime.Minute+":"+StartTime.Second,"", ChannelName[(ChannelName.Length - 1)], PhoneFrom,0,"",1,0,"");
                                    Console.WriteLine("arr.Count=" + arr.Count);
                                    StringBuilder builder = new StringBuilder();
                                    if (arr.Count == 0)
                                        Console.WriteLine("ошибка получения max(id) из таблицы calldetails");
                                    else
                                    {
                                        for (int i = 0; i <= arr.Count - 1; i++)
                                        {
                                            if (arr[i][0] == "0" | arr[i][0] == "Error")
                                            {
                                                break;
                                            }
                                            else
                                            {
                                                id_calldetails = Int32.Parse(arr[i][0]);
                                                string response = send_id("add_popup", id_calldetails, Int32.Parse((ChannelName[(ChannelName.Length - 1)]).ToString()), PhoneFrom);
                                                Console.WriteLine(response);
                                                Console.WriteLine("id=" + arr[i][0] + " StartTime=" + " " + StartTime + "ChannelName[(ChannelName.Length - 1)]=" + ChannelName[(ChannelName.Length - 1)] + "PhoneFrom=" + PhoneFrom + "SubPhoneFrom=" + SubPhoneFrom);
                                                break;
                                            }
                                        }
                                    }

                                }
                            }
                            else
                            {
                                /*if (current_FileName == "")
                                {
                                    priznak_incomin_ring = 0;
                                    Console.WriteLine("dozvon end");
                                }*/
/*                                if (current_FileName == FileName && priznak_incomin_ring == 2)
                                {
                                    Console.WriteLine("FileName=" + FileName+ "Call end");
                                    priznak_incomin_ring = 0;
                                }*/
                            }
                            if (IsLineActive == false)
                            {
                                if (current_FileName != "")
                                {
                                    if (priznak_incomin_ring == 2) TypeCall = 2;    // out call
                                    if (priznak_incomin_ring == 0) TypeCall = 1; // in call
                                    List<List<string>> arr = namespase_mysql_connection.MySql.mysql_connect_read_status_file(Form1.Srv, Form1.DataBase, Form1.User, Form1.Passwrd, 2, "", DateTime.Now.ToString("yyyy-MM-dd") + " " + DateTime.Now.ToString("HH:mm:ss"), 'c', "", 1, "", TypeCall, id_calldetails,"");
                                    Console.WriteLine("FileName=" + FileName + "Call end");
                                    current_FileName = "";
                                    TypeCall_str = " Ожидание вызова ...";
                                    glo_status1 =  TypeCall_str;
                                }
                                continue;
                            }
                            if (priznak_incomin_ring == 2 & TypeCall != 2)
                            {
                                //сюда вставить продолжительность звонка
                                SPRecordChannel.GetInfo(SPR_CHANNEL_INFO_FILENAME, out ChannelInfo);
                                FileName = ChannelInfo.ToString();
                                List<List<string>> arr = namespase_mysql_connection.MySql.mysql_connect_read_status_file(Form1.Srv, Form1.DataBase, Form1.User, Form1.Passwrd, 1, "", "", 'c', "", ring_count, FileName, TypeCall, id_calldetails,"");
                                Console.WriteLine("FileName=" + FileName + " ring_count=" + ring_count + " priznak_incomin_ring = 2;");
                            }

  /*object Msg;
                            var eee = SPRecordChannel.PeekMessage(out Msg);
                            byte[] bytes = (byte[])Msg;
                            string str = System.Text.Encoding.ASCII.GetString(bytes);
                            export_to_file(FileLogFileName, str);*/
                            SPRecordChannel.GetInfo(SPR_CHANNEL_INFO_FILENAME, out ChannelInfo);
                            FileName = ChannelInfo.ToString();
                            if (current_FileName != FileName)
                            {
                                current_FileName = FileName;
                                SPRecordChannel.GetInfo(SPR_CHANNEL_INFO_CONVERSATIONLENG, out ChannelInfo);
                                TimeLine = ChannelInfo.ToString();
                                SPRecordChannel.GetInfo(SPR_CHANNEL_INFO_CONVERSATIONDATETIME, out ChannelInfo);
                                StartTime = (DateTime)ChannelInfo;
                                SPRecordChannel.GetInfo(SPR_CHANNEL_INFO_RECORDTYPE, out ChannelInfo);
                                TypeCall = (int)ChannelInfo;
                                //export_to_file(FileLogFileName, ChannelInfo.ToString());
                                //SPRecordChannel.GetInfo(SPR_CHANNEL_INFO_CONVERSATIONACTIVE, out ChannelInfo);
                                //export_to_file(FileLogFileName, ChannelInfo.ToString());
                                if (priznak_incomin_ring == 0)
                                {
                                    //SPRecordChannel.GetInfo(SPR_CHANNEL_INFO_SUBPHONETO, out ChannelInfo);
                                    //PhoneFrom = ChannelInfo.ToString();
                                    List<List<string>> arr = namespase_mysql_connection.MySql.mysql_connect_read_status_file(Form1.Srv, Form1.DataBase, Form1.User, Form1.Passwrd, 0, DateTime.Now.ToString("yyyy-MM-dd") + " " + DateTime.Now.ToString("HH:mm:ss"), "", ChannelName[(ChannelName.Length - 1)], PhoneFrom, 0, FileName, 2, 0,"");
                                    Console.WriteLine("arr.Count=" + arr.Count);
                                    StringBuilder builder = new StringBuilder();
                                    if (arr.Count == 0)
                                    {
                                        MessageBox.Show("ошибка получения max(id) из таблицы calldetails");
                                    }
                                    else
                                    {
                                        for (int i = 0; i <= arr.Count - 1; i++)
                                        {
                                            if (arr[i][0] == "0" | arr[i][0] == "Error")
                                            {
                                                break;
                                            }
                                            else
                                            {
                                                id_calldetails = Int32.Parse(arr[i][0]);
                                                Console.WriteLine("id=" + arr[i][0] + " StartTime=" + " " + StartTime + "ChannelName[(ChannelName.Length - 1)]=" + ChannelName[(ChannelName.Length - 1)] + "PhoneFrom=" + PhoneFrom + "SubPhoneFrom=" + SubPhoneFrom);
                                                break;
                                            }
                                        }
                                    }
                                }
                                System.Threading.Thread.Sleep(100); // пауза 0.1 сек.
                                //Console.WriteLine("ChannelName1=" + ChannelName + ", StartTime= " + StartTime + ", TimeLine=" + TimeLine + ", FileName=" + FileName + ", TypeCall= " + TypeCall + ", PhoneFrom=" + PhoneFrom + ", SubPhoneFrom=" + SubPhoneFrom + "ChannelName=" + ChannelName[(ChannelName.Length - 1)] + "ring_count=" + ring_count);
                                if (priznak_incomin_ring == 2)
                                {
                                    TypeCall_str = "входящий, номер: " + PhoneFrom + ", " + SubPhoneFrom;
                                }
                                else
                                {
                                    TypeCall_str = "исходящий";
                                }
                                glo_status1 = "Канал " + ChannelName + " , звонок " + TypeCall_str;
                            }
                            else
                            {
                                priznak_incomin_ring = 0;
                            }
                        }
                        else
                        {
                            current_FileName = "";
                            priznak_incomin_ring = 0;
                            ring_count = 0;
                            export_to_file(FileLogFileName, FileName + " " + TimeLine + " " + PhoneFrom);
                            //continue;
                        }
                     //export_to_file(FileLogFileName, WaitMessage.ToString());
                    //SPRecordChannel.GetInfo(SPR_CHANNEL_INFO_PHONEFROM, out ChannelInfo);
                    //Console.WriteLine("Идет разговор ... ");
                    //Console.WriteLine(WaitMessage);
                    System.Threading.Thread.Sleep(300); // пауза 0.1 сек.
                //}
            }
            SPRecordChannel.Disconnect();
        }

        public static string CreateMD5(string input)
        {
            // Use input string to calculate MD5 hash
            using (System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create())
            {
                byte[] inputBytes = System.Text.Encoding.UTF8.GetBytes(input);
                byte[] hashBytes = md5.ComputeHash(inputBytes);

                // Convert the byte array to hexadecimal string
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < hashBytes.Length; i++)
                {
                    sb.Append(hashBytes[i].ToString("X2"));
                }
                return sb.ToString();
            }
        }
        public class Request_type
        {
            public string type { get; set; }
            public int unicod { get; set; }
            public int chanel { get; set; }
            public string phone { get; set; }

            // public Dictionary<string, string> data { get; set; }
        }
        
        [Serializable]
        public class Response_type
        {
            public Dictionary<string, Object> error { get; set; }

            public Dictionary<string, Object> data { get; set; }
        }
        [Serializable]
        public class ErrorList
            {
                public string id { get; set; }
                public string text { get; set; }
            }
            [Serializable]
            public class DataList
            {
                public string status { get; set; }
                public string unicod { get; set; }
            }
        
        public static string send_id(string type, int unicod, int chanel, string phone)
        {
            // ^id_documment=_iemk_exchenge_log.id
            string response = "";
            //            var SourceFile = "";
            //string urlString = "http://smp.volmed.org.rus/json/server.php";
            var Host = Form1.Service_address;
            string urlString = "http://" + Host;
            var SoapAction = "";
            string id_service = Form1.Service_id ;
            string passwrd = id_service + Form1.Service_pass;
            passwrd = CreateMD5(passwrd);
            urlString = urlString + "?id_service="+id_service+"&auth_key=" + passwrd.ToLower();
            //string[] MyArray = { type, unicod.ToString(), chanel.ToString(), phone };
            Request_type MyArray = new Request_type();
                MyArray.type=type;
                MyArray.unicod = unicod;
                MyArray.chanel = chanel;
                if (phone == null) MyArray.phone = "000000"; else MyArray.phone = phone;
            var jsonSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
            string json = jsonSerializer.Serialize(MyArray);
            export_to_file("12", "json=" + json);
            var response1 = XmlHttpRequest(json, urlString);
            // запись в файл
            if (Int32.Parse(response1.id)>0)
            {
                List<List<string>> arr = namespase_mysql_connection.MySql.mysql_connect_read_status_file(Form1.Srv, Form1.DataBase, Form1.User, Form1.Passwrd, 3, "", DateTime.Now.ToString("yyyy-MM-dd") + " " + DateTime.Now.ToString("HH:mm:ss"), 'c', "", 1, "", 0, Int32.Parse(response1.id), response1.text);
            }
            export_to_file("12", "response error id =" + response1.id + " response text =" + response1.text);
            string request = "";
            var jsonDeSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
            Response_type a = jsonDeSerializer.Deserialize<Response_type>(response);
            ErrorList a1 = jsonDeSerializer.Deserialize<ErrorList>(response);
            var DataList = jsonDeSerializer.Deserialize<DataList>(response);
            Console.WriteLine("a =" + a);
            return response;
        }

        public static ErrorList XmlHttpRequest(string Content, string urlString)
        {
            var ContentType = "application/json;";
            // param_return=1 полный ответ, 2 урезаный
                /* Get example *//*

                byte[] bytes;
                bytes = System.Text.Encoding.UTF8.GetBytes(get_s);

                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(get_s);
                request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;

                using (HttpWebResponse response1 = (HttpWebResponse)request.GetResponse())
                using (Stream stream = response1.GetResponseStream())
                using (StreamReader reader = new StreamReader(stream))
                {
                    return reader.ReadToEnd();
                }
                 */
                /* Post */

            byte[] dataBytes = Encoding.UTF8.GetBytes(Content);

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlString);
                request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
                request.ContentLength = dataBytes.Length;
                request.ContentType = ContentType;
                request.Method = "POST";

                using (Stream requestBody = request.GetRequestStream())
                {
                    requestBody.Write(dataBytes, 0, dataBytes.Length);
                }

                /*using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                using (Stream stream = response.GetResponseStream())
                using (StreamReader reader = new StreamReader(stream))
                {
                    return reader.ReadToEnd();
                }*/
                using (var twitpicResponse = (HttpWebResponse)request.GetResponse())
                {

                    using (var reader = new StreamReader(twitpicResponse.GetResponseStream()))
                    {
                        JavaScriptSerializer js = new JavaScriptSerializer();
                        var objText = reader.ReadToEnd();
                        //var json44 = JsonConvert.SerializeObject(objText, Formatting.Indented);
                        var myojb = js.DeserializeObject(objText);

                        var jsonData = (Dictionary<string, object>)js.DeserializeObject(objText);
                        ErrorList ErrorValue_class = new ErrorList();
                        foreach (KeyValuePair<string, object> keyValue in jsonData)
                        {
                            Console.WriteLine(keyValue.Key + " - " + keyValue.Value);
                            if (keyValue.Key == "error")
                            {
                                string ErrorValue_string = js.Serialize(keyValue.Value);
                                if (ErrorValue_string == "[]")
                                {
                                    ErrorValue_class.id = "0"; ErrorValue_class.text = "";
                                    break;
                                } 
                                ErrorValue_class = js.Deserialize<ErrorList>(ErrorValue_string);
                                Console.WriteLine("ErrorValue_class=" + ErrorValue_class.id + "ErrorValue_class.text=" + ErrorValue_class.text);
                            }
                            if (keyValue.Key == "data")
                            {
                                var jsonSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
                                string dataValue_string = jsonSerializer.Serialize(keyValue.Value);
                                if (dataValue_string == "[]") break;
                                DataList Data_class = js.Deserialize<DataList>(dataValue_string);
                                Console.WriteLine("myojb2212.status=" + Data_class.status + "myojb2212.value=" + Data_class.unicod);
                                ErrorValue_class.id = "0"; ErrorValue_class.text = "";
                                return ErrorValue_class;
                            }                              
                        }
                        
/*                    Object obj;
                    bool b = jsonData.TryGetValue("error", out obj);
                        var splashInfo = JsonConvert.DeserializeObject<ErrorList>(objText);
                        ErrorList myojb1 = js.Deserialize<ErrorList>(objText);
                        DataList myojb2 = js.Deserialize<DataList>(objText);
                        return myojb1;*/
                        return ErrorValue_class;
                    }

                }
        }
        public static void export_to_file(string filename, string text)
        {
            FileStream fs = new FileStream(filename, FileMode.Append, FileAccess.Write);
            StreamWriter sw = new StreamWriter(fs);
            Console.WriteLine(text);
            sw.WriteLine(text);
            sw.Close();
        }
/*        public static void Add()
        {
            while (1 == 1)
            {
                Console.WriteLine('1');
                System.Threading.Thread.Sleep(1000); // пауза 0.1 сек.
            }
        }
        public static void Add1()
        {
            while (1 == 1)
            {
                Console.WriteLine('2');
                System.Threading.Thread.Sleep(3000); // пауза 0.1 сек.
            }
        }*/

    }
}