Exemple #1
0
 private void btn_Poll_INstatus_Click(object sender, EventArgs e)
 {
     bool[] IN_status = new bool[8];
     IN_status           = master.ReadInputs(slave_address, 0, 8);
     lbl_IN1_status.Text = IN_status[0].ToString();
     lbl_IN2_status.Text = IN_status[1].ToString();
     lbl_IN3_status.Text = IN_status[2].ToString();
     lbl_IN4_status.Text = IN_status[3].ToString();
 }
        public bool[] ReadInputs(byte slaveAddress, ushort startAddress, ushort numberOfPoints)
        {
            if (!serialPort.IsOpen)
            {
                Open();
            }

            try
            {
                return(master.ReadInputs(slaveAddress, startAddress, numberOfPoints));
            }
            catch (Exception ex)
            {
                AddMessage("Catch exception in function ReadInputs(). " + ex.Message, DebugLevel.ExceptionLevel);
                Close();
                return(null);
            }
        }
Exemple #3
0
 public int GetData(out byte[] requestBytes, out byte[] responseBytes, out string errCode)
 {
     errCode = "OK";
     try
     {
         if (_config.SelectedMemType == Memtype.Coils)
         {
             CoilsArray = _modbus.ReadCoils(_config.Slaves, _config.StartAddress, _config.Amount);
         }
         if (_config.SelectedMemType == Memtype.Inputs)
         {
             CoilsArray = _modbus.ReadInputs(_config.Slaves, _config.StartAddress, _config.Amount);
         }
         if (_config.SelectedMemType == Memtype.InputRegisters)
         {
             RegisterArray = _modbus.ReadInputRegisters(_config.Slaves, _config.StartAddress, _config.Amount);
         }
         if (_config.SelectedMemType == Memtype.HoldingRegisters)
         {
             RegisterArray = _modbus.ReadHoldingRegisters(_config.Slaves, _config.StartAddress, _config.Amount);
         }
         return(0);
     }
     catch (SlaveException ex)
     {
         errCode = ex.Message;
         return(1);
     }
     catch (Exception ex)
     {
         if (ex is InvalidOperationException)
         {
             throw;
         }
         errCode = ex.Message;
         return(2);
     }
     finally
     {
         requestBytes  = _modbus.Transport.RequestFrame;
         responseBytes = _modbus.Transport.ResponseFrame;
     }
 }
