private void HandleError() { while (errorCode != 0) { switch (errorCode) { case 90: // part failed break; case 96: // max attempts reached, show dialog break; case 98: break; default: Console.WriteLine("UNKOWN ERROR"); break; } transactClient.DBRead(3100, 0, transactReadBuffer.Length, transactReadBuffer); errorCode = S7.GetByteAt(transactReadBuffer, 45); Thread.Sleep(50); } }
private void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { if (s7Client.Connected()) { byte[] buf = new byte[1]; int result = s7Client.DBRead(1, 0, 1, buf); if (result != 0) { toolStripStatusLabel1.Text = s7Client.ErrorText(result); return; } else { int flag = S7.GetByteAt(buf, 0); toolStripStatusLabel1.Text = flag.ToString(); } buf[0] = (byte)(buf[0] ^ 0x01); //S7.SetIntAt(buf, 0, 0x01); result = s7Client.DBWrite(1, 0, 1, buf); if (result != 0) { toolStripStatusLabel1.Text = s7Client.ErrorText(result); } } }
private void ReadTransactionDB() { while (isConnected) { transactClient.DBRead(3100, 0, transactReadBuffer.Length, transactReadBuffer); readTransactionID = S7.GetByteAt(transactReadBuffer, 45); S7.SetByteAt(transactWriteBuffer, 94, 1); transactClient.DBWrite(3101, 0, transactWriteBuffer.Length, transactWriteBuffer); if (readTransactionID == 0 && !handshakeCleared) { handshakeCleared = true; if (isConnected) { S7.SetByteAt(transactWriteBuffer, 45, 1); int result1 = transactClient.DBWrite(3101, 0, transactWriteBuffer.Length, transactWriteBuffer); Console.WriteLine("-------------------------" + "\nTransaction ID : 1" + "\nWrite Result : " + result1 + "\n-------------------------"); } } if ((readTransactionID != oldReadTransactionID) && handshakeCleared) { Console.WriteLine("Transaction ID IN : " + readTransactionID); oSignalTransactEvent.Set(); oldReadTransactionID = readTransactionID; } Thread.Sleep(50); } }
private bool ReadValue() { var client = _connection?.PlcClient; if (client == null) { return(false); } var buffer = new byte[Math.Max(64, _info.ByteCount + 2)]; var result = client.DBRead(_info.DbNumber, _info.Offset, _info.ByteCount, buffer); if (result != 0) { TronTrace.TraceError($"PlcItem.DBRead({_info.DbNumber}, {_info.Offset}) failed - {result} {PlcResult.GetResultText(result)}"); return(false); } switch (_info.PlcDataType) { case PlcDataTypes.X: _value = S7.GetBitAt(buffer, 0, _info.Bit) ? 1 : 0; break; case PlcDataTypes.B: _value = S7.GetByteAt(buffer, 0); break; case PlcDataTypes.INT: _value = S7.GetIntAt(buffer, 0); break; case PlcDataTypes.DINT: _value = S7.GetDIntAt(buffer, 0); break; case PlcDataTypes.DT: _value = S7.GetDateTimeAt(buffer, 0); break; case PlcDataTypes.STRING: _value = S7.GetStringAt(buffer, 0); break; } if (!_value.Equals(_oldValue)) { _oldValue = _value; ValueChanged?.Invoke(this); } return(true); }
public StructDB0 Lectura(int DbNumber, int offSetStart) { StructDB0 Result = new StructDB0(); byte[] readBuffer = new byte[21]; client.DBRead(DbNumber, offSetStart, readBuffer.Length, readBuffer);//Lectura de buffer //Extraer datos y meterlos en Struct Result.SerialNumber = S7.GetCharsAt(readBuffer, 0, 12); Result.TestResult = S7.GetIntAt(readBuffer, 12); Result.RealDetector = S7.GetRealAt(readBuffer, 14); Result.byte20 = S7.GetByteAt(readBuffer, 20); return(Result);// Devuelve un objeto del tipo StructDB0 }
/// <summary> /// extract value from raw buffer /// </summary> /// <param name="buffer"> buffer length must be greater than Offset.ByteOffset+4, else do nothing </param> public void GetValueFromGroupBuffer(byte[] buffer) { if (buffer.Length < Offset.ByteOffset + 4) { return; } switch (VType) { case varType.BOOL: Value = S7.GetBitAt(buffer, Offset.ByteOffset, Offset.BitOffset); break; case varType.BYTE: Value = S7.GetByteAt(buffer, Offset.ByteOffset); break; case varType.WORD: Value = S7.GetWordAt(buffer, Offset.ByteOffset); break; case varType.DWORD: Value = S7.GetDWordAt(buffer, Offset.ByteOffset); break; case varType.INT: Value = S7.GetIntAt(buffer, Offset.ByteOffset); break; case varType.DINT: Value = S7.GetDIntAt(buffer, Offset.ByteOffset); break; case varType.REAL: Value = S7.GetRealAt(buffer, Offset.ByteOffset); break; // Added String Read case varType.STRING: Value = S7.GetStringAt(buffer, Offset.ByteOffset); break; } }
private void ReadTransactionDB() { while (isConnected) { transactClient.DBRead(3100, 0, transactReadBuffer.Length, transactReadBuffer);//1110 readTransactionID = S7.GetByteAt(transactReadBuffer, 45); errorCode = S7.GetByteAt(transactReadBuffer, 45); //if (errorCode != 0) //{ // HandleError(); //} if (readTransactionID == 0 && !handshakeCleared) { handshakeCleared = true; if (isConnected) { S7.SetByteAt(transactWriteBuffer, 45, 1); S7.SetByteAt(transactWriteBuffer, 94, 60); // Send Equipment ID *** bolting tool //S7.SetByteAt(transactWriteBuffer, ?, TORQUE); // Send required torque of bolting tool (maybe not required) S7.SetByteAt(transactWriteBuffer, 44, (byte)maxNumAttempts); // Send MaxNumOfAttempts int result1 = transactClient.DBWrite(3101, 0, transactWriteBuffer.Length, transactWriteBuffer); Console.WriteLine("-------------------------" + "\nTransaction ID : 1" + "\nEquipment ID : " + equipmentID + "\nPLC Write Result : " + result1 + "\n-------------------------"); } } if ((readTransactionID != oldReadTransactionID) && handshakeCleared) { Console.WriteLine("Transaction ID IN : " + readTransactionID + "\n-------------------------"); oSignalTransactEvent.Set(); oldReadTransactionID = readTransactionID; } Thread.Sleep(50); } }
private int GetValueOfTypeFromPlc() { switch (ObjectConfigure.WorldLen) { case S7Consts.S7WLBit: return(Convert.ToInt32(S7.GetBitAt(BufferData, 0, 0))); case S7Consts.S7WLByte: case S7Consts.S7WLChar: return(Convert.ToInt32(S7.GetByteAt(BufferData, 0))); case S7Consts.S7WLWord: case S7Consts.S7WLInt: return(Convert.ToInt32(S7.GetIntAt(BufferData, 0))); case S7Consts.S7WLDWord: case S7Consts.S7WLReal: return(Convert.ToInt32(S7.GetRealAt(BufferData, 0))); default: return(0); } }
public void ReadAllValues() { client.DBRead(100, 0, readBuffer.Length, readBuffer);//1110 lineID = S7.GetStringAt(readBuffer, 0); identifier = S7.GetStringAt(readBuffer, 22); identifierCount = S7.GetByteAt(readBuffer, 44); // Number of entries in the database (Does not really need to read but write it to plc?) readTransactionID = S7.GetByteAt(readBuffer, 45); channelStatus = S7.GetByteAt(readBuffer, 46); stationStatus = S7.GetByteAt(readBuffer, 47); errorCode = S7.GetByteAt(readBuffer, 48); userName = S7.GetStringAt(readBuffer, 50); equipmentID = S7.GetByteAt(readBuffer, 94); productionData = S7.GetStringAt(readBuffer, 96); }
private void ReadPLC() { // Connect if disconnected if (!client.Connected) { client.Connect(); } //Do this for each DB in the configuration foreach (var db in configService.ActiveConfig.DBReads) { Byte[] buffer = new byte[db.DBLengthByte]; var ret = client.DBRead(db.DBNumber, db.DBOffsetByte, db.DBLengthByte, buffer); var errorText = client.ErrorText(ret); if (ret == 0) { Console.WriteLine($"Reading DB{db.DBNumber} success."); } else { Console.WriteLine($"Reading DB{db.DBNumber} failed, error {ret}:, {errorText}"); } //Parse the db into parts foreach (var tag in db.Tags) { switch (tag.Type) { case "Bool": tag.Data = S7.GetBitAt(buffer, tag.OffsetByte, tag.OffsetBit); break; case "Int8": tag.Data = S7.GetByteAt(buffer, tag.OffsetByte); break; case "Int16": tag.Data = S7.GetIntAt(buffer, tag.OffsetByte); break; case "Int32": tag.Data = S7.GetDIntAt(buffer, tag.OffsetByte); break; case "Int64": tag.Data = S7.GetLIntAt(buffer, tag.OffsetByte); break; case "Float": tag.Data = S7.GetRealAt(buffer, tag.OffsetByte); break; case "Double": tag.Data = S7.GetLRealAt(buffer, tag.OffsetByte); break; case "String": tag.Data = S7.GetCharsAt(buffer, tag.OffsetByte, tag.StringLength); break; default: Console.WriteLine($"Unknown type for tag {tag.Name}"); break; } } } }
[Fact] public void TestGetByteAt() { S7.GetByteAt(new byte[] { 1, 2, 3, 4 }, 1).ShouldBe((byte)2); }
/// <summary> /// ??? /// </summary> public static List <string> ReplaceCharByValues(byte[] buf, List <string> tab) { // ?? int offset = 0; int cntBool = 0; List <string> listTemp = new List <string>(); for (int i = 0; i < tab.Count; i++) { // For Bool if (tab[i] == "BOOL") { bool tempB; //int offsetB = 5; tempB = S7.GetBitAt(buf, offset, cntBool); listTemp.Add(tempB.ToString()); cntBool++; // Incrément compteur booléen if (cntBool == 8) { offset++; cntBool = 0; } } // For Byte if (tab[i] == "BYTE") { int tempB; tempB = S7.GetByteAt(buf, offset); listTemp.Add("B#16#" + "0"); cntBool = 0; offset = offset + 2; } // For Word if (tab[i] == "WORD") { int tempW; tempW = S7.GetWordAt(buf, offset); listTemp.Add("W#16#" + "0"); cntBool = 0; offset = offset + 2; } // For Int if (tab[i] == "INT") { int tempI; tempI = S7.GetIntAt(buf, offset); listTemp.Add(tempI.ToString()); cntBool = 0; offset = offset + 2; } // For DInt if (tab[i] == "DINT") { double tempDI; tempDI = S7.GetDIntAt(buf, offset); listTemp.Add(tempDI.ToString()); cntBool = 0; offset = offset + 4; } // For Real if (tab[i] == "REAL") { double tempR; float tempFR, test; tempR = S7.GetRealAt(buf, offset); tempFR = Convert.ToSingle(tempR); test = (float)(Math.Truncate((double)tempFR * 100.0) / 100.0); listTemp.Add(tempR.ToString("0.00")); cntBool = 0; offset = offset + 4; } } return(listTemp); }
// Thread to Process PLC Read Queue static void ProcessPLC(S7PLC plc) { do { try { System.Threading.Thread.Sleep(5000); S7Client client = new S7Client(); client.SetConnectionType(System.Convert.ToUInt16(plc.connection_type)); client.SetConnectionParams(plc.ip, System.Convert.ToUInt16(plc.local_tsap), System.Convert.ToUInt16(plc.remote_tsap)); Console.WriteLine("Try to connect " + plc.server_name); int res = client.Connect(); if (res != 0 || client.Connected == false) { continue; } Console.WriteLine("Connected " + plc.server_name + " IP:" + plc.ip); S7Client.S7CpuInfo Info = new S7Client.S7CpuInfo(); res = client.GetCpuInfo(ref Info); if (res == 0) { Console.WriteLine(plc.server_name + " Module Type Name : " + Info.ModuleTypeName); Console.WriteLine(plc.server_name + " Serial Number : " + Info.SerialNumber); Console.WriteLine(plc.server_name + " AS Name : " + Info.ASName); Console.WriteLine(plc.server_name + " Module Name : " + Info.ModuleName); } ; System.Threading.Thread.Sleep(1000); while (client.Connected) { foreach (S7RW read in plc.reads) { CheckCommand(client, plc); byte[] Buffer = new byte[1024]; int BytesRead = 0; res = client.ReadArea( System.Convert.ToInt32(read.data_area), System.Convert.ToInt32(read.db), System.Convert.ToInt32(read.offset), System.Convert.ToInt32(read.amount), System.Convert.ToInt32(StringToWordLengthCode(read.data_type)), Buffer, ref BytesRead); if (res == 0) { // HexDump(Buffer, BytesRead); for (int i = 0; i < read.amount; i++) { int bytecnt; double value = 0; switch (read.data_type) { case "BIT": bytecnt = i / 8; value = System.Convert.ToDouble(S7.GetBitAt(Buffer, bytecnt, i % 8)); break; case "BYTE": bytecnt = i; value = S7.GetByteAt(Buffer, bytecnt); break; case "CHAR": bytecnt = i; value = S7.GetByteAt(Buffer, bytecnt); break; case "WORD": bytecnt = i * 2; value = S7.GetWordAt(Buffer, bytecnt); break; case "DWORD": bytecnt = i * 4; value = S7.GetDWordAt(Buffer, bytecnt); break; case "INT": bytecnt = i * 2; value = S7.GetIntAt(Buffer, bytecnt); break; case "DINT": bytecnt = i * 4; value = S7.GetDIntAt(Buffer, bytecnt); break; case "REAL": bytecnt = i * 4; value = S7.GetRealAt(Buffer, bytecnt); break; case "COUNTER": bytecnt = i * 2; value = S7.GetCounter((ushort)((Buffer[bytecnt + 1] << 8) + (Buffer[bytecnt]))); break; case "TIMER": bytecnt = i * 2; value = (ushort)((Buffer[bytecnt + 1] << 8) + (Buffer[bytecnt])); break; default: Console.WriteLine("Unsupported data type: " + read.data_type); break; } SendUdp(Encoding.ASCII.GetBytes( "[{\"point_key\":" + (read.point_number + i) + ",\"value\":" + value + ",\"failed\":false" + "}]")); if (logread) { Console.WriteLine(plc.server_name + " " + read.name + " OSHMI_POINT_NUMBER=" + (read.point_number + i) + " VALUE=" + value + " " + read.data_type); } } } else { Console.WriteLine(plc.server_name + " Error " + read.name); } System.Threading.Thread.Sleep(System.Convert.ToInt32(read.delay_ms)); } } // client.Disconnect(); Console.WriteLine("Disconnected " + plc.server_name); } catch (Exception e) { // EXCEPTION HANDLER Console.WriteLine("Exception " + plc.server_name); Console.WriteLine(e); } System.Threading.Thread.Sleep(10000); } while (true); }
private void Handshake() { while (isConnected) { oSignalTransactEvent.WaitOne(); oSignalTransactEvent.Reset(); switch (readTransactionID) { case 2: StringBuilder sb = new StringBuilder(); sb.Append(S7.GetByteAt(transactReadBuffer, 352)) .Append(S7.GetByteAt(transactReadBuffer, 353)) .Append(S7.GetByteAt(transactReadBuffer, 354)) .Append(S7.GetByteAt(transactReadBuffer, 355)) .Append(S7.GetByteAt(transactReadBuffer, 356)) .Append(S7.GetByteAt(transactReadBuffer, 357)) .Append(S7.GetByteAt(transactReadBuffer, 358)) .Append(S7.GetByteAt(transactReadBuffer, 359)); palletID = Int64.Parse(sb.ToString()); this.Invoke((MethodInvoker) delegate { skid_txt.Text = sb.ToString(); }); using (SqlConnection conn = DBUtils.GetMainDBConnection()) { conn.Open(); dt = new DataTable(); SqlDataAdapter da = new SqlDataAdapter("SELECT [Pallet Number] FROM Pallets WHERE [Pallet ID] = '" + palletID + "'", conn); da.Fill(dt); } if (dt.Rows.Count > 0) { foreach (DataRow row in dt.Rows) { palletNum = Int32.Parse(row["Pallet Number"].ToString()); UpdateUISkidID(); } S7.SetByteAt(transactWriteBuffer, 45, 99); S7.SetStringAt(transactWriteBuffer, 96, 200, ((short)palletNum).ToString()); int result1 = transactClient.DBWrite(3101, 0, transactWriteBuffer.Length, transactWriteBuffer); Console.WriteLine("-------------------------" + "\nTransaction ID OUT : 99" + "\nPallet ID : " + palletID + "\nResult : Found pallet in database" + "\nPLC Write Result : " + result1 + "\n-------------------------"); } else { S7.SetByteAt(transactWriteBuffer, 45, 3); S7.SetByteAt(transactWriteBuffer, 48, 99); int result2 = transactClient.DBWrite(3101, 0, transactWriteBuffer.Length, transactWriteBuffer); Console.WriteLine("-------------------------" + "\nTransaction ID OUT : 3" + "\nPallet ID : " + palletID + "\nResult : Did not find pallet in database" + "\nErrorcode : 99" + "\nPLC Write Result : " + result2 + "\n-------------------------"); } Thread.Sleep(50); break; case 4: case 6: case 8: string a = S7.GetStringAt(transactReadBuffer, 96).ToString(); palletNum = Int32.Parse(a); using (SqlConnection conn = DBUtils.GetMainDBConnection()) { conn.Open(); dt = new DataTable(); SqlDataAdapter da1 = new SqlDataAdapter("SELECT [Pallet Number] FROM Pallets WHERE [Pallet Number] = " + palletNum, conn); da1.Fill(dt); // If no duplicates were found if (dt.Rows.Count == 0) { SqlCommand da2 = new SqlCommand("INSERT INTO Pallets ([Pallet ID],[Pallet Number]) VALUES (@palletID,@palletNum)", conn); da2.Parameters.AddWithValue("@palletID", palletID.ToString()); da2.Parameters.AddWithValue("@palletNum", palletNum); da2.ExecuteNonQuery(); UpdateUISkidID(); S7.SetByteAt(transactWriteBuffer, 45, 99); S7.SetStringAt(transactWriteBuffer, 96, 200, palletNum.ToString()); // Confirm what needs to be written back to plc with the trID int result3 = transactClient.DBWrite(3101, 0, transactWriteBuffer.Length, transactWriteBuffer); Console.WriteLine("-------------------------" + "\nTransaction ID OUT : 99" + "\nPallet ID : " + palletID + "\nResult : Successfully added pallet to database" + "\nPLC Write Result : " + result3 + "\n-------------------------"); } else { S7.SetByteAt(transactWriteBuffer, 45, 5); S7.SetByteAt(transactWriteBuffer, 48, 98); int result3 = transactClient.DBWrite(3101, 0, transactWriteBuffer.Length, transactWriteBuffer); Console.WriteLine("-------------------------" + "\nTransaction ID OUT : 5" + "\nPallet ID : " + palletID + "\nResult : Duplicate pallet number found in database" + "\nErrorcode : 99" + "\nPLC Write Result : " + result3 + "\n-------------------------"); } } break; case 100: Console.WriteLine("-------------------------" + "\nTransaction ID OUT : " + readTransactionID + "\nResult : Handshake done... Starting next screen." + "\n-------------------------"); hub.PublishAsync(new ScreenChangeObject("2", palletNum)); this.Close(); break; default: break; } } }
public void RangierenOutput(byte[] digOutput, byte[] anOutput) { mainWindow.AnzahlFahrzeuge = S7.GetByteAt(digOutput, 0); mainWindow.AnzahlPersonen = S7.GetByteAt(digOutput, 1); }
public void ReadFromByteArray(byte[] data) { var walker = new JPLC_BASEWalker(this, OrderedProperties); //=================================================================== // BOOL //=================================================================== walker.BooleanFound += (propertyWrapper, offsetFromStartOfWalk) => { JPLCProperty <bool> JPLCProperty = propertyWrapper.Property as JPLCProperty <bool>; // int bitNumber = (int)((offsetFromStartOfWalk - (int)offsetFromStartOfWalk)*10); // (2.3 -2)*10 = 3 // int bitNumber = (int)((offsetFromStartOfWalk * 1.0 - ((int)offsetFromStartOfWalk * 1.0)) * 10.0); // (2.3 -2)*10 = 3 double truncatedOffset = Math.Truncate(offsetFromStartOfWalk); double difference = Math.Round((offsetFromStartOfWalk - truncatedOffset) * 10); int bitNumber = (int)(difference); // (2.3 -2)*10 = 3 JPLCProperty.Value = S7.GetBitAt(data, (int)offsetFromStartOfWalk, bitNumber); }; //=================================================================== // BYTE //=================================================================== walker.ByteFound += (propertyWrapper, offsetFromStartOfWalk) => { JPLCProperty <byte> JPLCProperty = propertyWrapper.Property as JPLCProperty <byte>; JPLCProperty.Value = S7.GetByteAt(data, (int)offsetFromStartOfWalk); }; //=================================================================== // INT //=================================================================== walker.IntegerFound += (propertyWrapper, offsetFromStartOfWalk) => { JPLCProperty <int> JPLCProperty = propertyWrapper.Property as JPLCProperty <int>; JPLCProperty.Value = S7.GetDIntAt(data, (int)offsetFromStartOfWalk); }; //=================================================================== // REAL //=================================================================== walker.RealFound += (propertyWrapper, offsetFromStartOfWalk) => { JPLCProperty <float> JPLCProperty = propertyWrapper.Property as JPLCProperty <float>; JPLCProperty.Value = S7.GetRealAt(data, (int)offsetFromStartOfWalk); }; //=================================================================== // SHORT //=================================================================== walker.ShortFound += (propertyWrapper, offsetFromStartOfWalk) => { JPLCProperty <short> JPLCProperty = propertyWrapper.Property as JPLCProperty <short>; JPLCProperty.Value = (short)S7.GetIntAt(data, (int)offsetFromStartOfWalk); }; //=================================================================== // DATETIME //=================================================================== walker.DateTimeFound += (propertyWrapper, offsetFromStartOfWalk) => { JPLCProperty <DateTime> JPLCProperty = propertyWrapper.Property as JPLCProperty <DateTime>; JPLCProperty.Value = S7.GetDateTimeAt(data, (int)offsetFromStartOfWalk); }; //=================================================================== // DATE //=================================================================== walker.DateFound += (propertyWrapper, offsetFromStartOfWalk) => { JPLCProperty <S7Date> JPLCProperty = propertyWrapper.Property as JPLCProperty <S7Date>; JPLCProperty.Value = new S7Date(); JPLCProperty.Value.Date = S7.GetDateAt(data, (int)offsetFromStartOfWalk); }; //=================================================================== // TIME //=================================================================== walker.TimeFound += (propertyWrapper, offsetFromStartOfWalk) => { JPLCProperty <S7Time> JPLCProperty = propertyWrapper.Property as JPLCProperty <S7Time>; JPLCProperty.Value = new S7Time(); JPLCProperty.Value.Time = S7.GetTODAt(data, (int)offsetFromStartOfWalk); }; //=================================================================== // UDT //=================================================================== walker.UDTFound += (propertyWrapper, offsetFromStartOfWalk) => { // Console.WriteLine(propertyWrapper.Property); var udt = (propertyWrapper.PropertyType.GetProperty("Value").GetValue(propertyWrapper.Property, null)) as JPLC_BASE; byte[] extractedByteArray = data.Skip((int)offsetFromStartOfWalk).Take(udt.SizeInBytes).ToArray(); udt.ReadFromByteArray(extractedByteArray); }; //=================================================================== // STRING //=================================================================== walker.StringFound += (propertyWrapper, offsetFromStartOfWalk) => { JPLCProperty <string> JPLCProperty = propertyWrapper.Property as JPLCProperty <string>; JPLCProperty.Value = S7.GetStringAt(data, (int)offsetFromStartOfWalk); }; walker.Walk(); }