using System;
using System.Text;
using System.Collections.Generic;
using Shared;
//1440
namespace SuperGateWay
{
public class SendAndReceiveDatas
{
public static PacketInfo CurrentPacketInfo;
///
/// 接收数据的缓冲区
///
static List receiveDataList = new List ();//接收分段,接收完毕之后要拼起来
public static void Recevice (byte subnetId, byte deviceId, byte [] bytes)
{
var packetInfo = CurrentPacketInfo;
if (packetInfo == null ) {
return;
}
if (packetInfo.Command != 0) {
if (packetInfo.Command != bytes [0]) {
return;
}
}
if (subnetId != packetInfo.SubnetID || deviceId != packetInfo.DeviceID) return;
System.Console.WriteLine ("接收到新数据");
switch (bytes [0]) {
case 0:
packetInfo.ResponeBytes = bytes;
break;
case 1:
if (packetInfo.Command != 0 || packetInfo.FileBytes == null) {
return;
}
uint index = bytes [4] + (uint)bytes [3] * 256 + (uint)bytes [2] * 256 * 256 + (uint)bytes [1] * 256 * 256 * 256;
uint lenght = bytes [6] + (uint)bytes [5] * 256;
//如果请求的文件过大,当成无效数据
if (1024 * 1.5 < lenght) {
return;
}
//如果请求的数据大于当前文件的长度,就以当前文件的最大长度为请求长度
if (packetInfo.FileBytes.Length <= index + lenght) {
lenght = (uint)packetInfo.FileBytes.Length - index;
System.Console.WriteLine ("发送数据完成");
packetInfo.IsUploadFinish = true;
}
var buffer = new byte [1 + 4 + 2 + lenght];
buffer [0] = bytes [0];
buffer [1] = bytes [1];
buffer [2] = bytes [2];
buffer [3] = bytes [3];
buffer [4] = bytes [4];
buffer [5] = (byte)((lenght >> 8) & 0xFF);
buffer [6] = (byte)((lenght >> 0) & 0xFF);
System.Array.Copy (packetInfo.FileBytes, index, buffer, 7, lenght);
System.Console.WriteLine ("发送数据长度"+lenght);
Shared.Control.ControlBytesSend (Command.SuperGatewayAgent, subnetId, deviceId, buffer, Shared.SendCount.Zero);
break;
case 2: break;
case 3:
packetInfo.ResponeBytes = bytes;
break;
case 4:
for (int i = 1; i < 5; i++) {
if (bytes [i] != packetInfo.Buffer [i]) {
//如果不是当前发送的命令,就反馈回去
return;
}
}
packetInfo.ResponeBytes = bytes;
break;
case 5:
packetInfo.ResponeBytes = bytes;
break;
case 6:
for (int i = 5; i < packetInfo.Buffer.Length; i++) {
if (bytes [i] != packetInfo.Buffer [i]) {
//如果不是当前发送的命令,就反馈回去
return;
}
}
packetInfo.ResponeBytes = bytes;
break;
case 7: break;
case 8: break;
}
}
}
public class PacketInfo
{
// /scene /device /logic
///
/// 上传是App传数据到高级网关
/// 下载是高级网关从App下载文件
/// 0 通知上传
/// 1 请求上传
/// 2 请求上传完毕
/// 3 通知下载
/// 4 请求下载
/// 5 请求下载完毕
/// 6 浏览文件
/// 7 获取文件大小
/// 8 删除文件
///
public int Command;
public byte [] Buffer = { };//json数据集合,发送的时候要分包发送
[System.NonSerialized]
//发送数据了之后当前线程等待或者运行的信号
public System.Threading.ManualResetEvent ManualResetEvent = new System.Threading.ManualResetEvent (false);
///
/// 回复的数据
///
public byte [] ResponeBytes;
public bool IsFinish {
get {
return ResponeBytes != null;
}
}
///
/// 重发并次数
///
public int ReSendCount = 3;
public byte SubnetID =ScenePage.SubnetID;
public byte DeviceID= ScenePage.DeviceID;
public byte [] FileBytes;
public bool IsUploadFinish;
}
}