public bool Reconnect() { try { //close plc connection _plcConnection.Close(); ServiceBaseX._logger.Log(Category.Info, MethodBase.GetCurrentMethod().DeclaringType.Name + "_" + MethodBase.GetCurrentMethod().Name + ": PLC connection closed."); } catch (Exception ex) { ServiceBaseX._logger.Log(Category.Error, MethodBase.GetCurrentMethod().DeclaringType.Name + "_" + MethodBase.GetCurrentMethod().Name + ": " + ex.Message); return(false); } try { //open plc connection again _plcConnection.Open(); ServiceBaseX._logger.Log(Category.Info, MethodBase.GetCurrentMethod().DeclaringType.Name + "_" + MethodBase.GetCurrentMethod().Name + ": PLC connection re-established."); return(true); } catch (Exception ex) { ServiceBaseX._logger.Log(Category.Error, MethodBase.GetCurrentMethod().DeclaringType.Name + "_" + MethodBase.GetCurrentMethod().Name + ": " + ex.Message); return(false); } }
public static void Main(string[] args) { SimaticDevice device = new SimaticDevice("192.168.0.80", SimaticDeviceType.S7300_400); PlcDeviceConnection connection = device.CreateConnection(); connection.Open(); Program.temperature.Changed += Program.HandleTemperatureChanged; Timer pollTimer = new Timer(Program.PollWeatherStation, connection, 0, 10000); Console.ReadKey(); connection.Close(); }
public static void Main(string[] args) { //// As already demonstrated in the basic sample 'Notifications' it is possible to //// handle the state changes of a connection using the events provided by the static //// PlcNotifications class or using the events provided by the instance of a //// connection itself. //// Additionally taking the basic sample 'Exceptions' into account it is obvious that //// developers using the framework are able to fully control and monitor the creation //// of connections, the state of these connections and they can influence the status //// evaluation of every operation performed by the low level driver used within the //// framework. //// This sample does therefore demonstrate how a developer can get the most out of //// the features represented by the basic samples 'Notifications' and 'Exceptions'. // Assign an event handler to the ConnectionCreated event to get notified when ever // a new connection has been created within the framework. This handler does then // subscribe further events on the connection. PlcNotifications.ConnectionCreated += Program.HandleConnectionCreated; // Assign a callback method to evaluate the operational status in a custom way to // ensure that only in specific conditions failed operations will lead to an exception. PlcNotifications.EvaluateStatus = Program.EvaluateStatus; SimaticDevice device = new SimaticDevice("192.168.0.80", SimaticDeviceType.S7300_400); PlcDeviceConnection connection = device.CreateConnection(); Console.WriteLine(); Console.WriteLine("= Open ="); connection.Open(); //// An explicit call to Connect() is not required. But it will be done here to //// demonstrate the appropriate state changes which occur in case of the //// first attempt to acccess the PLC device. Console.WriteLine(); Console.WriteLine("= Connect ="); connection.Connect(); Program.ReadBoolean(connection); Program.ReadBooleanArray(connection); Console.WriteLine(); Console.WriteLine("= Close ="); connection.Close(); Console.ReadKey(); }
public static void Main(string[] args) { SimaticDevice device = new SimaticDevice("192.168.0.80", SimaticDeviceType.S7300_400); PlcDeviceConnection connection = device.CreateConnection(); connection.Open(); connection.WriteString("DB111.DBB 100", "Hello World!"); string message = connection.ReadString("DB111.DBB 100", 16); Console.WriteLine(message); connection.Close(); Console.ReadKey(); }
public static void Main(string[] args) { //// The following lines of code demonstrate how to read and write data //// using a custom PLC Object which defines its members dynamically. //// //// Note that each instance of the class Data initialized does refer to //// different DataBlocks upon changing the static DataBlockNumber property //// of the class. //// //// This scenario is not a general way how to use dynamic PlcObject members. //// It just demonstrates one possible way to refer to dynamic PLC data in an //// independent way. SimaticDevice device = new SimaticDevice("192.168.0.80", SimaticDeviceType.S7300_400); PlcDeviceConnection connection = device.CreateConnection(); connection.Open(); Data.DataBlockNumber = 1; Data data1 = connection.ReadObject <Data>(); Data.DataBlockNumber = 10; Data data10 = connection.ReadObject <Data>(); Data.DataBlockNumber = 15; Data data15 = connection.ReadObject <Data>(); Data.DataBlockNumber = 20; Data data20 = new Data(); data20.ByteValue = data1.ByteValue; data20.Int16Value = data10.Int16Value; data20.Int32Value = data15.Int32Value; data20.RealValue = data10.RealValue / data1.RealValue; data20.StringValue = data15.StringValue; connection.WriteObject(data20); connection.Close(); }
private bool Connect() { if (bFirstConnect == true) { ServiceBaseX._syncEvts.IncrementThreadsRunning(); } try { client = new SiemensDevice(_EndPoint, SiemensDeviceType.S7300_400); IPS7Lnk.Advanced.Licenser.LicenseKey = "lgAAAA29d9Q/xtEBlgFDb21wYW55TmFtZT1Mb2dvVGVrICBHbWJIIEdlc2VsbHNjaGFmdCBmw7xyIEluZm9ybWF0aW9uc3RlY2hub2xvZ2llO0ZpcnN0TmFtZT1DaHJpc3RvcGhlcjtMYXN0TmFtZT1Lw7ZtcGVsO0VtYWlsPWNocmlzdG9waGVyLmtvZW1wZWxAbG9nb3Rlay1nbWJoLmRlO0NvdW50cnlOYW1lPUQ7Q2l0eU5hbWU9TWFya3RoZWlkZW5mZWxkO1ppcENvZGU9OTc4Mjg7U3RyZWV0TmFtZT1BbiBkZXIgS8O2aGxlcmVpIDc7U3RyZWV0TnVtYmVyPTtSZXRhaWxlck5hbWU9VHJhZWdlciBJbmR1c3RyeSBDb21wb25lbnRzO1ZvbHVtZT0xO1NlcmlhbE51bWJlcj0xMDAxO1N1cHBvcnRFeHBpcnlEYXRlPTA2LzE0LzIwMTcgMDA6MDA6MDA7VXNlTm9CcmFuZGluZz1GYWxzZTtDb250YWN0Rmlyc3ROYW1lPTtDb250YWN0TGFzdE5hbWU9GQwP4pqjgIkqQ3rkHBitUvrSkZA87Wf+QGXIW7F54n+Fnqh7gR8rfZy/oUnKKTGz"; _plcConnection = client.CreateConnection(); _plcConnection.Open(); bFirstConnect = false; return(true); } catch (Exception ex) { ServiceBaseX._logger.Log(Category.Error, MethodBase.GetCurrentMethod().DeclaringType.Name + "_" + MethodBase.GetCurrentMethod().Name + ": " + ex.Message); return(false); } }
public static void Main(string[] args) { SimaticDevice device = new SimaticDevice("192.168.0.80", SimaticDeviceType.S7300_400); PlcDeviceConnection connection = device.CreateConnection(); connection.Open(); SQLiteConnectionStringBuilder builder = new SQLiteConnectionStringBuilder(); builder.DataSource = @".\Database.db"; SQLiteConnection sqlConnection = new SQLiteConnection( builder.ToString(), parseViaFramework: true); SQLiteCommand command = sqlConnection.CreateCommand(); command.CommandText = "select * from Data"; SQLiteDataReader dataReader = command.ExecuteReader(); DataTable table = new DataTable(); table.Load(dataReader); #region 1. Way: Sequential Write. { //// Either use the primitive low level methods of the PLC device connection to //// sequential write the data. foreach (DataRow row in table.Rows) { connection.WriteByte("DB111.DBB 2", Convert.ToByte(row["NumberOfPages"])); // Number of pages. connection.WriteInt16("DB111.DBW 4", Convert.ToInt16(row["Resolution"])); // Resolution in dpi. connection.WriteInt32("DB111.DBD 6", Convert.ToInt32(row["LineHeight"])); // Line Height in pixels. connection.WriteReal("DB111.DBD 10", Convert.ToSingle(row["Price"])); // Price. connection.WriteString("DB111.DBB 20", Convert.ToString(row["ArticleNumber"])); // Article Number. connection.WriteBoolean("DB111.DBX 1.0", true); // Wait while printing. while (connection.ReadBoolean("E 1.0")) { Thread.Sleep(TimeSpan.FromMilliseconds(100)); } } } #endregion #region 2. Way: Bulk write (with variables). { //// Or use the higher level methods of the PLC device connection to write a whole //// set of variables at once. While this way would be much faster than the //// previous one, because the values are write within one transaction instead of //// processing each value within a transaction for each action. PlcByte numberOfPages = new PlcByte("DB111.DBB 2"); PlcInt16 resolution = new PlcInt16("DB111.DBW 4"); PlcInt32 lineHeight = new PlcInt32("DB111.DBD 6"); PlcReal price = new PlcReal("DB111.DBD 10"); PlcString articleNumber = new PlcString("DB111.DBB 20", 16); PlcBoolean startPrint = new PlcBoolean("DB111.DBX 1.0", true); foreach (DataRow row in table.Rows) { numberOfPages.Value = Convert.ToByte(row["NumberOfPages"]); // Number of pages. resolution.Value = Convert.ToInt16(row["Resolution"]); // Resolution in dpi. lineHeight.Value = Convert.ToInt32(row["LineHeight"]); // Line Height in pixels. price.Value = Convert.ToSingle(row["Price"]); // Price. articleNumber.Value = Convert.ToString(row["ArticleNumber"]); // Article Number. connection.WriteValues(numberOfPages, resolution, lineHeight, price, articleNumber, startPrint); // Wait while printing. while (connection.ReadBoolean("E 1.0")) { Thread.Sleep(TimeSpan.FromMilliseconds(100)); } } } #endregion #region 3. Way: Bulk write (with object). { //// Or use the methods of the PLC device connection at the highest abstraction //// layer to write the whole PLC data at once from a user defined PLC object. foreach (DataRow row in table.Rows) { PrintJobData data = new PrintJobData(); data.NumberOfPages = Convert.ToByte(row["NumberOfPages"]); // Number of pages. data.Resolution = Convert.ToInt16(row["Resolution"]); // Resolution in dpi. data.LineHeight = Convert.ToInt32(row["LineHeight"]); // Line Height in pixels. data.Price = Convert.ToSingle(row["Price"]); // Price. data.ArticleNumber = Convert.ToString(row["ArticleNumber"]); // Article Number. connection.WriteObject(data); // Wait while printing. while (connection.ReadBoolean("E 1.0")) { Thread.Sleep(TimeSpan.FromMilliseconds(100)); } } } #endregion sqlConnection.Close(); connection.Close(); }
public static void Main(string[] args) { SimaticDevice device = new SimaticDevice("192.168.0.80", SimaticDeviceType.S7300_400); PlcDeviceConnection connection = device.CreateConnection(); connection.Open(); #region 1. Way: Sequential Write. { //// Either use the primitive low level methods of the PLC device connection to //// sequential write the data. foreach (string line in File.ReadAllLines(@".\Data.csv")) { string[] values = line.Split(';'); connection.WriteByte("DB111.DBB 2", Convert.ToByte(values[0])); // Number of pages. connection.WriteInt16("DB111.DBW 4", Convert.ToInt16(values[1])); // Resolution in dpi. connection.WriteInt32("DB111.DBD 6", Convert.ToInt32(values[2])); // Line Height in pixels. connection.WriteReal("DB111.DBD 10", Convert.ToSingle(values[3])); // Price. connection.WriteString("DB111.DBB 20", values[4]); // Article Number. connection.WriteBoolean("DB111.DBX 1.0", true); // Wait while printing. while (connection.ReadBoolean("E 1.0")) { Thread.Sleep(TimeSpan.FromMilliseconds(100)); } } } #endregion #region 2. Way: Bulk write (with variables). { //// Or use the higher level methods of the PLC device connection to write a whole //// set of variables at once. While this way would be much faster than the //// previous one, because the values are write within one transaction instead of //// processing each value within a transaction for each action. PlcByte numberOfPages = new PlcByte("DB111.DBB 2"); PlcInt16 resolution = new PlcInt16("DB111.DBW 4"); PlcInt32 lineHeight = new PlcInt32("DB111.DBD 6"); PlcReal price = new PlcReal("DB111.DBD 10"); PlcString articleNumber = new PlcString("DB111.DBB 20", 16); PlcBoolean startPrint = new PlcBoolean("DB111.DBX 1.0", true); foreach (string line in File.ReadAllLines(@".\Data.csv")) { string[] values = line.Split(';'); numberOfPages.Value = Convert.ToByte(values[0]); // Number of pages. resolution.Value = Convert.ToInt16(values[1]); // Resolution in dpi. lineHeight.Value = Convert.ToInt32(values[2]); // Line Height in pixels. price.Value = Convert.ToSingle(values[3]); // Price. articleNumber.Value = Convert.ToString(values[4]); // Article Number. connection.WriteValues(numberOfPages, resolution, lineHeight, price, articleNumber, startPrint); // Wait while printing. while (connection.ReadBoolean("E 1.0")) { Thread.Sleep(TimeSpan.FromMilliseconds(100)); } } } #endregion #region 3. Way: Bulk write (with object). { //// Or use the methods of the PLC device connection at the highest abstraction //// layer to write the whole PLC data at once from a user defined PLC object. foreach (string line in File.ReadAllLines(@".\Data.csv")) { string[] values = line.Split(';'); PrintJobData data = new PrintJobData(); data.NumberOfPages = Convert.ToByte(values[0]); // Number of pages. data.Resolution = Convert.ToInt16(values[1]); // Resolution in dpi. data.LineHeight = Convert.ToInt32(values[2]); // Line Height in pixels. data.Price = Convert.ToSingle(values[3]); // Price. data.ArticleNumber = Convert.ToString(values[4]); // Article Number. connection.WriteObject(data); // Wait while printing. while (connection.ReadBoolean("E 1.0")) { Thread.Sleep(TimeSpan.FromMilliseconds(100)); } } } #endregion connection.Close(); }
public static void Main(string[] args) { SimaticDevice device = new SimaticDevice("192.168.0.80", SimaticDeviceType.S7300_400); PlcDeviceConnection connection = device.CreateConnection(); connection.Open(); SQLiteConnectionStringBuilder builder = new SQLiteConnectionStringBuilder(); builder.DataSource = @".\Database.db"; SQLiteConnection sqlConnection = new SQLiteConnection( builder.ToString(), parseViaFramework: true); sqlConnection.Open(); SQLiteCommand command = sqlConnection.CreateCommand(); command.CommandText = "insert into Data (ChanceOfRain, WindSpeed, Pressure, Temperature, Forecast) " + "values (@chanceOfRain, @windSpeed, @pressure, @temperature, @forecast)"; SQLiteParameter sqlChanceOfRain = command.Parameters.Add("@chanceOfRain", DbType.Int16); SQLiteParameter sqlWindSpeed = command.Parameters.Add("@windSpeed", DbType.Int16); SQLiteParameter sqlPressure = command.Parameters.Add("@pressure", DbType.Int16); SQLiteParameter sqlTemperature = command.Parameters.Add("@temperature", DbType.Single); SQLiteParameter sqlForecast = command.Parameters.Add("@forecast", DbType.String); #region 1. Way: Sequential Read. { //// Either use the primitive low level methods of the PLC device connection to //// sequential read the desired data areas. // Is the weather station online. while (connection.ReadBoolean("E 1.0")) { sqlChanceOfRain.Value = connection.ReadByte("DB111.DBB 2"); // Chance of rain. sqlWindSpeed.Value = connection.ReadInt16("DB111.DBW 4"); // Wind speed. sqlPressure.Value = connection.ReadInt32("DB111.DBD 6"); // Pressure. sqlTemperature.Value = connection.ReadReal("DB111.DBD 10"); // Temperature. sqlForecast.Value = connection.ReadString("DB111.DBB 20", 16); // Forecast. command.ExecuteNonQuery(); Thread.Sleep(TimeSpan.FromMinutes(30)); } } #endregion #region 2. Way: Bulk read (with variables). { //// Or use the higher level methods of the PLC device connection to read a whole //// set of variables at once. While this way would be much faster than the previous //// one, because the values are read within one transaction instead of querying //// each value within a transaction for each request. PlcByte chanceOfRain = new PlcByte("DB111.DBB 2"); PlcInt16 windSpeed = new PlcInt16("DB111.DBW 4"); PlcInt32 pressure = new PlcInt32("DB111.DBD 6"); PlcReal temperature = new PlcReal("DB111.DBD 10"); PlcString forecast = new PlcString("DB111.DBB 20", 16); // Is the weather station online. while (connection.ReadBoolean("E 1.0")) { connection.ReadValues(chanceOfRain, windSpeed, pressure, temperature, forecast); sqlChanceOfRain.Value = chanceOfRain.Value; // Chance of rain. sqlWindSpeed.Value = windSpeed.Value; // Wind speed. sqlPressure.Value = pressure.Value; // Pressure. sqlTemperature.Value = temperature.Value; // Temperature. sqlForecast.Value = forecast.Value; // Forecast. command.ExecuteNonQuery(); Thread.Sleep(TimeSpan.FromMinutes(30)); } } #endregion #region 3. Way: Bulk read (with object). { //// Or use the methods of the PLC device connection at the highest abstraction //// layer to read the whole PLC data at once into a user defined PLC object. // Is the weather station online. while (connection.ReadBoolean("E 1.0")) { WeatherData data = connection.ReadObject <WeatherData>(); sqlChanceOfRain.Value = data.ChanceOfRain; // Chance of rain. sqlWindSpeed.Value = data.WindSpeed; // Wind speed. sqlPressure.Value = data.Pressure; // Pressure. sqlTemperature.Value = data.Temperature; // Temperature. sqlForecast.Value = data.Forecast; // Forecast. command.ExecuteNonQuery(); Thread.Sleep(TimeSpan.FromMinutes(30)); } } #endregion sqlConnection.Close(); connection.Close(); }
public static void Main(string[] args) { SimaticDevice device = new SimaticDevice("192.168.0.80", SimaticDeviceType.S7300_400); PlcDeviceConnection connection = device.CreateConnection(); connection.Open(); #region 1. Way: Sequential Write/Read. { //// Either use the primitive low level methods of the PLC device connection to //// sequential write the data or read the desired data areas. connection.WriteByte("DB111.DBB 2", 15); Console.WriteLine("DB111.DBB 2: {0}", connection.ReadByte("DB111.DBB 2")); connection.WriteInt16("DB111.DBW 4", 600); Console.WriteLine("DB111.DBW 4: {0}", connection.ReadInt16("DB111.DBW 4")); connection.WriteInt32("DB111.DBD 6", 280); Console.WriteLine("DB111.DBD 6: {0}", connection.ReadInt32("DB111.DBD 6")); connection.WriteReal("DB111.DBD 10", 2.46f); Console.WriteLine("DB111.DBD 10: {0}", connection.ReadReal("DB111.DBD 10")); connection.WriteString("DB111.DBB 20", "4-036300-076816"); Console.WriteLine("DB111.DBB 20: {0}", connection.ReadString("DB111.DBB 20", 16)); } #endregion #region 2. Way: Bulk write/read (with variables). { //// Or use the higher level methods of the PLC device connection to write/read //// a whole set of variables at once. While this way would be much faster than the //// previous one, because the values are write/read within one transaction //// instead of processing each value within a transaction for each action. connection.WriteValues( new PlcByte("DB111.DBB 2", 15), new PlcInt16("DB111.DBW 4", 600), new PlcInt32("DB111.DBD 6", 280), new PlcReal("DB111.DBD 10", 2.46f), new PlcString("DB111.DBB 20", "4-036300-076816", 16)); object[] values = connection.ReadValues( new PlcByte("DB111.DBB 2"), new PlcInt16("DB111.DBW 4"), new PlcInt32("DB111.DBD 6"), new PlcReal("DB111.DBD 10"), new PlcString("DB111.DBB 20", 16)); Console.WriteLine("DB111.DBB 2: {0}", values[0]); Console.WriteLine("DB111.DBW 4: {0}", values[1]); Console.WriteLine("DB111.DBD 6: {0}", values[2]); Console.WriteLine("DB111.DBD 10: {0}", values[3]); Console.WriteLine("DB111.DBB 20: {0}", values[4]); } #endregion #region 3. Way: Bulk write/read (with object). { //// Or use the methods of the PLC device connection at the highest abstraction //// layer to write/read the whole PLC data at once from a user defined PLC object. Data data = new Data(); data.ByteValue = 15; data.Int16Value = 600; data.Int32Value = 280; data.RealValue = 2.46f; data.StringValue = "4-036300-076816"; connection.WriteObject(data); data = connection.ReadObject <Data>(); Console.WriteLine("DB111.DBB 2: {0}", data.ByteValue); Console.WriteLine("DB111.DBW 4: {0}", data.Int16Value); Console.WriteLine("DB111.DBD 6: {0}", data.Int32Value); Console.WriteLine("DB111.DBD 10: {0}", data.RealValue); Console.WriteLine("DB111.DBB 20: {0}", data.StringValue); } #endregion Console.ReadKey(); }
public static void Main(string[] args) { SimaticDevice device = new SimaticDevice("192.168.0.80", SimaticDeviceType.S7300_400); #region 1. Way: Global events. { //// In case there it is necessary of being notified when ever a new connection //// has been created or the state of a connection has been changed there does //// the PlcNotifications class provide different events that can be used for that //// requirement. //// Simply assign custom event handlers to the appropriate events like the //// following lines demonstrate. PlcNotifications.ConnectionCreated += Program.HandleAnyEvent; PlcNotifications.ConnectionOpening += Program.HandleAnyEvent; PlcNotifications.ConnectionOpened += Program.HandleAnyEvent; PlcNotifications.ConnectionConnecting += Program.HandleAnyEvent; PlcNotifications.ConnectionConnected += Program.HandleAnyEvent; PlcNotifications.ConnectionClosing += Program.HandleAnyEvent; PlcNotifications.ConnectionClosed += Program.HandleAnyEvent; PlcDeviceConnection connection = device.CreateConnection(); connection.Open(); //// An explicit call to Connect() is not required. But it will be done here to //// demonstrate the appropriate state changes which occur in case of the //// first attempt to acccess the PLC device. connection.Connect(); connection.Close(); //// In case there is no longer any need of being notified simply detach the //// associated custom event handlers like the following lines demonstrate. PlcNotifications.ConnectionCreated -= Program.HandleAnyEvent; PlcNotifications.ConnectionOpening -= Program.HandleAnyEvent; PlcNotifications.ConnectionOpened -= Program.HandleAnyEvent; PlcNotifications.ConnectionConnecting -= Program.HandleAnyEvent; PlcNotifications.ConnectionConnected -= Program.HandleAnyEvent; PlcNotifications.ConnectionClosing -= Program.HandleAnyEvent; PlcNotifications.ConnectionClosed -= Program.HandleAnyEvent; } #endregion Console.WriteLine(); #region 2. Way: Global state event. { //// Instead of attachning/detaching a custom event handler to specific events it //// is also possible to handle all state events using code like the following one. PlcNotifications.ConnectionStateChanged += Program.HandleStateEvent; PlcDeviceConnection connection = device.CreateConnection(); connection.Open(); //// An explicit call to Connect() is not required. But it will be done here to //// demonstrate the appropriate state changes which occur in case of the //// first attempt to acccess the PLC device. connection.Connect(); connection.Close(); //// In case there is no longer any need of being notified simply detach the //// associated custom event handler like the following line demonstrate. PlcNotifications.ConnectionStateChanged -= Program.HandleStateEvent; } #endregion Console.WriteLine(); #region 3. Way: Instance events. { //// If there is no need of being notified when ever any connection changes its //// state, it is also possible to restrict the event handlers to one or more //// specific connection instances. //// Simply assign custom event handlers to the appropriate events like the //// following lines demonstrate. PlcDeviceConnection connection = device.CreateConnection(); connection.Opening += Program.HandleAnyInstanceEvent; connection.Opened += Program.HandleAnyInstanceEvent; connection.Connecting += Program.HandleAnyInstanceEvent; connection.Connected += Program.HandleAnyInstanceEvent; connection.Closing += Program.HandleAnyInstanceEvent; connection.Closed += Program.HandleAnyInstanceEvent; connection.Open(); //// An explicit call to Connect() is not required. But it will be done here to //// demonstrate the appropriate state changes which occur in case of the //// first attempt to acccess the PLC device. connection.Connect(); connection.Close(); //// In case there is no longer any need of being notified simply detach the //// associated custom event handlers like the following lines demonstrate. connection.Opening -= Program.HandleAnyInstanceEvent; connection.Opened -= Program.HandleAnyInstanceEvent; connection.Connecting -= Program.HandleAnyInstanceEvent; connection.Connected -= Program.HandleAnyInstanceEvent; connection.Closing -= Program.HandleAnyInstanceEvent; connection.Closed -= Program.HandleAnyInstanceEvent; } #endregion Console.WriteLine(); #region 4. Way: Instance state event. { //// Instead of attachning/detaching a custom event handler to specific events it //// is also possible to handle all state events using code like the following one. PlcDeviceConnection connection = device.CreateConnection(); connection.StateChanged += Program.HandleInstanceStateEvent; connection.Open(); //// An explicit call to Connect() is not required. But it will be done here to //// demonstrate the appropriate state changes which occur in case of the //// first attempt to acccess the PLC device. connection.Connect(); connection.Close(); //// In case there is no longer any need of being notified simply detach the //// associated custom event handler like the following line demonstrate. connection.StateChanged -= Program.HandleInstanceStateEvent; } #endregion Console.ReadKey(); }
public static void Main(string[] args) { SimaticDevice device = new SimaticDevice("192.168.0.80", SimaticDeviceType.S7300_400); PlcDeviceConnection connection = device.CreateConnection(); connection.Open(); string[] values = new string[5]; StreamWriter writer = File.AppendText(@".\Data.csv"); #region 1. Way: Sequential Read. { //// Either use the primitive low level methods of the PLC device connection to //// sequential read the desired data areas. // Is the weather station online. while (connection.ReadBoolean("E 1.0")) { values[0] = connection.ReadByte("DB111.DBB 2").ToString(); // Chance of rain. values[1] = connection.ReadInt16("DB111.DBW 4").ToString(); // Wind speed. values[2] = connection.ReadInt32("DB111.DBD 6").ToString(); // Pressure. values[3] = connection.ReadReal("DB111.DBD 10").ToString(); // Temperature. values[4] = connection.ReadString("DB111.DBB 20", 16); // Forecast. writer.WriteLine(string.Join(";", values)); writer.Flush(); Thread.Sleep(TimeSpan.FromMinutes(30)); } } #endregion #region 2. Way: Bulk read (with variables). { //// Or use the higher level methods of the PLC device connection to read a whole //// set of variables at once. While this way would be much faster than the //// previous one, because the values are read within one transaction instead of //// querying each value within a transaction for each request. PlcByte chanceOfRain = new PlcByte("DB111.DBB 2"); PlcInt16 windSpeed = new PlcInt16("DB111.DBW 4"); PlcInt32 pressure = new PlcInt32("DB111.DBD 6"); PlcReal temperature = new PlcReal("DB111.DBD 10"); PlcString forecast = new PlcString("DB111.DBB 20", 16); // Is the weather station online. while (connection.ReadBoolean("E 1.0")) { connection.ReadValues(chanceOfRain, windSpeed, pressure, temperature, forecast); values[0] = chanceOfRain.Value.ToString(); // Chance of rain. values[1] = windSpeed.Value.ToString(); // Wind speed. values[2] = pressure.Value.ToString(); // Pressure. values[3] = temperature.Value.ToString(); // Temperature. values[4] = forecast.Value.ToString(); // Forecast. writer.WriteLine(string.Join(";", values)); writer.Flush(); Thread.Sleep(TimeSpan.FromMinutes(30)); } } #endregion #region 3. Way: Bulk read (with object). { //// Or use the methods of the PLC device connection at the highest abstraction //// layer to read the whole PLC data at once into a user defined PLC object. // Is the weather station online. while (connection.ReadBoolean("E 1.0")) { WeatherData data = connection.ReadObject <WeatherData>(); values[0] = data.ChanceOfRain.ToString(); // Chance of rain. values[1] = data.WindSpeed.ToString(); // Wind speed. values[2] = data.Pressure.ToString(); // Pressure. values[3] = data.Temperature.ToString(); // Temperature. values[4] = data.Forecast.ToString(); // Forecast. writer.WriteLine(string.Join(";", values)); writer.Flush(); Thread.Sleep(TimeSpan.FromMinutes(30)); } } #endregion writer.Close(); connection.Close(); }
public static void Main(string[] args) { SimaticDevice device = new SimaticDevice("192.168.0.80", SimaticDeviceType.S7300_400); PlcDeviceConnection connection = device.CreateConnection(); connection.Open(); // NOTE // To access XLS files using OLEDB you will need to install // "Microsoft Access Database Engine 2010 Redistributable" // https://www.microsoft.com/en-us/download/details.aspx?id=13255 OleDbConnection excelConnection = new OleDbConnection( "Provider=Microsoft.ACE.OLEDB.12.0;" + @"Data Source=.\Data.xls;" + "Extended Properties=Excel 12.0"); excelConnection.Open(); // 'Data' represents the Excel Worksheet to write. OleDbCommand command = excelConnection.CreateCommand(); command.CommandText = "insert into [Data$] values (?, ?, ?, ?, ?)"; OleDbParameter excelChanceOfRain = command.Parameters.Add("@chanceOfRain", OleDbType.UnsignedTinyInt); OleDbParameter excelWindSpeed = command.Parameters.Add("@windSpeed", OleDbType.SmallInt); OleDbParameter excelPressure = command.Parameters.Add("@pressure", OleDbType.Integer); OleDbParameter excelTemperature = command.Parameters.Add("@temperature", OleDbType.Single); OleDbParameter excelForecast = command.Parameters.Add("@forecast", OleDbType.BSTR); #region 1. Way: Sequential Read. { //// Either use the primitive low level methods of the PLC device connection to //// sequential read the desired data areas. // Is the weather station online. while (connection.ReadBoolean("E 1.0")) { excelChanceOfRain.Value = connection.ReadByte("DB111.DBB 2"); // Chance of rain. excelWindSpeed.Value = connection.ReadInt16("DB111.DBW 4"); // Wind speed. excelPressure.Value = connection.ReadInt32("DB111.DBD 6"); // Pressure. excelTemperature.Value = connection.ReadReal("DB111.DBD 10"); // Temperature. excelForecast.Value = connection.ReadString("DB111.DBB 20", 16); // Forecast. command.ExecuteNonQuery(); Thread.Sleep(TimeSpan.FromMinutes(30)); } } #endregion #region 2. Way: Bulk read (with variables). { //// Or use the higher level methods of the PLC device connection to read a whole //// set of variables at once. While this way would be much faster than the previous //// one, because the values are read within one transaction instead of querying //// each value within a transaction for each request. PlcByte chanceOfRain = new PlcByte("DB111.DBB 2"); PlcInt16 windSpeed = new PlcInt16("DB111.DBW 4"); PlcInt32 pressure = new PlcInt32("DB111.DBD 6"); PlcReal temperature = new PlcReal("DB111.DBD 10"); PlcString forecast = new PlcString("DB111.DBB 20", 16); // Is the weather station online. while (connection.ReadBoolean("E 1.0")) { connection.ReadValues(chanceOfRain, windSpeed, pressure, temperature, forecast); excelChanceOfRain.Value = chanceOfRain.Value; // Chance of rain. excelWindSpeed.Value = windSpeed.Value; // Wind speed. excelPressure.Value = pressure.Value; // Pressure. excelTemperature.Value = temperature.Value; // Temperature. excelForecast.Value = forecast.Value; // Forecast. command.ExecuteNonQuery(); Thread.Sleep(TimeSpan.FromMinutes(30)); } } #endregion #region 3. Way: Bulk read (with object). { //// Or use the methods of the PLC device connection at the highest abstraction //// layer to read the whole PLC data at once into a user defined PLC object. // Is the weather station online. while (connection.ReadBoolean("E 1.0")) { WeatherData data = connection.ReadObject <WeatherData>(); excelChanceOfRain.Value = data.ChanceOfRain; // Chance of rain. excelWindSpeed.Value = data.WindSpeed; // Wind speed. excelPressure.Value = data.Pressure; // Pressure. excelTemperature.Value = data.Temperature; // Temperature. excelForecast.Value = data.Forecast; // Forecast. command.ExecuteNonQuery(); Thread.Sleep(TimeSpan.FromMinutes(30)); } } #endregion excelConnection.Close(); connection.Close(); }
public static void Main(string[] args) { SimaticDevice device = new SimaticDevice("192.168.0.80", SimaticDeviceType.S7300_400); PlcDeviceConnection connection = device.CreateConnection(); connection.Open(); // NOTE // To access XLS files using OLEDB you will need to install // "Microsoft Access Database Engine 2010 Redistributable" // https://www.microsoft.com/en-us/download/details.aspx?id=13255 OleDbConnection excelConnection = new OleDbConnection( "Provider=Microsoft.ACE.OLEDB.12.0;" + @"Data Source=.\Data.xls;" + "Extended Properties=Excel 12.0"); excelConnection.Open(); // 'Data' represents the Excel Worksheet to read. OleDbCommand command = excelConnection.CreateCommand(); command.CommandText = "select * from [Data$]"; OleDbDataReader dataReader = command.ExecuteReader(); DataTable table = new DataTable(); table.Load(dataReader); #region 1. Way: Sequential Write. { //// Either use the primitive low level methods of the PLC device connection to //// sequential write the data. foreach (DataRow row in table.Rows) { connection.WriteByte("DB111.DBB 2", Convert.ToByte(row[0])); // Number of pages. connection.WriteInt16("DB111.DBW 4", Convert.ToInt16(row[1])); // Resolution in dpi. connection.WriteInt32("DB111.DBD 6", Convert.ToInt32(row[2])); // Line Height in pixels. connection.WriteReal("DB111.DBD 10", Convert.ToSingle(row[3])); // Price. connection.WriteString("DB111.DBB 20", Convert.ToString(row[4])); // Article Number. connection.WriteBoolean("DB111.DBX 1.0", true); // Wait while printing. while (connection.ReadBoolean("E 1.0")) { Thread.Sleep(TimeSpan.FromMilliseconds(100)); } } } #endregion #region 2. Way: Bulk write (with variables). { //// Or use the higher level methods of the PLC device connection to write a whole //// set of variables at once. While this way would be much faster than the //// previous one, because the values are write within one transaction instead of //// processing each value within a transaction for each action. PlcByte numberOfPages = new PlcByte("DB111.DBB 2"); PlcInt16 resolution = new PlcInt16("DB111.DBW 4"); PlcInt32 lineHeight = new PlcInt32("DB111.DBD 6"); PlcReal price = new PlcReal("DB111.DBD 10"); PlcString articleNumber = new PlcString("DB111.DBB 20", 16); PlcBoolean startPrint = new PlcBoolean("DB111.DBX 1.0", true); foreach (DataRow row in table.Rows) { numberOfPages.Value = Convert.ToByte(row["NumberOfPages"]); // Number of pages. resolution.Value = Convert.ToInt16(row["Resolution"]); // Resolution in dpi. lineHeight.Value = Convert.ToInt32(row["LineHeight"]); // Line Height in pixels. price.Value = Convert.ToSingle(row["Price"]); // Price. articleNumber.Value = Convert.ToString(row["ArticleNumber"]); // Article Number. connection.WriteValues(numberOfPages, resolution, lineHeight, price, articleNumber, startPrint); // Wait while printing. while (connection.ReadBoolean("E 1.0")) { Thread.Sleep(TimeSpan.FromMilliseconds(100)); } } } #endregion #region 3. Way: Bulk write (with object). { //// Or use the methods of the PLC device connection at the highest abstraction //// layer to write the whole PLC data at once from a user defined PLC object. foreach (DataRow row in table.Rows) { PrintJobData data = new PrintJobData(); data.NumberOfPages = Convert.ToByte(row["NumberOfPages"]); // Number of pages. data.Resolution = Convert.ToInt16(row["Resolution"]); // Resolution in dpi. data.LineHeight = Convert.ToInt32(row["LineHeight"]); // Line Height in pixels. data.Price = Convert.ToSingle(row["Price"]); // Price. data.ArticleNumber = Convert.ToString(row["ArticleNumber"]); // Article Number. connection.WriteObject(data); // Wait while printing. while (connection.ReadBoolean("E 1.0")) { Thread.Sleep(TimeSpan.FromMilliseconds(100)); } } } #endregion excelConnection.Close(); connection.Close(); }