Example #1
1
 /// <summary>
 /// 从服务器中获得图片
 /// </summary>
 /// <param name="savePath">图片保存相对路径</param>
 /// <param name="pl">显示图片的容器</param>
 public void getPic_Server(string filepath, Panel pl)
 {
     if (string.IsNullOrEmpty(filepath))
         return;
     int port = 2010;
     string ipsrv = "127.0.0.1";
     string sport = DataAccRes.AppSettings("Granity文件服务");
     string conn = DataAccRes.DefaultDataConnInfo.Value;
     if (!string.IsNullOrEmpty(sport))
         try { port = Convert.ToInt32(sport); }
         catch { return; }
     Regex regIP = new Regex(@"server=([\w.\(\)]*)(;|\\)");
     if (regIP.IsMatch(conn))
     {
         Match mt = regIP.Match(conn);
         if (mt.Groups.Count > 1)
             ipsrv = mt.Groups[1].Value.ToLower();
         if ("(local)" == ipsrv || "127.0.0.1" == ipsrv)
             ipsrv = Dns.GetHostName();
         ipsrv = Dns.GetHostAddresses(ipsrv)[0].ToString();
     }
     CommiTarget target = new CommiTarget(ipsrv, port, CommiType.TCP);
     target.setProtocol(CmdFileTrans.PTL);
     CmdFileTrans cmd = new CmdFileTrans(false);
     cmd.GetFile(filepath);
     CommiManager.GlobalManager.SendCommand(target, cmd);
     if (cmd.EventWh.WaitOne(new TimeSpan(0, 0, 15), false))
     {
         byte[] data = cmd.FileContext;
         if (data.Length < 1)
             return;
         MemoryStream stream = new MemoryStream(data);
         pl.BackgroundImage = Image.FromStream(stream);
     }
 }
 /// <summary>
 /// 构造函数,默认成功
 /// </summary>
 /// <param name="client">通讯的Socket/UdpClient/SerailPort</param>
 /// <param name="param">通讯参数,IP地址或串口参数</param>
 /// <param name="cmds">当前进行通讯的指令列表</param>
 /// <param name="response">响应结果</param>
 public ErrorCommiEventArgs(object client, CommiTarget param, CommandBase cmd, Exception ex)
 {
     this.Client         = client;
     this.CurrentCommand = cmd;
     this.Target         = param;
     this.ex             = ex;
 }
 /// <summary>
 /// 构造函数,默认成功
 /// </summary>
 /// <param name="client">通讯的Socket/UdpClient/SerailPort</param>
 /// <param name="param">通讯参数,IP地址或串口参数</param>
 /// <param name="cmds">当前进行通讯的指令列表</param>
 /// <param name="response">响应结果</param>
 public ResponseEventArgs(object client, CommiTarget param, CommandBase[] cmds, byte[] response)
 {
     this.Client = client;
     this.Commands = cmds;
     this.Response = response;
     this.ContentLen = response.Length;
     this.Target = param;
 }
 /// <summary>
 /// 构造函数,默认成功
 /// </summary>
 /// <param name="client">通讯的Socket/UdpClient/SerailPort</param>
 /// <param name="param">通讯参数,IP地址或串口参数</param>
 /// <param name="cmds">当前进行通讯的指令列表</param>
 /// <param name="response">响应结果</param>
 public ResponseEventArgs(object client, CommiTarget param, CommandBase[] cmds, byte[] response)
 {
     this.Client     = client;
     this.Commands   = cmds;
     this.Response   = response;
     this.ContentLen = response.Length;
     this.Target     = param;
 }
 /// <summary>
 /// 构造函数,默认成功
 /// </summary>
 /// <param name="client">通讯的Socket/UdpClient/SerailPort</param>
 /// <param name="cmds">当前进行通讯的指令列表</param>
 /// <param name="response">响应结果</param>
 /// <param name="cmd">当前指令</param>
 /// <param name="success">响应是否成功</param>
 public ResponseEventArgs(object client, CommiTarget param, CommandBase[] cmds, byte[] response, CommandBase cmd, bool success)
 {
     this.Client         = client;
     this.Commands       = cmds;
     this.Response       = response;
     this.ContentLen     = null == response ? 0 : response.Length;
     this.CurrentCommand = cmd;
     this.Success        = success;
     this.Target         = param;
 }
Example #6
0
        /// <summary>
        /// 克隆通讯协议参数
        /// </summary>
        /// <returns>创建新的协议参数,参数值相同</returns>
        public CommiTarget Clone()
        {
            CommiTarget target = new CommiTarget();

            target.protocolType = this.protocolType;

            if (null != this.srvEndPoint)
            {
                target.srvEndPoint = new IPEndPoint(this.srvEndPoint.Address, this.srvEndPoint.Port);
            }

            target.portName = this.portName;
            target.baudRate = this.baudRate;
            target.parity   = this.parity;
            target.dataBits = this.dataBits;
            target.stopBits = this.stopBits;
            target.setProtocol(this.ptl);
            return(target);
        }
Example #7
0
 private void bnCommand_Click(object sender, EventArgs e)
 {
     if ("Æô¶¯" == this.bnCommand.Text)
     {
         CommiTarget target = new CommiTarget("COM3", 19200);
         bool su = cmdCard.SetTarget(target, 3, true);
         if (!su)
         {
             cmdCard.SetTarget(null, -1, true);
             MessageBox.Show("²»ÄÜÆô¶¯Ñ²¼ì£¡", "Ìáʾ", MessageBoxButtons.OK, MessageBoxIcon.Warning);
             return;
         }
         this.tmRefresh.Start();
         this.bnCommand.Text = "Í£Ö¹";
     }
     else
     {
         this.tmRefresh.Stop();
         cmdCard.SetTarget(null, -1, true);
         this.lbState.Text = "";
         this.bnCommand.Text = "Æô¶¯";
     }
 }
Example #8
0
        /// <summary>
        /// ���÷�����
        /// </summary>
        /// <param name="target">��������ַ</param>
        /// <param name="stationNum">������վַ</param>
        /// <param name="isCardIC">�Ƿ�IC��</param>
        /// <returns>�Ƿ�ɹ����÷�����</returns>
        public bool SetTarget(CommiTarget target, int stationNum, bool isCardIC)
        {
            //���������򱣳ֵ�ǰ״̬
            if (null != target && stationNum > 0 && stationNum < 255 && null!=this.targetwr)
                if (this.addrst == Convert.ToString(stationNum) && this.isCardIC == isCardIC
                    && ((null != target.SrvEndPoint && null != this.targetwr.SrvEndPoint && this.targetwr.SrvEndPoint.Port == target.SrvEndPoint.Port && this.targetwr.SrvEndPoint.Address.ToString() == target.SrvEndPoint.Address.ToString())
                    || (this.targetwr.PortName == target.PortName && this.targetwr.BaudRate == target.BaudRate)))
                {
                    if (!string.IsNullOrEmpty(this.cardid) || 0 == this.stateChecking)
                        return true;
                    this.reChecking(1);
                    return true;
                }
            this.TimeSendInv = new TimeSpan(24, 0, 0);
            this.stateChecking = 0;
            this.cardid = "";
            this.cardserno = "";
            this.cardnum = "";

            string tagdata = "@�豸��ַ=" + this.addrst;
            //ԭ�������ѻ�
            string[,] cmds ={ { "��������", "�ѻ�" }, { "��������", "����" } };
            if (null != this.targetwr && !string.IsNullOrEmpty(this.addrst))
            {
                for (int i = 0; i < cmds.GetLength(0); i++)
                {
                    this.setCommand(cmds[i, 0], cmds[i, 1], tagdata);
                    this.ResetState();
                    this.commiMgr.SendCommand(this.targetwr, this);
                    this.EventWh.WaitOne(this.waitTime, false);
                }
                this.commiMgr.RemoveCommand(this.targetwr, this);
            }

            //�÷������ѻ���������ʾ
            this.isCardIC = isCardIC;
            this.targetwr = null;
            this.addrst = "3";
            if (null == target || stationNum < 1 || stationNum > 255)
                return false;
            this.targetwr = target;
            this.addrst = Convert.ToString(stationNum);
            target.setProtocol(Protocol.PTLCard);
            tagdata = "@�豸��ַ=" + this.addrst;
            cmds = new string[,] { { "��������", "����" }, { "��������", "����ͻ" } };
            if (!isCardIC)
                cmds = new string[,] { { "��������", "����" } };
            for (int i = 0; i < cmds.GetLength(0); i++)
            {
                this.setCommand(cmds[i, 0], cmds[i, 1], tagdata);
                this.ResetState();
                this.commiMgr.SendCommand(this.targetwr, this);
                if (!this.EventWh.WaitOne(this.waitTime, false))
                    return false;
            }
            this.tmIDcache.Change(Timeout.Infinite, Timeout.Infinite);
            this.TimeSendInv = new TimeSpan(3000000);
            this.stateChecking = isCardIC ? 2 : 1;
            return true;
        }
