Browse Source

driverset in tagconfig use propertygrid

pull/15/head
Gavin 8 years ago
parent
commit
c672c428a2
  1. BIN
      SCADA/Database/db2014.bak
  2. BIN
      SCADA/Database/script.sql
  3. BIN
      SCADA/Example/BatchCoreTest.exe
  4. 25
      SCADA/Example/BatchCoreTest.exe.config
  5. BIN
      SCADA/Example/ClientDriver.dll
  6. BIN
      SCADA/Example/CoreTest.exe
  7. BIN
      SCADA/Example/DataHelper.dll
  8. BIN
      SCADA/Example/DataService.dll
  9. BIN
      SCADA/Example/TagConfig.exe
  10. 25
      SCADA/Program/BatchCoreService/App.config
  11. 10
      SCADA/Program/BatchCoreService/BatchCoreService.csproj
  12. 281
      SCADA/Program/BatchCoreService/DAService.cs
  13. 25
      SCADA/Program/BatchCoreTest/App.config
  14. 5
      SCADA/Program/BatchCoreTest/BatchCoreTest.csproj
  15. 5
      SCADA/Program/ClientDriver/ClientDriver.cs
  16. 19
      SCADA/Program/CoreTest/ClientService.cs
  17. 3
      SCADA/Program/DataService/IServer.cs
  18. 22
      SCADA/Program/FileDriver/DatabaseDriver.cs
  19. 8
      SCADA/Program/FileDriver/MemoryDriver.cs
  20. 4
      SCADA/Program/FileDriver/TagDriver.cs
  21. 37
      SCADA/Program/ModbusDriver/ModbusRTUDriver.cs
  22. 9
      SCADA/Program/ModbusDriver/ModbusTCPDriver.cs
  23. 18
      SCADA/Program/OPCDriver/OPCDriver.cs
  24. 41
      SCADA/Program/OmronPlcDriver/OmronUdpReader.cs
  25. 17
      SCADA/Program/PanasonicDriver/PanasonicSerialReader.cs
  26. 30
      SCADA/Program/SiemensPLCDriver/SiemensPLCDriver.cs
  27. 173
      SCADA/Program/TagConfig/TagConfig/DriverSet.Designer.cs
  28. 95
      SCADA/Program/TagConfig/TagConfig/DriverSet.cs
  29. 111
      SCADA/Program/TagConfig/TagConfig/Form1.cs
  30. 2
      SCADA/Program/TagConfig/TagConfig/Properties/Resources.Designer.cs
  31. 4
      SCADA/Program/TagConfig/TagConfig/Properties/Settings.Designer.cs
  32. 3
      SCADA/Program/TagConfig/TagConfig/TagConfig.csproj
  33. 294
      SCADA/Program/TagConfig/TagConfig/TagData.cs
  34. 2
      SCADA/Program/TagConfig/TagConfig/app.config
  35. BIN
      SCADA/dll/DataService.dll
  36. BIN
      SCADA/dll/FileDriver.dll
  37. BIN
      SCADA/dll/ModbusDriver.dll
  38. BIN
      SCADA/dll/OPCDriver.dll
  39. BIN
      SCADA/dll/OmronPlcDriver.dll
  40. BIN
      SCADA/dll/PanasonicDriver.dll
  41. BIN
      SCADA/dll/SiemensPLCDriver.dll

BIN
SCADA/Database/db2014.bak

Binary file not shown.

BIN
SCADA/Database/script.sql

Binary file not shown.

BIN
SCADA/Example/BatchCoreTest.exe

Binary file not shown.

25
SCADA/Example/BatchCoreTest.exe.config

@ -7,32 +7,9 @@
<services>
<!-- This section is optional with the new configuration model
introduced in .NET Framework 4. -->
<service name="BatchCoreService.DAService" behaviorConfiguration="DAServiceBehavior">
<host>
<baseAddresses>
<add baseAddress="http://localhost:8000/SCADA/service"/>
</baseAddresses>
</host>
<!-- this endpoint is exposed at the base address provided by host: http://localhost:8000/SCADA/service -->
<endpoint address="" binding="basicHttpBinding" bindingConfiguration="Binding1" bindingNamespace="http://BatchCoreService" contract="BatchCoreService.IDataExchangeService"/>
<!-- the mex endpoint is exposed at http://localhost:8000/SCADA/service/mex -->
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
<service name="BatchCoreService.DAService" >
</service>
</services>
<bindings>
<basicHttpBinding>
<binding name="Binding1" sendTimeout="00:10:00" transferMode="Streamed" messageEncoding="Text" textEncoding="utf-8" maxReceivedMessageSize="9223372036854775807">
</binding>
</basicHttpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior name="DAServiceBehavior">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="False"/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>

BIN
SCADA/Example/ClientDriver.dll

Binary file not shown.

BIN
SCADA/Example/CoreTest.exe

Binary file not shown.

BIN
SCADA/Example/DataHelper.dll

Binary file not shown.

BIN
SCADA/Example/DataService.dll

Binary file not shown.

BIN
SCADA/Example/TagConfig.exe

Binary file not shown.

25
SCADA/Program/BatchCoreService/App.config

@ -7,32 +7,9 @@
<services>
<!-- This section is optional with the new configuration model
introduced in .NET Framework 4. -->
<service name="BatchCoreService.DAService" behaviorConfiguration="DAServiceBehavior">
<host>
<baseAddresses>
<add baseAddress="http://localhost:8000/SCADA/service"/>
</baseAddresses>
</host>
<!-- this endpoint is exposed at the base address provided by host: http://localhost:8000/SCADA/service -->
<endpoint address="" binding="basicHttpBinding" bindingConfiguration="Binding1" bindingNamespace="http://BatchCoreService" contract="BatchCoreService.IDataExchangeService"/>
<!-- the mex endpoint is exposed at http://localhost:8000/SCADA/service/mex -->
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
<service name="BatchCoreService.DAService">
</service>
</services>
<bindings>
<basicHttpBinding>
<binding name="Binding1" sendTimeout="00:10:00" transferMode="Streamed" messageEncoding="Text" textEncoding="utf-8" maxReceivedMessageSize="9223372036854775807">
</binding>
</basicHttpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior name="DAServiceBehavior">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="False"/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>

10
SCADA/Program/BatchCoreService/BatchCoreService.csproj

@ -41,7 +41,6 @@
<Reference Include="System.Data" />
<Reference Include="System.Management" />
<Reference Include="System.ServiceModel" />
<Reference Include="System.ServiceModel.Web" />
<Reference Include="System.ServiceProcess" />
<Reference Include="System.Windows.Forms" />
<Reference Include="System.Xml" />
@ -78,12 +77,6 @@
<Name>DataService</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<None Include="App.config">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<SubType>Designer</SubType>
</None>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="BatchCoreService.resx">
<DependentUpon>BatchCoreService.cs</DependentUpon>
@ -92,6 +85,9 @@
<DependentUpon>ProjectInstaller.cs</DependentUpon>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.

281
SCADA/Program/BatchCoreService/DAService.cs

