public void Tick(ModbusClient c) { gas_v = ModbusClient.ConvertRegistersToFloat(c.ReadHoldingRegisters(0, 2), ModbusClient.RegisterOrder.HighLow); pump = ModbusClient.ConvertRegistersToFloat(c.ReadHoldingRegisters(2, 2), ModbusClient.RegisterOrder.HighLow); steam_v = ModbusClient.ConvertRegistersToFloat(c.ReadHoldingRegisters(4, 2), ModbusClient.RegisterOrder.HighLow); water_lvl = ModbusClient.ConvertRegistersToFloat(c.ReadHoldingRegisters(6, 2), ModbusClient.RegisterOrder.HighLow); pressure = ModbusClient.ConvertRegistersToFloat(c.ReadHoldingRegisters(8, 2), ModbusClient.RegisterOrder.HighLow); torch = c.ReadCoils(5, 1)[0]; alrm = c.ReadHoldingRegisters(10, 1)[0]; if (alrm == 0) { water_lvl += 0.02f * pump; if (torch) { water_lvl -= 0.01f * gas_v; pressure += 0.01f * gas_v; } pressure -= 0.03f * steam_v; if (water_lvl < 0) { water_lvl = 0; alrm = 3; } if (water_lvl > 1) { water_lvl = 1; alrm = 4; } if (pressure < 0.3f) { pressure = 0.3f; } if (pressure > 0.95f) { alrm = 1; } if (pressure > 1) { alrm = 2; } c.WriteMultipleRegisters(6, ModbusClient.ConvertFloatToRegisters(water_lvl, ModbusClient.RegisterOrder.HighLow)); c.WriteMultipleRegisters(8, ModbusClient.ConvertFloatToRegisters(pressure, ModbusClient.RegisterOrder.HighLow)); c.WriteSingleRegister(10, alrm); } }
private void escreverDoisRegistros(int posicaoDoPrimeiro, int[] registros) { try { //modbusClient.WriteMultipleCoils(4, new bool[] { true, true, true, true, true, true, true, true, true, true }); //Write Coils starting with Address 5 //bool[] readCoils = modbusClient.ReadCoils(9, 10); //Read 10 Coils from Server, starting with address 10 //int[] readHoldingRegisters = modbusClient.ReadHoldingRegisters(0, 10); //Read 10 Holding Registers from Server, starting with Address 1 modbusClient.WriteMultipleRegisters(posicaoDoPrimeiro - 1, registros.ToArray()); } catch (Exception ex) { logger.Error("Erro ao escrever o Heart-Beat: " + ex.ToString()); throw ex; } }
public void WriteInRegisters <T>(int startingAddress, T value) { int[] values = ConvertingValueHandler.ConvertToRegister(value); modbusClient.Connect(); modbusClient.WriteMultipleRegisters(startingAddress, values); modbusClient.Disconnect(); }
private void change_sp_btn_Click(object sender, EventArgs e) { int[] setpoints = new int[2]; setpoints[0] = Convert.ToInt16((Convert.ToDouble(station_min_sp.Text) * 100) + 100); setpoints[1] = Convert.ToInt16((Convert.ToDouble(station_max_sp.Text) * 100) + 100); modbusClient.WriteMultipleRegisters(1, setpoints); stations_data.stationVariables[0].min_sp = setpoints[0]; stations_data.stationVariables[0].max_sp = setpoints[1]; }
// 1. Run the Write - Part on a Threadpool Thread ... private Task WriteRegAsync(float variable, ModbusClient client) { return(Task.Run(() => { client.WriteMultipleRegisters( 2, ModbusClient.ConvertFloatToRegisters(variable, ModbusClient.RegisterOrder.HighLow) ); })); }
private void TnUstawCisnienie_N3_Click(object sender, RoutedEventArgs e) { ModbusClient modbusClient = new ModbusClient("192.168.1.101", 502); //Ip-Address and Port of Modbus-TCP-Server modbusClient.Connect(); float CisnienieZadane_N3 = float.Parse(txtCisnienieZadane_N3.Text); int[] aaa = ModbusClient.ConvertFloatToRegisters(CisnienieZadane_N3); modbusClient.WriteMultipleRegisters(4516, aaa); modbusClient.Disconnect(); }
private void btnTemperatuaZadana(object sender, RoutedEventArgs e) { ModbusClient modbusClient = new ModbusClient("192.168.1.101", 502); //Ip-Address and Port of Modbus-TCP-Server modbusClient.Connect(); float TemperaturaZadana = float.Parse(txtTemperaturaZadana.Text); int[] aaa = ModbusClient.ConvertFloatToRegisters(TemperaturaZadana); modbusClient.WriteMultipleRegisters(4506, aaa); modbusClient.Disconnect(); }
private void BtnCzasPomiaru_N4_Click(object sender, RoutedEventArgs e) { ModbusClient modbusClient = new ModbusClient("192.168.1.101", 502); //Ip-Address and Port of Modbus-TCP-Server modbusClient.Connect(); int CzasPomiaru_N4 = int.Parse(txtCzasPomiaru_N4.Text); int[] aaa = ModbusClient.ConvertIntToRegisters(CzasPomiaru_N4); modbusClient.WriteMultipleRegisters(4532, aaa); modbusClient.Disconnect(); }
private void BtnUstawTolerancjeCisnienia_N4_Click(object sender, RoutedEventArgs e) { ModbusClient modbusClient = new ModbusClient("192.168.1.101", 502); //Ip-Address and Port of Modbus-TCP-Server modbusClient.Connect(); float TolerancjaCisnienia_N4 = float.Parse(txtCisnienieTolerancja_N4.Text); int[] aaa = ModbusClient.ConvertFloatToRegisters(TolerancjaCisnienia_N4); modbusClient.WriteMultipleRegisters(4530, aaa); modbusClient.Disconnect(); }
private void Button_Click_1(object sender, RoutedEventArgs e) { ModbusClient modbusClient = new ModbusClient("192.168.1.101", 502); //Ip-Address and Port of Modbus-TCP-Server modbusClient.Connect(); float TolerancjaTemperatury = float.Parse(txtTolerancjaTemperatury.Text); int[] aaa = ModbusClient.ConvertFloatToRegisters(TolerancjaTemperatury); modbusClient.WriteMultipleRegisters(4508, aaa); modbusClient.Disconnect(); }
public List <int[]> getLogs(int startIndexRead) { modbusClient = ConnectUserControl.getModbusClient(); List <int[]> RecordNumbers = new List <int[]>(); if (modbusClient != null && modbusClient.Connected == true) { try { //long OldbestRecordNumber = getOldbestRecordNumber(); long NewbestRecordNumber = getNewbestRecordNumber(); if (startIndexRead != -1 && NewbestRecordNumber != -1) { modbusClient.WriteMultipleRegisters(1059, ModbusClient.ConvertIntToRegisters(768)); for (long i = startIndexRead; i <= NewbestRecordNumber; i++) { int[] numberCurrentWrite = new int[4]; numberCurrentWrite = ModbusClient.ConvertLongToRegisters(i); modbusClient.WriteMultipleRegisters(1060, numberCurrentWrite); int[] ArrayLogs = new int[64]; ArrayLogs = modbusClient.ReadHoldingRegisters(17344, 64); RecordNumbers.Add(ArrayLogs); } } return(RecordNumbers); } catch (Exception) { Console.WriteLine("Error: Неожиданный обрыв подключения"); return(RecordNumbers);// } } else { return(RecordNumbers); } }
private void button5_Click(object sender, EventArgs e) { //mi yazma butonu ModbusClient tcpclient = new ModbusClient(Convert.ToString(textBox1.Text), 502); tcpclient.Connect(); int cc = Convert.ToInt32(textBox12.Text); int[] mideger = ModbusClient.ConvertDoubleToTwoRegisters(Convert.ToInt32(textBox8.Text)); tcpclient.WriteMultipleRegisters(cc - 1, mideger); //tcpclient.WriteSingleRegister(cc-1, mideger[0]); //tcpclient.WriteSingleRegister(cc-1, mideger[1]); }
private void button6_Click(object sender, EventArgs e) { //mf yazma butonu ModbusClient tcpclient = new ModbusClient(Convert.ToString(textBox1.Text), 502); tcpclient.Connect(); int dd = Convert.ToInt32(textBox13.Text); float mff = float.Parse(textBox9.Text); int[] mfdeger = ModbusClient.ConvertFloatToTwoRegisters(mff); tcpclient.WriteMultipleRegisters(dd - 1, mfdeger); //tcpclient.WriteSingleRegister(dd, mfdeger[0]); //tcpclient.WriteSingleRegister(dd, mfdeger[1]); }
private void WriteVr_Click(object sender, RoutedEventArgs e) { if (textBoxVr0.Text != null && Regex.IsMatch(textBoxVr0.Text, @"^[+-]?\d*[.]?\d*$")) { //写多个寄存器的值 int[] WriteVrVal = { int.Parse(textBoxVr0.Text.Trim()), int.Parse(textBoxVr1.Text.Trim()), int.Parse(textBoxVr2.Text.Trim()) }; modbusClient.WriteMultipleRegisters(0, WriteVrVal); MessageBox.Show("写入成功"); } else { MessageBox.Show("非法值"); textBoxVr0.Text = "0"; textBoxVr1.Text = "0"; textBoxVr2.Text = "0"; } }
private void btnWriteMultipleRegisters_Click(object sender, EventArgs e) { try { if (!modbusClient.Connected) { button3_Click(null, null); } int[] registersToSend = new int[lsbWriteToServer.Items.Count]; for (int i = 0; i < lsbWriteToServer.Items.Count; i++) { registersToSend[i] = int.Parse(lsbWriteToServer.Items[i].ToString()); } modbusClient.WriteMultipleRegisters(int.Parse(txtStartingAddressOutput.Text) - 1, registersToSend); } catch (Exception exc) { MessageBox.Show(exc.Message, "Exception writing values to Server", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
public static void leituraDXM() { int linhas = oee.quantidade; bool falha = false; int tempoM = 0; int turno1 = 6 * 60 + 0; int turno2 = 18 * 60 + 0; //int turno3 = 22 * 60 + 0; zerar = false; while (!falha) { linhas = oee.quantidade; tempoM = (int)DateTime.Now.TimeOfDay.TotalMinutes; if (zerarAsc) { zerar = true; } //verifica se iniciou o dia if (tempoM < 5 || zerarAsc) { oee.zerou_turno[0] = false; oee.zerou_turno[1] = false; oee.zerou_turno[2] = false; banco.set_fabrica(JsonConvert.SerializeObject(oee)); } if (tempoM >= turno1 && !oee.zerou_turno[0]) { oee.zerou_turno[0] = true; zerar = true; banco.set_fabrica(JsonConvert.SerializeObject(oee)); } if (tempoM >= turno2 && !oee.zerou_turno[1]) { oee.zerou_turno[1] = true; zerar = true; banco.set_fabrica(JsonConvert.SerializeObject(oee)); } /* * if (tempoM >= turno3 && !oee.zerou_turno[2]) * { * oee.zerou_turno[2] = true; * zerar = true; * banco.set_fabrica(JsonConvert.SerializeObject(oee)); * * }*/ bool dxm_ok = false; try { if (dxmINIcia) { if (!dxm.Connected) { if (oee.DXM_Tcp) { dxm = new ModbusClient(oee.DXM_Endress, 502); } else { dxm = new ModbusClient(oee.DXM_Endress); } dxm.ConnectionTimeout = oee.timeOut; dxm.Connect(); } //int[] emu =new int[1]; int[] li = new int[1]; // for (int x = 0; x < oee.quantidade; x++) //{ // if (x == 0) { // emu[0] = oee.emulador; li[0] = oee.quantidade; // dxm.WriteMultipleRegisters(88, emu); dxm.WriteMultipleRegisters(89, li); //} //vel[0] = oee.Linhas[x].vel_esp; //dxm.WriteMultipleRegisters(57+(x*13), vel); // } dxmINIcia = false; Thread.Sleep(oee.timeOut); } else { for (int x = 0; x < linhas; x++) { if (!dxm.Connected) { if (oee.DXM_Tcp) { dxm = new ModbusClient(oee.DXM_Endress, 502); } else { dxm = new ModbusClient(oee.DXM_Endress); } dxm.ConnectionTimeout = oee.timeOut; dxm.Connect(); } int[] con = dxm.ReadHoldingRegisters(88, 2); oee.emulador = con[0]; oee.alteraLinhas(con[1]); oee.Linhas[x].leituraStatus(dxm.ReadHoldingRegisters(0 + x * 4, 4)); oee.Linhas[x].leituratimes(dxm.ReadHoldingRegisters(100 + x * 4, 4)); oee.Linhas[x].leituraPercent(dxm.ReadHoldingRegisters(200 + x * 4, 4)); //força zerar: if (zerar) { int[] wri = new int[1]; wri[0] = 1; dxm.WriteMultipleRegisters(300 + (x * 4), wri); dxm.WriteMultipleRegisters(301 + (x * 4), wri); dxm.WriteMultipleRegisters(302 + (x * 4), wri); dxm.WriteMultipleRegisters(303 + (x * 4), wri); } dxm_ok = true; } if (zerar) { zerar = false; if (zerarAsc) { zerarAsc = false; } banco.set_fabrica(JsonConvert.SerializeObject(oee)); } } } catch { if (oee.DXM_Tcp) { dxm = new ModbusClient(oee.DXM_Endress, 502); } else { dxm = new ModbusClient(oee.DXM_Endress); } dxmINIcia = true; Thread.Sleep(oee.timeOut); } if (dxm_ok) { oee.DXM_insertOnLine(); } else { oee.DXM_insertFalha(); } Thread.Sleep(1000); } }
void SetEnableds(bool val) { var gogo = true; if (!val) { if (startAddr.Text.Trim() == "") { startAddr.Focus(); return; } if (endAddr.Text.Trim() == "") { endAddr.Text = startAddr.Text; } if (startRange.Text.Trim() == "") { startRange.Focus(); return; } if (endRange.Text.Trim() == "") { endRange.Text = (Convert.ToInt32(startRange.Text) + 100).ToString(); } if (IsServer.Checked) { _mbSrv = new ModbusServer(); _mbSrv._output += (byte[] bytes, string type) => Log?.Invoke(type + " : " + BitConverter.ToString(TrimeZeros(bytes)).Replace('-', ' ')); if (radioButton1.Checked) { _mbSrv.Port = Convert.ToInt32(port.Text); _mbSrv.Listen(); } else { if (serialPort.Items.Count <= 0) { MessageBox.Show("Comport yok dedik ya.."); return; } _mbSrv.SerialPort = serialPort.SelectedItem.ToString(); _mbSrv.StopBits = System.IO.Ports.StopBits.One; _mbSrv.Parity = System.IO.Ports.Parity.None; _mbSrv.Baudrate = Convert.ToInt32(baudRate.Text); } _mbSrv.UnitIdentifier = Convert.ToByte(uID.Text); } else { _mbClt = new ModbusClient(ipAddr.Text, Convert.ToInt32(port.Text)) { UnitIdentifier = Convert.ToByte(uID.Text) }; _mbClt._output += (byte[] bytes, string type) => Log?.Invoke(type + " : " + BitConverter.ToString(TrimeZeros(bytes)).Replace('-', ' ')); try { _mbClt.Connect(); } catch (Exception ex) { gogo = false; MessageBox.Show(ex.Message); } } if (!gogo) { return; } running = true; Task.Run(async() => { var dly = Convert.ToInt32(delay.Text); var startAddress = Convert.ToInt32(startAddr.Text); var endAddress = Convert.ToInt32(endAddr.Text); var startRn = Convert.ToInt32(startRange.Text); var endRn = Convert.ToInt32(endRange.Text); while (running) { if (randomWriteChk.Checked) { if (IsServer.Checked) { for (int i = startAddress; i < endAddress; i++) { var rndVal = Convert.ToInt32(_rnd.Next(startRn, endRn >= 65536 ? 65535 : endRn)); if (rndVal >= 32768) { rndVal = ((65536 - rndVal) * -1); } var booVal = _rnd.Next(0, 2) == 1; if (radHR.Checked) { _mbSrv.holdingRegisters.localArray[i] = Convert.ToInt16(rndVal); } else if (radIR.Checked) { _mbSrv.inputRegisters.localArray[i] = Convert.ToInt16(rndVal); } else if (radCO.Checked) { _mbSrv.coils.localArray[i] = booVal; } else if (radDis.Checked) { _mbSrv.discreteInputs.localArray[i] = booVal; } } } else { if (radHR.Checked) { List <int> _values = new List <int>(); for (int i = startAddress; i < endAddress; i++) { var rndVal = _rnd.Next(startRn, endRn >= 65536 ? 65535 : endRn); if (rndVal >= 32768) { rndVal = ((65536 - rndVal) * -1); } _values.Add(rndVal); } _mbClt.WriteMultipleRegisters(startAddress, _values.ToArray()); } else if (radCO.Checked) { List <bool> _values = new List <bool>(); for (int i = startAddress; i < endAddress; i++) { _values.Add(_rnd.Next(0, 2) == 1); } _mbClt.WriteMultipleCoils(startAddress, _values.ToArray()); } } } await Task.Delay(dly); } }); } else { running = false; if (IsServer.Checked) { _mbSrv.StopListening(); } else { _mbClt.Disconnect(); } } button2.Enabled = !val; button1.Enabled = val; startAddr.Enabled = val; endAddr.Enabled = val; startRange.Enabled = val; endRange.Enabled = val; delay.Enabled = val; port.Enabled = val; uID.Enabled = val; radioButton1.Enabled = val; radioButton2.Enabled = val; showSignalPanel.Enabled = !val; }
public static List <float[, ]> getDataGrafiksOfDevice(int[] sizelog, ModbusClient modbusClient, int startIndex) { List <float[, ]> ListAllGraphics = new List <float[, ]>(); for (int i = 0; i < sizelog.Length; i++)//AllLog { float[,] WorksAndPointsForGraphs = new float[3, sizelog[i]]; int NumbersRead = Convert.ToInt32(Math.Ceiling(Convert.ToDouble(sizelog[i]) / 32)); int CurrentCountRead = 0; for (int j = 0; j < NumbersRead; j++) //dataMomentForLog { modbusClient.WriteMultipleRegisters(1059, ModbusClient.ConvertIntToRegisters(j)); modbusClient.WriteMultipleRegisters(1060, ModbusClient.ConvertIntToRegisters(i + startIndex)); int[] readRegisters = modbusClient.ReadHoldingRegisters(17344, 64); for (int z = 0; z < readRegisters.Length; z = z + 2) { WorksAndPointsForGraphs[0, CurrentCountRead] = ModbusClient.ConvertRegistersToFloat(new int[2] { readRegisters[z], readRegisters[z + 1] }); CurrentCountRead++; if (CurrentCountRead >= sizelog[i]) { break; } } } CurrentCountRead = 0; for (int j = 42; j < 42 + NumbersRead; j++) //dataRevolutionsForLog { modbusClient.WriteMultipleRegisters(1059, ModbusClient.ConvertIntToRegisters(j)); modbusClient.WriteMultipleRegisters(1060, ModbusClient.ConvertIntToRegisters(i + startIndex)); int[] readRegisters = modbusClient.ReadHoldingRegisters(17344, 64); for (int z = 0; z < readRegisters.Length; z = z + 2) { WorksAndPointsForGraphs[1, CurrentCountRead] = ModbusClient.ConvertRegistersToFloat(new int[2] { readRegisters[z], readRegisters[z + 1] }); CurrentCountRead++; if (CurrentCountRead == sizelog[i]) { break; } } } CurrentCountRead = 0; for (int j = 84; j < 84 + NumbersRead; j++)//dataTimeForLog { modbusClient.WriteMultipleRegisters(1059, ModbusClient.ConvertIntToRegisters(j)); modbusClient.WriteMultipleRegisters(1060, ModbusClient.ConvertIntToRegisters(i + startIndex)); int[] readRegisters = modbusClient.ReadHoldingRegisters(17344, 64); for (int z = 0; z < readRegisters.Length; z = z + 2) { WorksAndPointsForGraphs[2, CurrentCountRead] = ModbusClient.ConvertRegistersToFloat(new int[2] { readRegisters[z], readRegisters[z + 1] }); CurrentCountRead++; if (CurrentCountRead == sizelog[i]) { break; } } } AdapterDataBase.writeDataLogDB(WorksAndPointsForGraphs, i + startIndex); ListAllGraphics.Add(WorksAndPointsForGraphs); Viewer.setProgressBar(i); } return(ListAllGraphics); }
public void WriteMultipleRegisters(int startReg, int[] regs) { _client.WriteMultipleRegisters(startReg, regs); }
private bool Reset(char CoolantType) { try { int CoolantAddrHI = 0, CoolantAddrLO = 0; int WaterAddrHI = 0, WaterAddrLO = 0; int StartAddress; int[] value; if (CoolantType is 'A') { CoolantAddrHI = 103; CoolantAddrLO = 104; WaterAddrHI = 105; WaterAddrLO = 106; StartAddress = CoolantAddrHI; value = new int[] { 0, 0, 0, 0 }; } else if (CoolantType is 'B') { CoolantAddrHI = 107; CoolantAddrLO = 108; WaterAddrHI = 109; WaterAddrLO = 110; StartAddress = CoolantAddrHI; value = new int[] { 0, 0, 0, 0 }; } else if (CoolantType is 'C') { CoolantAddrHI = 111; CoolantAddrLO = 112; WaterAddrHI = 113; WaterAddrLO = 114; StartAddress = CoolantAddrHI; value = new int[] { 0, 0, 0, 0 }; } else { StartAddress = 103; value = new int[] { 0, 0, 0, 0 }; } if (CoolantAddrHI != 0) { // Reset Aichi Coolant HI LO _ModBusClient.WriteMultipleRegisters(StartAddress - 1, value); Debug.WriteLine($"AICHI RESET {CoolantType}"); } } catch (Exception x) { Error.Collect(x.StackTrace.ToString()); } return(true); }
} // End Read Function /// <summary> /// Write data to the Server Device.</summary> public bool Write(DataExtClass[] DataIn) { bool retVar = false; int i, j, jj, SAddress, boolReg, boolBit; uint intFloat; DAConfClass thisArea; var bitArray = new System.Collections.BitArray(16); var BitInt = new int[1]; //If is not initialized and not connected return error if (!(isInitialized && (DataIn != null))) { Status.NewStat(StatType.Bad, "Not Ready for Writing"); return false; } //If the DataIn and Internal data doesnt have the correct amount of data areas return error. if (!((DataIn.Length == MasterDriverConf.NDataAreas) && (IntData.Length == MasterDriverConf.NDataAreas))) { Status.NewStat(StatType.Bad, "Data Containers Mismatch"); return false; } if (!(isConnected && ModTCPObj.Connected)) { Status.NewStat(StatType.Bad, "Connection Error..."); this.Disconect(); return false; } for (i = 0; i < MasterDriverConf.NDataAreas; i++) { thisArea = MasterDataAreaConf[i]; SAddress = int.Parse(thisArea.StartAddress); if (thisArea.Enable && thisArea.Write) { jj = 0; //Index reinitialize for (j = 0; j < thisArea.Amount; j++) { switch (thisArea.dataType) { case DriverConfig.DatType.Bool: if (thisArea.DBnumber == 1) { if ((IntData[i].dBool.Length > j) && (DataIn[i].Data.dBoolean.Length > j)) { IntData[i].dBool[j] = DataIn[i].Data.dBoolean[j]; } } else if (thisArea.DBnumber == 3) { boolReg = Math.DivRem(j, 16, out boolBit); if ((IntData[i].dInt.Length > boolReg) && (DataIn[i].Data.dBoolean.Length > j)) { if (boolBit == 0) { bitArray.SetAll(false); BitInt[0] = 0; } bitArray.Set(boolBit, DataIn[i].Data.dBoolean[j]); bitArray.CopyTo(BitInt, 0); IntData[i].dInt[boolReg] = BitInt[0]; } } break; case DriverConfig.DatType.Byte: IntData[i].dInt[j] = DataIn[i].Data.dByte[j]; break; case DriverConfig.DatType.Word: IntData[i].dInt[j] = DataIn[i].Data.dWord[j]; break; case DriverConfig.DatType.DWord: //Endianess of the double word. if (RegOrder == ModbusClient.RegisterOrder.HighLow) { IntData[i].dInt[jj] = (int)((DataIn[i].Data.dDWord[j] & MaskHWord) >> 16); IntData[i].dInt[(jj + 1)] = (int)(DataIn[i].Data.dDWord[j] & MaskWord); } else { IntData[i].dInt[jj] = (int)(DataIn[i].Data.dDWord[j] & MaskWord); IntData[i].dInt[(jj + 1)] = (int)((DataIn[i].Data.dDWord[j] & MaskHWord) >> 16); } jj = jj + 2; break; case DriverConfig.DatType.Real: //Float point decimal. //Convert the intFloat = (uint)Math.Abs(Math.Round(DataIn[i].Data.dReal[j] * 1000.0)); //Turn ON/OFF the sign bit. if (DataIn[i].Data.dReal[j] < 0) { intFloat = intFloat | MaskNeg; } else { intFloat = intFloat & MaskiNeg; } //Endianess of the double word. if (RegOrder == ModbusClient.RegisterOrder.HighLow) { IntData[i].dInt[jj] = (int)((intFloat & MaskHWord) >> 16); IntData[i].dInt[(jj + 1)] = (int)(intFloat & MaskWord); } else { IntData[i].dInt[jj] = (int)(intFloat & MaskWord); IntData[i].dInt[(jj + 1)] = (int)((intFloat & MaskHWord) >> 16); } jj = jj + 2; break; default: Status.NewStat(StatType.Warning, "Wrong DataArea Type, Check Config."); break; } } // For j try { //Write the data to the device if ((thisArea.DBnumber == 1) && (thisArea.dataType == DriverConfig.DatType.Bool)) { ModTCPObj.WriteMultipleCoils(SAddress, IntData[i].dBool); retVar = true; } else if (thisArea.DBnumber == 3) { ModTCPObj.WriteMultipleRegisters(SAddress, IntData[i].dInt); retVar = true; } else { retVar = false; Status.NewStat(StatType.Warning, "Wrong FC for Write, Check Config."); } //Report Good if (retVar) Status.NewStat(StatType.Good); } catch (Exception e) { Status.NewStat(StatType.Bad, e.Message); return false; } }// Area Enable } //For Data Areas. return retVar; }// END Write Function
private async Task ExecuteWriteMultipleAnalogCommand(ushort startAddress, int[] commandValues, CommandOriginType commandOrigin) { StringBuilder commandValuesSB = new StringBuilder(); commandValuesSB.Append("[ "); foreach (int value in commandValues) { commandValuesSB.Append(value); commandValuesSB.Append(" "); } commandValuesSB.Append("]"); string verboseMessage = $"{baseLogString} entering ExecuteWriteMultipleAnalogCommand method, command's startAddress: {startAddress}, commandValues: {commandValuesSB}, commandOrigin: {commandOrigin}."; Logger.LogVerbose(verboseMessage); //LOGIC var modelReadAccessClient = ScadaModelReadAccessClient.CreateClient(); var modelUpdateAccessClient = ScadaModelUpdateAccessClient.CreateClient(); int quantity = commandValues.Length; var addressToGidMap = await modelReadAccessClient.GetAddressToGidMap(); //this.commandDescriptions = new Dictionary<long, CommandDescription>(); this.commandDescriptions.Clear(); //LOGIC for (ushort index = 0; index < quantity; index++) { ushort address = (ushort)(startAddress + index); var pointType = (short)PointType.ANALOG_OUTPUT; if (!addressToGidMap.ContainsKey(pointType)) { Logger.LogWarning($"{baseLogString} ExecuteWriteMultipleAnalogCommand => Point type: {pointType} is not in the current addressToGidMap."); continue; } if (addressToGidMap[pointType].ContainsKey(address)) { long gid = addressToGidMap[pointType][address]; CommandDescription commandDescription = new CommandDescription() { Gid = gid, Address = address, Value = commandValues[index], CommandOrigin = commandOrigin, }; //LOGIC this.commandDescriptions.Add(gid, commandDescription); string message = $"{baseLogString} ExecuteWriteMultipleAnalogCommand => CommandDescription added to the collection of commandDescriptions. Gid: {commandDescription.Gid:X16}, Address: {commandDescription.Address}, Value: {commandDescription.Value}, CommandOrigin: {commandDescription.CommandOrigin}"; Logger.LogInformation(message); } } string debugMessage = $"{baseLogString} ExecuteWriteMultipleAnalogCommand => About to send collection of CommandDescriptions to CommandDescriptionCache. collection count: {commandDescriptions.Count}"; Logger.LogDebug(debugMessage); //LOGIC await modelUpdateAccessClient.AddOrUpdateMultipleCommandDescriptions(this.commandDescriptions); debugMessage = $"{baseLogString} ExecuteWriteMultipleAnalogCommand => about to call ModbusClient.WriteMultipleRegisters({startAddress - 1}, {commandValuesSB}) method. StartAddress: {startAddress}, Quantity: {quantity}"; Logger.LogDebug(debugMessage); //KEY LOGIC modbusClient.WriteMultipleRegisters(startAddress - 1, commandValues); string infoMessage = $"{baseLogString} ExecuteWriteMultipleAnalogCommand => ModbusClient.WriteMultipleRegisters() method SUCCESSFULLY executed. StartAddress: {startAddress}, Quantity: {quantity}"; Logger.LogInformation(infoMessage); }
/// <summary> /// MoveAbsAxis /// </summary> /// <param name="axis"></param> public override void MoveAbsAxis(RealAxis axis, MLengthSpeed speed, bool waitForCompletion) { try { int iPos = (int)(axis.TargetPosition / 0.01); int iInpos = 1; int iSpeed = (int)(speed / 0.01); int iAccel = (int)(axis.AccelDecel / 0.01); string sPos = iPos.ToString("X8"); string sInpos = iInpos.ToString("X8"); string sSPeed = iSpeed.ToString("X8"); string s = sPos.Substring(4, 4); int iPos1 = int.Parse(sPos.Substring(0, 4), System.Globalization.NumberStyles.AllowHexSpecifier); int iPos2 = int.Parse(sPos.Substring(4, 4), System.Globalization.NumberStyles.AllowHexSpecifier); int iInpos1 = int.Parse(sInpos.Substring(0, 4), System.Globalization.NumberStyles.AllowHexSpecifier); int iInpos2 = int.Parse(sInpos.Substring(4, 4), System.Globalization.NumberStyles.AllowHexSpecifier); int iSpeed1 = int.Parse(sSPeed.Substring(0, 4), System.Globalization.NumberStyles.AllowHexSpecifier); int iSpeed2 = int.Parse(sSPeed.Substring(4, 4), System.Globalization.NumberStyles.AllowHexSpecifier); int[] regValue = new int[7]; regValue[0] = iPos1; regValue[1] = iPos2; regValue[2] = iInpos1; regValue[3] = iInpos2; regValue[4] = iSpeed1; regValue[5] = iSpeed2; regValue[6] = iAccel; lock (this) { _waitDataRecived.Reset(); try { _modbusClient.WriteMultipleRegisters(IAIConstAddr.PCMD, regValue); } catch { } finally { } WaitDataReceived(ReadTimeOut); } WaitForMoveDone(10000); lock (this) { System.Threading.Thread.Sleep(100); OnUpdateCurrentPositions(); } } catch (Exception ex) { //U.LogAlarmPopup(ex, "Move Absolute Command fail {0}", this.Nickname); throw new MCoreExceptionPopup(ex, "Move Absolute Command fail {0}", this.Nickname); } }
static async Task RunClientAsync() { //InternalLoggerFactory.DefaultFactory.AddProvider(new ConsoleLoggerProvider((s, level) => true, false)); ModbusClient client = new ModbusClient(0x01, "127.0.0.1"); try { await client.Connect(); while (true) { Console.WriteLine(@" <-------------------------------------------------------> 1: Read Coils; 2: Read Discrete Inputs; 3: Read Holding Registers; 4: Read Input Registers; 5: Write Single Coil; 6: Write Single Register; 15: Write Multiple Coils; 16: Write Multiple Registers; <------------------------------------------------------->"); var line = Console.ReadLine(); if (string.IsNullOrEmpty(line)) { break; } Console.WriteLine("<------------------------------------------------------->"); var command = Convert.ToInt32(line); ModbusFunction response = null; ushort startingAddress = 0x0000; ushort quantity = 0x000A; var state = true; ushort value = 0x0001; switch (command) { case 1: response = client.ReadCoils(startingAddress, quantity); var coils = (response as ReadCoilsResponse).Coils; for (int i = 0; i < quantity; i++) { Console.WriteLine(coils[i]); } break; case 2: response = client.ReadDiscreteInputs(startingAddress, quantity); var inputs = (response as ReadDiscreteInputsResponse).Inputs; for (int i = 0; i < quantity; i++) { Console.WriteLine(inputs[i]); } break; case 3: response = client.ReadHoldingRegisters(startingAddress, quantity); foreach (var register in (response as ReadHoldingRegistersResponse).Registers) { Console.WriteLine(register); } break; case 4: response = client.ReadInputRegisters(startingAddress, quantity); foreach (var register in (response as ReadInputRegistersResponse).Registers) { Console.WriteLine(register); } break; case 5: response = client.WriteSingleCoil(startingAddress, state); Console.WriteLine((response as WriteSingleCoilResponse).State == state ? "Successed" : "Failed"); break; case 6: response = client.WriteSingleRegister(startingAddress, value); Console.WriteLine((response as WriteSingleRegisterResponse).Value == value ? "Successed" : "Failed"); break; case 15: var states = new bool[] { true, true, true, true, true, true, true, true, true, true }; response = client.WriteMultipleCoils(startingAddress, states); Console.WriteLine((response as WriteMultipleCoilsResponse).Quantity == states.Length); break; case 16: var registers = new ushort[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }; response = client.WriteMultipleRegisters(startingAddress, registers); Console.WriteLine((response as WriteMultipleRegistersResponse).Quantity == registers.Length); break; } } await client.Close(); Console.ReadLine(); } catch (Exception exception) { Console.WriteLine(exception.Message); } }
private void buttonWExecute_Click(object sender, EventArgs e) { start = Int32.Parse(addBox3.Text); if (functionBox2.SelectedItem == "05 Write Single Coil") { modbusClient.WriteSingleCoil(start, bool.Parse(listBox2.Items[0].ToString())); /*if (listBox2.Text == "TRUE") * { * modbusClient.WriteSingleCoil(start, true); * } * if (listBox2.Text == "FALSE") * { * modbusClient.WriteSingleCoil(start, false); * } */ //modbusClient.WriteSingleCoil(start, bool.Parse(lista[0])); } else if (functionBox2.SelectedItem == "06 Write Single Register") { modbusClient.WriteSingleRegister(start, int.Parse(listBox2.Items[0].ToString())); } else if (functionBox2.SelectedItem == "15 Write Multiple Coils") { bool[] tab; int l = 0; int j = 0; foreach (string b in listBox2.Items) { l++; } tab = new bool[l]; foreach (string b in listBox2.Items) { tab[j] = bool.Parse(b); j++; } modbusClient.WriteMultipleCoils(start, tab); } else if (functionBox2.SelectedItem == "16 Write Multiple Registers") { int[] tab; int l = 0; int j = 0; foreach (string b in listBox2.Items) { l++; } tab = new int[l]; foreach (string b in listBox2.Items) { tab[j] = int.Parse(b); j++; } modbusClient.WriteMultipleRegisters(start, tab); } else { int[] tab; int l = 0; int j = 0; foreach (string b in listBox2.Items) { l++; } tab = new int[l]; foreach (string b in listBox2.Items) { tab[j] = int.Parse(b); j++; } modbusClient.WriteMultipleRegisters(start, tab); } }
///تایمر مربوط به خواندن هر دستگاه private void timer1_Tick(object sender, EventArgs e) { if (timerActive == true) { // try // { connection = new SqlConnection(@"Data Source=192.168.1.11\Towzin;Initial Catalog=Towzin;User ID=towzin;Password=123456;MultipleActiveResultSets=true"); connection.Close(); connection.Open(); /// مربوط به الگوریتم خواندن کلیه ای پی ها از لیست if (ListIP.Items.Count != 0 & CounterList == 0) { CounterList = ListIP.Items.Count; CounterListSql = CounterList; } if (CounterList != 0 & timerActive == true) { lblCorrect.Text = (SuccessCheckHMI = SuccessCheckHMI + 1).ToString(); ///کد مر بوط به پینگ کردن ای پی مقصد Ping p = new Ping(); PingReply r; string s; s = ListIP.Items[CounterList - 1].ToString(); r = p.Send(s, 1); if (r.Status == IPStatus.Success) { lblStatus.Text = "connect " + ListIP.Items[CounterList - 1].ToString(); svimaster.ConnectionTimeout = 1; s = svimaster.ToString(); svimaster.Connect(ListIP.Items[CounterList - 1].ToString(), 502); // ListErrors.Items.Add(CounterList.ToString() + "s" + DateTime.Now.TimeOfDay.Seconds.ToString() + ":" + DateTime.Now.TimeOfDay.Milliseconds.ToString()); int[] Main_ProductCode; // lblStatus.Text = "connect " + ListIP.Items[CounterList - 1].ToString() + " ok"; bool[] checkbit = svimaster.ReadCoils(0, 1); // Check bit send from HMI //Read Data From HMI if (checkbit[0] == true) { ///خواندن اطلاعات از HMI ///{ ///int[] productCodeHMI = svimaster.ReadHoldingRegisters(2, 12); int[] amountHMI = svimaster.ReadHoldingRegisters(105, 2); //مقدار واحد اول int[] amount1HMI = svimaster.ReadHoldingRegisters(109, 2); //مقدار واحد دوم int[] dateHMI = svimaster.ReadHoldingRegisters(101, 2); //تاریخ اضافه شدن int[] timeHMI = svimaster.ReadHoldingRegisters(103, 2); //ساعت اضافه شدن int[] opratorCodeHMI = svimaster.ReadHoldingRegisters(111, 1); //کد اپراتور ///1 محصول ///2-49 ضایعات ///50-100 توقف int[] kindHMI = svimaster.ReadHoldingRegisters(112, 1); //نوع محصول int[] sourceOrderCodeHMI = svimaster.ReadHoldingRegisters(107, 2); //کدسفارش مبدا int[] sourceProductCodeHMI = svimaster.ReadHoldingRegisters(19, 15); ///کد کالای مبدا int[] destinationOrderCodeHMI = svimaster.ReadHoldingRegisters(118, 2); ///کد سفارش مقصد int[] destinationProductCodeHMI = svimaster.ReadHoldingRegisters(40, 15); //کد کالای مقصد ///} ////تبدیل باینری به متغیر های قابل استفاده ////{ float amount = ModbusClient.ConvertRegistersToFloat(amountHMI); //وزن float amount1 = ModbusClient.ConvertRegistersToFloat(amount1HMI); //نمونه double dateInsert = ModbusClient.ConvertRegistersToDouble(dateHMI); //تاریخ double timeInsert = ModbusClient.ConvertRegistersToDouble(timeHMI); //ساعت float sourceOrderCode = ModbusClient.ConvertRegistersToFloat(sourceOrderCodeHMI); //کد شماره سفارش مبدا string sourceProductCode = ModbusClient.ConvertRegistersToString(sourceProductCodeHMI, 0, 15); //کد محصول مبدا float destinationOrderCode = ModbusClient.ConvertRegistersToFloat(destinationOrderCodeHMI); //شماره سفارش مقصد string destinationPartCode = ModbusClient.ConvertRegistersToString(destinationProductCodeHMI, 0, 15); //کد محصول مقصد DateTime dateTime; if (dateInsert > 999999) { dateTime = Convert.ToDateTime("20" + dateInsert.ToString().Substring(1, 2) + "-" + dateInsert.ToString().Substring(3, 2) + "-" + dateInsert.ToString().Substring(5, 2) + " " + timeInsert.ToString().Substring(2, 2) + ":" + timeInsert.ToString().Substring(4, 2) + ":" + timeInsert.ToString().Substring(6, 2)); } else { dateTime = Convert.ToDateTime("20" + dateInsert.ToString().Substring(0, 2) + "-" + dateInsert.ToString().Substring(2, 2) + "-" + dateInsert.ToString().Substring(4, 2) + " " + timeInsert.ToString().Substring(2, 2) + ":" + timeInsert.ToString().Substring(4, 2) + ":" + timeInsert.ToString().Substring(6, 2)); } ////} /////چک کردن اطلاعات دریافتی با دیتابیس جهت تایید اطلاعات گرفته شده ////{ bool partError = false; bool orderError = false; int status = 0; //جواب سرور دیتابیس ////چک کردن کد سفارش مبدا در دیتا بیس ////{ command = new SqlCommand("SELECT OrderCode FROM [Order] where OrderCode=" + sourceOrderCode.ToString(), connection); var tempSourceOrderCode = command.ExecuteScalar(); if (tempSourceOrderCode == null) { sourceOrderCode = 99999; // orderError = true; } ////} ///چک کردن کد سفارش مقصد در دیتا بیس ///{ //شرط جهت چک کردن اینکه اصلا کد سفارش مقصد وارد شده است یا نه if (destinationOrderCode > 0) { //check Order Code Destination command = new SqlCommand("SELECT OrderCode FROM [Order] where OrderCode=" + destinationOrderCode.ToString(), connection); var tempDestinationOrderCode = command.ExecuteScalar(); if (tempDestinationOrderCode == null) { destinationOrderCode = 99999; //orderError = true; } } ///} ////چک کردن خالی بودن کد کالای مبدا ///{ int temp = sourceProductCode.IndexOf("\0"); if (temp < 0) { sourceProductCode = sourceProductCode.Substring(0, 11); } else if (temp == 0) { sourceProductCode = "99999"; } else if (temp > 0) { sourceProductCode = sourceProductCode.Substring(0, temp); } ////} ////چک کردن کد کالای مقصد ///{ // temp = destinationPartCode.IndexOf("\0"); // if (temp < 0) // { // destinationPartCode = destinationPartCode.Substring(0, 11); //} //else if (temp == 0) //{ // destinationPartCode = "99999"; // } // else if (temp > 0) // { // destinationPartCode = destinationPartCode.Substring(0, temp); // } ////} ////چک کردن کد کالای سفارش مبدا در دیتا بیس ////{ long sourcePartID = 0; if (sourceProductCode != "99999") { command = new SqlCommand("select ID from Part where PartCode='" + sourceProductCode + "'", connection); var tempPartID = command.ExecuteScalar(); ////آیا کد کالا در دیتابیس وجود دارد if (tempPartID != null) { sourcePartID = (long)tempPartID; } else { ///در صورتی که وجود ندارد کد پیش فرض تعلق میگیرد sourcePartID = 10011; } } else { sourcePartID = 10011; } ///} //long destinationpartid = 0; /////چک کردن کد کالای سفارش مقصد //if (destinationpartcode.trim() != "") //{ // command = new sqlcommand("select id from part where partcode='" + destinationpartcode + "'", connection); // var temppartid = command.executescalar(); // ////آیا کد کالا در دیتابیس وجود دارد // if (temppartid != null) // { // destinationpartid = (long)temppartid; // } // else // { // ///در صورتی که وجود ندارد کد پیش فرض تعلق میگیرد // destinationpartid = 10011; // } //} //else //{ // destinationpartid = 10011; //} ////}پایان چک کردن در دیتا بیس ////گرفتن کد کالای ضایعاتی در صورتی وجود کد کالای مبدا /////{ long partWasteID = 0; if (sourcePartID != 10011) { command = new SqlCommand("select count(PartWesteID) from Part where ID='" + sourcePartID + "'", connection); if ((Int32)command.ExecuteScalar() != 0) { command = new SqlCommand("select PartWesteID from Part where ID='" + sourcePartID + "'", connection); var tempPartWasteID = command.ExecuteScalar(); ////آیا کد کالای ضایعاتی در دیتابیس وجود دارد if (tempPartWasteID.ToString() != null) { partWasteID = (long)tempPartWasteID; } } if (partWasteID == 0) { ///در صورتی که وجود ندارد کد پیش فرض تعلق میگیرد partWasteID = 30025; } } else { partWasteID = 30025; } ////} string Creator = "2b2f093d-19c0-4abd-b4b8-512cdacd97ab"; string modifier = "2b2f093d-19c0-4abd-b4b8-512cdacd97ab"; ///بررسی اینکه تا الان رکوردی با این زمان درج شده است یا خبر command = new SqlCommand("SELECT OrderCodeID FROM ProductiveDetails where AddDate='" + dateTime + "'", connection); var tempProductiveDetails = command.ExecuteScalar(); ///بررسی اینکه تا الان رکوردی با این زمان در جدول توقفات درج شده است یا خبر command = new SqlCommand("SELECT OrderCodeID FROM ProductiveStoppages where AddDate='" + dateTime + "'", connection); var tempProductiveStopages = command.ExecuteScalar(); ////گرفتن شماره خط تولید از ای پی string ProductionLineID = ListProductionLine.Items[CounterList - 1].ToString(); string destinationProductionLineID = ""; command = new SqlCommand("SELECT ProductionLineID FROM [Order] where OrderCode=" + destinationOrderCode + "", connection); var tempDestinationProductionLineID = command.ExecuteScalar(); if (tempDestinationProductionLineID != null) { destinationProductionLineID = tempDestinationProductionLineID.ToString(); } else { destinationProductionLineID = "20006"; } if (kindHMI[0] == 1 & tempProductiveDetails == null) { int Result1 = 1; int Result = 1; if (destinationOrderCode == 0) { command = new SqlCommand("insert into ProductiveDetails (OrderCodeID,ProductionLineID,PartID,OperatorID,IO,Waste,Amount,Amount1,IP,State,Creator,AddDate,LastModifier,LastModificationDate) VALUES (" + sourceOrderCode + "," + ProductionLineID + "," + sourcePartID + "," + "10006" + "," + 1 + "," + 0 + "," + amount + "," + amount1 + ",'" + ListIP.Items[CounterList - 1].ToString() + "'," + 1 + ",'" + Creator + "','" + dateTime + "','" + modifier + "','" + dateTime + "')", connection); Result = command.ExecuteNonQuery(); } else { //with Destination Code //command = new SqlCommand("insert into ProductiveDetails (OrderCodeID,ProductionLineID,PartID,OperatorID,IO,Waste,Amount,Amount1,ToOrderCodeID,ToPartID,State,Creator,AddDate,LastModifier,LastModificationDate) VALUES (" + sourceOrderCode + "," + ProductionLineID + "," + sourcePartID + "," + "10006" + "," + 1 + "," + 0 + "," + amount + "," + amount1 + "," + destinationOrderCode + "," + destinationPartID + "," + 1 + ",'" + Creator + "','" + dateTime + "','" + modifier + "','" + dateTime + "')", connection); command = new SqlCommand("insert into ProductiveDetails (OrderCodeID,ProductionLineID,PartID,OperatorID,IO,Waste,Amount,Amount1,IP,ToOrderCodeID,State,Creator,AddDate,LastModifier,LastModificationDate) VALUES (" + sourceOrderCode + "," + ProductionLineID + "," + sourcePartID + "," + "10006" + "," + 1 + "," + 0 + "," + amount + "," + amount1 + ",'" + ListIP.Items[CounterList - 1].ToString() + "'," + destinationOrderCode + "," + 1 + ",'" + Creator + "','" + dateTime + "','" + modifier + "','" + dateTime + "')", connection); Result1 = command.ExecuteNonQuery(); command = new SqlCommand("insert into ProductiveDetails (OrderCodeID,ProductionLineID,PartID,OperatorID,IO,Waste,Amount,Amount1,IP,FromOrderCodeID,FromPartID,State,Creator,AddDate,LastModifier,LastModificationDate) VALUES (" + destinationOrderCode + "," + destinationProductionLineID + "," + sourcePartID + "," + "10006" + "," + 0 + "," + 0 + "," + amount + "," + amount1 + ",'" + ListIP.Items[CounterList - 1].ToString() + "'," + sourceOrderCode + "," + sourcePartID + "," + 1 + ",'" + Creator + "','" + dateTime + "','" + modifier + "','" + dateTime + "')", connection); Result = command.ExecuteNonQuery(); } if (Result != 0 & orderError == false & partError == false & Result1 != 0) { status = 1; } else { status = 2; } } else if (kindHMI[0] >= 2 & kindHMI[0] <= 49 & tempProductiveDetails == null) { command = new SqlCommand("insert into ProductiveDetails (OrderCodeID,ProductionLineID,PartID,FromPartID,OperatorID,IO,Waste,Amount,IP,State,Creator,AddDate,LastModifier,LastModificationDate) VALUES (" + sourceOrderCode + "," + ProductionLineID + "," + partWasteID + "," + sourcePartID + "," + "10006" + "," + 1 + "," + 1 + "," + amount + ",'" + ListIP.Items[CounterList - 1].ToString() + "'," + 1 + ",'" + Creator + "','" + dateTime + "','" + modifier + "','" + dateTime + "')", connection); int Result = command.ExecuteNonQuery(); if (Result != 0 & partError == false & orderError == false) { status = 1; } else { status = 2; } } else if (kindHMI[0] >= 50 & kindHMI[0] <= 100 & tempProductiveStopages == null) { command = new SqlCommand("SELECT ID FROM Stoppages where Description='" + kindHMI[0] + "'", connection); var tempStoppagesID = command.ExecuteScalar(); long StoppagesID = 0; if (tempStoppagesID == null) { StoppagesID = 99; } else { StoppagesID = (long)tempStoppagesID; } if (kindHMI[0] < 100) { command = new SqlCommand("INSERT INTO [dbo].[ProductiveStoppages] ([StoppagesID],[OrderCodeID],[OperatorID],[StartTime],[IP],[State],[Creator],[AddDate],[LastModifier],[LastModificationDate]) VALUES(" + StoppagesID + "," + sourceOrderCode + "," + "10006" + ",'" + dateTime + "','" + ListIP.Items[CounterList - 1].ToString() + "'," + 1 + ",'" + Creator + "','" + dateTime + "','" + modifier + "','" + dateTime + "')", connection); } else { command = new SqlCommand("INSERT INTO [dbo].[ProductiveStoppages] ([StoppagesID],[OrderCodeID],[OperatorID],[EndTime],[IP],[State],[Creator],[AddDate],[LastModifier],[LastModificationDate]) VALUES(" + StoppagesID + "," + sourceOrderCode + "," + "10006" + ",'" + dateTime + "','" + ListIP.Items[CounterList - 1].ToString() + "'," + 1 + ",'" + Creator + "','" + dateTime + "','" + modifier + "','" + dateTime + "')", connection); } int Result = command.ExecuteNonQuery(); if (Result != 0 & partError == false) { status = 1; } else { status = 2; } } /////برگشت از سفارش else if ((kindHMI[0] == 101 || kindHMI[0] == 150) & tempProductiveDetails == null) { command = new SqlCommand("insert into ProductiveDetails (OrderCodeID,PartID,OperatorID,IO,Waste,Amount,Amount1,ip,State,Creator,AddDate,LastModifier,LastModificationDate) VALUES (" + sourceOrderCode + "," + sourcePartID + "," + "10006" + "," + 0 + "," + 0 + "," + amount * (-1) + "," + amount1 * (-1) + ",'" + ListIP.Items[CounterList - 1].ToString() + "'," + 1 + ",'" + Creator + "','" + dateTime + "','" + modifier + "','" + dateTime + "')", connection); int Result = command.ExecuteNonQuery(); if (Result != 0 & partError == false & orderError == false) { status = 1; } else { status = 2; } } if (kindHMI[0] == 0) { status = 2; } if (tempProductiveDetails != null || tempProductiveStopages != null) { status = 1; } SuccessInsert = SuccessInsert + 1; lblRead.Text = SuccessInsert.ToString(); /* Reply From SQL Sever * Status=0 Unable to Saved to SQL Server * Status=1 Save to SQL * Status=2 Error in Data */ svimaster.WriteSingleRegister(113, status); checkbit[0] = false; ///} ///پایان خواندن از HMI } long OrderCodeSource = 0; long OrderCodeDestination = 0; ///خواندن اینکه دستگاه تازه روشن شده است یا خیر اگه تازه روشن شده باشد 0 است bool[] RestartHMI = svimaster.ReadCoils(5, 1); command = new SqlCommand("SELECT SendOrderCode FROM Devices where IP='" + ListIP.Items[CounterList - 1].ToString() + "'", connection); var varSendOrderCode = command.ExecuteScalar(); bool SendOrderCode = (bool)varSendOrderCode; if (SendOrderCode == true || RestartHMI[0] == false) { ////ارسال لیست شماره شماره سفارش مبدا int addressOrder = 371; int addressLine = 299; command = new SqlCommand("SELECT OrderCode,ProductionLineLatinName FROM vwDeviceOrders where IP='" + ListIP.Items[CounterList - 1].ToString() + "' and SendOrderCode=1", connection); using (var reader = command.ExecuteReader()) { while (reader.Read()) { OrderCodeSource = (long)reader.GetInt64(reader.GetOrdinal("OrderCode")); float Main_order = OrderCodeSource; //شماره سفارش از سروربه پنل int[] floatreg = ModbusClient.ConvertFloatToTwoRegisters(Main_order); svimaster.WriteMultipleRegisters(addressOrder, floatreg); addressOrder = addressOrder + 2; string Main_ProductionLineLatinName = (string)reader.GetString(reader.GetOrdinal("ProductionLineLatinName")); //شماره سفارش از سروربه پنل int[] ProductionLineLatinName = ModbusClient.ConvertStringToRegisters(Main_ProductionLineLatinName); svimaster.WriteMultipleRegisters(addressLine, ProductionLineLatinName); addressLine = addressLine + 12; } } //command = new SqlCommand("Update Devices set SendOrderCode=0 where IP='" + ListIP.Items[CounterList - 1].ToString() + "'", connection); //command.ExecuteNonQuery(); } /////ارسال لیست شماره سفارش مقصد command = new SqlCommand("SELECT SendDestinationOrder FROM Devices where IP='" + ListIP.Items[CounterList - 1].ToString() + "'", connection); var varSendDestinationOrder = command.ExecuteScalar(); bool SendDestinationOrder = (bool)varSendDestinationOrder; if (SendDestinationOrder == true || RestartHMI[0] == false) { int addressLine = 399; int addressOrder = 519; command = new SqlCommand("SELECT OrderCode,ProductionLineLatinName FROM vwDeviceOrders where IP!='" + ListIP.Items[CounterList - 1].ToString() + "' and Region=" + ListRegion.Items[CounterList - 1].ToString(), connection); using (var reader = command.ExecuteReader()) { while (reader.Read()) { OrderCodeDestination = (long)reader.GetInt64(reader.GetOrdinal("OrderCode")); float Main_order = OrderCodeDestination; //شماره سفارش از سروربه پنل int[] floatreg = ModbusClient.ConvertFloatToTwoRegisters(Main_order); svimaster.WriteMultipleRegisters(addressOrder, floatreg); addressOrder = addressOrder + 2; string Main_ProductionLineLatinName = (string)reader.GetString(reader.GetOrdinal("ProductionLineLatinName")); //شماره سفارش از سروربه پنل int[] ProductionLineLatinName = ModbusClient.ConvertStringToRegisters(Main_ProductionLineLatinName); svimaster.WriteMultipleRegisters(addressLine, ProductionLineLatinName); addressLine = addressLine + 12; } } //command = new SqlCommand("Update Devices set SendDestinationOrder=0 where IP='" + ListIP.Items[CounterList - 1].ToString() + "'", connection); //command.ExecuteNonQuery(); } //////نوشتن شماره گاری و وزن آنها رو HMI command = new SqlCommand("SELECT SendGari FROM Devices where IP='" + ListIP.Items[CounterList - 1].ToString() + "'", connection); var varSendGari = command.ExecuteScalar(); bool SendGari = (bool)varSendGari; if (SendGari == true || RestartHMI[0] == false) //if (SendGari == true) { int addressContainerCode = 800; int addressContainerNetWeight = 600; command = new SqlCommand("SELECT ContainerCode,NetWeight FROM Container", connection); using (var reader = command.ExecuteReader()) { while (reader.Read()) { int ContainerCode = reader.GetInt32(reader.GetOrdinal("ContainerCode")); svimaster.WriteSingleRegister(addressContainerCode, ContainerCode); float Main_NetWeight = (float)reader.GetDouble(reader.GetOrdinal("NetWeight")); int[] NetWeight = ModbusClient.ConvertFloatToTwoRegisters(Main_NetWeight); svimaster.WriteMultipleRegisters(addressContainerNetWeight, NetWeight); addressContainerCode = addressContainerCode + 1; addressContainerNetWeight = addressContainerNetWeight + 2; } } command = new SqlCommand("Update Devices set SendGari=0 where IP='" + ListIP.Items[CounterList - 1].ToString() + "'", connection); command.ExecuteNonQuery(); ///ست کردن بیت ارسال مجدد گاری برای بارگزاری مجدد دیتا از دیتا بیس svimaster.WriteSingleCoil(7, true); } ////ارسال کد کالاهای سفارش مبدا در صورت تغییر در سفارش پنل bool[] ChangeOrderCodeSource = svimaster.ReadCoils(4, 1); //تغییری در کد سفارش اتفاق افتاده است یا خیر : خیر=0 if (ChangeOrderCodeSource[0] == true) { int[] OrderCodeSourceChange = svimaster.ReadHoldingRegisters(0, 2); OrderCodeSource = (long)ModbusClient.ConvertRegistersToFloat(OrderCodeSourceChange); int Address = 200; using (connection) using (command = new SqlCommand("select * from vwOrderParts where OrderCode=" + OrderCodeSource.ToString(), connection)) { { ///پاک کردن ردیف کالاها ///for (int j = 199; j <= 251; j = j + 13) ///{ // svimaster.WriteMultipleRegisters(j, ModbusClient.ConvertStringToRegisters(" ")); ///} using (SqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { string PartCodeSource = (string)reader.GetString(reader.GetOrdinal("PartCode")); string Main_prod_code = PartCodeSource;//کد کالا از سرور به پنل Main_ProductCode = ModbusClient.ConvertStringToRegisters(Main_prod_code); svimaster.WriteMultipleRegisters(Address, Main_ProductCode); Address = Address + 15; } } } svimaster.WriteSingleCoil(4, false); } } ////ارسال کد کالاهای سفارش مقصد در صورت تغییر در سفارش پنل bool[] ChangeOrderCodeDestination = svimaster.ReadCoils(6, 1); //تغییری در کد سفارش اتفاق افتاده است یا خیر : خیر=0 if (ChangeOrderCodeDestination[0] == true) { int[] OrderCodeDestinationChange = svimaster.ReadHoldingRegisters(549, 2); OrderCodeDestination = (long)ModbusClient.ConvertRegistersToFloat(OrderCodeDestinationChange); int addressPartCode = 1100; int addressPartName = 1300; using (connection) using (command = new SqlCommand("select * from vwOrderParts where OrderCode=" + OrderCodeDestination.ToString(), connection)) { { ////پاک کردن ردیف کالاها ///for (int j = 199; j <= 251; j = j + 13) ///{ /// svimaster.WriteMultipleRegisters(j, ModbusClient.ConvertStringToRegisters(" ")); ///} using (SqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { string tempSourcePartCode = (string)reader.GetString(reader.GetOrdinal("PartCode")); ///string Main_prod_code = tempSourcePartCode;//کد کالا از سرور به پنل Main_ProductCode = ModbusClient.ConvertStringToRegisters(tempSourcePartCode); svimaster.WriteMultipleRegisters(addressPartCode, Main_ProductCode); addressPartCode = addressPartCode + 15; string tempSourcePartName = (string)reader.GetString(reader.GetOrdinal("LatinName")); string Main_prod_code = tempSourcePartName;//کد کالا از سرور به پنل Main_ProductCode = ModbusClient.ConvertStringToRegisters(Main_prod_code); svimaster.WriteMultipleRegisters(addressPartName, Main_ProductCode); addressPartName = addressPartName + 12; } } } svimaster.WriteSingleCoil(6, false); } } //string Main_prod_code = "uyuy";//کد کالا از سرور به پنل // Main_ProductCode = ModbusClient.ConvertStringToRegisters(Main_prod_code); // svimaster.WriteMultipleRegisters(2, Main_ProductCode); lblStatus.Text = "Read Device " + ListIP.Items[CounterList - 1].ToString(); ///مربوط به الگوریتم خواندن کلیه ای پی ها از لیست svimaster.WriteSingleCoil(5, true); svimaster.WriteSingleCoil(8, true); } CounterList = CounterList - 1; //// برای قسمت تازه روشن دستگاه و یک کردن آن connection.Close(); svimaster.Disconnect(); int i = DateTime.Compare(DateTime.Now, startTime); TimeSpan avgTime = DateTime.Now.Subtract(startTime); lblAvarage.Text = (avgTime.TotalSeconds / SuccessCheckHMI).ToString(); } connection.Close(); svimaster.Disconnect(); /*} * * * catch (Exception ex) * { * * ListErrors.Items.Add(ListIP.Items[CounterList - 1].ToString() + ex.Message); * connection.Close(); * svimaster.Disconnect(); * lblWrong.Text = (wrongRead = wrongRead + 1).ToString(); * }*/ } }
private void PLCCom(object sender, DoWorkEventArgs e) { if (Data.InputDI[0] == false) { try { modbusClient.Connect(); } catch { // MessageBox.Show("连接设备故障,故障代码:" + ex.Message, "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Error); } } //判断PLC是否已经连接 Data.InputDI[0] = modbusClient.Connected; //如果已经连接并且通信标志位Data.PLCComFlag为1,则开始读写数据 if (modbusClient.Connected) { try { //周期性的读取数据 if (Data.PLCComFlag) { int[] readHoldingRegisters = new int[50]; readHoldingRegisters = modbusClient.ReadHoldingRegisters(0, 30); //对获取的数据进行解码 Data.InputAI[10] = Convert.ToDouble(readHoldingRegisters[0]) / 100.0; // Data.InputAI[11] = Convert.ToDouble(readHoldingRegisters[1]) / 100.0; Data.InputAI[12] = Convert.ToDouble(readHoldingRegisters[2]) / 100.0; Data.InputAI[13] = Convert.ToDouble(readHoldingRegisters[3]) / 100.0; Data.InputAI[14] = Convert.ToDouble(readHoldingRegisters[4]) / 10.0; byte[] LrealTrans1 = BitConverter.GetBytes(readHoldingRegisters[5]); byte[] LrealTrans2 = BitConverter.GetBytes(readHoldingRegisters[6]); byte[] LrealTrans3 = BitConverter.GetBytes(readHoldingRegisters[7]); byte[] LrealTrans4 = BitConverter.GetBytes(readHoldingRegisters[8]); byte[] LrealTrans = new byte[8]; LrealTrans[0] = LrealTrans1[0]; LrealTrans[1] = LrealTrans1[1]; LrealTrans[2] = LrealTrans2[0]; LrealTrans[3] = LrealTrans2[1]; LrealTrans[4] = LrealTrans3[0]; LrealTrans[5] = LrealTrans3[1]; LrealTrans[6] = LrealTrans4[0]; LrealTrans[7] = LrealTrans4[1]; //Data.InputAI[15] = BitConverter.ToDouble(LrealTrans,0); Data.InputAI[20] = Convert.ToDouble(readHoldingRegisters[10]) / 100.0; // Data.InputAI[21] = Convert.ToDouble(readHoldingRegisters[11]) / 100.0; Data.InputAI[22] = Convert.ToDouble(readHoldingRegisters[12]) / 100.0; Data.InputAI[23] = Convert.ToDouble(readHoldingRegisters[13]) / 100.0; Data.InputAI[24] = Convert.ToDouble(readHoldingRegisters[14]) / 10.0; LrealTrans1 = BitConverter.GetBytes(readHoldingRegisters[15]); LrealTrans2 = BitConverter.GetBytes(readHoldingRegisters[16]); LrealTrans3 = BitConverter.GetBytes(readHoldingRegisters[17]); LrealTrans4 = BitConverter.GetBytes(readHoldingRegisters[18]); LrealTrans = new byte[8]; LrealTrans[0] = LrealTrans1[0]; LrealTrans[1] = LrealTrans1[1]; LrealTrans[2] = LrealTrans2[0]; LrealTrans[3] = LrealTrans2[1]; LrealTrans[4] = LrealTrans3[0]; LrealTrans[5] = LrealTrans3[1]; LrealTrans[6] = LrealTrans4[0]; LrealTrans[7] = LrealTrans4[1]; //Data.InputAI[25] = BitConverter.ToDouble(LrealTrans, 0); // Data.InputAI[4] = Convert.ToDouble(readHoldingRegisters[20]) / 100.0;//InstantShipSpeed Data.InputAI[7] = Convert.ToDouble(readHoldingRegisters[21]) / 100.0; //Vol Data.InputAI[8] = Convert.ToDouble(readHoldingRegisters[22]) / 100.0; //Weight Data.InputAI[9] = Convert.ToDouble(readHoldingRegisters[23]) / 100.0; //Density Data.PLCComFlag = false; } //实时的写入数据 int[] PLCWrite = new int[20]; PLCWrite[0] = Data.Mode_Selected; //当前的模式选择 PLCWrite[1] = Data.OperatorNow; //当前的操作员选择 modbusClient.WriteMultipleRegisters(100, PLCWrite); } catch (Exception ex) { MessageBox.Show("连接设备故障,故障代码:" + ex.Message, "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Error); } } }