Beispiel #1
0
        /// <summary>读取寄存器 输入寄存器/保持寄存器</summary>
        /// <remarks>
        /// 保持寄存器
        /// 请求:0x03|2字节起始地址|2字节寄存器数量(1~2000)
        /// 响应:0x03|1字节字节数|n*2字节寄存器值
        ///
        /// 输入寄存器
        /// 请求:0x04|2字节起始地址|2字节输入寄存器数量(1~2000)
        /// 响应:0x04|1字节字节数|n*2字节输入寄存器
        /// </remarks>
        /// <param name="entity"></param>
        /// <returns></returns>
        ModbusEntity ReadRegisters(ModbusEntity entity)
        {
            var data = entity.Data;

            // 无效功能指令
            if (data == null || data.Length != 4)
            {
                return(entity.SetError(Errors.MessageLength));
            }

            var addr  = data.ReadUInt16(0);
            var count = data.ReadUInt16(2);

            // 输出数量不正确 count <= 0x07D0=2000
            //if (count == 0 || count > 0x07D0) return entity.SetError(3);
            if (count == 0)
            {
                return(entity.SetError(Errors.Count));
            }

            IWordStore store = null;

#if DEBUG
            var func = "";
#endif
            switch (entity.Function)
            {
            case MBFunction.ReadHoldingRegisters:
                store = DataStore.HoldingRegisters;
#if DEBUG
                func = "ReadHoldingRegisters";
#endif
                break;

            case MBFunction.ReadInputRegisters:
                store = DataStore.InputRegisters;
#if DEBUG
                func = "ReadInputRegisters";
#endif
                break;

            default:
                break;
            }
            if (count > store.Count)
            {
                return(entity.SetError(Errors.Count));
            }
            // 起始地址+数量 不正确
            if (addr + count > 0xFFFF)
            {
                return(entity.SetError(Errors.Address));
            }

#if DEBUG
            WriteLine(func + "(0x" + addr.ToString("X2") + ", 0x" + count.ToString("X2") + ")");
#endif
            if (OnReadRegister != null)
            {
                OnReadRegister(entity, addr, count);
            }

            var buf = new Byte[1 + count * 2];
            buf[0] = (Byte)(count * 2);

            for (var i = 0; i < count; i++)
            {
                buf.WriteUInt16(1 + i * 2, store.Read(addr + i));
            }

            // 读出来
            entity.Data = buf;

            return(entity);
        }
Beispiel #2
0
 /// <summary>读取整个UInt32</summary>
 /// <param name="store"></param>
 /// <param name="i"></param>
 /// <returns></returns>
 public static UInt32 ReadUInt32(this IWordStore store, Int32 i)
 {
     return((UInt32)((store.Read(i) << 16) + store.Read(i + 1)));
 }