using System;
using System.Collections.Generic;
using System.IO;
using Siemens.Engineering.HW;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.SqlServer.Server;
using Microsoft.VisualBasic;
using S7.Net;
using Siemens.Engineering;
using Siemens.Engineering.Library;
using static System.Windows.Forms.DataFormats;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
using System.Text.RegularExpressions;
using Siemens.Engineering.SW;
using Siemens.Engineering.HW.Features;
using Siemens.Engineering.Hmi;
using System.Configuration;
using Siemens.Engineering.Online;
using Siemens.Engineering.Connection;
using Siemens.Engineering.Cax;
using Microsoft.VisualBasic.Devices;
using System.Xml.Linq;
using System.Net;
using static Controller;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.TrackBar;
namespace TIAManagement
{
public class TiaApplication
{
private TiaPortal _instance;
private string _projectPath;
public static string _textPath;
public const string text = "text"; //najbolje pozvat konstantu umjesto hardcodinga
private int _instanceID;
public Project project;
private string _folderPath;
public static Device plcDevice;
public Device hmiDevice;
public static Device anyDevice;
public HmiTarget hmiTarget;
public Device devices;
public Subnet subnetSet;
public string getDeviceIpAddress;
public string getDeviceName;
public string getDeviceVersion;
public string getDeviceOrderNumber;
public string getSubnetMask;
public bool plc;
public NetworkInterface networkInterface;
public DeviceItem plcDeviceItem;
List<Device> DeviceList = new List<Device>();
class DataStore<T>
{
public T Data { get; set; }
}
public void OpenTiaPortal()
{
_instance = new TiaPortal(TiaPortalMode.WithUserInterface);
}
public void DisposeTiaPortal()
{
project.Close();
_instance.Dispose();
}
public void SetInstanceID()
{
IList<TiaPortalProcess> tiaPortalProcesses = TiaPortal.GetProcesses();
foreach (TiaPortalProcess tiaPortalProcess in tiaPortalProcesses)
{
foreach (TiaPortalSession session in tiaPortalProcess.AttachedSessions)
{
_instanceID = session.ProcessId;
}
}
}
public int GetInstanceID()
{
return _instanceID;
}
public void AddNewProject(string projectName)
{
FolderBrowserDialog folderBrowserDialog1 = new FolderBrowserDialog();
{
}
if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
//Get the path of specified folder
_folderPath = folderBrowserDialog1.SelectedPath;
MessageBox.Show(_folderPath);
ProjectComposition projectComposition = _instance.Projects;
DirectoryInfo directoryInfo = new DirectoryInfo(_folderPath);
project = projectComposition.Create(directoryInfo, projectName);
}
}
public void OpenExistingProject()
{
OpenFileDialog openFileDialog1 = new OpenFileDialog
{
InitialDirectory = @"D:\",
Title = "Browse Tia Portal Files",
CheckFileExists = true,
CheckPathExists = true,
DefaultExt = "ap17",
Filter = "TIA files (*.ap17)|*.ap17",
FilterIndex = 2,
RestoreDirectory = true,
ReadOnlyChecked = true,
ShowReadOnly = true
};
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
//Get the path of specified file
_projectPath = openFileDialog1.FileName;
FileInfo projectPath = new FileInfo(_projectPath);
MessageBox.Show(_projectPath);
//Project project = null;
//try
//{
//project = _instance.Projects.Open();
//}
//catch (Exception)
//{
// MessageBox.Show("blabla");
// return;
//}
ProjectComposition projectComposition = _instance.Projects;
project = projectComposition.OpenWithUpgrade(projectPath); //exception ako je vec otvoren
}
Subnet subnetSet = project.Subnets.Create("System:Subnet.Ethernet", "subnetSet");
}
public void CloseProject()
{
project.Close();
}
public void CreateGsdDevice()
{
//plcDevice = project.Devices.CreateWithItem(plctypeIdentifier, plcName, plcdeviceName);
CaxProvider caxProvider = project.GetService<CaxProvider>();
MessageBox.Show(caxProvider.ToString());
//string gsdOrderNumber = "6410038040802";
//string gsdDeviceID = "M";
//string gsdDeviceVersion = "V3.2.0";
string gsdTypeIdentifier = "GSD:" + getDeviceOrderNumber + ".XML/" + getDeviceVersion;
Device gsdDevice = project.Devices.CreateWithItem(gsdTypeIdentifier, getDeviceName, getDeviceName);
var gsdDeviceList = new List<Device>();
gsdDeviceList.Add(gsdDevice);
//not supported
DeviceItem gsdProfinet = plcDeviceItem.DeviceItems.FirstOrDefault(DeviceItem => DeviceItem.Name.Contains("PROFINET")); //dodat da uzme name od Ip-a
//networkInterface = ((IEngineeringServiceProvider)plcProfinet).GetService<NetworkInterface>(); //radi samo zeza za HMI IP adresu
if (networkInterface != null)
{
NodeComposition nodesGsd = networkInterface.Nodes;
InterfaceOperatingModes modeGsd = networkInterface.InterfaceOperatingMode;
foreach (Node node in networkInterface.Nodes)
{
if (node != null)
{
foreach (EngineeringAttributeInfo nodeInfo in node.GetAttributeInfos())
{
//node.CreateAndConnectToSubnet(getSubnetMask);
node.SetAttribute("Address", getDeviceIpAddress);
node.SetAttribute("SubnetMask", getSubnetMask);
//node.ConnectToSubnet(project.Subnets.First()); //radi samo treab postavit subnetset prije pokretaanja
//networkInterface.Nodes.Last().ConnectToSubnet(subnetSet);
}
}
}
}
}
public void CreateHMI(string hmiName)
{
string hmiVersion = "17.0.0.0";
string hmiOrderNumber = "6AV2 124-0QC02-0AX1"; //enumeracja preko deviceComposition str274
string hmitypeIdentifier = "OrderNumber:" + hmiOrderNumber + "/" + hmiVersion;
hmiDevice = project.Devices.CreateWithItem(hmitypeIdentifier, hmiName, hmiName);
}
public void CreateDevice()
{
//getDeviceVersion = "V2.8"; // dodat da se iz txt (xlsx ili pdf) povuce verzija
//getDeviceOrderNumber = "6ES7 518-4FP00-0AB0"; //dodat da se iz txt (xlsx ili pdf) povuce broj
string deviceTypeIdentifier = "OrderNumber:" + getDeviceOrderNumber + "/" + getDeviceVersion; //dodat gsdDevice i da se preko browsera upiše adresa gsd-a
//anydeviceName = "Name" + deviceName;
anyDevice = project.Devices.CreateWithItem(deviceTypeIdentifier, getDeviceName, getDeviceName);
DeviceList.Add(anyDevice);
plcDeviceItem = anyDevice.DeviceItems.FirstOrDefault(Device => Device.Name.Equals(getDeviceName));
}
//public void CreateGlobalSubnet()
// {
// Subnet subnetSet = project.Subnets.Create("System:Subnet.Ethernet", "subnetSet"); // could not set the name
// foreach (Node node in networkInterface.Nodes)
// {
// node.ConnectToSubnet(subnetSet);
// }
// }
// Returns PlcSoftware
public PlcSoftware GetPlcSoftware(Device device)
{
DeviceItemComposition deviceItemComposition = plcDeviceItem.DeviceItems;
foreach (DeviceItem deviceItem in deviceItemComposition)
{
SoftwareContainer softwareContainer = deviceItem.GetService<SoftwareContainer>();
if (softwareContainer != null)
{
Software softwareBase = softwareContainer.Software;
PlcSoftware plcSoftware = softwareBase as PlcSoftware;
return plcSoftware;
}
DeviceItem plcProfinet = plcDeviceItem.DeviceItems.FirstOrDefault(DeviceItem => DeviceItem.Name.Contains("PROFINET")); //dodat da uzme name od Ip-a
//networkInterface = ((IEngineeringServiceProvider)plcProfinet).GetService<NetworkInterface>(); //radi samo zeza za HMI IP adresu
if (networkInterface != null)
{
NodeComposition nodes = networkInterface.Nodes;
InterfaceOperatingModes mode = networkInterface.InterfaceOperatingMode;
//networkInterface.InterfaceOperatingMode = InterfaceOperatingModes.IoDevice;
//networkInterface.InterfaceType = NetType.Profibus;
//networkInterface.Nodes.First().ConnectToSubnet(subnetSet);
foreach (Node node in networkInterface.Nodes)
{
if (node != null)
{
foreach (EngineeringAttributeInfo nodeInfo in node.GetAttributeInfos())
{
//node.CreateAndConnectToSubnet(getSubnetMask);
node.SetAttribute("SubnetMask", getSubnetMask);
node.SetAttribute("Address", getDeviceIpAddress);
//node.ConnectToSubnet(project.Subnets.First()); //radi samo treab postavit subnetset prije pokretaanja
//networkInterface.Nodes.Last().ConnectToSubnet(subnetSet);
}
}
}
}
}
return null;
}
public void CreateSubnet()
{
//var howmanysubnets = project.Subnets.Count;
//MessageBox.Show(howmanysubnets.ToString());
foreach (Node node in networkInterface.Nodes)
{
if (node != null)
{
foreach (EngineeringAttributeInfo nodeInfo in node.GetAttributeInfos())
{
node.CreateAndConnectToSubnet("subnetSet"); //device is already connected to subnet error
//node.ConnectToSubnet(subnetSet);
}
}
}
}
public void ConnectSubnet()
{
foreach (Node node in networkInterface.Nodes)
{
if (node != null)
{
try
{
node.ConnectToSubnet(project.Subnets.First());
}
catch (Exception)
{
MessageBox.Show("Subnet connection error");
}
}
}
}
//Checks whether a device is of type hmitarget
public HmiTarget GetHmiTarget(Device device)
{
DeviceItemComposition deviceItemComposition = device.DeviceItems;
foreach (DeviceItem deviceItem in deviceItemComposition)
{
//MessageBox.Show(deviceItem.ToString());
SoftwareContainer softwareContainer = deviceItem.GetService<SoftwareContainer>();
if (softwareContainer != null)
{
Software softwareBase = softwareContainer.Software;
hmiTarget = softwareBase as HmiTarget;
//MessageBox.Show("HMITARGET:" + hmiTarget.ToString());
return hmiTarget;
}
plcDeviceItem.GetService<NetworkInterface>();
DeviceItem hmiDeviceItem = plcDeviceItem.Items.First(DeviceItem => DeviceItem.Name.Contains("Address")); //Name.Contains("HMI_1.IE_CP_1"); //dodat da uzme name od Ip-a
//NetworkInterface networkInterface = ((IEngineeringServiceProvider)hmiDeviceItem).GetService<NetworkInterface>();
Node node1 = networkInterface.Nodes.First();
var attributeNames = new[] { "Address", "SubnetMask"}; // "RouterAddress", "UseRouter", "DhcpClientId", "IpProtocolSelection"
foreach (var attributeName in attributeNames)
{
object attributeValue = ((IEngineeringObject)node1).GetAttribute(attributeName);
//MessageBox.Show(attributeValue.ToString());
//MessageBox.Show(attributeName.ToString());
}
// networkInterface.Nodes.First().CreateAndConnectToSubnet("getSubnetMask");
networkInterface.Nodes[0].SetAttribute("getSubnetMask", getSubnetMask);
networkInterface.Nodes[0].SetAttribute("Address", getDeviceIpAddress);
//networkInterface.SetAttribute("Address", getDeviceIpAddress);
//if (networkInterface != null)
//{
// foreach (Node node in networkInterface.Nodes)
// {
// //MessageBox.Show("nodetype:" + "" + node.NodeType.GetType());
// //MessageBox.Show("nodeId:" + "" + node.NodeId.FirstOrDefault());
// //MessageBox.Show("node:" + "" + node.Name.FirstOrDefault());
// node.SetAttribute("Address", getDeviceIpAddress);
// if (node != null)
// {
// foreach (EngineeringAttributeInfo nodeInfo in node.GetAttributeInfos())
// {
// if (nodeInfo != null && nodeInfo.Name == "Address")
// {
// //node.ConnectToSubnet(getSubnetMask);
// node.SetAttribute("SubnetMask", getSubnetMask);
// node.SetAttribute("Address", getDeviceIpAddress);
// node.ConnectToSubnet(project.Subnets.First());
// }
// //hmi?.Interfaces.FirstOrDefault(i => i.InterfaceType == DeviceInterfaceType.Ethernet);
// //interfaceObj?.IPv4Address.Address = "192.168.1.100";
// //interfaceObj?.IPv4Address.SubnetMask = "255.255.255.0";
// }
// }
// }
//}
}
return null;
}
//public void AddInterface(string ipAddress, string subnetMask, string gateway)
//{
// Interface @interface = new Interface(ipAddress, subnetMask, gateway);
// this.Interfaces.Add(@interface);
//}
public struct _IoCard
{
public string IoName;
public string IoPosition;
public string IoIdentifier;
public _IoCard(string _name, string _identifier, string _position)
{
IoName = _name;
IoPosition = _position;
IoIdentifier = _identifier;
}
}
public static IList<Tuple<_Device, IList<_IoCard>>> Devices;
//private void IoDevice(IList<Tuple<Controller._Device, IList<Controller._IoCard>>> devices) //devices, name, //Ne treba, ovo je plc
//{
// var subDevice = new List<Device>();
// //var subnet = project.Subnets.Create("System:Subnet.Ethernet", "GlobalNetwork"); //ne treba subnet!
// foreach(var d in devices)
// {
// var device = project.UngroupedDevicesGroup.Devices.CreateWithItem("OrderNumber:" + getDeviceOrderNumber, getDeviceName, getDeviceName );
// subDevice.Add(device);
// FindAnyAttributeSet(device.DeviceItems, "Author", "Ivan Nusdorfer");
// FillIoController(device, d.Item2); //mozda maknut .item2 i pustit samo d
// //var network = FindNetworkInterface(device.DeviceItems);
// //network.Nodes.Last().ConnectToSubnet(subnet);
// }
//}
public int positionNumber;
public string cardTypeId;
public string cardName;
public void FillIoController(Device device, IList<Controller._IoCard> controller)
{
int index = 0;
DeviceItem rail = FindRail(device.DeviceItems);
var name = FindRail(device.DeviceItems).Name;
foreach (var card in controller)
{
if (card.IoName.Equals(string.Empty)) continue;
for (int i = index; i < controller.Count; i++) //dodat dolje nesto kod ioidentifier, vjv ne ako je u pitanju citanje podataka
{
if (!rail.CanPlugNew("OrderNumber:" + card.IoIdentifier, card.IoName + "_" + card.IoPosition, i)) continue;
index = i;
rail = device.PlugNew("OrderNumber:6ES7 400-1TA01-0AA0", device.DeviceItems + Guid.NewGuid().ToString(), 0);
rail.PlugNew("OrderNumber:" + card.IoIdentifier, card.IoName + "_" + card.IoPosition, i); break;
}
}
}
#region Help
public DeviceItem FindRail(DeviceItemComposition devices)
{
foreach(var item in devices)
{
if (item.Name.Contains("Rack")) return item;
return FindRail(item.DeviceItems);
}
return null;
}
public NetworkInterface FindNetworkInterface(DeviceItemComposition devices)
{
NetworkInterface network = null;
foreach(var device in devices)
{
if (network != null) continue;
network = device.GetService<NetworkInterface>();
if(network != null)
{
if (FindAnyAttributeGet(device, "InterfaceType") != "Ethernet") network = null;
else if (network.Nodes == null) network = null;
else if (network.Nodes.Count == 0) network = null;
}
if (network == null) network = FindNetworkInterface(device.DeviceItems);
}
return network;
}
public string FindAnyAttributeGet(DeviceItem device, string attribute)
{
var list = device.GetAttributeInfos();
foreach( var item in list)
{
if (item.Name.Equals(attribute))
{
return device.GetAttribute(attribute).ToString();
}
}
return string.Empty;
}
public string FindAnyAttributeSet(DeviceItemComposition devices, string attribute, object value)
{
foreach (var d in devices)
{
var list = d.GetAttributeInfos();
foreach(var item in list)
{
if (item.Name.Equals(attribute))
d.SetAttribute(attribute, value);
}
}
return string.Empty;
}
}
}
#endregion Help end