private void Dt_Scan_IO_Ticker(object sender, EventArgs e) { if (Connect_flag == true) { bool[] _ReadCoils = modbusClient.ReadDiscreteInputs(0, 8); int _index = 0; CheckBox[] _CheckBoxes = { lb_DI_00, lb_DI_01, lb_DI_02, lb_DI_03, lb_DI_04, lb_DI_05, lb_DI_06, lb_DI_07 }; foreach (CheckBox cb in _CheckBoxes) { cb.IsChecked = _ReadCoils[_index]; if (cb.IsChecked == true) { cb.Foreground = new SolidColorBrush(Colors.Green); cb.FontWeight = FontWeights.ExtraBold; } else { cb.Foreground = new SolidColorBrush(Colors.Black); cb.FontWeight = FontWeights.Bold; } _index++; } } }
private void Timer1_Tick(object sender, EventArgs e) { try { timer1.Stop(); bool[] ip = modbusClient.ReadDiscreteInputs(0, 9); for (int i = 0; i < 9; i++) { Control[] sayacLabels = Controls.Find("lbl" + (i + 1).ToString(), true); Label sayac = (Label)sayacLabels[0]; sayac.BackColor = Color.White; sayac.ForeColor = Color.Black; if (ip[i]) { sayac.BackColor = Color.Green; sayac.ForeColor = Color.White; } } timer1.Start(); } catch (Exception ex) { timer1.Stop(); LblBaglandi.Visible = false; BtnBaglan.Enabled = true; MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
static void Main(string[] args) { ModbusClient modBusClient = new ModbusClient("127.0.0.1", 502); modBusClient.Connect(); bool[] readCoils = modBusClient.ReadCoils(0, 10); int[] readInputRegisters = modBusClient.ReadInputRegisters(0, 10); int[] readsHoldingRegisters = modBusClient.ReadHoldingRegisters(0, 10); bool[] readDiscreteInputs = modBusClient.ReadDiscreteInputs(0, 10); int[] ar = new int[5]; ar[0] = 1; ar[1] = 2; ar[2] = 3; int[] readMultipleRegisters = modBusClient.ReadWriteMultipleRegisters(0, 10, 0, ar); for (int i = 0; i < readCoils.Length; i++) { Console.WriteLine("Value of Coil :" + (9 + i + 1) + " " + readCoils[i].ToString()); } for (int i = 0; i < readsHoldingRegisters.Length; i++) { Console.WriteLine("Value of HoldingRegister :" + (9 + i + 1) + " " + readsHoldingRegisters[i].ToString()); } Console.Read(); }
public void ReadDiscreteInput() { try { Console.WriteLine("Please Enter The Starting Address of DiscreteInput:"); string discreteInput = Console.ReadLine(); int input = Convert.ToInt32(discreteInput); bool[] readDiscreteInputs = modbusClient.ReadDiscreteInputs(input, 10); if (readDiscreteInputs != null) { for (int i = 0; i < readDiscreteInputs.Length; i++) { Console.WriteLine((input) + ":" + "<" + readDiscreteInputs[i] + ">"); input++; } } modbusClient.Disconnect(); Console.ReadLine(); } catch (Exception e) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(e.Message); Console.ResetColor(); Console.ReadLine(); } }
public static bool[] LayDuLieuTCPInputs(ModbusClient modbus, ushort quantityInputs, ushort minAddressInputs, ThietBiModel thietBiModel) { List <bool> readDiscreteInputs = new List <bool>(); if (quantityInputs != 0) { try { int soNguyenSauChia = quantityInputs / DonViQuantityMoiLanDoc; for (int i = 0; i <= soNguyenSauChia; i++) { if (i != soNguyenSauChia) { int startAddress = i * DonViQuantityMoiLanDoc + minAddressInputs; int quantity = DonViQuantityMoiLanDoc - minAddressInputs; var temp = modbus.ReadDiscreteInputs(startAddress, (ushort)(quantity)); readDiscreteInputs.AddRange(temp.ToList()); } else if (i == soNguyenSauChia) { int startAddress = i * DonViQuantityMoiLanDoc + minAddressInputs; int quantity = quantityInputs % DonViQuantityMoiLanDoc - minAddressInputs; if (quantity != 0) { var temp = modbus.ReadDiscreteInputs(startAddress, (ushort)(quantity)); readDiscreteInputs.AddRange(temp.ToList()); } } } } catch (ModbusException ex) { ExceptionFunctionCode(ex, thietBiModel); throw; } catch (Exception ex)//Lỗi lấy dữ liệu thất bại { ExceptionErrorConnection(ex, thietBiModel); throw; } } return(readDiscreteInputs.ToArray()); }
// Reads data from OpenPLC public bool read(int index) { if (connectionEstablished == true) { readCoils = modbusClient.ReadDiscreteInputs(0, 22); //Read 15 Coils from Server, starting with address 0 return(readCoils[index]); //for (int i = 0; i < readCoils.Length; i++) // print("Value of Coil " + i + " " + readCoils[i].ToString()); } return(false); }
public void MasterShouldReadDiscreteInputsFromSlave() { var clientMemory = new ModbusMemoryMap(); var client = new ModbusClient(new ModbusRTUTransport(_clientStream)); var clientDevice = new ModbusDevice(clientMemory, 4); var serverMemory = new ModbusMemoryMap(); var server = new ModbusServer(new ModbusRTUTransport(_serverStream)); var serverDevice = new ModbusDevice(serverMemory, 4); serverMemory.InputCoils[10] = true; serverMemory.InputCoils[15] = true; clientMemory.InputCoils[10].ShouldBeFalse(); clientMemory.InputCoils[15].ShouldBeFalse(); Task.Run(() => server.HandleRequest(serverDevice)); //read only one input client.ReadDiscreteInputs(clientDevice, 10, 1); //slave memory not touched serverMemory.InputCoils[10].ShouldBeTrue(); serverMemory.InputCoils[15].ShouldBeTrue(); //master memory is synched clientMemory.InputCoils[10].ShouldBeTrue(); clientMemory.InputCoils[15].ShouldBeFalse(); Task.Run(() => server.HandleRequest(serverDevice)); //read another input client.ReadDiscreteInputs(clientDevice, 15, 1); //master memory is synched clientMemory.InputCoils[10].ShouldBeTrue(); clientMemory.InputCoils[15].ShouldBeTrue(); }
private void Actualizar_InDigitales() { var m = modbusClient.ReadDiscreteInputs(0, 8); consultaHabilitada = true; //motor1.Value = Valor[0].ToString(); //motor2.Value = Valor[1].ToString(); //motor3.Value = Valor[2].ToString(); //motor4.Value = Valor[3].ToString(); //waterPump1.Value = Valor[4].ToString(); //waterPump2.Value = Valor[5].ToString(); //waterPump3.Value = Valor[6].ToString(); //waterPump4.Value = Valor[7].ToString(); }
public void lerDados(int tipo) { int startadd, quant; string[] dados = new string[1]; try { if (modbus.Connected) { if (int.TryParse(tb_endi.Text, out startadd) && int.TryParse(tb_quantidade.Text, out quant) { tb_dados.Text = ""; switch (tipo) { case 1: bool[] dadosCo = modbus.ReadCoils(startadd, quant); dados = dadosCo.Select(x => x.ToString()).ToArray(); break; case 2: bool[] dadosDI = modbus.ReadDiscreteInputs(startadd, quant); dados = dadosDI.Select(x => x.ToString()).ToArray(); break; case 3: int[] dadosHR = modbus.ReadHoldingRegisters(startadd, quant); dados = dadosHR.Select(x => x.ToString()).ToArray(); break; case 4: int[] dadosIR = modbus.ReadInputRegisters(startadd, quant); dados = dadosIR.Select(x => x.ToString()).ToArray(); break; } for (int i = 0; i < dados.Length; i++) { tb_dados.Text += "Dado " + i.ToString() + ": " + dados[i].ToString() + "\r\n"; } } } else { MessageBox.Show("Servidor MODBUS TCP Desconectado"); } } catch (Exception err) { MessageBox.Show("Erro na leitura dos dados MODBUS. \r\nErro: " + err.Message); } }
private string ReadDataFromSlave(int FunctionCode, int startingAddress) { try // 데이터 Gathering 시도 { switch (FunctionCode) { case 0: return(modbusClient.ReadCoils(startingAddress, 1)[0].ToString()); // FC 1 00000-100000 시작번지 부터 지정한 개수 읽기 case 1: return(modbusClient.ReadDiscreteInputs(startingAddress, 1)[0].ToString()); // FC 2 100001-200000 case 2: return(modbusClient.ReadHoldingRegisters(startingAddress, 1)[0].ToString()); // FC 3 400001-500000 case 3: return(modbusClient.ReadInputRegisters(startingAddress, 1)[0].ToString()); // FC 4 300000-400000 default: // 이외의 값이 들어올 때 처리 return(null); } } catch (Exception) { return(null); } #region 예외처리 보관함 /*catch (ModbusException) // 모드버스 예외 발생 시 * { * i--; // 예외 발생한 부분 다시 반복 * } * catch (TimeoutException) // 타임 아웃 에러 시 * { * i--; // 예외 발생한 부분 다시 반복 * } * catch (StackOverflowException) // 데이터 과다복용 사망 시 * { * i--; * } * catch (NullReferenceException) * { * readData[i] = "Null 붙잡을 노래"; * } */ #endregion }
private bool[] ReadDiscretInputsValue() { bool[] readInputs = new bool[16]; try { readInputs = modbusClient.ReadDiscreteInputs(0, 16); return(readInputs); } catch (Exception ex) { Console.WriteLine(ex); MessageBox.Show("Erro de conexão com a placa Modbus", "Erro de conexão", MessageBoxButtons.OK, MessageBoxIcon.Error); modbusClient.Disconnect(); modbusClient = null; } return(readInputs); }
// read %I public bool[] ReadI(int startingAddress, int quantity) { bool[] val = new bool[quantity]; try { ModbusClient client = new ModbusClient(IPAddress, Port); client.Connect(); val = client.ReadDiscreteInputs(startingAddress, quantity); client.Disconnect(); } catch { } return(val); }
private void Dt_ModbusTicker(object sender, EventArgs e) { try// ---read Input { bool[] DI_Tray_Present_Sensor = modbusClient.ReadDiscreteInputs(int.Parse(Paras.DI_Tray_Present_Sensor.Value), 1); Cb_DI_Tray_Present_Sensor.IsChecked = DI_Tray_Present_Sensor[0]; if (DI_Tray_Present_Sensor[0]) { if (Threshold_Counter <= float.Parse(Paras.Threshold_Trigger.Value)) { Threshold_Counter++; //Capture_Flag = true; } } else { Threshold_Counter = 0; Cb_Trigger.IsChecked = false; } Lb_Trigger.Content = Threshold_Counter.ToString(); } catch { MessageBox.Show("Error104: Fail to read Digital Input"); StateMachine_NotInit(); Dt_Modbus.Stop(); } // ---Write Digital Output try { modbusClient.WriteSingleCoil(int.Parse(Paras.DO_Red_Light.Value), Convert.ToBoolean(Cb_DO_Red_Light.IsChecked)); //modbusClient.WriteSingleCoil(int.Parse(Paras.DO_Amber_Light.Value), Convert.ToBoolean(//Cb_DO_Amber_Light.IsChecked)); modbusClient.WriteSingleCoil(int.Parse(Paras.DO_Green_Light.Value), Convert.ToBoolean(Cb_DO_Green_Light.IsChecked)); modbusClient.WriteSingleCoil(int.Parse(Paras.DO_Buzzer.Value), Convert.ToBoolean(Cb_DO_Buzzer.IsChecked)); modbusClient.WriteSingleCoil(int.Parse(Paras.DO_Disable_Tray_Loading.Value), Convert.ToBoolean(Cb_DO_Disable_Tray_Loading.IsChecked)); } catch { MessageBox.Show("Error105: Fail to write Digital Output"); StateMachine_NotInit(); Dt_Modbus.Stop(); } }
public bool[] ReadDiscreteInputs(byte slaveAddress, int startAddress, int numberOfPoints) { Log.Debug("GET ReadDiscreteInputs: SlaveAddress {0}, StartAddress {1}, NumberOfPoints {2}", slaveAddress, startAddress, numberOfPoints); try { _master.UnitIdentifier = slaveAddress; var response = _master.ReadDiscreteInputs(startAddress, numberOfPoints); Log.Debug("RESPONSE ReadHoldingRegisters: {0}", String.Join(",", response)); return(response); } catch (Exception ex) { // return new ushort[] { Convert.ToUInt16(new Random().Next(2, 4)) }; Log.Error(ex, "ERROR: ReadHoldingRegisters: SlaveAddress {0}, StartAddress {1}, NumberOfPoints {2} - MSG: {3}", slaveAddress, startAddress, numberOfPoints, ex.Message); //throw ex; return(null); } }
private void btnReadDiscreteInputs_Click(object sender, EventArgs e) { try { if (!modbusClient.Connected) { button3_Click(null, null); } bool[] serverResponse = modbusClient.ReadDiscreteInputs(int.Parse(txtStartingAddressInput.Text) - 1, int.Parse(txtNumberOfValuesInput.Text)); lsbAnswerFromServer.Items.Clear(); for (int i = 0; i < serverResponse.Length; i++) { lsbAnswerFromServer.Items.Add(serverResponse[i]); } } catch (Exception exc) { MessageBox.Show(exc.Message, "Exception Reading values from Server", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
//lấy dữ liệu của các thiết bị private void getDataDevice(KeyValuePair <string, DeviceModel> deviceUnit, string filePath) { string[] output = new string[deviceUnit.Value.ListDuLieuChoTungPLC.Count]; //doc tung dong trong list data cua 1 device for (int i = 0; i < deviceUnit.Value.ListDuLieuChoTungPLC.Count; i++) { DuLieuModel duLieuTemp = deviceUnit.Value.ListDuLieuChoTungPLC.ElementAt(i).Value; string giaTriDuLieu = ""; try { if (Convert.ToInt32(duLieuTemp.DiaChi) <= 65536) { bool[] readCoil = mobus.ReadCoils(Convert.ToInt32(duLieuTemp.DiaChi), 1); giaTriDuLieu = readCoil[0].ToString(); } else if (Convert.ToInt32(duLieuTemp.DiaChi) <= 165536 && Convert.ToInt32(duLieuTemp.DiaChi) >= 100001) { bool[] discreteInput = mobus.ReadDiscreteInputs(Convert.ToInt32(duLieuTemp.DiaChi) - 100001, 1); giaTriDuLieu = discreteInput[0].ToString(); } else if (Convert.ToInt32(duLieuTemp.DiaChi) <= 365536 && Convert.ToInt32(duLieuTemp.DiaChi) >= 300001) { int[] readRegister = mobus.ReadInputRegisters(Convert.ToInt32(duLieuTemp.DiaChi) - 300001, 1); giaTriDuLieu = readRegister[0].ToString(); } else if (Convert.ToInt32(duLieuTemp.DiaChi) <= 465536 && Convert.ToInt32(duLieuTemp.DiaChi) >= 400001) { int[] readHoldingRegister = mobus.ReadHoldingRegisters(Convert.ToInt32(duLieuTemp.DiaChi) - 400001, 1); giaTriDuLieu = readHoldingRegister[0].ToString(); } duLieuTemp.GiaTri = Convert.ToInt32(giaTriDuLieu); duLieuTemp.ThoiGianDocGiuLieu = DateTime.Now; deviceUnit.Value.TrangThaiKetNoi = 1; } catch (Exception ex) { } } }
private void b_read_input_Click(object sender, RoutedEventArgs e) { //读取输入 input 信号 : ReadDiscreteInputs bool[] InputStatus = modbusClient.ReadDiscreteInputs(0, 3); if (InputStatus[0] == true) { label3_Copy0.Background = new SolidColorBrush(Colors.Green); label3_Copy0.Content = InputStatus[0].ToString(); } else { label3_Copy0.Background = new SolidColorBrush(Colors.Red); label3_Copy0.Content = InputStatus[0].ToString(); } if (InputStatus[1] == true) { label3_Copy1.Background = new SolidColorBrush(Colors.Green); label3_Copy1.Content = InputStatus[1].ToString(); } else { label3_Copy1.Background = new SolidColorBrush(Colors.Red); label3_Copy1.Content = InputStatus[1].ToString(); } if (InputStatus[2] == true) { label3_Copy2.Background = new SolidColorBrush(Colors.Green); label3_Copy2.Content = InputStatus[2].ToString(); } else { label3_Copy2.Background = new SolidColorBrush(Colors.Red); label3_Copy2.Content = InputStatus[2].ToString(); } }
public async Task ClientReadDiscreteInputsTest() { // Function Code 0x02 var expectedRequest = new byte[] { 0, 0, 0, 6, 1, 2, 0, 12, 0, 2 }; var expectedResponse = new List <DiscreteInput> { new DiscreteInput { Address = 12, Value = true }, new DiscreteInput { Address = 13, Value = true } }; using (var server = new MiniTestServer()) { server.RequestHandler = (request, clientIp) => { CollectionAssert.AreEqual(expectedRequest, request.Skip(2).ToArray(), "Request is incorrect"); Console.WriteLine("Server sending response"); return(new byte[] { request[0], request[1], 0, 0, 0, 4, 1, 2, 1, 3 }); }; server.Start(); using (var client = new ModbusClient(IPAddress.Loopback, server.Port, new ConsoleLogger())) { await client.Connect(); Assert.IsTrue(client.IsConnected); var inputs = await client.ReadDiscreteInputs(1, 12, 2); Assert.IsTrue(string.IsNullOrWhiteSpace(server.LastError), server.LastError); CollectionAssert.AreEqual(expectedResponse, inputs, "Response is incorrect"); } } }
public void GetValues(ConnectionProperties connectionProperties) { modbusClient = connectionProperties.modbusClient; if (!modbusClient.Connected) { modbusClient.IPAddress = connectionProperties.ModbusTCPAddress; modbusClient.Port = connectionProperties.Port; modbusClient.Connect(); } foreach (FunctionProperties functionProperty in connectionProperties.FunctionPropertiesList) { switch (functionProperty.FunctionCode) { case FunctionCode.ReadCoils: functionProperty.values = modbusClient.ReadCoils(functionProperty.StartingAdress, functionProperty.Quantity); break; case FunctionCode.ReadDiscreteInputs: functionProperty.values = modbusClient.ReadDiscreteInputs(functionProperty.StartingAdress, functionProperty.Quantity); break; case FunctionCode.ReadHoldingRegisters: functionProperty.values = modbusClient.ReadHoldingRegisters(functionProperty.StartingAdress, functionProperty.Quantity); break; case FunctionCode.ReadInputRegisters: functionProperty.values = modbusClient.ReadInputRegisters(functionProperty.StartingAdress, functionProperty.Quantity); break; default: break; } } if (valuesChanged != null) { valuesChanged(this); } }
private void imagegrabtimer_Tick(object sender, EventArgs e) { try { bool[] data = plcmodule.ReadDiscreteInputs(1024, 1); draw = true; if (data[0] == true) { sw.Reset(); sw1.Reset(); textBox1.Text = "0"; textBox2.Text = "0"; sw1.Start(); plcmodule.WriteSingleCoil(1283, false); Thread.Sleep(2000); for (int i = 0; i < 2; i++) { capture.Read(Inputimg); } framecount++; Cv2.CvtColor(Inputimg, outimg, ColorConversionCodes.BGR2GRAY); frame_conut.Text = framecount.ToString(); sw1.Stop(); textBox2.Text = sw1.ElapsedMilliseconds.ToString(); //Cv2.ImWrite("Empty" + ".bmp", outimg); Process_image(); } } catch (Exception Ex) { //MessageBox.Show("image is not good"); //MessageBox.Show(Ex.Message.ToString()); log.Error("Error Message: " + Ex.Message.ToString(), Ex); } }
public override void Execute(ModbusClient modbusClient) { ModbusReadCommandParameters mdb_read_comm_pars = this.CommandParameters as ModbusReadCommandParameters; ushort startAddress = mdb_read_comm_pars.StartAddress; ushort quantity = mdb_read_comm_pars.Quantity; if (quantity <= 0) { string message = $"Reading Quantity: {quantity} does not make sense."; Logger.LogError(message); throw new Exception(message); } if (startAddress + quantity >= ushort.MaxValue || startAddress + quantity == ushort.MinValue || startAddress == ushort.MinValue) { string message = $"Address is out of bound. Start address: {startAddress}, Quantity: {quantity}"; Logger.LogError(message); throw new Exception(message); } bool[] data = new bool[0]; try { if (modbusClient.Connected) { data = modbusClient.ReadDiscreteInputs(startAddress - 1, quantity); } else { Logger.LogError("modbusClient is disconected "); } } catch (Exception e) { Logger.LogError("Error on ReadDiscreteInputs()", e); throw e; } Data = new Dictionary <long, DiscreteModbusData>(data.Length); var currentSCADAModel = SCADAModel.CurrentScadaModel; var currentAddressToGidMap = SCADAModel.CurrentAddressToGidMap; var commandValuesCache = SCADAModel.CommandedValuesCache; for (ushort i = 0; i < data.Length; i++) { ushort address = (ushort)(startAddress + i); ushort value = (ushort)(data[i] ? 1 : 0); //for commands enqueued during model update if (!currentAddressToGidMap[PointType.DIGITAL_INPUT].ContainsKey(address)) { Logger.LogWarn($"ReadDiscreteInputsFunction execute => trying to read value on address {address}, Point type: {PointType.DIGITAL_INPUT}, which is not in the current SCADA Model."); continue; } long gid = currentAddressToGidMap[PointType.DIGITAL_INPUT][address]; //for commands enqueued during model update if (!currentSCADAModel.ContainsKey(gid)) { Logger.LogWarn($"ReadDiscreteInputsFunction execute => trying to read value for measurement with gid: 0x{gid:X16}, which is not in the current SCADA Model."); continue; } if (!(currentSCADAModel[gid] is DiscreteSCADAModelPointItem pointItem)) { string message = $"PointItem [Gid: 0x{gid:X16}] is not type DiscreteSCADAModelPointItem."; Logger.LogError(message); throw new Exception(message); } if (pointItem.CurrentValue != value) { pointItem.CurrentValue = value; Logger.LogInfo($"Alarm for Point [Gid: 0x{pointItem.Gid:X16}, Point type: {PointType.DIGITAL_INPUT}, Address: {pointItem.Address}] set to {pointItem.Alarm}."); } CommandOriginType commandOrigin = CommandOriginType.OTHER_COMMAND; if (commandValuesCache.ContainsKey(gid) && commandValuesCache[gid].Value == value) { commandOrigin = commandValuesCache[gid].CommandOrigin; commandValuesCache.Remove(gid); Logger.LogDebug($"[ReadDiscreteInputsFunction] Command origin of command address: {pointItem.Address} is set to {commandOrigin}."); } DiscreteModbusData digitalData = new DiscreteModbusData(value, pointItem.Alarm, gid, commandOrigin); Data.Add(gid, digitalData); //Logger.LogDebug($"ReadDiscreteInputsFunction execute => Current value: {value} from address: {address}, point type: {PointType.DIGITAL_INPUT}, gid: 0x{gid:X16}."); } //Logger.LogDebug($"ReadDiscreteInputsFunction executed SUCCESSFULLY. StartAddress: {startAddress}, Quantity: {quantity}"); }
private void Form1_Load(object sender, EventArgs e) { try { //VideoCapture capture = new VideoCapture(0, VideoCaptureAPIs.DSHOW); // capture.Settings = 1; capture.AutoFocus = false; //capture.Set(VideoCaptureProperties.AutoFocus, false); //capture.Set(VideoCaptureProperties.Focus, 3); capture.Focus = 35; capture.AutoExposure = 3; capture.Exposure = -6; capture.Gain = 20;//120 //capture.Brightness = 128;//1 capture.FrameWidth = 1920; capture.FrameHeight = 1080; //capture.Sharpness = 128; //capture.Saturation = 129; //capture.BackLight = 1; DateTime currentdate = DateTime.Now.Date; DateTime Expirydate = new DateTime(2021, 04, 01); int res = currentdate.CompareTo(Expirydate); if (res == 1) { MessageBox.Show("SOFTWARE EXPIRED"); Application.Exit(); } else if (res == 0) { MessageBox.Show("1 day to expire"); } datetime.Enabled = true; //sw.Start(); //capture.Open(1); //sw.Stop(); framecount = 0; loadsettings(); //imagecount = 0; if (!Directory.Exists(@"D:\VISION RESULTS\"))//creating folder folder for saving imager { Directory.CreateDirectory(@"D:\VISION RESULTS\"); } if (!Directory.Exists(@"D:\VISION RESULTS\" + DateTime.Now.ToString("dd/MM/yyyy"))) { Directory.CreateDirectory(@"D:\VISION RESULTS\" + DateTime.Now.ToString("dd/MM/yyyy")); imagecount = 0; } if (capture.IsOpened()) { camstatus.Text = "Camera connected"; camstatus.ForeColor = Color.Green; } else { camstatus.Text = "Camera not connected"; camstatus.ForeColor = Color.Red; } plcmodule = new ModbusClient("COM4"); plcmodule.Parity = System.IO.Ports.Parity.Even; plcmodule.Connect(); bool[] plcdata = plcmodule.ReadDiscreteInputs(1024, 1); if ((plcdata == null)) { plcstatus.Text = "PLC is not connected"; plcstatus.ForeColor = Color.Red; } else { plcstatus.Text = "PLC is connected"; plcstatus.ForeColor = Color.Green; } //capture.Release(); //stop reading an image,erase parametrs(release) } catch (Exception Ex) { if (plcstatus.Text == "PLC Status") { plcstatus.Text = "PLC is not connected"; plcstatus.ForeColor = Color.Red; } MessageBox.Show(Ex.Message.ToString()); log.Error("Error Message: " + Ex.Message.ToString(), Ex); } }
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); } }
public bool[] ReadDiscreteInputs(int startReg, int length) { return(_client.ReadDiscreteInputs(startReg, length)); }
private void buttonExecute_Click(object sender, EventArgs e) { start = Int32.Parse(addBox1.Text); licznik = Int32.Parse(addBox2.Text); //bool[] b; //var dict = new ConcurrentDictionary<int, int>(); //var task = Task.Factory.StartNew(() => CykliczneOdpytanie(ref dict)); //wynik = new List<ChartData>(); //ChartData chartDate = new ChartData(); if (functionBox.SelectedItem == "01 Read Coil Status") { cts.Cancel(); cts.Dispose(); cts = new CancellationTokenSource(); ThreadPool.QueueUserWorkItem(new WaitCallback(CoilOdczyt), cts.Token); //Task.Factory.StartNew(() => CoilOdczyt()); //Task.Factory.StartNew(() => backgroundWorker1.RunWorkerAsync()); //listBox1.DataSource = modbusClient.ReadCoils(start, licznik); //backgroundWorker1.RunWorkerAsync(); //Thread.Sleep(1000); //for (int i = 0; i < licznik; i++) //{ // chartDate.IDex = i; // if (bool.Parse(listBox1.Items[i].ToString()) == false) // { // chartDate.Value = 0; // } // else if (bool.Parse(listBox1.Items[i].ToString()) == true) // { // chartDate.Value = 1; // } // wynik.Add(chartDate); //} } else if (functionBox.SelectedItem == "02 Read Input Status") { cts.Cancel(); cts.Dispose(); cts = new CancellationTokenSource(); listBox1.DataSource = modbusClient.ReadDiscreteInputs(start, licznik); } else if (functionBox.SelectedItem == "03 Read Holding Registers") { cts.Cancel(); cts.Dispose(); cts = new CancellationTokenSource(); listBox1.DataSource = modbusClient.ReadHoldingRegisters(start, licznik); //for (int i = 0; i < licznik; i++) //{ // chartDate.IDex = i; // chartDate.Value = int.Parse(listBox1.Items[i].ToString()); // wynik.Add(chartDate); //} } else if (functionBox.SelectedItem == "04 Read Input Registers") { cts.Cancel(); cts.Dispose(); cts = new CancellationTokenSource(); listBox1.DataSource = modbusClient.ReadInputRegisters(start, licznik); } else { cts.Cancel(); cts.Dispose(); cts = new CancellationTokenSource(); listBox1.DataSource = modbusClient.ReadHoldingRegisters(start, licznik); } }
} //End Function Disconnect /// <summary> /// Reads data from the Server Device.</summary> public bool Read(DataExtClass[] DataOut) { bool retVar = false; int i, j, jj, SAddress, boolReg, boolBit; uint highWord, lowWord; DAConfClass thisArea; //If is not initialized and not connected return error. if (!(isInitialized && (DataOut != null))) { Status.NewStat(StatType.Bad, "Not Ready for Reading"); return false; } //If the DataOut and Internal data doesnt have the correct amount of data areas return error. if (!((DataOut.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; } //Cicle thru Data Areas. for (i = 0; i < MasterDriverConf.NDataAreas; i++) { thisArea = MasterDataAreaConf[i]; SAddress = int.Parse(thisArea.StartAddress); if (thisArea.Enable && (!thisArea.Write)) { try { //Read the data from the device switch (thisArea.dataType) { case DriverConfig.DatType.Bool: if ((thisArea.DBnumber >= 1) && (thisArea.DBnumber <= 2)) { if (thisArea.DBnumber == 1) IntData[i].dBool = ModTCPObj.ReadCoils(SAddress, thisArea.Amount); if (thisArea.DBnumber == 2) IntData[i].dBool = ModTCPObj.ReadDiscreteInputs(SAddress, thisArea.Amount); if (IntData[i].dBool.Length == thisArea.Amount) retVar = true; } else if ((thisArea.DBnumber >= 3) && (thisArea.DBnumber <= 4)) { boolReg = (int)Math.Ceiling(thisArea.Amount / 16.0); if (thisArea.DBnumber == 3) IntData[i].dInt = ModTCPObj.ReadHoldingRegisters(SAddress, boolReg); if (thisArea.DBnumber == 4) IntData[i].dInt = ModTCPObj.ReadInputRegisters(SAddress, boolReg); //Check read complete set of data if (IntData[i].dInt.Length == boolReg) retVar = true; } else { //Invalid Conf retVar = false; Status.NewStat(StatType.Warning, "Wrong FC for Read, Check Config."); } break; case DriverConfig.DatType.Byte: case DriverConfig.DatType.Word: if ((thisArea.DBnumber >= 3) && (thisArea.DBnumber <= 4)) { if (thisArea.DBnumber == 3) IntData[i].dInt = ModTCPObj.ReadHoldingRegisters(SAddress, thisArea.Amount); if (thisArea.DBnumber == 4) IntData[i].dInt = ModTCPObj.ReadInputRegisters(SAddress, thisArea.Amount); //Check read complete set of data if (IntData[i].dInt.Length == thisArea.Amount) retVar = true; } else {//Invalid Conf retVar = false; Status.NewStat(StatType.Warning, "Wrong FC for Read, Check Config."); } break; case DriverConfig.DatType.DWord: case DriverConfig.DatType.Real: if ((thisArea.DBnumber >= 3) && (thisArea.DBnumber <= 4)) { if (thisArea.DBnumber == 3) IntData[i].dInt = ModTCPObj.ReadHoldingRegisters(SAddress, (2 * thisArea.Amount)); if (thisArea.DBnumber == 4) IntData[i].dInt = ModTCPObj.ReadInputRegisters(SAddress, (2 * thisArea.Amount)); if (IntData[i].dInt.Length == (2 * thisArea.Amount)) retVar = true; } else {//Invalid Conf retVar = false; Status.NewStat(StatType.Warning, "Wrong FC for Read, Check Config."); } break; default: Status.NewStat(StatType.Warning, "Wrong DataArea Type, Check Config."); retVar = false; break; } } catch (Exception e) { Status.NewStat(StatType.Bad, e.Message); return false; } //Copy data to the Data Out if (retVar) { jj = 0; //Index reinitialize for (j = 0; j < thisArea.Amount; j++) { switch (thisArea.dataType) { case DriverConfig.DatType.Bool: if ((thisArea.DBnumber >= 1) && (thisArea.DBnumber <= 2)) { DataOut[i].Data.dBoolean[j] = IntData[i].dBool[j]; } else if ((thisArea.DBnumber >= 3) && (thisArea.DBnumber <= 4)) { boolReg = Math.DivRem(j, 16, out boolBit); var b = new BitArray(new int[] { IntData[i].dInt[boolReg] }); ; DataOut[i].Data.dBoolean[j] = b[boolBit]; } break; case DriverConfig.DatType.Byte: DataOut[i].Data.dByte[j] = (byte)(IntData[i].dInt[j] & MaskByte); break; case DriverConfig.DatType.Word: DataOut[i].Data.dWord[j] = (ushort)(IntData[i].dInt[j] & MaskWord); break; case DriverConfig.DatType.DWord: case DriverConfig.DatType.Real: //Endianess of the double word. if (RegOrder == ModbusClient.RegisterOrder.HighLow) { highWord = ((uint)IntData[i].dInt[jj] & MaskWord) << 16; lowWord = ((uint)IntData[i].dInt[(jj + 1)] & MaskWord); } else { highWord = ((uint)IntData[i].dInt[jj] & MaskWord); lowWord = ((uint)IntData[i].dInt[(jj + 1)] & MaskWord) << 16; } //Store the value in the DataOut. if (thisArea.dataType == DriverConfig.DatType.DWord) { DataOut[i].Data.dDWord[j] = (highWord | lowWord); } else { //Float point decimal. DataOut[i].Data.dReal[j] = (highWord | lowWord) / ((float)1000.0); } jj = jj + 2; break; default: Status.NewStat(StatType.Warning, "Wrong DataArea Type, Check Config."); break; } } // For j DataOut[i].NowTimeTicks = DateTime.UtcNow.Ticks; } else { Status.NewStat(StatType.Warning, "ModBus Read error.."); DataOut[i].NowTimeTicks = 0; } //if retVar == 0. Was reading ok? }// Area Enable } //For cicle Data Areas. return retVar; } // End Read Function
//获取输入状态 private void GetInputStatus(object sender, System.EventArgs e) { if (LayupPLC.ConnectionMethod == "ModbusTCP") { bool[] Result; Result = ModbusClient1.ReadDiscreteInputs(0000, 24); _layupPLC.Input000 = BoolToIntFunc(Result[0]); _layupPLC.Input001 = BoolToIntFunc(Result[1]); _layupPLC.Input002 = BoolToIntFunc(Result[2]); _layupPLC.Input003 = BoolToIntFunc(Result[3]); _layupPLC.Input004 = BoolToIntFunc(Result[4]); _layupPLC.Input005 = BoolToIntFunc(Result[5]); _layupPLC.Input006 = BoolToIntFunc(Result[6]); _layupPLC.Input007 = BoolToIntFunc(Result[7]); _layupPLC.Input010 = BoolToIntFunc(Result[8]); _layupPLC.Input011 = BoolToIntFunc(Result[9]); _layupPLC.Input012 = BoolToIntFunc(Result[10]); _layupPLC.Input013 = BoolToIntFunc(Result[11]); _layupPLC.Input014 = BoolToIntFunc(Result[12]); _layupPLC.Input015 = BoolToIntFunc(Result[13]); _layupPLC.Input016 = BoolToIntFunc(Result[14]); _layupPLC.Input017 = BoolToIntFunc(Result[15]); _layupPLC.Input020 = BoolToIntFunc(Result[16]); _layupPLC.Input021 = BoolToIntFunc(Result[17]); _layupPLC.Input022 = BoolToIntFunc(Result[18]); _layupPLC.Input023 = BoolToIntFunc(Result[19]); _layupPLC.Input024 = BoolToIntFunc(Result[20]); _layupPLC.Input025 = BoolToIntFunc(Result[21]); _layupPLC.Input026 = BoolToIntFunc(Result[22]); _layupPLC.Input027 = BoolToIntFunc(Result[23]); } else { int[] a = new int[2]; int b = _frmPLC.axActUtlType1.ReadDeviceBlock("X000", 2, out a[0]); string str = Convert.ToString(a[0], 2).PadLeft(16, '0'); int[] array1 = new int[16]; int[] array2 = new int[16]; for (int i = 0; i < 16; i++) { array1[i] = int.Parse(str.Substring(i, 1)); } str = Convert.ToString(a[1], 2).PadLeft(16, '0'); for (int i = 0; i < 16; i++) { array2[i] = int.Parse(str.Substring(i, 1)); } _layupPLC.Input000 = array1[15]; _layupPLC.Input001 = array1[14]; _layupPLC.Input002 = array1[13]; _layupPLC.Input003 = array1[12]; _layupPLC.Input004 = array1[11]; _layupPLC.Input005 = array1[10]; _layupPLC.Input006 = array1[9]; _layupPLC.Input007 = array1[8]; _layupPLC.Input010 = array1[7]; _layupPLC.Input011 = array1[6]; _layupPLC.Input012 = array1[5]; _layupPLC.Input013 = array1[4]; _layupPLC.Input014 = array1[3]; _layupPLC.Input015 = array1[2]; _layupPLC.Input016 = array1[1]; _layupPLC.Input017 = array1[0]; _layupPLC.Input020 = array2[15]; _layupPLC.Input021 = array2[14]; _layupPLC.Input022 = array2[13]; _layupPLC.Input023 = array2[12]; _layupPLC.Input024 = array2[11]; _layupPLC.Input025 = array2[10]; _layupPLC.Input026 = array2[9]; _layupPLC.Input027 = array2[8]; // _layupPLC.Input004 = array1[0]; //Console.WriteLine(str); // BitConverter } }
private async Task ExecuteDiscreteReadCommand(ModbusFunctionCode functionCode, ushort startAddress, ushort quantity) { string verboseMessage = $"{baseLogString} entering ExecuteDiscreteReadCommand method, command's functionCode: {functionCode}, startAddress: {startAddress}, quantity:{quantity}."; Logger.LogVerbose(verboseMessage); bool[] data; PointType pointType; if (functionCode == ModbusFunctionCode.READ_COILS) { verboseMessage = $"{baseLogString} ExecuteDiscreteReadCommand => about to call ModbusClient.ReadCoils({startAddress - 1}, {quantity}) method."; Logger.LogVerbose(verboseMessage); //KEY LOGIC pointType = PointType.DIGITAL_OUTPUT; data = modbusClient.ReadCoils(startAddress - 1, quantity); verboseMessage = $"{baseLogString} ExecuteDiscreteReadCommand => ModbusClient.ReadCoils({startAddress - 1}, {quantity}) method SUCCESSFULLY executed. Resulting data count: {data.Length}."; Logger.LogVerbose(verboseMessage); } else if (functionCode == ModbusFunctionCode.READ_DISCRETE_INPUTS) { verboseMessage = $"{baseLogString} ExecuteDiscreteReadCommand => about to call ModbusClient.ReadDiscreteInputs({startAddress - 1}, {quantity}) method."; Logger.LogVerbose(verboseMessage); //KEY LOGIC pointType = PointType.DIGITAL_INPUT; data = modbusClient.ReadDiscreteInputs(startAddress - 1, quantity); verboseMessage = $"{baseLogString} ExecuteDiscreteReadCommand => ModbusClient.ReadDiscreteInputs({startAddress - 1}, {quantity}) method SUCCESSFULLY executed. Resulting data count: {data.Length}."; Logger.LogVerbose(verboseMessage); } else { string errorMessage = $"{baseLogString} ExecuteDiscreteReadCommand => function code is neither ModbusFunctionCode.READ_COILS nor ModbusFunctionCode.READ_DISCRETE_INPUTS"; Logger.LogError(errorMessage); throw new ArgumentException(errorMessage); } //this.discreteMeasurementCache = new Dictionary<long, DiscreteModbusData>(data.Length); this.discreteMeasurementCache.Clear(); var modelReadAccessClient = ScadaModelReadAccessClient.CreateClient(); var modelUpdateAccessClient = ScadaModelUpdateAccessClient.CreateClient(); var currentSCADAModel = await modelReadAccessClient.GetGidToPointItemMap(); var currentAddressToGidMap = await modelReadAccessClient.GetAddressToGidMap(); var commandValuesCache = await modelReadAccessClient.GetCommandDescriptionCache(); for (ushort i = 0; i < data.Length; i++) { ushort address = (ushort)(startAddress + i); ushort value = (ushort)(data[i] ? 1 : 0); if (!currentAddressToGidMap.ContainsKey((short)pointType)) { Logger.LogWarning($"{baseLogString} ExecuteDiscreteReadCommand => Point type: {pointType} is not in the current addressToGidMap."); continue; } //for commands enqueued during model update, that are not valid if (!currentAddressToGidMap[(short)pointType].ContainsKey(address)) { Logger.LogWarning($"{baseLogString} ExecuteDiscreteReadCommand => trying to read value on address {address}, Point type: {pointType}, which is not in the current SCADA Model."); continue; } long gid = currentAddressToGidMap[(short)pointType][address]; //for commands enqueued during model update, that are not valid if (!currentSCADAModel.ContainsKey(gid)) { Logger.LogWarning($"{baseLogString} ExecuteDiscreteReadCommand => trying to read value for measurement with gid: 0x{gid:X16}, which is not in the current SCADA Model."); continue; } if (!(currentSCADAModel[gid] is IDiscretePointItem pointItem)) { string message = $"{baseLogString} ExecuteDiscreteReadCommand => PointItem [Gid: 0x{gid:X16}] does not implement {typeof(IDiscretePointItem)}."; Logger.LogError(message); throw new InternalSCADAServiceException(message); } //KEY LOGIC if (pointItem.CurrentValue != value) { pointItem = (IDiscretePointItem)(await modelUpdateAccessClient.UpdatePointItemRawValue(pointItem.Gid, value)); Logger.LogInformation($"{baseLogString} ExecuteDiscreteReadCommand => Alarm for Point [Gid: 0x{pointItem.Gid:X16}, Address: {pointItem.Address}] set to {pointItem.Alarm}."); } //LOGIC CommandOriginType commandOrigin = CommandOriginType.UNKNOWN_ORIGIN; if (commandValuesCache.ContainsKey(gid) && commandValuesCache[gid].Value == value) { commandOrigin = commandValuesCache[gid].CommandOrigin; await modelUpdateAccessClient.RemoveCommandDescription(gid); Logger.LogDebug($"{baseLogString} ExecuteDiscreteReadCommand => Command origin of command address: {pointItem.Address} is set to {commandOrigin}."); //LOGIC DiscreteModbusData digitalData = new DiscreteModbusData(value, pointItem.Alarm, gid, commandOrigin); this.discreteMeasurementCache.Add(gid, digitalData); verboseMessage = $"{baseLogString} ExecuteDiscreteReadCommand => DiscreteModbusData added to measurementCache. MeasurementGid: {digitalData.MeasurementGid:X16}, Value: {digitalData.Value}, Alarm: {digitalData.Alarm}, CommandOrigin: {digitalData.CommandOrigin} ."; Logger.LogVerbose(verboseMessage); } } //LOGIC await modelUpdateAccessClient.MakeDiscreteEntryToMeasurementCache(this.discreteMeasurementCache, true); verboseMessage = $"{baseLogString} ExecuteDiscreteReadCommand => MakeDiscreteEntryToMeasurementCache method called. measurementCache count: {this.discreteMeasurementCache.Count}."; Logger.LogVerbose(verboseMessage); }