@ -6,6 +6,7 @@ using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
@ -19,36 +20,8 @@ using System.Xml;
namespace BatchCoreService
{
[ServiceContract(Namespace = "http://BatchCoreService")]
public interface IDataExchangeService
{
[OperationContract]
string Read(string id);
[OperationContract]
bool ReadExpression(string expression);
[OperationContract]
int Write(string id, string value);
[OperationContract]
Dictionary<string, string> BatchRead(string[] tags);
[OperationContract]
int BatchWrite(Dictionary<string, string> tags);
[OperationContract]
Stream LoadMetaData();
[OperationContract]
Stream LoadHdaBatch(DateTime start, DateTime end);
[OperationContract]
Stream LoadHdaSingle(DateTime start, DateTime end, short id);
}
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, Namespace = "http://BatchCoreService")]
public class DAService : IDataExchangeService, IDataServer, IAlarmServer
public class DAService : IDataServer, IAlarmServer
{
const int PORT = 6543;
@ -138,6 +111,7 @@ namespace BatchCoreService
bool _hasHda = false;
List<HistoryData> _hda;
List<DriverArgumet> _arguments = new List<DriverArgumet>();
Dictionary<short, ArchiveTime> _archiveTimes = new Dictionary<short, ArchiveTime>();
Socket tcpServer = null;
@ -420,9 +394,12 @@ namespace BatchCoreService
if (dataReader == null) return;// Stopwatch sw = Stopwatch.StartNew();
while (dataReader.Read())
{
AddDriver(dataReader.GetInt16(0), dataReader.GetNullableString(1),
dataReader.GetNullableString(2), dataReader.GetInt32(3), dataReader.GetNullableString(4), dataReader.GetNullableString(5),
dataReader.GetNullableString(6), dataReader.GetNullableString(7));
_arguments.Add(new DriverArgumet(dataReader.GetInt16(0), dataReader.GetNullableString(1), dataReader.GetNullableString(2)));
}
dataReader.NextResult();
while (dataReader.Read())
{
AddDriver(dataReader.GetInt16(0), dataReader.GetNullableString(1), dataReader.GetNullableString(2), dataReader.GetNullableString(3));
}
dataReader.NextResult();
@ -1493,8 +1470,7 @@ namespace BatchCoreService
}
}
public IDriver AddDriver(short id, string name, string server, int timeOut,
string assembly, string className, string spare1, string spare2)
public IDriver AddDriver(short id, string name, string assembly, string className)
{
if (_drivers.ContainsKey(id))
return _drivers[id];
@ -1505,9 +1481,25 @@ namespace BatchCoreService
var dvType = ass.GetType(className);
if (dvType != null)
{
dv = Activator.CreateInstance(dvType, new object[] { this, id, name, server, timeOut, spare1, spare2 }) as IDriver;
dv = Activator.CreateInstance(dvType, new object[] { this, id, name }) as IDriver;
if (dv != null)
{
foreach (var arg in _arguments)
{
if (arg.DriverID == id)
{
var prop = dvType.GetProperty(arg.PropertyName);
if (prop != null)
{
if (prop.PropertyType.IsEnum)
prop.SetValue(dv, Enum.Parse(prop.PropertyType, arg.PropertyValue), null);
else
prop.SetValue(dv, Convert.ChangeType(arg.PropertyValue, prop.PropertyType, CultureInfo.CreateSpecificCulture("en-US")), null);
}
}
}
_drivers.Add(id, dv);
}
}
}
catch (Exception e)
@ -1859,228 +1851,63 @@ namespace BatchCoreService
}
return 1;
}
#endregion
#region DataExchange(数据交换服务器)
public Dictionary<string, string> BatchRead(string[] tags)
public string Read(string id)
{
var itags = new List<ITag>(tags.Length);
for (int i = 0; i < tags.Length; i++)
{
var tag = this[tags[i]];
if (tag != null)
itags.Add(tag);
}
var ds = new Dictionary<string, string>(tags.Length);
foreach (var tag in itags)
{
string obj;
if (tag.Address.VarType == DataType.FLOAT && Math.Abs(tag.Value.Single) < 5 * 10E-33)
{
obj = "0";
}
else obj = tag.ToString();
ds.Add(tag.GetTagName(), obj ?? "");//此处大小写应注意与元数据表一致。
}
return ds;
throw new NotImplementedException();
}
public int BatchWrite(Dictionary<string, string> tags)
public bool ReadExpression(string expression)
{
var dict = new Dictionary<string, object>();
foreach (var tag in tags)
{
dict.Add(tag.Key, tag.Value);
}
return BatchWrite(dict, true);
throw new NotImplementedException();
}
public string Read(string id)
public int Write(string id, string value)
{
var tag = this[id];
return tag == null ? string.Empty : tag.Address.VarType == DataType.BOOL ? tag.Value.Boolean ? "1" : "0" : tag.ToString();
throw new NotImplementedException();
}
public int Write(string id, string value)
public Dictionary<string, string> BatchRead(string[] tags)
{
var tag = this[id];
return tag == null ? -1 : tag.Write(value);
throw new NotImplementedException();
}
Dictionary<string, Func<bool>> _exprdict = new Dictionary<string, Func<bool>>();
public bool ReadExpression(string expression)
public int BatchWrite(Dictionary<string, string> tags)
{
Func<bool> func;
if (_exprdict.TryGetValue(expression, out func))
{
return func();
}
else
{
func = Eval.Eval(expression) as Func<bool>;
if (func != null)
{
_exprdict[expression] = func;
return func();
}
else return false;
}
throw new NotImplementedException();
}
public Stream LoadMetaData()
{
var stream = new MemoryStream(); // var sb = new StringBuilder();
using (var writer = XmlTextWriter.Create(stream))
{
writer.WriteStartDocument();
writer.WriteStartElement("Sever");
foreach (var device in _drivers.Values)
{
writer.WriteStartElement("Device");
writer.WriteAttributeString("id", device.ID.ToString());
writer.WriteAttributeString("name", device.Name);
if (!string.IsNullOrEmpty(device.ServerName))
writer.WriteAttributeString("server", device.ServerName);
writer.WriteAttributeString("timeout", device.TimeOut.ToString());
foreach (var grp in device.Groups)
{
writer.WriteStartElement("Group");
writer.WriteAttributeString("id", grp.ID.ToString());
writer.WriteAttributeString("name", grp.Name);
writer.WriteAttributeString("deviceId", device.ID.ToString());
writer.WriteAttributeString("updateRate", grp.UpdateRate.ToString());
writer.WriteAttributeString("deadBand", grp.DeadBand.ToString());
writer.WriteAttributeString("active", grp.IsActive.ToString());
var list = _list.FindAll(x => x.GroupID == grp.ID);
if (list != null && list.Count > 0)
{
foreach (var tag in list)
{
writer.WriteStartElement("Tag");
writer.WriteAttributeString("id", tag.ID.ToString());
writer.WriteAttributeString("groupid", tag.GroupID.ToString());
writer.WriteAttributeString("name", tag.Name);
writer.WriteAttributeString("address", tag.Address);
writer.WriteAttributeString("datatype", ((byte)tag.DataType).ToString());
writer.WriteAttributeString("size", tag.Size.ToString());
writer.WriteAttributeString("archive", tag.Archive.ToString());
writer.WriteAttributeString("min", tag.Minimum.ToString());
writer.WriteAttributeString("max", tag.Maximum.ToString());
writer.WriteAttributeString("cycle", tag.Cycle.ToString());
writer.WriteEndElement();
}
}
writer.WriteEndElement();
}
writer.WriteEndElement();
}
writer.WriteStartElement("Conditions");
foreach (var cond in _conditions)
{
writer.WriteStartElement("Condition");
writer.WriteAttributeString("id", cond.ID.ToString());
writer.WriteAttributeString("alarmtype", ((int)cond.AlarmType).ToString());
writer.WriteAttributeString("enabled", cond.IsEnabled.ToString());
writer.WriteAttributeString("severity", ((int)cond.Severity).ToString());
writer.WriteAttributeString("source", cond.Source);
writer.WriteAttributeString("comment", cond.Comment);
writer.WriteAttributeString("conditiontype", ((byte)cond.ConditionType).ToString());
writer.WriteAttributeString("para", cond.Para.ToString());
writer.WriteAttributeString("deadband", cond.DeadBand.ToString());
writer.WriteAttributeString("delay", cond.Delay.ToString());
foreach (var subcond in cond.SubConditions)
{
if (subcond.SubAlarmType != SubAlarmType.None)
{
writer.WriteStartElement("SubCondition");
writer.WriteAttributeString("subalarmtype", ((int)subcond.SubAlarmType).ToString());
writer.WriteAttributeString("enabled", subcond.IsEnabled.ToString());
writer.WriteAttributeString("severity", ((int)subcond.Severity).ToString());
writer.WriteAttributeString("threshold", subcond.Threshold.ToString());
writer.WriteAttributeString("message", subcond.Message);
writer.WriteEndElement();
}
}
writer.WriteEndElement();
}
writer.WriteEndElement();
writer.WriteStartElement("Scales");
foreach (var scale in _scales)
{
writer.WriteStartElement("Scale");
writer.WriteAttributeString("id", scale.ID.ToString());
writer.WriteAttributeString("scaletype", ((byte)scale.ScaleType).ToString());
writer.WriteAttributeString("euhi", scale.EUHi.ToString());
writer.WriteAttributeString("eulo", scale.EULo.ToString());
writer.WriteAttributeString("rawhi", scale.RawHi.ToString());
writer.WriteAttributeString("rawlo", scale.RawLo.ToString());
writer.WriteEndElement();
}
writer.WriteEndElement();
if (ArchiveList != null)
{
writer.WriteStartElement("ArchiveList");
foreach (var archv in _archiveList)
{
writer.WriteStartElement("Archive");
writer.WriteAttributeString("id", archv.Key.ToString());
writer.WriteAttributeString("desp", archv.Value);
writer.WriteEndElement();
}
writer.WriteEndElement();
}
writer.WriteEndElement();
}
stream.Position = 0L;
return stream;
throw new NotImplementedException();
}
public Stream LoadHdaBatch(DateTime start, DateTime end)
{
List<byte> list = new List<byte>();
var result = GetHData(start, end);
short tempid = short.MinValue;
ITag tag = null;
byte[] idarray = new byte[2];
foreach (var data in result)
{
if (tempid != data.ID)
{
tempid = data.ID;
idarray = BitConverter.GetBytes(tempid);
tag = this[tempid];
}
if (tag == null) continue;
list.AddRange(idarray);
list.AddRange(tag.ToByteArray(data.Value));
list.AddRange(BitConverter.GetBytes(data.TimeStamp.ToFileTime()));
}
list.AddRange(new byte[] { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF});
return new MemoryStream(list.ToArray());
throw new NotImplementedException();
}
public Stream LoadHdaSingle(DateTime start, DateTime end, short id)
{
var tag = this[id];
if (tag == null) return new MemoryStream();
List<byte> list = new List<byte>();
var result = GetHData(start, end, id);
list.AddRange(BitConverter.GetBytes(id));
foreach (var data in result)
{
list.AddRange(tag.ToByteArray(data.Value));
list.AddRange(BitConverter.GetBytes(data.TimeStamp.ToFileTime()));
}
list.AddRange(new byte[] { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF});
return new MemoryStream(list.ToArray());
throw new NotImplementedException();
}
#endregion
}
class DriverArgumet
{
public short DriverID;
public string PropertyName;
public string PropertyValue;
public DriverArgumet(short id, string name, string value)
{
DriverID = id;
PropertyName = name;
PropertyValue = value;
}
}
class TempCachedData
{
IPAddress _addr;

25
SCADA/Program/BatchCoreTest/App.config

@ -7,32 +7,9 @@
<services>
<!-- This section is optional with the new configuration model
introduced in .NET Framework 4. -->
<service name="BatchCoreService.DAService" behaviorConfiguration="DAServiceBehavior">
<host>
<baseAddresses>
<add baseAddress="http://localhost:8000/SCADA/service"/>
</baseAddresses>
</host>
<!-- this endpoint is exposed at the base address provided by host: http://localhost:8000/SCADA/service -->
<endpoint address="" binding="basicHttpBinding" bindingConfiguration="Binding1" bindingNamespace="http://BatchCoreService" contract="BatchCoreService.IDataExchangeService"/>
<!-- the mex endpoint is exposed at http://localhost:8000/SCADA/service/mex -->
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
<service name="BatchCoreService.DAService" >
</service>
</services>
<bindings>
<basicHttpBinding>
<binding name="Binding1" sendTimeout="00:10:00" transferMode="Streamed" messageEncoding="Text" textEncoding="utf-8" maxReceivedMessageSize="9223372036854775807">
</binding>
</basicHttpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior name="DAServiceBehavior">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="False"/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>

5
SCADA/Program/BatchCoreTest/BatchCoreTest.csproj

@ -43,7 +43,6 @@
<Reference Include="System" />
<Reference Include="System.Data" />
<Reference Include="System.ServiceModel" />
<Reference Include="System.ServiceModel.Web" />
<Reference Include="System.Xml" />
<Reference Include="System.Core" />
</ItemGroup>
@ -76,9 +75,7 @@
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
</EmbeddedResource>
<None Include="App.config">
<SubType>Designer</SubType>
</None>
<None Include="App.config" />
<None Include="Properties\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<LastGenOutput>Settings.Designer.cs</LastGenOutput>

5
SCADA/Program/ClientDriver/ClientDriver.cs

@ -68,14 +68,11 @@ namespace ClientDriver
get { return _server; }
}
public ClientReader(IDataServer server, short id, string name, string ip, int timeout)
public ClientReader(IDataServer server, short id, string name)
{
_id = id;
_server = server;
_ip = ip;
_name = name;
_timeout = timeout;
Connect();
}
public bool Connect()

