Esempio n. 1
0
        /// <summary>
        /// 自动延时控制开闭(仅写寄存器)
        /// (必须值:cmd.SlaveId,cmd.Address)
        /// </summary>
        /// <param name="cmd"></param>
        /// <returns></returns>
        public static string TcpAuto2(Cmd cmd)
        {
            var myListener = new TcpListener(IPAddress.Parse(TcpAddress), int.Parse(TcpPort));

            myListener.Server.ReceiveTimeout = 20000;
            myListener.Start();
            try
            {
                using (var newClient = myListener.AcceptTcpClient())
                {
                    using (var clientStream = newClient.GetStream())
                    {
                        using (var bw = new BinaryWriter(clientStream))
                        {
                            bw.Write(ModBus.ModBusWrite(int.Parse(cmd.slaveid), ModBus.ModBusFunction.WriteCoil,
                                                        int.Parse(cmd.address), true));                              //写开状态
                            Thread.Sleep(string.IsNullOrEmpty(cmd.value) ? int.Parse(Delay) : int.Parse(cmd.value)); //cmd.Value替代默认值Delay
                            bw.Write(ModBus.ModBusWrite(int.Parse(cmd.slaveid), ModBus.ModBusFunction.WriteCoil,
                                                        int.Parse(cmd.address), false));                             //写闭状态
                        }
                    }
                }
                myListener.Stop();
                return("调用成功");
            }
            catch (Exception e)
            {
                myListener.Stop();
                if (DebugSwitchOn)
                {
                    Logger.WriteLog(new LogItem(LogType.Error, e.Message));
                }
                return(e.Message);
            }
        }
Esempio n. 2
0
 public static string TcpControll(Cmd cmd)
 {
     try
     {
         var rtn     = "";
         var ipe     = new IPEndPoint(IPAddress.Parse("172.16.10.40"), 2317);
         var sSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
         sSocket.Bind(ipe);
         sSocket.Listen(0);
         var    serverSocket = sSocket.Accept();
         string rst          = "";
         if (cmd.readwrite == "write")//写
         {
             var data = cmd.value == "1";
             var sd   = ModBus.ModBusWrite(int.Parse(cmd.slaveid), ModBus.ModBusFunction.WriteCoil,
                                           int.Parse(cmd.address), data);//写数据
             rtn = "调用成功-" + WriteRead(sd, serverSocket);
         }
         else//读
         {
             var sd = ModBus.ModBusRead(int.Parse(cmd.slaveid), ModBus.ModBusFunction.ReadCoils,
                                        int.Parse(cmd.address), 1);//读数据
             rst = WriteRead(sd, serverSocket);
             //解析返回数据
             rtn = rst.Length == 14 ? rst.Substring(9, 1) : "";
         }
         serverSocket.Close();
         sSocket.Close();
         return(rtn);
     }
     catch (Exception e)
     {
         return(e.Message);
     }
 }