Example #9
0
 /// <summary>
 /// 对目标通讯启动心跳,已经有则不会重复
 /// </summary>
 /// <param name="mgr">通讯管理器</param>
 /// <param name="target">通讯目标</param>
 public static CommandBase OpenHeaderBeat(CommiManager mgr, CommiTarget target)
 {
     if (null == mgr || null == target)
         return null;
     target.setProtocol(CmdFileTrans.PTL);
     mgr.SendCommand(target, CmdHeaderBeat);
     return CmdHeaderBeat;
 }
        /// <summary>
        /// 获取数据行的设备目标位置参数
        /// 记录包含字段【访问方式】(TCP/UDP/SerialPort)、【端口】(60000/COM1)、【地址】(192.168.1.146)
        /// </summary>
        /// <param name="dr">数据记录</param>
        /// <returns></returns>
        private CommiTarget getTarget(DataRow dr)
        {
            if (null == dr || (DBNull.Value == dr["串口"] && DBNull.Value == dr["IP地址"]))
                return null;
            CommiTarget target = new CommiTarget();
            CommiType commiType = CommiType.UDP;
            string stype = Convert.ToString(dr["通讯类别"]);
            switch (stype)
            {
                case "TCP/IP(局域网)":
                    commiType = CommiType.TCP; break;
                case "UDP/IP(局域网)":
                    commiType = CommiType.UDP; break;
                default:
                    commiType = CommiType.SerialPort; break;
            }
            try
            {
                if (CommiType.SerialPort == commiType)
                {
                    string portname = Convert.ToString(dr["串口"]);
                    int baudRate = Convert.ToInt16(dr["波特率"]);
                    int dataBits = Convert.ToInt16(dr["数据位"]);
                    decimal s = Convert.ToDecimal(dr["停止位"]);
                    StopBits sb = StopBits.None;
                    if (1 == s) sb = StopBits.One;
                    else if (2 == s) sb = StopBits.Two;
                    else if (1 < s && s < 2) sb = StopBits.OnePointFive;

                    target.SetProtocolParam(portname, baudRate, Parity.None, dataBits, sb);
                }
                else
                {
                    string addr = Convert.ToString(dr["IP地址"]);
                    if (string.IsNullOrEmpty(addr) || DBNull.Value == dr["端口"])
                        return null;
                    int port = Convert.ToInt32(dr["端口"]);
                    target.SetProtocolParam(addr, port, commiType);
                }
            }
            catch (Exception ex)
            {
                NameValueCollection data = new NameValueCollection();
                data["操作"] = "创建通讯目标";
                data["设备ID"] = Convert.ToString(dr["ID"]);
                ServiceTool.LogMessage(ex, data, EventLogEntryType.Error);
                return null;
            }
            return target;
        }
Example #11
0
        /// <summary>
        /// 搜索网络内支持UDP通讯的设备信息,设备信息使用tag格式数据
        /// </summary>
        /// <returns>返回tag格式数据信息</returns>
        public static string[] SearchUDPnet()
        {
            IPEndPoint srv = new IPEndPoint(IPAddress.Broadcast, initport);
            CommiTarget target = new CommiTarget(srv, CommiType.UDP);
            target.setProtocol(ptlZnet);

            DateTime dtStart = DateTime.Now;
            CommandBase cmd = new CommandBase(false);
            cmd.TimeSendInv = new TimeSpan(0, 0, 50);
            cmd.TimeOut = new TimeSpan(0, 0, 2);
            cmd.TimeFailLimit = new TimeSpan(0, 0, 5);
            cmd.TimeLimit = new TimeSpan(0, 0, 20);
            cmd.IsResposeHandle = isRpsZnet;

            cmd.setCommand(initcmd, true);
            cmd.ResponseHandle += new EventHandler<ResponseEventArgs>(cmd_ResponseHandle);
            CommiManager.GlobalManager.SendCommand(target, cmd);
            //广播搜索,有多个设备返回信息,直到超时停止接收
            List<string> infolist = cmd.Tag as List<string>;
            while (cmd.EventWh.WaitOne(cmd.TimeLimit, false) && DateTime.Now - dtStart < cmd.TimeLimit)
            {
                infolist = cmd.Tag as List<string>;
                if (null == infolist || infolist.Count < 1)
                    continue;
                string[] infos = infolist.ToArray();
                bool iscomplete = true;
                for (int i = 0; i < infos.Length; i++)
                {
                    if (!string.IsNullOrEmpty(basefun.valtag(infos[i], "工作端口")))
                        continue;
                    iscomplete = false;
                    break;
                }
                if (iscomplete)
                    break;
            }
            cmd.TimeSendInv = new TimeSpan(0, 0, -10);
            CommiManager.GlobalManager.RemoveCommand(target, cmd);
            //返回搜索结果
            infolist = cmd.Tag as List<string>;
            cmd.Tag = null;
            if (null == infolist || infolist.Count < 1)
                return new string[0];
            return infolist.ToArray();
        }