19
SCADA/Program/CoreTest/ClientService.cs

@ -1,13 +1,12 @@
using System;
using ClientDriver;
using DatabaseLib;
using DataService;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using ClientDriver;
using DatabaseLib;
using DataService;
namespace CoreTest
{
@ -125,7 +124,10 @@ namespace CoreTest
void InitClient()
{
string sLine = DataHelper.HostName;
AddDriver(1, "Client1", string.IsNullOrEmpty(sLine) ? Environment.MachineName : sLine, 20000, null, null, null, null);
var cdrv = AddDriver(1, "Client1", null, null);
cdrv.ServerName = string.IsNullOrEmpty(sLine) ? Environment.MachineName : sLine;
cdrv.TimeOut = 20000;
cdrv.Connect();
}
void InitConnection()
@ -285,12 +287,11 @@ namespace CoreTest
return group.BatchWrite(dict, sync);
}
public IDriver AddDriver(short id, string name, string server, int timeOut,
string assembly, string className, string spare1, string spare2)
public IDriver AddDriver(short id, string name, string assembly, string className)
{
if (reader == null)
{
reader = new ClientReader(this, id, name, server, timeOut);//server应为远程主机名/IP,从本地字符串解析获取
reader = new ClientReader(this, id, name);//server应为远程主机名/IP,从本地字符串解析获取
}
return reader;
}

3
SCADA/Program/DataService/IServer.cs

@ -36,8 +36,7 @@ namespace DataService
IList<Scaling> ScalingList { get; }
IEnumerable<IDriver> Drivers { get; }
IEnumerable<string> BrowseItems(BrowseType browseType, string tagName, DataType dataType);
IDriver AddDriver(short id, string name, string server, int timeOut,
string assembly, string className, string spare1, string spare2);
IDriver AddDriver(short id, string name, string assembly, string className);
IGroup GetGroupByName(string name);
int GetScaleByID(short id);
int GetItemProperties(short id);//返回的是元数据在元数据列表的索引