Exemple #4
0
        }                                     //COM开口通讯是否正常的标志
        /// <summary>
        /// 一次读取全部电源信息
        /// </summary>
        /// <param name="slaveAddress">从机地址</param>
        /// <param name="serialPort1">从机连接的串口号</param>
        public void ReadAll(byte slaveAddress, SerialPort serialPort1)
        {
            try
            {
                //ModbusSerialMaster master = ModbusSerialMaster.CreateRtu(serialPort1);
                ////serialPort1.Open(); //开机就打开
                //master.Transport.ReadTimeout = 300;//设置端口超时时间,单位ms
                //bool[] DI = master.ReadInputs(slaveAddress, 10000, 1);//读取高压开关状态
                //HVState = DI[0];
                //ushort[] AI = master.ReadInputRegisters(slaveAddress, 30000, 2);//读取管电压管电流
                //kVRead = (PowerSupplyType.MaxkV - PowerSupplyType.MinkV) * 1.2F * ((float)AI[0] / 4096);
                //kVRead = (float)Math.Round(kVRead,2);
                //mARead = (PowerSupplyType.MaxmA - PowerSupplyType.MinmA) * 1.2F * ((float)AI[1] / 4096);
                //mARead= (float)Math.Round(mARead, 3);

                //AI = master.ReadInputRegisters(slaveAddress, 30004, 1);//读取灯丝电流
                //FilamentRead = 10 * 1.2F * (float)AI[0] / 4096;//12A对应4095
                //FilamentRead= (float)Math.Round(FilamentRead, 2);

                //AI = master.ReadInputRegisters(slaveAddress, 30010, 1);//读取温度
                //TempRead = (PowerSupplyType.MaxTemp - PowerSupplyType.MinTemp) * (float)AI[0] / 4096;
                //TempRead= (float)Math.Round(TempRead, 2);

                //AI = master.ReadInputRegisters(slaveAddress, 30012, 1);//读取电源电压
                ////TempRead = (PowerSupplyType.MaxPowerVoltage - PowerSupplyType.MinPowerVoltage) * (float)AI[0] / 4096;
                //PowerVoltageRead = 43.9F * (float)AI[0] / 4096;
                //PowerVoltageRead= (float)Math.Round(PowerVoltageRead, 2);
                //ComStateFlag = true;

                ModbusSerialMaster master = ModbusSerialMaster.CreateRtu(serialPort1);
                //serialPort1.Open(); //开机就打开
                master.Transport.ReadTimeout = 300;                               //设置端口超时时间,单位ms
                bool[] DI = master.ReadInputs(slaveAddress, 10000, 1);            //读取高压开关状态
                HVState = DI[0];
                ushort[] AI = master.ReadInputRegisters(slaveAddress, 30000, 13); //读取管电压管电流
                kVRead = (PowerSupplyType.MaxkV - PowerSupplyType.MinkV) * 1.2F * ((float)AI[0] / 4096);
                kVRead = (float)Math.Round(kVRead, 2);
                mARead = (PowerSupplyType.MaxmA - PowerSupplyType.MinmA) * 1.2F * ((float)AI[1] / 4096);
                mARead = (float)Math.Round(mARead, 3);

                //AI = master.ReadInputRegisters(slaveAddress, 30004, 1);//读取灯丝电流
                FilamentRead = 10 * 1.2F * (float)AI[4] / 4096;//12A对应4095
                FilamentRead = (float)Math.Round(FilamentRead, 2);

                //AI = master.ReadInputRegisters(slaveAddress, 30010, 1);//读取温度
                TempRead = PowerSupplyType.MinTemp + (PowerSupplyType.MaxTemp - PowerSupplyType.MinTemp) * (float)AI[10] / 4096;
                TempRead = (float)Math.Round(TempRead, 2);

                //AI = master.ReadInputRegisters(slaveAddress, 30012, 1);//读取电源电压
                //TempRead = (PowerSupplyType.MaxPowerVoltage - PowerSupplyType.MinPowerVoltage) * (float)AI[0] / 4096;
                PowerVoltageRead = 43.9F * (float)AI[12] / 4096;
                PowerVoltageRead = (float)Math.Round(PowerVoltageRead, 2);
                ComStateFlag     = true;
            }
            catch (Exception)
            {
                //MessageBox.Show("请检查端口设置","错误提示");
                ComStateFlag = false;
                //throw;
            }
        }