Esempio n. 3
0
        /// <summary>
        /// 自动延时控制开闭(仅写寄存器)
        /// (必须值:cmd.SlaveId,cmd.Address)
        /// </summary>
        /// <param name="cmd"></param>
        /// <returns></returns>
        public static string TcpAuto(Cmd cmd)
        {
            try
            {
                //ipe = new IPEndPoint(IPAddress.Parse(TcpAddress), int.Parse(TcpPort));
                //using (_sSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
                //{
                //    //_sSocket.ReceiveTimeout = int.Parse(SocketDelay) * 1000;
                //    //sSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, -300);
                //    _sSocket.Bind(ipe);
                //    _sSocket.Listen(0);

                //    TimeoutObject.Reset();
                //    //同步Accept改异步,以便设置超时
                //    IAsyncResult connResult = _sSocket.BeginAccept(new AsyncCallback(AcceptCallback), _sSocket);
                //    TimeoutObject.WaitOne(int.Parse(SocketDelay) * 1000, false);

                //    if (!connResult.IsCompleted)
                //    {
                //        //_serverSocket.Close();
                //        _sSocket.Close();
                //        //处理连接不成功的动作
                //        if (DebugSwitchOn)
                //        {
                //            Logger.WriteLog(new LogItem(LogType.Error, "连接超时"));
                //        }
                //        return "连接超时请重试";
                //    }
                //    else
                //    {
                //        WriteRead(ModBus.ModBusWrite(int.Parse(cmd.slaveid), ModBus.ModBusFunction.WriteCoil,
                //            int.Parse(cmd.address), true), _serverSocket);//写开状态
                //        Thread.Sleep(string.IsNullOrEmpty(cmd.value) ? int.Parse(Delay) : int.Parse(cmd.value));//cmd.Value替代默认值Delay
                //        WriteRead(ModBus.ModBusWrite(int.Parse(cmd.slaveid), ModBus.ModBusFunction.WriteCoil,
                //            int.Parse(cmd.address), false), _serverSocket);//写闭状态
                //        _serverSocket.Close();
                //        _sSocket.Close();
                //        return "调用成功";
                //    }
                //}

                WriteRead(ModBus.ModBusWrite(int.Parse(cmd.slaveid), ModBus.ModBusFunction.WriteCoil,
                                             int.Parse(cmd.address), true), _serverSocket);              //写开状态
                Thread.Sleep(string.IsNullOrEmpty(cmd.value) ? int.Parse(Delay) : int.Parse(cmd.value)); //cmd.Value替代默认值Delay
                WriteRead(ModBus.ModBusWrite(int.Parse(cmd.slaveid), ModBus.ModBusFunction.WriteCoil,
                                             int.Parse(cmd.address), false), _serverSocket);             //写闭状态
                return("调用成功");
            }
            catch (Exception e)
            {
                if (DebugSwitchOn)
                {
                    Logger.WriteLog(new LogItem(LogType.Error, e.Message));
                }
                return(e.Message);
            }
        }
Esempio n. 4
0
        /// <summary>
        /// socket方式
        /// </summary>
        public static void TestSocket()
        {
            var socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            var endpoint    = new IPEndPoint(IPAddress.Parse("172.16.10.40"), 2317);

            socketWatch.Bind(endpoint);
            socketWatch.Listen(20);
            Socket socConnection = socketWatch.Accept();

            socConnection.Send(ModBus.HexStrToHexByte("06 05 00 10 FF 00 8C 48"));
            Thread.Sleep(5000);
            socConnection.Send(ModBus.HexStrToHexByte("06 05 00 10 00 00 CD B8"));
            Console.ReadKey();
        }
Esempio n. 5
0
 /// <summary>
 /// 读寄存器、手动写寄存器
 /// (必须值:cmd.SlaveId,cmd.Address,cmd.ReadWrite,cmd.Value)
 /// </summary>
 /// <param name="cmd">cmd.ReadWrite="write",cmd.Value="1"</param>
 /// <returns></returns>
 public static string TcpControll2(Cmd cmd)
 {
     try
     {
         var rtn        = "";
         var myListener = new TcpListener(IPAddress.Parse(TcpAddress), int.Parse(TcpPort));
         myListener.Start();
         using (var newClient = myListener.AcceptTcpClient())
         {
             using (var clientStream = newClient.GetStream())
             {
                 if (cmd.readwrite == "write")//写
                 {
                     using (var bw = new BinaryWriter(clientStream))
                     {
                         var data = cmd.value == "1";
                         bw.Write(ModBus.ModBusWrite(int.Parse(cmd.slaveid), ModBus.ModBusFunction.WriteCoil, int.Parse(cmd.address), data));
                     }
                 }
                 else//读
                 {
                     using (var bw = new BinaryWriter(clientStream))
                     {
                         using (var br = new BinaryReader(clientStream))
                         {
                             bw.Write(ModBus.ModBusRead(int.Parse(cmd.slaveid), ModBus.ModBusFunction.ReadCoils, int.Parse(cmd.address), 1)); //先写
                             rtn = ModBus.HexByteToHexStr(br.ReadBytes(100));                                                                 //后读
                         }
                     }
                 }
             }
         }
         myListener.Stop();
         return(rtn);
     }
     catch (Exception e)
     {
         if (DebugSwitchOn)
         {
             Logger.WriteLog(new LogItem(LogType.Error, e.Message));
         }
         return(e.Message);
     }
 }