22
SCADA/Program/FileDriver/DatabaseDriver.cs

@ -46,7 +46,7 @@ namespace FileDriver
}
}
string _serverIP;
string _serverIP = ".";
public string ServerName
{
get
@ -97,28 +97,22 @@ namespace FileDriver
get { return _server; }
}
public DataBaseReader(IDataServer parent, short id, string name, string server = ".", int timeOut = 2, string databaseName = "SharpSCADA", string ins = null)
public DataBaseReader(IDataServer parent, short id, string name)
{
_id = id;
_name = name;
_server = parent;
_database = databaseName;
_serverIP = server;
_ins = ins;
_timeOut = timeOut / 1000;
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
builder.DataSource = (ins == null ? server : string.Format(@"{0}\{1}", _serverIP, _ins));
builder.InitialCatalog = _database;
builder.ConnectTimeout = _timeOut;
builder.IntegratedSecurity = true;
m_ConnStr = builder.ConnectionString;
}
string m_ConnStr;
SqlConnection m_Conn;
public bool Connect()
{
m_Conn = new SqlConnection(m_ConnStr);
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
builder.DataSource = (_ins == null ? _serverIP : string.Format(@"{0}\{1}", _serverIP, _ins));
builder.InitialCatalog = _database;
builder.ConnectTimeout = _timeOut;
builder.IntegratedSecurity = true;
m_Conn = new SqlConnection(builder.ConnectionString);
//mySqlConnection.ConnectionTimeout = 1;//设置连接超时的时间,写在连接字符串内
try
{

8
SCADA/Program/FileDriver/MemoryDriver.cs

@ -100,17 +100,13 @@ namespace FileDriver
int _count = 0;
MemoryMappedFile mapp = null;
MemoryMappedViewAccessor accessor = null;
SortedList<short, int> psList;
SortedList<short, int> psList = new SortedList<short, int>();
public MemoryReader(IDataServer parent, short id, string name, string server, int timeOut, string fileName = null, string spare2 = null)
public MemoryReader(IDataServer parent, short id, string name)
{
_parent = parent;
_id = id;
_name = name;
_fileName = fileName;
_server = server;
_timeOut = timeOut;
psList = new SortedList<short, int>();
}
public bool Connect()

4
SCADA/Program/FileDriver/TagDriver.cs

@ -82,13 +82,11 @@ namespace FileDriver
get { return _parent; }
}
public TagDriver(IDataServer parent, short id, string name, string server, int timeOut, string spare1 = null, string spare2 = null)
public TagDriver(IDataServer parent, short id, string name)
{
_parent = parent;
_id = id;
_name = name;
_server = server;
_timeOut = timeOut;
}
public bool Connect()

37
SCADA/Program/ModbusDriver/ModbusRTUDriver.cs

@ -32,17 +32,18 @@ namespace ModbusDriver
}
}
string _port;
string _port = "COM1";
public string ServerName
{
get { return _port; }
set { _port = value; }
}
public bool IsClosed
{
get
{
return _serialPort.IsOpen == false;
return _serialPort == null ? false : _serialPort.IsOpen == false;
}
}
@ -53,6 +54,13 @@ namespace ModbusDriver
set { _timeOut = value; }
}
private int _baudRate = 9600;
public int BaudRate
{
get { return _baudRate; }
set { _baudRate = value; }
}
List<IGroup> _grps = new List<IGroup>();
public IEnumerable<IGroup> Groups
{
@ -64,10 +72,19 @@ namespace ModbusDriver
{
get { return _server; }
}
public bool Connect()
{
try
{
if (_serialPort == null)
_serialPort = new SerialPort(_port);
_serialPort.ReadTimeout = _timeOut;
_serialPort.WriteTimeout = _timeOut;
_serialPort.BaudRate = _baudRate;
_serialPort.DataBits = 8;
_serialPort.Parity = Parity.Even;
_serialPort.StopBits = StopBits.One;
_serialPort.Open();
return true;
}
@ -96,20 +113,11 @@ namespace ModbusDriver
public event ShutdownRequestEventHandler OnClose;
#endregion
//自定义构造函数3
public ModbusRTUReader(IDataServer server, short id, string name, string port = "COM1", int timeOut = 10000, string spare1 = "0", string baudRate = "9600")
public ModbusRTUReader(IDataServer server, short id, string name)
{
_id = id;
_name = name;
_server = server;
_port = port;
_serialPort = new SerialPort(port);
_timeOut = timeOut;
_serialPort.ReadTimeout = _timeOut;
_serialPort.WriteTimeout = _timeOut;
_serialPort.BaudRate = int.Parse(baudRate);
_serialPort.DataBits = 8;
_serialPort.Parity = Parity.Even;
_serialPort.StopBits = StopBits.One;
}
private SerialPort _serialPort;
@ -222,7 +230,7 @@ namespace ModbusDriver
return data;
}
#endregion
#region :IPLCDriver
public int PDU
{
@ -510,7 +518,7 @@ namespace ModbusDriver
}
public sealed class Modbus
public sealed class Modbus
{
public const byte fctReadCoil = 1;
public const byte fctReadDiscreteInputs = 2;
@ -547,5 +555,4 @@ namespace ModbusDriver
/// <summary>Constant for exception send failt.</summary>
public const byte excSendFailt = 100;
}
}

9
SCADA/Program/ModbusDriver/ModbusTCPDriver.cs

@ -1,11 +1,10 @@
using System;
using DataService;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Timers;
using DataService;
namespace ModbusDriver
{
@ -164,13 +163,11 @@ namespace ModbusDriver
get { return _server; }
}
public ModbusTCPReader(IDataServer server, short id, string name, string ip, int timeOut = 500, string spare1 = null, string spare2 = null)
public ModbusTCPReader(IDataServer server, short id, string name)
{
_id = id;
_name = name;
_server = server;
_ip = ip;
_timeout = timeOut;
}
public bool Connect()

18
SCADA/Program/OPCDriver/OPCDriver.cs

