@@ -28,6 +28,8 @@ sealed class OpcServer : IOpcServer
2828 /// </summary>
2929 public bool IsConnected => _server ? . IsConnected ?? false ;
3030
31+ private readonly Dictionary < string , ISubscription > _subscriptions = [ ] ;
32+
3133 /// <summary>
3234 /// 连接到 OPCServer 方法
3335 /// </summary>
@@ -60,6 +62,7 @@ public void Disconnect()
6062 {
6163 _server . CancelSubscription ( sub ) ;
6264 }
65+
6366 _server . Disconnect ( ) ;
6467 _server = null ;
6568 }
@@ -72,28 +75,33 @@ public void Disconnect()
7275 /// <param name="updateRate">更新频率 默认 1000 毫秒</param>
7376 /// <param name="active">是否激活 默认 true</param>
7477 /// <returns></returns>
75- public ISubscription CreateSubscription ( string name , int updateRate = 1000 , bool active = true )
78+ public IOpcSubscription CreateSubscription ( string name , int updateRate = 1000 , bool active = true )
7679 {
7780 var server = GetOpcServer ( ) ;
78- var subscription = server . CreateSubscription ( new SubscriptionState
81+ if ( _subscriptions . TryGetValue ( name , out var subscription ) )
7982 {
80- Name = name ,
81- Deadband = 0 ,
82- UpdateRate = updateRate ,
83- Active = active
84- } ) ;
83+ // 已经存在该订阅
84+ server . CancelSubscription ( subscription ) ;
85+ }
86+
87+ subscription = server . CreateSubscription ( name , updateRate , active ) ;
88+ _subscriptions . Add ( name , subscription ) ;
8589 return subscription . ToOpcSubscription ( ) ;
8690 }
8791
8892 /// <summary>
8993 /// 取消订阅方法
9094 /// </summary>
91- /// <param name="subscription">订阅接口 <see cref="ISubscription "/> 实例</param>
95+ /// <param name="subscription">订阅接口 <see cref="IOpcSubscription "/> 实例</param>
9296 /// <returns></returns>
93- public void CancelSubscription ( ISubscription subscription )
97+ public void CancelSubscription ( IOpcSubscription subscription )
9498 {
9599 var server = GetOpcServer ( ) ;
96- server . CancelSubscription ( subscription . GetSubscription ( ) ) ;
100+ var name = subscription . Name ;
101+ if ( _subscriptions . Remove ( name , out var sub ) )
102+ {
103+ server . CancelSubscription ( sub ) ;
104+ }
97105 }
98106
99107 /// <summary>
@@ -121,16 +129,17 @@ public HashSet<OpcWriteItem> Write(params HashSet<OpcWriteItem> items)
121129 return items . Select ( i =>
122130 {
123131 var item = results . FirstOrDefault ( v => v . ItemName == i . Name ) ;
124- return new OpcWriteItem ( i . Name , i . Value ) { Result = item != null && item . ResultID == ResultID . S_OK } ;
132+ return i with { Result = item != null && item . ResultID == ResultID . S_OK } ;
125133 } ) . ToHashSet ( OpcItemEqualityComparer < OpcWriteItem > . Default ) ;
126134 }
127135
128136 private Opc . Da . Server GetOpcServer ( )
129137 {
130- if ( _server is not { IsConnected : true } )
138+ if ( _server is not { IsConnected : true } )
131139 {
132140 throw new InvalidOperationException ( "OPC Server is not connected." ) ;
133141 }
142+
134143 return _server ;
135144 }
136145
0 commit comments