public void Reset() { //蓝屏了 居然 /*** * if(!ConstantMethod.CheckAddressPort(serCurrent)) * { * MessageBox.Show(Constant.TcpIpError); * return; * //ConstantMethod.AppExit(); * } ***/ try { client = new TcpClient(serCurrent.server_Ip, int.Parse(serCurrent.server_Port)); master = ModbusIpMaster.CreateIp(client); Status = Constant.DeviceConnected; ConstantMethod.Delay(100); StartGetData(); } catch (Exception ex) { Status = Constant.DeviceNoConnection; MessageBox.Show(Constant.ErrorSocConnection); // ConstantMethod.AppExit(); } }
public void Reset(ServerInfo ser) { try { if (client != null && client.Connected) { client.Close(); } if (master != null) { master.Dispose(); } StopGetData(); client = new TcpClient(ser.server_Ip, int.Parse(ser.server_Port)); master = ModbusIpMaster.CreateIp(client); Status = 0; } catch (Exception ex) { Status = -1; } }
public List<RegisterAndValues> RequestRegisterValues(ModbusIpMaster master) { try { var regCount = this.RegisterAddresses.Count(); if (regCount <= 0) return new List<RegisterAndValues>(); var minAddress = RegisterAddresses[0].Address; var results = master.ReadInputRegisters(minAddress, (ushort)regCount); var timeRead = DateTime.UtcNow; Debug.Assert(results.Count() == regCount); var res = new List<RegisterAndValues>(regCount); for (int i = 0; i < regCount; i++) { res.Add(new RegisterAndValues() { Address = this.RegisterAddresses[i], Value = results[i], At = timeRead }); } return res; } catch (Exception ex) { var exceptionMessage = "ModBus query error. Message: " + ex.Message; throw new Exception(exceptionMessage, ex); } }
//-------------------------------------------------------------------------------------------------// public PowerMeterVsd(ModbusIpMaster modbusIpMaster, int slaveId) : base(modbusIpMaster, slaveId) { const string methodName = "PowerMeterVsd"; Logfile.WriteCalled(logLevel, STR_ClassName, methodName); /* * Nothing to do here */ Logfile.WriteCompleted(logLevel, STR_ClassName, methodName); }
//создает подключение модбус private void CreatModbIPMaster() { // await Task.Run(() => { try { this._modbusIpMaster = ModbusIpMaster.CreateIp(new TcpClient(ip, port)); } catch (Exception exc) { //Form1._form.richTextBox1.Invoke(new Action(() => Form1._form.richTextBox1.Text = "\r\n IVIT #" + id + " ошибка при подключении \r\n" + exc.Message + "\r\n" + Form1._form.richTextBox1.Text)); if (exc.HResult.ToString() != "-2147467259") { Mylog.writeExc("класс: " + GetType().Name + ". метод: " + System.Reflection.MethodBase.GetCurrentMethod().Name + exc.Message); } status = "no connect!"; return; } //}); }
//-------------------------------------------------------------------------------------------------// /// <summary> /// /// </summary> /// <param name="modbusIpMaster"></param> /// <param name="slaveId"></param> public PowerMeter(ModbusIpMaster modbusIpMaster, int slaveId) { const string methodName = "PowerMeter"; Logfile.WriteCalled(logLevel, STR_ClassName, methodName); this.modbusIpMaster = modbusIpMaster; this.slaveId = slaveId; /* * Create register map */ if (RegisterMap == null) { RegisterMap = new Dictionary<int, RegisterDescription>(); RegisterMap.Add((int)ModbusRegs_RO.PhaseToPhaseVoltageMeanRMS, new RegisterDescription("Ph-Ph Voltage", "Volts", "f01", "Phase to Phase Voltage, Mean RMS Amplitude")); RegisterMap.Add((int)ModbusRegs_RO.ThreePhaseCurrentRMS, new RegisterDescription("Phase Current", "Amps", "f03", "Three Phase Current, RMS Amplitude")); RegisterMap.Add((int)ModbusRegs_RO.TotalPowerFactor, new RegisterDescription("Power Factor", "", "f01", "Total Power Factor (Imp/Exp)")); } Logfile.WriteCompleted(logLevel, STR_ClassName, methodName); }
public DataTransform(ServerInfo ser) { try { client = new TcpClient(ser.server_Ip, int.Parse(ser.server_Port)); master = ModbusIpMaster.CreateIp(client); Status = 0; } catch (Exception ex) { Status = -1; } DataGetTimer = new System.Timers.Timer(Constant.XJConnectTimeOut); //这里0.3 秒别改 加到常量里 工控机性能不行 DataGetTimer.Enabled = false; DataGetTimer.AutoReset = true; DataGetTimer.Elapsed += new System.Timers.ElapsedEventHandler(GetDataEvent); }
//-------------------------------------------------------------------------------------------------// public PowerMeter(ModbusIpMaster master) { const string STRLOG_MethodName = "PowerMeter"; Logfile.WriteCalled(null, STRLOG_MethodName); this.master = master; // // Determine the logging level for this class // try { this.logLevel = (Logfile.LoggingLevels)Utilities.GetIntAppSetting(STRLOG_ClassName); } catch { this.logLevel = Logfile.LoggingLevels.Minimum; } Logfile.Write(Logfile.STRLOG_LogLevel + this.logLevel.ToString()); Logfile.WriteCompleted(null, STRLOG_MethodName); }
//-------------------------------------------------------------------------------------------------// public bool CreateConnection() { const string STRLOG_MethodName = "CreateConnection"; Logfile.WriteCalled(STRLOG_ClassName, STRLOG_MethodName); bool success = false; try { this.tcpClient = new TcpClient(this.machineIP, this.machinePort); this.master = ModbusIpMaster.CreateTcp(this.tcpClient); this.acDrive = new ACDrive(this.master); this.powerMeter = new PowerMeter(this.master); success = true; this.lastError = null; } catch (Exception ex) { this.lastError = ex.Message; Logfile.WriteError(ex.Message); } string logMessage = STRLOG_Success + success.ToString(); Logfile.WriteCompleted(STRLOG_ClassName, STRLOG_MethodName, logMessage); return success; }
//-----------------------------------------------------------------------------------------------------------// /// <summary> /// /// </summary> /// <param name="modbusIpMaster"></param> /// <param name="slaveId"></param> public ACDrive(ModbusIpMaster modbusIpMaster, int slaveId, DeviceRedLion.KeepAliveCallback keepAliveCallback) { const string methodName = "ACDrive"; Logfile.WriteCalled(logLevel, STR_ClassName, methodName); this.modbusIpMaster = modbusIpMaster; this.slaveId = slaveId; this.keepAliveCallback = keepAliveCallback; /* * Create register map */ if (RegisterMap == null) { RegisterMap = new Dictionary<int, RegisterDescription>(); RegisterMap.Add((int)ModbusRegs_RO.DriveSpeed, new RegisterDescription(-3000000, 3000000, 0, -30000, 30000, "Motor Speed", "RPM", "f0", "Drive Speed")); RegisterMap.Add((int)ModbusRegs_RO.DriveTorque, new RegisterDescription(0, 16000, 0, 0, 1600, "Motor Torque", "%", "f0", "Drive Torque")); RegisterMap.Add((int)ModbusRegs_RO.LoadTemperature, new RegisterDescription(-400, 1600, 0, -40, 160, "Load Temp", "deg-C", "f01", "Load Temperature")); RegisterMap.Add((int)ModbusRegs_RW.ControlSpeed, new RegisterDescription(-200000000, 200000000, 0, -3000, 3000, "", "RPM", "", "Control Speed")); RegisterMap.Add((int)ModbusRegs_RW.ControlTorque, new RegisterDescription(-200000000, 200000000, 0, -2000, 2000, "", "%", "", "Control Torque")); RegisterMap.Add((int)ModbusRegs_RW.SpeedRampTime, new RegisterDescription(0, 1800000, 0, 0, 1800, "", "Secs", "", "Speed Ramp Time")); RegisterMap.Add((int)ModbusRegs_RW.MaximumCurrent, new RegisterDescription(0, 3000000, 0, 0, 30000000, "", "Milliamps", "", "Maximum Current")); RegisterMap.Add((int)ModbusRegs_RW.MaximumTorque, new RegisterDescription(0, 3000000, 0, 0, 300000, "", "%", "", "Maximum Torque")); RegisterMap.Add((int)ModbusRegs_RW.MinimumTorque, new RegisterDescription(49536, 65536, -65535, -1600, 0, "", "%", "", "Minimum Torque")); } Logfile.WriteCompleted(logLevel, STR_ClassName, methodName); }
//-------------------------------------------------------------------------------------------------// public bool OpenConnection() { const string STRLOG_MethodName = "OpenConnection"; Logfile.WriteCalled(this.logLevel, STRLOG_ClassName, STRLOG_MethodName); bool success = false; this.lastError = null; try { // // Open a connection to the specified IP address and port number // this.tcpClient = new TcpClient(this.ipaddr, this.ipport); success = true; } catch (Exception ex) { Logfile.WriteError(ex.Message); this.lastError = STRERR_UnableToOpenNetworkConnection + this.ipaddr + ":" + this.ipport.ToString(); } if (success == true) { this.tcpClient.ReceiveTimeout = this.receiveTimeout; this.modbusIpMaster = ModbusIpMaster.CreateTcp(tcpClient); } this.connectionOpen = success; string logMessage = STRLOG_Success + success.ToString(); Logfile.WriteCompleted(this.logLevel, STRLOG_ClassName, STRLOG_MethodName, logMessage); return success; }
/// <summary> /// read the data from the PLC and parse it and save it to the database /// </summary> /// <param name="OmniMaster">Masters object</param> /// <param name="startAddress">start register of information (start offset)</param> /// <param name="numInputs">number of registers containing information</param> public static void ReadSlaveOmniID(ModbusIpMaster OmniMaster, ushort startAddress, ushort numInputs) { ushort[] inputs = OmniMaster.ReadInputRegisters(startAddress, numInputs); //parsing logic and send information somewhere for (int i = 0; i < numInputs; i++) { Console.WriteLine("Register {0}={1}", startAddress + i, inputs[i]); } }
/// <summary> /// use the master to poll the slave, investigating the flag register. on flag condition read information, parse and send to /// database. /// </summary> /// <param name="OmniMaster">Masters object</param> /// <param name="startAddress">start register of polling flag</param> /// <param name="numInputs"># of registers for the polling flag</param> /// <param name="dataStartAddress">start register of information</param> /// <param name="dataNumInputs"># of registers for the data</param> public static void PollSlaveOmniId(ModbusIpMaster OmniMaster, ushort startAddress, ushort numInputs, ushort dataStartAddress, ushort dataNumInputs) { // read polling register and do action when set high while (_shouldpoll) { ushort[] inputs = OmniMaster.ReadInputRegisters(startAddress, numInputs); int flag = inputs[0]; if (flag > 0) { ReadSlaveOmniID(OmniMaster, dataStartAddress, dataNumInputs); } } }
//-----------------------------------------------------------------------------------------------------------// /// <summary> /// /// </summary> /// <param name="modbusIpMaster"></param> /// <param name="slaveId"></param> public DCDrive(ModbusIpMaster modbusIpMaster, int slaveId, DeviceRedLion.KeepAliveCallback keepAliveCallback) { const string methodName = "DCDrive"; Logfile.WriteCalled(logLevel, STR_ClassName, methodName); this.modbusIpMaster = modbusIpMaster; this.slaveId = slaveId; this.keepAliveCallback = keepAliveCallback; /* * Create register map */ if (RegisterMap == null) { RegisterMap = new Dictionary<int, RegisterDescription>(); RegisterMap.Add((int)ModbusRegs_RO.SpeedEncoder, new RegisterDescription(0, 2000, 0, 0, 2000, "Motor Speed", "RPM", "f0", "Actual speed measured with pulse encoder")); RegisterMap.Add((int)ModbusRegs_RO.Torque, new RegisterDescription(0, 10000, 0, 0, 100, "Motor Torque", "%", "f01", "Motor torque")); RegisterMap.Add((int)ModbusRegs_RO.ArmatureVoltage, new RegisterDescription(-400, 400, 0, -400, 400, "Armature Voltage", "Volts", "", "Actual armature voltage")); RegisterMap.Add((int)ModbusRegs_RO.FieldCurrent, new RegisterDescription(0, 200, 0, 0, 2, "Field Current", "Amps", "f02", "Actual field current")); RegisterMap.Add((int)ModbusRegs_RW.ControlSpeed, new RegisterDescription(-20000, 20000, 0, -1500, 1500, "", "RPM", "f01", "Control Speed")); RegisterMap.Add((int)ModbusRegs_RW.ControlTorque, new RegisterDescription(-32700, 32700, 0, -327, 327, "", "%", "f01", "Control Torque")); RegisterMap.Add((int)ModbusRegs_RW.MinSpeedLimit, new RegisterDescription(-10000, 0, 0, -10000, 0, "", "RPM", "", "Minimum Speed Limit")); RegisterMap.Add((int)ModbusRegs_RW.MaxSpeedLimit, new RegisterDescription(0, 10000, 0, 0, 10000, "", "RPM", "", "Maximum Speed Limit")); RegisterMap.Add((int)ModbusRegs_RW.MaxTorqueLimit, new RegisterDescription(0, 32500, 0, 0, 325, "", "%", "", "Maximum Torque Limit")); RegisterMap.Add((int)ModbusRegs_RW.MinTorqueLimit, new RegisterDescription(-32500, 0, 0, -325, 0, "", "%", "", "Minimum Torque Limit")); RegisterMap.Add((int)ModbusRegs_RW.SpeedRampTime, new RegisterDescription(0, 30000, 0, 0, 300, "", "Secs", "", "Speed Ramp Time")); RegisterMap.Add((int)ModbusRegs_RW.FieldLimit, new RegisterDescription(0, 10000, 0, 0, 100, "", "%", "", "Field Limit")); RegisterMap.Add((int)ModbusRegs_RW.FieldTrim, new RegisterDescription(-20, 20, 0, -20, 20, "", "%", "", "Field Trim")); } Logfile.WriteCompleted(logLevel, STR_ClassName, methodName); }