@ -842,7 +842,7 @@ namespace OPCDriver
[Description("OPC Client")]
public class OPCReader : IOPCShutdown, IDriver
{
private string _clsidOPCserver, _serverIP;
private string _clsidOPCserver = "{6E6170F0-FF2D-11D2-8087-00105AA8F840}", _serverIP;
private object _opcServerObj;
private IOPCServer _opcServer;
private IOPCItemProperties _opcProp;
@ -851,22 +851,24 @@ namespace OPCDriver
private IConnectionPoint _shutDownPoint;
private int _shutDownCookie;
public OPCReader(IDataServer dataServer, short id, string name, string serverIP = null,
int timeout = 0, string clsidOPCserver = "{6E6170F0-FF2D-11D2-8087-00105AA8F840}", string spare2 = null)
public string TypeID
{
get { return _clsidOPCserver; }
set { _clsidOPCserver = value; }
}
public OPCReader(IDataServer dataServer, short id, string name)
{
this._id = id;
this._dataServer = dataServer;
this._clsidOPCserver = clsidOPCserver;
this._serverIP = serverIP;
if (string.IsNullOrEmpty(serverIP)) _serverIP = null;
this._name = name;
Connect();
}
public bool Connect()
{
if (_opcServerObj != null)
Dispose();
if (string.IsNullOrEmpty(_serverIP)) _serverIP = null;
Guid cid;
Type svrComponenttype = Guid.TryParse(_clsidOPCserver, out cid) ? Type.GetTypeFromCLSID(cid, _serverIP, false)
: Type.GetTypeFromProgID(_clsidOPCserver, _serverIP, false);
@ -1091,6 +1093,8 @@ namespace OPCDriver
{
if (!_metaGroups.Exists(x => x.ID == id))
_metaGroups.Add(new MetaGroup { ID = id, Name = name, UpdateRate = updateRate, DeadBand = deadBand, Active = active });
if (IsClosed)
Connect();
if (_opcServer == null) return null;
GCHandle hDeadband, hTimeBias;
hDeadband = GCHandle.Alloc(deadBand, GCHandleType.Pinned);

41
SCADA/Program/OmronPlcDriver/OmronUdpReader.cs

@ -31,6 +31,7 @@ namespace OmronPlcDriver
public int PDU
{
get { return _pdu; }
set { _pdu = value; }
}
/// <summary>
/// 获取设备地址
@ -147,20 +148,16 @@ namespace OmronPlcDriver
string _ip;//服务ip
int _port = 9600; //服务端口
public int Port
{
get { return _port; }
set { _port = value; }
}
public string ServerName
{
get { return _ip + ":" + _port; }
set
{
if (!string.IsNullOrEmpty(value))
{
int index = value.IndexOf(':');
_ip = value.Substring(0, index);//ip地址
int index0 = value.Substring(index + 1).IndexOf(',');
_port = int.Parse(value.Substring(index + 1, index0 - index - 1));//端口号
_pdu = int.Parse(value.Substring(index0 + 1));//pdu
}
}
get { return _ip; }
set { _ip = value; }
}
/// <summary>
/// 是否关闭
@ -214,24 +211,11 @@ namespace OmronPlcDriver
get { return _server; }
}
public OmronCsCjUDPReader(IDataServer server, short id, string name, string servername, int timeOut = 500, string spare1 = null, string spare2 = null)
public OmronCsCjUDPReader(IDataServer server, short id, string name)
{
_id = id;
_name = name;
_server = server;
if (!string.IsNullOrEmpty(servername))
{
int index = servername.IndexOf(':');
_ip = servername.Substring(0, index);//ip地址
int index0 = servername.IndexOf(',');
_port = int.Parse(servername.Substring(index + 1, index0 - index - 1));//端口号
_pdu = int.Parse(servername.Substring(index0 + 1));//pdu
}
_timeout = timeOut;
byte.TryParse(spare1, out _plcNodeId);
byte.TryParse(spare2, out _pcNodeId);
//Console.WriteLine("id->" + _id.ToString() + " name->" + _name + " _server->" + _server + " _ip->" + _ip + " _port->" + _port + " _pdu->" + _pdu + " _timeout->" + _timeout + " plcNodeId->" + _plcNodeId + " pcNodeId->" + PcNodeId);
}
/// <summary>
@ -253,11 +237,6 @@ namespace OmronPlcDriver
udpSynCl.SendTimeout = _timeout;
udpSynCl.ReceiveTimeout = _timeout;
udpSynCl.Connect(_ip, _port);
//if (OnConnect != null)
//{
// OnConnect(this,new ConnectRequestEventArgs(Name + ServerName +"连接打开"));
//}
return true;
}
catch (SocketException error)

17
SCADA/Program/PanasonicDriver/PanasonicSerialReader.cs

@ -37,14 +37,14 @@ namespace PanasonicPLCriver
return string.Empty;
}
#endregion
public PanasonicSerialReader(IDataServer server, short id, string name, string ip, int timeOut = 500, string spare1 = null, string spare2 = null)
public PanasonicSerialReader(IDataServer server, short id, string name)
{
_server = server;
_id = id;
_name = name;
//spare1 = {COM3,9600,Odd,8,One}
_serialPort = new SerialPort("COM2", 57600, Parity.Odd, 8, StopBits.One);
_devId = byte.Parse(spare2);
}
public bool IsClosed
{
get
@ -58,11 +58,12 @@ namespace PanasonicPLCriver
get { return 60; }//应该是读取最大数的上限吧
}
string _name;
public string Name
{
get
{
throw new NotImplementedException();
return _name;
}
}
@ -73,11 +74,11 @@ namespace PanasonicPLCriver
return 256;//每帧最大字节数
}
}
string _port;
string _com;
public string ServerName
{
get { return _port; }
set { _port = value; }
get { return _com; }
set { _com = value; }
}
private int _timeOut;
@ -102,6 +103,8 @@ namespace PanasonicPLCriver
{
try
{
if (_serialPort == null)
_serialPort = new SerialPort(_com, 57600, Parity.Odd, 8, StopBits.One);
_serialPort.Open();
_serialPort.NewLine = "\r";
_serialPort.ReadTimeout = 10000;

30
SCADA/Program/SiemensPLCDriver/SiemensPLCDriver.cs

@ -79,13 +79,33 @@ namespace SiemensPLCDriver
}
}
public SiemensTCPReader(IDataServer server, short id, string name, string IP, int timeOut = 10000, string rack = "0", string slot = "0")
public int Rack
{
get
{
return _rack;
}
set
{
_rack = value;
}
}
public int Slot
{
get
{
return _slot;
}
set
{
_slot = value;
}
}
public SiemensTCPReader(IDataServer server, short id, string name)
{
_id = id;
int.TryParse(rack, out _rack);
int.TryParse(slot, out _slot);
_IP = IP;
_timeOut = timeOut;
_server = server;
_name = name;
}

173
SCADA/Program/TagConfig/TagConfig/DriverSet.Designer.cs