Example #12
0
        /// <summary>
        /// 设置通讯ZNetCom模块端口好,及串口波特率
        /// </summary>
        /// <param name="macaddr">物理地址,为空则忽略操作</param>
        /// <param name="netport">网络端口</param>
        /// <param name="baudRate">波特率</param>
        /// <param name="parity">奇偶校验</param>
        /// <param name="dataBits">数据位</param>
        /// <param name="stopBits">停止位</param>
        /// <returns>修改是否成功</returns>
        public static bool SetSerialZnet(string macaddr, int netport, int baudRate, Parity parity, int dataBits, StopBits stopBits)
        {
            if (string.IsNullOrEmpty(macaddr) || netport < 0 || netport > 0xFFFF || baudRate < 0 || baudRate > 0xFFFFFF || dataBits < 5 || dataBits > 8)
                return false;
            //读取串口通讯
            string strcmd = string.Format(infocmd, macaddr.Replace("-", " "), "A114010202");

            IPEndPoint srv = new IPEndPoint(IPAddress.Broadcast, infoport);
            CommiTarget target = new CommiTarget(srv, CommiType.UDP);
            target.setProtocol(ptlznet);
            CommandBase cmd = new CommandBase(false);
            cmd.TimeOut = new TimeSpan(0, 0, 0, 0, 300);
            cmd.TimeFailLimit = new TimeSpan(0, 0, 1);
            cmd.TimeLimit = new TimeSpan(0, 0, 3);
            cmd.IsResposeHandle = isResponseCmd;
            cmd.setCommand(strcmd, true);
            CommiManager.GlobalManager.SendCommand(target, cmd);
            if (!cmd.EventWh.WaitOne(cmd.TimeFailLimit, false))
                return false;
            //修改设备信息
            string response = CommandBase.Parse(cmd.ResponseData, true);
            string funcode = "A1FE01030200";
            string strport = Convert.ToString(netport, 16).PadLeft(4, '0');
            string strbaud = Convert.ToString(baudRate, 16).PadLeft(6, '0');
            string strdata = Convert.ToString(dataBits, 16).PadLeft(2, '0');
            string strstop = StopBits.None == stopBits ? "00" : StopBits.One == stopBits ? "01" : "02";
            string strpartity = Parity.None == parity ? "00" : Parity.Even == parity ? "01" : Parity.Odd == parity ? "02" : Parity.Mark == parity ? "03" : "04";
            string[] cmdfun ={ funcode, strport, strbaud, strdata, strstop, strpartity };
            int[,] cmdpos ={ { 10, 5 }, { 16, 2 }, { 26, 3 }, { 29, 1 }, { 30, 1 }, { 31, 1 } };
            int leninv = 0;
            for (int i = 0; i < cmdfun.Length; i++)
            {
                if (string.IsNullOrEmpty(cmdfun[i]) || string.IsNullOrEmpty(cmdfun[i].Replace("0", "")))
                    continue;
                response = response.Substring(0, cmdpos[i, 0] * 2 + leninv) + cmdfun[i]
                           + response.Substring(cmdpos[i, 0] * 2 + leninv + cmdpos[i, 1] * 2, response.Length);
                leninv += cmdfun[i].Length - cmdpos[i, 1] * 2;
            }
            //发送修改指令,再发送确认指令
            cmd.setCommand(response, true);
            cmd.ResetState();
            CommiManager.GlobalManager.SendCommand(target, cmd);
            cmd.EventWh.WaitOne(cmd.TimeFailLimit, false);
            strcmd = string.Format(infomdi, macaddr.Replace("-", ""));
            cmd.setCommand(strcmd, true);
            cmd.ResetState();
            CommiManager.GlobalManager.SendCommand(target, cmd);
            cmd.EventWh.WaitOne(cmd.TimeFailLimit, false);
            return true;
        }
Example #13
0
        /// <summary>
        /// 搜索网络内支持UDP通讯的设备信息,设备信息使用tag格式数据
        /// </summary>
        /// <returns>返回tag格式数据信息</returns>
        public static string[] SearchUDPDoor()
        {
            IPEndPoint srv = new IPEndPoint(IPAddress.Broadcast, searport);
            CommiTarget target = new CommiTarget(srv, CommiType.UDP);
            target.setProtocol(Protocol.PTLDoor);

            DateTime dtStart = DateTime.Now;
            CommandBase cmd = new CommandBase(false);
            cmd.TimeSendInv = new TimeSpan(0, 0, 50);
            cmd.TimeOut = new TimeSpan(0, 0, 2);
            cmd.TimeFailLimit = new TimeSpan(0, 0, 5);
            cmd.TimeLimit = new TimeSpan(0, 0, 20);
            cmd.IsResposeHandle = isRpsDoor;

            cmd.setCommand(searcmd, true);
            cmd.ResponseHandle += new EventHandler<ResponseEventArgs>(cmd_RpsDoorHandle);
            CommiManager.GlobalManager.SendCommand(target, cmd);
            //广播搜索,有多个设备返回信息,直到超时停止接收
            List<string> infolist = cmd.Tag as List<string>;
            while (cmd.EventWh.WaitOne(cmd.TimeLimit, false) && DateTime.Now - dtStart < cmd.TimeLimit)
            {
                cmd.EventWh.Reset();
            }
            cmd.TimeSendInv = new TimeSpan(0, 0, -10);
            CommiManager.GlobalManager.RemoveCommand(target, cmd);
            //返回搜索结果
            infolist = cmd.Tag as List<string>;
            cmd.Tag = null;
            if (null == infolist || infolist.Count < 1)
                return new string[0];
            return infolist.ToArray();
        }
 /// <summary>
 /// 构造函数,默认成功
 /// </summary>
 /// <param name="client">通讯的Socket/UdpClient/SerailPort</param>
 /// <param name="cmds">当前进行通讯的指令列表</param>
 /// <param name="response">响应结果</param>
 /// <param name="cmd">当前指令</param>
 /// <param name="success">响应是否成功</param>
 public ResponseEventArgs(object client, CommiTarget param, CommandBase[] cmds, byte[] response, CommandBase cmd, bool success)
 {
     this.Client = client;
     this.Commands = cmds;
     this.Response = response;
     this.ContentLen = null == response ? 0 : response.Length;
     this.CurrentCommand = cmd;
     this.Success = success;
     this.Target = param;
 }
Example #15
0
 /// <summary>
 /// ����ͨѶ����,portΪ�ջ�station��Χ����ȷ��ͨѶ�ÿ�
 /// </summary>
 /// <param name="port">ͨѶ�˿�</param>
 /// <param name="baudRate">ͨѶ������</param>
 /// <param name="station">ͨѶվַ</param>
 /// <param name="isCardIC">�Ƿ�IC��</param>
 /// <returns>�Ƿ�ɹ�����ͨѶ����</returns>
 public bool setTarget(string port, int baudRate, int station, bool isCardIC)
 {
     CommiManager.GlobalManager.ClearCommand();
     if (string.IsNullOrEmpty(port) || station < 1 || station > 255)
     {
         this.target = null;
         this.cmdCard.SetTarget(null, -1, false);
         return false;
     }
     try
     {
         this.Beat();
         this.target = new CommiTarget(port, baudRate);
         this.station = station;
         this.isCardIC = isCardIC;
         return this.cmdCard.SetTarget(target, station, isCardIC);
     }
     catch (Exception ex)
     {
         this.target = null;
         this.cmdCard.SetTarget(null, -1, false);
         return false;
     }
     return true;
 }
 /// <summary>
 /// 构造函数,默认成功
 /// </summary>
 /// <param name="client">通讯的Socket/UdpClient/SerailPort</param>
 /// <param name="param">通讯参数,IP地址或串口参数</param>
 /// <param name="cmds">当前进行通讯的指令列表</param>
 /// <param name="response">响应结果</param>
 public ErrorCommiEventArgs(object client, CommiTarget param, CommandBase cmd, Exception ex)
 {
     this.Client = client;
     this.CurrentCommand = cmd;
     this.Target = param;
     this.ex = ex;
 }
