Пример #1
0
        private bool ReadParams(HVAC hvac)
        {
            //1.读取保持寄存器的数据,从40000 读到 40046,寄存器数量48
            byte[] b1 = objTcpClient.ReadHoldingRegisters(0, 48, 0);
            //2.处理数据
            if (b1 != null)
            {
                //遍历modbus地址为4区的param
                foreach (Param item in hvac.Params)
                {
                    if (item.ModubsAddr[0] == '4')    //4xxxx
                    {
                        // 40002 => 002 => 4
                        int    start = int.Parse(item.ModubsAddr.Substring(2, 3)) * 2;
                        byte[] data  = new byte[4] {
                            b1[start], b1[start + 1], b1[start + 2], b1[start + 3]
                        };
                        data       = Common.DataConverter.ReverseFormatDCBA(data);
                        item.Value = BitConverter.ToSingle(data, 0);    //startIndex处的字节为高位字节
                    }
                }
            }
            else
            {
                return(false);
            }

            //3.读取输入线圈状态,从00000读到00003,共4个线圈,起始地址为0
            byte[] b2 = objTcpClient.ReadCoilStatus(0, 4, 0);
            if (b2 != null)
            {
                foreach (Param item in hvac.Params)
                {
                    if (item.ModubsAddr[0] == '0')
                    {
                        //获取该变量的相对地址,相对地址为绝对地址减去读取起始地址
                        //此处读取起始地址为0,则相对地址即为modbus绝对地址的尾数
                        int i = int.Parse(item.ModubsAddr.Substring(2, 3));

                        //将第0个字节转换成2进制形式的字符串 11011010
                        string str = Convert.ToString(b2[0], 2).PadLeft(8, '0');

                        char c = str[7 - i];

                        item.Value = (c == '1' ? 1f : 0f);
                    }
                }
                return(true);
            }
            else
            {
                return(false);
            }
        }