Exemple #5
0
        private void timer1_Tick(object sender, EventArgs e)
        {
            try
            {
                byte   slaveID      = 1;
                ushort startAddress = 0;
                ushort numofPoints  = 4;
                //read DI(1xxxx)
                bool[] status = master.ReadInputs(slaveID, startAddress, numofPoints);
                for (int i = 0; i < numofPoints; i++)
                {
                    if (status[i] == true)
                    {
                        listDI[i].BackColor = Color.DodgerBlue;
                    }
                    else
                    {
                        listDI[i].BackColor = Color.Navy;
                    }
                }
                //read DO(0xxxx)
                bool[] coilstatus = master.ReadCoils(slaveID, startAddress, numofPoints);
                for (int i = 0; i < numofPoints; i++)
                {
                    if (coilstatus[i] == true)
                    {
                        listDO[i].BackColor = Color.Red;
                    }
                    else
                    {
                        listDO[i].BackColor = Color.DarkRed;
                    }
                }
                //read AI(3xxxx)
                ushort[] register = master.ReadInputRegisters(slaveID, startAddress, numofPoints);
                for (int i = 0; i < numofPoints; i++)
                {
                    listAI[i].Text = register[i].ToString();

                    //If you need to show the value with other unit, you have to caculate the gain and offset
                    //eq. 0 to 0kg, 32767 to 1000kg
                    //0 (kg) = gain * 0 + offset
                    //1000 (kg) = gain *32767 + offset
                    //=> gain=1000/32767, offset=0
                    //double value = (double)register[i] * 10.0 / 32767;
                    //listAI[i].Text = value.ToString("0.00");
                }
                //read AO(4xxxx)
                ushort[] holdingregister = master.ReadHoldingRegisters(slaveID, startAddress, numofPoints);
                for (int i = 0; i < numofPoints; i++)
                {
                    listAO[i].Text = holdingregister[i].ToString();

                    //If you need to show the value with other unit, you have to caculate the gain and offset
                    //eq. 0 to 0 mA, 32767 to 20 mA
                    //0 (mA) = gain * 0 + offset
                    //20 (mA) = gain *32767 + offset
                    //=> gain=20/32767, offset=0
                    //double holdvalue = (double)holdingregister[i] * 20.0 / 32767;
                    //listAO[i].Text = holdvalue.ToString("0.00");
                }
            }
            catch (Exception exception)
            {
                //Connection exception
                //No response from server.
                //The server maybe close the com port, or response timeout.
                if (exception.Source.Equals("System"))
                {
                    Console.WriteLine(DateTime.Now.ToString() + " " + exception.Message);
                }
                //The server return error code.
                //You can get the function code and exception code.
                if (exception.Source.Equals("nModbusPC"))
                {
                    string str = exception.Message;
                    int    FunctionCode;
                    string ExceptionCode;

                    str          = str.Remove(0, str.IndexOf("\r\n") + 17);
                    FunctionCode = Convert.ToInt16(str.Remove(str.IndexOf("\r\n")));
                    Console.WriteLine("Function Code: " + FunctionCode.ToString("X"));

                    str           = str.Remove(0, str.IndexOf("\r\n") + 17);
                    ExceptionCode = str.Remove(str.IndexOf("-"));
                    switch (ExceptionCode.Trim())
                    {
                    case "1":
                        Console.WriteLine("Exception Code: " + ExceptionCode.Trim() + "----> Illegal function!");
                        break;

                    case "2":
                        Console.WriteLine("Exception Code: " + ExceptionCode.Trim() + "----> Illegal data address!");
                        break;

                    case "3":
                        Console.WriteLine("Exception Code: " + ExceptionCode.Trim() + "----> Illegal data value!");
                        break;

                    case "4":
                        Console.WriteLine("Exception Code: " + ExceptionCode.Trim() + "----> Slave device failure!");
                        break;
                    }

                    /*
                     * //Modbus exception codes definition
                     * Code   * Name                                      * Meaning
                     *   01       ILLEGAL FUNCTION                            The function code received in the query is not an allowable action for the server.
                     *
                     *   02       ILLEGAL DATA ADDRESS                        The data addrdss received in the query is not an allowable address for the server.
                     *
                     *   03       ILLEGAL DATA VALUE                          A value contained in the query data field is not an allowable value for the server.
                     *
                     *   04       SLAVE DEVICE FAILURE                        An unrecoverable error occurred while the server attempting to perform the requested action.
                     *
                     *   05       ACKNOWLEDGE                                 This response is returned to prevent a timeout error from occurring in the client (or master)
                     *                                                        when the server (or slave) needs a long duration of time to process accepted request.
                     *
                     *   06       SLAVE DEVICE BUSY                           The server (or slave) is engaged in processing a long–duration program command , and the
                     *                                                        client (or master) should retransmit the message later when the server (or slave) is free.
                     *
                     *   08       MEMORY PARITY ERROR                         The server (or slave) attempted to read record file, but detected a parity error in the memory.
                     *
                     *   0A       GATEWAY PATH UNAVAILABLE                    The gateway is misconfigured or overloaded.
                     *
                     *   0B       GATEWAY TARGET DEVICE FAILED TO RESPOND     No response was obtained from the target device. Usually means that the device is not present on the network.
                     */
                }
            }
        }