Example #17
0
 /// <summary>
 /// 接收传递通讯
 ///     包含参数: len,dir=request/response,cmd=TransFile.trans,source,target,
 ///               CommiType,addr=ipaddr/COM1,port,baudRate,parity,dataBits,stopBits
 /// </summary>
 /// <param name="sender">触发事件的实例</param>
 /// <param name="e">响应参数</param>
 private static void onCommiTransHandle(object sender, ResponseEventArgs e)
 {
     CmdFileTrans trans = sender as CmdFileTrans;
     if (null == trans || null == e || null == e.Target)
         return;
     NameValueCollection ps = trans.FileHeader;
     byte[] data = trans.FileContext;
     if ("TransFile.trans" != ps["cmd"] || "request" != ps["dir"])
         return;
     if (string.IsNullOrEmpty(ps["CommiType"]) || string.IsNullOrEmpty(ps["addr"]))
         return;
     CommiType commitype = CommiType.SerialPort;
     string addr = ps["addr"];
     int port = -1;
     //检测地址
     try
     {
         addr = addr.ToUpper();
         if (!addr.StartsWith("COM"))
             commitype = (CommiType)Enum.Parse(typeof(CommiType), ps["CommiType"], true);
         if (!string.IsNullOrEmpty(ps["port"]))
             port = Convert.ToInt32(ps["port"]);
     }
     catch { return; }
     //检测通讯参数
     if (CommiType.SerialPort != commitype && port < 0)
         return;
     if (CommiType.SerialPort == commitype &&
         (string.IsNullOrEmpty(ps["baudRate"]) || string.IsNullOrEmpty(ps["parity"])
             || string.IsNullOrEmpty(ps["dataBits"]) || string.IsNullOrEmpty(ps["stopBits"])))
         return;
     //创建通讯目标
     CommiTarget target = null;
     if (CommiType.SerialPort != commitype)
         target = new CommiTarget(addr, port, commitype);
     else
         try
         {
             int baudRate = Convert.ToInt32(ps["baudRate"]);
             Parity parity = (Parity)Enum.Parse(typeof(Parity), ps["parity"], true);
             int databits = Convert.ToInt16(ps["dataBits"]);
             StopBits stopBits = (StopBits)Enum.Parse(typeof(StopBits), ps["stopBits"], true);
             target = new CommiTarget(addr, baudRate, parity, databits, stopBits);
         }
         catch { return; }
     target.setProtocol(Protocol.PTLCard);
     switch (ps["dtpl"])
     {
         case "停车场":
             target.setProtocol(Protocol.PTLPark); break;
         case "门禁":
             target.setProtocol(Protocol.PTLDoor); break;
         case "消费":
             target.setProtocol(Protocol.PTLEatery); break;
     }
     //执行传递的指令
     CmdProtocol cmd = new CmdProtocol(false);
     cmd.setCommand(data);
     ps["dir"] = "response";
     CommiManager.GlobalManager.SendCommand(target, cmd);
     if (!cmd.EventWh.WaitOne(800, false))
         ps["msg"] = "目标通讯超时失败";
     data = cmd.ResponseData;
     ps["len"] = data.LongLength.ToString();
     byte[] fh = SvrFileTrans.ParseInfo(ps);
     byte[] response = new byte[fh.LongLength + data.LongLength];
     Array.Copy(fh, response, fh.LongLength);
     if (data.Length > 0)
         Array.Copy(data, 0, response, fh.LongLength, data.LongLength);
     cmd.setCommand(response);
     CommiManager.GlobalManager.SendCommand(e.Target, cmd, true);
 }
Example #18
0
 /// <summary>
 /// 传递通讯指令
 ///     包含参数: len,dir=request/response,cmd=TransFile.trans,source,target,
 ///               CommiType,addr=ipaddr/COM1,port,baudRate,parity,dataBits,stopBits
 /// </summary>
 /// <param name="src">当前指令自身IP地址</param>
 /// <param name="proxy">执行目标的代理IP地址</param>
 /// <param name="dest">最终目标位置</param>
 /// <param name="dtpl">目标协议类型名称</param>
 /// <param name="dcmd">目标指令名称</param>
 /// <param name="data">传送的指令字节,本地执行时返回响应字节,非本地执行则返回0长度字节</param>
 /// <returns></returns>
 public void CommiTrans(IPAddress proxy, CommiTarget dest,string dtpl, string dcmd, ref byte[] data)
 {
     if (null == proxy || null == dest || null == data || data.Length < 1)
         return;
     string ipaddr = proxy.ToString();
     if (string.IsNullOrEmpty(this.CmdId))
         this.CmdId = Guid.NewGuid().ToString();
     NameValueCollection info = new NameValueCollection();
     info["dtpl"] = dtpl;
     info["dcmd"] = dcmd;
     string[,] head ={ {"id",this.CmdId},{"cmd","TransFile.trans"},{"len", data.LongLength.ToString()},
                 {"dir","request"},{"target",proxy.ToString()},{"CommiType",dest.ProtocolType.ToString()}};
     for (int i = 0; i < head.GetLength(0); i++)
         info.Add(head[i, 0], head[i, 1]);
     if (CommiType.SerialPort != dest.ProtocolType)
     {
         info.Add("addr", dest.SrvEndPoint.Address.ToString());
         info.Add("port", dest.SrvEndPoint.Port.ToString());
     }
     else
     {
         info.Add("addr", dest.PortName);
         info.Add("baudRate", dest.BaudRate.ToString());
         info.Add("parity", dest.Parity.ToString());
         info.Add("dataBits", dest.DataBits.ToString());
         info.Add("stopBits", dest.StopBits.ToString());
     }
     bool islocal = false;
     string addr = proxy.ToString();
     IPAddress[] locals = Dns.GetHostAddresses(Dns.GetHostName());
     foreach (IPAddress ip in locals)
         if (addr == ip.ToString())
         {
             islocal = true;
             break;
         }
     if ("127.0.0.1" == addr)
         islocal = true;
     //本机通讯或目标是代理机本机则直接通讯
     if (islocal || proxy.ToString() == info["addr"])
     {
         info["dir"] = "response";
         info["source"] = info["target"];
         CmdProtocol cmd = new CmdProtocol(false);
         cmd.setCommand(dtpl, dcmd, "");
         cmd.setCommand(data);
         CommiManager.GlobalManager.SendCommand(dest, cmd);
         if (!cmd.EventWh.WaitOne(800, false))
             info["msg"] = "目标通讯超时失败";
         data = cmd.ResponseData;
         info["len"] = data.LongLength.ToString();
         CommiManager.GlobalManager.RemoveCommand(dest, cmd);
     }
     byte[] fh = SvrFileTrans.ParseInfo(info);
     byte[] context = new byte[fh.LongLength + data.LongLength];
     Array.Copy(fh, context, fh.LongLength);
     Array.Copy(data, 0, context, fh.LongLength, data.LongLength);
     this.setCommand(context);
     if (!islocal) data = new byte[0];
 }
Example #19
0
 /// <summary>
 /// 对目标通讯关闭心跳
 /// </summary>
 /// <param name="mgr">通讯管理器</param>
 /// <param name="target">通讯目标</param>
 public static void CloseHeaderBeat(CommiManager mgr, CommiTarget target)
 {
     if (null == mgr || null == target)
         return;
     mgr.RemoveCommand(target, CmdHeaderBeat);
 }
