Hello Friends,
I have created win form application which will read data from TCP and com port from Hardware using modbus and display information on different viewer screen.
For that I have done following code and its seems I am missing something to manage thread properly.
When my viewer screen will be get open that time I have initialing all ports and opening required ports if not open with as below code.
- public void InitializeReadingAllInouts()
- {
- string query = "select * from portinformation";
- SQLLiteHelper sql = new SQLLiteHelper();
- DataTable dt = sql.GetDataTable(query);
- if (dt.Rows.Count > 0)
- {
- for (int i = 0; i < dt.Rows.Count; i++)
- {
- inputsList.Add(new InputsDetails { InputsID = currentValuename, LastReadingValue = 0 });
- ManageHarwareRW.GetInputsDetails(currentValuename, ManageHarwareRW.input_or_output.input);
-
- }
- }
- }
-
-
- public void StartInputsReading()
- {
- foreach (InputsDetails item in inputsList)
- {
- Thread reading = new System.Threading.Thread(() =>
- {
- ReadInputsFromHardware(item.InputsID);
- });
- reading.IsBackground = true;
- reading.Start();
- }
- }
-
-
- private void ReadInputsFromHardware(int inputId)
- {
- float lastReadingValue = 0;
- InputTypeInformation inputTypeInformation = ManageHarwareRW.GetInputInformation(inputId);
- if (inputTypeInformation == null)
- {
- return;
- }
- ushort quantity = 2;
- Int16[] holdingRegisters = new Int16[2];
- ushort tcpQuantity = (ushort)inputTypeInformation.Quantity;
- int decimaplPoints = inputTypeInformation.DecimalPlacesRound;
- while (true)
- {
- if (GetInputDetails(inputId) == null)
- {
- return;
- }
- string currentStatus = "";
- if (inputTypeInformation.ConnectionType == EnumConfiguration.HardwareconnectionType.COM)
- {
- lastReadingValue = ReadHarwareHoldingRegister(inputTypeInformation.SerialPortConfiguration, false, 1, inputTypeInformation.Address, quantity, lastReadingValue, "", "", ref currentStatus);
- }
- else if (inputTypeInformation.ConnectionType == EnumConfiguration.HardwareconnectionType.TCP)
- {
- lastReadingValue = ReadFromTCP(inputTypeInformation.TCPPortConfiguration, inputTypeInformation.UnitID, inputTypeInformation.Address, tcpQuantity, holdingRegisters, lastReadingValue, ref currentStatus);
- }
- lastReadingValue = (float)Math.Round((double)lastReadingValue, decimaplPoints);
- SetInputsValues(inputId, lastReadingValue, inputTypeInformation.InputName, inputTypeInformation.Measuretype, currentStatus);
- Thread.Sleep(inputTypeInformation.RefreshIntervalTime);
- }
- }
-
- private float ReadHarwareHoldingRegister(SerialPortConfiguration serialPortConfiguration, bool isWrite, byte slaveId, ushort startAddress, ushort numRegisters, float lastValue, string target, string writevalue, ref string currentStatus)
- {
- float resultData = lastValue;
-
-
- mutex.WaitOne();
- try
- {
- if (isWrite)
- {
- try
- {
- if (target.ToLower() == "coil".ToLower())
- {
- bool isTrue = false;
- if (writevalue.ToLower() == "True".ToLower())
- isTrue = true;
- int val = 0;
- if (int.TryParse(writevalue, out val))
- isTrue = val == 1 ? true : false;
- serialPortConfiguration.Master.WriteSingleCoil(slaveId, startAddress, isTrue);
- }
- else if (target.ToLower() == "register".ToLower())
- {
- serialPortConfiguration.Master.WriteSingleRegister(1, startAddress, ushort.Parse(writevalue));
- }
- }
- catch (Exception ex)
- {
- }
- finally
- {
-
- }
- }
- else
- {
- ushort[] registers = serialPortConfiguration.Master.ReadHoldingRegisters(slaveId, startAddress, numRegisters);
-
- ushort[] data = new ushort[2] { registers[1], registers[0] };
- float[] floatdata = new float[data.Length / 2];
- Buffer.BlockCopy(data, 0, floatdata, 0, data.Length * 2);
- for (int index = 0; index < floatdata.Length; index++)
- {
- resultData = (floatdata[index / 2]);
- }
- }
- }
- catch (Exception ex)
- {
-
- }
- finally
- {
- mutex.ReleaseMutex();
- }
-
- return resultData;
- }
-
-
-
- Each viewer has thread which are getting call as below
- void work()
- {
- while (true)
- {
- List currentInputs = ManageInputsReading.InputsList();
- for (int i = 0; i < dt.Rows.Count; i++)
- {
- int currentValuename = int.Parse(dt.Rows[i]["id_valuename"].ToString());
- InputsDetails inputs = currentInputs.Where(q => q.InputsID == currentValuename).FirstOrDefault();
- if (inputs != null)
- {
- if (!this.IsDisposed)
- Invoke((MethodInvoker)delegate
- {
- textboxes.Text = inputs.LastReadingValue
- }
- );
- }
- }
- if (currentInputs.Count > 0)
- {
- m_latchandoutput.postprocess(inputs.LastReadingValue));
- }
- Thread.Sleep(refresh.refreshinterval);
- }
- }
-
- public void postprocess(double valuescalculated)
- {
-
- try
- {
- int outputId = 123;
- InputTypeInformation inputTypeInformation = ManageHarwareRW.GetOutputInformation(outputId);
- if (inputTypeInformation == null)
- {
- ManageHarwareRW.GetInputsDetails(objConditionValue.commandID, ManageHarwareRW.input_or_output.output);
- inputTypeInformation = ManageHarwareRW.GetOutputInformation(objConditionValue.commandID);
- }
- if (inputTypeInformation == null)
- {
- continue;
- }
-
- ManageInputsReading manageInputsReading = new ManageInputsReading();
- if (inputTypeInformation.ConnectionType == EnumConfiguration.HardwareconnectionType.COM)
- {
-
- manageInputsReading.WriteToComHardware(inputTypeInformation.SerialPortConfiguration, inputTypeInformation.Target, inputTypeInformation.UnitID, inputTypeInformation.Address, objConditionValue.resultValue);
- }
-
- else if (inputTypeInformation.ConnectionType == EnumConfiguration.HardwareconnectionType.TCP)
- {
- manageInputsReading.WriteToTCPHardware(inputTypeInformation.TCPPortConfiguration, inputTypeInformation.Target, inputTypeInformation.UnitID, inputTypeInformation.Address, objConditionValue.resultValue);
- }
- }
- catch (Exception exp)
- {
-
- }
- }
-
- public void WriteToComHardware(SerialPortConfiguration serialPortConfiguration, string target, byte slaveId, ushort startAddress, string writevalue)
- {
- string currentStatus = "";
- ReadHarwareHoldingRegister(serialPortConfiguration, true, slaveId, startAddress, 0, 0, target, writevalue, ref currentStatus);
- }
As in code I have added my comments. When I am trying to call WriteToComHarware Reading to hardware method getting stop working due to port has been closed and no longer enables the code to produce a read=
I think something wrong with Threading and Static List I have taken for this.
Please anyone can look into code and suggest me what's the wrong or please suggest me the alternate solution to manage this reading and writing from different thread.
Thanks in advance for your help.