Esempio n. 6
0
        public static void TestModbus()
        {
            var myListener = new TcpListener(IPAddress.Parse("172.16.10.40"), 2317);

            myListener.Start();
            var newClient = myListener.AcceptTcpClient();

            Console.WriteLine("连接成功");
            NetworkStream clientStream = newClient.GetStream();
            var           bw           = new BinaryWriter(clientStream);

            //写入
            bw.Write(ModBus.ModBusWrite(6, ModBus.ModBusFunction.WriteCoil, 16, true));
            Console.WriteLine("开启");
            Thread.Sleep(5000);
            bw.Write(ModBus.ModBusWrite(6, ModBus.ModBusFunction.WriteCoil, 16, false));
            Console.WriteLine("关闭");
            Console.ReadKey();
        }
Esempio n. 7
0
        private static string WriteRead(byte[] hexData, Socket serverSocket)
        {
            byte[] recByte = new byte[1024];
            serverSocket.Send(hexData, hexData.Length, 0);
            int bytes = serverSocket.Receive(recByte, recByte.Length, 0);
            var rcv   = new byte[bytes];

            Array.Copy(recByte, 0, rcv, 0, bytes);
            var rst = ModBus.HexByteToHexStr(rcv);
            var s   = rst.Replace("7777772E7573722E636E", "");

            if (s == "")//排除第一个空
            {
                bytes = serverSocket.Receive(recByte, recByte.Length, 0);
                rcv   = new byte[bytes];
                Array.Copy(recByte, 0, rcv, 0, bytes);
                rst = ModBus.HexByteToHexStr(rcv);
                s   = rst.Replace("7777772E7573722E636E", "");
            }
            return(s);
        }
Esempio n. 8
0
        public static string TcpControll(Cmd cmd)
        {
            try
            {
                //var rtn = "";
                //ipe = new IPEndPoint(IPAddress.Parse(TcpAddress), int.Parse(TcpPort));
                //using (_sSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
                //{
                //    _sSocket.Bind(ipe);
                //    _sSocket.Listen(0);

                //    TimeoutObject.Reset();
                //    //同步Accept改异步,以便设置超时
                //    IAsyncResult connResult = _sSocket.BeginAccept(new AsyncCallback(AcceptCallback), _sSocket);
                //    TimeoutObject.WaitOne(int.Parse(SocketDelay) * 1000, false);

                //    if (!connResult.IsCompleted)
                //    {
                //        //_serverSocket.Close();
                //        _sSocket.Close();
                //        //处理连接不成功的动作
                //        if (DebugSwitchOn)
                //        {
                //            Logger.WriteLog(new LogItem(LogType.Error, "连接超时"));
                //        }
                //        return "连接超时请重试";
                //    }
                //    else
                //    {
                //        if (cmd.readwrite == "write") //写
                //        {
                //            var data = cmd.value == "1";
                //            var sd = ModBus.ModBusWrite(int.Parse(cmd.slaveid), ModBus.ModBusFunction.WriteCoil,
                //                int.Parse(cmd.address), data); //写数据
                //            rtn = "调用成功-" + WriteRead(sd, _serverSocket);
                //        }
                //        else //读
                //        {
                //            var sd = ModBus.ModBusRead(int.Parse(cmd.slaveid), ModBus.ModBusFunction.ReadCoils,
                //                int.Parse(cmd.address), 1); //读数据
                //            var rst = WriteRead(sd, _serverSocket);
                //            //解析返回数据
                //            rtn = rst.Length == 14 ? rst.Substring(9, 1) : "";
                //        }
                //        _serverSocket.Close();
                //        _sSocket.Close();
                //        return rtn;
                //    }
                //}


                if (cmd.readwrite == "write") //写
                {
                    var data = cmd.value == "1";
                    var sd   = ModBus.ModBusWrite(int.Parse(cmd.slaveid), ModBus.ModBusFunction.WriteCoil,
                                                  int.Parse(cmd.address), data); //写数据
                    return("调用成功-" + WriteRead(sd, _serverSocket));
                }
                else //读
                {
                    var sd = ModBus.ModBusRead(int.Parse(cmd.slaveid), ModBus.ModBusFunction.ReadCoils,
                                               int.Parse(cmd.address), 1); //读数据
                    var rst = WriteRead(sd, _serverSocket);
                    //解析返回数据
                    return(rst.Length == 14 ? rst.Substring(9, 1) : "");
                }
            }
            catch (Exception e)
            {
                if (DebugSwitchOn)
                {
                    Logger.WriteLog(new LogItem(LogType.Error, e.Message));
                }
                return(e.Message);
            }
        }