提交 d6072cdd 编写于 作者: cdy816's avatar cdy816

增加独立的历史数据服务功能

上级 e5970666
...@@ -103,11 +103,13 @@ namespace Cdy.Tag ...@@ -103,11 +103,13 @@ namespace Cdy.Tag
/// </summary> /// </summary>
public void Close() public void Close()
{ {
if (mProcessThread != null) mIsClosed = true;
{ resetEvent.Set();
mProcessThread.Abort(); //if (mProcessThread != null)
mProcessThread = null; //{
} // mProcessThread.Abort();
// mProcessThread = null;
//}
} }
/// <summary> /// <summary>
......
...@@ -57,6 +57,8 @@ namespace Cdy.Tag ...@@ -57,6 +57,8 @@ namespace Cdy.Tag
private DateTime mLastNotiyTime = DateTime.Now; private DateTime mLastNotiyTime = DateTime.Now;
private bool mIsClosed = false;
#endregion ...Variables... #endregion ...Variables...
#region ... Events ... #region ... Events ...
...@@ -114,11 +116,14 @@ namespace Cdy.Tag ...@@ -114,11 +116,14 @@ namespace Cdy.Tag
/// </summary> /// </summary>
public void Close() public void Close()
{ {
if (mProcessThread != null) mIsClosed = true;
{ resetEvent.Set();
mProcessThread.Abort();
mProcessThread = null; //if (mProcessThread != null)
} //{
// mProcessThread.Abort();
// mProcessThread = null;
//}
} }
/// <summary> /// <summary>
...@@ -215,9 +220,11 @@ namespace Cdy.Tag ...@@ -215,9 +220,11 @@ namespace Cdy.Tag
/// </summary> /// </summary>
private void ThreadProcess() private void ThreadProcess()
{ {
while(true) while(!mIsClosed)
{ {
resetEvent.WaitOne(); resetEvent.WaitOne();
if (mIsClosed) break;
resetEvent.Reset(); resetEvent.Reset();
if (mLenght > 0) if (mLenght > 0)
{ {
......
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<Prefer32Bit>false</Prefer32Bit>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\Cdy.Tag.Network\Cdy.Tag.Network.csproj" />
<ProjectReference Include="..\Cdy.Tag\Cdy.Tag.csproj" />
<ProjectReference Include="..\DBHisData\DBHisData.csproj" />
<ProjectReference Include="..\DBRuntime.Real\DBRuntime.Real.csproj" />
<ProjectReference Include="..\DotNettyCore\DotNettyCore.csproj" />
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
<Target Name="PostBuild" AfterTargets="PostBuildEvent">
<Exec Command="copy &quot;$(TargetPath)&quot; &quot;$(SolutionDir)\Output&quot; /y&#xD;&#xA;copy &quot;$(TargetDir)$(TargetName).exe&quot; &quot;$(SolutionDir)\Output&quot; /y&#xD;&#xA;copy &quot;$(TargetDir)$(TargetName).runtimeconfig.json&quot; &quot;$(SolutionDir)\Output&quot; /y&#xD;&#xA;if exist &quot;$(TargetDir)$(TargetName).XML&quot; copy &quot;$(TargetDir)$(TargetName).XML&quot; &quot;$(SolutionDir)\Output\Xml&quot; /y&#xD;&#xA;if exist &quot;$(TargetDir)$(TargetName).pdb&quot; copy &quot;$(TargetDir)$(TargetName).pdb&quot; &quot;$(SolutionDir)\Output&quot; /y&#xD;&#xA;if exist &quot;$(TargetDir)zh-CN&quot; copy &quot;$(TargetDir)zh-CN\*.dll&quot; &quot;$(SolutionDir)\Output\zh-CN&quot; /y" />
</Target>
</Project>
//==============================================================
// Copyright (C) 2020 Inc. All rights reserved.
//
//==============================================================
// Create by 种道洋 at 2020/5/14 10:22:00.
// Version 1.0
// 种道洋
//==============================================================
using Cdy.Tag;
using DotNetty.Buffers;
using System;
using System.Collections.Generic;
using System.Text;
namespace DBRuntime.Api
{
public class ApiFunConst
{
/// <summary>
///
/// </summary>
public const byte TagInfoRequest = 1;
/// <summary>
///
/// </summary>
public const byte RealDataRequestFun = 10;
/// <summary>
///
/// </summary>
public const byte RealDataPushFun = 12;
/// <summary>
///
/// </summary>
public const byte HisDataRequestFun = 20;
public const byte AysncReturn = byte.MaxValue;
}
/// <summary>
///
/// </summary>
public class DataService: SocketServer
{
#region ... Variables ...
private IByteBuffer mAsyncCalldata;
private Dictionary<byte, ServerProcessBase> mProcess = new Dictionary<byte, ServerProcessBase>();
private HisDataServerProcess mHisProcess;
private TagInfoServerProcess mInfoProcess;
/// <summary>
///
/// </summary>
public static DataService Service = new DataService();
#endregion ...Variables...
#region ... Events ...
#endregion ...Events...
#region ... Constructor...
/// <summary>
///
/// </summary>
public DataService()
{
RegistorInit();
}
#endregion ...Constructor...
#region ... Properties ...
#endregion ...Properties...
#region ... Methods ...
/// <summary>
///
/// </summary>
/// <param name="port"></param>
protected override void StartInner(int port)
{
mHisProcess = new HisDataServerProcess() { Parent = this };
mInfoProcess = new TagInfoServerProcess() { Parent = this };
mHisProcess.Start();
mInfoProcess.Start();
base.StartInner(port);
}
/// <summary>
///
/// </summary>
public override void Stop()
{
base.Stop();
if (mHisProcess != null)
{
mHisProcess.Stop();
mHisProcess.Dispose();
mHisProcess = null;
}
}
private IByteBuffer GetAsyncData()
{
mAsyncCalldata = BufferManager.Manager.Allocate(ApiFunConst.AysncReturn, 4);
mAsyncCalldata.WriteInt(0);
return mAsyncCalldata;
}
/// <summary>
///
/// </summary>
private void RegistorInit()
{
this.RegistorFunCallBack(ApiFunConst.HisDataRequestFun, HisDataRequest);
this.RegistorFunCallBack(ApiFunConst.TagInfoRequest, TagInfoRequest);
}
/// <summary>
///
/// </summary>
public void PushRealDatatoClient(string clientId,byte[] value)
{
this.SendData(clientId, Api.ApiFunConst.RealDataPushFun, value,value.Length);
}
/// <summary>
///
/// </summary>
/// <param name="clientId"></param>
/// <param name="value"></param>
public void PushRealDatatoClient(string clientId, IByteBuffer value)
{
this.SendData(clientId, value);
}
/// <summary>
///
/// </summary>
/// <param name="clientId"></param>
/// <param name="fun"></param>
/// <param name="value"></param>
public void AsyncCallback(string clientId,byte fun, byte[] value,int len)
{
this.SendData(clientId, fun, value, len);
}
/// <summary>
///
/// </summary>
/// <param name="clientId"></param>
/// <param name="data"></param>
public void AsyncCallback(string clientId, IByteBuffer data)
{
this.SendData(clientId, data);
}
/// <summary>
///
/// </summary>
/// <param name="clientId"></param>
/// <param name="fun"></param>
/// <param name="value"></param>
/// <param name="len"></param>
public void AsyncCallback(string clientId, byte fun, IntPtr value, int len)
{
this.SendData(clientId, fun, value, len);
}
private IByteBuffer TagInfoRequest(string clientId, IByteBuffer memory)
{
mInfoProcess.ProcessData(clientId, memory);
return GetAsyncData();
}
/// <summary>
///
/// </summary>
/// <param name="clientId"></param>
/// <param name="memory"></param>
/// <returns></returns>
private IByteBuffer HisDataRequest(string clientId, IByteBuffer memory)
{
this.mHisProcess.ProcessData(clientId, memory);
return GetAsyncData();
}
#endregion ...Methods...
#region ... Interfaces ...
#endregion ...Interfaces...
}
}
此差异已折叠。
using System;
using System.IO.Pipes;
using System.Text;
using System.Threading.Tasks;
namespace DBHisDataServer
{
class Program
{
static bool mIsClosed = false;
static void Main(string[] args)
{
Console.CancelKeyPress += Console_CancelKeyPress;
AppDomain.CurrentDomain.ProcessExit += CurrentDomain_ProcessExit;
Console.WriteLine(Res.Get("WelcomeMsg"));
if (args.Length > 0 && args[0] == "start")
{
if (args.Length > 1)
{
Runner.Instance.Start(args[1]);
}
else
{
Runner.Instance.Start("local");
}
Task.Run(() => {
StartMonitor(args.Length > 1 ? args[1] : "local");
});
}
Console.WriteLine(Res.Get("HelpMsg"));
while (!mIsClosed)
{
Console.Write(">");
string smd = Console.ReadLine();
if (mIsClosed)
{
break;
}
if (string.IsNullOrEmpty(smd)) continue;
string[] cmd = smd.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);
if (cmd.Length == 0) continue;
string scmd = cmd[0].ToLower();
switch (scmd)
{
case "exit":
if (Runner.Instance.IsStarted)
{
Runner.Instance.Stop();
}
mIsClosed = true;
break;
case "start":
if (cmd.Length > 1)
{
Runner.Instance.Start(cmd[1]);
}
else
{
Runner.Instance.Start("local");
}
Task.Run(() => {
StartMonitor(cmd.Length > 1 ? cmd[1] : "local");
});
break;
case "stop":
Runner.Instance.Stop();
break;
case "h":
Console.WriteLine(GetHelpString());
break;
//case "mtest":
// block = new MarshalMemoryBlock((long)(1024 * 1024 * 1024)*2);
// //block.Clear();
// break;
}
}
}
/// <summary>
///
/// </summary>
/// <returns></returns>
private static string GetHelpString()
{
StringBuilder re = new StringBuilder();
re.AppendLine();
re.AppendLine("start [database] // " + Res.Get("StartMsg"));
re.AppendLine("stop // " + Res.Get("StopMsg"));
re.AppendLine("exit // ");
re.AppendLine("h // " + Res.Get("HMsg"));
return re.ToString();
}
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private static void CurrentDomain_ProcessExit(object sender, EventArgs e)
{
if (Runner.Instance.IsStarted)
{
Runner.Instance.Stop();
}
}
private static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)
{
if (Runner.Instance.IsStarted)
{
Runner.Instance.Stop();
}
mIsClosed = true;
e.Cancel = true;
Console.WriteLine(Res.Get("AnyKeyToExit"));
}
private static void StartMonitor(string name)
{
try
{
while (!mIsClosed)
{
using (var server = new NamedPipeServerStream(name+"h", PipeDirection.InOut))
{
server.WaitForConnection();
while (!mIsClosed)
{
try
{
if (!server.IsConnected) break;
var cmd = server.ReadByte();
if (cmd == 0)
{
if (Runner.Instance.IsStarted)
{
Runner.Instance.Stop();
}
mIsClosed = true;
server.WriteByte(1);
server.WaitForPipeDrain();
Console.WriteLine(Res.Get("AnyKeyToExit"));
break;
//退出系统
}
else
{
}
}
catch
{
break;
}
}
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
//------------------------------------------------------------------------------
// <auto-generated>
// 此代码由工具生成。
// 运行时版本:4.0.30319.42000
//
// 对此文件的更改可能会导致不正确的行为,并且如果
// 重新生成代码,这些更改将会丢失。
// </auto-generated>
//------------------------------------------------------------------------------
namespace DBHisDataServer.Properties {
using System;
/// <summary>
/// 一个强类型的资源类,用于查找本地化的字符串等。
/// </summary>
// 此类是由 StronglyTypedResourceBuilder
// 类通过类似于 ResGen 或 Visual Studio 的工具自动生成的。
// 若要添加或移除成员,请编辑 .ResX 文件,然后重新运行 ResGen
// (以 /str 作为命令选项),或重新生成 VS 项目。
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// 返回此类使用的缓存的 ResourceManager 实例。
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("DBHisDataServer.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// 重写当前线程的 CurrentUICulture 属性
/// 重写当前线程的 CurrentUICulture 属性。
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// 查找类似 press any key to exit. 的本地化字符串。
/// </summary>
internal static string AnyKeyToExit {
get {
return ResourceManager.GetString("AnyKeyToExit", resourceCulture);
}
}
/// <summary>
/// 查找类似 Enter h for command help information 的本地化字符串。
/// </summary>
internal static string HelpMsg {
get {
return ResourceManager.GetString("HelpMsg", resourceCulture);
}
}
/// <summary>
/// 查找类似 display command list 的本地化字符串。
/// </summary>
internal static string HMsg {
get {
return ResourceManager.GetString("HMsg", resourceCulture);
}
}
/// <summary>
/// 查找类似 start to run a databse,ignor database name to run default &apos;local&apos; database 的本地化字符串。
/// </summary>
internal static string StartMsg {
get {
return ResourceManager.GetString("StartMsg", resourceCulture);
}
}
/// <summary>
/// 查找类似 stop databse 的本地化字符串。
/// </summary>
internal static string StopMsg {
get {
return ResourceManager.GetString("StopMsg", resourceCulture);
}
}
/// <summary>
/// 查找类似 ***************Welcome to Mars high performance realtime iot database his data server*************** 的本地化字符串。
/// </summary>
internal static string WelcomeMsg {
get {
return ResourceManager.GetString("WelcomeMsg", resourceCulture);
}
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="AnyKeyToExit" xml:space="preserve">
<value>press any key to exit.</value>
</data>
<data name="HelpMsg" xml:space="preserve">
<value>Enter h for command help information</value>
</data>
<data name="HMsg" xml:space="preserve">
<value>display command list</value>
</data>
<data name="StartMsg" xml:space="preserve">
<value>start to run a databse,ignor database name to run default 'local' database</value>
</data>
<data name="StopMsg" xml:space="preserve">
<value>stop databse</value>
</data>
<data name="WelcomeMsg" xml:space="preserve">
<value>***************Welcome to Mars high performance realtime iot database his data server***************</value>
</data>
</root>
\ No newline at end of file
{
"profiles": {
"DBHisDataServer": {
"commandName": "Executable",
"executablePath": "D:\\Project\\Galaxy\\Output\\DBHisDataServer.exe"
}
}
}
\ No newline at end of file
//==============================================================
// Copyright (C) 2020 Inc. All rights reserved.
//
//==============================================================
// Create by 种道洋 at 2020/3/29 11:05:05.
// Version 1.0
// 种道洋
//==============================================================
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
namespace DBHisDataServer
{
public class Res
{
public static string Get(string name)
{
return DBHisDataServer.Properties.Resources.ResourceManager.GetString(name, Thread.CurrentThread.CurrentCulture);
}
}
}
//==============================================================
// Copyright (C) 2020 Inc. All rights reserved.
//
//==============================================================
// Create by 种道洋 at 2020/5/17 17:53:01.
// Version 1.0
// 种道洋
//==============================================================
using Cdy.Tag;
using System;
using System.Collections.Generic;
using System.Text;
namespace DBHisDataServer
{
/// <summary>
///
/// </summary>
public class Runner
{
#region ... Variables ...
private Database mDatabase;
private RealDatabase mRealDatabase;
private string mDatabaseName = "local";
private SecurityRunner mSecurityRunner;
private QuerySerivce querySerivce;
public static Runner Instance = new Runner();
private bool mIsStarted = false;
#endregion ...Variables...
#region ... Events ...
#endregion ...Events...
#region ... Constructor...
#endregion ...Constructor...
#region ... Properties ...
/// <summary>
/// 数据库存访路径
/// </summary>
public string DatabasePath { get; set; }
/// <summary>
///
/// </summary>
public bool IsStarted
{
get
{
return mIsStarted;
}
}
#endregion ...Properties...
#region ... Methods ...
private bool Init(string database)
{
if (System.IO.Path.IsPathRooted(database))
{
this.mDatabaseName = System.IO.Path.GetFileNameWithoutExtension(database);
this.DatabasePath = System.IO.Path.GetDirectoryName(database);
}
else
{
this.mDatabaseName = database;
}
PathHelper.helper.CheckDataPathExist();
if (CheckDatabaseExist(mDatabaseName))
{
LoadDatabase();
querySerivce = new QuerySerivce(this.mDatabaseName);
mSecurityRunner = new SecurityRunner() { Document = mDatabase.Security };
DataFileSeriserManager.manager.Init();
CompressUnitManager.Manager.Init();
HisQueryManager.Instance.Registor(mDatabaseName);
RegistorInterface();
return true;
}
else
{
LoggerService.Service.Erro("Runner", "database " + database + " is not exist.");
return false;
}
}
private bool CheckDatabaseExist(string name)
{
return System.IO.File.Exists(PathHelper.helper.GetDataPath(name, name + ".db"));
}
/// <summary>
///
/// </summary>
private void LoadDatabase()
{
this.mDatabase = new DatabaseSerise().Load(mDatabaseName);
this.mRealDatabase = this.mDatabase.RealDatabase;
}
private void RegistorInterface()
{
ServiceLocator.Locator.Registor<ITagManager>(mRealDatabase);
ServiceLocator.Locator.Registor<IRuntimeSecurity>(mSecurityRunner);
ServiceLocator.Locator.Registor<IHisQuery>(querySerivce);
}
/// <summary>
///
/// </summary>
public void Start(string database)
{
var re = Init(database);
if (!re)
{
return;
}
DBRuntime.Api.DataService.Service.Start(14331);
mSecurityRunner.Start();
mIsStarted = true;
}
/// <summary>
///
/// </summary>
public void Stop()
{
DBRuntime.Api.DataService.Service.Stop();
mSecurityRunner.Stop();
mIsStarted = false;
}
#endregion ...Methods...
#region ... Interfaces ...
#endregion ...Interfaces...
}
}
//==============================================================
// Copyright (C) 2020 Inc. All rights reserved.
//
//==============================================================
// Create by 种道洋 at 2020/5/14 11:01:03.
// Version 1.0
// 种道洋
//==============================================================
using Cdy.Tag;
using DotNetty.Buffers;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
namespace DBRuntime.Api
{
public abstract class ServerProcessBase:IDisposable
{
#region ... Variables ...
/// <summary>
///
/// </summary>
private Dictionary<string, Queue<IByteBuffer>> mDatasCach = new Dictionary<string, Queue<IByteBuffer>>();
private Thread mProcessThread;
private ManualResetEvent resetEvent;
private bool mIsClosed = false;
#endregion ...Variables...
#region ... Events ...
#endregion ...Events...
#region ... Constructor...
#endregion ...Constructor...
#region ... Properties ...
/// <summary>
///
/// </summary>
public abstract byte FunId { get; }
/// <summary>
///
/// </summary>
public DataService Parent { get; set; }
#endregion ...Properties...
#region ... Methods ...
/// <summary>
///
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
protected IByteBuffer ToByteBuffer(byte id, string value)
{
var re = BufferManager.Manager.Allocate(ApiFunConst.TagInfoRequest, value.Length*2);
re.WriteString(value);
return re;
}
/// <summary>
///
/// </summary>
/// <param name="id"></param>
/// <param name="value"></param>
/// <returns></returns>
protected IByteBuffer ToByteBuffer(byte id, byte value)
{
var re = BufferManager.Manager.Allocate(ApiFunConst.TagInfoRequest, 1);
re.WriteByte(value);
return re;
}
/// <summary>
///
/// </summary>
/// <param name="data"></param>
public virtual void ProcessData(string client, IByteBuffer data)
{
data.Retain();
if (mDatasCach.ContainsKey(client))
{
mDatasCach[client].Enqueue(data);
}
else
{
var vq = new Queue<IByteBuffer>();
vq.Enqueue(data);
mDatasCach.Add(client, vq);
}
resetEvent.Set();
}
/// <summary>
///
/// </summary>
private void DataProcess()
{
while (!mIsClosed)
{
resetEvent.WaitOne();
if (mIsClosed) return;
resetEvent.Reset();
foreach (var vv in mDatasCach)
{
while(vv.Value.Count>0)
{
var dd = vv.Value.Dequeue();
ProcessSingleData(vv.Key, dd);
}
}
}
}
/// <summary>
///
/// </summary>
/// <param name="client"></param>
/// <param name="data"></param>
protected virtual void ProcessSingleData(string client, IByteBuffer data)
{
data.Release();
}
public virtual void Start()
{
resetEvent = new ManualResetEvent(false);
mProcessThread = new Thread(DataProcess);
mProcessThread.IsBackground = true;
mProcessThread.Start();
}
/// <summary>
///
/// </summary>
public virtual void Stop()
{
mIsClosed = true;
resetEvent.Set();
resetEvent.Close();
}
/// <summary>
///
/// </summary>
public virtual void Dispose()
{
Parent = null;
}
#endregion ...Methods...
#region ... Interfaces ...
#endregion ...Interfaces...
}
}
//==============================================================
// Copyright (C) 2020 Inc. All rights reserved.
//
//==============================================================
// Create by 种道洋 at 2020/5/14 11:00:38.
// Version 1.0
// 种道洋
//==============================================================
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using Cdy.Tag;
using DotNetty.Buffers;
namespace DBRuntime.Api
{
public class TagInfoServerProcess : ServerProcessBase
{
#region ... Variables ...
public const byte GetTagIdByNameFun = 0;
public const byte Login = 1;
public const byte RegistValueCallBack = 2;
public const byte GetdatabaseName = 3;
#endregion ...Variables...
#region ... Events ...
#endregion ...Events...
#region ... Constructor...
#endregion ...Constructor...
#region ... Properties ...
public override byte FunId => ApiFunConst.TagInfoRequest;
#endregion ...Properties...
#region ... Methods ...
/// <summary>
///
/// </summary>
/// <param name="client"></param>
/// <param name="data"></param>
protected unsafe override void ProcessSingleData(string client, IByteBuffer data)
{
var mm = Cdy.Tag.ServiceLocator.Locator.Resolve<Cdy.Tag.ITagManager>();
byte sfun = data.ReadByte();
switch (sfun)
{
case Login:
string user = data.ReadString();
string pass = data.ReadString();
string result = Cdy.Tag.ServiceLocator.Locator.Resolve<IRuntimeSecurity>().Login(user, pass);
if (!string.IsNullOrEmpty(result))
{
Parent.AsyncCallback(client, ToByteBuffer(ApiFunConst.TagInfoRequest,result));
}
else
{
Parent.AsyncCallback(client, ToByteBuffer(ApiFunConst.TagInfoRequest, ""));
}
break;
}
}
#endregion ...Methods...
#region ... Interfaces ...
#endregion ...Interfaces...
}
}
using Cdy.Tag; using Cdy.Tag;
using System; using System;
using System.IO.Pipes;
using System.Text; using System.Text;
using System.Threading.Tasks;
namespace DBInRun namespace DBInRun
{ {
...@@ -24,6 +26,10 @@ namespace DBInRun ...@@ -24,6 +26,10 @@ namespace DBInRun
{ {
Cdy.Tag.Runner.RunInstance.Start(); Cdy.Tag.Runner.RunInstance.Start();
} }
Task.Run(() => {
StartMonitor(args.Length > 1 ? args[1] : "local");
});
} }
Console.WriteLine(Res.Get("HelpMsg")); Console.WriteLine(Res.Get("HelpMsg"));
...@@ -53,17 +59,22 @@ namespace DBInRun ...@@ -53,17 +59,22 @@ namespace DBInRun
mIsClosed = true; mIsClosed = true;
break; break;
case "start": case "start":
string dbname = "local";
if (cmd.Length > 1) if (cmd.Length > 1)
{ {
Cdy.Tag.Runner.RunInstance.StartAsync(cmd[1]); Cdy.Tag.Runner.RunInstance.StartAsync(cmd[1]);
Console.Title = "DbInRun-" + cmd[1]; Console.Title = "DbInRun-" + cmd[1];
dbname = cmd[1];
} }
else else
{ {
Cdy.Tag.Runner.RunInstance.Start(); Cdy.Tag.Runner.RunInstance.Start();
Console.Title = "DbInRun-local"; Console.Title = "DbInRun-local";
dbname = "local";
} }
Task.Run(() => {
StartMonitor(dbname);
});
break; break;
case "stop": case "stop":
Cdy.Tag.Runner.RunInstance.Stop(); Cdy.Tag.Runner.RunInstance.Stop();
...@@ -130,6 +141,55 @@ namespace DBInRun ...@@ -130,6 +141,55 @@ namespace DBInRun
} }
private static void StartMonitor(string name)
{
try
{
while (!mIsClosed)
{
using (var server = new NamedPipeServerStream(name, PipeDirection.InOut))
{
server.WaitForConnection();
while (!mIsClosed)
{
try
{
if (!server.IsConnected) break;
var cmd = server.ReadByte();
if (cmd == 0)
{
if (Cdy.Tag.Runner.RunInstance.IsStarted)
{
Cdy.Tag.Runner.RunInstance.Stop();
}
mIsClosed = true;
server.WriteByte(1);
server.WaitForPipeDrain();
Console.WriteLine(Res.Get("AnyKeyToExit"));
break;
//退出系统
}
else
{
}
}
catch
{
break;
}
}
}
}
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
}
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
......
...@@ -127,6 +127,9 @@ namespace DBRunTime.ServiceApi ...@@ -127,6 +127,9 @@ namespace DBRunTime.ServiceApi
public ProcessDataPushDelegate ProcessDataPush { get; set; } public ProcessDataPushDelegate ProcessDataPush { get; set; }
private string mUser;
private string mPass;
#endregion ...Properties... #endregion ...Properties...
#region ... Methods ... #region ... Methods ...
...@@ -185,6 +188,8 @@ namespace DBRunTime.ServiceApi ...@@ -185,6 +188,8 @@ namespace DBRunTime.ServiceApi
/// <param name="password"></param> /// <param name="password"></param>
public bool Login(string username,string password,int timeount=5000) public bool Login(string username,string password,int timeount=5000)
{ {
mUser = username;
mPass = password;
int size = username.Length + password.Length + 9; int size = username.Length + password.Length + 9;
var mb = GetBuffer(ApiFunConst.TagInfoRequest, size); var mb = GetBuffer(ApiFunConst.TagInfoRequest, size);
mb.WriteByte(ApiFunConst.Login); mb.WriteByte(ApiFunConst.Login);
...@@ -199,7 +204,7 @@ namespace DBRunTime.ServiceApi ...@@ -199,7 +204,7 @@ namespace DBRunTime.ServiceApi
return IsLogin; return IsLogin;
} }
} }
mInfoRequreData?.Release(); //mInfoRequreData?.Release();
LoginId = string.Empty; LoginId = string.Empty;
return IsLogin; return IsLogin;
} }
...@@ -261,7 +266,7 @@ namespace DBRunTime.ServiceApi ...@@ -261,7 +266,7 @@ namespace DBRunTime.ServiceApi
} }
finally finally
{ {
mInfoRequreData?.ReleaseBuffer(); //mInfoRequreData?.ReleaseBuffer();
} }
return string.Empty; return string.Empty;
} }
...@@ -278,6 +283,7 @@ namespace DBRunTime.ServiceApi ...@@ -278,6 +283,7 @@ namespace DBRunTime.ServiceApi
/// <returns></returns> /// <returns></returns>
public bool RegistorTagValueCallBack(int minid, int maxid, int timeout = 5000) public bool RegistorTagValueCallBack(int minid, int maxid, int timeout = 5000)
{ {
CheckLogin();
var mb = GetBuffer(ApiFunConst.RealDataRequestFun, this.LoginId.Length + 8); var mb = GetBuffer(ApiFunConst.RealDataRequestFun, this.LoginId.Length + 8);
mb.WriteByte(ApiFunConst.RegistorValueCallback); mb.WriteByte(ApiFunConst.RegistorValueCallback);
mb.WriteString(this.LoginId); mb.WriteString(this.LoginId);
...@@ -294,7 +300,7 @@ namespace DBRunTime.ServiceApi ...@@ -294,7 +300,7 @@ namespace DBRunTime.ServiceApi
} }
finally finally
{ {
mRealRequreData?.ReleaseBuffer(); //mRealRequreData?.ReleaseBuffer();
} }
return true; return true;
} }
...@@ -306,6 +312,7 @@ namespace DBRunTime.ServiceApi ...@@ -306,6 +312,7 @@ namespace DBRunTime.ServiceApi
/// <returns></returns> /// <returns></returns>
public bool ClearRegistorTagValueCallBack(int timeout = 5000) public bool ClearRegistorTagValueCallBack(int timeout = 5000)
{ {
CheckLogin();
var mb = GetBuffer(ApiFunConst.RealDataRequestFun, this.LoginId.Length + 8); var mb = GetBuffer(ApiFunConst.RealDataRequestFun, this.LoginId.Length + 8);
mb.WriteByte(ApiFunConst.ResetValueChangeNotify); mb.WriteByte(ApiFunConst.ResetValueChangeNotify);
mb.WriteString(this.LoginId); mb.WriteString(this.LoginId);
...@@ -321,7 +328,7 @@ namespace DBRunTime.ServiceApi ...@@ -321,7 +328,7 @@ namespace DBRunTime.ServiceApi
} }
finally finally
{ {
mRealRequreData?.ReleaseBuffer(); //mRealRequreData?.ReleaseBuffer();
} }
return true; return true;
} }
...@@ -332,6 +339,7 @@ namespace DBRunTime.ServiceApi ...@@ -332,6 +339,7 @@ namespace DBRunTime.ServiceApi
/// <returns></returns> /// <returns></returns>
public IByteBuffer GetRealData(List<int> ids,int timeout=5000) public IByteBuffer GetRealData(List<int> ids,int timeout=5000)
{ {
CheckLogin();
var mb = GetBuffer(ApiFunConst.RealDataRequestFun, this.LoginId.Length +ids.Count* 4); var mb = GetBuffer(ApiFunConst.RealDataRequestFun, this.LoginId.Length +ids.Count* 4);
mb.WriteByte(ApiFunConst.RequestRealData); mb.WriteByte(ApiFunConst.RequestRealData);
mb.WriteString(this.LoginId); mb.WriteString(this.LoginId);
...@@ -352,7 +360,7 @@ namespace DBRunTime.ServiceApi ...@@ -352,7 +360,7 @@ namespace DBRunTime.ServiceApi
} }
finally finally
{ {
mRealRequreData?.ReleaseBuffer(); //mRealRequreData?.ReleaseBuffer();
} }
...@@ -361,7 +369,7 @@ namespace DBRunTime.ServiceApi ...@@ -361,7 +369,7 @@ namespace DBRunTime.ServiceApi
public IByteBuffer GetRealData(int ids,int ide, int timeout = 5000) public IByteBuffer GetRealData(int ids,int ide, int timeout = 5000)
{ {
CheckLogin();
var mb = GetBuffer(ApiFunConst.RealDataRequestFun, this.LoginId.Length + (ide - ids) * 4); var mb = GetBuffer(ApiFunConst.RealDataRequestFun, this.LoginId.Length + (ide - ids) * 4);
mb.WriteByte(ApiFunConst.RequestRealData2); mb.WriteByte(ApiFunConst.RequestRealData2);
mb.WriteString(this.LoginId); mb.WriteString(this.LoginId);
...@@ -374,7 +382,7 @@ namespace DBRunTime.ServiceApi ...@@ -374,7 +382,7 @@ namespace DBRunTime.ServiceApi
{ {
return mRealRequreData; return mRealRequreData;
} }
mRealRequreData?.ReleaseBuffer(); //mRealRequreData?.ReleaseBuffer();
return null; return null;
} }
...@@ -387,6 +395,7 @@ namespace DBRunTime.ServiceApi ...@@ -387,6 +395,7 @@ namespace DBRunTime.ServiceApi
/// <param name="value"></param> /// <param name="value"></param>
public bool SetTagValue(int id,byte valueType,object value,int timeout=5000) public bool SetTagValue(int id,byte valueType,object value,int timeout=5000)
{ {
CheckLogin();
var mb = GetBuffer(ApiFunConst.RealDataRequestFun, this.LoginId.Length + 30); var mb = GetBuffer(ApiFunConst.RealDataRequestFun, this.LoginId.Length + 30);
mb.WriteByte(ApiFunConst.SetDataValue); mb.WriteByte(ApiFunConst.SetDataValue);
mb.WriteString(this.LoginId); mb.WriteString(this.LoginId);
...@@ -479,7 +488,7 @@ namespace DBRunTime.ServiceApi ...@@ -479,7 +488,7 @@ namespace DBRunTime.ServiceApi
} }
finally finally
{ {
mRealRequreData?.ReleaseBuffer(); //mRealRequreData?.ReleaseBuffer();
} }
return false; return false;
} }
...@@ -494,6 +503,7 @@ namespace DBRunTime.ServiceApi ...@@ -494,6 +503,7 @@ namespace DBRunTime.ServiceApi
/// <returns></returns> /// <returns></returns>
public bool SetTagValue(List<int> id, List<byte> valueType, List<object> value, int timeout = 5000) public bool SetTagValue(List<int> id, List<byte> valueType, List<object> value, int timeout = 5000)
{ {
CheckLogin();
var mb = GetBuffer(ApiFunConst.RealDataRequestFun, this.LoginId.Length + 30); var mb = GetBuffer(ApiFunConst.RealDataRequestFun, this.LoginId.Length + 30);
mb.WriteByte(ApiFunConst.SetDataValue); mb.WriteByte(ApiFunConst.SetDataValue);
mb.WriteString(this.LoginId); mb.WriteString(this.LoginId);
...@@ -588,7 +598,7 @@ namespace DBRunTime.ServiceApi ...@@ -588,7 +598,7 @@ namespace DBRunTime.ServiceApi
} }
finally finally
{ {
mRealRequreData?.ReleaseBuffer(); //mRealRequreData?.ReleaseBuffer();
} }
return false; return false;
} }
...@@ -596,6 +606,14 @@ namespace DBRunTime.ServiceApi ...@@ -596,6 +606,14 @@ namespace DBRunTime.ServiceApi
#endregion #endregion
private void CheckLogin()
{
if(string.IsNullOrEmpty(LoginId))
{
Login(mUser, mPass);
}
}
#region HisData #region HisData
/// <summary> /// <summary>
...@@ -607,6 +625,7 @@ namespace DBRunTime.ServiceApi ...@@ -607,6 +625,7 @@ namespace DBRunTime.ServiceApi
/// <returns></returns> /// <returns></returns>
public IByteBuffer QueryAllHisValue(int id,DateTime startTime,DateTime endTime,int timeout=5000) public IByteBuffer QueryAllHisValue(int id,DateTime startTime,DateTime endTime,int timeout=5000)
{ {
CheckLogin();
var mb = GetBuffer(ApiFunConst.HisDataRequestFun, this.LoginId.Length + 20); var mb = GetBuffer(ApiFunConst.HisDataRequestFun, this.LoginId.Length + 20);
mb.WriteByte(ApiFunConst.RequestAllHisData); mb.WriteByte(ApiFunConst.RequestAllHisData);
mb.WriteString(this.LoginId); mb.WriteString(this.LoginId);
...@@ -625,7 +644,7 @@ namespace DBRunTime.ServiceApi ...@@ -625,7 +644,7 @@ namespace DBRunTime.ServiceApi
} }
finally finally
{ {
mHisRequreData?.ReleaseBuffer(); //mHisRequreData?.ReleaseBuffer();
} }
return null; return null;
} }
...@@ -639,6 +658,7 @@ namespace DBRunTime.ServiceApi ...@@ -639,6 +658,7 @@ namespace DBRunTime.ServiceApi
/// <returns></returns> /// <returns></returns>
public IByteBuffer QueryHisValueAtTimes(int id, List<DateTime> times, Cdy.Tag.QueryValueMatchType matchType, int timeout = 5000) public IByteBuffer QueryHisValueAtTimes(int id, List<DateTime> times, Cdy.Tag.QueryValueMatchType matchType, int timeout = 5000)
{ {
CheckLogin();
var mb = GetBuffer(ApiFunConst.HisDataRequestFun, this.LoginId.Length + times.Count * 8 + 5); var mb = GetBuffer(ApiFunConst.HisDataRequestFun, this.LoginId.Length + times.Count * 8 + 5);
mb.WriteByte(ApiFunConst.RequestHisDatasByTimePoint); mb.WriteByte(ApiFunConst.RequestHisDatasByTimePoint);
mb.WriteString(this.LoginId); mb.WriteString(this.LoginId);
...@@ -661,7 +681,7 @@ namespace DBRunTime.ServiceApi ...@@ -661,7 +681,7 @@ namespace DBRunTime.ServiceApi
} }
finally finally
{ {
mHisRequreData?.ReleaseBuffer(); //mHisRequreData?.ReleaseBuffer();
} }
return null; return null;
} }
...@@ -677,6 +697,7 @@ namespace DBRunTime.ServiceApi ...@@ -677,6 +697,7 @@ namespace DBRunTime.ServiceApi
/// <returns></returns> /// <returns></returns>
public IByteBuffer QueryHisValueForTimeSpan(int id,DateTime startTime,DateTime endTime,TimeSpan span,QueryValueMatchType matchType, int timeout = 5000) public IByteBuffer QueryHisValueForTimeSpan(int id,DateTime startTime,DateTime endTime,TimeSpan span,QueryValueMatchType matchType, int timeout = 5000)
{ {
CheckLogin();
var mb = GetBuffer(ApiFunConst.HisDataRequestFun, this.LoginId.Length + 24+ 5); var mb = GetBuffer(ApiFunConst.HisDataRequestFun, this.LoginId.Length + 24+ 5);
mb.WriteByte(ApiFunConst.RequestHisDataByTimeSpan); mb.WriteByte(ApiFunConst.RequestHisDataByTimeSpan);
mb.WriteString(this.LoginId); mb.WriteString(this.LoginId);
...@@ -696,7 +717,7 @@ namespace DBRunTime.ServiceApi ...@@ -696,7 +717,7 @@ namespace DBRunTime.ServiceApi
} }
finally finally
{ {
mHisRequreData?.ReleaseBuffer(); //mHisRequreData?.ReleaseBuffer();
} }
return null; return null;
} }
......
<?xml version="1.0" encoding="utf-8" ?> <?xml version="1.0" encoding="utf-8" ?>
<Config> <Config>
<ProxyClient Ip="127.0.0.1" Port="14330" LoginUser="Admin" LoginPassword="Admin" WorkMode="0" PollCircle="1000" /> <ProxyClient Ip="127.0.0.1" Port="14330" LoginUser="Admin" LoginPassword="Admin" WorkMode="0" PollCircle="1000" IsUseStandardHisDataServer="false"/>
</Config> </Config>
\ No newline at end of file
...@@ -50,6 +50,8 @@ namespace DBRuntime.Proxy ...@@ -50,6 +50,8 @@ namespace DBRuntime.Proxy
private int mPollCircle = 1000; private int mPollCircle = 1000;
private bool mUseStandardHisDataServer = false;
#endregion ...Variables... #endregion ...Variables...
#region ... Events ... #region ... Events ...
...@@ -131,6 +133,11 @@ namespace DBRuntime.Proxy ...@@ -131,6 +133,11 @@ namespace DBRuntime.Proxy
{ {
mPollCircle = int.Parse(xe.Attribute("PollCircle").Value); mPollCircle = int.Parse(xe.Attribute("PollCircle").Value);
} }
if (xe.Attribute("IsUseStandardHisDataServer") != null)
{
mUseStandardHisDataServer = bool.Parse(xe.Attribute("IsUseStandardHisDataServer").Value);
}
} }
} }
...@@ -139,7 +146,7 @@ namespace DBRuntime.Proxy ...@@ -139,7 +146,7 @@ namespace DBRuntime.Proxy
/// </summary> /// </summary>
public void Start() public void Start()
{ {
mProxy = new DbServerProxy() { UserName = mUserName, Password = mPassword }; mProxy = new DbServerProxy() { UserName = mUserName, Password = mPassword,IsUseStandardHisDataServer= mUseStandardHisDataServer };
mProxy.Connect(mIp, mPort); mProxy.Connect(mIp, mPort);
mProxy.PropertyChanged += MProxy_PropertyChanged; mProxy.PropertyChanged += MProxy_PropertyChanged;
mMonitorThread = new Thread(MonitorThreadPro); mMonitorThread = new Thread(MonitorThreadPro);
......
...@@ -20,6 +20,8 @@ namespace DBRuntime.Proxy ...@@ -20,6 +20,8 @@ namespace DBRuntime.Proxy
ApiClient dbClient; ApiClient dbClient;
ApiClient mHisClient;
private bool mIsConnected; private bool mIsConnected;
private ManualResetEvent resetEvent; private ManualResetEvent resetEvent;
...@@ -33,6 +35,8 @@ namespace DBRuntime.Proxy ...@@ -33,6 +35,8 @@ namespace DBRuntime.Proxy
private bool mIsClosed = false; private bool mIsClosed = false;
ApiClient mUsedHisClient;
#endregion ...Variables... #endregion ...Variables...
#region ... Events ... #region ... Events ...
...@@ -46,7 +50,7 @@ namespace DBRuntime.Proxy ...@@ -46,7 +50,7 @@ namespace DBRuntime.Proxy
/// </summary> /// </summary>
public DbServerProxy() public DbServerProxy()
{ {
Init();
resetEvent = new ManualResetEvent(false); resetEvent = new ManualResetEvent(false);
} }
...@@ -91,6 +95,7 @@ namespace DBRuntime.Proxy ...@@ -91,6 +95,7 @@ namespace DBRuntime.Proxy
} }
} }
public bool IsUseStandardHisDataServer { get; set; } = false;
#endregion ...Properties... #endregion ...Properties...
...@@ -110,6 +115,17 @@ namespace DBRuntime.Proxy ...@@ -110,6 +115,17 @@ namespace DBRuntime.Proxy
{ {
dbClient.Connect(mIp, mPort); dbClient.Connect(mIp, mPort);
} }
if (IsUseStandardHisDataServer)
{
if (!mHisClient.IsConnected)
{
mHisClient.Connect(mIp, mPort + 1);
}
else
{
mHisClient.Login(UserName, Password);
}
}
resetEvent.Set(); resetEvent.Set();
while (!mIsClosed) while (!mIsClosed)
{ {
...@@ -125,6 +141,18 @@ namespace DBRuntime.Proxy ...@@ -125,6 +141,18 @@ namespace DBRuntime.Proxy
{ {
dbClient.Connect(mIp, mPort); dbClient.Connect(mIp, mPort);
} }
if (IsUseStandardHisDataServer)
{
if (mHisClient.IsConnected)
{
mHisClient.Login(UserName, Password);
}
else if (mHisClient.NeedReConnected)
{
mHisClient.Connect(mIp, mPort + 1);
}
}
Thread.Sleep(1000); Thread.Sleep(1000);
} }
else else
...@@ -142,6 +170,31 @@ namespace DBRuntime.Proxy ...@@ -142,6 +170,31 @@ namespace DBRuntime.Proxy
{ {
dbClient = new ApiClient(); dbClient = new ApiClient();
dbClient.PropertyChanged += DbClient_PropertyChanged; dbClient.PropertyChanged += DbClient_PropertyChanged;
if (IsUseStandardHisDataServer)
{
mHisClient = new ApiClient();
mHisClient.PropertyChanged += MHisClient_PropertyChanged;
mUsedHisClient = mHisClient;
}
else
{
mUsedHisClient = dbClient;
}
}
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void MHisClient_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "IsConnected")
{
if (!mHisClient.IsConnected)
resetEvent.Set();
}
} }
/// <summary> /// <summary>
...@@ -166,9 +219,15 @@ namespace DBRuntime.Proxy ...@@ -166,9 +219,15 @@ namespace DBRuntime.Proxy
/// <param name="port"></param> /// <param name="port"></param>
public void Connect(string ip,int port) public void Connect(string ip,int port)
{ {
Init();
mIp = ip; mIp = ip;
mPort = port; mPort = port;
dbClient.Connect(ip, port); dbClient.Connect(ip, port);
if (IsUseStandardHisDataServer)
{
mHisClient.Connect(ip, port + 1);
}
mScanThread = new Thread(ConnectProcess); mScanThread = new Thread(ConnectProcess);
mScanThread.IsBackground = true; mScanThread.IsBackground = true;
mScanThread.Start(); mScanThread.Start();
...@@ -183,6 +242,11 @@ namespace DBRuntime.Proxy ...@@ -183,6 +242,11 @@ namespace DBRuntime.Proxy
resetEvent.Set(); resetEvent.Set();
dbClient.PropertyChanged -= DbClient_PropertyChanged; dbClient.PropertyChanged -= DbClient_PropertyChanged;
dbClient.Close(); dbClient.Close();
if (IsUseStandardHisDataServer)
{
mHisClient.PropertyChanged -= MHisClient_PropertyChanged;
mHisClient.Close();
}
} }
/// <summary> /// <summary>
...@@ -424,8 +488,8 @@ namespace DBRuntime.Proxy ...@@ -424,8 +488,8 @@ namespace DBRuntime.Proxy
{ {
if (IsConnected) if (IsConnected)
{ {
var res = dbClient.QueryAllHisValue(id, stime, etime); var res = this.mUsedHisClient.QueryAllHisValue(id, stime, etime);
if (res == null || res.ReadableBytes == 0) return null; if (res == null || res.ReferenceCount == 0) return null;
TagType tp = (TagType)res.ReadByte(); TagType tp = (TagType)res.ReadByte();
switch (tp) switch (tp)
{ {
...@@ -489,7 +553,7 @@ namespace DBRuntime.Proxy ...@@ -489,7 +553,7 @@ namespace DBRuntime.Proxy
{ {
if (IsConnected) if (IsConnected)
{ {
var res = dbClient.QueryHisValueForTimeSpan(id, stime, etime, span, type); var res = mUsedHisClient.QueryHisValueForTimeSpan(id, stime, etime, span, type);
if (res == null) return null; if (res == null) return null;
TagType tp = (TagType)res.ReadByte(); TagType tp = (TagType)res.ReadByte();
switch (tp) switch (tp)
...@@ -544,7 +608,7 @@ namespace DBRuntime.Proxy ...@@ -544,7 +608,7 @@ namespace DBRuntime.Proxy
{ {
if (IsConnected) if (IsConnected)
{ {
var res = dbClient.QueryHisValueAtTimes(id, times, type); var res = mUsedHisClient.QueryHisValueAtTimes(id, times, type);
if (res == null) return null; if (res == null) return null;
TagType tp = (TagType)res.ReadByte(); TagType tp = (TagType)res.ReadByte();
switch (tp) switch (tp)
......
...@@ -5,6 +5,8 @@ using System.Linq; ...@@ -5,6 +5,8 @@ using System.Linq;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using System.Diagnostics; using System.Diagnostics;
using System.IO.Pipes;
using System.Threading;
namespace DBStudio namespace DBStudio
{ {
...@@ -46,7 +48,7 @@ namespace DBStudio ...@@ -46,7 +48,7 @@ namespace DBStudio
else if (cmsg == "db") else if (cmsg == "db")
{ {
if (cmd.Length > 1) if (cmd.Length > 1)
ProcessDatabaseCreat(cmd[1]); ProcessDatabaseCreate(cmd[1]);
} }
else if (cmsg == "list") else if (cmsg == "list")
{ {
...@@ -144,7 +146,7 @@ namespace DBStudio ...@@ -144,7 +146,7 @@ namespace DBStudio
/// ///
/// </summary> /// </summary>
/// <param name="name"></param> /// <param name="name"></param>
private static void ProcessDatabaseCreat(string name) private static void ProcessDatabaseCreate(string name)
{ {
if (!DBDevelopService.DbManager.Instance.IsLoaded) if (!DBDevelopService.DbManager.Instance.IsLoaded)
DBDevelopService.DbManager.Instance.Load(); DBDevelopService.DbManager.Instance.Load();
...@@ -187,9 +189,36 @@ namespace DBStudio ...@@ -187,9 +189,36 @@ namespace DBStudio
} }
else if (cmsg == "start") else if (cmsg == "start")
{ {
if (!CheckStart(db.Name))
{
StartDb(db.Name);
}
else
{
Console.WriteLine("database " + db.Name + " is in running.");
}
}
else if (cmsg == "restart")
{
StopDatabase(db.Name);
while (CheckStart(db.Name)) Thread.Sleep(100);
StartDb(db.Name); StartDb(db.Name);
} }
else if (cmsg == "isstart")
{
if(CheckStart(db.Name))
{
Console.WriteLine("database "+db.Name+" is start.");
}
else
{
Console.WriteLine("database " + db.Name + " is stop.");
}
}
else if (cmsg == "stop")
{
StopDatabase(db.Name);
}
else if (cmsg == "updatehis") else if (cmsg == "updatehis")
{ {
UpdateHisTag(db, cmd[1].ToLower(), cmd[2], cmd[3]); UpdateHisTag(db, cmd[1].ToLower(), cmd[2], cmd[3]);
...@@ -233,7 +262,7 @@ namespace DBStudio ...@@ -233,7 +262,7 @@ namespace DBStudio
break; break;
} }
} }
catch catch(Exception ex)
{ {
OutByLine(name, Res.Get("ErroParameter")); OutByLine(name, Res.Get("ErroParameter"));
} }
...@@ -365,6 +394,9 @@ namespace DBStudio ...@@ -365,6 +394,9 @@ namespace DBStudio
{ {
StringBuilder re = new StringBuilder(); StringBuilder re = new StringBuilder();
re.AppendLine(); re.AppendLine();
re.AppendLine("start // start database ");
re.AppendLine("restart // restart database ");
re.AppendLine("stop // stop database ");
re.AppendLine("add [tagtype] [tagname] [linkaddress] [repeat] // add numbers tag to database "); re.AppendLine("add [tagtype] [tagname] [linkaddress] [repeat] // add numbers tag to database ");
re.AppendLine("remove [tagname] // remove a tag"); re.AppendLine("remove [tagname] // remove a tag");
re.AppendLine("clear // clear all tags in database"); re.AppendLine("clear // clear all tags in database");
...@@ -1079,7 +1111,45 @@ namespace DBStudio ...@@ -1079,7 +1111,45 @@ namespace DBStudio
return re.ToString(); return re.ToString();
} }
public static void StopDatabase(string name)
{
using (var client = new NamedPipeClientStream(".", name, PipeDirection.InOut))
{
try
{
client.Connect(2000);
client.WriteByte(0);
client.WaitForPipeDrain();
var res = client.ReadByte();
if (res == 1)
{
Console.WriteLine("Stop database" + name + " sucessfull.");
}
}
catch
{
Console.WriteLine("Stop database " + name + " failed.");
}
}
}
public static bool CheckStart(string name)
{
using (var client = new NamedPipeClientStream(".", name, PipeDirection.InOut))
{
try
{
client.Connect(1000);
client.Close();
return true;
}
catch
{
return false;
}
}
}
} }
} }
......
...@@ -80,6 +80,7 @@ namespace DBRuntime.Api ...@@ -80,6 +80,7 @@ namespace DBRuntime.Api
mChangedTags.Add(vv, true); mChangedTags.Add(vv, true);
} }
} }
if(!mIsClosed)
resetEvent.Set(); resetEvent.Set();
}), new Func<List<int>>(() => { return new List<int>() { -1 }; })); }), new Func<List<int>>(() => { return new List<int>() { -1 }; }));
mTagManager = ServiceLocator.Locator.Resolve<ITagManager>(); mTagManager = ServiceLocator.Locator.Resolve<ITagManager>();
......
<?xml version="1.0" encoding="utf-8" ?> <?xml version="1.0" encoding="utf-8" ?>
<Config> <Config>
<ProxyClient Ip="127.0.0.1" Port="14330" LoginUser="Admin" LoginPassword="Admin" WorkMode="0" PollCircle="1000" /> <ProxyClient Ip="127.0.0.1" Port="14330" LoginUser="Admin" LoginPassword="Admin" WorkMode="0" PollCircle="1000" IsUseStandardHisDataServer="false"/>
</Config> </Config>
\ No newline at end of file
...@@ -51,7 +51,9 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DBRunTime.ServiceApi", "DBR ...@@ -51,7 +51,9 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DBRunTime.ServiceApi", "DBR
EndProject EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DBRuntime.Real", "DBRuntime.Real\DBRuntime.Real.csproj", "{55D1E991-570C-4357-8A7D-73756AA96B83}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DBRuntime.Real", "DBRuntime.Real\DBRuntime.Real.csproj", "{55D1E991-570C-4357-8A7D-73756AA96B83}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DBRuntime.Proxy", "DBRuntime.Proxy\DBRuntime.Proxy.csproj", "{A346892B-AA87-40D0-8537-1E3C2CD285E3}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DBRuntime.Proxy", "DBRuntime.Proxy\DBRuntime.Proxy.csproj", "{A346892B-AA87-40D0-8537-1E3C2CD285E3}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DBHisDataServer", "DBHisDataServer\DBHisDataServer.csproj", "{C022701B-B2F7-429A-850F-C50CDC15B925}"
EndProject EndProject
Global Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution GlobalSection(SolutionConfigurationPlatforms) = preSolution
...@@ -143,6 +145,10 @@ Global ...@@ -143,6 +145,10 @@ Global
{A346892B-AA87-40D0-8537-1E3C2CD285E3}.Debug|Any CPU.Build.0 = Debug|Any CPU {A346892B-AA87-40D0-8537-1E3C2CD285E3}.Debug|Any CPU.Build.0 = Debug|Any CPU
{A346892B-AA87-40D0-8537-1E3C2CD285E3}.Release|Any CPU.ActiveCfg = Release|Any CPU {A346892B-AA87-40D0-8537-1E3C2CD285E3}.Release|Any CPU.ActiveCfg = Release|Any CPU
{A346892B-AA87-40D0-8537-1E3C2CD285E3}.Release|Any CPU.Build.0 = Release|Any CPU {A346892B-AA87-40D0-8537-1E3C2CD285E3}.Release|Any CPU.Build.0 = Release|Any CPU
{C022701B-B2F7-429A-850F-C50CDC15B925}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{C022701B-B2F7-429A-850F-C50CDC15B925}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C022701B-B2F7-429A-850F-C50CDC15B925}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C022701B-B2F7-429A-850F-C50CDC15B925}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection EndGlobalSection
GlobalSection(SolutionProperties) = preSolution GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE HideSolutionNode = FALSE
...@@ -169,6 +175,7 @@ Global ...@@ -169,6 +175,7 @@ Global
{A1C80D29-71CE-4EBC-982C-C94B9263F7F8} = {95F6A9D4-42A9-483A-80F8-EADDD6CEFEDE} {A1C80D29-71CE-4EBC-982C-C94B9263F7F8} = {95F6A9D4-42A9-483A-80F8-EADDD6CEFEDE}
{55D1E991-570C-4357-8A7D-73756AA96B83} = {95F6A9D4-42A9-483A-80F8-EADDD6CEFEDE} {55D1E991-570C-4357-8A7D-73756AA96B83} = {95F6A9D4-42A9-483A-80F8-EADDD6CEFEDE}
{A346892B-AA87-40D0-8537-1E3C2CD285E3} = {95F6A9D4-42A9-483A-80F8-EADDD6CEFEDE} {A346892B-AA87-40D0-8537-1E3C2CD285E3} = {95F6A9D4-42A9-483A-80F8-EADDD6CEFEDE}
{C022701B-B2F7-429A-850F-C50CDC15B925} = {95F6A9D4-42A9-483A-80F8-EADDD6CEFEDE}
EndGlobalSection EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {577CCEC3-4CDB-458A-B93D-F8579C2C3D8F} SolutionGuid = {577CCEC3-4CDB-458A-B93D-F8579C2C3D8F}
......
...@@ -164,7 +164,7 @@ namespace SimDriver ...@@ -164,7 +164,7 @@ namespace SimDriver
Stopwatch sw = new Stopwatch(); Stopwatch sw = new Stopwatch();
sw.Start(); sw.Start();
//if(mNumber%10==0) //if(mNumber%10==0)
Log("Sim:Sin " + fval + " " + "Sim:Cos " + sval + " " + "Sim:step " + mNumber + " " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")); //Log("Sim:Sin " + fval + " " + "Sim:Cos " + sval + " " + "Sim:step " + mNumber + " " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));
//#endif //#endif
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册