Example #20
0
        /// <summary>
        /// ���չ㲥����,��Ҫ��ν�����ȡ������Ϣ
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private static void cmd_ResponseHandle(object sender, ResponseEventArgs e)
        {
            if (null == sender || !(sender is CommandBase) || null == e || !e.Success || null == e.Response || e.Response.Length < 1)
                return;
            CommandBase cmd = sender as CommandBase;
            string rsl = CommandBase.Parse(cmd.ResponseData, true);
            //��鹦���룺�������ܣ���ȡ������Ϣ����ȡ��ϸ��Ϣ
            string codesearch  = "A1FD000922";
            string codedetailA = "A114010200";
            string codedetailB = "A114010202";
            string code = parseFunCode(rsl);
            string addr = parseAddrMac(rsl);
            if (codesearch != code && codedetailA != code && codedetailB != code)
                return;

            //��ʽ��������ͨ/�����ַ/IP��ַ/�ı�/����
            string[] formatinit ={ "������,10,4;", "�����ַ,4,6", "IP��ַ,17,4;", "", "" };
            string[] formatdtlA ={"������,10,4;", "�����ַ,4,6",
                                    "IP��ַ,47,4;��������,51,4;����IP,55,4;DNS������,59,4;",
                                    "�豸����,15,16;����,31,5;",
                                    "��ҳ�˿�,71,1;����˿�,72,2;"};
            string[] formatdtlB ={ "������,10,4;", "�����ַ,4,6", "","",
                                    "������ʽ,15,1;�����˿�,16,2;��ʱ�Ͽ�ʱ��,18,3;����ʱ��,21,1;������,26,3;����λ,29,1;ֹͣλ,30,1;У��λ,31,1;"};
            formatdtlB[4] += "�ְ�����,32,3;֡���,35,2;Ŀ��˿�1,47,2;Ŀ��˿�2,49,2;Ŀ��˿�3,51,2;Ŀ��˿�4,53,2;Ŀ��˿�5,55,2;Ŀ��˿�6,57,2;Ŀ��˿�7,59,2;Ŀ��˿�8,61,2;";

            //��ȡ��Ϣ�б�
            List<string> infolist = new List<string>();
            if (null == cmd.Tag)
                cmd.Tag = infolist;

            int index = -1;
            infolist = cmd.Tag as List<string>;
            for (int i = 0; i < infolist.Count; i++)
            {
                if (addr != basefun.valtag(infolist[i], "�����ַ"))
                    continue;
                index = i;
                break;
            }
            string info = "";
            if (index > -1)
                info = infolist[index];
            if (codesearch == code)
                info = parseDetail(rsl, info, formatinit[0], formatinit[1], formatinit[2], formatinit[3], formatinit[4], false);
            else if (codedetailA == code)
                info = parseDetail(rsl, info, formatdtlA[0], formatdtlA[1], formatdtlA[2], formatdtlA[3], formatdtlA[4], false);
            else if (codedetailB == code)
                info = parseDetail(rsl, info, formatdtlB[0], formatdtlB[1], formatdtlB[2], formatdtlB[3], formatdtlB[4], false);
            if (index > -1)
                infolist[index] = info;
            else
                infolist.Add(info);

            //���һ����ȡ��ϸ��Ϣ�����
            if (codedetailB == code)
                return;
            //�ٻ�ȡ������Ϣ������ȡ��ϸ��Ϣ
            IPEndPoint srv = new IPEndPoint(IPAddress.Broadcast, infoport);
            CommiTarget target = new CommiTarget(srv, CommiType.UDP);
            target.setProtocol(ptlZnet);
            string strcmd = string.Format(infocmd, addr.Replace("-", " "), codesearch == code ? "A114000200" : "A114000202");
            CommandBase cmdNext = new CommandBase();
            //ʹ����ͬ��ͬ���¼����ɶ�̬���UDP�����������
            cmdNext.EventWh = cmd.EventWh;
            cmdNext.Tag = cmd.Tag;
            cmdNext.ResponseHandle += new EventHandler<ResponseEventArgs>(cmd_ResponseHandle);
            cmdNext.IsResposeHandle = isResponseCmd;
            cmdNext.setCommand(strcmd, true);
            CommiManager.GlobalManager.SendCommand(target, cmdNext);
        }
Example #21
0
        /// <summary>
        /// 接收广播反馈,需要多次交互获取完整信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private static void cmd_ResponseHandle(object sender, ResponseEventArgs e)
        {
            if (null == sender || !(sender is CommandBase) || null == e || !e.Success || null == e.Response || e.Response.Length < 1)
                return;
            CommandBase cmd = sender as CommandBase;
            string rsl = CommandBase.Parse(cmd.ResponseData, true);
            //检查功能码:搜索功能,获取网络信息,获取详细信息
            string codesearch  = "A1FD000922";
            string codedetailA = "A114010200";
            string codedetailB = "A114010202";
            string code = parseFunCode(rsl);
            string addr = parseAddrMac(rsl);
            if (codesearch != code && codedetailA != code && codedetailB != code)
                return;

            //格式参数:普通/物理地址/IP地址/文本/数字
            string[] formatinit ={ "功能码,10,5;", "物理地址,4,6", "IP地址,17,4;", "", "" };
            string[] formatdtlA ={"功能码,10,5;", "物理地址,4,6",
                                    "IP地址,47,4;子网掩码,51,4;网关IP,55,4;DNS服务器,59,4;",
                                    "设备名称,15,16;密码,31,5;",
                                    "网页端口,71,1;命令端口,72,2;"};
            string[] formatdtlB ={ "功能码,10,5;", "物理地址,4,6", "","",
                                    "工作方式,15,1;工作端口,16,2;超时断开时间,18,3;心跳时间,21,1;波特率,26,3;数据位,29,1;停止位,30,1;校验位,31,1;"};
            formatdtlB[4] += "分包长度,32,3;帧间隔,35,2;目标端口1,47,2;目标端口2,49,2;目标端口3,51,2;目标端口4,53,2;目标端口5,55,2;目标端口6,57,2;目标端口7,59,2;目标端口8,61,2;";

            //读取信息列表
            List<string> infolist = new List<string>();
            if (null == cmd.Tag)
                cmd.Tag = infolist;

            int index = -1;
            infolist = cmd.Tag as List<string>;
            for (int i = 0; i < infolist.Count; i++)
            {
                if (addr != basefun.valtag(infolist[i], "物理地址"))
                    continue;
                index = i;
                break;
            }
            string info = "";
            if (index > -1)
                info = infolist[index];
            if (codesearch == code)
                info = parseDetail(rsl, info, formatinit[0], formatinit[1], formatinit[2], formatinit[3], formatinit[4], false);
            else if (codedetailA == code)
                info = parseDetail(rsl, info, formatdtlA[0], formatdtlA[1], formatdtlA[2], formatdtlA[3], formatdtlA[4], false);
            else if (codedetailB == code)
                info = parseDetail(rsl, info, formatdtlB[0], formatdtlB[1], formatdtlB[2], formatdtlB[3], formatdtlB[4], false);
            if (index > -1)
                infolist[index] = info;
            else
                infolist.Add(info);

            //最后一步获取详细信息后结束
            if (codedetailB == code)
                return;
            //再获取网络信息,最后获取详细信息
            IPEndPoint srv = new IPEndPoint(IPAddress.Broadcast, infoport);
            CommiTarget target = new CommiTarget(srv, CommiType.UDP);
            target.setProtocol(ptlZnet);
            string strcmd = string.Format(infocmd, addr.Replace("-", " "), codesearch == code ? "A114000200" : "A114000202");
            CommandBase cmdNext = new CommandBase();
            //使用相同的同步事件,可动态检测UDP搜索反馈结果
            cmdNext.EventWh = cmd.EventWh;
            cmdNext.Tag = cmd.Tag;
            cmdNext.ResponseHandle += new EventHandler<ResponseEventArgs>(cmd_ResponseHandle);
            cmdNext.IsResposeHandle = isResponseCmd;
            cmdNext.setCommand(strcmd, true);
            CommiManager.GlobalManager.SendCommand(target, cmdNext);
        }
