/// <summary>
 /// API 函数初始化
 /// </summary>
 /// <returns></returns>
 private int APIOpen()
 {
     if (!bAPIOpen)
     {
         int ret;
         try
         {
             ret = Dapapi.AB_API_Open();
             if (ret < 0)
             {
                 return(-1);
             }
             else
             {
                 bAPIOpen = true;
                 return(1);
             }
         }
         catch (Exception e)
         {
             MessageBox.Show(e.Message);
         }
     }
     return(0);
 }
        /// <summary>
        /// 显示数字
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void bu_int_Click(object sender, EventArgs e)
        {
            TagClear();
            iNodeAddr                 = short.Parse(cb_ip.Text);
            iNumData                  = Convert.ToInt32(this.Cb_int.Text);
            this.Cb_int.ForeColor     = Color.Red;
            this.radioButton1.Checked = true;
            //this.Cb_int.Enabled = false;
            if (this.Cb_int.Text == string.Empty || this.Cb_int.Text == "")
            {
                MessageBox.Show("请选择数字!");
                return;
            }

            for (int i = 0; i < GWCount; i++)
            {
                if (iNodeAddr != 0)
                {
                    Dapapi.AB_LB_DspNum(GWID[i], iNodeAddr, iNumData, iDigitPoint, iLEDInterval);
                    Bigling(GWID[i], i);
                }
                else
                {
                    Dapapi.AB_LB_DspNum(GWID[i], -252, iNumData, iDigitPoint, iLEDInterval);
                    Dapapi.AB_LB_DspNum(GWID[i], 252, iNumData, iDigitPoint, iLEDInterval);
                }
            }
        }
 /// <summary>
 /// API注销
 /// </summary>
 /// <returns></returns>
 private int APIClose()
 {
     if (bAPIOpen)
     {
         int i = Dapapi.AB_API_Close();
         bAPIOpen = false;
         return(1);
     }
     else
     {
         return(0);
     }
 }
        //发送指令
        private void button1_Click(object sender, EventArgs e)
        {
            Dapapi.AB_API_Open();
            string ip = this.cb_ip.Text;

            string  [] list = ip.Split('-');
            //int[] a =Convert.ToInt32( list[0]);
            try
            {
                int a = Dapapi.AB_LB_DspNum(Convert.ToInt32(list[0]), Convert.ToInt32(list[1]), Convert.ToInt32(list[2]), 0, 0);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
        /// <summary>
        /// 显示字符
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void bu_str_Click(object sender, EventArgs e)
        {
            iNodeAddr                 = short.Parse(this.cb_ip.Text);
            this.cb_str.ForeColor     = Color.Red;
            this.radioButton2.Checked = true;
            //this.cb_str.Enabled = false;
            if (this.cb_str.Text == string.Empty || this.cb_str.Text == "")
            {
                MessageBox.Show("请选择字符!");
                return;
            }
            string sShowData;

            radioButton2.Checked = true;
            //ShowFunColor(3);

            //if (CheckNodeAddr() == -1) return;
            //if (CheckNumeric() == -1) return;
            //if (CheckLEDInterval() == -1) return;

            sShowData = cb_str.Text /*.Trim()*/;
            if (sShowData.Length > 6)
            {
                sShowData = sShowData.Substring(0, 6);
            }
            else
            {
                sShowData = sShowData.PadLeft(6);
            }

            for (int i = 0; i < GWCount; i++)
            {
                if (iNodeAddr != 0)
                {
                    Dapapi.AB_LB_DspStr(GWID[i], iNodeAddr, sShowData, iDigitPoint, iLEDInterval);
                    Bigling(GWID[i], i);
                }

                else
                {
                    Dapapi.AB_LB_DspStr(GWID[i], -252, sShowData, iDigitPoint, iLEDInterval);
                    Dapapi.AB_LB_DspStr(GWID[i], 252, sShowData, iDigitPoint, iLEDInterval);
                }
            }
        }
 /// <summary>
 /// 排灯
 /// </summary>
 /// <param name="iNodeAddr"></param>
 /// <param name="i"></param>
 public void Bigling(int iNodeAddr, int i)
 {
     if (iNodeAddr > 90)
     {
         Dapapi.AB_LB_DspNum(GWID[i], 120, iNumData, iDigitPoint, iLEDInterval);
     }
     else if (iNodeAddr > 60)
     {
         Dapapi.AB_LB_DspNum(GWID[i], 90, iNumData, iDigitPoint, iLEDInterval);
     }
     else if (iNodeAddr > 30)
     {
         Dapapi.AB_LB_DspNum(GWID[i], 60, iNumData, iDigitPoint, iLEDInterval);
     }
     else if (iNodeAddr > 0)
     {
         Dapapi.AB_LB_DspNum(GWID[i], 30, iNumData, iDigitPoint, iLEDInterval);
     }
 }
        /// <summary>
        /// 获取控制器状态
        /// </summary>
        private void GetGWStatus()
        {
            bool bGoOn;
            int  ret, timeStart;

            for (int i = 0; i < GWCount; i++)
            {
                Dapapi.AB_GW_Open(GWID[i]);
                ret = Dapapi.AB_GW_Status(GWID[i]);

                if (ret != 7)
                {
                    bGoOn     = true;
                    timeStart = System.Environment.TickCount;
                    while (bGoOn)
                    {
                        ret = Dapapi.AB_GW_Status(GWID[i]);
                        if (ret == 7)
                        {
                            bGoOn = false;
                        }
                        else if (System.Environment.TickCount - timeStart > 3000)
                        {
                            bGoOn = false;
                        }
                    }
                }

                if (ret == 7)
                {
                    this.tb_msg.Text += "\r\n Gateway ID:" + GWID[i] + " success connected, status return :" + ret;
                }
                else
                {
                    this.tb_msg.Text += "\r\n Gateway ID:" + GWID[i] + " failed to connected, status return :" + ret;
                }
            }
        }
        /// <summary>
        /// 熄灭所有标签
        /// </summary>
        private void TagClear()
        {
            for (int i = 0; i < GWCount; i++)
            {
                if (Dapapi.AB_GW_Status(GWID[i]) == 7)
                {
                    Dapapi.AB_LB_DspNum(GWID[i], -252, 0, 0, -3);
                    Dapapi.AB_LB_DspNum(GWID[i], 252, 0, 0, -3);
                    Dapapi.AB_LED_Dsp(GWID[i], -252, 0, 0);
                    Dapapi.AB_LED_Dsp(GWID[i], 252, 0, 0);
                    Dapapi.AB_BUZ_On(GWID[i], -252, 0);
                    Dapapi.AB_BUZ_On(GWID[i], 252, 0);
                    Dapapi.AB_LB_DspStr(GWID[i], -252, "", 0, -3);
                    Dapapi.AB_LB_DspStr(GWID[i], 252, "", 0, -3);

                    //12-digits Alphanumerical display
                    Dapapi.AB_AHA_ClrDsp(GWID[i], -252);
                    Dapapi.AB_AHA_ClrDsp(GWID[i], 252);
                    Dapapi.AB_AHA_BUZ_On(GWID[i], -252, 0);
                    Dapapi.AB_AHA_BUZ_On(GWID[i], 252, 0);
                }
            }
        }
        /// <summary>
        /// 控制器打开
        /// </summary>
        /// <returns></returns>
        private int Dap_Open(string name, string IP)
        {
            int posspace, postab, pos;

            tb_Addrlist.Clear();

            GWCount = 0;
            if (!System.IO.File.Exists(name))
            {
                MessageBox.Show("JSON文件不存在!");
                return(-1);
            }
            try
            {
                using (System.IO.StreamReader sr = new System.IO.StreamReader(name))
                {
                    String line;
                    // Read and display lines from the file until the end of
                    // the file is reached.
                    //StreamReader file = File.OpenText("IPindex.json");
                    //JsonTextReader reader = new JsonTextReader(file);
                    //JObject jsonObject = (JObject)JToken.ReadFrom(reader);
                    //line = (string)jsonObject["IP"];
                    //file.Close();
                    line = IP;

                    //while ((line = sr.ReadLine()) != null)
                    if (line != null)
                    {
                        GWCount++;
                        posspace = line.IndexOf(" ");     //find space
                        postab   = line.IndexOf((char)9); //find tab

                        if (posspace <= 0)
                        {
                            posspace = postab;
                        }
                        if (postab <= 0)
                        {
                            postab = posspace;
                        }
                        pos = System.Math.Min(posspace, postab);
                        if (pos <= 0)
                        {
                            MessageBox.Show("JSON格式错误!");
                            return(-1);
                        }

                        tb_Addrlist.AppendText(line + "\r\n");

                        GWID[GWCount - 1] = int.Parse(line.Substring(0, pos));
                        diagnosis[GWCount - 1].Init(2);
                    }
                }
            }
            catch (Exception e)
            {
                MessageBox.Show("读取文件JSON失败!" + e.Message);
                return(-1);
            }

            if (APIOpen() < 0)
            {
                MessageBox.Show("初始化API失败!");
                return(-1);
            }

            MessageBox.Show("API Open Success!");

            for (int i = 0; i < GWCount; i++)
            {
                if (Dapapi.AB_GW_Open(GWID[i]) < 0)
                {
                    MessageBox.Show("控制器'" + GWID[i] + "'打开失败!");
                }
            }

            return(1);
        }
        private void bn_sendmessage_Click(object sender, EventArgs e)
        {
            TagClear();
            Dap_Close();


            MessageQueue mqQue = null;

            if (MessageQueue.Exists(sMessageConnectionString))
            {
                mqQue = new System.Messaging.MessageQueue(sMessageConnectionString);
            }
            if (mqQue == null)
            {
                MessageBox.Show("消息队列获取失败!");
                return;
            }
            //得到所有消息
            System.Messaging.Message[] messages = mqQue.GetAllMessages();
            if (messages.Length > 0)
            {
                foreach (System.Messaging.Message msgVal in messages)
                {
                    //根据ID得到消息(这个ID放在消息的label中)
                    if (msgVal.Label == tb_JID.Text)
                    {
                        //同步接收,直到得到一条消息为止,如果消息队列为空,会一直阻塞
                        System.Messaging.Message msg = mqQue.Receive();
                        msg.Formatter = new System.Messaging.XmlMessageFormatter(new Type[] { typeof(string) });
                        //消息的内容
                        tb_receive.Text = msg.Body.ToString();
                        string   tagID = msg.Body.ToString();
                        string[] ip    = tagID.Split('-');
                        string   a     = ip[0];
                        string   IPstr = "";
                        IPstr = GetIP(a);
                        string name = "";

                        //switch (a)
                        //{
                        //    case "1":
                        //        IPstr = "1 4660 10.0.50.111";
                        //        break;
                        //    case "2":
                        //        IPstr = "1 4660 10.0.50.112";
                        //        //name = "IPTWOINDEX";
                        //        break;
                        //    case "3":
                        //        IPstr = "1 4660 10.0.50.113";
                        //        //name = "IPTHREEINDEX";
                        //        break;
                        //    case "4":
                        //        IPstr = "1 4660 10.0.50.114";
                        //        //name = "IPFOURINDEX";
                        //        break;
                        //    default:
                        //        MessageBox.Show("控制器不存在!");
                        //        return;
                        //}
                        //Writejson(IPstr);
                        //name = "IPindex.json";
                        name = "IPindex.xml";
                        Dap_Open(name, IPstr);
                        GetGWStatus();
                        //string b = ip[1];
                        iNodeAddr = short.Parse(ip[1]);
                        iNumData  = Convert.ToInt32(ip[2]);
                        try
                        {
                            for (int i = 0; i < GWCount; i++)
                            {
                                if (iNodeAddr != 0)
                                {
                                    Dapapi.AB_LB_DspNum(GWID[i], iNodeAddr, iNumData, iDigitPoint, iLEDInterval);
                                    Bigling(iNodeAddr, i);
                                }
                                else
                                {
                                    Dapapi.AB_LB_DspNum(GWID[i], -252, iNumData, iDigitPoint, iLEDInterval);
                                    Dapapi.AB_LB_DspNum(GWID[i], 252, iNumData, iDigitPoint, iLEDInterval);
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message.ToString());
                        }
                        break;
                    }
                    else
                    {
                        tb_receive.Text = "没有找到指定ID的Message";
                    }
                }
            }
            else
            {
                tb_receive.Text = "没有读取到数据!";
            }
        }
        /// <summary>
        /// 控制器打开
        /// </summary>
        /// <returns></returns>
        private int Dap_Open()
        {
            int posspace, postab, pos;

            tb_Addrlist.Clear();

            GWCount = 0;
            if (!System.IO.File.Exists("IPINDEX"))
            {
                MessageBox.Show("文件IPINDEX不存在!");
                return(-1);
            }
            try
            {
                using (System.IO.StreamReader sr = new System.IO.StreamReader("IPINDEX"))
                {
                    String line;
                    // Read and display lines from the file until the end of
                    // the file is reached.
                    while ((line = sr.ReadLine()) != null)
                    {
                        GWCount++;
                        posspace = line.IndexOf(" ");     //find space
                        postab   = line.IndexOf((char)9); //find tab

                        if (posspace <= 0)
                        {
                            posspace = postab;
                        }
                        if (postab <= 0)
                        {
                            postab = posspace;
                        }
                        pos = System.Math.Min(posspace, postab);
                        if (pos <= 0)
                        {
                            MessageBox.Show("IPINDEX格式错误!");
                            return(-1);
                        }

                        tb_Addrlist.AppendText(line + "\r\n");

                        GWID[GWCount - 1] = int.Parse(line.Substring(0, pos));
                        diagnosis[GWCount - 1].Init(2);
                    }
                }
            }
            catch (Exception e)
            {
                MessageBox.Show("读取文件IPINDEX失败!" + e.Message);
                return(-1);
            }

            if (APIOpen() < 0)
            {
                MessageBox.Show("初始化API失败!");
                return(-1);
            }

            MessageBox.Show("API Open Success!");

            for (int i = 0; i < GWCount; i++)
            {
                if (Dapapi.AB_GW_Open(GWID[i]) < 0)
                {
                    MessageBox.Show("控制器'" + GWID[i] + "'打开失败!");
                }
            }

            return(1);
        }