ModbusTCP-.Net-代码碎片记录

ModbusTCP文件

using Emrys.FlashLog;
using HslCommunication;
using SatelliteC.Common;
using System;
using System.Configuration;
using System.Linq;
using System.Windows.Forms;

namespace SatelliteC
{
    internal class ModbusTCP
    {
        // 功能按钮操作权限
        public static bool fnAuthority = false;

        // Modbus链路校验权限 true开启 false关闭
        public static bool ModbusVerify = bool.Parse(ConfigurationManager.AppSettings["modbusVerify"].ToString());
        // Modbus链路配置 
        public static string ModbusIp = ConfigurationManager.AppSettings["modbusIp"].ToString();
        public static int ModbusPort = int.Parse(ConfigurationManager.AppSettings["modbusPort"].ToString());
        public static HslCommunication.ModBus.ModbusTcpNet modbusTcpNet_PLC = new HslCommunication.ModBus.ModbusTcpNet(ModbusIp, ModbusPort);

        //modbus长连接初始化
        public void modbusClientInit()
        {
            if (ModbusVerify) {
                // 校验IP端口
                bool result = new CommonUtility().IsPortOpen(ModbusIp, ModbusPort);
                if (result) init(modbusTcpNet_PLC, "PLC");
                else MessageBox.Show($"Modbus地址端口【{ModbusIp}:{ModbusPort}】未启用,请检查", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else init(modbusTcpNet_PLC, "PLC");
        }

        private void init(HslCommunication.ModBus.ModbusTcpNet modbusTcpNet, string device)
        {
            modbusTcpNet?.ConnectClose();
            modbusTcpNet.AddressStartWithZero = true;
            modbusTcpNet.IsStringReverse = false;
            try
            {
                OperateResult connect = modbusTcpNet.ConnectServer();
                // 设长连接
                modbusTcpNet.SetPersistentConnection();
                if (connect.IsSuccess) FlashLogger.Info($"{device}连接成功");
                else FlashLogger.Error($"{device}连接失败");
            }
            catch (Exception ex)
            {
                Console.WriteLine("modbusTcpinit - error:" + ex.ToString());
                FlashLogger.Error("modbusTcpinit - error:" + ex.ToString());
            }
        }

        public short[] modbusRTUReadIntArray(string adrress, ushort length)
        {
            OperateResult<short[]> KGData = modbusTcpNet_PLC.ReadInt16(adrress, length);
            if (KGData.IsSuccess)
            {
                short[] shorts = new short[length];
                shorts = KGData.Content.ToArray();
                return shorts;
            }
            return null;
        }

        public short[] PLC_ReadInt(string intAddress, ushort intLength)
        {
            try
            {
                short[] shorts = modbusTcpNet_PLC.ReadInt16(intAddress, intLength).Content;
                return shorts;
            }
            catch (Exception ex)
            {
                Console.WriteLine("PLC_ReadInt - error:" + ex.ToString());
                FlashLogger.Debug("PLC_ReadInt - error:" + ex.ToString());
                return null;
            }
        }
        public float[] PLC_ReadFloat(string intAddress, ushort intLength)
        {
            try
            {
                float[] floats = modbusTcpNet_PLC.ReadFloat(intAddress, intLength).Content;
                return floats;
            }
            catch (Exception ex)
            {
                Console.WriteLine("PLC_ReadFloat - error:" + ex.ToString());
                FlashLogger.Debug("PLC_ReadFloat - error:" + ex.ToString());
                return null;
            }
        }
    }
}

App.config

CommonUtility工具类,测试IP端口是否已开启,可以减少开发中经常怀疑端口是否有效

// 测试IP地址端口是否可用
        public bool IsPortOpen(string host, int port)
        {
            try
            {
                IPAddress ipAddress = GetIpAddress(host);
                if (ipAddress == null)
                {
                    return false;
                }
                IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);
                Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                socket.Connect(remoteEP);
                return true;
            }
            catch
            {
                return false;
            }
        }
        static IPAddress GetIpAddress(string host)
        {
            try
            {
                IPAddress[] addressList = Dns.GetHostEntry(host).AddressList;
                foreach (IPAddress iPAddress in addressList)
                {
                    if (iPAddress.AddressFamily == AddressFamily.InterNetwork)
                    {
                        return iPAddress;
                    }
                }
                return null;
            }
            catch
            {
                return null;
            }
        }

界面使用

本地测试工具

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值