Example #22
0
        /// <summary>
        /// 对同一个target循环执行数据记录关联的指令,执行成功后执行sql更新
        /// </summary>
        /// <param name="drs">指令数据数组</param>
        /// <param name="colmap">字段与指令的映射</param>
        /// <param name="tpl">指令协议类别:停车场/消费/门禁/考勤/卡务中心</param>
        /// <param name="cmd">指令命令名称</param>
        /// <param name="target">通讯目标位置</param>
        /// <param name="deviceID">设备下位机地址</param>
        /// <param name="query">数据更新执行实例</param>
        /// <param name="dbItem">执行更新的数据项</param>
        /// <returns>成功执行返回空,失败返回错误原因</returns>
        public static string ExecuteDataRows(DataRow[] drs, string[,] colmap, string tpl, string cmd, CommiTarget target, string deviceID, QueryDataRes query, string dbItem)
        {
            if (null == drs || drs.Length < 1 || null == colmap || colmap.GetLength(1) < 2 || string.IsNullOrEmpty(tpl) || string.IsNullOrEmpty(cmd))
                return "";
            if (null == target || string.IsNullOrEmpty(deviceID))
                return "";
            //声明一个集合来储存数据
            List<DataRow> drList = new List<DataRow>();
            string msg = "";

            //执行指令
            CmdProtocol cmdP = new CmdProtocol(deviceID, false);
            //循环得到传过来的数据
            foreach (DataRow dr in drs)
            {
                if (null == dr) continue;
                string tagdata = "@设备地址=" + deviceID;
                for (int c = 0; c < colmap.GetLength(0); c++)
                {
                    object val = dr[colmap[c, 1]];
                    if (true.Equals(val)) val = "1";
                    if (false.Equals(val)) val = "0";
                    tagdata = basefun.setvaltag(tagdata, colmap[c, 0], Convert.ToString(val));
                }
                //设置指令
                cmdP.setCommand(tpl, cmd, tagdata);
                cmdP.ResetState();
                //发送指令
                CommiManager.GlobalManager.SendCommand(target, cmdP);
                if (!cmdP.EventWh.WaitOne(2000, false))
                {
                    msg = basefun.setvaltag(tagdata, "{状态}", "通讯超时失败!");
                    break;
                }
                if (string.IsNullOrEmpty(cmdP.ResponseFormat))
                {
                    msg = basefun.setvaltag(tagdata, "{状态}", tagdata + "指令错误!");
                    break;
                }
                drList.Add(dr);
            }
            //更新数据库
            //判断数据源和存储过程是否为空
            if (null == query || string.IsNullOrEmpty(dbItem))
                return msg;
            //得到数据的数量
            Estar.Common.Tools.NameObjectList[] ps = new Estar.Common.Tools.NameObjectList[drList.Count];
            for (int i = 0; i < drList.Count; i++)
                ps[i] = ParamManager.createParam(drList[i]);
            //得到数据与配置的数据已经保持一致,但发现没有执行存储过程。。。
            //执行数据库操作(方法封装在query内)
            bool success = query.ExecuteNonQuery(dbItem, ps, ps, ps);
            
            if (!success)
                msg = basefun.setvaltag(msg, "{状态}", basefun.valtag(msg, "{状态}") + "更新数据库失败!");
            return msg;
        }
Example #23
0
 /// <summary>
 /// 设置通讯ZNetCom模块IP地址端口号及网关
 /// </summary>
 /// <param name="macaddr">物理地址,为空则忽略操作</param>
 /// <param name="ipaddr">IP地址,为空则忽略操作</param>
 /// <param name="maskcode">子网掩码,为空保持原值</param>
 /// <param name="gateway">网关,为空保持原值</param>
 /// <returns>修改是否成功</returns>
 public static bool SetTCPIPZnet(string macaddr, string ipaddr, string maskcode, string gateway)
 {
     if (string.IsNullOrEmpty(macaddr) || string.IsNullOrEmpty(ipaddr) || !regMacaddr.IsMatch(macaddr) || !regIPaddr.IsMatch(ipaddr))
         return false;
     //读取IP地址
     string strcmd = string.Format(infocmd, macaddr.Replace("-", " "), "A114000200");
     
     IPEndPoint srv = new IPEndPoint(IPAddress.Broadcast, infoport);
     CommiTarget target = new CommiTarget(srv, CommiType.UDP);
     target.setProtocol(ptlznet);
     CommandBase cmd = new CommandBase(false);
     cmd.TimeOut = new TimeSpan(0, 0, 0, 0, 300);
     cmd.TimeFailLimit = new TimeSpan(0, 0, 1);
     cmd.TimeLimit = new TimeSpan(0, 0, 3);
     cmd.IsResposeHandle = isResponseCmd;
     cmd.setCommand(strcmd, true);
     CommiManager.GlobalManager.SendCommand(target, cmd);
     if (!cmd.EventWh.WaitOne(cmd.TimeFailLimit, false))
         return false;
     //修改设备信息
     string response = CommandBase.Parse(cmd.ResponseData, true);
     if (ipaddr.Contains(":"))
         ipaddr = ipaddr.Substring(0, ipaddr.IndexOf(":"));
     ipaddr = convertHEX(ipaddr, ".", false);
     maskcode = convertHEX(maskcode, ".", false);
     gateway = convertHEX(gateway, ".", false);
     string funcode = "A1FE01030000";
     string[] cmdfun ={ funcode, ipaddr, maskcode, gateway };
     int[,] cmdpos ={ { 10, 5 }, { 47, 4 }, { 51, 4 }, { 55, 4 } };
     int leninv = 0;
     for (int i = 0; i < cmdfun.Length; i++)
     {
         if (string.IsNullOrEmpty(cmdfun[i]))
             continue;
         response = response.Substring(0, cmdpos[i, 0] * 2 + leninv) + cmdfun[i] 
                    + response.Substring(cmdpos[i, 0] * 2 + leninv + cmdpos[i, 1] * 2, response.Length);
         leninv += cmdfun[i].Length - cmdpos[i, 1] * 2;
     }
     //发送修改指令,再发送确认指令
     cmd.setCommand(response, true);
     cmd.ResetState();
     CommiManager.GlobalManager.SendCommand(target, cmd);
     cmd.EventWh.WaitOne(cmd.TimeFailLimit, false);
     strcmd = string.Format(infomdi, macaddr.Replace("-", ""));
     cmd.setCommand(strcmd, true);
     cmd.ResetState();
     CommiManager.GlobalManager.SendCommand(target, cmd);
     cmd.EventWh.WaitOne(cmd.TimeFailLimit, false);
     return true;
 }
Example #24
0
 /// <summary>
 /// ����ָ���ȡָ��������ͨѶʧ��ʱ�Զ�����ִ��5��
 /// </summary>
 /// <param name="mgr">ͨѶ������</param>
 /// <param name="target">ͨѶĿ��</param>
 /// <param name="cmd">ִ��ָ��</param>
 /// <param name="timeout">��ʱ���</param>
 /// <returns>����ָ����Ӧ���</returns>
 private static string getResponse(CommiManager mgr, CommiTarget target, CmdProtocol cmd, TimeSpan timeout)
 {
     if (null == mgr || null == target || null == cmd)
         return "";
     if(null==cmd.EventWh)
         cmd.EventWh = new ManualResetEvent(false);
     string msg = "";
     for (int i = 0; i < 5; i++)
     {
         msg = "";
         cmd.ResetState();
         mgr.SendCommand(target, cmd);
         if (cmd.EventWh.WaitOne(timeout, false))
             msg = cmd.ResponseFormat;
         string suc = basefun.valtag(msg, "Success");
         if ("true" == suc)
             break;
         Thread.Sleep(200);
     }
     return msg;
 }
