Esempio n. 1
0
        public static async void ConnnectPlc2()
        {
            Task task = new Task(() =>
            {
                try
                {
                    OperateResult connect2 = ModbusTcpNet2.ConnectServer();
                    if (connect2.IsSuccess)
                    {
                        Global.ConnectStatus2 = true;
                    }
                    else
                    {
                        Global.ConnectStatus2 = false;
                    }
                }
                catch
                {
                    Global.ConnectStatus2 = false;
                }
            });

            task.Start();
            await task;
        }
        public void Connection()
        {
            try
            {
                busTcpClient?.ConnectClose();
                busTcpClient = new ModbusTcpNet(IP, Port, Station);
                busTcpClient.AddressStartWithZero = true;


                busTcpClient.IsStringReverse = false;

                try
                {
                    OperateResult connect = busTcpClient.ConnectServer();
                    if (connect.IsSuccess)
                    {
                        IsConnected = true;
                    }
                    else
                    {
                        IsConnected = false;
                    }
                }
                catch (Exception ex)
                {
                    EventscadaException?.Invoke(this.GetType().Name, ex.Message);
                }
            }
            catch (SocketException ex)
            {
                EventscadaException?.Invoke(this.GetType().Name, ex.Message);
            }
        }
Esempio n. 3
0
        protected override bool Connect()
        {
            try
            {
                _modbusDevice.IpAddress = _ip;
                _modbusDevice.Port      = _port;
                var res = _modbusDevice.ConnectServer();

                if (res.IsSuccess)
                {
                    LOG.Info($"Connect to ModbusTcp device [{SourceName}] success.");
                    return(true);
                }
                else
                {
                    LOG.Info($"Connect to ModbusTcp device [{SourceName}] failed.");
                    return(false);
                }
            }
            catch (Exception ex)
            {
                LOG.Error($"Connect to ModbusTcp device [{SourceName}] error. Exception:{ex.Message}");
                return(false);
            }
        }
        private void button1_Click(object sender, EventArgs e)
        {
            // 连接
            if (!int.TryParse(textBox2.Text, out int port))
            {
                MessageBox.Show("端口输入不正确!");
                return;
            }

            if (!byte.TryParse(textBox15.Text, out byte station))
            {
                MessageBox.Show("站号输入不正确!");
                return;
            }

            busTcpClient        = new ModbusTcpNet(textBox1.Text, port, station);
            busTcpClient.LogNet = logNet;
            busTcpClient.AddressStartWithZero = checkBox1.Checked;

            try
            {
                busTcpClient.ConnectionId = textBox1.Text; // 设置唯一的ID
                NetworkAlienStart(port);
                busTcpClient.ConnectServer(null);          // 切换为异形客户端,并等待服务器的连接。


                MessageBox.Show("等待服务器的连接!");
                button1.Enabled = false;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Esempio n. 5
0
        public ModbusTest( )
        {
            tcpServer = new ModbusTcpServer( );
            tcpServer.ServerStart(502);

            modbusTcp = new ModbusTcpNet("127.0.0.1");
            modbusTcp.ConnectServer( );
        }
Esempio n. 6
0
        public override bool Connect()
        {
            modusRtu?.ConnectClose();
            OperateResult result = modusRtu.ConnectServer();

            connectFlag = result.IsSuccess;
            return(result.IsSuccess);
        }
Esempio n. 7
0
        private void button1_Click(object sender, EventArgs e)
        {
            // 连接
            if (!System.Net.IPAddress.TryParse(textBox1.Text, out System.Net.IPAddress address))
            {
                MessageBox.Show(DemoUtils.IpAddressInputWrong);
                return;
            }


            if (!int.TryParse(textBox2.Text, out int port))
            {
                MessageBox.Show(DemoUtils.PortInputWrong);
                return;
            }


            if (!byte.TryParse(textBox15.Text, out byte station))
            {
                MessageBox.Show("Station input is wrong!");
                return;
            }

            busTcpClient?.ConnectClose( );
            busTcpClient = new ModbusTcpNet(textBox1.Text, port, station);
            busTcpClient.AddressStartWithZero = checkBox1.Checked;

            busTcpClient.SetLoginAccount(textBox14.Text, textBox12.Text);

            ComboBox1_SelectedIndexChanged(null, new EventArgs( ));                // 设置数据服务
            busTcpClient.IsStringReverse = checkBox3.Checked;

            try
            {
                OperateResult connect = busTcpClient.ConnectServer( );
                if (connect.IsSuccess)
                {
                    MessageBox.Show(HslCommunication.StringResources.Language.ConnectedSuccess);
                    button2.Enabled = true;
                    button1.Enabled = false;
                    panel2.Enabled  = true;

                    userControlReadWriteOp1.SetReadWriteNet(busTcpClient, "100", false);
                }
                else
                {
                    MessageBox.Show(HslCommunication.StringResources.Language.ConnectedFailed + connect.Message + Environment.NewLine +
                                    "Error: " + connect.ErrorCode);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Esempio n. 8
0
 private void NetworkAlien_OnClientConnected(NetworkAlienClient network, AlienSession session)
 {
     if (session.DTU == busTcpClient.ConnectionId)
     {
         busTcpClient.ConnectServer(session);
         Invoke(new Action(() =>
         {
             panel2.Enabled  = true;
             button2.Enabled = true;
         }));
     }
 }
Esempio n. 9
0
        public bool Connection()
        {
            if (!System.Net.IPAddress.TryParse(IP, out System.Net.IPAddress address))
            {
                EventscadaException?.Invoke(GetType().Name, DemoUtils.IpAddressInputWrong);
                return(false);
            }

            if (!int.TryParse($"{Port}", out int port))
            {
                EventscadaException?.Invoke(GetType().Name, DemoUtils.PortInputWrong);
                return(false);
            }



            try
            {
                busTcpClient?.ConnectClose();
                busTcpClient = new ModbusTcpNet(IP, Port, Station)
                {
                    AddressStartWithZero = true,


                    IsStringReverse = false
                };

                try
                {
                    OperateResult connect = busTcpClient.ConnectServer();
                    if (connect.IsSuccess)
                    {
                        EventscadaException?.Invoke(GetType().Name, StringResources.Language.ConnectedSuccess);
                        IsConnected = true;
                    }
                    else
                    {
                        EventscadaException?.Invoke(GetType().Name, StringResources.Language.ConnectedFailed);
                    }
                    return(IsConnected);
                }
                catch (Exception ex)
                {
                    EventscadaException?.Invoke(GetType().Name, ex.Message);
                    return(IsConnected);
                }
            }
            catch (Exception ex)
            {
                EventscadaException?.Invoke(GetType().Name, ex.Message);
                return(IsConnected);
            }
        }
Esempio n. 10
0
        /// <summary>
        /// 连接
        /// </summary>
        /// <returns></returns>
        public bool Connect()
        {
            if (string.IsNullOrEmpty(_ip))
            {
                return(false);
            }
            modbusNet.IpAddress = _ip;
            modbusNet.Port      = _port;
            var result = modbusNet.ConnectServer();

            return(result.IsSuccess = _connected);
        }
 private void userButton1_Click(object sender, EventArgs e)
 {
     // 连接PLC
     if (client.ConnectServer( ).IsSuccess)
     {
         userButton1.Enabled = false;
         userButton2.Enabled = true;
     }
     else
     {
         MessageBox.Show("连接失败");
     }
 }
Esempio n. 12
0
        private void connect_btn_Click(object sender, EventArgs e)//modbustcp连接
        {
            // 连接
            if (!System.Net.IPAddress.TryParse(IpAddress.Text, out System.Net.IPAddress address))
            {
                MessageBox.Show(DemoUtils.IpAddressInputWrong);
                return;
            }


            if (!int.TryParse(PortNum.Text, out int port))
            {
                MessageBox.Show(DemoUtils.PortInputWrong);
                return;
            }


            if (!byte.TryParse(stationNum.Text, out byte station))
            {
                MessageBox.Show("Station input is wrong!");
                return;
            }

            DELTARobotClient?.ConnectClose();
            DELTARobotClient = new ModbusTcpNet(IpAddress.Text, port, station);
            DELTARobotClient.AddressStartWithZero = checkBox1.Checked;



            comboBox1_SelectedIndexChanged(null, new EventArgs());  // 设置数据服务
            DELTARobotClient.IsStringReverse = checkBox3.Checked;

            try
            {
                OperateResult connect = DELTARobotClient.ConnectServer();
                if (connect.IsSuccess)
                {
                    MessageBox.Show(HslCommunication.StringResources.Language.ConnectedSuccess);
                    disconnect_btn.Enabled = true;
                    connect_btn.Enabled    = false;
                }
                else
                {
                    MessageBox.Show(HslCommunication.StringResources.Language.ConnectedFailed + connect.Message);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Esempio n. 13
0
        private void button1_Click(object sender, EventArgs e)
        {
            // 连接
            if (!System.Net.IPAddress.TryParse(textBox1.Text, out System.Net.IPAddress address))
            {
                MessageBox.Show("Ip地址输入不正确!");
                return;
            }


            if (!int.TryParse(textBox2.Text, out int port))
            {
                MessageBox.Show("端口输入不正确!");
                return;
            }


            if (!byte.TryParse(textBox15.Text, out byte station))
            {
                MessageBox.Show("站号输入不正确!");
                return;
            }

            busTcpClient?.ConnectClose( );
            busTcpClient = new ModbusTcpNet(textBox1.Text, port, station);
            busTcpClient.AddressStartWithZero = checkBox1.Checked;

            ComboBox1_SelectedIndexChanged(null, new EventArgs( ));    // 设置数据服务
            busTcpClient.IsStringReverse = checkBox3.Checked;

            try
            {
                OperateResult connect = busTcpClient.ConnectServer( );
                if (connect.IsSuccess)
                {
                    MessageBox.Show("连接成功!");
                    button2.Enabled = true;
                    button1.Enabled = false;
                    panel2.Enabled  = true;
                }
                else
                {
                    MessageBox.Show("连接失败!");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Esempio n. 14
0
        public bool Connection()
        {
            busTcpClient?.ConnectClose();
            busTcpClient = new ModbusTcpNet(adds, port, 1);
            busTcpClient.AddressStartWithZero = false;
            OperateResult connect = busTcpClient.ConnectServer();

            if (connect.IsSuccess)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
Esempio n. 15
0
        public ApcmDeviceApi(string serviceName, string ipAddress, int port)
        {
            _serviceName = serviceName;
            _ipAddress   = ipAddress;
            _port        = port;

            _deviceApi = new ModbusTcpNet(_ipAddress, _port);
            if ((_deviceApi != null) && (_deviceApi.ConnectServer().IsSuccess))
            {
                Logger.Main.Info($"[{_serviceName}]初始化设备成功: {_ipAddress}:{_port}");
                ConnectStatus = true;
            }
            else
            {
                Logger.Main.Info($"[{_serviceName}]初始化设备失败: {_ipAddress}:{_port}");
            }
        }
Esempio n. 16
0
        private void button1_Click(object sender, EventArgs e)
        {
            // 连接
            if (!System.Net.IPAddress.TryParse(textBox1.Text, out System.Net.IPAddress address))
            {
                MessageBox.Show("Ip地址输入不正确!");
                return;
            }


            if (!int.TryParse(textBox2.Text, out int port))
            {
                MessageBox.Show("端口输入不正确!");
                return;
            }


            if (!byte.TryParse(textBox15.Text, out byte station))
            {
                MessageBox.Show("站号输入不正确!");
                return;
            }

            busTcpClient?.ConnectClose( );
            busTcpClient = new ModbusTcpNet(textBox1.Text, port, station);

            try
            {
                OperateResult connect = busTcpClient.ConnectServer( );
                if (connect.IsSuccess)
                {
                    MessageBox.Show("连接成功!");
                    button2.Enabled = true;
                    button1.Enabled = false;
                    panel2.Enabled  = true;
                }
                else
                {
                    MessageBox.Show("连接失败!");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Esempio n. 17
0
        /// <summary>
        /// 连接PLC
        /// </summary>
        /// <param name="IPAddress"></param>
        public bool connectPLC(string IPAddress)
        {
            busTcpClient = new ModbusTcpNet(IPAddress);   // 端口号502,站号1
            OperateResult write = busTcpClient.ConnectServer();

            if (write.IsSuccess)
            {
                MessageBox.Show("连接PLC成功!!!");
                //NetLog.WriteTextLog("连接PLC成功!!!");
                return(true);
            }
            else
            {
                MessageBox.Show(write.ToMessageShowString());
                //NetLog.WriteTextLog("连接PLC失败!!!" + write.ToMessageShowString());
                return(false);
            }
        }
Esempio n. 18
0
File: DevicePlc.cs Progetto: Gz1d/Gz
        //MudbusTCP设备初始化
        void DoInitMudbusTcp(LD.Config.PlcTypeItem item)
        {
            // 连接
            byte station;

            if (!byte.TryParse(item.Station, out station))
            {
                MessageBox.Show(string.Format("station {0} input is wrong!", item.Station));
                return;
            }
            System.Net.IPAddress address;
            if (!System.Net.IPAddress.TryParse(item.IP, out address))
            {
                MessageBox.Show(string.Format("IP {0} input wrong!", item.IP));
                return;
            }
            int port;

            if (!int.TryParse(item.Port.ToString(), out port))
            {
                MessageBox.Show(string.Format("port {0} input wrong!", item.Port));
                return;
            }
            ModbusTcpNet busTcpClient = new ModbusTcpNet(item.IP, port, station);

            busTcpClient.AddressStartWithZero = item.AddressStartWithZero;
            if (busTcpClient != null)
            {
                busTcpClient.DataFormat = item.DataFormat;
            }
            busTcpClient.IsStringReverse = item.IsStringReverse;
            item.Tag = busTcpClient;
            OperateResult connect = busTcpClient.ConnectServer();

            if (connect.IsSuccess)
            {
                item.IsConnected = true;
                //Plcs.Add(item.DevName, busTcpClient);
            }
            else
            {
                item.IsConnected = false;
            }
        }
Esempio n. 19
0
        public void Connect()
        {
            if (ConnectStatus)
            {
                return;
            }

            var rs = _deviceApi.ConnectServer();

            if (rs.IsSuccess)
            {
                Logger.Main.Info($"[{_serviceName}]重新连接设备成功: {_ipAddress}:{_port}");
                ConnectStatus = true;
            }
            else
            {
                Logger.Main.Info($"[{_serviceName}]重新连接设备失败: {_ipAddress}:{_port}");
            }
        }
Esempio n. 20
0
 /// <summary>
 /// 连接设备
 /// </summary>
 /// <param name="ip">IP</param>
 /// <param name="port">端口</param>
 /// <param name="station">站号</param>
 /// <returns></returns>
 public bool Connect(string ip, int port = 502, byte station = 1)
 {
     try
     {
         busTcpClient = new ModbusTcpNet(ip, port, station);
         OperateResult connect = busTcpClient.ConnectServer();
         if (connect.IsSuccess)
         {
             return(true);
         }
         else
         {
             return(false);
         }
     }
     catch (Exception)
     {
         return(false);
     }
 }
Esempio n. 21
0
 public IoService()
 {
     modbusTcp = new ModbusTcpNet {
         IpAddress = "192.168.0.240", Port = 502, AddressStartWithZero = false
     };
     modbusTcp.ConnectServer();
     Task.Run(() =>
     {
         while (true)
         {
             var r1      = modbusTcp.ReadCoil("1");
             IsConnected = r1.IsSuccess;
             if (r1.IsSuccess)
             {
                 _inputs[0] = r1.Content;
                 modbusTcp.WriteCoil("17", _outputs[0]);
             }
             Thread.Sleep(10);
         }
     });
 }
Esempio n. 22
0
        /*数据采集线程*/
        public void AcRunnable()
        {
            modbusClient = new ModbusTcpNet(config.modbus.ip, config.modbus.port, config.modbus.slaveId);
            modbusClient.AddressStartWithZero = config.modbus.addressStartWithZero;

            while (Program.gThreadRunning)
            {
                var connect = modbusClient.ConnectServer();
                if (!connect.IsSuccess)
                {
                    Console.WriteLine($"连接失败[{connect.Message}] 500ms后重连");
                }
                else
                {
                    Console.WriteLine("连接成功");
                    break;
                }

                Thread.Sleep(500);
            }
            while (Program.gThreadRunning)
            {
                foreach (Tag tag in config.modbus.tags)
                {
                    try
                    {
                        Data data = tag.read(modbusClient);
                        Program.gData[tag] = data;
                    }
                    catch (Exception e)
                    {
                        Program.gData[tag] = null;
                    }
                }
                Thread.Sleep(2000);
            }

            Console.WriteLine("数据采集任务退出");
        }
Esempio n. 23
0
        private void Btn_connetc_Click(object sender, EventArgs e)
        {
            string serverIpAddress = this.tb_Server_IpAddress.Text.Trim();

            tb_Server_IpAddress.Enabled = false;
            tb_Server_IpAddress.Enabled = false;
            busTcpClient = new ModbusTcpNet(serverIpAddress, 502, 0x01);
            HslCommunication.OperateResult result = busTcpClient.ConnectServer();
            if (!result.IsSuccess)
            {
                MessageBox.Show("连接服务器失败,请重试");
                return;
            }
            btn_connect.Enabled    = false;
            btn_disconnect.Enabled = true;

            // 读线圈部分使能
            tb_coil_address.Enabled = true;
            tb_coil_length.Enabled  = true;
            rb_coil_one.Enabled     = true;
            rb_coil_two.Enabled     = true;
            rb_coil_four.Enabled    = true;
            btn_coil_send.Enabled   = true;

            // 读寄存器部分使能
            tb_register_address.Enabled = true;
            btn_register_send.Enabled   = true;
            rb_register_one.Enabled     = true;
            rb_register_two.Enabled     = true;
            rb__register_four.Enabled   = true;
            tb_register_length.Enabled  = true;

            // 读离散使能
            tb_discrete_address.Enabled = true;
            btn_discrete_send.Enabled   = true;
            rb_discrete_one.Enabled     = true;
            rb_discrete_two.Enabled     = true;
            rb_discrete_four.Enabled    = true;
            tb_discrete_length.Enabled  = true;

            // 写线圈部分使能
            tb_write_coil_address.Enabled   = true;
            tb_write_coil_length.Enabled    = true;
            rb_write_coil_one.Enabled       = true;
            rb_write_coil_two.Enabled       = true;
            rb_write_coil_four.Enabled      = true;
            btn_write_coil_send.Enabled     = true;
            tb_write_coil_data_bit0.Enabled = true;
            //tb_write_coil_data_bit1.Enabled = true;
            //tb_write_coil_data_bit2.Enabled = true;
            //tb_write_coil_data_bit3.Enabled = true;
            //tb_write_coil_data_bit4.Enabled = true;
            //tb_write_coil_data_bit5.Enabled = true;
            //tb_write_coil_data_bit6.Enabled = true;
            //tb_write_coil_data_bit7.Enabled = true;
            //tb_write_coil_data_bit8.Enabled = true;
            //tb_write_coil_data_bit9.Enabled = true;
            //tb_write_coil_data_bit10.Enabled = true;
            //tb_write_coil_data_bit11.Enabled = true;
            //tb_write_coil_data_bit12.Enabled = true;
            //tb_write_coil_data_bit13.Enabled = true;
            //tb_write_coil_data_bit14.Enabled = true;
            //tb_write_coil_data_bit15.Enabled = true;

            // 写寄存器部分使能
            tb_write_register_address.Enabled  = true;
            btn_write_register_send.Enabled    = true;
            tb_write_register_data.Enabled     = true;
            this.cb_write_register_one.Enabled = true;

            // 自动发送部分使能
            this.cb_cron_coil.Enabled     = true;
            this.cb_cron_register.Enabled = true;
            this.cb_cron_discrete.Enabled = true;
            this.tb_cron_time.Enabled     = true;
            this.btn_cron_start.Enabled   = true;
            this.btn_cron_stop.Enabled    = true;
        }
Esempio n. 24
0
 /// <summary>
 ///     设置为异形客户端对象
 /// </summary>
 /// <param name="alienSession">异形对象</param>
 public override void SetAlineSession(AlienSession alienSession)
 {
     modbusTcp.ConnectServer(alienSession);
 }
Esempio n. 25
0
        public void ModbusTcpUnitTest( )
        {
            ModbusTcpNet modbus = new ModbusTcpNet("127.0.0.1", 502, 1);

            if (!modbus.ConnectServer( ).IsSuccess)
            {
                Console.WriteLine("无法连接modbus,将跳过单元测试。等待网络正常时,再进行测试");
                return;
            }

            // 开始单元测试,从coil类型开始测试
            string address = "1200";

            bool[] boolTmp = new bool[] { true, true, false, true, false, true, false };
            Assert.IsTrue(modbus.WriteCoil(address, true).IsSuccess);
            Assert.IsTrue(modbus.ReadCoil(address).Content == true);
            Assert.IsTrue(modbus.WriteCoil(address, boolTmp).IsSuccess);
            bool[] readBool = modbus.ReadCoil(address, (ushort)boolTmp.Length).Content;
            for (int i = 0; i < boolTmp.Length; i++)
            {
                Assert.IsTrue(readBool[i] == boolTmp[i]);
            }

            address = "300";
            // short类型
            Assert.IsTrue(modbus.Write(address, (short)12345).IsSuccess);
            Assert.IsTrue(modbus.ReadInt16(address).Content == 12345);
            short[] shortTmp = new short[] { 123, 423, -124, 5313, 2361 };
            Assert.IsTrue(modbus.Write(address, shortTmp).IsSuccess);
            short[] readShort = modbus.ReadInt16(address, (ushort)shortTmp.Length).Content;
            for (int i = 0; i < readShort.Length; i++)
            {
                Assert.IsTrue(readShort[i] == shortTmp[i]);
            }

            // ushort类型
            Assert.IsTrue(modbus.Write(address, (ushort)51234).IsSuccess);
            Assert.IsTrue(modbus.ReadUInt16(address).Content == 51234);
            ushort[] ushortTmp = new ushort[] { 5, 231, 12354, 5313, 12352 };
            Assert.IsTrue(modbus.Write(address, ushortTmp).IsSuccess);
            ushort[] readUShort = modbus.ReadUInt16(address, (ushort)ushortTmp.Length).Content;
            for (int i = 0; i < ushortTmp.Length; i++)
            {
                Assert.IsTrue(readUShort[i] == ushortTmp[i]);
            }

            // int类型
            Assert.IsTrue(modbus.Write(address, 12342323).IsSuccess);
            Assert.IsTrue(modbus.ReadInt32(address).Content == 12342323);
            int[] intTmp = new int[] { 123812512, 123534, 976124, -1286742 };
            Assert.IsTrue(modbus.Write(address, intTmp).IsSuccess);
            int[] readint = modbus.ReadInt32(address, (ushort)intTmp.Length).Content;
            for (int i = 0; i < intTmp.Length; i++)
            {
                Assert.IsTrue(readint[i] == intTmp[i]);
            }

            // uint类型
            Assert.IsTrue(modbus.Write(address, (uint)416123237).IsSuccess);
            Assert.IsTrue(modbus.ReadUInt32(address).Content == (uint)416123237);
            uint[] uintTmp = new uint[] { 81623123, 91712749, 91273123, 123, 21242, 5324 };
            Assert.IsTrue(modbus.Write(address, uintTmp).IsSuccess);
            uint[] readuint = modbus.ReadUInt32(address, (ushort)uintTmp.Length).Content;
            for (int i = 0; i < uintTmp.Length; i++)
            {
                Assert.IsTrue(readuint[i] == uintTmp[i]);
            }

            // float类型
            Assert.IsTrue(modbus.Write(address, 123.45f).IsSuccess);
            Assert.IsTrue(modbus.ReadFloat(address).Content == 123.45f);
            float[] floatTmp = new float[] { 123, 5343, 1.45f, 563.3f, 586.2f };
            Assert.IsTrue(modbus.Write(address, floatTmp).IsSuccess);
            float[] readFloat = modbus.ReadFloat(address, (ushort)floatTmp.Length).Content;
            for (int i = 0; i < readFloat.Length; i++)
            {
                Assert.IsTrue(floatTmp[i] == readFloat[i]);
            }

            // double类型
            Assert.IsTrue(modbus.Write(address, 1234.5434d).IsSuccess);
            Assert.IsTrue(modbus.ReadDouble(address).Content == 1234.5434d);
            double[] doubleTmp = new double[] { 1.4213d, 1223d, 452.5342d, 231.3443d };
            Assert.IsTrue(modbus.Write(address, doubleTmp).IsSuccess);
            double[] readDouble = modbus.ReadDouble(address, (ushort)doubleTmp.Length).Content;
            for (int i = 0; i < doubleTmp.Length; i++)
            {
                Assert.IsTrue(readDouble[i] == doubleTmp[i]);
            }

            // long类型
            Assert.IsTrue(modbus.Write(address, 123617231235123L).IsSuccess);
            Assert.IsTrue(modbus.ReadInt64(address).Content == 123617231235123L);
            long[] longTmp = new long[] { 12312313123L, 1234L, 412323812368L, 1237182361238123 };
            Assert.IsTrue(modbus.Write(address, longTmp).IsSuccess);
            long[] readLong = modbus.ReadInt64(address, (ushort)longTmp.Length).Content;
            for (int i = 0; i < longTmp.Length; i++)
            {
                Assert.IsTrue(readLong[i] == longTmp[i]);
            }

            // ulong类型
            Assert.IsTrue(modbus.Write(address, 1283823681236123UL).IsSuccess);
            Assert.IsTrue(modbus.ReadUInt64(address).Content == 1283823681236123UL);
            ulong[] ulongTmp = new ulong[] { 21316UL, 1231239127323UL, 1238612361283123UL };
            Assert.IsTrue(modbus.Write(address, ulongTmp).IsSuccess);
            ulong[] readULong = modbus.ReadUInt64(address, (ushort)ulongTmp.Length).Content;
            for (int i = 0; i < readULong.Length; i++)
            {
                Assert.IsTrue(readULong[i] == ulongTmp[i]);
            }

            // string类型
            Assert.IsTrue(modbus.Write(address, "123123").IsSuccess);
            Assert.IsTrue(modbus.ReadString(address, 3).Content == "123123");

            // byte类型
            byte[] byteTmp = new byte[] { 0x4F, 0x12, 0x72, 0xA7, 0x54, 0xB8 };
            Assert.IsTrue(modbus.Write(address, byteTmp).IsSuccess);
            Assert.IsTrue(SoftBasic.IsTwoBytesEquel(modbus.Read(address, 3).Content, byteTmp));

            modbus.ConnectClose( );
        }
Esempio n. 26
0
        private void ReadData()
        {
            while (true)
            {
                if (IsConnected)
                {
                    try
                    {
                        ManulDataBtnFeedBack.Clear();

                        #region 主页
                        OperateResult <short> operateResult = busTcpClient.ReadInt16((1040).ToString());//水压
                        if (operateResult.IsSuccess)
                        {
                            homeData.WashPress = operateResult.Content;
                        }
                        else
                        {
                            IsConnected = false;
                            continue;
                        }

                        homeData.Mode        = busTcpClient.ReadCoil((207 + 49408).ToString()).Content;  //手动自动模式
                        homeData.EStop       = busTcpClient.ReadCoil(510.ToString()).Content;            //急停
                        homeData.CurrentPos1 = busTcpClient.ReadInt32((41088 + 200).ToString()).Content; //电机位置1
                        homeData.CurrentPos2 = busTcpClient.ReadInt32((41088 + 202).ToString()).Content; //电机位置2
                        homeData.WashPress   = busTcpClient.ReadInt16(1040.ToString()).Content;          //冲洗水压
                        homeData.WashStep    = busTcpClient.ReadInt16((35 + 41088).ToString()).Content;  //冲洗序号
                        homeData.alreadyTime = busTcpClient.ReadInt16((41088 + 120).ToString()).Content; //已冲洗时间
                        homeData.WashSetTime = busTcpClient.ReadInt16((41088 + 115).ToString()).Content; //冲洗设定时间

                        homeData.IsPumpRun = busTcpClient.ReadCoil(20740.ToString()).Content;
                        List <bool> datas = busTcpClient.ReadCoil("330", 5).Content.ToList();
                        homeData.IsAlarm = busTcpClient.ReadCoil("608").Content;
                        datas.Add(homeData.IsAlarm);
                        homeData.EquipmentState(datas.ToArray());

                        homeData.IsReady = busTcpClient.ReadCoil("120").Content;//准备就绪;
                        #endregion

                        #region 手动页面
                        ManulDataBtnFeedBack.AddRange(busTcpClient.ReadCoil((24896 + 2).ToString(), 12).Content);    //手动按钮反馈
                                                                                                                     //  ManulDataBtnFeedBack.Add(busTcpClient.ReadCoil((24896 + 1).ToString()).Content);//手动按钮反馈

                        ManulDataBtnFeedBack.Add(busTcpClient.ReadCoil((24896 + 14).ToString()).Content);            //手动按钮反馈
                        ManulDataBtnFeedBack.Add(busTcpClient.ReadCoil((24896 + 0).ToString()).Content);             //手动按钮反馈

                        manualData.MotorWorkPos = busTcpClient.ReadInt16((41088 + 610).ToString()).Content / 100.0f; //电机工作位置
                        manualData.MotorSpeed   = busTcpClient.ReadInt16((41088 + 609).ToString()).Content;          //电机速度

                        manualData.MannualSetWaterPres = busTcpClient.ReadInt16((41088 + 27).ToString()).Content;    //手动水压设定(KPa)
                        manualData.MannualSetFreq      = busTcpClient.ReadInt16((41088 + 28).ToString()).Content;    //手动频率设定(Hz)

                        manualData.WaterSet          = busTcpClient.ReadInt16((41088 + 10).ToString()).Content;
                        manualData.WaterCompensation = busTcpClient.ReadInt16((41088 + 15).ToString()).Content;
                        manualData.PumpPresMax       = busTcpClient.ReadInt16((41088 + 11).ToString()).Content;
                        manualData.PumpPresMin       = busTcpClient.ReadInt16((41088 + 12).ToString()).Content;
                        manualData.LowFreq           = busTcpClient.ReadInt16((41088 + 23).ToString()).Content;
                        manualData.DampingTime       = busTcpClient.ReadInt16((41088 + 25).ToString()).Content;
                        manualData.WashSetTime       = busTcpClient.ReadInt32((41088 + 115).ToString()).Content;
                        #endregion

                        #region 报警信息
                        if (homeData.IsAlarm)
                        // if (true)
                        {
                            alarmdata = busTcpClient.ReadCoil("780", 45).Content.ToList();//错误
                            for (int i = 0; i < alarmdata.Count; i++)
                            {
                                if (alarmdata[i])
                                {
                                    if (!AlarmInfos.ToList().Exists(x => x.TriggerValue == "M" + (780 + i).ToString()))
                                    {
                                        AlarmInfo alarmInfo = new AlarmInfo();
                                        alarmInfo.Description  = alarmJson["M" + (780 + i).ToString()].ToString();
                                        alarmInfo.BeginTime    = DateTime.Now;
                                        alarmInfo.TriggerValue = "M" + (780 + i).ToString();
                                        this.Invoke(new Action(() =>
                                        {
                                            AlarmInfos.Add(alarmInfo);
                                            DGCurrentAlarm.DataSource = null;
                                            DGCurrentAlarm.DataSource = AlarmInfos;
                                            // DGCurrentAlarm.Refresh();
                                        }
                                                               ));
                                    }
                                }
                                else
                                {
                                    if (AlarmInfos.ToList().Exists(x => x.TriggerValue == "M" + (780 + i).ToString()))
                                    {
                                        var rs = AlarmInfos.ToList().Find(x => x.TriggerValue == "M" + (780 + i).ToString());
                                        if (rs != null)
                                        {
                                            rs.EndTime = DateTime.Now;
                                            this.Invoke(new Action(
                                                            () =>
                                            {
                                                AlarmInfos.Remove(rs);
                                                DGCurrentAlarm.DataSource = null;
                                                DGCurrentAlarm.DataSource = AlarmInfos;
                                                HistoryAlarmInfos.Add(rs);
                                                if (HistoryAlarmInfos.Count > 100)
                                                {
                                                    HistoryAlarmInfos.RemoveAt(0);
                                                }

                                                DGHistoryAlarm.DataSource = null;
                                                DGHistoryAlarm.DataSource = new BindingList <AlarmInfo>(HistoryAlarmInfos);
                                                DGHistoryAlarm.Refresh();
                                            }
                                                            ));
                                        }
                                    }
                                }
                            }
                        }
                        else
                        {
                            this.Invoke(new Action(() =>
                            {
                                foreach (var item in AlarmInfos)
                                {
                                    item.EndTime = DateTime.Now;
                                    HistoryAlarmInfos.Add(item);
                                    if (HistoryAlarmInfos.Count > 100)
                                    {
                                        HistoryAlarmInfos.RemoveAt(0);
                                    }

                                    DGHistoryAlarm.DataSource = null;
                                    DGHistoryAlarm.DataSource = new BindingList <AlarmInfo>(HistoryAlarmInfos);
                                    DGHistoryAlarm.Refresh();
                                }
                                AlarmInfos.Clear();
                                DGCurrentAlarm.DataSource = null;
                            }

                                                   ));
                        }
                        #endregion
                    }
                    catch (Exception ex)
                    {
                        IsConnected = false;
                    }
                }
                else
                {
                    IsConnected = busTcpClient.ConnectServer().IsSuccess;
                }
                Thread.Sleep(300);
            }
        }
Esempio n. 27
0
        /// <summary>
        /// 窗体加载初始化
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MainFrm_Load(object sender, EventArgs e)
        {
            #region 初始化PLC

            try
            {
                string jsonText = File.ReadAllText("server.json");
                CgInfo                  = (JObject)JsonConvert.DeserializeObject(jsonText);
                alarmJson               = (JObject)JsonConvert.DeserializeObject(File.ReadAllText("error.json"));
                busTcpClient            = new ModbusTcpNet(CgInfo["IP"].ToString(), int.Parse(CgInfo["Port"].ToString()), byte.Parse(CgInfo["ID"].ToString()));
                busTcpClient.DataFormat = HslCommunication.Core.DataFormat.CDAB;
                Task.Run(() =>
                {
                    OperateResult result = busTcpClient.ConnectServer();
                    IsConnected          = result.IsSuccess;
                });


                // lampPLCConnected.LampColor[0] = result.IsSuccess ? Color.LawnGreen : Color.Gray;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载上次参数失败!原因:{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            #endregion

            #region 初始化线程读取
            readThread = new Thread(() => ReadData());
            readThread.IsBackground = true;
            readThread.Start();

            #endregion

            #region 加载设备参数
            try
            {
                //if (File.Exists("deviceParams.json"))
                //{
                //    TaskParams = JsonConvert.DeserializeObject<FatigueTaskParameter>(File.ReadAllText("deviceParams.json"));

                //    this.ProductType = TaskParams.ProductType;
                //    this.VersionTime = TaskParams.VersionTime;
                //}

                //if (File.Exists("injectorParams.json"))
                //{
                //    List<InjectorParameter> injectors = JsonConvert.DeserializeObject<List<InjectorParameter>>(File.ReadAllText("injectorParams.json"));
                //    for (int i = 0; i < InjectorParameter1.Count; i++)
                //    {
                //        var injfd = injectors.Find(x => x.WorkGroupNum == 1 && x.LineNum == InjectorParameter1[i].LineNum);
                //        if (injfd != null)
                //        {
                //            InjectorParameter1[i] = injfd;
                //        }
                //    }

                //    for (int i = 0; i < InjectorParameter2.Count; i++)
                //    {
                //        var injfd = injectors.Find(x => x.WorkGroupNum == 2 && x.LineNum == InjectorParameter2[i].LineNum);
                //        if (injfd != null)
                //        {
                //            InjectorParameter2[i] = injfd;
                //        }
                //    }

                //    var w1 = injectors.Find(x => x.WorkGroupNum == 1);
                //    if (w1 != null)
                //    {
                //        WorkingParamter1 = w1.GetGroupParameter();
                //    }

                //    var w2 = injectors.Find(x => x.WorkGroupNum == 2);
                //    if (w2 != null)
                //    {
                //        WorkingParamter2 = w2.GetGroupParameter();
                //    }
                //}
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载上次参数失败!原因:{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            #endregion


            timer1.Interval = 500;
            timer1.Enabled  = true;
            userButtons     = new List <UserButton> {
                BtnGasVel1, BtnGasVel2, BtnGasVel3, BtnGasVel4, BtnGasVel5, BtnGasVel6,
                BtnWash1, BtnWash2, BtnWash3, BtnWash4, BtnWash5, BtnWash6
                , BtnOverVel, BtnHighPres
            };
            uCValves = new List <UCValve>
            {
                AirVavel1, AirVavel2, AirVavel3, AirVavel4, AirVavel5, AirVavel6,
                WaterVaVel1, WaterVaVel2, WaterVaVel3, WaterVaVel4, WaterVaVel5, WaterVaVel6,
                ucValve1
            };
            if (Program.objCurrentAdmin != null)
            {
                toolUser.Text = $"当前用户:{Program.objCurrentAdmin.operator_num}";
            }

            for (int i = 0; i < 30; i++)
            {
                washParameters.Add(new WashParameter()
                {
                    EquipmentNum = equipmentName, ProductType = this.ProductName, EquipmentWashNum = i + 1
                });
                washParameters[i].getBools();
            }
            dataGridParam.AutoGenerateColumns = false;
            dataGridParam.DataSource          = new BindingList <WashParameter> (washParameters.Skip(currentPage).Take(10).ToList());
            this.dataGridParam.Refresh();
            DGCurrentAlarm.AutoGenerateColumns = false;
        }