@ -1,8 +1,7 @@
using Newtonsoft.Js on;
using Newtonsoft.Json.Linq ;
using EC.Util.Comm on;
using System.Collections.Concurrent ;
using System.Net ;
using System.Net.Sockets ;
using System.Text ;
using System.Timers ;
using Timer = System . Timers . Timer ;
namespace JiLinApp.Docking.VibrateAlarm ;
@ -11,675 +10,506 @@ public class TcpManager
{
#region Fields
private JsonSerializerSettings jSetting { get ; } = new ( ) ;
private AsyncTcpServer Server { get ; set ; }
private AsyncTcpServer server { get ; s et; } = null ;
private ConcurrentDictionary < string , ClientMessage > ClientMessageDict { g et; } = new ( ) ;
private Timer stateSpan Timer { get ; } = new ( ) ;
private Timer Heart Timer { get ; } = new ( ) ;
private Timer heart Timer { get ; } = new ( ) ;
private Timer StateSpan Timer { get ; } = new ( ) ;
private List < ClientMessage > list { get ; } = new ( ) ;
public delegate void TcpDeviceMessageEvent ( TcpAlarmHostTable host , string msg ) ;
public delegate void TcpSensorMessageEvent ( TcpAlarmHostTable host , TcpSensorTable section , string msg ) ;
public delegate void TcpSensorStateChangeEvent ( SensorState state ) ;
public delegate void TcpSensorAlarmEvent ( TcpAlarmHostMessage msg ) ;
public event TcpDeviceMessageEvent OnTcpDeviceMessage ;
public event TcpSensorMessageEvent OnTcpSensorMessage ;
public event TcpSensorStateChangeEvent OnTcpSensorStateChange ;
public event TcpSensorAlarmEvent OnTcpSensorAlarm ;
#endregion Fields
public TcpManager ( )
{
jSetting . NullValueHandling = NullValueHandling . Ignore ;
jSetting . DefaultValueHandling = DefaultValueHandling . Ignore ;
}
#region BaseMethod
#region Server
public void StartServer ( TcpManagerConfig config )
public void Start ( TcpManagerConfig config )
{
if ( IsRunning ( ) ) return ;
IPAddress address = IPAddress . Any ;
_ = IPAddress . TryParse ( config . ServerIp , out address ) ;
server = new AsyncTcpServer ( address , config . ServerPort ) ;
server . ClientConnected + = server_ClientConnected ;
server . ClientDisconnected + = server_ClientDisconnected ;
server . DatagramReceived + = server_DatagramReceived ;
server . Start ( ) ;
Server = new AsyncTcpServer ( IPAddress . Any , config . ServerPort ) ;
Server . ClientConnected + = Server_ClientConnected ;
Server . ClientDisconnected + = Server_ClientDisconnected ;
Server . DatagramReceived + = Server_DatagramReceived ;
Server . Start ( ) ;
h eartTimer. Close ( ) ;
h eartTimer. Interval = 1 0 0 0 * config . DeviceHeartKeep ;
h eartTimer. Elapsed + = HeartTimer_Elapsed ;
h eartTimer. Enabled = true ;
h eartTimer. Start ( ) ;
HeartTimer . Close ( ) ;
HeartTimer . Interval = 1 0 0 0 * config . DeviceHeartKeep ;
H eartTimer. Elapsed + = HeartTimer_Elapsed ;
H eartTimer. Enabled = true ;
H eartTimer. Start ( ) ;
}
public void StopServer ( )
{
heartTimer . Enabled = false ;
if ( IsRunning ( ) )
public void Stop ( )
{
server . Stop ( ) ;
server = null ;
}
HeartTimer . Enabled = false ;
if ( IsRunning ( ) ) Server . Stop ( ) ;
}
public bool IsRunning ( )
{
return s erver ! = null & & s erver. IsRunning ;
return S erver ! = null & & S erver. IsRunning ( ) ;
}
public bool StartScan ( ref string error )
{
if ( server = = null )
{
error = "服务未创建" ;
return false ;
}
if ( ! server . IsRunning )
{
error = "服务未运行" ;
return false ;
}
stateSpanTimer . Enabled = true ;
return true ;
}
#endregion Server
public void StopScan ( )
{
stateSpanTimer . Enabled = false ;
}
#endregion BaseMethod
#region Register Event
private void StateSpan Timer_Elapsed( object sender , System . Timers . ElapsedEventArgs e )
private void HeartTimer_Elapsed ( object? sender , ElapsedEventArgs e )
{
string error = "" ;
for ( int i = 0 ; i < list . Count ; i + + )
foreach ( var clientMsg in ClientMessageDict . Values )
{
sendState ( list [ i ] , ref error ) ;
SendHostHeart_01 ( clientMsg ) ;
}
}
private void Heart Timer_Elapsed( object sender , System . Timers . ElapsedEventArgs e )
private void StateSpanTimer_Elapsed ( object? sender , ElapsedEventArgs e )
{
string error = "" ;
for ( int i = 0 ; i < list . Count ; i + + )
foreach ( var clientMsg in ClientMessageDict . Values )
{
sendHeart ( list [ i ] , ref error ) ;
RequestSensorState_04 ( clientMsg ) ;
}
}
private ClientMessage GetClientMessage ( TcpClient client )
private void Server_ClientConnected ( object? sender , TcpClientConnectedEventArgs e )
{
string clientIP = client . Client . RemoteEndPoint . ToString ( ) . Split ( ':' ) [ 0 ] ;
for ( int i = 0 ; i < list . Count ; i + + )
string clientKey = e . TcpClient . Client . RemoteEndPoint ? . ToString ( ) ? ? "" ;
if ( clientKey = = "" ) return ;
string clientIp = clientKey . Split ( ':' ) [ 0 ] ;
string clientPort = clientKey . Split ( ':' ) [ 1 ] ;
Console . WriteLine ( "上线:{0}" , clientIp ) ;
if ( ! TryGetClientMessage ( clientIp , out ClientMessage clientMsg ) )
{
if ( list [ i ] . IP = = clientIP )
clientMsg = new ( )
{
return list [ i ] ;
Client = e . TcpClient ,
Host = new ( ) { Id = - 1 , Ip = clientIp , Port = clientPort , Name = "未知设备" }
} ;
AddClientMessage ( clientIp , clientMsg ) ;
}
if ( OnTcpDeviceMessage ! = null )
{
TcpAlarmHostTable host = clientMsg . Host ? ? new ( ) { Id = - 1 , Ip = clientIp , Port = clientPort , Name = "未知设备" } ;
OnTcpDeviceMessage ( host , "报警主机上线" ) ;
}
return null ;
}
private ClientMessage GetClientMessageIP ( string clientIP )
private void Server_ClientDisconnected ( object? sender , TcpClientDisconnectedEventArgs e )
{
for ( int i = 0 ; i < list . Count ; i + + )
string clientKey = e . TcpClient . Client . RemoteEndPoint ? . ToString ( ) ? ? "" ;
if ( clientKey = = "" ) return ;
string clientIp = clientKey . Split ( ':' ) [ 0 ] ;
string clientPort = clientKey . Split ( ':' ) [ 1 ] ;
Console . WriteLine ( "下线:{0}" , clientIp ) ;
if ( TryGetClientMessage ( clientIp , out ClientMessage clientMsg ) )
{
if ( list [ i ] . IP = = clientIP )
RemoveClientMessage ( clientIp ) ;
if ( OnTcpDeviceMessage ! = null )
{
return list [ i ] ;
TcpAlarmHostTable host = clientMsg . Host ? ? new ( ) { Id = - 1 , Ip = clientIp , Port = clientPort , Name = "未知设备" } ;
OnTcpDeviceMessage ( host , "报警主机下线" ) ;
}
}
return null ;
}
private ClientMessage GetClientMessageDeviceID ( int deviceId )
{
for ( int i = 0 ; i < list . Count ; i + + )
private void Server_DatagramReceived ( object? sender , TcpDatagramReceivedEventArgs < byte [ ] > e )
{
if ( list [ i ] . host ! = null & & list [ i ] . host . id = = deviceId )
string clientKey = e . TcpClient . TcpClient . Client . RemoteEndPoint ? . ToString ( ) ? ? "" ;
if ( clientKey = = "" ) return ;
string clientIp = clientKey . Split ( ':' ) [ 0 ] ;
if ( TryGetClientMessage ( clientIp , out ClientMessage clientMsg ) )
{
return list [ i ] ;
}
clientMsg . AddData ( e . Datagram ) ;
AnalysisClientMessage ( clientMsg ) ;
}
return null ;
}
public delegate void TCPSectionAlarmOnEvent ( TcpAlarmHostMessage msg ) ;
public event TCPSectionAlarmOnEvent OnTcpSectionAlarmOn ;
public delegate void TCPSectionStateChangeEvent ( SectionState state ) ;
public event TCPSectionStateChangeEvent OnTcpSectionStateChange ;
#endregion Register Event
public delegate void TCPDeviceMessageEvent ( TcpAlarmHostTable host , string msg ) ;
#region ClientMessage
public event TCPDeviceMessageEvent OnTcpDeviceMessage ;
public delegate void TCPSectionMessageEvent ( TcpAlarmHostTable host , TcpSectionTable section , string msg ) ;
public event TCPSectionMessageEvent OnTcpSectionMessage ;
private void server_DatagramReceived ( object sender , TcpDatagramReceivedEventArgs < byte [ ] > e )
private bool ContainsClientMessage ( string clientIp )
{
string clientIP = e . TcpClient . TcpClient . Client . RemoteEndPoint . ToString ( ) . Split ( ':' ) [ 0 ] ;
ClientMessage client = GetClientMessage ( e . TcpClient . TcpClient ) ;
if ( client ! = null )
{
AnalysisClientMessage ( client , e . Datagram ) ;
}
return ClientMessageDict . ContainsKey ( clientIp ) ;
}
public void TestAlarm ( string devideId , string channel )
private ClientMessage GetClientMessage ( string clientIp )
{
ClientMessage message = new ClientMessage ( ) ;
message . client = new TcpClient ( "127.0.0.1" , 5 0 8 0 ) ;
list . Add ( message ) ;
byte [ ] bytes1 = BitConverter . GetBytes ( int . Parse ( devideId ) ) ;
byte [ ] bytes2 = BitConverter . GetBytes ( int . Parse ( channel ) ) ;
byte [ ] bytes = new byte [ 2 4 ] {
0xAA , 0xAA , bytes1 [ 0 ] , bytes1 [ 1 ] ,
1 2 7 , 0 , 0 , 1 ,
0x00 , 0x00 , 1 2 7 , 0 ,
0 , 1 , 0x00 , 0x00 ,
1 , 0x14 , 0x04 , bytes2 [ 0 ] ,
bytes2 [ 1 ] , 0x02 , 0x00 , 0x00
} ;
AnalysisClientMessage ( message , bytes ) ;
return ClientMessageDict [ clientIp ] ;
}
private string ToHexString ( byte [ ] bytes )
private bool TryGetClientMessage ( string clientIp , out ClientMessage clientMsg )
{
string hexString = string . Empty ;
return ClientMessageDict . TryGetValue ( clientIp , out clientMsg ) ;
}
if ( bytes ! = null )
private bool AddClientMessage ( string clientIp , ClientMessage clientMsg )
{
StringBuilder strB = new StringBuilder ( ) ;
if ( ContainsClientMessage ( clientIp ) ) return false ;
ClientMessageDict [ clientIp ] = clientMsg ;
return true ;
}
for ( int i = 0 ; i < bytes . Length ; i + + )
private void SetClientMessage ( string clientIp , ClientMessage clientMsg )
{
strB . Append ( bytes [ i ] . ToString ( "X2" ) + " " ) ;
ClientMessageDict [ clientIp ] = clientMsg ;
}
hexString = strB . ToString ( ) ;
private bool RemoveClientMessage ( string clientIp )
{
return ClientMessageDict . Remove ( clientIp , out _ ) ;
}
return hexString ;
private bool UpdateClientMessage ( string clientIp , TcpAlarmHostTable host )
{
if ( ! ClientMessageDict . ContainsKey ( clientIp ) ) return false ;
ClientMessageDict [ clientIp ] . Host = host ;
return true ;
}
private void AnalysisClientMessage ( ClientMessage client , byte [ ] bytes )
private bool UpdateClientMessage ( string clientIp , List < byte > sensorList )
{
client . list . AddRange ( bytes ) ;
if ( ! ClientMessageDict . ContainsKey ( clientIp ) ) return false ;
ClientMessageDict [ clientIp ] . SensorList = sensorList ;
return true ;
}
List < byte [ ] > msglist = client . getMessageList ( ) ;
if ( msglist ! = null & & msglist . Count > 0 )
#endregion ClientMessage
#region Analysis
private void AnalysisClientMessage ( ClientMessage clientMsg )
{
//AA AA 01 C0 A8 01 64 88 13 C0 A8 01 05 28 23 74 00 01 01 18
//AA AA 01 C0 A8 01 05 28 23 C0 A8 01 64 88 13 7C 04 02 04 00 2B
//AA AA 01 C0 A8 01 64 88 13 C0 A8 01 05 28 23 24 14 04 0A 00 02 00 03
List < byte [ ] > msglist = clientMsg . GetMessageList ( ) ;
if ( msglist = = null | | msglist . Count = = 0 ) return ;
for ( int i = 0 ; i < msglist . Count ; i + + )
{
Console . WriteLine ( client . IP + " 收到数据:" + ToHexString ( msglist [ i ] ) ) ;
DataMessage mm = new DataMessage ( ) ;
mm . decode ( msglist [ i ] ) ;
switch ( mm . functionNum )
DataMessage mm = new ( ) ;
mm . Decode ( msglist [ i ] ) ;
Console . WriteLine ( "Receive from {0}:{1} => {2}, {3}" , clientMsg . Ip , clientMsg . Port , DataMessage . ToHexString ( msglist [ i ] ) , JsonUtil . ToJson ( mm ) ) ;
TcpAlarmHostTable host ;
switch ( mm . FunctionNum )
{
case 0x00 :
Console . WriteLine ( client . IP + " 登录" ) ;
if ( client . host = = null | | client . host . id ! = mm . deviceID )
{
//string error = "";
//JArray arr = DBCenter.center.SearchByConditionJArray("table_TCPAlarmHost", "id=" + mm.deviceID, ref error);
JArray arr = new ( ) ;
if ( arr ! = null & & arr . Count > 0 )
Console . WriteLine ( "主机登录:{0}" , clientMsg . Ip ) ;
if ( clientMsg . Host = = null | | clientMsg . Host . Id ! = mm . DeviceId )
{
client . host = JsonConvert . DeserializeObject < TcpAlarmHostTable > ( arr [ 0 ] . ToString ( ) , jSetting ) ;
client . host . ip = mm . sendIP ;
client . host . port = mm . sendPort . ToString ( ) ;
clientMsg . Host = new ( ) { Id = mm . DeviceId , Ip = mm . SendIp , Port = mm . SendPort . ToString ( ) , Name = "未知设备" } ;
UpdateClientMessage ( clientMsg . Ip , clientMsg . Host ) ;
}
}
if ( OnTcpDeviceMessage ! = null )
ResponseHostLogin_10 ( clientMsg , mm ) ;
if ( clientMsg . SensorListEmpty & & clientMsg . SensorListLock . TryEnterWriteLock ( 1 0 0 0 ) )
{
if ( client . host ! = null )
Task . Run ( ( ) = >
{
OnTcpDeviceMessage ( client . host , "报警主机登录" ) ;
}
else
while ( clientMsg . SensorListEmpty )
{
OnTcpDeviceMessage ( new TcpAlarmHostTable ( ) { id = mm . deviceID , ip = mm . sendIP , port = mm . sendPort . ToString ( ) , name = "未知设备" } , "报警主机登录" ) ;
RequestSensorList_07 ( clientMsg ) ;
Thread . Sleep ( 1 0 0 0 ) ;
}
clientMsg . SensorListLock . ExitWriteLock ( ) ;
} ) ;
}
if ( OnTcpDeviceMessage ! = null )
{
host = clientMsg . Host ? ? new ( ) { Id = mm . DeviceId , Ip = mm . SendIp , Port = mm . SendPort . ToString ( ) , Name = "未知设备" } ;
OnTcpDeviceMessage ( host , "报警主机登录" ) ;
}
break ;
case 0x01 :
Console . WriteLine ( client . IP + " 心跳" ) ;
Console . WriteLine ( "心跳:{0}" , clientMsg . Ip ) ;
break ;
case 0x12 :
Console . WriteLine ( client . IP + "传感器地址设置响应" ) ;
Console . WriteLine ( "传感器地址设置响应:{0}" , clientMsg . Ip ) ;
SetDataRequest ( mm , 0x02 ) ;
break ;
case 0x13 :
Console . WriteLine ( client . IP + "传感器模式设置响应" ) ;
Console . WriteLine ( "传感器模式设置响应:{0}" , clientMsg . Ip ) ;
SetDataRequest ( mm , 0x03 ) ;
break ;
case 0x14 :
Console . WriteLine ( client . IP + "传感器状态响应" ) ;
int channel = mm . d ata[ 0 ] + mm . d ata[ 1 ] * 2 5 6 ;
int state = mm . d ata[ 2 ] + mm . d ata[ 3 ] * 2 5 6 ;
Console . WriteLine ( "传感器状态响应:{0}" , clientMsg . Ip ) ;
int channel = mm . D ata[ 0 ] + mm . D ata[ 1 ] * 2 5 6 ;
int state = mm . D ata[ 2 ] + mm . D ata[ 3 ] * 2 5 6 ;
int online = state % 2 ;
int alarm = state / 2 % 2 ;
TcpAlarmHostTable host = new ( ) { id = mm . deviceID , ip = mm . sendIP , port = mm . sendPort . ToString ( ) , name = "未知设备" } ;
ProcessOnlineEvent ( client , host , mm , channel , online ) ;
ProcessAlarmEvent ( client , host , mm , channel , alarm ) ;
UpdateOnLineAlarm ( client , host , channel , online , alarm ) ;
if ( clientMsg . Host = = null | | clientMsg . Host . Id ! = mm . DeviceId )
{
clientMsg . Host = new ( ) { Id = mm . DeviceId , Ip = mm . SendIp , Port = mm . SendPort . ToString ( ) , Name = "未知设备" } ;
UpdateClientMessage ( clientMsg . Ip , clientMsg . Host ) ;
}
ProcessOnlineEvent ( clientMsg , mm , channel , online ) ;
ProcessAlarmEvent ( clientMsg , mm , channel , alarm ) ;
UpdateOnLineAlarm ( clientMsg , channel , online , alarm ) ;
SetDataRequest ( mm , 0x04 ) ;
if ( alarm = = 1 )
{
RequestSensorReset_05 ( clientMsg ) ;
}
break ;
case 0x15 :
Console . WriteLine ( client . IP + "传感器复位响应" ) ;
Console . WriteLine ( "传感器复位响应:{0}" , clientMsg . Ip ) ;
SetDataRequest ( mm , 0x05 ) ;
break ;
case 0x17 :
Console . WriteLine ( "返回传感器列表:{0}" , clientMsg . Ip ) ;
if ( clientMsg . Host = = null | | clientMsg . Host . Id ! = mm . DeviceId )
{
clientMsg . Host = new ( ) { Id = mm . DeviceId , Ip = mm . SendIp , Port = mm . SendPort . ToString ( ) , Name = "设备" } ;
UpdateClientMessage ( clientMsg . Ip , clientMsg . Host ) ;
}
if ( clientMsg . SensorListEmpty )
{
List < byte > sensorList = new ( ) ;
for ( int j = 2 ; j < mm . Data . Length ; j + + )
{
sensorList . Add ( Convert . ToByte ( ( mm . Data [ j ] + mm . Data [ + + j ] * 2 5 6 ) ) ) ;
}
clientMsg . SensorList = sensorList ;
UpdateClientMessage ( clientMsg . Ip , sensorList ) ;
RequestSensorState_04 ( clientMsg ) ;
}
SetDataRequest ( mm , 0x07 ) ;
break ;
}
}
}
private void ProcessOnlineEvent ( ClientMessage client , TcpAlarmHostTable host , DataMessage mm , int channel , int online )
private void ProcessOnlineEvent ( ClientMessage client , DataMessage mm , int channel , int online )
{
if ( client . sectioTable . ContainsKey ( channel ) )
if ( client . Section Table. ContainsKey ( channel ) )
{
SectionState oldState = client . sectioTable [ channel ] as SectionState ;
Sensor State oldState = client . Section Table[ channel ] as Sensor State ;
if ( oldState . online = = online ) return ;
}
TcpAlarmHostTable host1 = client . host = = null ? host : client . host ;
string error = "" ;
TcpSectionTable section = new TcpSectionTable ( ) { deviceID = host . id , name = "未知传感器" , channel = channel . ToString ( ) } ;
//JArray arr = DBCenter.center.SearchByConditionJArray("table_TCPSection", "deviceID=" + mm.deviceID + "/channel='" + channel + "'", ref error);
JArray arr = new ( ) ;
if ( arr ! = null & & arr . Count > 0 ) section = JsonConvert . DeserializeObject < TcpSectionTable > ( arr [ 0 ] . ToString ( ) , jSetting ) ;
if ( OnTcpSectionMessage ! = null )
{
OnTcpSectionMessage ( host1 , section , online = = 0 ? "传感器上线" : "传感器离线" ) ;
}
TcpAlarmHostTable host = client . Host ;
TcpSensorTable section = new ( ) { DeviceId = host . Id , Name = "未知传感器" , Channel = channel . ToString ( ) } ;
OnTcpSensorMessage ? . Invoke ( host , section , online = = 0 ? "传感器上线" : "传感器离线" ) ;
}
private void ProcessAlarmEvent ( ClientMessage client , TcpAlarmHostTable host , DataMessage mm , int channel , int alarm )
private void ProcessAlarmEvent ( ClientMessage client , DataMessage mm , int channel , int alarm )
{
if ( client . sectio Table. ContainsKey ( channel ) )
if ( client . SectionTable . ContainsKey ( channel ) )
{
Section State oldState = client . sectio Table[ channel ] as Section State ;
SensorState oldState = client . SectionTable [ channel ] as SensorState ;
if ( oldState . alarm = = alarm ) return ;
}
TcpAlarmHostTable host1 = client . host = = null ? host : client . h ost;
TcpAlarmHostTable host = client . H ost;
if ( alarm = = 1 )
{
ProcessAlarm ( host1 . i d , channel , alarm ) ;
ProcessAlarm ( host . I d, channel ) ;
}
}
private void UpdateOnLineAlarm ( ClientMessage client , TcpAlarmHostTable host , int channel , int online , int alarm )
private void UpdateOnLineAlarm ( ClientMessage client , int channel , int online , int alarm )
{
if ( client . sectio Table. ContainsKey ( channel ) )
if ( client . Section Table. ContainsKey ( channel ) )
{
Section State oldState = client . sectio Table[ channel ] as Section State ;
Sensor State oldState = client . Section Table[ channel ] as Sensor State ;
oldState . online = online ;
oldState . alarm = alarm ;
if ( OnTcpSectionStateChange ! = null )
{
OnTcpSectionStateChange ( oldState ) ;
}
OnTcpSensorStateChange ? . Invoke ( oldState ) ;
}
else
{
TcpAlarmHostTable host1 = client . host = = null ? host : client . host ;
SectionState state = new SectionState ( host1 . id , channel , online , alarm ) ;
client . sectioTable [ channel ] = state ;
if ( OnTcpSectionStateChange ! = null )
{
OnTcpSectionStateChange ( state ) ;
}
TcpAlarmHostTable host = client . Host ;
SensorState state = new ( host . Id , channel , online , alarm ) ;
client . SectionTable [ channel ] = state ;
OnTcpSensorStateChange ? . Invoke ( state ) ;
}
}
private void ProcessAlarm ( int deviceId , int channel , int alarmId )
private void ProcessAlarm ( int deviceId , int channel )
{
TcpAlarmHostMessage alarm = new ( )
TcpAlarmHostMessage alarmMsg = new ( )
{
AlarmId = Convert . ToString ( alarmId ) ,
AlarmTime = DateTime . Now . ToString ( "yyyy-MM-dd HH:mm:ss" ) ,
CID = "1151" ,
DeviceID = deviceId ,
ChannelNum = channel . ToString ( )
} ;
ProcessAlarmDB ( alarm ) ;
OnTcpSensorAlarm ? . Invoke ( alarmMsg ) ;
}
//处理报警事件
private void ProcessAlarmDB ( TcpAlarmHostMessage msg )
{
if ( OnTcpSectionAlarmOn ! = null ) OnTcpSectionAlarmOn ( msg ) ;
}
#endregion Analysis
public void SetDataRequest ( DataMessage msg , byte functionNum )
{
lock ( this )
{
for ( int i = 0 ; i < reqlist . Count ; i + + )
{
if ( reqlist [ i ] . request . functionNum = = functionNum & & reqlist [ i ] . request . frameNum = = msg . frameNum )
{
reqlist [ i ] . responce = msg ;
}
}
}
}
#region Send
public bool SendMessage ( string IP , byte [ ] bytes , ref string error )
{
if ( server = = null )
public bool SendMessage ( string ip , byte [ ] bytes )
{
error = "服务未创建" ;
return false ;
}
if ( ! server . IsRunning )
{
error = "服务未运行" ;
return false ;
}
ClientMessage client = GetClientMessageIP ( IP ) ;
if ( client ! = null )
{
server . Send ( client . client , bytes ) ;
if ( Server = = null | | ! Server . IsRunning ( ) ) return false ;
if ( ! TryGetClientMessage ( ip , out ClientMessage clientMsg ) ) return false ;
string cmd = DataMessage . ToHexString ( bytes ) ;
DataMessage mm = new ( ) ;
mm . Decode ( bytes ) ;
Console . WriteLine ( "Send to {0}:{1} => {2}, {3}" , ip , clientMsg . Port , cmd , JsonUtil . ToJson ( mm ) ) ;
Server . SendAsync ( clientMsg . Client , bytes ) ;
return true ;
}
else
public bool SendRequest ( ref DataRequest request )
{
error = "主机未连接" ;
return false ;
if ( request . Request = = null ) return false ;
request . Request . FrameNum = FrameNumber ;
FrameNumber + + ;
bool send = SendMessage ( request . Request . ReceiveIp , request . Request . Encode ( ) ) ;
return send ;
}
}
private List < DataRequest > reqlist = new List < DataRequest > ( ) ;
private byte frameNumber = 0 ;
public bool sendRequest ( ref DataRequest request , ref string error )
{
if ( request . request = = null )
public bool SendNoRequest ( DataMessage msg )
{
error = "请求信息未填写" ;
return false ;
msg . FrameNum = FrameNumber ;
FrameNumber + + ;
bool send = SendMessage ( msg . ReceiveIp , msg . Encode ( ) ) ;
return send ;
}
//int waitTime = int.Parse(DBCenter.center.GetConfig("WW_TCP_DeviceTimeOut")) * 10;
int waitTime = 1 0 0 ;
request . request . frameNum = frameNumber ;
frameNumber + + ;
bool send = SendMessage ( request . request . receiveIP , request . request . encode ( ) , ref error ) ;
if ( ! send ) return false ;
reqlist . Add ( request ) ;
for ( int i = 0 ; i < waitTime ; i + + )
{
if ( request . responce ! = null )
public bool SendResponse ( DataMessage msg )
{
reqlist . Remove ( request ) ;
return true ;
}
System . Threading . Thread . Sleep ( 1 0 0 ) ;
}
return false ;
bool send = SendMessage ( msg . ReceiveIp , msg . Encode ( ) ) ;
return send ;
}
public bool sendNoRequest ( DataMessage msg , ref string error )
public bool SendHostHeart_01 ( ClientMessage client )
{
msg . frameNum = frameNumber ;
frameNumber + + ;
return SendMessage ( msg . receiveIP , msg . encode ( ) , ref error ) ;
if ( client . Host = = null ) return false ;
DataMessage msg = GetSendMessageHead ( client . Host . Id , client , 0x01 , 1 ) ;
msg . Data = new byte [ ] { 0xFF } ;
return SendNoRequest ( msg ) ;
}
public bool sendHeart ( ClientMessage client , ref string error )
public bool RequestSensorChange_02 ( ClientMessage client )
{
if ( client . host = = null )
if ( client . Host = = null | | client . Host . Id < 0 ) return false ;
DataMessage msg = GetSendMessageHead ( client . Host . Id , client , 0x02 , 4 ) ;
int channel = 1 0 ;
msg . Data = new byte [ ] { ( byte ) ( channel % 2 5 6 ) , ( byte ) ( channel / 2 5 6 ) , ( 1 0 0 % 2 5 6 ) , ( 1 0 0 / 2 5 6 ) } ;
DataRequest request = new ( )
{
error = "报警主机信息缺失" ;
return false ;
}
DataMessage msg = getSendMessageHead ( client . host . id , client , 0x01 , 1 ) ;
msg . data = new byte [ ] { 0xFF } ;
return sendNoRequest ( msg , ref error ) ;
Request = msg
} ;
SendRequest ( ref request ) ;
return true ;
}
public bool SetSectionAddress ( int deviceId , string channel_str , int address , ref string error )
public bool RequestSensorState_04 ( ClientMessage client )
{
ClientMessage client = GetClientMessageDeviceID ( deviceId ) ;
if ( client = = null )
if ( client . Host = = null | | client . Host . Id < 0 ) return false ;
if ( client . SensorListEmpty ) return false ;
DataMessage msg = GetSendMessageHead ( client . Host . Id , client , 0x04 , 2 ) ;
foreach ( var item in client . SensorList )
{
error = "此主机号不在线" ;
return false ;
}
DataMessage msg = getSendMessageHead ( deviceId , client , 0x02 , 4 ) ;
int channel = int . Parse ( channel_str ) ;
msg . data = new byte [ ] { ( byte ) ( channel % 2 5 6 ) , ( byte ) ( channel / 2 5 6 ) , ( byte ) ( address % 2 5 6 ) , ( byte ) ( address / 2 5 6 ) } ;
DataRequest request = new DataRequest ( ) ;
request . request = msg ;
bool result = sendRequest ( ref request , ref error ) ;
if ( result )
int channel = item ;
msg . Data = new byte [ ] { ( byte ) ( channel % 2 5 6 ) , ( byte ) ( channel / 2 5 6 ) } ;
DataRequest request = new ( )
{
JObject conlist = new JObject ( ) ;
conlist . Add ( "deviceID" , deviceId ) ;
conlist . Add ( "channel" , channel_str ) ;
JObject valuelist = new JObject ( ) ;
valuelist . Add ( "channel" , address . ToString ( ) ) ;
//DBCenter.center.UpdateResult("table_TCPSection", valuelist, conlist, ref error);
Request = msg
} ;
SendRequest ( ref request ) ;
}
return result ;
return true ;
}
public bool SetSectionMode ( int deviceId , string channel_str , byte mode , byte sensitivity , ref string error )
public bool RequestSensorReset_05 ( ClientMessage client )
{
ClientMessage client = GetClientMessageDeviceID ( deviceId ) ;
if ( client = = null )
if ( client . Host = = null | | client . Host . Id < 0 ) return false ;
if ( client . SensorListEmpty ) return false ;
DataMessage msg = GetSendMessageHead ( client . Host . Id , client , 0x05 , 2 ) ;
foreach ( var item in client . SensorList )
{
error = "此主机号不在线" ;
return false ;
}
DataMessage msg = getSendMessageHead ( deviceId , client , 0x03 , 3 ) ;
int channel = int . Parse ( channel_str ) ;
msg . data = new byte [ ] { ( byte ) ( channel % 2 5 6 ) , ( byte ) ( channel / 2 5 6 ) , ( byte ) ( mode + sensitivity * 8 ) } ;
DataRequest request = new DataRequest ( ) ;
request . request = msg ;
bool result = sendRequest ( ref request , ref error ) ;
if ( result )
int channel = item ;
msg . Data = new byte [ ] { ( byte ) ( channel % 2 5 6 ) , ( byte ) ( channel / 2 5 6 ) } ;
DataRequest request = new ( )
{
JObject conlist = new JObject ( ) ;
conlist . Add ( "deviceID" , deviceId ) ;
conlist . Add ( "channel" , channel_str ) ;
JObject valuelist = new JObject ( ) ;
valuelist . Add ( "mode" , mode . ToString ( ) ) ;
valuelist . Add ( "sensitivity" , sensitivity . ToString ( ) ) ;
//DBCenter.center.UpdateResult("table_TCPSection", valuelist, conlist, ref error);
Request = msg
} ;
SendRequest ( ref request ) ;
}
return result ;
return true ;
}
public bool SetSectionReset ( int deviceId , string channel_str , ref string error )
public bool RequestSensorList_07 ( ClientMessage client )
{
ClientMessage client = GetClientMessageDeviceID ( deviceId ) ;
if ( client = = null )
if ( client . Host = = null | | client . Host . Id < 0 ) return false ;
DataMessage msg = GetSendMessageHead ( client . Host . Id , client , 0x07 , 0 ) ;
DataRequest request = new ( )
{
error = "此主机号不在线" ;
return false ;
}
DataMessage msg = getSendMessageHead ( deviceId , client , 0x05 , 2 ) ;
int channel = int . Parse ( channel_str ) ;
msg . data = new byte [ ] { ( byte ) ( channel % 2 5 6 ) , ( byte ) ( channel / 2 5 6 ) } ;
DataRequest request = new DataRequest ( ) ;
request . request = msg ;
return sendRequest ( ref request , ref error ) ;
Request = msg
} ;
return SendRequest ( ref request ) ;
}
public SectionState SetSectionCheck ( int deviceId , string channel_str , ref string error )
{
ClientMessage client = GetClientMessageDeviceID ( deviceId ) ;
if ( client = = null )
{
error = "此主机号不在线" ;
return null ;
}
DataMessage msg = getSendMessageHead ( deviceId , client , 0x04 , 2 ) ;
int channel = int . Parse ( channel_str ) ;
msg . data = new byte [ ] { ( byte ) ( channel % 2 5 6 ) , ( byte ) ( channel / 2 5 6 ) } ;
DataRequest request = new DataRequest ( ) ;
request . request = msg ;
bool result = sendRequest ( ref request , ref error ) ;
if ( result )
public bool ResponseHostLogin_10 ( ClientMessage client , DataMessage mm )
{
int channel2 = request . responce . data [ 0 ] + request . responce . data [ 1 ] * 2 5 6 ;
int state2 = request . responce . data [ 2 ] + request . responce . data [ 3 ] * 2 5 6 ;
return new SectionState ( deviceId , channel2 , state2 ) ;
}
else
{
return null ;
}
if ( client . Host = = null ) return false ;
DataMessage msg = GetSendMessageHead ( client . Host . Id , client , 0x10 , 0 ) ;
msg . FrameNum = mm . FrameNum ;
return SendResponse ( msg ) ;
}
public List < SectionState > SetDeviceCheck ( int deviceId , ref string error )
{
List < SectionState > list = new List < SectionState > ( ) ;
//JArray arr = DBCenter.center.SearchByConditionJArray("table_TCPSection", "deviceID=" + deviceId, ref error);
JArray arr = new ( ) ;
if ( arr ! = null & & arr . Count > 0 )
{
for ( int i = 0 ; i < arr . Count ; i + + )
{
string channel = arr [ i ] [ "channel" ] . ToString ( ) ;
SectionState state = SetSectionCheck ( deviceId , channel , ref error ) ;
if ( state = = null )
{
state = new SectionState ( deviceId , int . Parse ( channel ) , - 1 , - 1 ) ;
}
list . Add ( state ) ;
}
}
else
{
error = "数据库中没有防区信息" ;
}
return list ;
}
#endregion Send
public List < SectionState > SetAllCheck ( ref string error )
{
List < SectionState > list = new List < SectionState > ( ) ;
//JArray arr = DBCenter.center.SearchByConditionJArray("table_TCPAlarmHost", "", ref error);
JArray arr = new ( ) ;
if ( arr ! = null & & arr . Count > 0 )
#region Set
private List < DataRequest > Reqlist { get ; } = new ( ) ;
private byte FrameNumber { get ; set ; } = 0 ;
private DataMessage GetSendMessageHead ( int deviceId , ClientMessage client , byte fun_num , byte datalen )
{
for ( int i = 0 ; i < arr . Count ; i + + )
DataMessage msg = new ( )
{
int deviceId = int . Parse ( arr [ i ] [ "id" ] . ToString ( ) ) ;
list . AddRange ( SetDeviceCheck ( deviceId , ref error ) ) ;
}
}
return list ;
DeviceId = deviceId ,
SendIp = client . Client . Client . LocalEndPoint . ToString ( ) . Split ( ':' ) [ 0 ] ,
SendPort = Server . Port ,
ReceiveIp = client . Ip ,
ReceivePort = int . Parse ( client . Port ) ,
FunctionNum = fun_num ,
DataLen = datalen
} ;
return msg ;
}
private DataMessage getSendMessageHead ( int deviceId , ClientMessage client , byte fun_num , byte datalen )
public void SetDataRequest ( DataMessage msg , byte functionNum )
{
//DataMessage msg = new DataMessage();
//msg.deviceID = deviceId;
//msg.sendIP = DBCenter.center.GetConfig("WW_TCP_ServeIP");
//msg.sendPort = int.Parse(DBCenter.center.GetConfig("WW_TCP_ServePort"));
//msg.receiveIP = client.IP;
//msg.receivePort = int.Parse(client.Port);
//msg.functionNum = fun_num;
//msg.dataLen = datalen;
//return msg;
return null ;
}
public void sendState ( ClientMessage client , ref string error )
lock ( this )
{
//if (client.host == null )
//for (int i = 0; i < Reqlist.Count; i++)
//{
// error = "报警主机信息缺失";
// return;
//}
//JArray arr = DBCenter.center.SearchByConditionJArray("table_TCPSection", "deviceID='" + client.host.id + "'", ref error);
//if (arr != null && arr.Count > 0)
// if (Reqlist[i].Request.FunctionNum == functionNum && Reqlist[i].Request.FrameNum == msg.FrameNum)
// {
// for (int i = 0; i < arr.Count; i++)
// {
// DataMessage msg = getSendMessageHead(client.host.id, client, 0x04, 2);
// int channel = int.Parse(arr[i]["channel"].ToString());
// msg.data = new byte[] { (byte)(channel % 256), (byte)(channel / 256) };
// sendNoRequest(msg, ref error);
// Reqlist[i].Responce = msg;
// }
//}
}
private void server_ClientDisconnected ( object sender , TcpClientDisconnectedEventArgs e )
{
string clientIP = e . TcpClient . Client . RemoteEndPoint . ToString ( ) . Split ( ':' ) [ 0 ] ;
Console . WriteLine ( clientIP + "下线" ) ;
ClientMessage client = GetClientMessage ( e . TcpClient ) ;
if ( client ! = null )
{
list . Remove ( client ) ;
if ( OnTcpDeviceMessage ! = null )
{
if ( client . host ! = null )
{
OnTcpDeviceMessage ( client . host , "报警主机掉线" ) ;
}
else
{
OnTcpDeviceMessage ( new TcpAlarmHostTable ( ) { id = - 1 , ip = clientIP , port = client . Port , name = "未知设备" } , "报警主机掉线" ) ;
}
}
}
}
private void server_ClientConnected ( object sender , TcpClientConnectedEventArgs e )
{
string error = "" ;
string clientIP = e . TcpClient . Client . RemoteEndPoint . ToString ( ) . Split ( ':' ) [ 0 ] ;
string port = e . TcpClient . Client . RemoteEndPoint . ToString ( ) . Split ( ':' ) [ 1 ] ;
Console . WriteLine ( clientIP + "上线" ) ;
ClientMessage client = GetClientMessage ( e . TcpClient ) ;
if ( client = = null )
{
ClientMessage msg = new ClientMessage ( ) ;
msg . client = e . TcpClient ;
//JArray arr = DBCenter.center.SearchByConditionJArray("table_TCPAlarmHost", "IP='" + clientIP + "'", ref error);
JArray arr = new ( ) ;
if ( arr ! = null & & arr . Count > 0 )
{
msg . host = JsonConvert . DeserializeObject < TcpAlarmHostTable > ( arr [ 0 ] . ToString ( ) , jSetting ) ;
}
list . Add ( msg ) ;
if ( OnTcpDeviceMessage ! = null )
{
if ( msg . host ! = null )
{
OnTcpDeviceMessage ( msg . host , "报警主机上线" ) ;
}
else
{
OnTcpDeviceMessage ( new TcpAlarmHostTable ( ) { id = - 1 , ip = clientIP , port = client . Port , name = "未知设备" } , "报警主机上线" ) ;
}
}
}
}
public List < SectionState > getOnlineState ( int deviceId )
{
ClientMessage msg = GetClientMessageDeviceID ( deviceId ) ;
if ( msg ! = null )
{
return msg . sectioTable . Values as List < SectionState > ;
}
else
{
return new List < SectionState > ( ) ;
}
}
#endregion Set
}