Example #25
0
        /// <summary>
        /// 设置门禁IP地址端口号及网关;无IP地址忽略操作,无其它则默认保持原来的值
        /// </summary>
        /// <param name="station">站址序列号</param>
        /// <param name="ipaddr">IP地址</param>
        /// <param name="maskcode">掩码,默认255.255.255.0</param>
        /// <param name="gateway">网关</param>
        /// <param name="macaddr">物理地址</param>
        public static bool SetTCPIPDoor(int station, string ipaddr, string maskcode, string gateway, string macaddr)
        {
            //校验参数格式
            if (station < 0 || station > 65534 || string.IsNullOrEmpty(ipaddr) || !regIPaddr.IsMatch(ipaddr))
                return false;
            if (!string.IsNullOrEmpty(maskcode) && !regIPaddr.IsMatch(maskcode))
                return false;
            if (!string.IsNullOrEmpty(gateway) && !regIPaddr.IsMatch(gateway))
                return false;
            if (!string.IsNullOrEmpty(macaddr) && !regMacaddr.IsMatch(macaddr))
                return false;
            //网关、掩码或物理地址为空时,使用1102功能码,都需要设置时使用11F2功能码
            string funcode = "F211";
            if (string.IsNullOrEmpty(maskcode) && string.IsNullOrEmpty(gateway) && string.IsNullOrEmpty(macaddr))
                funcode = "0211";
            if (string.IsNullOrEmpty(macaddr))
                macaddr = "00-00-00-00-00-00";
            if (string.IsNullOrEmpty(gateway))
                gateway = "00.00.00.00";
            if (string.IsNullOrEmpty(maskcode))
                maskcode = "00.00.00.00";
            if (maskcode.Contains(":") || gateway.Contains(":"))
                return false;
            string port = "60000";
            int idxp = ipaddr.IndexOf(":");
            if (idxp>0)
            {
                port = ipaddr.Substring(idxp + 1, ipaddr.Length - idxp - 1);
                ipaddr = ipaddr.Substring(0, idxp);
            }
            //转换16进制值
            string stcode = Convert.ToString(station, 16).PadLeft(4, '0');
            port = Convert.ToString(Convert.ToUInt32(port), 16).PadLeft(4, '0').Substring(0, 4);
            ipaddr = convertHEX(ipaddr, ".", false);
            gateway = convertHEX(gateway, ".", false);
            maskcode = convertHEX(maskcode, ".", false);
            macaddr = convertHEX(macaddr, "-", true);
            //计算校验码
            string codevali = sumValiHex(string.Format("{0} {1} {2} {3} {4} {5} {6}", stcode, funcode, macaddr, ipaddr, maskcode, gateway, port));
            codevali = codevali.PadLeft(4, '0');
            codevali = codevali.Substring(codevali.Length - 4, 4);
            string strcmd = string.Format("7E {0} {1} {2} {3} {4} {5} {6} 00 00 00 00 00 00 {7} 0D", 
                                          stcode, funcode, macaddr, ipaddr, maskcode, gateway, port, codevali);
            //设置执行指令
            IPEndPoint srv = new IPEndPoint(IPAddress.Broadcast, searport);
            CommiTarget target = new CommiTarget(srv, CommiType.UDP);
            target.setProtocol(Protocol.PTLDoor);

            CommandBase cmd = new CommandBase(false);
            cmd.TimeOut = new TimeSpan(0, 0, 0, 0, 500);
            cmd.TimeFailLimit = new TimeSpan(0, 0, 3);
            cmd.TimeLimit = new TimeSpan(0, 0, 5);
            cmd.IsResposeHandle = isRpsDoor;
            cmd.setCommand(strcmd, true);
            CommiManager.GlobalManager.SendCommand(target, cmd);
            if (cmd.EventWh.WaitOne(cmd.TimeFailLimit, false))
                return 1 == cmd.ResponseData[5];
            return false;
        }
Example #26
0
        /// <summary>
        /// 克隆通讯协议参数
        /// </summary>
        /// <returns>创建新的协议参数,参数值相同</returns>
        public CommiTarget Clone()
        {
            CommiTarget target = new CommiTarget();
            target.protocolType = this.protocolType;

            if (null != this.srvEndPoint)
                target.srvEndPoint = new IPEndPoint(this.srvEndPoint.Address, this.srvEndPoint.Port);

            target.portName = this.portName;
            target.baudRate = this.baudRate;
            target.parity = this.parity;
            target.dataBits = this.dataBits;
            target.stopBits = this.stopBits;
            target.setProtocol(this.ptl);
            return target;
        }
 /// <summary>
 /// 巡检设备静态构造函数,初始化巡检指令,并发心跳和接收巡检数据
 /// </summary>
 static hdlDeviceMonitor()
 {
     tgService = getService();
     CmdFileTrans.OpenHeaderBeat(CommiManager.GlobalManager, tgService);
     tmBeat = new Timer(new TimerCallback(tmExecute), null, 60000, 60000);
 }
 /// <summary>
 /// 获取服务器目标
 /// </summary>
 /// <returns></returns>
 private static CommiTarget getService()
 {
     //服务器目标
     int port = 2010;
     string sport = DataAccRes.AppSettings("Granity文件服务");
     if (!string.IsNullOrEmpty(sport))
         try { port = Convert.ToInt32(sport); }
         catch { return null; }
     string conn = DataAccRes.DefaultDataConnInfo.Value;
     Regex regIP = new Regex(@"server=([\w.\(\)]*)(;|\\)");
     string ipsrv = "127.0.0.1";
     if (regIP.IsMatch(conn))
     {
         Match mt = regIP.Match(conn);
         if (mt.Groups.Count > 1)
             ipsrv = mt.Groups[1].Value.ToLower();
         if ("(local)" == ipsrv || "127.0.0.1" == ipsrv)
             ipsrv = Dns.GetHostName();
         IPAddress[] ips = Dns.GetHostAddresses(ipsrv);
         foreach (IPAddress ip in ips)
         {
             if (ip.AddressFamily != System.Net.Sockets.AddressFamily.InterNetwork)
                 continue;
             ipsrv = ip.ToString();
         }
     }
     CommiTarget target = new CommiTarget(ipsrv, port, CommiType.TCP);
     return target;
 }
Example #29
0
        /// <summary>
        /// ��ʼ��������
        /// </summary>
        public void initCmdCard()
        {
            IPHostEntry IpEntry = Dns.GetHostEntry(Dns.GetHostName());
            string myip = IpEntry.AddressList[0].ToString();

            NameObjectList pstrans = new NameObjectList();
            ParamManager.MergeParam(pstrans, this.paramwin);
            pstrans["IP��ַ"] = myip;
            //��ѯ����
            QueryDataRes query = new QueryDataRes(this.unitItem.DataSrcFile);
            DataTable tab = dsUnit.Tables["�豸����"];
            tab.Clear();
            query.FillDataSet(tab.TableName, pstrans, this.dsUnit);
            if (null == tab || tab.Rows.Count < 1) return;
            if (tab.Rows.Count < 1)
            {
                MessageBox.Show("�����÷�����");
                return;
            }
            DataRow dr = this.dsUnit.Tables["�豸����"].Rows[0];
            string port = Convert.ToString(dr["����"]);
            int baudrate = Convert.ToInt32(dr["������"]);
            Parity parity = Parity.None;
            int databits = Convert.ToInt32(dr["����λ"]);
            StopBits stopbits = StopBits.One;
            switch (Convert.ToString(dr["ֹͣλ"]))
            {
                case "1.5λ": stopbits = StopBits.OnePointFive; break;
                case "2λ": stopbits = StopBits.Two; break;
                default: stopbits = StopBits.One; break;
            }
            CommiTarget target = new CommiTarget(port, baudrate, parity, databits, stopbits);
            int addrst = Convert.ToInt32(dr["վַ"]);
            bool success = this.cmdCard.SetTarget(target, addrst, this.radic.Checked);
            if (success)
                this.cmdCard.Buzz(true);
        }
