public static ushort[] ReadInputRegisters(ushort startAddress, ushort numofPoints) { ushort[] uArr = new ushort[numofPoints]; try { uArr = master.ReadInputRegisters(slaveID, startAddress, numofPoints); } catch (Exception ex) { _logger.Error("Error: " + ex.Message); } return(uArr); }
//konekcija na ModBus private void TimerEventProcessor(object sender, EventArgs e) { if (serialPort.IsOpen) { ModbusSerialMaster master = ModbusSerialMaster.CreateRtu(serialPort); master.Transport.ReadTimeout = 500; try { ushort[] bratee = master.ReadInputRegisters(1, 28, 12); ushort[] snaga = master.ReadInputRegisters(1, 0, 12); ushort[] cosfi = master.ReadInputRegisters(1, 10, 2); string[] riRString = bratee.Select(x => x.ToString("X")).ToArray(); string[] pString = snaga.Select(x => x.ToString("X")).ToArray(); short output = short.Parse(riRString[0], NumberStyles.HexNumber); radnaTacka._uL1 = Convert.ToDouble(riRString[0]) * Math.Pow(10, (short)bratee[1]); radnaTacka._uL2 = Convert.ToDouble(riRString[2]) * Math.Pow(10, (short)bratee[3]); radnaTacka._uL3 = Convert.ToDouble(riRString[4]) * Math.Pow(10, (short)bratee[5]); radnaTacka._iL1 = Convert.ToDouble(riRString[6]) * Math.Pow(10, (short)bratee[7]); radnaTacka._iL2 = Convert.ToDouble(riRString[8]) * Math.Pow(10, (short)bratee[9]); radnaTacka._iL3 = Convert.ToDouble(riRString[10]) * Math.Pow(10, (short)bratee[11]); radnaTacka._u3p = Convert.ToDouble(pString[0]) * Math.Pow(10, (short)snaga[1]); radnaTacka._i3p = Convert.ToDouble(pString[2]) * Math.Pow(10, (short)snaga[3]); radnaTacka._p3p = Convert.ToDouble(pString[4]) * Math.Pow(10, (short)snaga[5]); radnaTacka._cosphi3p = Convert.ToDouble(pString[10]) * Math.Pow(10, (short)snaga[11]); lbl_uL1.Text = radnaTacka._uL1.ToString(); lbl_uL2.Text = radnaTacka._uL2.ToString(); lbl_uL3.Text = radnaTacka._uL3.ToString(); lbl_iL1.Text = radnaTacka._iL1.ToString(); lbl_iL2.Text = radnaTacka._iL2.ToString(); lbl_iL3.Text = radnaTacka._iL3.ToString(); lbl_u3p.Text = radnaTacka._u3p.ToString(); lbl_i3p.Text = radnaTacka._i3p.ToString(); lbl_p3p.Text = radnaTacka._p3p.ToString(); lbl_cosphi3p.Text = radnaTacka._cosphi3p.ToString(); } catch (Exception ex) { MessageBox.Show(ex.ToString()); } } }
/// <summary> /// 获取Sta2字状态 /// </summary> /// <param name="Address">站号地址</param> /// <param name="Channel">通道地址</param> /// <returns>成功或失败</returns> public static bool Get_C_Sta2(byte Address, ushort Channel, ref short C_Sta2) { if (PMAMaster == null) { return(false); } byte SlaveAddress = Address; ushort StartAddress = (ushort)(1238 + Channel * 512); ushort DataLenght = 1; ushort[] ReturnData; try { lock (LockValue) { ReturnData = PMAMaster.ReadInputRegisters(SlaveAddress, StartAddress, DataLenght); } if (ReturnData != null && ReturnData.Length == DataLenght) { C_Sta2 = Auxiliary.UshortToShort(ReturnData[0]); return(true); } else { return(false); } } catch { return(false); } }
void GetDesTemDrgData(out float des, out float tem, out float drg) { byte slaveID = SlaveAddress; ushort startAddress = (ushort)(AddressConfig.Density - 1); ushort numofPoints = 20; //数据帧中 word 的数量 ushort[] holdingregister = master.ReadInputRegisters(slaveID, startAddress, numofPoints); var dataDriveGain = master.ReadInputRegisters(SlaveAddress, (ushort)(AddressConfig.DriveGain - 1), 2); byte[] bytes = { }; for (int i = 0; i < numofPoints; i++) { byte[] byteTemp; byteTemp = BitConverter.GetBytes(holdingregister[i]); bytes = BitConverterHelper.BytesConnect(bytes, byteTemp); } des = ModbusFloatHelper.UshortToFloat(holdingregister, 0, 3); tem = ModbusFloatHelper.UshortToFloat(holdingregister, 2, 3); drg = ModbusFloatHelper.UshortToFloat(dataDriveGain, 0, 3); }
public ushort[] ReadInputRegisters(byte slaveAddress, ushort startAddress, ushort numberOfPoints) { if (!serialPort.IsOpen) { Open(); } try { return(master.ReadInputRegisters(slaveAddress, startAddress, numberOfPoints)); } catch (Exception ex) { AddMessage("Catch exception in function ReadInputRegisters(). " + ex.Message, DebugLevel.ExceptionLevel); Close(); return(null); } }
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; } }
public void Read_impotent(ModbusSerialMaster master) { ushort[] data0 = new ushort[50]; data0 = master.ReadInputRegisters(this.slaveID, address_v, 36); v_a = ushortToFloat(data0[0], data0[1]); v_b = ushortToFloat(data0[2], data0[3]); v_c = ushortToFloat(data0[4], data0[5]); v = ushortToFloat(data0[6], data0[7]); vl_ab = ushortToFloat(data0[8], data0[9]); vl_bc = ushortToFloat(data0[10], data0[11]); vl_ca = ushortToFloat(data0[12], data0[13]); vl = ushortToFloat(data0[14], data0[15]); i_a = ushortToFloat(data0[16], data0[17]); i_b = ushortToFloat(data0[18], data0[19]); i_c = ushortToFloat(data0[20], data0[21]); i = ushortToFloat(data0[22], data0[23]); i_n = ushortToFloat(data0[24], data0[25]); f = ushortToFloat(data0[26], data0[27]); power_a = ushortToFloat(data0[28], data0[29]); power_b = ushortToFloat(data0[30], data0[31]); power_c = ushortToFloat(data0[32], data0[33]); power_total = ushortToFloat(data0[34], data0[35]); }
/// <summary> /// 定时读取数据 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void timerGetData_Tick(object sender, EventArgs e) { try { //GetDesTemData(250, out var des, out var tem); //地址减一读 GetDesTemDrgData(out var des, out var tem, out var drg); //读取状态位 var datasBitsDefine = master?.ReadInputRegisters(SlaveAddress, (ushort)(AddressConfig.BitsDefine - 1), 1); pictureBoxDriveGain.BackColor = (((datasBitsDefine[0]) >> (5)) & 0x01) == 1 ? Color.Red : Color.Lime; pictureBoxSensor.BackColor = (((datasBitsDefine[0]) >> (10)) & 0x01) == 1 ? Color.Red : Color.Lime; //读取单位 var datasUnits = master?.ReadHoldingRegisters(SlaveAddress, (ushort)(AddressConfig.DensityUnit - 1), 2); desUnitsLabel.Text = ParaUnits.DesTable[datasUnits[0]]; temUnitsLabel.Text = ParaUnits.TemTable[datasUnits[1]]; //读取A37 A38 var datasA37 = master?.ReadInputRegisters(SlaveAddress, (ushort)(AddressConfig.A37 - 1), 1); pictureBoxSensorCheck.BackColor = (((datasA37[0]) >> (3)) & 0x01) == 1 ? Color.Red : Color.Lime; var datasA38 = master?.ReadInputRegisters(SlaveAddress, (ushort)(AddressConfig.A38 - 1), 1); pictureBoxTimeOutLimits.BackColor = (((datasA38[0]) >> (2)) & 0x01) == 1 ? Color.Red : Color.Lime; paraDensity.Value = des; paraTem.Value = tem; paraDriveGain.Value = drg; labelDes.Text = paraDensity.Value.ToString(); LabelTem.Text = paraTem.Value.ToString(); labelDriveGain.Text = paraDriveGain.Value.ToString() + "%"; labelStatus.Text = "通信正常"; timerDraw.Enabled = true; timerSave.Enabled = true; isShowInfoBox = false; } catch (Exception exception) { //timerGetData.Enabled = false; //timerGetData.Stop(); if (exception.Source.Equals("System")) { if (!isShowInfoBox) { isShowInfoBox = true; MessageBox.Show(DateTime.Now.ToString() + " " + "通信超时"); } labelStatus.Text = "通信超时"; } if (exception.Source.Equals("nModbusPC")) { string str = exception.Message; int FunctionCode; string ExceptionCode; str = str.Remove(0, str.IndexOf("\r\n", StringComparison.Ordinal) + 17); FunctionCode = Convert.ToInt16(str.Remove(str.IndexOf("\r\n", StringComparison.Ordinal))); //MessageBox.Show("Function Code: " + FunctionCode.ToString("X")); str = str.Remove(0, str.IndexOf("\r\n", StringComparison.Ordinal) + 17); ExceptionCode = str.Remove(str.IndexOf("-", StringComparison.Ordinal)); switch (ExceptionCode.Trim()) { case "1": labelStatus.Text = "通信异常:非法的通信功能码"; //MessageBox.Show("Exception Code: " + ExceptionCode.Trim() + "----> Illegal function!" ); break; case "2": labelStatus.Text = "通信异常:非法的数据地址"; //MessageBox.Show("Exception Code: " + ExceptionCode.Trim() + "----> Illegal data address!" ); break; case "3": labelStatus.Text = "通信异常:非法的数据值"; //MessageBox.Show("Exception Code: " + ExceptionCode.Trim() + "----> Illegal data value!" ); break; case "4": labelStatus.Text = "从机故障"; //MessageBox.Show("Exception Code: " + ExceptionCode.Trim() + "----> Slave device failure!" ); break; } //this.formMain.Close(); } //labelStatus.Text = exception.Message.ToString(); } }
} //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; } }
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. */ } } }
/// <summary> /// Read contiguous block of input registers. /// </summary> /// <param name="startAddress">Address to begin reading.</param> /// <param name="numOfPoints">Number of input registers to read.</param> /// <returns>Array of register data.</returns> public ushort[] ReadInputRegisters(ushort startAddress = 0, ushort numOfPoints = 2) { return(master.ReadInputRegisters( slaveAddress, startAddress, numOfPoints)); }
private static void StartReading() { while (readingAllow) { if (errorPort) { System.Threading.Thread.Sleep(1000); SerialStart(); continue; } for (int i = 0; i < devices.Count; i++) { try { if (!(devices[i].QuantityAddressHolding == 0)) { ushort[] holding_reg = master.ReadHoldingRegisters(devices[i].ModbusID, devices[i].StartAddressHolding, devices[i].QuantityAddressHolding); Application.Current.Dispatcher.Invoke((Action)(() => { devices[i].ResultHolding = holding_reg; })); } if (!(devices[i].QuantityAddressInput == 0)) { ushort[] input_reg = master.ReadInputRegisters(devices[i].ModbusID, devices[i].StartAddressInput, devices[i].QuantityAddressInput); Application.Current.Dispatcher.Invoke((Action)(() => { devices[i].ResultInput = input_reg; })); } devices[i].ErrorMessage = ""; System.Threading.Thread.Sleep(250); } catch (Exception exception) { if (exception.Message == "Порт закрыт.") { errorPort = true; } if (exception.Message == "Время ожидания операции истекло.") { devices[i].ErrorMessage = "Время ожидания запроса истекло"; } string strExcp = exception.ToString(); int res = strExcp.IndexOf("Modbus"); if (res > -1) { int pos = strExcp.IndexOf("Exception Code:"); switch (strExcp.Substring(108, 1)) { case "1": devices[i].ErrorMessage = "ILLEGAL FUNCTION"; break; case "2": devices[i].ErrorMessage = "ILLEGAL DATA ADRESS"; break; case "3": devices[i].ErrorMessage = "ILLEGAL DATA VALUE"; break; case "4": devices[i].ErrorMessage = "SLAVE DEVICE FAILURE"; break; case "5": devices[i].ErrorMessage = "ACKNOWLEDGE"; break; case "6": devices[i].ErrorMessage = "SLAVE DEVICE BUSY"; break; case "8": devices[i].ErrorMessage = "MEMORY PARITY ERROR"; break; case "0A": devices[i].ErrorMessage = "GATEWAY PATH UNAVAILABLE"; break; case "0B": devices[i].ErrorMessage = "GATEWAY TARGET DEVICE FAILED TO RESPOND"; break; } } } } } }
public void Read_pq_kwh(ModbusSerialMaster master) { try { Thread.Sleep(Form1.WaitingTime); ushort[] data0 = new ushort[28]; data0 = master.ReadInputRegisters(this.slaveID, address_v, 28); v_a = ushortToFloat(data0[0], data0[1]); v_b = ushortToFloat(data0[2], data0[3]); v_c = ushortToFloat(data0[4], data0[5]); v = ushortToFloat(data0[6], data0[7]); vl_ab = ushortToFloat(data0[8], data0[9]); vl_bc = ushortToFloat(data0[10], data0[11]); vl_ca = ushortToFloat(data0[12], data0[13]); vl = ushortToFloat(data0[14], data0[15]); i_a = ushortToFloat(data0[16], data0[17]); i_b = ushortToFloat(data0[18], data0[19]); i_c = ushortToFloat(data0[20], data0[21]); i = ushortToFloat(data0[22], data0[23]); i_n = ushortToFloat(data0[24], data0[25]); f = ushortToFloat(data0[26], data0[27]); Thread.Sleep(Form1.WaitingTime); ushort[] data = new ushort[24]; data = master.ReadInputRegisters(this.slaveID, address_power_a, 24); power_a = ushortToFloat(data[0], data[1]); power_b = ushortToFloat(data[2], data[3]); power_c = ushortToFloat(data[4], data[5]); power_total = ushortToFloat(data[6], data[7]); Q1 = ushortToFloat(data[8], data[9]); Q2 = ushortToFloat(data[10], data[12]); Q3 = ushortToFloat(data[12], data[13]); Q_total = ushortToFloat(data[14], data[15]); s_a = ushortToFloat(data[16], data[17]); s_b = ushortToFloat(data[18], data[19]); s_c = ushortToFloat(data[20], data[21]); s = ushortToFloat(data[22], data[23]); Thread.Sleep(Form1.WaitingTime); ushort[] data2 = new ushort[24]; data2 = master.ReadInputRegisters(slaveID, address_energy, 18); exp_wh_h = ushortToFloat(data2[0], data2[1]); imp_wh_h = ushortToFloat(data2[2], data2[3]); tot_wh_h = ushortToFloat(data2[4], data2[5]); net_wh_h = ushortToFloat(data2[6], data2[7]); imp_varh_h = ushortToFloat(data2[10], data2[11]); exp_varh_h = ushortToFloat(data2[8], data2[9]); tot_varh_h = ushortToFloat(data2[12], data2[13]); net_varh_h = ushortToFloat(data2[14], data2[15]); vah_h = ushortToFloat(data2[16], data2[17]); Thread.Sleep(Form1.WaitingTime); ushort[] data3 = new ushort[8]; data3 = master.ReadInputRegisters(slaveID, address_PF, 8); pf_a = ushortToFloat(data3[0], data3[1]); pf_b = ushortToFloat(data3[2], data3[3]); pf_c = ushortToFloat(data3[4], data3[5]); pf = ushortToFloat(data3[6], data3[7]); CommFailureFlag = false; Fault_info = "Communication is normal"; } catch (Exception e) { CommFailureFlag = true; Fault_info = e.Message; } }
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(); }