@ -29,163 +29,38 @@
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.txtName = new System.Windows.Forms.TextBox();
this.label1 = new System.Windows.Forms.Label();
this.txtServer = new System.Windows.Forms.TextBox();
this.label2 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.col = new System.Windows.Forms.ComboBox();
this.label6 = new System.Windows.Forms.Label();
this.toolTip1 = new System.Windows.Forms.ToolTip(this.components);
this.txtspare2 = new System.Windows.Forms.TextBox();
this.txtspare1 = new System.Windows.Forms.TextBox();
this.label4 = new System.Windows.Forms.Label();
this.numTimout = new System.Windows.Forms.NumericUpDown();
this.saveFileDialog1 = new System.Windows.Forms.SaveFileDialog();
this.label8 = new System.Windows.Forms.Label();
this.label9 = new System.Windows.Forms.Label();
((System.ComponentModel.ISupportInitialize)(this.numTimout)).BeginInit();
this.col = new System.Windows.Forms.ComboBox();
this.propertyGrid1 = new System.Windows.Forms.PropertyGrid();
this.SuspendLayout();
//
// txtName
//
this.txtName.Font = new System.Drawing.Font("Microsoft Sans Serif", 15.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.txtName.Location = new System.Drawing.Point(66, 14);
this.txtName.Name = "txtName";
this.txtName.Size = new System.Drawing.Size(188, 31);
this.txtName.TabIndex = 16;
this.toolTip1.SetToolTip(this.txtName, "设备名不能为空!");
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(9, 22);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(55, 13);
this.label1.TabIndex = 15;
this.label1.Text = "设备名:";
//
// txtServer
//
this.txtServer.Font = new System.Drawing.Font("Microsoft Sans Serif", 15.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.txtServer.Location = new System.Drawing.Point(66, 115);
this.txtServer.Name = "txtServer";
this.txtServer.Size = new System.Drawing.Size(188, 31);
this.txtServer.TabIndex = 18;
this.toolTip1.SetToolTip(this.txtServer, "可为空值,输入服务器名或IP地址");
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(8, 122);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(55, 13);
this.label2.TabIndex = 17;
this.label2.Text = "服务器:";
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(21, 169);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(43, 13);
this.label3.TabIndex = 19;
this.label3.Text = "超时:";
//
// col
//
this.col.Dock = System.Windows.Forms.DockStyle.Top;
this.col.Font = new System.Drawing.Font("Microsoft Sans Serif", 15.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.col.FormattingEnabled = true;
this.col.Location = new System.Drawing.Point(66, 63);
this.col.Location = new System.Drawing.Point(0, 0);
this.col.Name = "col";
this.col.Size = new System.Drawing.Size(188, 33);
this.col.Size = new System.Drawing.Size(272, 33);
this.col.TabIndex = 24;
this.col.SelectedIndexChanged += new System.EventHandler(this.col_SelectedIndexChanged);
//
// label6
//
this.label6.AutoSize = true;
this.label6.Location = new System.Drawing.Point(17, 73);
this.label6.Name = "label6";
this.label6.Size = new System.Drawing.Size(43, 13);
this.label6.TabIndex = 23;
this.label6.Text = "类型:";
//
// txtspare2
// propertyGrid1
//
this.txtspare2.Font = new System.Drawing.Font("Microsoft Sans Serif", 15.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.txtspare2.Location = new System.Drawing.Point(65, 261);
this.txtspare2.Name = "txtspare2";
this.txtspare2.Size = new System.Drawing.Size(188, 31);
this.txtspare2.TabIndex = 35;
this.toolTip1.SetToolTip(this.txtspare2, "可为空值,输入服务器名或IP地址");
//
// txtspare1
//
this.txtspare1.Font = new System.Drawing.Font("Microsoft Sans Serif", 15.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.txtspare1.Location = new System.Drawing.Point(66, 210);
this.txtspare1.Name = "txtspare1";
this.txtspare1.Size = new System.Drawing.Size(188, 31);
this.txtspare1.TabIndex = 33;
this.toolTip1.SetToolTip(this.txtspare1, "设备名不能为空!");
//
// label4
//
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(192, 168);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(67, 13);
this.label4.TabIndex = 25;
this.label4.Text = "单位:毫秒";
//
// numTimout
//
this.numTimout.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.numTimout.Location = new System.Drawing.Point(66, 166);
this.numTimout.Maximum = new decimal(new int[] {
100000,
0,
0,
0});
this.numTimout.Name = "numTimout";
this.numTimout.Size = new System.Drawing.Size(120, 22);
this.numTimout.TabIndex = 28;
//
// label8
//
this.label8.AutoSize = true;
this.label8.Location = new System.Drawing.Point(15, 266);
this.label8.Name = "label8";
this.label8.Size = new System.Drawing.Size(49, 13);
this.label8.TabIndex = 34;
this.label8.Text = "参数2:";
//
// label9
//
this.label9.AutoSize = true;
this.label9.Location = new System.Drawing.Point(15, 217);
this.label9.Name = "label9";
this.label9.Size = new System.Drawing.Size(49, 13);
this.label9.TabIndex = 32;
this.label9.Text = "参数1:";
this.propertyGrid1.Dock = System.Windows.Forms.DockStyle.Fill;
this.propertyGrid1.Location = new System.Drawing.Point(0, 33);
this.propertyGrid1.Name = "propertyGrid1";
this.propertyGrid1.Size = new System.Drawing.Size(272, 309);
this.propertyGrid1.TabIndex = 30;
//
// DriverSet
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(264, 300);
this.Controls.Add(this.txtspare2);
this.Controls.Add(this.label8);
this.Controls.Add(this.txtspare1);
this.Controls.Add(this.label9);
this.Controls.Add(this.numTimout);
this.Controls.Add(this.label4);
this.ClientSize = new System.Drawing.Size(272, 342);
this.Controls.Add(this.propertyGrid1);
this.Controls.Add(this.col);
this.Controls.Add(this.label6);
this.Controls.Add(this.label3);
this.Controls.Add(this.txtServer);
this.Controls.Add(this.label2);
this.Controls.Add(this.txtName);
this.Controls.Add(this.label1);
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "DriverSet";
@ -193,28 +68,14 @@
this.Text = "驱动参数设置";
this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.Form3_FormClosed);
this.Load += new System.EventHandler(this.Form3_Load);
((System.ComponentModel.ISupportInitialize)(this.numTimout)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.TextBox txtName;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.TextBox txtServer;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.ComboBox col;
private System.Windows.Forms.Label label6;
private System.Windows.Forms.ToolTip toolTip1;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.NumericUpDown numTimout;
private System.Windows.Forms.SaveFileDialog saveFileDialog1;
private System.Windows.Forms.TextBox txtspare2;
private System.Windows.Forms.Label label8;
private System.Windows.Forms.TextBox txtspare1;
private System.Windows.Forms.Label label9;
private System.Windows.Forms.ComboBox col;
private System.Windows.Forms.PropertyGrid propertyGrid1;
}
}

95
SCADA/Program/TagConfig/TagConfig/DriverSet.cs

@ -1,26 +1,26 @@
using System;
using System.Windows.Forms;
using System.Collections.Generic;
using DatabaseLib;
using System.Globalization;
using System.Reflection;
using System.Windows.Forms;
namespace TagConfig
{
public partial class DriverSet : Form
{
bool _started;
Driver _device;
List<DataTypeSource1> _typeList;
List<DriverArgumet> _arguments;
static Dictionary<string, Type> _classList = new Dictionary<string, Type>();
public DriverSet(Driver device)
public DriverSet(Driver device, List<DataTypeSource1> typeList, List<DriverArgumet> args)
{
_device = device;
_typeList = typeList;
_arguments = args;
InitializeComponent();
List<DataTypeSource1> typeList = new List<DataTypeSource1>();
using (var reader = DataHelper.Instance.ExecuteReader("SELECT DRIVERID,ISNULL(Description,CLASSNAME) FROM RegisterModule"))
{
while (reader.Read())
{
typeList.Add(new DataTypeSource1(reader.GetInt32(0), reader.GetString(1)));
}
}
col.DataSource = typeList;
col.DisplayMember = "Name";
col.ValueMember = "DataType";
@ -30,24 +30,75 @@ namespace TagConfig
{
if (_device != null)
{
txtName.Text = _device.Name;
txtServer.Text = _device.ServerName;
numTimout.Value = _device.TimeOut;
col.SelectedValue = (int)_device.DeviceDriver;
txtspare1.Text = _device.Spare1;
txtspare2.Text = _device.Spare2;
col.SelectedValue = _device.DeviceDriver;
//col.SelectedValue = _device.Driver;
if (_device.Target != null)
{
propertyGrid1.SelectedObject = _device.Target;
}
else GetProperties(false);
_started = true;
}
}
private void Form3_FormClosed(object sender, FormClosedEventArgs e)
{
_device.Name = txtName.Text;
_device.ServerName = txtServer.Text;
_device.TimeOut = (int)numTimout.Value;
_device.DeviceDriver = Convert.ToInt32(col.SelectedValue);
_device.Spare1 = txtspare1.Text;
_device.Spare2 = txtspare2.Text;
}
private void GetProperties(bool isnew)
{
var item = _typeList.Find(x => x.DataType == _device.DeviceDriver);
if (item != null)
{
try
{
Type dvType;
if (!_classList.TryGetValue(item.ClassName, out dvType))
{
Assembly ass = Assembly.LoadFrom(item.Path);
dvType = ass.GetType(item.ClassName);
_classList[item.ClassName] = dvType;
}
if (dvType != null)
{
var dv = Activator.CreateInstance(dvType, new object[] { null, _device.ID, _device.Name });
if (dv != null)
{
if (!isnew)
{
foreach (var arg in _arguments)
{
if (arg.DriverID == _device.ID)
{
var prop = dvType.GetProperty(arg.PropertyName);
if (prop != null)
{
if (prop.PropertyType.IsEnum)
prop.SetValue(dv, Enum.Parse(prop.PropertyType, arg.PropertyValue), null);
else
prop.SetValue(dv, Convert.ChangeType(arg.PropertyValue, prop.PropertyType, CultureInfo.CreateSpecificCulture("en-US")), null);
}
}
}
}
_device.Target = dv;
propertyGrid1.SelectedObject = dv;
}
}
}
catch (Exception err)
{ }
}
}
private void col_SelectedIndexChanged(object sender, EventArgs e)
{
if (_started)
{
_device.DeviceDriver = Convert.ToInt32(col.SelectedValue);
GetProperties(true);
}
}
}
}

111
SCADA/Program/TagConfig/TagConfig/Form1.cs

@ -30,6 +30,8 @@ namespace TagConfig
List<Condition> conditions = new List<Condition>();
List<SubCondition> subConds = new List<SubCondition>();
List<TagData> selectedTags = new List<TagData>();
List<DataTypeSource1> typeList = new List<DataTypeSource1>();
List<DriverArgumet> arguments = new List<DriverArgumet>();
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
@ -63,13 +65,12 @@ namespace TagConfig
list.Clear();
//subConds.Clear();
majorTop.Nodes.Clear();
string sql = "SELECT DriverID,DriverType,DriverName,Server,TimeOut,Spare1,Spare2 FROM META_DRIVER;";
string sql = "SELECT DriverID,DriverType,DriverName FROM META_DRIVER;";
using (var reader = DataHelper.Instance.ExecuteReader(sql))
{
while (reader.Read())
{
Driver device = new Driver(reader.GetInt16(0), reader.GetInt32(1), reader.GetString(2), reader.GetNullableString(3),
reader.GetInt32(4), reader.GetNullableString(5), reader.GetNullableString(6));
Driver device = new Driver(reader.GetInt16(0), reader.GetInt32(1), reader.GetString(2));
devices.Add(device);
majorTop.Nodes.Add(device.ID.ToString(), device.Name, 1, 1);
}
@ -131,6 +132,22 @@ namespace TagConfig
scaleList.Add(scale);
}
}
sql = "SELECT DRIVERID,ISNULL(Description,CLASSNAME),AssemblyName,ClassFullName FROM RegisterModule";
using (var reader = DataHelper.Instance.ExecuteReader(sql))
{
while (reader.Read())
{
typeList.Add(new DataTypeSource1(reader.GetInt32(0), reader.GetString(1), reader.GetNullableString(2), reader.GetNullableString(3)));
}
}
sql = "SELECT DriverID,PropertyName,PropertyValue FROM Argument";
using (var reader = DataHelper.Instance.ExecuteReader(sql))
{
while (reader.Read())
{
arguments.Add(new DriverArgumet(reader.GetInt16(0), reader.GetString(1), reader.GetNullableString(2)));
}
}
list.Sort();
//conditions.Sort();
subConds.Sort();
@ -161,7 +178,7 @@ namespace TagConfig
}
}
var obj = DataHelper.Instance.ExecuteScalar("SELECT MAX(TypeID) FROM Meta_Condition");
if (obj != DBNull.Value) Program.MAXCONDITIONID =Convert.ToInt32(obj);
if (obj != DBNull.Value) Program.MAXCONDITIONID = Convert.ToInt32(obj);
start = true;
}
@ -170,27 +187,47 @@ namespace TagConfig
//dataGridView1.CurrentCell = null;
//bindingSource1.EndEdit();
bool result = true;
TagDataReader reader = new TagDataReader(list);
ConditionReader condReader = new ConditionReader(conditions);
SubConditionReader subReader = new SubConditionReader(subConds);
ScaleReader scalereader = new ScaleReader(scaleList);
string sql = "DELETE FROM Meta_Driver;DELETE FROM Meta_Group;";
foreach (Driver device in devices)
{
sql = string.Concat(sql, string.Format("INSERT INTO Meta_Driver(DriverID,DriverName,DriverType,Server,TimeOut,Spare1,Spare2)"
+ " VALUES({0},'{1}',{2},'{3}',{4},'{5}','{6}');",
device.ID, device.Name, device.DeviceDriver, device.ServerName, device.TimeOut, device.Spare1, device.Spare2));
sql = string.Concat(sql, string.Format("INSERT INTO Meta_Driver(DriverID,DriverName,DriverType)"
+ " VALUES({0},'{1}',{2});",
device.ID, device.Name, device.DeviceDriver));
if (device.Target != null)
{
for (int i = arguments.Count - 1; i >= 0; i--)
{
if (arguments[i].DriverID == device.ID)
arguments.RemoveAt(i);
}
var type = device.Target.GetType();
foreach (var prop in type.GetProperties())
{
if (prop.CanWrite)
{
var value = prop.GetValue(device.Target, null);
var item = new DriverArgumet(device.ID, prop.Name, value == null ? null : value.ToString());
arguments.Add(item);
}
}
}
}
foreach (Group grp in groups)
{
sql = string.Concat(sql, string.Format("INSERT INTO Meta_Group(GroupID,GroupName,DriverID,UpdateRate,DeadBand,IsActive) VALUES({0},'{1}',{2},{3},{4},'{5}');",
grp.ID, grp.Name, grp.DriverID, grp.UpdateRate, grp.DeadBand, grp.Active));
}
TagDataReader reader = new TagDataReader(list);
ConditionReader condReader = new ConditionReader(conditions);
SubConditionReader subReader = new SubConditionReader(subConds);
ScaleReader scalereader = new ScaleReader(scaleList);
ArgumentReader argumentreader = new ArgumentReader(arguments);
result &= DataHelper.Instance.ExecuteNonQuery(sql) >= 0;
result &= DataHelper.Instance.BulkCopy(reader, "Meta_Tag", "DELETE FROM Meta_Tag", SqlBulkCopyOptions.KeepIdentity);
result &= DataHelper.Instance.BulkCopy(condReader, "Meta_Condition", "DELETE FROM Meta_Condition", SqlBulkCopyOptions.KeepIdentity);
result &= DataHelper.Instance.BulkCopy(subReader, "Meta_SubCondition", "DELETE FROM Meta_SubCondition", SqlBulkCopyOptions.KeepIdentity);
result &= DataHelper.Instance.BulkCopy(scalereader, "Meta_Scale", "DELETE FROM Meta_Scale", SqlBulkCopyOptions.KeepIdentity);
result &= DataHelper.Instance.BulkCopy(argumentreader, "Argument", "DELETE FROM Argument");
return result;
}
@ -225,14 +262,6 @@ namespace TagConfig
{
device.Name = reader.Value;
}
if (reader.MoveToAttribute("server"))
{
device.ServerName = reader.Value;
}
if (reader.MoveToAttribute("timeout"))
{
device.TimeOut = int.Parse(reader.Value);
}
devices.Add(device);
majorTop.Nodes.Add(device.ID.ToString(), device.Name, 1, 1);
}
@ -337,9 +366,6 @@ namespace TagConfig
writer.WriteStartElement("Device");
writer.WriteAttributeString("id", device.ID.ToString());
writer.WriteAttributeString("name", device.Name);
if (!string.IsNullOrEmpty(device.ServerName))
writer.WriteAttributeString("server", device.ServerName);
writer.WriteAttributeString("timeout", device.TimeOut.ToString());
foreach (Group grp in groups)
{
if (grp.DriverID != device.ID)
@ -841,10 +867,10 @@ namespace TagConfig
}
break;
case "保存":
if(Save())
if (Save())
MessageBox.Show("保存成功!");
break;
case "注册":
{
RegisterSet frm = new RegisterSet();
@ -908,22 +934,22 @@ namespace TagConfig
{
case "配方":
{
}
break;
case "设备":
{
}
break;
case "仓容":
{
}
break;
case "路径":
{
}
break;
case "导入变量":
@ -984,7 +1010,7 @@ namespace TagConfig
case "前缀":
{
string front = txtFront.Text;
if (treeView1.SelectedNode.Level ==0)
if (treeView1.SelectedNode.Level == 0)
{
foreach (var item in list)
{
@ -1084,7 +1110,7 @@ namespace TagConfig
{
if (device.ID == id)
{
DriverSet frm = new DriverSet(device);
DriverSet frm = new DriverSet(device, typeList, arguments);
frm.ShowDialog();
node.Text = device.Name;
return;
@ -1360,12 +1386,33 @@ namespace TagConfig
string _name;
public string Name { get { return _name; } set { _name = value; } }
public DataTypeSource1(int type, string name)
string _path;
public string Path { get { return _path; } set { _path = value; } }
string _className;
public string ClassName { get { return _className; } set { _className = value; } }
public DataTypeSource1(int type, string name, string path, string className)
{
_type = type;
_name = name;
_path = path;
_className = className;
}
}
public class DriverArgumet
{
public short DriverID;
public string PropertyName;
public string PropertyValue;
public DriverArgumet(short id, string name, string value)
{
DriverID = id;
PropertyName = name;
PropertyValue = value;
}
}
}

2
SCADA/Program/TagConfig/TagConfig/Properties/Resources.Designer.cs

@ -1,7 +1,7 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.18052
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.

4
SCADA/Program/TagConfig/TagConfig/Properties/Settings.Designer.cs

@ -1,7 +1,7 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.17929
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
@ -12,7 +12,7 @@ namespace TagConfig.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "10.0.0.0")]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "14.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));

3
SCADA/Program/TagConfig/TagConfig/TagConfig.csproj

@ -12,7 +12,8 @@
<AssemblyName>TagConfig</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<TargetFrameworkProfile>Client</TargetFrameworkProfile>
<TargetFrameworkProfile>
</TargetFrameworkProfile>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' ">
<PlatformTarget>x86</PlatformTarget>

294
SCADA/Program/TagConfig/TagConfig/TagData.cs

@ -354,8 +354,9 @@ namespace TagConfig
public class Driver
{
short _id;
int _timeOut, _driver;
string _server, _name, _spare1, _spare2;
int _driver;
string _name;
object _target;
public string Name
{
@ -369,18 +370,6 @@ namespace TagConfig
}
}
public string ServerName
{
get
{
return _server;
}
set
{
_server = value;
}
}
public short ID
{
get
@ -393,18 +382,6 @@ namespace TagConfig
}
}
public int TimeOut
{
get
{
return _timeOut;
}
set
{
_timeOut = value;
}
}
public int DeviceDriver
{
get
@ -417,40 +394,23 @@ namespace TagConfig
}
}
public string Spare1
{
get
{
return _spare1;
}
set
{
_spare1 = value;
}
}
public string Spare2
public object Target
{
get
{
return _spare2;
return _target;
}
set
{
_spare2 = value;
_target = value;
}
}
public Driver(short id, int driver, string name, string server, int timeOut, string spare1, string spare2)
public Driver(short id, int driver, string name)
{
_id = id;
_driver = driver;
_name = name;
_server = server;
_timeOut = timeOut;
_spare1 = spare1;
_spare2 = spare2;
}
public Driver()
@ -1799,4 +1759,244 @@ namespace TagConfig
#endregion
}
public class ArgumentReader : IDataReader
{
IEnumerator<DriverArgumet> _enumer;
public ArgumentReader(IEnumerable<DriverArgumet> list)
{
this._enumer = list.GetEnumerator();
}
#region IDataReader Members
public void Close()
{
}
public int Depth
{
get { return 0; }
}
public DataTable GetSchemaTable()
{
DataTable table = new DataTable("Argument");
table.Columns.Add("DriverID", typeof(short));
table.Columns.Add("PropertyName", typeof(string));
table.Columns.Add("PropertyValue", typeof(string));
return table;
}
public bool IsClosed
{
get { return false; }
}
public bool NextResult()
{
return false;
}
public bool Read()
{
return _enumer.MoveNext();
}
public int RecordsAffected
{
get { throw new NotImplementedException(); }
}
#endregion
#region IDisposable Members
public void Dispose()
{
}
#endregion
#region IDataRecord Members
public int FieldCount
{
get { return 3; }
}
public bool GetBoolean(int i)
{
return (bool)GetValue(i);
}
public byte GetByte(int i)
{
return (byte)GetValue(i);
}
public long GetBytes(int i, long fieldOffset, byte[] buffer, int bufferoffset, int length)
{
throw new NotImplementedException();
}
public char GetChar(int i)
{
return (char)GetValue(i);
}
public long GetChars(int i, long fieldoffset, char[] buffer, int bufferoffset, int length)
{
throw new NotImplementedException();
}
public IDataReader GetData(int i)
{
return this;
}
public string GetDataTypeName(int i)
{
throw new NotImplementedException();
}
public DateTime GetDateTime(int i)
{
return (DateTime)GetValue(i);
}
public decimal GetDecimal(int i)
{
return (decimal)GetValue(i);
}
public double GetDouble(int i)
{
return (double)GetValue(i);
}
public Type GetFieldType(int i)
{
switch (i)
{
case 0:
return typeof(short);
case 1:
return typeof(string);
case 2:
return typeof(string);
default:
return typeof(string);
}
}
public float GetFloat(int i)
{
return Convert.ToSingle(GetValue(i));
}
public Guid GetGuid(int i)
{
return (Guid)GetValue(i);
}
public short GetInt16(int i)
{
return (short)GetValue(i);
}
public int GetInt32(int i)
{
return (int)GetValue(i);
}
public long GetInt64(int i)
{
return (long)GetValue(i);
}
public string GetName(int i)
{
switch (i)
{
case 0:
return "DriverID";
case 1:
return "PropertyName";
case 2:
return "PropertyValue";
default:
return string.Empty;
}
}
public int GetOrdinal(string name)
{
switch (name)
{
case "DriverID":
return 0;
case "PropertyName":
return 1;
case "PropertyValue":
return 2;
default:
return -1;
}
}
public string GetString(int i)
{
return (string)GetValue(i);
}
public object GetValue(int i)
{
switch (i)
{
case 0:
return _enumer.Current.DriverID;
case 1:
return _enumer.Current.PropertyName;
case 2:
return _enumer.Current.PropertyValue;
default:
return null;
}
}
public int GetValues(object[] values)
{
throw new NotImplementedException();
}
public bool IsDBNull(int i)
{
switch (i)
{
case 2:
return _enumer.Current.PropertyValue == null;
default:
return false;
}
}
public object this[string name]
{
get
{
return GetValue(GetOrdinal(name));
}
}
public object this[int i]
{
get
{
return GetValue(i);
}
}
#endregion
}
}

2
SCADA/Program/TagConfig/TagConfig/app.config

@ -3,4 +3,4 @@
<configSections>
</configSections>
<connectionStrings/>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0,Profile=Client"/></startup></configuration>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/></startup></configuration>

BIN
SCADA/dll/DataService.dll

Binary file not shown.

BIN
SCADA/dll/FileDriver.dll

Binary file not shown.

BIN
SCADA/dll/ModbusDriver.dll

Binary file not shown.

BIN
SCADA/dll/OPCDriver.dll

Binary file not shown.

BIN
SCADA/dll/OmronPlcDriver.dll

Binary file not shown.

BIN
SCADA/dll/PanasonicDriver.dll

Binary file not shown.

BIN
SCADA/dll/SiemensPLCDriver.dll

Binary file not shown.
Loading…
Cancel
Save