Example #30
0
        /// <summary>
        /// ��ȡ�����е��豸Ŀ��λ�ò���
        /// ��¼�����ֶΡ����ʷ�ʽ��(TCP/UDP/SerialPort)�����˿ڡ�(60000/COM1)������ַ��(192.168.1.146)
        /// </summary>
        /// <param name="dr">���ݼ�¼</param>
        /// <returns></returns>
        private CommiTarget getTarget(string[] devps)
        {
            string[] cols ={ "ͨѶ���", "����", "������", "����λ", "ֹͣλ", "IP��ַ", "�˿�", "վַ", "����" };

            if (null == devps || devps.Length < 7)
                return null;
            CommiTarget target = new CommiTarget();
            target.setProtocol(Protocol.PTLEatery);
            CommiType commiType = CommiType.UDP;
            string stype = Convert.ToString(devps[0]);
            switch (stype)
            {
                case "TCP/IP(������)":
                    commiType = CommiType.TCP; break;
                case "UDP/IP(������)":
                    commiType = CommiType.UDP; break;
                default:
                    commiType = CommiType.SerialPort; break;
            }
            try
            {
                if (CommiType.SerialPort == commiType)
                {
                    string portname = Convert.ToString(devps[1]);
                    int baudRate = Convert.ToInt16(devps[2]);
                    int dataBits = Convert.ToInt16(devps[3]);
                    decimal s = Convert.ToDecimal(devps[4]);
                    StopBits sb = StopBits.None;
                    if (1 == s) sb = StopBits.One;
                    else if (2 == s) sb = StopBits.Two;
                    else if (1 < s && s < 2) sb = StopBits.OnePointFive;
                    target.SetProtocolParam(portname, baudRate, Parity.None, dataBits, sb);
                }
                else
                {
                    string addr = Convert.ToString(devps[5]);
                    int port = Convert.ToInt32(devps[6]);
                    target.SetProtocolParam(addr, port, commiType);
                }
            }
            catch (Exception ex)
            {
                return null;
            }
            return target;
        }
Example #31
0
 /// <summary>
 /// ��������Ϣ
 /// </summary>
 public void initCmdCard()
 {
     DataTable tab = initDev();
     if (null == tab || tab.Rows.Count < 1)
     {
         this.cmdCard.SetTarget(null, -1, false);
         return;
     }
     DataRow dr = this.dsUnit.Tables["������"].Rows[0];
     string port = Convert.ToString(dr["����"]);
     int baudrate = Convert.ToInt32(dr["������"]);
     Parity parity = Parity.None;
     int databits = Convert.ToInt32(dr["����λ"]);
     DevIdS = Convert.ToString(dr["վַ"]);
     StopBits stopbits = StopBits.One;
     switch (Convert.ToString(dr["ֹͣλ"]))
     {
         case "1.5λ": stopbits = StopBits.OnePointFive; break;
         case "2λ": stopbits = StopBits.Two; break;
         default: stopbits = StopBits.One; break;
     }
     CommiTarget target = new CommiTarget(port, baudrate, parity, databits, stopbits);
     int addrst = Convert.ToInt32(dr["վַ"]);
     bool success = this.cmdCard.SetTarget(target, addrst, false);
     if (success)
         this.cmdCard.Buzz(true);
 }
Example #32
0
 /// <summary>
 /// 获取数据行的设备目标位置参数
 /// 记录包含字段【访问方式】(TCP/UDP/SerialPort)、【端口】(60000/COM1)、【地址】(192.168.1.146)
 /// </summary>
 /// <param name="dr">数据记录</param>
 /// <returns></returns>
 private CommiTarget getTarget(DataRow dr)
 {
     if (null == dr) return null;
     CommiTarget target = new CommiTarget();
     CommiType commiType = CommiType.UDP;
     int typecommi = 0;
     if (dr["通讯类别"].ToString() == "485")
     {
         typecommi = 1;
     }
     else if (dr["通讯类别"].ToString() == @"TCP\IP")
     {
         typecommi = 2;
     }
     else
     {
         typecommi = 3;
     }
     if (DBNull.Value != dr["通讯类别"])
     {
         //int typecommi = Convert.ToInt16(dr["通讯类别"]);
         if (1 == typecommi) commiType = CommiType.SerialPort;
         if (2 == typecommi) commiType = CommiType.TCP;
     }
     if (CommiType.SerialPort == commiType)
     {
         string portname = "COM" + Convert.ToString(dr["端口"]);
         target.SetProtocolParam(portname, 19200);
     }
     else
     {
         string addr = Convert.ToString(dr["站址"]);
         int port = Convert.ToInt16(dr["端口"]);
         target.SetProtocolParam(addr, port, commiType);
     }
     target.setProtocol(Protocol.PTLPark);
     return target;
 }
Example #33
0
        /// <summary>
        /// ���ͣ�����豸
        /// </summary>
        private void Monitor()
        {
            IPHostEntry IpEntry = Dns.GetHostEntry(Dns.GetHostName());
            string ipstr = ",";
            foreach (IPAddress ip in IpEntry.AddressList)
                ipstr += ip + ",";

            string tpl = "ͣ����", cmd = "�ռ���һ����¼";
            foreach (DataGridViewRow dr in this.gdGrid.Rows)
            {
                string devname = Convert.ToString(dr.Cells["�豸����"].Value);
                string ipaddr = Convert.ToString(dr.Cells["IP��ַ"].Value);
                string devicetype = Convert.ToString(dr.Cells["�豸����"].Value);
                string commitype = Convert.ToString(dr.Cells["ͨѶ���"].Value);
                string port = Convert.ToString(dr.Cells["�˿�"].Value);
                string addrst = Convert.ToString(dr.Cells["ͨѶվַ"].Value);
                if ("ͣ������Ʊ��" != devicetype || string.IsNullOrEmpty(ipaddr))
                    continue;
                if ("Ser" == commitype && !ipstr.Contains(ipaddr))
                    continue;
                if (string.IsNullOrEmpty(addrst))
                    continue;

                //�������ʱ�ɼ�ͨѶ
                CommiTarget target = null;
                if ("Ser" == commitype)
                    target = new CommiTarget(port, 19200);
                if ("UDP" == commitype)
                    target = new CommiTarget(ipaddr, Convert.ToInt16(port), CommiType.UDP);
                if ("TCP" == commitype)
                    target = new CommiTarget(ipaddr, Convert.ToInt16(port), CommiType.TCP);
                string tagdata = "@�豸��ַ=" + addrst;
                CmdProtocol cmdP = new CmdProtocol(devname + "(" + addrst + ")");
                cmdP.setCommand(tpl, cmd, tagdata);
                target.setProtocol(Protocol.PTLPark);

                //����������ͨ���������ֽ������ݲ���ȷ
                cmdP.TimeFailLimit = TimeSpan.MaxValue;
                cmdP.TimeLimit = TimeSpan.MaxValue;
                cmdP.TimeSendInv = new TimeSpan(0, 0, 1);

                //��Ϊ������Ӧ���ٷ���ָ��ķ�ʽ
                this.target = target;
                cmdP.ResponseHandle += new EventHandler<ResponseEventArgs>(cmdP_ResponseHandle);
                CommiManager.GlobalManager.SendCommand(target, cmdP);
            }
        }
Example #34
0
 /// <summary>
 /// ����ͨѶ�豸
 /// </summary>
 /// <param name="devid">�豸ID</param>
 /// <param name="target">ͨѶĿ��</param>
 /// <param name="station">վַ</param>
 public virtual void SetDevice(CommiManager mgr, CommiTarget target, string devid, int station)
 {
     if (null == mgr || string.IsNullOrEmpty(devid) || null == target || station < 1)
         return;
     this.commimgr = mgr;
     this.target = target;
     this.devid = devid;
     this.station = station;
 }