Exemple #6
0
        static void Main(string[] args)
        {
            try{
                /*
                 *  Connecting via Serial
                 */
                SerialPort serialPort = new SerialPort(); //Create a new SerialPort object.
                serialPort.PortName  = "COM5";            //PC port
                serialPort.BaudRate  = 19200;             //baud rate
                serialPort.DataBits  = 8;
                serialPort.Parity    = Parity.None;
                serialPort.StopBits  = StopBits.One;
                serialPort.RtsEnable = true; //false for RS232, true for RS48
                serialPort.Open();

                ModbusSerialMaster master = ModbusSerialMaster.CreateRtu(serialPort); //or .CreateAscii(serialPort)
                master.Transport.ReadTimeout = 1000;                                  //ms


                {
                    // read multiple int16 values
                    string[] totusTemps =
                    {
                        "Thermal/AmbientTemp",
                        "Thermal/AmbientTemp/1hAvg",
                        "Thermal/AmbientHumidity",
                        "Thermal/AmbientHumidity/1hAvg",
                        "Thermal/TopOilTemp",
                        "Thermal/TopOilTemp/1hAvg",
                        "Thermal/BottomOilTemp",
                        "Thermal/BottomOilTemp/1hAvg",
                        "Thermal/TapChangerTemp",
                        "Thermal/TapChangerTemp/1hAvg"
                    };

                    {
                        //read int16 temperatures
                        ushort   numInputs    = 10;
                        byte     slaveID      = 1;
                        ushort   startAddress = 1000;                                                        //select address from Totus Modbus table
                        ushort[] temps        = master.ReadInputRegisters(slaveID, startAddress, numInputs); //*2 because we are reading 2byte unsigned short that needs converted to 4 byte floats

                        for (int i = 0; i < numInputs; i++)
                        {
                            Console.WriteLine("{0} = {1}°C", totusTemps[i], (float)temps[i] / 10); // divide by 10 as specified in Scaling column
                        }
                    }
                }
                {
                    //read alarms
                    byte   slaveID      = 1;
                    ushort numInputs    = 2;
                    ushort startAddress = 100;
                    bool[] alarms       = master.ReadInputs(slaveID, startAddress, numInputs);

                    string[] totusAlarms =
                    {
                        "ALARM/System/HL/State",
                        "ALARM/System/HHLL/State"
                    };
                    for (int i = 0; i < numInputs; i++)
                    {
                        Console.WriteLine("{0} = {1}", totusAlarms[i], alarms[i]);
                    }
                }
                {
                    //read DGA float32 gases
                    string[] totusDGA =
                    {
                        "DGA/SourceA/CH4",
                        "DGA/SourceA/C2H6",
                        "DGA/SourceA/C2H4",
                        "DGA/SourceA/C2H2",
                        "DGA/SourceA/CO",
                        "DGA/SourceA/CO2",
                        "DGA/SourceA/O2",
                        "DGA/SourceA/N2",
                        "DGA/SourceA/H2",
                        "DGA/SourceA/H2O",
                        "DGA/SourceA/TDCG",
                        "DGA/SourceA/THC"
                    };
                    byte     slaveID      = 1;
                    ushort   numInputs    = 12;
                    ushort   startAddress = 2200;                                                                      //select address from Totus Modbus table
                    ushort[] inputsdga    = master.ReadInputRegisters(slaveID, startAddress, (ushort)(numInputs * 2)); //*2 because we are reading 2byte unsigned short that needs converted to 4 byte floats

                    for (int i = 0; i < numInputs; i++)
                    {
                        Console.WriteLine("Float32 {0} {1} = {2} ppm", startAddress + i * 2, totusDGA[i], Convert2Float(inputsdga[i * 2], inputsdga[i * 2 + 1]));
                    }
                }
                master.Dispose();
            }
            catch (Exception exception)
            {
                //Connection exception
                //No response from server.
                //The server maybe close the connection, or response timeout.
                Console.WriteLine(exception.Message);
            }

            Console.Read();
        }