C#基于Socket的UDP和TCP处理通信报文开发传输
程序员文章站
2022-06-30 13:33:17
...
设备通过TCP/IP接入OMC,此时OMC作为TCP/IP服务端,主设备作为客户端且主设备IP地址和端口号可设。主设备通过开站上报数据包或者登录包来主动接入OMC。开站上报的接入流程如下(登录包与之相似)
包的协议格式如下:
起始标志 (7E) |
AP层协议类型 (01或03) |
承载协议类型 (01) |
数据单元(PDU) |
校验单元 (CRC) |
结束标志 |
程序主要通过TCP UDP协议进行通讯。
要求用VS2013编译文件,用C#开发代码,需要安装framework4.6的WINDOW框架,服务程序只需要framework3.5框架,其本上编译后的应用程序,所有WINDOW7以上的操作系统都可以正常使用。
1、创建服务
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using SignalRules;
using System.Timers;
namespace SignalServ
{
public partial class SignalMonitor : ServiceBase
{
private Thread _oil_Thread;
private Thread _monter_Thread; //ODS修复线程
private static bool bExitThread = false; //是否退出线程
public SignalMonitor()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
string errmsg = "服务启动成功,";
try
{
//启动授权线程
//_oil_Thread = new Thread(new ThreadStart(SignalRules.SocketServer.Socket_Thread));
_oil_Thread = new Thread(new ThreadStart(SignalRules.SocketServer1.StartListen));
_oil_Thread.Start();
errmsg += "Socket线程启动;";
//启动心跳监控线程
_monter_Thread = new Thread(new ThreadStart(monter_heartbeat));
_monter_Thread.Start();
errmsg += "monter线程启动,";
WebCore.Log.WebLog.WriteTextLog("", WebCore.Log.WebLogType.SignalCmd, "SignalServ_Socket", errmsg);
}
catch (Exception err)
{
errmsg += "socket启动错误:" + err.Message + err.StackTrace + ";";
WebCore.Log.WebLog.WriteTextLog("", WebCore.Log.WebLogType.SignalCmd, "SignalServ_Socket", errmsg);
}
}
protected override void OnStop()
{
if (_oil_Thread != null)
{
_oil_Thread.Abort();
}
if (_monter_Thread != null)
{
_monter_Thread.Abort();
}
SignalRules.SocketServer1.Socket_Close();
string errmsg = "停止Socket服务";
WebCore.Log.WebLog.WriteTextLog("", WebCore.Log.WebLogType.SignalCmd, "SignalServ_Socket", errmsg);
}
/// <summary>
/// 心跳监控线程
/// </summary>
private static void monter_heartbeat()
{
while (true)
{
if (bExitThread)
{
break;
}
try
{
new SignalRules.BLL.omc_device_heartbeat().monter_heartbeat();
Thread.Sleep(10000);//10秒运行一次
}
catch (Exception ex)
{
WebCore.Log.WebLog.WriteTextLog("", WebCore.Log.WebLogType.SignalCmd, "monter_heartbeat", ex.Message);
}
}
}
}
}
2、Socket服务端监听
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;
using WebCore;
using SignalRules.Model;
using System.Threading;
namespace SignalRules
{
public class SocketServer1
{
static Socket sokWatch = null;//负责监听 客户端段 连接请求的 套接字
static Thread threadWatch = null;//负责 调用套接字, 执行 监听请求的线程
static Thread threadSend = null;
static bool isWatch = true;
static bool isRec = true;//与客户端通信的套接字 是否 监听消息
static bool isSend = true;//给客户端发信息。
static int monitor_interval = WebConfig.MonitorInterval;
static Dictionary<string, ConnectionClient> dictConn = new Dictionary<string, ConnectionClient>();
public delegate void DGShowMsg(string strMsg);
public static void StartListen()
{
//实例化 套接字 (ip4寻址协议,流式传输,TCP协议)
sokWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//创建 ip对象
IPAddress address = IPAddress.Parse(WebConfig.SocketIP);
//创建网络节点对象 包含 ip和port
IPEndPoint endpoint = new IPEndPoint(address, int.Parse(WebConfig.SocketPort));
//将 监听套接字 绑定到 对应的IP和端口
try
{
sokWatch.Bind(endpoint);
//设置 监听队列 长度为10(同时能够处理 10个连接请求)
sokWatch.Listen(10);
threadWatch = new Thread(StartWatch);
threadWatch.IsBackground = true;
threadWatch.Start();
WebCore.Log.WebLog.WriteTextLog(WebCore.Log.WebLogLevel.INFO, "system", WebCore.Log.WebLogType.SignalCmd, "SocketListen", String.Format("启动监听{0}成功", sokWatch.LocalEndPoint.ToString()));
//txtShow.AppendText("启动服务器成功......\r\n");
threadSend = new Thread(socket_Send);
threadSend.IsBackground = true;
threadSend.Start();
WebCore.Log.WebLog.WriteTextLog(WebCore.Log.WebLogLevel.INFO, "system", WebCore.Log.WebLogType.SignalCmd, "SocketListen", String.Format("启动发送"));
}
catch (Exception ex)
{
WebCore.Log.WebLog.WriteTextLog(WebCore.Log.WebLogLevel.ERROR, "system", WebCore.Log.WebLogType.SignalCmd, "StartListen", ex.Message);
}
}
#region 1.被线程调用 监听连接端口
/// <summary>
/// 被线程调用 监听连接端口
/// </summary>
static void StartWatch()
{
while (isWatch)
{
try
{
//threadWatch.SetApartmentState(ApartmentState.STA);
//监听 客户端 连接请求,但是,Accept会阻断当前线程
Socket sokMsg = sokWatch.Accept();//监听到请求,立即创建负责与该客户端套接字通信的套接字
ConnectionClient connection = new ConnectionClient(sokMsg, RemoveClientConnection);
//将负责与当前连接请求客户端 通信的套接字所在的连接通信类 对象 装入集合
try
{
dictConn.Add(((IPEndPoint)sokMsg.RemoteEndPoint).Address.ToString(), connection);
WebCore.Log.WebLog.WriteTextLog(WebCore.Log.WebLogLevel.INFO,"system", WebCore.Log.WebLogType.SignalCmd, "SocketListen", String.Format("监听到请求IP={0}", sokMsg.RemoteEndPoint.ToString()));
}
catch (Exception ex)
{
WebCore.Log.WebLog.WriteTextLog(WebCore.Log.WebLogLevel.ERROR, "system", WebCore.Log.WebLogType.SignalCmd, "SocketListen", String.Format("重新监听到请求IP={0}", sokMsg.RemoteEndPoint.ToString()));
}
//将 通信套接字 加入 集合,并以通信套接字的远程IpPort作为键
//dictSocket.Add(sokMsg.RemoteEndPoint.ToString(), sokMsg);
//ShowMsg("接收连接成功......");
//启动一个新线程,负责监听该客户端发来的数据
//Thread threadConnection = new Thread(ReciveMsg);
//threadConnection.IsBackground = true;
//threadConnection.Start(sokMsg);
}
catch (Exception ex)
{
WebCore.Log.WebLog.WriteTextLog(WebCore.Log.WebLogLevel.ERROR, "system", WebCore.Log.WebLogType.SignalCmd, "StartWatch", "监听连接端口错误:" + ex.Message);
}
}
}
#endregion
#region 发送消息 到指定的客户端 -btnSend_Click
//发送消息 到指定的客户端
private static void socket_Send()
{
//获取客户端信息
int result=0;
byte[] recvBytes = new byte[1024];
byte[] sendBytes;
List<byte[]> sendByte_list = new List<byte[]>();
string connectionSokKey = "";
while (isSend)
{
try
{
#region 发送数据给终端板
cmd_execute m_cmd_execute = new cmd_execute();
SignalRules.Model.EntReturn send_result = SignalRules.DealLib.Signal_Send_Deal(ref m_cmd_execute);
if (send_result != null && send_result.ResultCode == 0)
{
sendByte_list = (List<byte[]>)send_result.ResultObject;
connectionSokKey = m_cmd_execute.device_ip;//取得发送的客户端IP
WebCore.Log.WebLog.WriteTextLog(WebCore.Log.WebLogLevel.INFO, "system", WebCore.Log.WebLogType.SignalCmd, "socket_Send/Deal", "取得发送的客户端IP:" + connectionSokKey);
for (int i = 0; i < sendByte_list.Count; i++)
{
sendBytes = sendByte_list[i];//发送数据给终端板
if (!string.IsNullOrEmpty(connectionSokKey) && dictConn.ContainsKey(connectionSokKey))
{
//从字典集合中根据键获得 负责与该客户端通信的套接字,并调用send方法发送数据过去
result = dictConn[connectionSokKey].doSend_Work(sendBytes);//返回信息给客户端
if (result == -1)
{
continue;
}
WebCore.Log.WebLog.WriteTextLog(WebCore.Log.WebLogLevel.INFO, "system", WebCore.Log.WebLogType.SignalCmd, "socket_Send/Deal", SignalRules.DealLib.byteToHexStr(sendBytes));
}
Thread.Sleep(100);
}
//发送成功,修改数据库
if (m_cmd_execute != null && m_cmd_execute.device_code != "")
{
DealLib.Signal_Send_Deal_Data(m_cmd_execute);
}
}
else if (send_result.ResultCode ==-1)
{
WebCore.Log.WebLog.WriteTextLog(WebCore.Log.WebLogLevel.INFO, "system", WebCore.Log.WebLogType.SignalCmd, "socket_Send/Deal", send_result.ResultCode + send_result.ResultMsg);
}
Thread.Sleep(monitor_interval);
#endregion
}
catch (Exception ex)
{
WebCore.Log.WebLog.WriteTextLog(WebCore.Log.WebLogLevel.ERROR, "system", WebCore.Log.WebLogType.SignalCmd, "socket_Send/Error", ex.Message);
}
}
}
#endregion
//发送闪屏!!
private void socket_Shack(string key)
{
string connectionSokKey = key;
if (!string.IsNullOrEmpty(connectionSokKey))
{
dictConn[connectionSokKey].SendShake();
}
}
//群闪
private void socket_ShackAll(string key)
{
foreach (ConnectionClient conn in dictConn.Values)
{
conn.SendShake();
}
}
public static void Socket_Close()
{
try
{
isSend = false;
isRec = false;
isWatch = false;
Thread.Sleep(100);
foreach (ConnectionClient conn in dictConn.Values)
{
conn.CloseConnection();
}
if (sokWatch != null && sokWatch.Connected)
{
sokWatch.Close();
}
if (threadWatch != null)
{
threadWatch.Abort();
}
if (threadSend != null)
{
threadSend.Abort();
}
}
catch(Exception ex)
{
WebCore.Log.WebLog.WriteTextLog(WebCore.Log.WebLogLevel.ERROR, "system", WebCore.Log.WebLogType.SignalCmd, "Socket_Close/Error", ex.Message);
}
}
}
}
3、业务协议处理
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using SignalRules.Model;
using System.Data;
using WebCore;
using WebCore.Log;
namespace SignalRules
{
public class DealLib
{
#region 枚举定义
/// <summary>
/// 命令位数
/// </summary>
enum cmd_place
{
////7E 03 01 00 000000000000 D280 80 01 01 FF 04410106 C508 7E
start = 0, //起始标志,固定为0x7E
ap_layer = 1, //AP层协议类型,0x03表示为AP:C
load_bearing = 2,//承载协议类型,0x01表示承载的上层协议类型为VP:A
site_code = 3, //主单元站点编号
floor_no=4, //获取楼号
floor_num1=5, //楼层,低位字节
floor_num2=6, //楼层,低位字节
device_type=7, //设备类型(主控单元0x00、远端单元0x01、*侦测单元0x02)
remote_code1=8, //远端单元编号,共两个字节.
remote_code2=9,//远端单元编号,共两个字节.
communica_identify1=10,//监控中心发起的通信,低位.
communica_identify2=11,//监控中心发起的通信,高位
vp_layer_interact_flag=12, //VP层交互标志
mcp_layer_protocol_flag=13, //MCP层协议标识,目前只定义了一种0x01
data_command_identify=14, //命令标识,0x01 设备主动告警(上报)、0x02 查询、0x03 设置
data_response_flag=15, //应答标志,0xFF 表示此包为发出的命令,而非命令的应答包
monitor_data_length=16, //监控数据长度
monitor_identify=17, //监控标识
monitor_data_value = 18 //监控数据的值
}
/// <summary>
/// VP层交互标志
/// </summary>
enum vp_layer_interact
{
res_success=0x00, // 通信请求的执行结果,表示执行正常。
res_busy=0x01,// 通信请求的执行结果,表示设备忙,无法处理命令请求。
req_success=0x80,// 正常的命令请求。
}
/// <summary>
/// a) 命令标识:命令的唯一标识
/// </summary>
enum command_identify
{
device_active_alarm = 0x01,//设备主动告警(上报)
query = 0x02, //查询
set_up = 0x03, //设置
upgrade_mode = 0x10, //转换到软件升级模式
monitor_software_version = 0x11 //切换监控软件版本
}
/// <summary>
/// b) 应答标志:
/// </summary>
enum response_flag
{
success = 0x00, // 成功
execute = 0x01, // 命令被有条件执行
code_error = 0x02, // 命令编号错
leng_error = 0x03, // 长度错
crc_error = 0x04, // CRC校验错
error = 0xFE, // 其它错误
cmd = 0xFF // 命令
}
#endregion
/// <summary>
/// 获取数据值,存在多个数据值。
/// </summary>
/// <param name="revcByte"></param>
/// <param name="start">数据开始项,第一个数据块为16</param>
/// <returns></returns>
private static List<SignalRules.Model.cmd_packet_data> get_Packet_DataValue(byte[] revcByte,int start)
{
string str = "";
int tmp_num = 0;
byte[] datavalue_byte;
List<SignalRules.Model.cmd_packet_data> result = new List<SignalRules.Model.cmd_packet_data>();
SignalRules.Model.cmd_packet_data m_cmd_packet_data;
try
{
//判断整长度-3 还大于3,说明有两个以上的数据块。
while ((revcByte.Length - start - 3) > 3)
{
str = "revcByte.Length=" + revcByte.Length + ",start=" + start;
//取得数据数块
m_cmd_packet_data = new SignalRules.Model.cmd_packet_data();
m_cmd_packet_data.monitor_data_length = revcByte[start];//标识监控数据结构的长度,指的是从“长度”到“值”的所有字节总数,其本身为1个字节无符号整型数,单位是字节。
str = str + ",data_length=" + m_cmd_packet_data.monitor_data_length;
m_cmd_packet_data.monitor_identify = byteToHexStr(new byte[] { revcByte[start + 2], revcByte[start + 1] });//监控数据标识为2个字节的无符号整型数,其可取值范围为0x0000~0xFFFF
str = str + ",monitor_identify=" + m_cmd_packet_data.monitor_identify;
#region//start计划出数据块的值
if (m_cmd_packet_data.monitor_data_length > 3)
{
tmp_num = m_cmd_packet_data.monitor_data_length - 3;//数据块值的位数。
datavalue_byte = new byte[tmp_num];
start = start + 3;//从第4位数据值开始计算。
for (int i = 0; i < tmp_num; i++)
{
datavalue_byte[i] = revcByte[start];
start++;
}
m_cmd_packet_data.monitor_data_value = datavalue_byte;//byteToHexStr(datavalue_byte);
}
else
{
tmp_num = revcByte.Length - start;
datavalue_byte = new byte[tmp_num];
for (int i = 0; i < tmp_num; i++)
{
datavalue_byte[i] = revcByte[start];
start++;
}
m_cmd_packet_data.monitor_data_value = datavalue_byte;
throw new Exception("数据块长度异常:data_length=" + m_cmd_packet_data.monitor_data_length + ",tmp_num=" + tmp_num + ",datavalue=" + byteToHexStr(datavalue_byte));
}
result.Add(m_cmd_packet_data);
str = str + ",data_value=" + byteToHexStr(m_cmd_packet_data.monitor_data_value);
WebCore.Log.WebLog.WriteTextLog(WebLogLevel.INFO,"system", WebCore.Log.WebLogType.SignalCmd, "SocketServer/Deal/test", str);//测试打印日志
//
}
#endregion
}
catch (Exception ex)
{
WebCore.Log.WebLog.WriteTextLog(WebLogLevel.ERROR, "system", WebCore.Log.WebLogType.SignalCmd, "SocketServer/Deal/get_Packet_DataValue", ex.Message + "; " + str);
}
return result;
}
/// <summary>
/// 得到通信包标识ID
/// </summary>
/// <returns></returns>
public static byte[] get_Comm_Packet_Identify()
{
string tmp_str = "";
byte[] result = new byte[2];
if (_COMM_PACKET_IDENTIFY > 9999)
{
_COMM_PACKET_IDENTIFY = 1;
}
else
{
_COMM_PACKET_IDENTIFY++;
}
tmp_str =_COMM_PACKET_IDENTIFY.ToString().PadLeft(4, '0');
for (int i = 0; i < 2; i++)
{
result[i] = Convert.ToByte(tmp_str.Substring(i * 2, 2));
}
return result;
}
#region 处理从终端收到的数据
private static bool revice_response_verify(byte response_flag)
{
bool result = false;
if (response_flag == 0x01)//0x01 命令被有条件执行
{
result = true;
}
else if (response_flag == 0x02)//0x02 命令编号错
{
result = false;
}
else if (response_flag == 0x03)//0x03 长度错
{
result = false;
}
else if (response_flag == 0x04)//0x04 CRC校验错
{
result = false;
}
else if (response_flag == 0xFE)//0xFE 其它错误
{
result = false;
}
return result;
}
/// <summary>
/// 接收命令包业务处理
/// </summary>
/// <param name="m_cmd_execute">命令工单</param>
/// <param name="m_cmd_packet_data_list">命令里数据块列表</param>
/// <returns></returns>
private static bool revice_command_package_deal(SignalRules.Model.cmd_execute m_cmd_execute, List<SignalRules.Model.cmd_packet_data> m_cmd_packet_data_list)
{
bool result = false;
string[,] ary_packet_data;
string tmp_str = "";
SignalRules.Model.omc_device_alarm m_omc_device_alarm = new SignalRules.Model.omc_device_alarm();
// 获取数据列表数组 ID|数据值|数据类型|数据编码|表字|字段|数据描述
ary_packet_data = SignalRules.BLL.common.get_cmd_data_identify(m_cmd_packet_data_list);
for (int i = 0; i < ary_packet_data.GetLength(0); i++)
{
tmp_str = ary_packet_data[i, 0].Substring(0, 2);
if (tmp_str == "02" || tmp_str == "03")//获取告警使能或告警状态
{
int rows = new SignalRules.BLL.omc_cmd_execute().revice_device_alarm_info(m_cmd_execute.device_code, m_cmd_execute.device_ip, ary_packet_data[i, 0], ary_packet_data[i, 1]);
}
else if (ary_packet_data[i, 0] == "0141")//上报类型
{
//WebCore.Log.WebLog.WriteTextLog("system", WebCore.Log.WebLogType.SignalCmd, "doReceive_Work/DealLib/revice_command_package_deal", "device_code=" + m_cmd_execute.device_code + ",monitor_id=" + ary_packet_data[i, 0] + ",data_str=" + ary_packet_data[i, 1]);
new SignalRules.BLL.omc_cmd_execute().revice_device_report_type(m_cmd_execute.device_code, m_cmd_execute.device_ip,ary_packet_data[i, 0], ary_packet_data[i, 1]);
//new SignalRules.BLL.omc_driverinfo().ExistUpdate(m_cmd_execute.device_code);
}
}
return result;
}
/// <summary>
/// 接收响应包业务处理
/// </summary>
/// <param name="response_flag"></param>
/// <returns></returns>
private static SignalRules.Model.EntReturn revice_response_package_deal(SignalRules.Model.cmd_packet m_cmd_packet, SignalRules.Model.cmd_execute m_cmd_execute, List<SignalRules.Model.cmd_packet_data> m_cmd_packet_data_list)
{
SignalRules.Model.EntReturn result = new SignalRules.Model.EntReturn();
int command_identify = 0;
SignalRules.Model.omc_device_alarm m_omc_device_alarm = new SignalRules.Model.omc_device_alarm();
SignalRules.Model.omc_device_query m_omc_device_query = new SignalRules.Model.omc_device_query();
List<cmd_packet_data> m_cmd_data_list = new List<cmd_packet_data>();
string[,] ary_packet_data;
string remote_code = "";
string remote_ip = "";
string monitor_id = "";
byte[] remote_byte=new byte[18] ;
byte[] tmp_byte;
int num = 0;
try
{
//ID|数据值|数据类型|数据编码|表字|字段|数据描述
ary_packet_data = SignalRules.BLL.common.get_cmd_data_identify(m_cmd_packet_data_list);
if (ary_packet_data == null)
{
result.ResultCode = -1;
return result;
}
//获取命令响应标识
command_identify = m_cmd_packet.data_command_identify;
if (command_identify == 0x02)//查询
{
#region 获取查询的响应
for (int i = 0; i < ary_packet_data.GetLength(0); i++)
{
#region
/*
m_omc_device_query = new SignalRules.Model.omc_device_query();
m_omc_device_query.device_type = m_cmd_execute.device_type;
m_omc_device_query.device_code = m_cmd_execute.device_code;
m_omc_device_query.monitor_id = ary_packet_data[i, 0];
m_omc_device_query.monitoring_name = ary_packet_data[i, 6];
m_omc_device_query.data_value = ary_packet_data[i, 1];
m_omc_device_query.status = 0;
m_omc_device_query.query_time = DateTime.Now;
new SignalRules.BLL.omc_device_query().Add(m_omc_device_query);*/
#endregion
//监控数据标识=0x0008,获取远端设备编号和IP地址,有N台远端机
if (ary_packet_data[i, 0] == "0008")
{
#region 获取远端设备编号和IP地址,有N台远端机
remote_byte = strToToHexByte(ary_packet_data[i, 1]);
m_cmd_data_list = get_Packet_DataValue(remote_byte, 3);//得到数组为2,1个为远端设备号,另一个为远端IP地址。
if (m_cmd_data_list.Count == 2)//远端单元设备编号 和 IP
{
tmp_byte = m_cmd_data_list[0].monitor_data_value;//远端单元设备编号
if (tmp_byte.Length == 6)
{
//remote_code = byteToHexStr(m_cmd_data_list[0].monitor_data_value);//获取远端设备号
remote_code = asciiToStr(m_cmd_data_list[0].monitor_data_value);//远端设备编号,转为ASCII码
remote_code = m_cmd_execute.site_code.ToString("000") + remote_code;//设备编号
monitor_id = m_cmd_data_list[1].monitor_identify; //远端标识号
tmp_byte = m_cmd_data_list[1].monitor_data_value;//远程端的IP地址
if (tmp_byte.Length == 4)
{
remote_ip = tmp_byte[0].ToString() + "." + tmp_byte[1].ToString() + "." + tmp_byte[2].ToString() + "." + tmp_byte[3].ToString();
new SignalRules.BLL.omc_cmd_execute().revice_query_response_deal(remote_code,monitor_id, remote_ip);
}
}
}
#endregion
}
else if (ary_packet_data[i, 0] == "0009")//监控数据标识=0x0009,获取设备所有的监控标识
{
#region 获取设备所有的监控标识
//WebCore.Log.WebLog.WriteTextLog("system", WebCore.Log.WebLogType.SignalCmd, "SocketServer/Common/set_cmd_execute", ary_packet_data[i, 1]);
remote_byte = strToToHexByte(ary_packet_data[i, 1]);
for (int j = 1; j < remote_byte.Length / 2; j++)
{
num=j*2;
monitor_id = byteToHexStr(new byte[] { remote_byte[num + 1], remote_byte[num] });
new SignalRules.BLL.omc_cmd_execute().p_revice_query_response_init(m_cmd_execute.device_code, monitor_id);
}
#endregion
}
else
{
//修改设备表
monitor_id=ary_packet_data[i, 0];
int rows = new SignalRules.BLL.omc_cmd_execute().revice_query_response_deal(m_cmd_execute.device_code, monitor_id, ary_packet_data[i, 1]);
}
}
//WebCore.Log.WebLog.WriteTextLog("system", WebCore.Log.WebLogType.SignalCmd, "SocketServer/Common/set_cmd_execute", strSql.ToString());
result.ResultCode = 0;
#endregion
}
else if (command_identify == 0x03)//设置
{
#region 获得设置响应
for (int i = 0; i < ary_packet_data.GetLength(0); i++)
{
//修改设备表
monitor_id = ary_packet_data[i, 0];
int rows = new SignalRules.BLL.omc_cmd_execute().revice_query_response_deal(m_cmd_execute.device_code, monitor_id, ary_packet_data[i, 1]);
}
new SignalRules.BLL.omc_cmd_execute().UpdateStatus(m_cmd_execute.device_code,"03", 3);
result.ResultCode = 0;
#endregion
}
}
catch (Exception ex)
{
result.ResultCode = -1;
result.ResultMsg = ex.Message;
}
return result;
}
/// <summary>
/// 处理从终端收到的数据
/// </summary>
/// <param name="revcByte"></param>
/// <param name="str"></param>
/// <returns>ResultCode>0需要响应包;ResultCode=0不需要响应包;ResultCode小于为异常包</returns>
public static SignalRules.Model.EntReturn Signal_Revice_Deal(byte[] revcByte, string socketRemoteKey)
{
byte[] sendByte = revcByte;
byte[] ary_byte=null;
string tmp_str = "";
int data_num = revcByte.Length;
SignalRules.Model.EntReturn result = new SignalRules.Model.EntReturn();
SignalRules.Model.cmd_packet m_cmd_packet = new SignalRules.Model.cmd_packet();
//SignalRules.Model.cmd_packet_data m_cmd_packet_data;
List<SignalRules.Model.cmd_packet_data> m_cmd_packet_data_list =new List<cmd_packet_data>();
List<SignalRules.Model.cmd_execute> m_cmd_execute_list =new List<cmd_execute>();
try
{
result.ResultCode = 0;
//转义字符,接收到数据包后,先进行转义处理,再进行CRC校验
set_Escape(ref revcByte, ref data_num, "revice");
//7E 03 01 00 000000000000 D280 80 01 01 FF 04410106 C508 7E
#region 解读数据包,检验CRC检验正确性
if (get_DataPacket_CRC_Check(revcByte) == true)
{
try
{
#region 解读数据包字节
#region 解析数据包头信息
m_cmd_packet.site_code = revcByte[3];//获取主单元站点编号
m_cmd_packet.floor_no = revcByte[4];//获取楼号
m_cmd_packet.floor_num=new byte[]{ revcByte[5], revcByte[6] };//获取楼层,共两个字节
m_cmd_packet.device_type = revcByte[7];//获取设备类型(主控单元0x00、远端单元0x01、*侦测单元0x02)
m_cmd_packet.remote_code = new byte[] { revcByte[8], revcByte[9] };//获取远端单元编号,共两个字节.
////获取通信包标识号,在传输时低字节在前,高字节在后,
//其中0x0000~0x7FFF用于监控中心发起的通信,而0x8000~0x8FFF则用于由设备发起的通信,余下的0x9000~0xFFFF则为保留
m_cmd_packet.communica_packet_identify = new byte[] { revcByte[10], revcByte[11] };//获取通信包标识号,在传输时低字节在前,高字节在后,
m_cmd_packet.vp_layer_interact_flag = revcByte[12];//获取VP层交互标志
m_cmd_packet.mcp_layer_protocol_flag = revcByte[13];//获取MCP层协议标识,目前只定义了一种0x01
m_cmd_packet.data_command_identify = revcByte[14];//获取命令标识,0x01表示是上报命令
m_cmd_packet.data_response_flag = revcByte[15];//获取应答标志,命令发起方该字段填充0xFF
#endregion
//判断VP层的命令
if (m_cmd_packet.vp_layer_interact_flag >= 0x00 && m_cmd_packet.vp_layer_interact_flag <= 0xFF)
{
//其中0x80~0xFF用于命令,而0x00~0x7F则用于应答包中
}
else
{
result.ResultCode = -8;
result.ResultMsg = "VP层的命令有误,不属于0x80~0xFF用于命令,而0x00~0x7F则用于应答包";
}
//判断设备类型(主控单元0x00、远端单元0x01、*侦测单元0x02),不正常丢掉。
if ((m_cmd_packet.device_type == 0x00 || m_cmd_packet.device_type == 0x01 || m_cmd_packet.device_type == 0x02))
{
//只接收从设备过来的三种数据,包括主控单元0x00、远端单元0x01、侦测单元0x02
}
else
{
result.ResultCode = -9;
result.ResultMsg = "设备类型有误,不属于主控单元0x00、远端单元0x01、侦测单元0x02";
}
SignalRules.Model.cmd_execute m_cmd_execute = new SignalRules.Model.cmd_execute();
m_cmd_execute.site_code = revcByte[3];////获取主单元站点编号
//m_cmd_execute.remote_code = byteToHexOneStr(new byte[] { revcByte[4], revcByte[5], revcByte[6], revcByte[7], revcByte[8], revcByte[9] });//远端设备编号
//转为ASCII码
//remote_code=楼号(1字节) 楼层(2字节) 设备类型(1字节) 远端单元编号(2字节)
m_cmd_execute.remote_code = asciiToStr(new byte[] { revcByte[4], revcByte[5], revcByte[6], revcByte[7], revcByte[8], revcByte[9] });//远端设备编号
m_cmd_execute.device_code = m_cmd_execute.site_code.ToString("000") + m_cmd_execute.remote_code;//设备编号
m_cmd_execute.device_ip = socketRemoteKey;
m_cmd_execute.action_type = "03";//操作类型 读、写
//获取数据库块的值
m_cmd_packet_data_list = get_Packet_DataValue(revcByte, 16);//
//判断命令包还是应答包
if (m_cmd_packet.vp_layer_interact_flag <= 0x7F) //应答包
{
try
{
#region 应答包处理
if (m_cmd_packet.data_response_flag == 0x00) //返回应答标志为成功
{
//将命令语句转为SQL处理语句
SignalRules.Model.EntReturn ent = revice_response_package_deal(m_cmd_packet, m_cmd_execute, m_cmd_packet_data_list);
if (ent.ResultCode == 0)
{
tmp_str = m_cmd_packet.data_command_identify.ToString();
//处理完成 状态为已响应
new SignalRules.BLL.omc_cmd_execute().UpdateStatus(m_cmd_execute.device_code, tmp_str,3);
result.ResultCode = 0;
//result.ResultString = m_cmd_execute.site_code + "," + m_cmd_execute.device_code + "," + m_cmd_execute.device_type + "," +
//m_cmd_execute.monitor_type + "," + m_cmd_execute.monitor_identify + "," + m_cmd_execute.action_type + "," +
//m_cmd_execute.monitor_identify.ToString();
}
else
{
result.ResultCode = -1;
result.ResultMsg = ent.ResultMsg;
}
}
else
{
result.ResultCode = -1;
result.ResultMsg = "返回应答标志为" + m_cmd_packet.data_response_flag.ToString();
throw new Exception("返回“命令被有条件执行=" + m_cmd_packet.data_response_flag + "”");
}
#endregion
}
catch (Exception ex)
{
WebCore.Log.WebLog.WriteTextLog(WebLogLevel.ERROR, "system", WebCore.Log.WebLogType.SignalCmd, "doReceive_Work/DealLib/Signal_Revice_Deal", "应答包处理:" + ex.Message);
}
}
else //命令包
{
try
{
#region 命令包处理
if (m_cmd_packet.data_command_identify == 0x01)//设备主动告警(上报)
{
revice_command_package_deal(m_cmd_execute, m_cmd_packet_data_list);
//WebCore.Log.WebLog.WriteTextLog("system", WebCore.Log.WebLogType.SignalCmd, "SocketServer/Common/set_cmd_execute", strSql.ToString());
}
#endregion
}
catch (Exception ex)
{
WebCore.Log.WebLog.WriteTextLog(WebLogLevel.ERROR, "system", WebCore.Log.WebLogType.SignalCmd, "doReceive_Work/DealLib/Signal_Revice_Deal", "命令包处理:" + ex.Message);
}
}
#endregion
}
catch (Exception ex)
{
throw new Exception("解读数据包字节:"+ex.Message);
}
}
else
{
sendByte[15] = 0x04;//重置应答标志,0x00 发送CRC校验错
result.ResultCode = 1;
result.ResultMsg = "CRC校验错";
}
#endregion
#region 构造响应包
try
{
if (Convert.ToInt16(m_cmd_packet.vp_layer_interact_flag) >= 0x80) //0x80~0xFF 命令,
{
result.ResultCode = 1;//命令发起方,需要响应包
//判断通讯标识
//tmp_str = m_cmd_packet.communica_packet_identify;
//int sss = Convert.ToInt16("80", 16); sss = Convert.ToInt16("FF", 16);
if (m_cmd_packet.communica_packet_identify[1]<= 128) //中心主动发起
{
sendByte[12] = 0x00;
sendByte[15] = 0x00;
}
//else if (tmp_str != "" && Convert.ToInt16(tmp_str, 16) <= 255) //设备主动发起
else if (m_cmd_packet.communica_packet_identify[1] <= 255) //设备主动发起
{
sendByte[12] = 0x00;
sendByte[15] = 0x00;//重置应答标志,0x00 发送成功
}
else
{
sendByte[12] = 0x00;//VP层交互标志
sendByte[15] = 0x00;//重置应答标志,0x00 发送成功
}
try
{
#region 生成CRC检验码
ary_byte = new byte[sendByte.Length - 4];
for (int i = 0; i < sendByte.Length - 4; i++)
{
ary_byte[i] = sendByte[i + 1];
}
//WebCore.Log.WebLog.WriteTextLog("system", WebCore.Log.WebLogType.SignalCmd, "SocketServer/DealLib/Signal_Revice_Deal", byteToHexStr(ary_byte));
ary_byte = strToToHexByte(CCITTCrc16(ary_byte, ary_byte.Length).ToString("X2"));
if (ary_byte.Length == 2)
{
sendByte[sendByte.Length - 3] = ary_byte[1]; //取得CRC高位值
sendByte[sendByte.Length - 2] = ary_byte[0];//取得CRC低位值
}
#endregion
///转义字符,发送数据包之前,先生成CRC校验值,再进行转义处理
set_Escape(ref sendByte, ref data_num, "send");
//WebCore.Log.WebLog.WriteTextLog("system", WebCore.Log.WebLogType.SignalCmd, "SocketServer/DealLib/Signal_Revice_Deal/转义字符", byteToHexStr(sendByte));
}
catch (Exception ex)
{
WebCore.Log.WebLog.WriteTextLog("system", WebCore.Log.WebLogType.SignalCmd, "SocketServer/DealLib/Signal_Revice_Deal", "构造响应包->生成CRC检验码:" + ex.Message+byteToHexStr(ary_byte));
//throw new Exception("构造响应包->生成CRC检验码:" + ex.Message);
}
result.ResultObject = sendByte;
}
else
{
result.ResultCode = 0;//命令接收方,不需要响应包
}
}
catch (Exception ex)
{
throw new Exception("构造响应包:" + ex.Message);
}
#endregion
}
catch (Exception ex)
{
result.ResultMsg = ex.Message;
WebCore.Log.WebLog.WriteTextLog(WebLogLevel.ERROR, "system", WebCore.Log.WebLogType.SignalCmd, "doReceive_Work/DealLib/Signal_Revice_Deal", ex.Message);
}
return result;
}
#endregion
#region 处理向终端发送数据
/// <summary>
/// 处理向终端发送数据
/// </summary>
/// <returns></returns>
public static SignalRules.Model.EntReturn Signal_Send_Deal(ref cmd_execute m_cmd_execute )
{
byte[] sendByte = new byte[1064];
List<byte[]> sendByte_list=new List<byte[]>();
byte[] package_head = new byte[16];
List<byte[]> package_list = new List<byte[]>();
byte[] ary_byte;
int data_num = 0;
SignalRules.Model.EntReturn result = new SignalRules.Model.EntReturn();
//SignalRules.Model.cmd_execute m_cmd_execute = new cmd_execute();
result.ResultCode = 0;
try
{
result.ResultCode = 0;
#region 生成命令
#region 获取数据包集合
List<SignalRules.Model.cmd_execute> m_cmd_execute_list = get_Send_Data();//从发送列表获取需要发送的数据
if (m_cmd_execute_list.Count == 0)
{
result.ResultCode = 1;//数据包为空
}
for (int n = 0; n < m_cmd_execute_list.Count; n++)
{
m_cmd_execute = m_cmd_execute_list[n];
if (m_cmd_execute != null && m_cmd_execute.packet_data_byte != null)
{
//分拆数据包,//每个包为1000+19的长度,超过需要分成2个或多个包
package_list = split_data_package(m_cmd_execute.packet_data_byte);
for (int num = 0; num < package_list.Count; num++) //每个包处理
{
#region 命令赋值
////7E 03 01 00 000000000000 D280 80 01 01 FF 04410106 C508 7E
package_head[0] = 0x7E;//起始标志,固定为0x7E
package_head[1] = 0x03;//AP层协议类型,0x03表示为AP:C
package_head[2] = 0x01;//承载协议类型,0x01表示承载的上层协议类型为VP:A
package_head[3] = Convert.ToByte(m_cmd_execute.site_code);//主单元站点编号
//ary_byte = oneStrToHexByte(m_cmd_execute.remote_code); //分解远端设备号
ary_byte = Encoding.ASCII.GetBytes(m_cmd_execute.remote_code);//分解远端设备号,转为ASCII编号
package_head[4] = ary_byte[0];//获取楼号
package_head[5] = ary_byte[1];//获取楼层,共两个字节
package_head[6] = ary_byte[2];//获取楼层,共两个字节
package_head[7] = ary_byte[3];//设备类型(主控单元0x00、远端单元0x01、*侦测单元0x02)
package_head[8] = ary_byte[4];//远端单元编号,共两个字节.
package_head[9] = ary_byte[5];//远端单元编号,共两个字节.
//其中0x0000~0x7FFF用于监控中心发起的通信,而0x8000~0x8FFF则用于由设备发起的通信
ary_byte = get_Comm_Packet_Identify();
package_head[10] = ary_byte[1];//监控中心发起的通信,共两个字节.
package_head[11] = ary_byte[0];//监控中心发起的通信,共两个字节.
package_head[12] = 0x80;//VP层交互标志 80请求
package_head[13] = 0x01;//MCP层协议标识,目前只定义了一种0x01
// 设置包的命令标识,0x01 设备主动告警(上报)、0x02 查询、0x03 设置
package_head[14] = get_command_identify(m_cmd_execute.action_type);
package_head[15] = 0xFF;//应答标志,0xFF 表示此包为发出的命令,而非命令的应答包
data_num = 16;
#endregion
#region 赋值包头
for (int j = 0; j < package_head.Length; j++)
{
sendByte[j] = package_head[j];
}
#endregion
#region 获取包内容
ary_byte = package_list[num];//每个分包内容处理
for (int i = 0; i < ary_byte.Length; i++)
{
sendByte[data_num++] = ary_byte[i];
}
#endregion
#region 生成CRC检验码
ary_byte = new byte[data_num - 1];
for (int i = 0; i < data_num - 1; i++)
{
ary_byte[i] = sendByte[i + 1];
}
//WebCore.Log.WebLog.WriteTextLog("system", WebCore.Log.WebLogType.SignalCmd, "SocketServer/DealLib/Signal_Revice_Deal", byteToHexStr(ary_byte));
ary_byte = strToToHexByte(CCITTCrc16(ary_byte, ary_byte.Length).ToString("X2"));
if (ary_byte.Length == 2)
{
sendByte[data_num++] = ary_byte[1]; //取得CRC高位值
sendByte[data_num++] = ary_byte[0];//取得CRC低位值
}
#endregion
sendByte[data_num++] = 0x7E; //结束符。
//转义字符,发送数据包之前,先生成CRC校验值,再进行转义处理
set_Escape(ref sendByte, ref data_num, "send");
#region 重新赋值数据包
ary_byte = new byte[data_num];
for (int i = 0; i < ary_byte.Length; i++)
{
ary_byte[i] = sendByte[i];
}
sendByte_list.Add(ary_byte);
#endregion
}
}
}
#endregion
#endregion
}
catch (Exception ex)
{
result.ResultCode = -1;
result.ResultMsg = ex.Message;
}
result.ResultObject = sendByte_list;
return result;
}
/// <summary>
/// 分拆包大小
/// </summary>
/// <param name="packet_data_byte"></param>
/// <returns></returns>
private static List<byte[]> split_data_package(List<SignalRules.Model.cmd_packet_data_byte> packet_data_byte)
{
byte[] sendByte = new byte[532];
byte[] ary_byte = ary_byte = new byte[500];
List<byte[]> result = new List<byte[]>();
int tmp_num = 0;
SignalRules.Model.cmd_packet_data_byte m_cmd_packet_data_byte = new SignalRules.Model.cmd_packet_data_byte();
tmp_num = 0;
int num = 0;
try
{
//计算包个数,并列表队列中
for (int i = 0; i < packet_data_byte.Count; i++)
{
m_cmd_packet_data_byte = packet_data_byte[i];
ary_byte[num++] = m_cmd_packet_data_byte.monitor_data_length;
ary_byte[num++] = m_cmd_packet_data_byte.monitor_identify1;//低位在前,高位在后
ary_byte[num++] = m_cmd_packet_data_byte.monitor_identify2;//低位在前,高位在后
for (int j = 0; j < m_cmd_packet_data_byte.monitor_data_value.Length; j++)
{
ary_byte[num++] = m_cmd_packet_data_byte.monitor_data_value[j];
}
tmp_num += m_cmd_packet_data_byte.monitor_data_length;//包的长度
if (tmp_num > 500) //包长度:每个包的长度不超过500字节。
{
sendByte = new byte[num];
for (int j = 0; j < num; j++)
{
sendByte[j] = ary_byte[j];
}
result.Add(sendByte);
tmp_num = 0; //包长度
num = 0; //包字节数
}
}
if (num > 0)
{
sendByte = new byte[num];
for (int j = 0; j < num; j++)
{
sendByte[j] = ary_byte[j];
}
result.Add(sendByte);
}
}
catch (Exception ex)
{
throw new Exception("分析包长度时异常:"+ex.Message);
}
return result;
}
/// <summary>
/// 从omc_cmd_execute表获得到发送的数据串
/// </summary>
/// <returns></returns>
private static List<SignalRules.Model.cmd_execute> get_Send_Data()
{
byte[] ary_byte; //无符号
//sbyte[] ary_sbyte;
int tmp_num_int = 0;
uint tmp_num_uint = 0;
string data_value = "";
string[] tmp_ary ;
//byte[] tmp_byte;
int data_length=0;
DataSet ds = null;
DataRow drow = null;
//SignalRules.Model.cmd_execute m_cmd_execute = new cmd_execute();
SignalRules.Model.cmd_packet_data_byte m_cmd_packet_data_byte;
SignalRules.Model.cmd_execute result = new cmd_execute();
List<SignalRules.Model.cmd_execute> result_lest = new List<SignalRules.Model.cmd_execute>();
//获得取omc_cmd_execute表里一条记录做为命令
SignalRules.Model.omc_cmd_execute m_omc_cmd_execute = new SignalRules.Model.omc_cmd_execute();
try
{
List<SignalRules.Model.omc_cmd_execute> m_omc_cmd_execute_list = new SignalRules.BLL.omc_cmd_execute().GetModel_List("");
for (int n = 0; n < m_omc_cmd_execute_list.Count; n++)
{
m_omc_cmd_execute = m_omc_cmd_execute_list[n];
if (m_omc_cmd_execute != null)
{
try
{
result.id = m_omc_cmd_execute.id;
result.device_code = m_omc_cmd_execute.device_code;
result.device_ip = m_omc_cmd_execute.device_ip;
if (result.device_code.Length == 9)
{
result.site_code = Convert.ToInt16(result.device_code.Substring(0, 3)); //device_code前3位为主控单元编号
result.remote_code = result.device_code.Substring(3, 6); //device_code后6位为远端单元编号
}
else
{
throw new Exception("设备号非9位(主单元号+远端单元号)");
}
result.action_type = m_omc_cmd_execute.action_type;//命令类型
result.package_length = 0;
result.package_num = 0;
result.packet_data_byte = new List<cmd_packet_data_byte>();
ds = new SignalRules.BLL.omc_cmd_execute_identify().GetList(m_omc_cmd_execute.id);
if (ds.Tables[0].Rows.Count > 0)
{
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
#region 构造cmd_packet_data_byte
drow = ds.Tables[0].Rows[i];
if (drow["monitor_id"].ToString() != "")
{
m_cmd_packet_data_byte = new SignalRules.Model.cmd_packet_data_byte();
ary_byte = strToToHexByte(drow["monitor_id"].ToString());//获取网络数据标识,转为16进制。高位在前,低位在后
m_cmd_packet_data_byte.monitor_identify1 = ary_byte[1];//低位在前,高位在后
m_cmd_packet_data_byte.monitor_identify2 = ary_byte[0];//低位在前,高位在后
data_value = drow["data_value"].ToString();
data_length = Convert.ToInt16(drow["data_length"]);
if (drow["data_type"].ToString() == "03") //数据类型03:字符串
{
#region 数据类型03:字符串
if (drow["data_encode"].ToString() == "06")//06:ASCII
{
ary_byte = Encoding.ASCII.GetBytes(data_value);
}
else if (drow["data_encode"].ToString() == "02")//02:GBK
{
//ary_byte = Encoding.GetEncoding("GBK").GetBytes(data_value);
ary_byte = Encoding.UTF8.GetBytes(data_value);
//ary_byte = Encoding.Default.GetBytes(data_value);
//StringToHexString(drow["data_value"].ToString(), Encoding.Default);//获取数据块
}
else//默认编码
{
ary_byte = Encoding.Default.GetBytes(data_value);
}
#endregion
}
else if (drow["data_type"].ToString() == "01")//数据类型01:Uint型
{
#region 数据类型01:Uint型
if ((drow["data_encode"].ToString() == "03") && data_value.Contains('.'))//03:IP地址格式
{
tmp_ary = data_value.Split('.');
ary_byte = new byte[tmp_ary.Length];
for (int j = 0; j < tmp_ary.Length; j++)
{
ary_byte[j] = Convert.ToByte(tmp_ary[j]);
}
}
else if ((drow["data_encode"].ToString() == "04"))//04:时间格式2015-08-22 10:38:22
{
data_value = data_value.Replace("-", "").Replace(":", "").Replace(" ", "");
ary_byte = strToToHexByte(data_value);
}
else if ((drow["data_encode"].ToString() == "05"))//整数型显示
{
#region data_encode:05 整数型显示无符号
try
{
tmp_num_uint = Convert.ToUInt32(data_value);
if (tmp_num_uint > 4294967295)
{
throw new Exception("设置数据值超过4294967295");
}
}
catch
{
throw new Exception("设置数据值超过4294967295");
}
if (tmp_num_uint >= 0 && tmp_num_uint <= 255)
{
ary_byte = new byte[] { Convert.ToByte(tmp_num_uint) };
}
else if (tmp_num_uint >= 0 && tmp_num_uint <= 65535)
{
tmp_num_uint = Convert.ToUInt16(tmp_num_uint);
ary_byte = System.BitConverter.GetBytes(tmp_num_uint);
}
else if (tmp_num_uint >= 0 && tmp_num_uint <= 4294967295)
{
tmp_num_uint = Convert.ToUInt32(tmp_num_uint);
ary_byte = System.BitConverter.GetBytes(tmp_num_uint);
}
#endregion
}
else//01:default字符串、数字串
{
try
{
tmp_num_uint = Convert.ToUInt32(data_value);
if (tmp_num_uint > 4294967295)
{
throw new Exception("设置数据值不能超过4294967295");
}
ary_byte = strToToHexByte(tmp_num_uint.ToString("X2")); // strToDecByte
if (ary_byte.Length == 2)
{
ary_byte = new byte[] {ary_byte[1],ary_byte[0]};
//WebCore.Log.WebLog.WriteTextLog("system", WebCore.Log.WebLogType.SignalCmd, "strToToHexByte", (ary_byte[0]+ary_byte[1]).ToString());
}
else if (ary_byte.Length == 4)
{
ary_byte = new byte[] { ary_byte[1], ary_byte[0], ary_byte[3], ary_byte[2] };
}
//ary_byte = intToHexByte(tmp_num_uint);
}
catch
{
throw new Exception("设置数据值超过4294967295");
}
}
#endregion
}
else if (drow["data_type"].ToString() == "02")//数据类型02:Sint型
{
#region data_encode:05 整数型显示无符号
try
{
tmp_num_int = Convert.ToInt32(data_value);
if (tmp_num_int > 2147483647 || tmp_num_int < -2147483648)
{
throw new Exception("设置数据值超过2147483647");
}
}
catch
{
throw new Exception("设置数据值超过2147483647");
}
if (tmp_num_int >= -128 && tmp_num_int <= 127) //
{
sbyte tmp = Convert.ToSByte(tmp_num_int);
ary_byte = new byte[] { (byte)tmp };
}
else if (tmp_num_int >= -32768 && tmp_num_int <= 32767)
{
tmp_num_int = Convert.ToInt16(tmp_num_int);
ary_byte = System.BitConverter.GetBytes(tmp_num_int);
}
else if (tmp_num_int >= -2147483648 && tmp_num_int <= 2147483647)
{
tmp_num_int = Convert.ToInt32(tmp_num_int);
ary_byte = System.BitConverter.GetBytes(tmp_num_int);
}
#endregion
}
else if (drow["data_type"].ToString() == "04")//数据类型04:bit型
{
ary_byte = new byte[] { Convert.ToByte(data_value) };
}
else if (drow["data_type"].ToString() == "05")//数据类型05:16进制字符
{
ary_byte = strToToHexByte(data_value);
}
//定义数组的长度
m_cmd_packet_data_byte.monitor_data_value = new byte[data_length];
if (data_length >= ary_byte.Length)
{
for (int j = 0; j < ary_byte.Length; j++)
{
m_cmd_packet_data_byte.monitor_data_value[j] = ary_byte[j];
}
}
else
{
for (int j = 0; j < data_length; j++)
{
m_cmd_packet_data_byte.monitor_data_value[j] = ary_byte[j];
}
}
m_cmd_packet_data_byte.data_length = m_cmd_packet_data_byte.monitor_data_value.Length + 3;//设置数据块长度 int类
if (m_cmd_packet_data_byte.data_length <= 255)
{
m_cmd_packet_data_byte.monitor_data_length = Convert.ToByte((m_cmd_packet_data_byte.data_length));
}
else
{
//数据块长度超过255
WebCore.Log.WebLog.WriteTextLog("system", WebCore.Log.WebLogType.SignalCmd, "SocketServer/Deal/get_Send_Data", "数据块长度超过255" + m_cmd_packet_data_byte.monitor_data_value);
continue;
}
result.package_num++;//所有数据包数量
result.package_length += m_cmd_packet_data_byte.monitor_data_length;//所有包累加长度。
result.packet_data_byte.Add(m_cmd_packet_data_byte);//增加数据块赋值
}
#endregion
}
}
result_lest.Add(result);
}
catch (Exception ex)
{
WebCore.Log.WebLog.WriteTextLog("system", WebCore.Log.WebLogType.SignalCmd, "SocketServer/Deal/get_Send_Data", ex.Message);
}
}
}
}
catch (Exception ex)
{
WebCore.Log.WebLog.WriteTextLog("system", WebCore.Log.WebLogType.SignalCmd, "SocketServer/Deal/get_Send_Data", ex.Message);
}
return result_lest;
}
/// <summary>
/// 设置命令标识
/// </summary>
/// <param name="action_type">操作类型</param>
/// <returns></returns>
private static byte get_command_identify(string action_type)
{
byte result = new byte();
#region 设置命令标识
if (action_type == "01") //告警(设备主动告警(上报))
{
result = 0x01;//(设备主动告警(上报))
}
else if (action_type == "02") //读(查询)
{
result = 0x02;//查询
}
else if (action_type == "03")//写(设置)
{
result = 0x03;//设置
}
else if (action_type == "10")//升级(转换到软件升级模式)
{
result = 0x10;//转换到软件升级模式
}
else if (action_type == "11")//版本(切换监控软件版本)
{
result = 0x11;//切换监控软件版本
}
#endregion
return result;
}
/// <summary>
/// 向板发送成功,修改数据库
/// </summary>
/// <param name="m_cmd_execute"></param>
/// <returns></returns>
public static bool Signal_Send_Deal_Data(cmd_execute m_cmd_execute)
{
bool result = false;
if (m_cmd_execute.action_type == "03")//操作类型 01 设备主动告警(上报);02 查询;03 设置;10 转换到软件升级模式;11 切换监控软件版本
{
int rows = new SignalRules.BLL.omc_cmd_execute().send_set_request_deal(m_cmd_execute.id);
if (rows >= 0)
{
result = true;
WebCore.Log.WebLog.WriteTextLog("system", WebCore.Log.WebLogType.SignalCmd, "SocketServer/revice_response_package_deal", "已处理条数:" + rows.ToString());
}
else
{
result = false;
}
}
else ////修改命令单状态为已发送
{
new SignalRules.BLL.omc_cmd_execute().UpdateStatus(m_cmd_execute.id, 2);
}
return result;
}
#endregion
}
}
4、数据库入库处理
using System;
using System.Data;
using System.Text;
using MySql.Data.MySqlClient;
using Maticsoft.DBUtility;//Please add references
using System.Collections.Generic;
namespace SignalRules.DAL
{
/// <summary>
/// 数据访问类:omc_cmd_execute
/// </summary>
public partial class omc_cmd_execute
{
public omc_cmd_execute()
{ }
#region BasicMethod
/// <summary>
/// 是否存在该记录
/// </summary>
public bool Exists(int id)
{
StringBuilder strSql = new StringBuilder();
strSql.Append("select count(1) from omc_cmd_execute");
strSql.Append(" where aaa@qq.com");
MySqlParameter[] parameters = {
new MySqlParameter("@id", MySqlDbType.Int32)
};
parameters[0].Value = id;
return DbHelperMySQL.Exists(strSql.ToString(), parameters);
}
/// <summary>
/// 增加一条数据
/// </summary>
public bool Add(SignalRules.Model.omc_cmd_execute model)
{
StringBuilder strSql = new StringBuilder();
strSql.Append("insert into omc_cmd_execute(");
strSql.Append("device_code,action_type,cmd_time,status)");
strSql.Append(" values (");
strSql.Append("@device_code,@action_type,@cmd_time,@status)");
MySqlParameter[] parameters = {
new MySqlParameter("@device_code", MySqlDbType.VarChar,20),
new MySqlParameter("@action_type", MySqlDbType.VarChar,10),
new MySqlParameter("@cmd_time", MySqlDbType.DateTime),
new MySqlParameter("@status", MySqlDbType.Int32,4)};
parameters[0].Value = model.device_code;
parameters[1].Value = model.action_type;
parameters[2].Value = model.cmd_time;
parameters[3].Value = model.status;
int rows = DbHelperMySQL.ExecuteSql(strSql.ToString(), parameters);
if (rows > 0)
{
return true;
}
else
{
return false;
}
}
/// <summary>
/// 更新一条数据
/// </summary>
public bool Update(SignalRules.Model.omc_cmd_execute model)
{
StringBuilder strSql = new StringBuilder();
strSql.Append("update omc_cmd_execute set ");
strSql.Append("aaa@qq.com_code,");
strSql.Append("aaa@qq.com_type,");
strSql.Append("aaa@qq.com_time,");
strSql.Append("aaa@qq.com");
strSql.Append(" where aaa@qq.com");
MySqlParameter[] parameters = {
new MySqlParameter("@device_code", MySqlDbType.VarChar,20),
new MySqlParameter("@action_type", MySqlDbType.VarChar,10),
new MySqlParameter("@cmd_time", MySqlDbType.DateTime),
new MySqlParameter("@status", MySqlDbType.Int32,4),
new MySqlParameter("@id", MySqlDbType.Int32,4)};
parameters[0].Value = model.device_code;
parameters[1].Value = model.action_type;
parameters[2].Value = model.cmd_time;
parameters[3].Value = model.status;
parameters[4].Value = model.id;
int rows = DbHelperMySQL.ExecuteSql(strSql.ToString(), parameters);
if (rows > 0)
{
return true;
}
else
{
return false;
}
}
/// <summary>
/// 删除一条数据
/// </summary>
public bool Delete(int id)
{
StringBuilder strSql = new StringBuilder();
strSql.Append("delete from omc_cmd_execute ");
strSql.Append(" where aaa@qq.com");
MySqlParameter[] parameters = {
new MySqlParameter("@id", MySqlDbType.Int32)
};
parameters[0].Value = id;
int rows = DbHelperMySQL.ExecuteSql(strSql.ToString(), parameters);
if (rows > 0)
{
return true;
}
else
{
return false;
}
}
/// <summary>
/// 批量删除数据
/// </summary>
public bool DeleteList(string idlist)
{
StringBuilder strSql = new StringBuilder();
strSql.Append("delete from omc_cmd_execute ");
strSql.Append(" where id in (" + idlist + ") ");
int rows = DbHelperMySQL.ExecuteSql(strSql.ToString());
if (rows > 0)
{
return true;
}
else
{
return false;
}
}
/// <summary>
/// 得到一个对象实体
/// </summary>
public SignalRules.Model.omc_cmd_execute GetModel(int id)
{
StringBuilder strSql = new StringBuilder();
strSql.Append("select id,device_code,action_type,cmd_time,status from omc_cmd_execute ");
strSql.Append(" where aaa@qq.com");
MySqlParameter[] parameters = {
new MySqlParameter("@id", MySqlDbType.Int32)
};
parameters[0].Value = id;
SignalRules.Model.omc_cmd_execute model = new SignalRules.Model.omc_cmd_execute();
DataSet ds = DbHelperMySQL.Query(strSql.ToString(), parameters);
if (ds.Tables[0].Rows.Count > 0)
{
return DataRowToModel(ds.Tables[0].Rows[0]);
}
else
{
return null;
}
}
/// <summary>
/// 得到一个对象实体
/// </summary>
public SignalRules.Model.omc_cmd_execute DataRowToModel(DataRow row)
{
SignalRules.Model.omc_cmd_execute model = new SignalRules.Model.omc_cmd_execute();
if (row != null)
{
if (row["id"] != null && row["id"].ToString() != "")
{
model.id = int.Parse(row["id"].ToString());
}
if (row["device_code"] != null)
{
model.device_code = row["device_code"].ToString();
}
if (row["device_ip"] != null)
{
model.device_ip = row["device_ip"].ToString();
}
if (row["action_type"] != null)
{
model.action_type = row["action_type"].ToString();
}
if (row["cmd_time"] != null && row["cmd_time"].ToString() != "")
{
model.cmd_time = DateTime.Parse(row["cmd_time"].ToString());
}
if (row["status"] != null && row["status"].ToString() != "")
{
model.status = int.Parse(row["status"].ToString());
}
}
return model;
}
/// <summary>
/// 获得数据列表
/// </summary>
public DataSet GetList(string strWhere)
{
StringBuilder strSql = new StringBuilder();
strSql.Append("select id,device_code,action_type,cmd_time,status ");
strSql.Append(" FROM omc_cmd_execute ");
if (strWhere.Trim() != "")
{
strSql.Append(" where " + strWhere);
}
return DbHelperMySQL.Query(strSql.ToString());
}
/// <summary>
/// 获取记录总数
/// </summary>
public int GetRecordCount(string strWhere)
{
StringBuilder strSql = new StringBuilder();
strSql.Append("select count(1) FROM omc_cmd_execute ");
if (strWhere.Trim() != "")
{
strSql.Append(" where " + strWhere);
}
object obj = DbHelperSQL.GetSingle(strSql.ToString());
if (obj == null)
{
return 0;
}
else
{
return Convert.ToInt32(obj);
}
}
/// <summary>
/// 分页获取数据列表
/// </summary>
public DataSet GetListByPage(string strWhere, string orderby, int startIndex, int endIndex)
{
StringBuilder strSql = new StringBuilder();
strSql.Append("SELECT * FROM ( ");
strSql.Append(" SELECT ROW_NUMBER() OVER (");
if (!string.IsNullOrEmpty(orderby.Trim()))
{
strSql.Append("order by T." + orderby);
}
else
{
strSql.Append("order by T.id desc");
}
strSql.Append(")AS Row, T.* from omc_cmd_execute T ");
if (!string.IsNullOrEmpty(strWhere.Trim()))
{
strSql.Append(" WHERE " + strWhere);
}
strSql.Append(" ) TT");
strSql.AppendFormat(" WHERE TT.Row between {0} and {1}", startIndex, endIndex);
return DbHelperMySQL.Query(strSql.ToString());
}
/*
/// <summary>
/// 分页获取数据列表
/// </summary>
public DataSet GetList(int PageSize,int PageIndex,string strWhere)
{
MySqlParameter[] parameters = {
new MySqlParameter("@tblName", MySqlDbType.VarChar, 255),
new MySqlParameter("@fldName", MySqlDbType.VarChar, 255),
new MySqlParameter("@PageSize", MySqlDbType.Int32),
new MySqlParameter("@PageIndex", MySqlDbType.Int32),
new MySqlParameter("@IsReCount", MySqlDbType.Bit),
new MySqlParameter("@OrderType", MySqlDbType.Bit),
new MySqlParameter("@strWhere", MySqlDbType.VarChar,1000),
};
parameters[0].Value = "omc_cmd_execute";
parameters[1].Value = "id";
parameters[2].Value = PageSize;
parameters[3].Value = PageIndex;
parameters[4].Value = 0;
parameters[5].Value = 0;
parameters[6].Value = strWhere;
return DbHelperMySQL.RunProcedure("UP_GetRecordByPage",parameters,"ds");
}*/
#endregion BasicMethod
#region ExtensionMethod
/// <summary>
/// 得到一个对象实体
/// </summary>
public SignalRules.Model.omc_cmd_execute GetModel_Top()
{
StringBuilder strSql = new StringBuilder();
strSql.Append("set @id=0;select id into @id from omc_cmd_execute where status=0 order by id limit 1;");
strSql.Append("select id,device_code,device_ip,action_type,status,cmd_time from omc_cmd_execute where aaa@qq.com;");
strSql.Append("update omc_cmd_execute set status=1 where aaa@qq.com;");
SignalRules.Model.omc_cmd_execute model = new SignalRules.Model.omc_cmd_execute();
DataSet ds = DbHelperMySQL.Query(strSql.ToString());
if (ds.Tables[0].Rows.Count > 0)
{
return DataRowToModel(ds.Tables[0].Rows[0]);
}
else
{
return null;
}
}
/// <summary>
/// 获得数据列表
/// </summary>
public DataSet Get_DealStatus()
{
StringBuilder strSql = new StringBuilder();
strSql.Append("update omc_cmd_execute set status=9 where status=0;");
strSql.Append("select id,device_code,device_ip,action_type,status,cmd_time from omc_cmd_execute where status=9;");
strSql.Append("update omc_cmd_execute set status=1 where status=9;");
try
{
return DbHelperMySQL.Query(strSql.ToString());
}
catch (Exception ex)
{
WebCore.Log.WebLog.WriteTextLog("system", WebCore.Log.WebLogType.SignalCmd, "doReceive_Work/DealLib/Get_DealStatus", "获取omc_cmd_execute数据时出错:" + ex.Message);
return null;
}
}
/// <summary>
/// 更新一条数据
/// </summary>
public bool UpdateStatus(int id ,int status)
{
StringBuilder strSql = new StringBuilder();
strSql.Append("update omc_cmd_execute set ");
strSql.Append("aaa@qq.com,");
strSql.Append("aaa@qq.com_time");
strSql.Append(" where aaa@qq.com");
MySqlParameter[] parameters = {
new MySqlParameter("@status", MySqlDbType.Int32,4),
new MySqlParameter("@cmd_time", MySqlDbType.DateTime),
new MySqlParameter("@id", MySqlDbType.Int32,4)};
parameters[0].Value = status;
parameters[1].Value = DateTime.Now;
parameters[2].Value = id;
int rows = DbHelperMySQL.ExecuteSql(strSql.ToString(), parameters);
if (rows > 0)
{
return true;
}
else
{
return false;
}
}
/// <summary>
/// 更新一条数据
/// </summary>
public bool UpdateStatus(string device_code, string action_type,int status)
{
try
{
StringBuilder strSql = new StringBuilder();
strSql.Append("update omc_cmd_execute set ");
strSql.Append("aaa@qq.com,");
strSql.Append("aaa@qq.com_time");
strSql.Append(" where aaa@qq.com_code and aaa@qq.com_type");
MySqlParameter[] parameters = {
new MySqlParameter("@status", MySqlDbType.Int32,4),
new MySqlParameter("@cmd_time", MySqlDbType.DateTime),
new MySqlParameter("@device_code", MySqlDbType.VarChar,45),
new MySqlParameter("@action_type", MySqlDbType.VarChar,2)
};
parameters[0].Value = status;
parameters[1].Value = DateTime.Now;
parameters[2].Value = device_code;
parameters[3].Value = action_type;
int rows = DbHelperMySQL.ExecuteSql(strSql.ToString(), parameters);
if (rows > 0)
{
return true;
}
else
{
return false;
}
}
catch (Exception ex)
{
WebCore.Log.WebLog.WriteTextLog("system", WebCore.Log.WebLogType.SignalCmd, "doReceive_Work/DealLib/UpdateStatus", "修改omc_cmd_execute状态时出错:" + ex.Message);
return false;
}
}
public int revice_response_package_set(SignalRules.Model.omc_cmd_execute m_omc_cmd_execute)
{
int result_code = 0;
try
{
MySqlParameter[] parameters = {
new MySqlParameter("device_code", MySqlDbType.VarChar, 30),
new MySqlParameter("action_type", MySqlDbType.VarChar,10),
new MySqlParameter("result_code", MySqlDbType.Int16)
};
parameters[0].Value = m_omc_cmd_execute.device_code;
parameters[1].Value = m_omc_cmd_execute.action_type;
parameters[2].Direction = ParameterDirection.Output;
DbHelperMySQL.RunProcedure("p_revice_response_package_set", parameters, "table");
result_code = Convert.ToInt32(parameters[2].Value);
}
catch (Exception ex)
{
WebCore.Log.WebLog.WriteTextLog("system", WebCore.Log.WebLogType.SignalCmd, "doReceive_Work/DealLib/revice_response_package_set", "执行p_revice_response_package_set时出错:" + ex.Message);
}
return result_code;
}
public int revice_device_alarm_info(string device_code, string device_ip, string monitor_id, string data_str)
{
int result_code = 0;
try
{
MySqlParameter[] parameters = {
new MySqlParameter("i_device_code", MySqlDbType.VarChar, 30),
new MySqlParameter("i_device_ip", MySqlDbType.VarChar,45),
new MySqlParameter("i_monitor_id", MySqlDbType.VarChar,10),
new MySqlParameter("i_data_value", MySqlDbType.VarChar,1000),
new MySqlParameter("result_code", MySqlDbType.Int16)
};
parameters[0].Value = device_code;
parameters[1].Value = device_ip;
parameters[2].Value = monitor_id;
parameters[3].Value = data_str;
parameters[4].Direction = ParameterDirection.Output;
DbHelperMySQL.RunProcedure("p_revice_device_alarm_info", parameters, "table1");
result_code = Convert.ToInt32(parameters[4].Value);
}
catch (Exception ex)
{
WebCore.Log.WebLog.WriteTextLog("system", WebCore.Log.WebLogType.SignalCmd, "doReceive_Work/DealLib/revice_device_alarm_info", "执行p_revice_device_alarm_info时出错:" + ex.Message);
}
return result_code;
}
/// <summary>
/// 发送设置请求数据处理
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public int send_set_request_deal(int id)
{
int result_code = 0;
try
{
MySqlParameter[] parameters = {
new MySqlParameter("i_id", MySqlDbType.Int32),
new MySqlParameter("result_code", MySqlDbType.Int16)
};
parameters[0].Value = id;
parameters[1].Direction = ParameterDirection.Output;
DbHelperMySQL.RunProcedure("p_send_set_request_deal", parameters, "table");
result_code = Convert.ToInt32(parameters[1].Value);
}
catch (Exception ex)
{
WebCore.Log.WebLog.WriteTextLog("system", WebCore.Log.WebLogType.SignalCmd, "doReceive_Work/DealLib/send_set_request_deal", "执行p_send_set_request_deal时出错:" + ex.Message);
}
return result_code;
}
/// <summary>
/// 接收查询命令包响应处理
/// </summary>
/// <param name="m_omc_cmd_execute"></param>
/// <param name="monitor_id"></param>
/// <param name="data_str"></param>
/// <returns></returns>
public int revice_query_response_deal(string device_code, string monitor_id, string data_str)
{
int result_code = 0;
try
{
MySqlParameter[] parameters = {
new MySqlParameter("i_device_code", MySqlDbType.VarChar, 30),
new MySqlParameter("i_monitor_id", MySqlDbType.VarChar,10),
new MySqlParameter("i_data_value", MySqlDbType.VarChar,1000),
new MySqlParameter("result_code", MySqlDbType.Int16)
};
parameters[0].Value = device_code;
parameters[1].Value = monitor_id;
parameters[2].Value = data_str;
parameters[3].Direction = ParameterDirection.Output;
DbHelperMySQL.RunProcedure("p_revice_query_response_deal", parameters, "table1");
result_code = Convert.ToInt32(parameters[3].Value);
WebCore.Log.WebLog.WriteTextLog("system", WebCore.Log.WebLogType.SignalCmd, "doReceive_Work/DealLib/revice_query_response_deal", "device_code="+device_code +"|monitor_id="+ monitor_id+ "|data_str=" + data_str);
}
catch (Exception ex)
{
WebCore.Log.WebLog.WriteTextLog("system", WebCore.Log.WebLogType.SignalCmd, "doReceive_Work/DealLib/revice_query_response_deal", "执行p_revice_query_response_deal时出错:" + ex.Message);
}
return result_code;
}
/// <summary>
///
/// </summary>
/// <param name="device_code"></param>
/// <param name="monitor_id"></param>
/// <returns></returns>
public int p_revice_query_response_init(string device_code, string monitor_id)
{
int result_code = 0;
try
{
MySqlParameter[] parameters = {
new MySqlParameter("i_device_code", MySqlDbType.VarChar, 30),
new MySqlParameter("i_monitor_id", MySqlDbType.VarChar,10),
new MySqlParameter("result_code", MySqlDbType.Int16)
};
parameters[0].Value = device_code;
parameters[1].Value = monitor_id;
parameters[2].Direction = ParameterDirection.Output;
DbHelperMySQL.RunProcedure("p_revice_query_response_init", parameters, "table1");
result_code = Convert.ToInt32(parameters[2].Value);
//WebCore.Log.WebLog.WriteTextLog("system", WebCore.Log.WebLogType.SignalCmd, "doReceive_Work/DealLib/revice_query_response_init", "monitor_id=" + monitor_id);
}
catch (Exception ex)
{
WebCore.Log.WebLog.WriteTextLog("system", WebCore.Log.WebLogType.SignalCmd, "doReceive_Work/DealLib/revice_query_response_deal", "执行p_revice_query_response_init时出错:" + ex.Message);
}
return result_code;
}
/// <summary>
/// 接收设备上报类型
/// </summary>
/// <param name="device_code"></param>
/// <param name="monitor_id"></param>
/// <param name="data_str"></param>
/// <returns></returns>
public int revice_device_report_type(string device_code, string device_ip, string monitor_id, string data_str)
{
int result_code = 0;
try
{
MySqlParameter[] parameters = {
new MySqlParameter("i_device_code", MySqlDbType.VarChar, 30),
new MySqlParameter("i_device_ip", MySqlDbType.VarChar, 30),
new MySqlParameter("i_monitor_id", MySqlDbType.VarChar,10),
new MySqlParameter("i_data_value", MySqlDbType.VarChar,1000),
new MySqlParameter("result_code", MySqlDbType.Int16)
};
parameters[0].Value = device_code;
parameters[1].Value = device_ip;
parameters[2].Value = monitor_id;
parameters[3].Value = data_str;
parameters[4].Direction = ParameterDirection.Output;
DbHelperMySQL.RunProcedure("p_revice_device_report_type", parameters, "table1");
result_code = Convert.ToInt32(parameters[4].Value);
}
catch (Exception ex)
{
WebCore.Log.WebLog.WriteTextLog("system", WebCore.Log.WebLogType.SignalCmd, "doReceive_Work/DealLib/revice_device_report_type", "执行p_revice_device_report_type时出错:" + ex.Message);
}
return result_code;
}
#endregion ExtensionMethod
}
}
上一篇: iQOO 5游戏性能怎么样 iQOO 5游戏性能测试介绍
下一篇: 清除浮动(8.30)