private void MyThread() { int counter = 0; int MaxVal = 0; ResponseCnt = 1; int compaire = -1; // table.Clear(); List <cls_1> outputs = new List <cls_1>(); lblStatus1.Invoke((Action)(() => lblStatus1.Text = "Searching..")); MaxVal = stopBitsList.Count * bitLengthList.Count * parityList.Count * baudRateList.Count * addressList.Count * protocolList.Count; //MessageBox.Show("MaxVal: " + MaxVal); progressBar1.Invoke((Action)(() => progressBar1.Maximum = MaxVal)); try { if (_thread != null) { if (_thread.IsAlive) { foreach (string address in addressList) { foreach (string baudRate in baudRateList) { foreach (string parity in parityList) { foreach (string bitsLength in bitLengthList) { foreach (string stopBits in stopBitsList) { foreach (string protocol in protocolList) { //if (modbusRTUobj.IsSerialPortOpen()) //{ // modbusRTUobj.CloseSerialPort(); //} Thread.Sleep(150); obj.Comport = SetValues.Set_PortName; obj.Baudrate = baudRate; obj.Parity = parity; obj.Stopbits = stopBits; obj.Bitslength = bitsLength; obj.Protocol = protocol; string UntAddrs1 = Convert.ToInt32(address, 16).ToString(); string UntAddrs = UntAddrs1.Length < 2 ? UntAddrs1.PadLeft(2, '0') : UntAddrs1; string strParams = string.Format("{0},{1},{2},{3},{4},{5}H,{6}", obj.Comport, obj.Baudrate, obj.Parity, obj.Bitslength, obj.Stopbits, Convert.ToInt32(UntAddrs).ToString("X").PadLeft(2, '0'), obj.Protocol); if (!(obj.Baudrate == "2400")) { if (modbusRTUobj != null) { //if (modbusRTUobj.IsSerialPortOpen() == false) { if (modbusRTUobj.OpenSerialPort(obj.Comport, Convert.ToInt32(obj.Baudrate), obj.Parity, Convert.ToInt32(obj.Stopbits), Convert.ToInt32(obj.Bitslength), 100)) { //MessageBox.Show("port opened"); } } string result = string.Empty; if (modbusRTUobj.IsSerialPortOpen()) { lblFrame.Invoke((Action)(() => lblFrame.Text = strParams)); progressBar1.Invoke((Action)(() => progressBar1.Value = counter++)); byte[] RecieveData = null; //Send System.Threading.Thread.Sleep(1500); if (obj.Protocol.Equals("ASCII")) { RecieveData = modbusRTUobj.AscFrame( Convert.ToInt32(UntAddrs).ToString("X").PadLeft(2, '0'), "03", "4701", "0001"); try { if (RecieveData != null && RecieveData.Length > 0) { char[] recdata = System.Text.Encoding.UTF8.GetString(RecieveData).ToCharArray(); result = string.Join("", recdata); if (!string.IsNullOrEmpty(result)) { if (RecieveData.Length > 10 && result.Contains("0302") && result.StartsWith(":")) { dataGridView1.Invoke((Action)(() => { dataGridView1.Rows.Add( string.Format("{0}H", Convert.ToInt32(UntAddrs).ToString("X").PadLeft(2, '0') ), string.Format("{0},{1},{2},{3},{4},{5}", comName, obj.Baudrate, obj.Bitslength, parity, obj.Stopbits, obj.Protocol ) ); }) ); ResponseCnt++; } } } } catch (Exception ae) { } } else if (obj.Protocol.Equals("RTU")) { RecieveData = modbusRTUobj.RtuFrame(UntAddrs, "03" , "4701", "0001", baudRate); try { if (RecieveData != null && RecieveData.Length > 0) { result = modbusRTUobj.DisplayFrame(RecieveData); if (!string.IsNullOrEmpty(result)) { //if (RecieveData.Length > 5 && result.StartsWith(":")) //&& result.Contains("0302") { dataGridView1.Invoke((Action)(() => { dataGridView1.Rows.Add( string.Format("{0}H", Convert.ToInt32(UntAddrs).ToString("X").PadLeft(2, '0') ), string.Format("{0},{1},{2},{3},{4},{5}", comName, obj.Baudrate, obj.Bitslength, parity, obj.Stopbits, obj.Protocol ) ); }) ); ResponseCnt++; } } } } catch (Exception ae) { } } } } } } } } } } } progressBar1.Invoke((Action)(() => progressBar1.Value = MaxVal)); lblFrame.Invoke((Action)(() => lblFrame.Text = "")); lblStatus1.Invoke((Action)(() => lblStatus1.Text = "Search Completed")); this.BeginInvoke((System.Windows.Forms.MethodInvoker) delegate() { ControlBox = true; }); btnClose.Invoke((Action)(() => btnClose.Text = "Close")); } } } catch (Exception ex) { LogWriter.WriteToFile("AutoDetectsettings: ", ex.StackTrace, "DTC_ErrorLog"); } }
void worker_DoWork(object sender, DoWorkEventArgs e) { int i = 1; object userState = ""; bool isRun = true; do { string portName = SetValues.Set_PortName; string baudRate = SetValues.Set_Baudrate; string parity = SetValues.Set_parity; int bitsLength = SetValues.Set_BitsLength; string stopBits = SetValues.Set_StopBits; try { if (modbusobj.OpenSerialPort(portName, Convert.ToInt32(baudRate), parity, Convert.ToInt32(stopBits), bitsLength)) { byte[] RecieveData = null; if (!string.IsNullOrEmpty(SetValues.Set_CommunicationProtocol)) { if (SetValues.Set_CommunicationProtocol.ToLower() == "ascii" || SetValues.Set_CommunicationProtocolindex == 1) { RecieveData = modbusobj.AscFrame((Convert.ToInt32(SetValues.Set_UnitAddress, 16)).ToString(), SetValues.Set_CommandType, SetValues.Set_RegAddress, SetValues.Set_WordCount); if (RecieveData != null && RecieveData.Length > 0) { string result = modbusobj.DisplayFrame(RecieveData); char[] recdata = System.Text.Encoding.UTF8.GetString(RecieveData).ToCharArray(); if (recdata != null) { userState = recdata; txtBxRecievecmd.Invoke((Action)(() => txtBxRecievecmd.Text = string.Join("", userState))); worker.ReportProgress(i, userState); } if (worker.CancellationPending) { e.Cancel = true; worker.ReportProgress(0); //return; isRun = false; } i++; } else { txtBxRecievecmd.Invoke((Action)(() => txtBxRecievecmd.Text = "Received time-out")); } } else if (SetValues.Set_CommunicationProtocol.ToLower() == "rtu" || SetValues.Set_CommunicationProtocolindex == 2) { RecieveData = modbusobj.RtuFrame(SetValues.Set_UnitAddress, SetValues.Set_CommandType, SetValues.Set_RegAddress, SetValues.Set_WordCount, SetValues.Set_Baudrate); if (RecieveData != null && RecieveData.Length > 0) { string result = modbusobj.DisplayFrame(RecieveData); if (!string.IsNullOrEmpty(result)) { userState = result; txtBxRecievecmd.Invoke((Action)(() => txtBxRecievecmd.Text = result)); worker.ReportProgress(i, userState); } if (worker.CancellationPending) { e.Cancel = true; worker.ReportProgress(0); //return; isRun = false; } i++; } else { txtBxRecievecmd.Invoke((Action)(() => txtBxRecievecmd.Text = "Received time-out")); } } } } } catch (Exception ex) { // lblMessage.Invoke((Action)(() => lblMessage.Text = ex.Message)); // MessageBox.Show("Exception worker: " + ex.StackTrace); } finally { if (modbusobj != null) { modbusobj.CloseSerialPort(); } } } while (isRun); }
private string SendFrameToDevice1(string node) { string portName = SetValues.Set_PortName; string baudRate = SetValues.Set_Baudrate; string parity = SetValues.Set_parity; int bitsLength = SetValues.Set_BitsLength; string stopBits = SetValues.Set_StopBits; if (!string.IsNullOrEmpty(portName) && !string.IsNullOrEmpty(baudRate) && !string.IsNullOrEmpty(parity) && bitsLength > 0 && !string.IsNullOrEmpty(stopBits)) { try { if (modbusobj.OpenSerialPort(portName, Convert.ToInt32(baudRate), parity, Convert.ToInt32(stopBits), bitsLength)) { byte[] RecieveData = null; string result = ""; if (!string.IsNullOrEmpty(SetValues.Set_CommunicationProtocol)) { if ((SetValues.Set_CommunicationProtocol.ToLower() == "ascii" || SetValues.Set_CommunicationProtocolindex == 1) && SetValues.Set_CommType == 1) { RecieveData = modbusobj.AscFrame(node, "03", "470B", "0001"); } else if (SetValues.Set_CommunicationProtocol.ToLower() == "rtu" || SetValues.Set_CommunicationProtocolindex == 2) { RecieveData = modbusobj.RtuFrame(node, "03", "470B", "0001", SetValues.Set_Baudrate); } if (RecieveData != null && RecieveData.Length > 0) { char[] recdata = System.Text.Encoding.UTF8.GetString(RecieveData).ToCharArray(); if ((SetValues.Set_CommunicationProtocol.ToLower() == "ascii" || SetValues.Set_CommunicationProtocolindex == 1) && SetValues.Set_CommType == 1) { result = string.Join("", recdata); // MessageBox.Show(result); } else if (SetValues.Set_CommunicationProtocol.ToLower() == "rtu" || SetValues.Set_CommunicationProtocolindex == 2) { result = modbusobj.DisplayFrame(RecieveData); // MessageBox.Show(result); } //txtBxRecievecmd.Text = result; double int64Val = 0; // returnVal.Text = int64Val.ToString(); return(result); } else { // data not received // txtBxRecievecmd.Text = "Received Data Timeout!"; return(result); } } else { // txtBxRecievecmd.Text = "Received Data Timeout!"; } } else { //txtBxRecievecmd.Text = "Connection failed"; return(""); } } catch (Exception ex) { MessageBox.Show(ex.StackTrace); //LogWriter.WriteToFile("ModbusRTU: 5)", ex.Message, "DTC_ErrorLog"); //lblMessage.Text = "3" + ex.Message; return(""); } finally { if (modbusobj.IsSerialPortOpen()) { modbusobj.CloseSerialPort(); } } } else { // settings are empty } return(""); }
private void Write16AddrsForSamePropertiesForAllAddresses() { //byte[] GetASKdata = null; try { stringHex = "00"; for (int j = 1; j <= 256; j++) { int intFromHex = int.Parse(stringHex, System.Globalization.NumberStyles.HexNumber) + 1; string UntAddrs = intFromHex.ToString("X"); stringHex = UntAddrs; if (UntAddrs.Length == 1) { UntAddrs = "0" + UntAddrs; } SetValues.Set_UnitAddress = UntAddrs; SetValues.Set_CommandType = "03"; // "03"; SetValues.Set_RegAddress = "1000"; // "4701"; SetValues.Set_WordCount = "0001"; byte[] RecieveData = null; int ii = 0; if (!string.IsNullOrEmpty(SetValues.Set_CommunicationProtocol)) { if (SetValues.Set_CommunicationProtocol.ToLower() == "ascii") { var arr = modbusRTUobj.AscFrame(SetValues.Set_UnitAddress, SetValues.Set_CommandType, SetValues.Set_RegAddress, SetValues.Set_WordCount); string str = SetValues.Set_Baudrate + "," + SetValues.Set_BitsLength + "," + SetValues.Set_parity + "," + SetValues.Set_StopBits; lblStatus.Invoke((Action)(() => lblStatus.Text = str)); if (arr != null) { if (arr.Length > 0) { RecieveData = new byte[arr.Length]; RecieveData = arr; ii = 1; } } } else if (SetValues.Set_CommunicationProtocol.ToLower() == "rtu") { var arr = modbusRTUobj.RtuFrame(SetValues.Set_UnitAddress, SetValues.Set_CommandType, SetValues.Set_RegAddress, SetValues.Set_WordCount); if (arr != null) { if (arr.Length > 0) { RecieveData = new byte[arr.Length]; RecieveData = arr; ii = 2; } } } } if (RecieveData != null) { string result = modbusRTUobj.DisplayFrame(RecieveData); //modbusRTUobj.MakeAscFrameCombinations(SetValues.Set_UnitAddress, SetValues.Set_CommandType, // SetValues.Set_RegAddress, SetValues.Set_WordCount); //GetASKdata = modbusRTUobj.Read_AscDataRegisterCombinations(1); //if (GetASKdata != null) //{ // if (GetASKdata[0] != 0) // { if (!string.IsNullOrEmpty(result)) { table.Rows.Add(new Object[] { ResponseCnt , SetValues.Set_UnitAddress, SetValues.Set_Baudrate + "," + SetValues.Set_parity + "," + SetValues.Set_StopBits + "," + SetValues.Set_BitsLength + "," + ii }); dataGridView1.DataSource = null; dataGridView1.DataSource = table; dataGridView1.Columns[0].Width = 50; dataGridView1.Columns[2].Width = 120; ResponseCnt++; } // } //} } } } catch (Exception ex) { MessageBox.Show("3" + ex.Message); } }
private double SendFrameToDevice1(string unitAddress) { string portName = SetValues.Set_PortName; string baudRate = SetValues.Set_Baudrate; string parity = SetValues.Set_parity; int bitsLength = SetValues.Set_BitsLength; string stopBits = SetValues.Set_StopBits; if (!string.IsNullOrEmpty(portName) && !string.IsNullOrEmpty(baudRate) && !string.IsNullOrEmpty(parity) && bitsLength > 0 && !string.IsNullOrEmpty(stopBits)) { try { if (modbusobj.IsSerialPortOpen()) { modbusobj.CloseSerialPort(); } if (modbusobj.OpenSerialPort(portName, Convert.ToInt32(baudRate), parity, Convert.ToInt32(stopBits), bitsLength)) { byte[] RecieveData = null; if (!string.IsNullOrEmpty(SetValues.Set_CommunicationProtocol)) { if (SetValues.Set_CommunicationProtocol.ToLower() == "ascii") { RecieveData = modbusobj.AscFrame(unitAddress.PadLeft(2, '0'), "03", "4700", "0002"); } else if (SetValues.Set_CommunicationProtocol.ToLower() == "rtu") { RecieveData = modbusobj.RtuFrame(unitAddress.PadLeft(2, '0'), "03", "4700", "0001"); } if (RecieveData != null && RecieveData.Length > 0) { char[] recdata = System.Text.Encoding.UTF8.GetString(RecieveData).ToCharArray(); byte[] sizeBytes = null; string result = ""; int size = 0; int value = 0; if (SetValues.Set_CommunicationProtocol.ToLower() == "ascii") { result = string.Join("", recdata); sizeBytes = ExtractByteArray(RecieveData, 4, 7); value = Convert.ToInt32(System.Text.Encoding.UTF8.GetString(sizeBytes), 16); } else if (SetValues.Set_CommunicationProtocol.ToLower() == "rtu") { result = modbusobj.DisplayFrame(RecieveData); sizeBytes = ExtractByteArray(RecieveData, 2, 3); short val1 = Convert.ToInt16(string.Join("", sizeBytes), 16); value = val1; } LogWriter.WriteToFile("GraphRecoder: 5)", result, "GraphRecoder_ErrorLog"); //sizeBytes = ExtractByteArray(RecieveData, 4, 7); //int value = Convert.ToInt32(System.Text.Encoding.UTF8.GetString(sizeBytes), 16); return(Convert.ToDouble(value) / 10); //returnVal.Text = int64Val.ToString(); } else { // data not received LogWriter.WriteToFile("GraphRecoder: 4)", "Received Data Timeout!", "GraphRecoder_ErrorLog"); //txtBxRecievecmd.Text = "Received Data Timeout!"; return(-1); } } else { LogWriter.WriteToFile("GraphRecoder: 3)", "Received Data Timeout!", "GraphRecoder_ErrorLog"); //txtBxRecievecmd.Text = "Received Data Timeout!"; return(-1); } } else { LogWriter.WriteToFile("GraphRecoder: 2)", "Connection failed", "GraphRecoder_ErrorLog"); //txtBxRecievecmd.Text = "Connection failed"; return(-1); } } catch (Exception ex) { LogWriter.WriteToFile("GraphRecoder: 1)", ex.Message, "GraphRecoder_ErrorLog"); //lblMessage.Text = "3" + ex.Message; return(-1); } } else { // settings are empty return(-1); } }
private int CreateFrames(string nodeAddress, string functionCode, string regAddress, string wordCount, bool read, string portNameN, int baudRateN, string parityN, int bitsLengthN, int stopBitsN) { byte[] RecieveData = null; try { //if (modObj != null) //{ // if (modObj.IsSerialPortOpen()) // { // modObj.CloseSerialPort(); // } //} //else //{ // modObj = new clsModbus(); // modObj._GetLRCResultResult += new clsModbus.GetLRCResult(singlecmdtxt); //} // if (!modObj.IsSerialPortOpen()) { #region Port Settings //string portNameN = SetValues.Set_PortName; //int baudRateN = Convert.ToInt32(SetValues.Set_Baudrate); //string parityN = SetValues.Set_parity; //int bitsLengthN = SetValues.Set_BitsLength; //int stopBitsN = Convert.ToInt32(SetValues.Set_StopBits); int readTimeOut = baudRateN == 2400 ? 1000 : 100; if (modObj.OpenSerialPort(portNameN, baudRateN, parityN, stopBitsN, bitsLengthN, readTimeOut)) { } else { lblMsg.Visible = true; lblMsg.Text = "Connection error."; } #endregion } // if (modObj.IsSerialPortOpen()) { if (!string.IsNullOrEmpty(SetValues.Set_CommunicationProtocol)) { if ((SetValues.Set_CommunicationProtocol.ToLower() == "ascii" || SetValues.Set_CommunicationProtocolindex == 1) && SetValues.Set_CommType == 1) //|| SetValues.Set_CommunicationProtocolindex == 1 { Thread.Sleep(700); RecieveData = modObj.AscFrame(nodeAddress, functionCode, regAddress, wordCount.PadLeft(4, '0')); if (baudRateN == 9600 && bitsLengthN == 8) { return(1); } if (RecieveData != null && RecieveData.Length > 0) { string funcCode = System.Text.Encoding.UTF8.GetString( ExtractByteArray(RecieveData, 2, 3)); // check if received function code is empty or not if (!string.IsNullOrEmpty(funcCode)) { // check if function code sent and received are same if (funcCode.Equals(functionCode) || (baudRateN == 9600 && bitsLengthN == 7)) { return(1); } } else { return(2); } } } else if (SetValues.Set_CommunicationProtocol.ToLower() == "rtu" || SetValues.Set_CommunicationProtocolindex == 2) //|| SetValues.Set_CommunicationProtocolindex == 2 { //need to optimize Thread.Sleep(700); RecieveData = modObj.RtuFrame(nodeAddress, functionCode, regAddress, wordCount.PadLeft(4, '0'), SetValues.Set_Baudrate); // Convert.ToInt32(nodeAddress).ToString("X").PadLeft(4, '0') if (RecieveData != null && RecieveData.Length > 0) { string funcCode = BitConverter.ToString(ExtractByteArray(RecieveData, 1, 1)).Replace("-", ""); string result = modObj.DisplayFrame(RecieveData); // MessageBox.Show(result); // check if received function code is empty or not if (!string.IsNullOrEmpty(funcCode)) { // check if function code sent and received are same if (funcCode.Equals(functionCode)) { return(1); } else { return(2); } } } } } } } catch (Exception) { return(3); } return(2); }